)
where
-import Control.Monad.State
+import Control.Monad.State.Strict
import qualified Data.ByteString.Lazy.Char8 as B
import Data.ByteString.Lazy.Char8 (ByteString)
+
-- |@Parser a@ is obviously a parser which parses and returns @a@.
newtype Parser a = Parser {
runParser :: State ParserState (ParserResult a)
}
-type ParserState = (ByteString, IsEOFFatal)
-type IsEOFFatal = Bool
+data ParserState
+ = PST {
+ pstInput :: ByteString
+ , pstIsEOFFatal :: !Bool
+ }
+ deriving (Eq, Show)
+
data ParserResult a = Success !a
| IllegalInput -- 受理出來ない入力があった
-- (>>=) :: Parser a -> (a -> Parser b) -> Parser b
instance Monad Parser where
- p >>= f = Parser $! do saved@(_, isEOFFatal) <- get -- 失敗した時の爲に状態を保存
+ p >>= f = Parser $! do saved <- get -- 失敗した時の爲に状態を保存
result <- runParser p
case result of
- Success a -> a `seq` runParser (f a)
+ Success a -> runParser (f a)
IllegalInput -> do put saved -- 状態を復歸
return IllegalInput
- ReachedEOF -> do unless isEOFFatal
- $ put saved -- 状態を復歸
+ ReachedEOF -> do put saved -- 状態を復歸
return ReachedEOF
return x = x `seq` Parser $! return $! Success x
fail _ = Parser $! return $! IllegalInput
parse :: Parser a -> ByteString -> (ParserResult a, ByteString)
parse p input -- input は lazy である必要有り。
= p `seq`
- let (result, (input', _)) = runState (runParser p) (input, True)
+ let (result, state') = runState (runParser p) (PST input True)
in
- result `seq` (result, input') -- input' も lazy である必要有り。
+ result `seq` (result, pstInput state') -- pstInput state' も lazy である必要有り。
-- |@'parseStr' p str@ packs @str@ and parses it.
parseStr :: Parser a -> String -> (ParserResult a, ByteString)
anyChar :: Parser Char
anyChar = Parser $!
- do (input, isEOFFatal) <- get
+ do state@(PST input _) <- get
if B.null input then
return ReachedEOF
else
- do put (B.tail input, isEOFFatal)
+ do put $! state { pstInput = B.tail input }
return (Success $! B.head input)
eof :: Parser ()
eof = Parser $!
- do (input, _) <- get
+ do PST input _ <- get
if B.null input then
- return $ Success ()
+ return $! Success ()
else
return IllegalInput
-- |@'allowEOF' p@ makes @p@ treat reaching EOF a normal failure.
allowEOF :: Parser a -> Parser a
allowEOF f = f `seq`
- Parser $! do (input, isEOFFatal) <- get
- put (input, False)
+ Parser $! do saved@(PST _ isEOFFatal) <- get
+ put $! saved { pstIsEOFFatal = False }
result <- runParser f
- (input', _) <- get
- put (input', isEOFFatal)
+ state <- get
+ put $! state { pstIsEOFFatal = isEOFFatal }
return result
(<|>) :: Parser a -> Parser a -> Parser a
f <|> g
= f `seq` g `seq`
- Parser $! do saved@(_, isEOFFatal) <- get -- 状態を保存
+ Parser $! do saved <- get -- 状態を保存
result <- runParser f
case result of
- Success a -> return $ Success a
+ Success a -> return $! Success a
IllegalInput -> do put saved -- 状態を復歸
runParser g
- ReachedEOF -> if isEOFFatal then
+ ReachedEOF -> if pstIsEOFFatal saved then
return ReachedEOF
else
do put saved