Code Snippets

Parsers/NanoParsec.hs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
{-# LANGUAGE FlexibleInstances #-}

--------------------------------------------------------------------------------
  
module Parsers.NanoParsec
  ( Parseable
  , Parser
  , item
  , some, many, sepBy, sepBy1
  , satisfy, oneOf, chainl, chainl1
  , char, string, token, reserved, spaces
  , runParser
  )
where

--------------------------------------------------------------------------------

import qualified Data.ByteString                 as BS
import           Data.String
  ( IsString
  )
import           Control.Applicative.Alternative
  ( Alternative
    ( empty
    , (<|>)
    )
  )
import           Control.Monad.Plus
  ( MonadPlus
    ( mzero
    , mplus
    )
  )

--------------------------------------------------------------------------------

-- NanoParsec:
-- http://dev.stephendiehl.com/fun/002_parsers.html#nanoparsec

newtype Parser s a = Parser { parse :: s -> [ (a, s) ] }

class (Eq a, IsString a) => Parseable a where
  nil :: a -> Bool
  hd  :: a -> Char
  tl  :: a -> a

instance Parseable String where
  nil = (== [])
  hd  =  head
  tl  =  tail

instance Parseable BS.ByteString where
  nil =                         BS.null
  hd  = toEnum . fromIntegral . BS.head
  tl  =                         BS.tail

--------------------------------------------------------------------------------

instance (Parseable s) => Functor (Parser s) where
  fmap f (Parser cs) =
    Parser $ \s -> [(f a, b) | (a, b) <- cs s]

instance (Parseable s) => Applicative (Parser s) where
  pure = return
  (Parser cs1) <*> (Parser cs2) =
    Parser $ \s -> [(f a, s2) | (f, s1) <- cs1 s, (a, s2) <- cs2 s1]

instance (Parseable s) => Monad (Parser s) where
  return = unit
  (>>=)  = bind

instance (Parseable s) => MonadPlus (Parser s) where
  mzero = failure
  mplus = combine

instance (Parseable s) => Alternative (Parser s) where
  empty = mzero
  (<|>) = option

--------------------------------------------------------------------------------

bind
  :: (Parseable s)
  => Parser s a
  -> (a -> Parser s b)
  -> Parser s b
bind p f =
  Parser $ \s -> concatMap (\(a, s') -> parse (f a) s') $ parse p s

unit
  :: (Parseable s)
  => a
  -> Parser s a
unit a =
  Parser $ \s -> [ (a, s) ]

combine
  :: (Parseable s)
  => Parser s a
  -> Parser s a
  -> Parser s a
combine p q =
  Parser $ \s -> parse p s ++ parse q s

failure
  :: (Parseable s)
  => Parser s a
failure =
  Parser $ \_ -> []

option
  :: (Parseable s)
  => Parser s a
  -> Parser s a
  -> Parser s a
option p q =
  Parser
  $ \s ->
      case parse p s of
        [ ] -> parse q s
        res -> res
        
--------------------------------------------------------------------------------

item
  :: (Parseable s)
  => Parser s Char
item =
  Parser
  $ \s ->
      case nil s of
        True  -> []
        False -> [ (hd s, tl s) ]



        
--------------------------------------------------------------------------------

-- | One or more.
some
  :: (Alternative f)
  => f a
  -> f [a]
some v = some_v
  where
    many_v = some_v <|> pure []
    some_v = (:) <$> v <*> many_v

-- | Zero or more.
many
  :: (Alternative f)
  => f a
  -> f [a]
many v = many_v
  where
    many_v = some_v <|> pure []
    some_v = (:) <$> v <*> many_v

-- | One or more.
sepBy1
  :: (Alternative f)
  => f a
  -> f b
  -> f [a]
sepBy1 p sep =
  (:) <$> p <*> (many $ sep *> p)

-- | Zero or more.
sepBy
  :: (Alternative f)
  => f a
  -> f b
  -> f [a]
sepBy p sep =
  sepBy1 p sep <|> pure []

--------------------------------------------------------------------------------

satisfy
  :: (Parseable s)
  => (Char -> Bool)
  -> Parser s Char
satisfy p =
  item `bind`
  \c ->
    if p c
    then unit c
    else Parser $ \_ -> []
    
--------------------------------------------------------------------------------

oneOf
  :: (Parseable s)
  => [Char]
  -> Parser s Char
oneOf s =
  satisfy $ flip elem s

chainl
  :: (Parseable s)
  => Parser s a
  -> Parser s (a -> a -> a)
  -> a
  -> Parser s a
chainl p op a =
  (p `chainl1` op) <|> return a

chainl1
  :: (Parseable s)
  => Parser s a
  -> Parser s (a -> a -> a)
  -> Parser s a
p `chainl1` op =
  do {a <- p; rest a}
  where
    rest a =
      (do f <- op
          b <- p
          rest (f a b)) <|> return a
      
--------------------------------------------------------------------------------

char
  :: (Parseable s)
  => Char
  -> Parser s Char
char c = satisfy (c ==)

string
  :: (Parseable s)
  => String
  -> Parser s String
string [] = return []
string (c:cs) = do { _ <- char c; _ <- string cs; return (c:cs)}

token
  :: (Parseable s)
  => Parser s a
  -> Parser s a
token p = do { a <- p; _ <- spaces ; return a}

reserved
  :: (Parseable s)
  => String
  -> Parser s String
reserved s = token (string s)

spaces
  :: (Parseable s)
  => Parser s String
spaces = many $ oneOf " \n\r"
    
--------------------------------------------------------------------------------

runParser
  :: (Parseable s)
  => Parser s a
  -> s
  -> Either String a
runParser m s =
  ps $ parse m s
  where
    ps [   ] = Left "Parser error."
    ps (x:_) = aux x
    aux x
      |       nil $ rest = Right $ fst $ x
      | not . nil $ rest = Left  $ "Parser didn't consume entire stream."
      | otherwise        = Left  $ "Parser error."
      where
        rest = snd x

Parsers/URL/Types.hs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
module Parsers.URL.Types
  ( URI (..)
  , Scheme (..)
  , Authority (..)
  , Query (..)
  )
where

--------------------------------------------------------------------------------

-- URI = scheme:[//authority]path[?query][#fragment]
data URI
  = URI
  { scheme    ::       Scheme
  , authority ::       Authority
  , path      :: Maybe String
  , query     :: Maybe Query
  , fragment  :: Maybe String
  }
  deriving Show

data Scheme
  = HTTPS
  | HTTP
  | NotSupported
  deriving Show

-- authority = [userinfo@]host[:port]
data Authority
  = Authority
  { userinfo :: Maybe String
  , host     ::       String
  , port     :: Maybe Int
  }
  deriving Show

newtype Query
  = Query
    { keyValues :: [ (String, Maybe String) ]
    }
  deriving Show

-- Reference:
--
-- https://en.wikipedia.org/wiki/URL#Syntax

Parsers/URL/Internal.hs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
{-# LANGUAGE OverloadedStrings #-}

--------------------------------------------------------------------------------

module Parsers.URL.Internal
  ( uri
  )
where

--------------------------------------------------------------------------------

import           Control.Applicative.Alternative
  ( Alternative
    ( (<|>)
    )
  )
import           Parsers.NanoParsec
import           Parsers.URL.Types

--------------------------------------------------------------------------------

data Optional
  = OPath     String (Maybe Optional)
  | OQuery    Query  (Maybe Optional)
  | OFragment String
  deriving Show

--------------------------------------------------------------------------------

scheme'
  :: (Parseable s)
  => Parser s Scheme
scheme' =
  do
    -- tdammers, #haskell freenode, on how to avoid backtracking:
    -- do { string "http"; optional "https" (string "s" >> pure "https") }
    s <- string "https" <|> string "http"
    _ <- reserved ":"
    return $ aux s
    where
      aux "https" = HTTPS
      aux "http"  = HTTP
      aux _______ = NotSupported

userinfo'
  :: (Parseable s)
  => Parser s (Maybe String)
userinfo' =
  do
    u <- some noseparator
    _ <- reserved "@"
    return $ Just u
    where
      noseparator =
        satisfy ('@' /=)

host'
  :: (Parseable s)
  => Parser s String
host' =
  do
    h <- some noseparators
    return $ h
    where
      noseparators =
        satisfy $ \c -> ':' /= c && '/' /= c

port'
  :: (Parseable s)
  => Parser s (Maybe Int)
port' =
  do
    _ <- reserved ":"
    p <- some noseparator
    return $ Just $ read p
    where
      noseparator = satisfy ('/' /=)

authority'
  :: (Parseable s)
  => Parser s Authority
authority' =
  do
    _ <- reserved "//"
    u <- userinfo' <|> return Nothing
    h <- host'
    p <- port'     <|> return Nothing
    return $ Authority u h p

nooseparators
  :: (Parseable s)
  => Parser s Char
nooseparators =
  satisfy
  $ \c ->
      ':' /= c &&
      '/' /= c &&
      '?' /= c &&
      '&' /= c &&
      '=' /= c &&
      '#' /= c

path'
  :: (Parseable s)
  => Parser s String
path' =
  do
    _ <- some $ reserved "/"
    p <- many nooseparators
    return $ p

opath
  :: (Parseable s)
  => Parser s (Maybe Optional)
opath =
  do
    p <- path'
    o <- optional
    return $ Just $ OPath p o

query'
  :: (Parseable s)
  => Parser s Query
query' =
  do
    _ <- reserved "?"
    p <- pair `sepBy` char '&'
    return $ Query p
    where
      might m =
        do
          a <- m
          return $ Just $ a
      pair =
        do
          key <- some nooseparators
          ___ <- reserved "="
          val <- (might $ some nooseparators) <|> return Nothing
          return (key, val)
      
oquery
  :: (Parseable s)
  => Parser s (Maybe Optional)
oquery =
  do
    q <- query'
    o <- optional
    return $ Just $ OQuery q o

fragment'
  :: (Parseable s)
  => Parser s String
fragment' =
  do
    _ <- reserved "#"
    p <- many nooseparators
    return $ p

ofragment
  :: (Parseable s)
  => Parser s (Maybe Optional)
ofragment =
  do
    q <- fragment'
    return $ Just $ OFragment q

optional
  :: (Parseable s)
  => Parser s (Maybe Optional)
optional =
  do
    o <- opath <|> oquery <|> ofragment <|> return Nothing
    return $ o

uri
  :: (Parseable s)
  => Parser s URI
uri =
  do
    s <- scheme'
    a <- authority'
    o <- optional
    return $ aux s a o
    where
      aux s a o = URI s a p q f
        where 
          (p,q,f) =
            opt (Nothing, Nothing, Nothing) o
      opt (p,q,f) (Just o) =
        case o of
          OPath     p' mo -> opt (Just p',      q ,      f ) mo
          OQuery    q' mo -> opt (p      , Just q',      f ) mo
          OFragment f'    ->     (p      ,      q , Just f')
      opt (p,q,f) (Nothing) =
        (p,q,f)

Parsers/URI.hs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
module Parsers.URL
  ( parse
  )
where

--------------------------------------------------------------------------------

import qualified Parsers.NanoParsec   as NP
import           Parsers.URL.Internal
import qualified Parsers.URL.Types    as URL
 
--------------------------------------------------------------------------------

parse
  :: (NP.Parseable s)
  => s
  -> Either String URL.URI
parse url =
  NP.runParser uri url

Main.hs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#!/usr/bin/env stack
{- stack
   --resolver lts-11.7
   --install-ghc
   runghc
   --package bytestring
   --package monadplus
   --
   -Wall -Werror
-}

--------------------------------------------------------------------------------

{-# LANGUAGE OverloadedStrings #-}

--------------------------------------------------------------------------------

module Main (main) where

--------------------------------------------------------------------------------

import qualified Data.ByteString       as BS
import qualified Parsers.URL           as URL

--------------------------------------------------------------------------------

main
  :: IO ()

--------------------------------------------------------------------------------

main =
  do
    putStrLn $ show $ URL.parse url
    putStrLn ""
    putStrLn $ show $ URL.parse url'
    where
      -- Call the parse on a regular string
      url  :: String
      url  = "https://johndoe@www.example.com:8433/foo?bar=42&baz=#qux"
      -- But also call it on a ByteString
      url' :: BS.ByteString
      url' = "https://johndoe@www.example.com:8433/foo?bar=42&baz=#qux"

Output:

user@personal:~/.../src$ ./Main.hs 
Right
  ( URI
    { scheme = HTTPS
    , authority =
      Authority
      { userinfo = Just "johndoe"
      , host = "www.example.com"
      , port = Just 8433
      }
    , path = Just "foo"
    , query =
      Just
      ( Query
        { keyValues =
          [ ("bar",Just "42")
          , ("baz",Nothing)
          ]
        }
      )
    , fragment = Just "qux"
    }

Right
  ( URI
    { scheme = HTTPS
    , authority =
      Authority
      { userinfo = Just "johndoe"
      , host = "www.example.com"
      , port = Just 8433
      }
    , path = Just "foo"
    , query =
      Just
      ( Query
        { keyValues =
          [ ("bar",Just "42")
          , ("baz",Nothing)
          ]
        }
      )
    , fragment = Just "qux"
    }
user@personal:~/.../src$ 

Note: Output has been prettyfied to fit in this code snippet.

References: