| Copyright | (C) 2026 - Eitan Chatav |
|---|---|
| License | BSD-style (see the file LICENSE) |
| Maintainer | Eitan Chatav <eitan.chatav@gmail.com> |
| Stability | provisional |
| Portability | non-portable |
| Safe Haskell | None |
| Language | Haskell2010 |
Control.Lens.Grammar
Description
See Chomsky, On Certain Formal Properties of Grammars
Synopsis
- class Grammar token a => RegGrammar token a where
- regGrammar :: RegGrammatical token p => p a a
- type RegGrammatical token (p :: Type -> Type -> Type) = (forall x y. (x ~ (), y ~ ()) => TerminalSymbol token (p x y), forall x y. (x ~ token, y ~ token) => TokenAlgebra token (p x y), Alternator p, forall x y. Tried (p x y))
- regexG :: forall a -> (Categorized token, RegGrammar token a) => RegEx token
- class CtxGrammar token a => Grammar token a where
- grammar :: Grammatical token p => p a a
- type Grammatical token (p :: Type -> Type -> Type) = (RegGrammatical token p, forall x y. BackusNaurForm (p x y))
- regbnfG :: forall a -> (Categorized token, Grammar token a) => Bnf (RegEx token)
- applicativeG :: (Grammar token a, Alternative f, TokenAlgebra token (f token), TerminalSymbol token (f ()), forall x. BackusNaurForm (f x), forall x. Tried (f x)) => f a
- transducerG :: forall a -> (Categorized token, Grammar token a) => Transducer token
- class CtxGrammar token a where
- ctxGrammar :: CtxGrammatical token p => p a a
- type CtxGrammatical token (p :: Type -> Type -> Type) = (Grammatical token p, Filtrator p, forall x. MonadPlus (p x), forall x. MonadFail (p x))
- printG :: forall a string token m. (CtxGrammar token a, Cons string string token token, IsList string, Item string ~ token, Categorized token, Alternative m, Monad m, Filterable m) => a -> m (string -> string)
- parseG :: forall a string token m. (CtxGrammar token a, Cons string string token token, Snoc string string token token, IsList string, Item string ~ token, Categorized token, Alternative m, Monad m, Filterable m) => string -> m (a, string)
- unparseG :: forall a string token m. (CtxGrammar token a, Cons string string token token, Snoc string string token token, IsList string, Item string ~ token, Categorized token, Alternative m, Monad m, Filterable m) => a -> string -> m string
- parsecG :: forall a string token. (CtxGrammar token a, Cons string string token token, Snoc string string token token, Item string ~ token, Categorized token) => string -> ParsecState string a
- unparsecG :: forall a string token. (CtxGrammar token a, Cons string string token token, Snoc string string token token, Item string ~ token, Categorized token) => a -> string -> ParsecState string a
- readG :: CtxGrammar Char a => ReadP a
- monadG :: (CtxGrammar token a, MonadPlus m, MonadFail m, Filterable m, forall x. BackusNaurForm (m x), forall x. Tried (m x), TokenAlgebra token (m token), TerminalSymbol token (m ())) => m a
- digit :: (Integral n, Choice p, Tokenized Char (p Char Char)) => n -> p n n
- numeral :: (Integral n, Alternator p, Tokenized Char (p Char Char)) => n -> p n n
- putStringLn :: (IsList string, Item string ~ Char) => string -> IO ()
- module Control.Lens.Bifocal
- module Control.Lens.Cons
- module Control.Lens.Diopter
- module Control.Lens.Empty
- module Control.Lens.Grammar.Analysis
- module Control.Lens.Grammar.Machine
- module Control.Lens.Grammar.Prec
- module Control.Lens.Grammar.Pretty
- module Control.Lens.Grammar.RegEx
- module Control.Lens.Grammar.Symbol
- module Control.Lens.Grammar.Token
- module Control.Lens.PartialIso
- module Control.Lens.Prismoid
- module Control.Lens.Varifocal
- module Data.Monoid.Disjunctive
- module Data.Profunctor.Distributor
- module Data.Profunctor.Filtrator
- module Data.Profunctor.Grammar
- module Data.Profunctor.Grammar.Parsector
- module Data.Profunctor.Monadic
- module Data.Profunctor.Monoidal
- module Data.Profunctor.Monoidal.Cocartesian
- module Data.Traversable.Homogeneous
- module Data.Traversable.Homogeneous.Enumerable
- failP :: (Ruled p, DisjunctiveMonoid p) => String -> p
- ruleTyped :: (Typeable a, Ruled (p a a)) => p a a -> p a a
- class Ruled bnf => BackusNaurForm bnf where
- class Ruled p where
- class Tried p where
- try :: p -> p
- class Applicative f => Alternative (f :: Type -> Type) where
- class (Alternative m, Monad m) => MonadPlus (m :: Type -> Type) where
- class Monad m => MonadFail (m :: Type -> Type) where
- class Functor f => Filterable (f :: Type -> Type) where
Regular grammar
A regular grammar may be constructed using
terminal symbols, Tokenized combinators, tokenClasses
and Alternator combinators.
Let's see an example using
semantic versioning syntax.
>>>import Numeric.Natural (Natural)>>>:{data SemVer = SemVer -- e.g., 2.1.5-rc.1+build.123 { major :: Natural -- e.g., 1 , minor :: Natural -- e.g., 2 , patch :: Natural -- e.g., 3 , preRelease :: [String] -- e.g., "alpha.1", "rc.2" , buildMetadata :: [String] -- e.g., "build.123", "20130313144700" } deriving (Eq, Ord, Show, Read) :}
We'd like to define an optic _SemVer,
corresponding to the constructor pattern SemVer.
You could generate it with the TemplateHaskell combinator,
makeNestedPrisms.
makeNestedPrisms ''SemVer
Unfortunately, we can't use TemplateHaskell to generate it in GHCi,
which is used to test this documentation.
Here is equivalent Haskell code instead.
Since SemVer has only one constructor,
_SemVer can be an Iso.
>>>:set -XRecordWildCards>>>import Control.Lens (Iso', iso)>>>:{_SemVer :: Iso' SemVer (Natural, (Natural, (Natural, ([String], [String])))) _SemVer = iso (\SemVer {..} -> (major, (minor, (patch, (preRelease, buildMetadata))))) (\(major, (minor, (patch, (preRelease, buildMetadata)))) -> SemVer {..}) :}
Now we can build a RegGrammar for SemVer using the "idiom" style of
Applicative parsing with a couple modifications.
>>>:{semverGrammar :: RegGrammatical Char p => p SemVer SemVer semverGrammar = _SemVer >? numberG >*< terminal "." >* numberG >*< terminal "." >* numberG >*< optionP _Empty (terminal "-" >* identifiersG) >*< optionP _Empty (terminal "+" >* identifiersG) where numberG = numeral 10 identifiersG = sepWith "." (atLeast 1) (someP charG) charG = asIn LowercaseLetter >|< asIn UppercaseLetter >|< asIn DecimalNumber >|< token '-' instance CtxGrammar Char SemVer instance Grammar Char SemVer instance RegGrammar Char SemVer where regGrammar = semverGrammar :}
A type's RegGrammar instance, here semverGrammar, & its Grammar
& CtxGrammar instances, by default, let generators run it by its type,
a required type argument, (type SemVer) where a constructor shares
its name, & parsers & printers by inference.
Instead of using the constructor SemVer with the Functor applicator <$>,
we use the optic _SemVer we defined and the Choice applicator >?;
although, we could have used the Profunctor applicator >~ instead,
because _SemVer is an Iso.
| Functorial | Profunctorial |
|---|---|
SemVer | _SemVer |
<$> | >? |
pure | pureP |
*> | >* |
<* | *< |
<*> | >*< |
empty | falseP |
<|> | >|< |
choice | orP |
many | manyP |
some | someP |
optional | optionalP |
You can generate a regular expression string, a RegEx, from a RegGrammar
with regexG.
>>>putStringLn (regexG (type SemVer))[0-9]+.[0-9]+.[0-9]+(-(\p{Ll}|\p{Lu}|\p{Nd}|-)+(.(\p{Ll}|\p{Lu}|\p{Nd}|-)+)*)?(\+(\p{Ll}|\p{Lu}|\p{Nd}|-)+(.(\p{Ll}|\p{Lu}|\p{Nd}|-)+)*)?
You can also generate parsers and printers.
>>>[parsed | (parsed, "") <- parseG @SemVer "2.1.5-rc.1+build.123"][SemVer {major = 2, minor = 1, patch = 5, preRelease = ["rc","1"], buildMetadata = ["build","123"]}]
Parsing unconses tokens left-to-right, from the beginning of a string.
Unparsing, on the other hand, snocs tokens left-to-right, to the end of a string.
>>>unparseG (SemVer 1 0 0 ["alpha"] []) "SemVer: " :: Maybe StringJust "SemVer: 1.0.0-alpha"
Printing, on the gripping hand, conses tokens right-to-left, to the beginning of a string.
>>>($ " is the SemVer.") <$> printG (SemVer 1 2 3 [] []) :: Maybe StringJust "1.2.3 is the SemVer."
Profunctorial combinators give us correct-by-construction invertible parsers.
New RegGrammar generators can be defined with new RegGrammatical instances.
class Grammar token a => RegGrammar token a where Source #
A type's regular grammar, over its tokens, which is also its context-free & context-sensitive grammar.
Methods
regGrammar :: RegGrammatical token p => p a a Source #
type RegGrammatical token (p :: Type -> Type -> Type) = (forall x y. (x ~ (), y ~ ()) => TerminalSymbol token (p x y), forall x y. (x ~ token, y ~ token) => TokenAlgebra token (p x y), Alternator p, forall x y. Tried (p x y)) Source #
The Alternators of terminal symbols, Tokenized combinators
& tokenClasses, which are Tried, & run
Control.Lens.Grammar.RegGrammars.
regexG :: forall a -> (Categorized token, RegGrammar token a) => RegEx token Source #
regexG generates a RegExpression from a regular grammar,
over any token, a regular expression string over characters.
Since context-free Grammars and CtxGrammars aren't necessarily regular,
the type system will prevent regexG from being applied to them.
Context-free grammar
Context-free Grammars add two capabilities to RegGrammars,
coming from the BackusNaurForm interface
ruleabstraction,- and general recursion.
The Grammars of RegExpressions & of their Bnfs, in
Control.Lens.Grammar.RegEx, are examples of context-free Grammars. Regular expressions are a form of expression algebra.
Let's see a similar but simpler example,
the algebra of arithmetic expressions of natural numbers.
>>>import Numeric.Natural (Natural)>>>:{data Arith = Num Natural | Add Arith Arith | Mul Arith Arith deriving stock (Eq, Ord, Show, Read) :}
Here are Prisms for the constructor patterns.
>>>import Control.Lens (Prism', prism')>>>:{_Num :: Prism' Arith Natural _Num = prism' Num (\case Num n -> Just n; _ -> Nothing) _Add, _Mul :: Prism' Arith (Arith, Arith) _Add = prism' (uncurry Add) (\case Add x y -> Just (x,y); _ -> Nothing) _Mul = prism' (uncurry Mul) (\case Mul x y -> Just (x,y); _ -> Nothing) :}
Now we can build a Grammar for Arith
by combining "idiom" style with named rules,
and tying the recursive loop
(caused by parenthesization)
with ruleRec.
>>>:{arithGrammar :: Grammatical Char p => p Arith Arith arithGrammar = ruleRec "arith" sumG where sumG arith = rule "sum" $ sepWith "+" (chain1 Left _Add) (prodG arith) prodG arith = rule "product" $ sepWith "*" (chain1 Left _Mul) (factorG arith) factorG arith = rule "factor" $ numberG >|< terminal "(" >* arith *< terminal ")" numberG = rule "number" $ _Num >? numeral 10 instance CtxGrammar Char Arith instance Grammar Char Arith where grammar = arithGrammar :}
We can generate grammar strings, printers and parsers from arithGrammar.
>>>putStringLn (regbnfG Arith){start} = \q{arith} {arith} = \q{sum} {factor} = \q{number}|\(\q{arith}\) {number} = [0-9]+ {product} = \q{factor}(\*\q{factor})* {sum} = \q{product}(\+\q{product})*>>>[x | (x,"") <- parseG @Arith "1+2*3+4"][Add (Add (Num 1) (Mul (Num 2) (Num 3))) (Num 4)]>>>unparseG (Add (Num 1) (Mul (Num 2) (Num 3))) "" :: Maybe StringJust "1+2*3">>>do pr <- printG (Num 69); pure (pr "") :: Maybe StringJust "69"
Operator tables with precedence, like buildExpressionParser's,
are built by withOperators. For example, an expression grammar
over natural numbers with a postfix factorial ! (binding tightest,
and not required to actually compute a factorial), a right-associative
exponent ^, a left-associative *, and left-associative + & -
binding loosest:
>>>:{data Expr = Nat Natural | Fac Expr | Exp Expr Expr | Mul Expr Expr | Add Expr Expr | Sub Expr Expr deriving stock (Eq, Ord, Show, Read) _Nat :: Prism' Expr Natural _Nat = prism' Nat (\case Nat n -> Just n; _ -> Nothing) _Fac :: Prism' Expr Expr _Fac = prism' Fac (\case Fac x -> Just x; _ -> Nothing) _Exp, _Mul, _Add, _Sub :: Prism' Expr (Expr, Expr) _Exp = prism' (uncurry Exp) (\case Exp x y -> Just (x,y); _ -> Nothing) _Mul = prism' (uncurry Mul) (\case Mul x y -> Just (x,y); _ -> Nothing) _Add = prism' (uncurry Add) (\case Add x y -> Just (x,y); _ -> Nothing) _Sub = prism' (uncurry Sub) (\case Sub x y -> Just (x,y); _ -> Nothing) exprGrammar :: Grammatical Char p => p Expr Expr exprGrammar = ruleRec "expr" $ \expr -> let atom = rule "atom" $ nat >|< terminal "(" >* expr *< terminal ")" nat = rule "nat" $ _Nat >? numeral 10 in withOperators [ [ Postfix _Fac (terminal "!") ] , [ Infix RightAssoc _Exp (terminal "^") ] , [ Infix LeftAssoc _Mul (terminal "*") ] , [ Infix LeftAssoc _Add (terminal "+"), Infix LeftAssoc _Sub (terminal "-") ] ] atom instance CtxGrammar Char Expr instance Grammar Char Expr where grammar = exprGrammar :}
The right-associative ^ groups to the right, - to the left, *
binds tighter than +, and postfix ! binds tighter than ^:
>>>[e | (e,"") <- parseG @Expr "2^3^2"][Exp (Nat 2) (Exp (Nat 3) (Nat 2))]>>>[e | (e,"") <- parseG @Expr "3-2-1"][Sub (Sub (Nat 3) (Nat 2)) (Nat 1)]>>>[e | (e,"") <- parseG @Expr "2*3+4"][Add (Mul (Nat 2) (Nat 3)) (Nat 4)]>>>[e | (e,"") <- parseG @Expr "2*(3+4)"][Mul (Nat 2) (Add (Nat 3) (Nat 4))]>>>[e | (e,"") <- parseG @Expr "3!"][Fac (Nat 3)]>>>[e | (e,"") <- parseG @Expr "2^3!"][Exp (Nat 2) (Fac (Nat 3))]
Being bidirectional, the same grammar prints:
>>>unparseG (Exp (Nat 2) (Exp (Nat 3) (Nat 2))) "" :: Maybe StringJust "2^3^2">>>unparseG (Exp (Nat 2) (Fac (Nat 3))) "" :: Maybe StringJust "2^3!"
If all rules are non-recursive, then a Grammar
can be rewritten as a RegGrammar.
Since Haskell permits general recursion, and RegGrammars are
embedded in Haskell, you can define context-free grammars with them.
But it's recommended to use Grammars for rule abstraction
and generator support for ruleRec.
class CtxGrammar token a => Grammar token a where Source #
A type's context-free grammar, over its tokens, which is also its context-sensitive grammar; its regular grammar, by default.
Minimal complete definition
Nothing
Methods
grammar :: Grammatical token p => p a a Source #
default grammar :: (RegGrammar token a, Grammatical token p) => p a a Source #
Instances
| Grammar Char (Bnf (RegEx Char)) Source # | The context-free
Such a
Like
They can be generated from context-free Like
|
| Grammar Char (RegEx Char) Source # | The context-free
Since they are strings, they have a string-like interface.
They can be generated from
A regular expression string is stored as an algebraic datatype, a
They're similar to regular expression strings in many other
programming languages. We can use them to see if a word and pattern
are
Like
Since they're a
Like other regular expression languages, they support character classes.
The character classes are used for failure, matching no character or string, as well as the wildcard, matching any single character.
Additional forms of character classes test for a character's
Ill-formed regular expression strings normalize to failure.
|
Defined in Control.Lens.Grammar.RegEx | |
type Grammatical token (p :: Type -> Type -> Type) = (RegGrammatical token p, forall x y. BackusNaurForm (p x y)) Source #
The RegGrammatical BackusNaurForms, which run Grammars.
regbnfG :: forall a -> (Categorized token, Grammar token a) => Bnf (RegEx token) Source #
regbnfG generates a Bnf of RegExpressions from a context-free
Grammar, over any token, of regular expression strings over characters.
Since CtxGrammars aren't context-free,
the type system will prevent regbnfG from being applied to a CtxGrammar.
It can apply to a RegGrammar.
applicativeG :: (Grammar token a, Alternative f, TokenAlgebra token (f token), TerminalSymbol token (f ()), forall x. BackusNaurForm (f x), forall x. Tried (f x)) => f a Source #
Generate any Applicative parser backend
from a Grammar with applicativeG.
It works the same way as monadG,
for parsers without Monad instances.
That permits backends to use algorithms
that can only parse context-free Grammars.
transducerG :: forall a -> (Categorized token, Grammar token a) => Transducer token Source #
Compile a Grammar into a Transducer.
>>>let regexMachine = transducerG @Char (RegEx Char)
A transducer is a form of finite state machine,
usable as an intermediary for further generators like
=~, expectNext, languageSample, parseForest & unreachableRules.
>>>import Test.QuickCheck>>>let regexLang = languageSample @Char regexMachine>>>words100 <- generate (take 100 <$> regexLang)>>>quickCheck (property (all (=~ regexMachine) words100))+++ OK, passed 100 tests.>>>import Control.Monad.State>>>import System.Random>>>let gen = mkStdGen 69>>>evalState (take 15 <$> regexLang) gen["","|","\776269","()","[]","\\[","||","|\249908","\770923*","\1008821+","\318904?","\845807|","\477898\1026934","()*","()+"]
>>>import Data.Tree (drawForest)
>>> let (forest, _) = parseForest regexMachine "xy|z" in putStr (drawForest (map (fmap show) forest))
("regex",0,4,"xy|z")
|
`- ("alternate",0,4,"xy|z")
|
+- ("sequence",0,2,"xy")
| |
| +- ("expression",0,1,"x")
| | |
| | `- ("atom",0,1,"x")
| | |
| | `- ("class",0,1,"x")
| | |
| | `- ("class-one-of",0,1,"x")
| | |
| | `- ("char",0,1,"x")
| |
| `- ("expression",1,2,"y")
| |
| `- ("atom",1,2,"y")
| |
| `- ("class",1,2,"y")
| |
| `- ("class-one-of",1,2,"y")
| |
| `- ("char",1,2,"y")
|
`- ("sequence",3,4,"z")
|
`- ("expression",3,4,"z")
|
`- ("atom",3,4,"z")
|
`- ("class",3,4,"z")
|
`- ("class-one-of",3,4,"z")
|
`- ("char",3,4,"z")
Context-sensitive grammar
For context-sensitivity,
the Monadic interface is used by importing Data.Profunctor.Monadic.Do
qualified and using a "bonding" notation which mixes
"idiom" style with qualified do-notation.
Let's use length-encoded vectors of numbers as an example.
>>>import Numeric.Natural (Natural)>>>import Control.Lens.Iso (Iso', iso)>>>:set -XRecordWildCards>>>:{data LenVec = LenVec {length :: Natural, vector :: [Natural]} deriving (Eq, Ord, Show, Read) _LenVec :: Iso' LenVec (Natural, [Natural]) _LenVec = iso (\LenVec {..} -> (length, vector)) (\(length, vector) -> LenVec {..}) :}
>>>:set -XQualifiedDo>>>import qualified Data.Profunctor.Monadic.Do as P>>>:{lenvecGrammar :: CtxGrammatical Char p => p LenVec LenVec lenvecGrammar = _LenVec >? P.do let numberG = numeral 10 vectorG n = sepWith "," (exactly n) numberG len <- numberG -- bonds to _LenVec terminal ";" -- doesn't bond vectorG (fromIntegral len) -- bonds to _LenVec instance CtxGrammar Char LenVec where ctxGrammar = lenvecGrammar :}
The qualified do-notation changes the signature of
P.>>=,
so that we must apply the constructor pattern _LenVec
to the do-block with the >? applicator.
Any scoped bound action, var <- action,
gets "bonded" to the constructor pattern.
Unbound actions, except for the last action in the do-block,
don't get bonded to the pattern.
The last action does get bonded to the pattern.
Any unscoped bound action, _ <- action,
also gets bonded to the pattern,
but being unscoped means it isn't added to the context.
If all bound actions are unscoped,
and filtration & failure handling aren't used,
then a CtxGrammar can be rewritten as a Grammar since it is context-free.
We can't generate a Bnf from a CtxGrammar since the rules
aren't static, but dynamic and contextual.
We can generate parsers and printers as expected.
>>>[vec | (vec, "") <- parseG "3;1,2,3"] :: [LenVec][LenVec {length = 3, vector = [1,2,3]}]>>>[vec | (vec, "") <- parseG "0;1,2,3"] :: [LenVec][]>>>[pr "" | pr <- printG (LenVec 2 [6,7])] :: [String]["2;6,7"]>>>[pr "" | pr <- printG (LenVec 200 [100])] :: [String][]
In addition to context-sensitivity via Monadic combinators,
CtxGrammars add unrestricted filtration to Grammars.
The satisfy combinator is an unrestricted token filter.
And the satisfied pattern is used together with the Choice &
Cochoice applicator >?< for unrestricted filtration.
>>>:{palindromeG :: CtxGrammatical Char p => p String String palindromeG = rule "palindrome" $ satisfied (\wrd -> reverse wrd == wrd) >?< manyP (anyToken @Char) :}
>>>[pal | word <- ["racecar", "word"], (pal, "") <- parseP (palindromeG :: Parsor String [] String String) word]["racecar"]
Since CtxGrammars are embedded in Haskell,
permitting computable predicates,
and Filtrator has a default definition for Monadic Alternators,
the context-sensitivity of CtxGrammar implies
unrestricted filtration of grammars by computable predicates,
which can recognize the larger class of recursively enumerable languages.
Context-sensitivity can also be optical. A Varifocal is an optic
whose shape depends on the foci it builds, as no Bifocal can,
applied in a CtxGrammar by contextually,
or on a MonadicTrans profunctor, by contextuallyT.
A heredoc's lines are its foci,
its tag, its body, & its tag again, delimitBy by the first line
equal to the opening tag, a language which isn't context-free.
>>>:{data Heredoc = Heredoc String [String] deriving (Eq, Show) heredocG :: CtxGrammatical Char p => p Heredoc Heredoc heredocG = lined >~ terminal "<<" >* contextually (delimitBy (==)) lineG where lineG = manyP (notOneOf "\n") *< terminal "\n" lined = iso (\(Heredoc tag body) -> tag : body ++ [tag]) (\case tag : rest -> Heredoc tag (if null rest then [] else init rest) [] -> Heredoc "" []) instance CtxGrammar Char Heredoc where ctxGrammar = heredocG :}
>>>[pr "" | pr <- printG (Heredoc "EOF" ["hi"])] :: [String]["<<EOF\nhi\nEOF\n"]>>>[h | (h, "") <- parseG @Heredoc "<<EOF\nhi\nEOF\n"][Heredoc "EOF" ["hi"]]>>>parsecResult (parsecG @Heredoc "<<EOF\nhi\nEOF\n")Just (Heredoc "EOF" ["hi"])>>>[pr "" | pr <- printG (Heredoc "EOF" ["EOF"])] :: [String][]
Finally, CtxGrammars support failure reporting and backtracking.
This has no effect on printG,
parseG or unparseG;
but it affects parsecG
and unparsecG.
For context, an LL grammar can be (un)parsed by an LL parser.
An LL parser (un)parses from left to right,
and constructs leftmost derivations.
An LL(k) parser can look k tokens ahead.
tParsor is an LL(∞) parser.
tParsector is an LL(1) parser.
The backtracking try combinator
restores full lookahead to Parsector.
Since both Parsor & Parsector are LL parsers they
diverge if the CtxGrammar they're run on is left-recursive.
>>>parsecP (rule "foo" (fail "bar") >|< fail "baz") "abc"ParsecState {parsecLooked = False, parsecOffset = 0, parsecStream = "abc", parsecFailure = ParsecFailure {parsecExpect = TokenClass (OneOf (fromList "")), parsecLabels = [Node {rootLabel = "foo", subForest = [Node {rootLabel = "bar", subForest = []}]},Node {rootLabel = "baz", subForest = []}]}, parsecResult = Nothing}
>>>parsecP (manyP (token 'a') >*< asIn @Char DecimalNumber :: Parsector String (String, Char) (String, Char)) "aaab"ParsecState {parsecLooked = True, parsecOffset = 3, parsecStream = "b", parsecFailure = ParsecFailure {parsecExpect = TokenClass (Alternate (TokenClass (OneOf (fromList "a"))) (TokenClass (NotOneOf (fromList "") (AndAsIn DecimalNumber))) []), parsecLabels = []}, parsecResult = Nothing}
>>>unparsecP (tokens "abc") "abx" ""ParsecState {parsecLooked = True, parsecOffset = 2, parsecStream = "ab", parsecFailure = ParsecFailure {parsecExpect = TokenClass (OneOf (fromList "c")), parsecLabels = []}, parsecResult = Nothing}
class CtxGrammar token a where Source #
A type's context-sensitive grammar, over its tokens; its context-free grammar, by default.
Minimal complete definition
Nothing
Methods
ctxGrammar :: CtxGrammatical token p => p a a Source #
default ctxGrammar :: (Grammar token a, CtxGrammatical token p) => p a a Source #
Instances
| CtxGrammar Char (Bnf (RegEx Char)) Source # | |
Defined in Control.Lens.Grammar.RegEx | |
| CtxGrammar Char (RegEx Char) Source # | |
Defined in Control.Lens.Grammar.RegEx Methods ctxGrammar :: CtxGrammatical Char p => p (RegEx Char) (RegEx Char) Source # | |
type CtxGrammatical token (p :: Type -> Type -> Type) = (Grammatical token p, Filtrator p, forall x. MonadPlus (p x), forall x. MonadFail (p x)) Source #
The Grammatical Filtrators, MonadPluses & MonadFails,
which run CtxGrammars.
Arguments
| :: forall a string token m. (CtxGrammar token a, Cons string string token token, IsList string, Item string ~ token, Categorized token, Alternative m, Monad m, Filterable m) | |
| => a | syntax |
| -> m (string -> string) |
printG generates a printer from a CtxGrammar.
Since both RegGrammars and context-free Grammars are CtxGrammars,
the type system will allow printG to be applied to them.
Running the printer on a syntax value returns a function
that conses tokens at the beginning of an input string,
from right to left.
Arguments
| :: forall a string token m. (CtxGrammar token a, Cons string string token token, Snoc string string token token, IsList string, Item string ~ token, Categorized token, Alternative m, Monad m, Filterable m) | |
| => string | input |
| -> m (a, string) |
parseG generates a parser from a LL(∞) CtxGrammar.
Since both RegGrammars and context-free Grammars are CtxGrammars,
the type system will allow parseG to be applied to them.
Running the parser on an input string value unconses
tokens from the beginning of an input string from left to right,
returning a syntax value and the remaining output string.
Arguments
| :: forall a string token m. (CtxGrammar token a, Cons string string token token, Snoc string string token token, IsList string, Item string ~ token, Categorized token, Alternative m, Monad m, Filterable m) | |
| => a | syntax |
| -> string | input |
| -> m string |
unparseG generates a printer from a LL(∞) CtxGrammar.
Since both RegGrammars and context-free Grammars are CtxGrammars,
the type system will allow unparseG to be applied to them.
Running the printer on a syntax value and an input string
snocs tokens at the end of the string, from left to right,
returning the output string.
Print to a string with a constant time snoc, like a
Data.Sequence.Seq, since a list's snoc is linear,
making printing to a String quadratic.
Arguments
| :: forall a string token. (CtxGrammar token a, Cons string string token token, Snoc string string token token, Item string ~ token, Categorized token) | |
| => string | input |
| -> ParsecState string a |
parsecG generates a parser from a LL(1) CtxGrammar,
with try for restoring full LL(∞) lookahead.
Since both RegGrammars and context-free Grammars are CtxGrammars,
the type system will allow parsecG to be applied to them.
Running the parser on an input string value unconses
tokens from the beginning of an input string from left to right,
returning parsecResult as Nothing on failure or Just
an output syntax value, with parse failure stored in parsecFailure,
and a remaining output parsecStream.
Arguments
| :: forall a string token. (CtxGrammar token a, Cons string string token token, Snoc string string token token, Item string ~ token, Categorized token) | |
| => a | syntax |
| -> string | input |
| -> ParsecState string a |
unparsecG generates a printer from a LL(1) CtxGrammar,
with try for restoring full LL(∞) lookahead.
Since both RegGrammars and context-free Grammars are CtxGrammars,
the type system will allow unparsecG to be applied to them.
Running the printer on a syntax value and an input string
snocs tokens at the end of the string, from left to right,
returning parsecResult as Nothing on failure or Just
the input syntax value, with print success stored in parsecStream.
Print to a string with a constant time snoc, like a
Data.Sequence.Seq, since a list's snoc is linear,
making printing to a String quadratic.
readG :: CtxGrammar Char a => ReadP a Source #
Generate a ReadP backend from a CtxGrammar Char.
monadG :: (CtxGrammar token a, MonadPlus m, MonadFail m, Filterable m, forall x. BackusNaurForm (m x), forall x. Tried (m x), TokenAlgebra token (m token), TerminalSymbol token (m ())) => m a Source #
Generate any parser Monad backend
from a CtxGrammar with monadG.
Let's see how to do this without orphan instances,
using the Megaparsec library.
import qualified Text.Megaparsec as M
import qualified Text.Megaparsec.Char as M
import Control.Lens.Grammar
newtype WrapMega a = WrapMega {unwrapMega :: M.Parsec String String a}
deriving newtype
( Functor, Applicative, Alternative
, Monad, MonadPlus, MonadFail
)
instance TerminalSymbol Char (WrapMega ()) where
terminal str = WrapMega (M.chunk str *> pure ())
instance TokenAlgebra Char (WrapMega Char) where
tokenClass exam = WrapMega $ M.label (show exam) (M.satisfy (tokenClass exam))
instance Tokenized Char (WrapMega Char) where
anyToken = WrapMega M.anySingle
token = WrapMega . M.single
oneOf = WrapMega . M.oneOf
notOneOf = WrapMega . M.noneOf
asIn cat = WrapMega $ M.label ("in category " ++ show cat) (M.satisfy (asIn cat))
notAsIn cat = WrapMega $ M.label ("not in category " ++ show cat) (M.satisfy (notAsIn cat))
instance Ruled (WrapMega a) where
rule lbl (WrapMega p) = WrapMega (M.label lbl p)
instance BackusNaurForm (WrapMega a)
instance Tried (WrapMega a) where
try (WrapMega p) = WrapMega (M.try p)
instance Filterable WrapMega where
catMaybes m = m >>= maybe (fail "unrestricted filtration") pure
megaparsecG :: CtxGrammar Char a => M.Parsec String String a
megaparsecG = unwrapMega (monadG @Char)
Numerals
digit :: (Integral n, Choice p, Tokenized Char (p Char Char)) => n -> p n n Source #
A digit in a base, from 2 to 36, by its value: 0-9, then letters,
printing in lowercase, & parsing either case.
>>>[d | (d, "") <- parseP (digit (16 :: Int) :: Parsor String [] Int Int) "F"][15]
numeral :: (Integral n, Alternator p, Tokenized Char (p Char Char)) => n -> p n n Source #
A natural number in a base, from 2 to 36, by its digits, most significant first, printing without leading zeros, & parsing them too, an improper iso.
>>>($ "") <$> printP (numeral (16 :: Integer) :: Printor String Maybe Integer Integer) 255Just "ff"
Utility
putStringLn :: (IsList string, Item string ~ Char) => string -> IO () Source #
putStringLn is a utility that generalizes putStrLn
to string-like interfaces such as RegEx and Bnf of Chars.
Re-exports
module Control.Lens.Bifocal
module Control.Lens.Cons
module Control.Lens.Diopter
module Control.Lens.Empty
module Control.Lens.Grammar.Machine
module Control.Lens.Grammar.Prec
module Control.Lens.Grammar.Pretty
module Control.Lens.Grammar.RegEx
module Control.Lens.Grammar.Symbol
module Control.Lens.Grammar.Token
module Control.Lens.PartialIso
module Control.Lens.Prismoid
module Control.Lens.Varifocal
module Data.Monoid.Disjunctive
module Data.Profunctor.Distributor
module Data.Profunctor.Filtrator
module Data.Profunctor.Grammar
module Data.Profunctor.Monadic
module Data.Profunctor.Monoidal
module Data.Traversable.Homogeneous
failP :: (Ruled p, DisjunctiveMonoid p) => String -> p Source #
A nonterminal symbol to indicate a failure.
ruleTyped :: (Typeable a, Ruled (p a a)) => p a a -> p a a Source #
A rule for a Haskell type, like a type definition,
named by its Typeable type, so that each type's rule is its own.
Rule names follow a convention: a module-qualified word, like M.N.x,
names a definition by its qualified name, & may be displayed unqualified,
as x, whenever that's unambiguous. So a type's rule is named by its
fully qualified type, such as
Data.Map.Internal.Map Data.Text.Internal.Text GHC.Types.Int,
displayed as Map Text Int.
class Ruled bnf => BackusNaurForm bnf where Source #
BackusNaurForm grammar combinators formalize traced
rule abstraction and general recursion with ruleRec,
related by this invariant.
prop> rule label bnf = ruleRec label (\_ -> bnf)
The BackusNaurForm interface is reminiscent of
two distinct notions of "trace".
First as a traced Cartesian monoidal category
which models general recursion abstractly,
and second as a trace-like label for rule abstraction.
The category (->) already has a traced (,)-monoidal structure
in the form of unfirst = loop
or equivalently the fixpoint function fix,
determining the default method for a BackusNaurForm,
by which the invariant holds for any Ruled rule.
prop> ruleRec label = rule label . fix
The BackusNaurForm interface permits overloading these methods,
and tracing them with a label.
Both context-free Grammars
& CtxGrammars
support the BackusNaurForm interface.
See Breitner, Showcasing Applicative,
for the original interface.
Minimal complete definition
Nothing
Instances
| (Ord rule, NonTerminalSymbol rule) => BackusNaurForm (Bnf rule) Source # | |
| BackusNaurForm (ReadP a) Source # | |
| BackusNaurForm (ReadPrec a) Source # | |
| BackusNaurForm (p a b) => BackusNaurForm (Precedence p a b) Source # | |
Defined in Control.Lens.Grammar.Prec Methods ruleRec :: String -> (Precedence p a b -> Precedence p a b) -> Precedence p a b Source # | |
| BackusNaurForm k => BackusNaurForm (Grammor k a b) Source # | |
| BackusNaurForm (Parsector s a b) Source # | |
| BackusNaurForm (Prettor w f a b) Source # | |
| BackusNaurForm (Parsor s m a b) Source # | |
| BackusNaurForm (Printor s m a b) Source # | |
| (forall x. BackusNaurForm (f x)) => BackusNaurForm (Joker f a b) Source # | |
Ruled grammar combinators formalize
rule abstraction, labeling a subgrammar,
which a BackusNaurForm names as a nonterminal,
& a parser may report on failure.
prop> rule _ = id
Minimal complete definition
Nothing
Instances
| (Ord rule, NonTerminalSymbol rule) => Ruled (Bnf rule) Source # | |
| Ruled (ReadP a) Source # | |
| Ruled (ReadPrec a) Source # | |
| Ruled (p a b) => Ruled (Precedence p a b) Source # | |
Defined in Control.Lens.Grammar.Prec Methods rule :: String -> Precedence p a b -> Precedence p a b Source # | |
| Ruled k => Ruled (Grammor k a b) Source # | |
| Ruled (Parsector s a b) Source # | |
| Ruled (Prettor w f a b) Source # | |
| Ruled (Parsor s m a b) Source # | |
| Ruled (Printor s m a b) Source # | |
| (forall x. Ruled (f x)) => Ruled (Joker f a b) Source # | |
Tried grammar combinators mark subgrammars to backtrack
upon failure, by try, in a predictive parser,
like Parsector.
Use try on a subgrammar which isn't LL(1) but still is LL(∞).
try doesn't change the language of a grammar,
so the default, for grammars which can't record it, is
prop> try = id
Minimal complete definition
Nothing
Instances
| Tried rule => Tried (Bnf rule) Source # | |
| Tried (RegEx token) Source # | A |
| Tried (ReadP a) Source # | |
| Tried (ReadPrec a) Source # | |
| Tried (p a b) => Tried (Precedence p a b) Source # | |
Defined in Control.Lens.Grammar.Prec Methods try :: Precedence p a b -> Precedence p a b Source # | |
| Tried k => Tried (Grammor k a b) Source # | |
| Tried (Parsector s a b) Source # | |
| Tried (Prettor w f a b) Source # | |
| Tried (Parsor s m a b) Source # | |
| Tried (Printor s m a b) Source # | |
| (forall x. Tried (f x)) => Tried (Joker f a b) Source # | |
class Applicative f => Alternative (f :: Type -> Type) where #
A monoid on applicative functors.
If defined, some and many should be the least solutions
of the equations:
Examples
>>>Nothing <|> Just 42Just 42
>>>[1, 2] <|> [3, 4][1,2,3,4]
>>>empty <|> print (2^15)32768
Methods
The identity of <|>
empty <|> a == a a <|> empty == a
(<|>) :: f a -> f a -> f a infixl 3 #
An associative binary operation
One or more.
Examples
>>>some (putStr "la")lalalalalalalalala... * goes on forever *
>>>some Nothingnothing
>>>take 5 <$> some (Just 1)* hangs forever *
Note that this function can be used with Parsers based on
Applicatives. In that case some parser will attempt to
parse parser one or more times until it fails.
Zero or more.
Examples
>>>many (putStr "la")lalalalalalalalala... * goes on forever *
>>>many NothingJust []
>>>take 5 <$> many (Just 1)* hangs forever *
Note that this function can be used with Parsers based on
Applicatives. In that case many parser will attempt to
parse parser zero or more times until it fails.
Instances
class (Alternative m, Monad m) => MonadPlus (m :: Type -> Type) where #
Monads that also support choice and failure.
Minimal complete definition
Nothing
Methods
The identity of mplus. It should also satisfy the equations
mzero >>= f = mzero v >> mzero = mzero
The default definition is
mzero = empty
An associative operation. The default definition is
mplus = (<|>)
Instances
class Monad m => MonadFail (m :: Type -> Type) where #
When a value is bound in do-notation, the pattern on the left
hand side of <- might not match. In this case, this class
provides a function to recover.
A Monad without a MonadFail instance may only be used in conjunction
with pattern that always match, such as newtypes, tuples, data types with
only a single data constructor, and irrefutable patterns (~pat).
Instances of MonadFail should satisfy the following law: fail s should
be a left zero for >>=,
fail s >>= f = fail s
If your Monad is also MonadPlus, a popular definition is
fail _ = mzero
fail s should be an action that runs in the monad itself, not an
exception (except in instances of MonadIO). In particular,
fail should not be implemented in terms of error.
Since: base-4.9.0.0
Instances
class Functor f => Filterable (f :: Type -> Type) where #
Like Functor, but you can remove elements instead of updating them.
Formally, the class Filterable represents a functor from Kleisli Maybe to Hask.
A definition of mapMaybe must satisfy the following laws:
Methods
mapMaybe :: (a -> Maybe b) -> f a -> f b #
Like mapMaybe.
catMaybes :: f (Maybe a) -> f a #