]> gitweb @ CieloNegro.org - Lucu.git/blobdiff - Network/HTTP/Lucu/Parser.hs
Fixed stack-overflow bugs
[Lucu.git] / Network / HTTP / Lucu / Parser.hs
index 90c52696fbb4293e95849e5335758d7a255913bd..8c591defd4be602e13db5534567637039b0679bb 100644 (file)
@@ -174,7 +174,8 @@ f <|> g
                      IllegalInput -> do put saved -- 状態を復歸
                                         runParser g
                      ReachedEOF   -> if pstIsEOFFatal saved then
-                                         return ReachedEOF
+                                         do put saved
+                                            return ReachedEOF
                                      else
                                          do put saved
                                             runParser g
@@ -221,27 +222,48 @@ hexDigit = do c <- anyChar
 
 
 many :: Parser a -> Parser [a]
-many p = p `seq`
-         do x  <- p
-            xs <- many p
-            return (x:xs)
-         <|>
-         return []
+many !p = Parser $! many' p []
+
+-- This implementation is rather ugly but we need to make it
+-- tail-recursive to avoid stack overflow.
+many' :: Parser a -> [a] -> State ParserState (ParserResult [a])
+many' !p !soFar
+    = do saved  <- get
+         result <- runParser p
+         case result of
+           Success a    -> many' p (a:soFar)
+           IllegalInput -> do put saved
+                              return $! Success $ reverse soFar
+           ReachedEOF   -> if pstIsEOFFatal saved then
+                               do put saved
+                                  return ReachedEOF
+                           else
+                               do put saved
+                                  return $! Success $ reverse soFar
 
 
 many1 :: Parser a -> Parser [a]
-many1 p = p `seq`
-          do x  <- p
-             xs <- many p
-             return (x:xs)
+many1 !p = do x  <- p
+              xs <- many p
+              return (x:xs)
 
 
 count :: Int -> Parser a -> Parser [a]
-count 0 _ = return []
-count n p = n `seq` p `seq`
-            do x  <- p
-               xs <- count (n-1) p
-               return (x:xs)
+count !n !p = Parser $! count' n p []
+
+-- This implementation is rather ugly but we need to make it
+-- tail-recursive to avoid stack overflow.
+count' :: Int -> Parser a -> [a] -> State ParserState (ParserResult [a])
+count' 0  _  !soFar = return $! Success $ reverse soFar
+count' !n !p !soFar = do saved  <- get
+                         result <- runParser p
+                         case result of
+                           Success a    -> count' (n-1) p (a:soFar)
+                           IllegalInput -> do put saved
+                                              return IllegalInput
+                           ReachedEOF   -> do put saved
+                                              return ReachedEOF
+
 
 -- def may be a _|_
 option :: a -> Parser a -> Parser a