module Text.ParserCombinators.Poly.NoLeak.State
(
Parser(P)
, runParser
, next
, satisfy
, stUpdate
, stQuery
, stGet
, reparse
, module Text.ParserCombinators.Poly.Base
) where
import Text.ParserCombinators.Poly.Base
newtype Parser s t a = P (s -> [t] -> Result [t] s a)
data Result z s a = Success z s a
| Failure z s String
| Committed (Result z s a)
instance Functor (Result z s) where
fmap f (Success z s a) = Success z s (f a)
fmap f (Failure z s e) = Failure z s e
fmap f (Committed r) = Committed (fmap f r)
runParser :: Parser s t a -> s -> [t] -> (Either String a, s, [t])
runParser (P p) = \s-> resultToEither . p s
where
resultToEither :: Result z s a -> (Either String a, s, z)
resultToEither (Success z s a) = (Right a, s, z)
resultToEither (Failure z s e) = (Left e, s, z)
resultToEither (Committed r) = resultToEither r
instance Functor (Parser s t) where
fmap f (P p) = P (\s-> fmap f . p s)
instance Monad (Parser s t) where
return x = P (\s ts-> Success ts s x)
fail e = P (\s ts-> Failure ts s e)
(P f) >>= g = P (\s-> continue . f s)
where
continue (Success ts s x) = let (P g') = g x in g' s ts
continue (Committed (Committed r)) = continue (Committed r)
continue (Committed r) = Committed (continue r)
continue (Failure ts s e) = Failure ts s e
instance PolyParse (Parser s t) where
commit (P p) = P (\s-> Committed . p s)
(P p) `adjustErr` f = P (\s-> adjust . p s)
where
adjust (Failure z s e) = Failure z s (f e)
adjust (Committed r) = Committed (adjust r)
adjust good = good
(P p) `onFail` (P q) = P (\s ts-> continue s ts $ p s ts)
where
continue s ts (Failure _ _ _) = q s ts
continue _ _ r = r
oneOf' = accum []
where accum errs [] =
fail ("failed to parse any of the possible choices:\n"
++indent 2 (concatMap showErr (reverse errs)))
accum errs ((e,P p):ps) =
P (\s ts-> case p s ts of
Failure _ _ err ->
let (P p) = accum ((e,err):errs) ps
in p s ts
r@(Success z _ a) -> r
r@(Committed _) -> r )
showErr (name,err) = name++":\n"++indent 2 err
next :: Parser s t t
next = P (\s ts-> case ts of
[] -> Failure [] s "Ran out of input (EOF)"
(t:ts') -> Success ts' s t )
satisfy :: (t->Bool) -> Parser s t t
satisfy pred = do { x <- next
; if pred x then return x else fail "Parse.satisfy: failed"
}
stUpdate :: (s->s) -> Parser s t ()
stUpdate f = P (\s ts-> Success ts (f s) ())
stQuery :: (s->a) -> Parser s t a
stQuery f = P (\s ts-> Success ts s (f s))
stGet :: Parser s t s
stGet = P (\s ts-> Success ts s s)
reparse :: [t] -> Parser s t ()
reparse ts = P (\s inp-> Success (ts++inp) s ())