module Text.GrammarCombinators.Parser.Parsec (
parseParsec,
parseParsecR,
parseParsecBiased,
WrapGenParser, unWGP
) where
import Text.GrammarCombinators.Base
import Text.GrammarCombinators.Transform.UnfoldRecursion
import Text.GrammarCombinators.Transform.IntroduceBias
import Text.Parsec
import Text.Parsec.Pos
import qualified Text.Parsec as Parsec
newtype WrapGenParser t v = WGP { unWGP :: Parsec [ConcreteToken t] () v }
instance (Token t) => ProductionRule (WrapGenParser t) where
a >>> b = WGP $ do f <- unWGP a; x <- unWGP b; return $ f x
a ||| b = WGP $ try (unWGP a) <|> unWGP b
endOfInput = WGP eof
die = WGP parserZero
instance BiasedProductionRule (WrapGenParser t) where
a >||| b = WGP $ unWGP a <|> unWGP b
instance (Token t) => EpsProductionRule (WrapGenParser t) where
epsilon v = WGP $ return v
instance (Token t) => LiftableProductionRule (WrapGenParser t) where
epsilonL v _ = epsilon v
nextPos :: SourcePos -> t -> t1 -> SourcePos
nextPos p _ _ = newPos (sourceName p) (sourceLine p) (sourceColumn p+1)
instance (Token t) => TokenProductionRule (WrapGenParser t) t where
token tt = WGP $ tokenPrim show nextPos testToken
where
testToken t = if classify t == tt then Just t else Nothing
anyToken = WGP $ tokenPrim show nextPos Just
parseParsec :: forall phi t r ix.
(Token t) =>
ProcessingBiasedContextFreeGrammar phi t r ->
phi ix -> SourceName -> [ConcreteToken t] -> Either ParseError (r ix)
parseParsec gram idx =
let irule :: WrapGenParser t (r ix)
irule = unfoldRecursionB gram idx
parser = unWGP irule
in Parsec.parse parser
parseParsecR :: forall phi t r ix.
(Token t) =>
ProcessingBiasedRegularGrammar phi t r ->
phi ix -> SourceName -> [ConcreteToken t] -> Either ParseError (r ix)
parseParsecR gram idx =
let irule :: WrapGenParser t (r ix)
irule = gram idx
parser = unWGP irule
in Parsec.parse parser
parseParsecBiased :: forall phi t r ix.
(Token t, EqFam phi) =>
ProcessingContextFreeGrammar phi t r ->
phi ix -> SourceName ->
[ConcreteToken t] -> Either ParseError (r ix)
parseParsecBiased gram idx =
let gramB :: ProcessingBiasedContextFreeGrammar phi t r
gramB = introduceBias gram
irule :: WrapGenParser t (r ix)
irule = unfoldRecursionB gramB idx
parser = unWGP irule
in Parsec.parse parser