IllegalInput -> do put saved -- 状態を復歸
runParser g
ReachedEOF -> if pstIsEOFFatal saved then
- return ReachedEOF
+ do put saved
+ return ReachedEOF
else
do put saved
runParser g
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