]> gitweb @ CieloNegro.org - Lucu.git/blob - Network/HTTP/Lucu/Parser.hs
Fixed breakage on GHC 6.10.1
[Lucu.git] / Network / HTTP / Lucu / Parser.hs
1 -- |Yet another parser combinator. This is mostly a subset of
2 -- "Text.ParserCombinators.Parsec" but there are some differences:
3 --
4 -- * This parser works on 'Data.ByteString.Base.LazyByteString'
5 --   instead of 'Prelude.String'.
6 --
7 -- * Backtracking is the only possible behavior so there is no \"try\"
8 --   action.
9 --
10 -- * On success, the remaining string is returned as well as the
11 --   parser result.
12 --
13 -- * You can choose whether to treat reaching EOF (trying to eat one
14 --   more letter at the end of string) a fatal error or to treat it a
15 --   normal failure. If a fatal error occurs, the entire parsing
16 --   process immediately fails without trying any backtracks. The
17 --   default behavior is to treat EOF fatal.
18 --
19 -- In general, you don't have to use this module directly.
20 module Network.HTTP.Lucu.Parser
21     ( Parser
22     , ParserResult(..)
23
24     , failP
25
26     , parse
27     , parseStr
28
29     , anyChar
30     , eof
31     , allowEOF
32     , satisfy
33     , char
34     , string
35     , (<|>)
36     , choice
37     , oneOf
38     , digit
39     , hexDigit
40     , notFollowedBy
41     , many
42     , many1
43     , count
44     , option
45     , sepBy
46     , sepBy1
47
48     , sp
49     , ht
50     , crlf
51     )
52     where
53
54 import           Control.Monad.State.Strict
55 import qualified Data.ByteString.Lazy as Lazy (ByteString)
56 import qualified Data.ByteString.Lazy.Char8 as B hiding (ByteString)
57
58 -- |@'Parser' a@ is obviously a parser which parses and returns @a@.
59 newtype Parser a = Parser {
60       runParser :: State ParserState (ParserResult a)
61     }
62
63
64 data ParserState
65     = PST {
66         pstInput      :: Lazy.ByteString
67       , pstIsEOFFatal :: !Bool
68       }
69     deriving (Eq, Show)
70
71
72 data ParserResult a = Success !a
73                     | IllegalInput -- 受理出來ない入力があった
74                     | ReachedEOF   -- 限界を越えて讀まうとした
75                       deriving (Eq, Show)
76
77
78 --  (>>=) :: Parser a -> (a -> Parser b) -> Parser b
79 instance Monad Parser where
80     p >>= f = Parser $! do saved <- get -- 失敗した時の爲に状態を保存
81                            result <- runParser p
82                            case result of
83                              Success a    -> runParser (f a)
84                              IllegalInput -> do put saved -- 状態を復歸
85                                                 return IllegalInput
86                              ReachedEOF   -> do put saved -- 状態を復歸
87                                                 return ReachedEOF
88     return x = x `seq` Parser $! return $! Success x
89     fail _   = Parser $! return $! IllegalInput
90
91 -- |@'failP'@ is just a synonym for @'Prelude.fail'
92 -- 'Prelude.undefined'@.
93 failP :: Parser a
94 failP = fail undefined
95
96 -- |@'parse' p bstr@ parses @bstr@ with @p@ and returns @(# result,
97 -- remaining #)@.
98 parse :: Parser a -> Lazy.ByteString -> (# ParserResult a, Lazy.ByteString #)
99 parse p input -- input は lazy である必要有り。
100     = p `seq`
101       let (result, state') = runState (runParser p) (PST input True)
102       in
103         result `seq` (# result, pstInput state' #) -- pstInput state' も lazy である必要有り。
104
105 -- |@'parseStr' p str@ packs @str@ and parses it.
106 parseStr :: Parser a -> String -> (# ParserResult a, Lazy.ByteString #)
107 parseStr p input
108     = p `seq` -- input は lazy である必要有り。
109       parse p (B.pack input)
110
111
112 anyChar :: Parser Char
113 anyChar = Parser $!
114           do state@(PST input _) <- get
115              if B.null input then
116                  return ReachedEOF
117                else
118                  do put $! state { pstInput = B.tail input }
119                     return (Success $! B.head input)
120
121
122 eof :: Parser ()
123 eof = Parser $!
124       do PST input _ <- get
125          if B.null input then
126              return $! Success ()
127            else
128              return IllegalInput
129
130 -- |@'allowEOF' p@ makes @p@ treat reaching EOF a normal failure.
131 allowEOF :: Parser a -> Parser a
132 allowEOF f = f `seq`
133              Parser $! do saved@(PST _ isEOFFatal) <- get
134                           put $! saved { pstIsEOFFatal = False }
135
136                           result <- runParser f
137                          
138                           state <- get
139                           put $! state { pstIsEOFFatal = isEOFFatal }
140
141                           return result
142
143
144 satisfy :: (Char -> Bool) -> Parser Char
145 satisfy f = f `seq`
146             do c <- anyChar
147                if f $! c then
148                    return c
149                  else
150                    failP
151
152
153 char :: Char -> Parser Char
154 char c = c `seq` satisfy (== c)
155
156
157 string :: String -> Parser String
158 string str = str `seq`
159              do mapM_ char str
160                 return str
161
162
163 infixr 0 <|>
164
165 -- |This is the backtracking alternation. There is no non-backtracking
166 -- equivalent.
167 (<|>) :: Parser a -> Parser a -> Parser a
168 f <|> g
169     = f `seq` g `seq`
170       Parser $! do saved  <- get -- 状態を保存
171                    result <- runParser f
172                    case result of
173                      Success a    -> return $! Success a
174                      IllegalInput -> do put saved -- 状態を復歸
175                                         runParser g
176                      ReachedEOF   -> if pstIsEOFFatal saved then
177                                          return ReachedEOF
178                                      else
179                                          do put saved
180                                             runParser g
181
182
183 choice :: [Parser a] -> Parser a
184 choice = foldl (<|>) failP
185
186
187 oneOf :: [Char] -> Parser Char
188 oneOf = foldl (<|>) failP . map char
189
190
191 notFollowedBy :: Parser a -> Parser ()
192 notFollowedBy p
193     = p `seq`
194       Parser $! do saved  <- get -- 状態を保存
195                    result <- runParser p
196                    case result of
197                      Success _    -> do put saved -- 状態を復歸
198                                         return IllegalInput
199                      IllegalInput -> do put saved -- 状態を復歸
200                                         return $! Success ()
201                      ReachedEOF   -> do put saved -- 状態を復歸
202                                         return $! Success ()
203
204
205 digit :: Parser Char
206 digit = do c <- anyChar
207            if c >= '0' && c <= '9' then
208                return c
209              else
210                failP
211
212
213 hexDigit :: Parser Char
214 hexDigit = do c <- anyChar
215               if (c >= '0' && c <= '9') ||
216                  (c >= 'a' && c <= 'f') ||
217                  (c >= 'A' && c <= 'F') then
218                   return c
219                 else
220                   failP
221
222
223 many :: Parser a -> Parser [a]
224 many p = p `seq`
225          do x  <- p
226             xs <- many p
227             return (x:xs)
228          <|>
229          return []
230
231
232 many1 :: Parser a -> Parser [a]
233 many1 p = p `seq`
234           do x  <- p
235              xs <- many p
236              return (x:xs)
237
238
239 count :: Int -> Parser a -> Parser [a]
240 count 0 _ = return []
241 count n p = n `seq` p `seq`
242             do x  <- p
243                xs <- count (n-1) p
244                return (x:xs)
245
246 -- def may be a _|_
247 option :: a -> Parser a -> Parser a
248 option def p = p `seq`
249                p <|> return def
250
251
252 sepBy :: Parser a -> Parser sep -> Parser [a]
253 sepBy p sep = p `seq` sep `seq`
254               sepBy1 p sep <|> return []
255
256
257 sepBy1 :: Parser a -> Parser sep -> Parser [a]
258 sepBy1 p sep = p `seq` sep `seq`
259                do x  <- p
260                   xs <- many $! sep >> p
261                   return (x:xs)
262
263
264 sp :: Parser Char
265 sp = char ' '
266
267
268 ht :: Parser Char
269 ht = char '\t'
270
271
272 crlf :: Parser String
273 crlf = string "\x0d\x0a"