diff --git a/.hlint.yaml b/.hlint.yaml index c30aa497..85128933 100644 --- a/.hlint.yaml +++ b/.hlint.yaml @@ -97,3 +97,5 @@ # Printor matches its pairs strictly, for speed. - ignore: {name: "Use first", within: Data.Profunctor.Grammar} - ignore: {name: "Use snd", within: Data.Profunctor.Grammar} +- ignore: {name: "Use first", within: Data.Profunctor.Grammar.Printor} +- ignore: {name: "Use snd", within: Data.Profunctor.Grammar.Printor} diff --git a/README.md b/README.md index a80c5892..7e7382fe 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ With Stack: ```sh stack build --test --bench -DISTRIBUTORS_RUN_DOCTESTS=1 stack test +stack test ``` With Cabal: diff --git a/distributors-grammar/CHANGELOG.md b/distributors-grammar/CHANGELOG.md index 77257c43..961a1222 100644 --- a/distributors-grammar/CHANGELOG.md +++ b/distributors-grammar/CHANGELOG.md @@ -2,6 +2,115 @@ ## Unreleased +- `Control.Lens.Grammar.Pretty`: grammars laid out by Wadler-Leijen + layout combinators, `Lined`'s `hardlineP` & `LaidOut`'s `flatAltP`, + `nestP`, `groupP` & `alignP`, with `lineP`, `lineP'` & `softlineP`. + `PrettyGrammar` types, run by `Grammatical` interpreters which are + `Lined` & `LaidOut`, print, by + `Prettor`, a printer into a `Monoid`, a @prettyprinter@ `Doc`, by + `prettyG`, laid out by `layoutG` in a `LayoutStyle`; & parse, by + `Parsor`, every layout they print, with any indentation, which `RegEx`, + `Bnf` & `Grammor` describe. `Grammor` is `IsString`. +- `ruleTyped`, in `Control.Lens.Grammar.BackusNaur`, a `rule` named by its + `Typeable` type, module-qualified, which was `distributors-json`'s + `jsonTyped`. Base types' grammars name their rules by it. +- Regular expressions escape control characters by hexadecimal codes, + @\\x{e}@, rather than by names, which were ambiguous, @\\SO@ & @H@ + reading as @\\SOH@; codes parse in either case. +- `digit` & `numeral`, digits & natural numbers in a base, by their values, + rather than by `show` & `read`, which `Natural` & `Integer` grammars, + quantifiers' counts, & the examples use. +- `regexGrammar` & `regbnfGrammar` are removed: they're the `Grammar Char` + instances of `RegEx Char` & `Bnf (RegEx Char)`, by `grammar`. The classes + `RegGrammar`, `Grammar` & `CtxGrammar`, & the base types' instances, are + in `Control.Lens.Grammar.Class`, which `Control.Lens.Grammar` re-exports, + so that `Control.Lens.Grammar.RegEx` defines its own instances; their + tutorials are `Control.Lens.Grammar`'s module documentation. +- `RegEx` has counts, a `KleeneTimes` constructor, normalized by `quantK`, + rendered @x{n}@, @x{n,}@ & @x{n,m}@, & parsed so, normalizing; `Grammor`s + keep counts, so `exactly`, `atLeast`, `atMost` & `inRange` render by them. + Machines & analyses unroll them. +- `RegEx` records `try`, by a `Backtracking` constructor, whose language + is its own, rendered @\\t{…}@; `ll1Conflicts` skips conflicts resolved + by `try`. `Tried` is part of `RegGrammatical`. +- Character classes render runs of three or more plain characters as + ranges, @[a-z]@, & parse ranges; a dash in a class is escaped, @\\-@. +- `Control.Lens.Grammar.Prec`: Haskell types' grammars, by precedence, + equivalent to their stock `Read` & `Show` instances. `PrecGrammar` types, + run by `PrecGrammatical` interpreters, with `precP`, `precStep`, `precReset` & + `precWith`, as `ReadPrec`'s `prec`, `step` & `reset`, `precParens`, as + `GHC.Read.parens` & `showParen`, & `precList`, as `GHC.Read.list` & + `showList`, & `precListGrammar`, as `readListPrec` & `showList`; `Precedence`, an interpreter over any + `Grammatical` one, run by `precG`, `readsPrecG` & `showsPrecG`. Instances for + lists, & `String`s, as string literals, with `showLitString`'s & `read`'s + escapes, empty escapes & gaps, maximally munched, as `read`'s lexer does; + `Char`, with `showLitChar`'s escapes & `read`'s named, control & numeric + escapes, up to `maxBound`; `Natural`, `Integer`, & sized `Int`s & `Word`s, + which wrap out of range as `read` does, in decimal, & binary, octal & + hexadecimal; & `Double`s & `Float`s, by `floatToDigits` & `fromRational`; + negative numbers parenthesized above precedence 6, as `showsPrec` does, & + read bare at any, as `read` does. Property tested against `showsPrec` & + `readsPrec`, at each precedence. Haskell types have no `Grammar` instances. +- `PrecGrammar` defaults, by `GHC.Generics`, to derived `Read` & `Show` + instances' syntax: nullary & prefix constructors, at precedence 10, + records, read bare at 11 & shown within parentheses there, with operator + fields, infix constructors, symbolic & backquoted, at their fixities, & + symbolic constructors in prefix. Instances for `Bool`, `Ordering`, `Maybe` + & `Either`, by it, & for `()` & tuples. `NotFollowedBy`, negative lookahead + by `notFollowedBy` a `RegEx`, which `PrecGrammatical` requires, & + `eof`, `munch`, `munch1` & `skipSpaces`, as `ReadP`'s, + so that identifiers, symbols & numbers are munched maximally, & + whitespace skipped greedily, as `read`'s lexer does. +- `Predicate`s are `Tokenized` & `TokenAlgebra`s, as predicates are; & + `ReadPrec` runs grammars as `ReadP` does, `Tokenized`, a `TokenAlgebra`, + `TerminalSymbol`, `Ruled`, `BackusNaurForm` & `Tried`. +- `Control.Lens.Grammar.Analysis`, static analyses of `RegEx`tended + t'Bnf's over any token: `foldRegEx`, the homomorphism out of `RegEx`, the + free `KleeneStarAlgebra` of token classes & nonterminals, & `fixRules`, + least fixpoints over a t'Bnf''s `bnfRules`; `Leading`, nullability & + leading atoms, by which `firsts` & `leftRecursive`; `Guard`, a + `BooleanAlgebra` of one-token lookahead, by which `follows`; & + `ll1Conflicts`, built of them, testing each example's @LL(1)@ flag. + The lambda example's abstraction rule is renamed, as it shared its name + with the grammar's, merging into a left-recursive rule. +- `RegString` & `RegBnf` are removed: `RegEx Char` & `Bnf (RegEx Char)` + are them, `IsString` & `IsList` by the string syntax of regular + expressions, of `regexGrammar` & `regbnfGrammar`, & their `Grammar Char` + instances, while their `Show` & `Read` are stock; render them by + `toList` or `putStringLn`. `regstringG` is renamed `regexG`, & `regexG` + & `regbnfG` generate over any token, `RegEx token` & `Bnf (RegEx token)`. +- Modules, without orphans: `Control.Lens.Grammar.BackusNaur` has `Ruled`, + `BackusNaurForm` & `Tried`, & the `RegGrammatical`, `Grammatical` & + `CtxGrammatical` constraints, `Lexical` being folded into + `RegGrammatical`, of which it was always a part; `Control.Lens.Grammar.RegEx` + has `RegEx` & `Bnf`, with `liftBnf0`, `liftBnf1`, `liftBnf2` & `diffB`, + & `regexGrammar` & `regbnfGrammar`; & `Printor` has its own module, + `Data.Profunctor.Grammar.Printor`, re-exported by + `Data.Profunctor.Grammar`. `Control.Lens.Grammar` re-exports them all. +- `Control.Monad.Fail.Try`, with `MonadTry` & `MonadicTry`, is removed. + `Control.Lens.Grammar.BackusNaur` has, instead: + - `Ruled`, with `rule`, split from `BackusNaurForm`, now its subclass, + whose `ruleRec` defaults to @ruleRec label = rule label . fix@, so + that its invariant holds for any `rule`; + - `failP`, renamed from `failBnf`, for any `Ruled` `DisjunctiveMonoid`; + - `Tried`, with `try`, for any grammar, not only monads, defaulting to + `id`, as `try` doesn't change a language. `Parsector` backtracks by + it, a t'Bnf' tries its start, & a `RegEx` doesn't record it, for now. + + `Grammatical` requires `Tried`, so context-free grammars can `try`, & + `CtxGrammatical` requires `MonadPlus` & `MonadFail` of `Filtrator`s. + `Control.Lens.Grammar` still re-exports `Alternative`, `MonadPlus`, + `MonadFail` & `Filterable`. +- `RegGrammar`, `Grammar` & `CtxGrammar` are classes, of a type's + grammar over a token, by `regGrammar`, `grammar` & `ctxGrammar`, each + defaulting to the more restrictive, & `RegGrammatical`, `Grammatical` + & `CtxGrammatical` are the constraints on profunctors which run them, + typing grammar values, as @Grammatical Char p => p a a@. Runners take + the grammar from the class: parsers & printers by inference, as + @parseG \@Arith@, & generators by a required type argument, as + @regbnfG Arith@, or @regbnfG (type SemVer)@ where a constructor shares + the type's name. Run a grammar value by the backends' own runners, + `parseP`, `printP`, `parsecP` & co. - Token classes test their sets of tokens logarithmically, by `Set`, in `tokenClass`'s default & in `oneOf` & `notOneOf` of predicates, rather than linearly by `Foldable`: parsing the JSON example, whose characters diff --git a/distributors-grammar/bench/Main.hs b/distributors-grammar/bench/Main.hs index dd3cc2f2..0c48bd97 100644 --- a/distributors-grammar/bench/Main.hs +++ b/distributors-grammar/bench/Main.hs @@ -14,6 +14,7 @@ import Control.Lens.Comonocle (_BoundedEnum, indexComonocle) import Control.Monad (unless) import Data.List (intercalate) import Test.Tasty.Bench +import qualified GHC.Exts as Exts import Examples.Arithmetic import Examples.Expression @@ -36,7 +37,8 @@ main = do defaultMain groups -- | A named workload: a grammar, an input string & its syntax value. -data Workload = forall a. Eq a => Workload String (CtxGrammar Char a) String a +data Workload = forall a. Eq a => + Workload String (forall p. CtxGrammatical Char p => p a a) String a -- | Benchmark each workload at each backend which round-trips it. backends :: String -> [Workload] -> IO Benchmark @@ -50,7 +52,7 @@ backends name workloads = bgroup name . concat <$> traverse workload workloads cases :: forall a. Eq a - => String -> CtxGrammar Char a -> String -> a + => String -> (forall p. CtxGrammatical Char p => p a a) -> String -> a -> [(String, Bool, Benchmark)] cases wname g str a = [ ( wname <> "/parse" @@ -72,18 +74,18 @@ cases wname g str a = ] where parser :: String -> Maybe (a, String) - parser = parseG g + parser = parseP (g :: Parsor String Maybe a a) printer :: a -> Maybe (String -> String) - printer = printG g + printer = printP (g :: Printor String Maybe a a) parsector :: String -> ParsecState String a - parsector = parsecG g + parsector = parsecP (g :: Parsector String a a) unparsector :: a -> String -> ParsecState String a - unparsector = unparsecG g + unparsector = unparsecP (g :: Parsector String a a) -digitG :: RegGrammar Char Char +digitG :: RegGrammatical Char p => p Char Char digitG = asIn @Char DecimalNumber -commaG :: RegGrammar Char () +commaG :: RegGrammatical Char p => p () () commaG = terminal "," size :: Int @@ -137,17 +139,17 @@ varifocals = -- | The test examples, scaled up. examples :: [Workload] examples = - [ Workload "arith" arithGrammar arithStr (parsed arithGrammar arithStr) - , Workload "expr" exprGrammar exprStr (parsed exprGrammar exprStr) - , Workload "expr left-assoc" leftGrammar leftStr (parsed leftGrammar leftStr) - , Workload "json" jsonGrammar jsonStr (parsed jsonGrammar jsonStr) - , Workload "sexpr" sexprGrammar sexprStr (parsed sexprGrammar sexprStr) - , Workload "lambda" lambdaGrammar lambdaStr (parsed lambdaGrammar lambdaStr) - , Workload "semver" semverCtxGrammar semverStr (parsed semverCtxGrammar semverStr) + [ Workload @Arith "arith" arithGrammar arithStr (parsed arithGrammar arithStr) + , Workload @Expr "expr" exprGrammar exprStr (parsed exprGrammar exprStr) + , Workload @Expr "expr left-assoc" leftGrammar leftStr (parsed leftGrammar leftStr) + , Workload @Json "json" jsonGrammar jsonStr (parsed jsonGrammar jsonStr) + , Workload @SExpr "sexpr" sexprGrammar sexprStr (parsed sexprGrammar sexprStr) + , Workload @Lambda "lambda" lambdaGrammar lambdaStr (parsed lambdaGrammar lambdaStr) + , Workload @SemVer "semver" semverCtxGrammar semverStr (parsed semverCtxGrammar semverStr) ] where - parsed :: CtxGrammar Char a -> String -> a - parsed g s = case parseG g s of + parsed :: forall a. (forall p. CtxGrammatical Char p => p a a) -> String -> a + parsed g s = case parseP (g :: Parsor String Maybe a a) s of Just (a, "") -> a _ -> error ("bench input doesn't parse: " <> take 40 s) terms n ops = concat @@ -165,9 +167,10 @@ examples = -- | Building static grammars, as regular expressions & Backus-Naur forms. statics :: Benchmark statics = bgroup "static" - [ bench "regstring sepBy" $ whnf (length . show . regstringG) (sepBy commaG several digitG) - , bench "regbnf json" $ whnf (length . show . regbnfG) jsonGrammar - , bench "regbnf expr" $ whnf (length . show . regbnfG) exprGrammar + [ bench "regstring sepBy" $ whnf (\g -> length (Exts.toList (runGrammor g :: RegEx Char))) + (sepBy commaG several digitG) + , bench "regbnf json" $ whnf (\() -> length (Exts.toList (regbnfG @Char Json))) () + , bench "regbnf expr" $ whnf (\() -> length (Exts.toList (regbnfG @Char Expr))) () ] -- | Optics as lenses, at functions. diff --git a/distributors-grammar/distributors-grammar.cabal b/distributors-grammar/distributors-grammar.cabal index cae63344..183453f5 100644 --- a/distributors-grammar/distributors-grammar.cabal +++ b/distributors-grammar/distributors-grammar.cabal @@ -29,14 +29,18 @@ source-repository head library exposed-modules: Control.Lens.Grammar + Control.Lens.Grammar.Analysis Control.Lens.Grammar.BackusNaur + Control.Lens.Grammar.Class Control.Lens.Grammar.Machine + Control.Lens.Grammar.Prec + Control.Lens.Grammar.Pretty Control.Lens.Grammar.RegEx Control.Lens.Grammar.Symbol Control.Lens.Grammar.Token - Control.Monad.Fail.Try Data.Profunctor.Grammar Data.Profunctor.Grammar.Parsector + Data.Profunctor.Grammar.Printor other-modules: Paths_distributors_grammar autogen-modules: @@ -92,6 +96,7 @@ library , lens >=5.0 && <6 , monad-loops >=0.4.3 && <1 , mtl >=2.2 && <3 + , prettyprinter >=1.7 && <2 , profunctors >=5.6 && <6 , random >=1.2 && <2 , witherable >=0.4 && <1 @@ -157,6 +162,7 @@ test-suite doctests , lens >=5.0 && <6 , monad-loops >=0.4.3 && <1 , mtl >=2.2 && <3 + , prettyprinter >=1.7 && <2 , profunctors >=5.6 && <6 , random >=1.2 && <2 , witherable >=0.4 && <1 @@ -174,9 +180,12 @@ test-suite test Examples.Lambda Examples.LenVec Examples.RegString + Examples.Rho Examples.SemVer Examples.SExpr + Properties.Base Properties.Kleene + Properties.Pretty Properties.Varifocal Paths_distributors_grammar autogen-modules: @@ -230,11 +239,13 @@ test-suite test , containers >=0.6 && <1 , distributors , distributors-grammar + , free >=5.1 && <6 , hspec >=2.7 && <3 , lens >=5.0 && <6 , megaparsec >=9.0 && <10 , monad-loops >=0.4.3 && <1 , mtl >=2.2 && <3 + , prettyprinter >=1.7 && <2 , profunctors >=5.6 && <6 , random >=1.2 && <2 , witherable >=0.4 && <1 @@ -304,6 +315,7 @@ benchmark core , lens >=5.0 && <6 , monad-loops >=0.4.3 && <1 , mtl >=2.2 && <3 + , prettyprinter >=1.7 && <2 , profunctors >=5.6 && <6 , random >=1.2 && <2 , tasty-bench >=0.3 && <1 diff --git a/distributors-grammar/package.yaml b/distributors-grammar/package.yaml index c29da918..58d86893 100644 --- a/distributors-grammar/package.yaml +++ b/distributors-grammar/package.yaml @@ -27,6 +27,7 @@ dependencies: - MemoTrie >= 0.6 && < 1 - monad-loops >= 0.4.3 && < 1 - mtl >= 2.2 && < 3 +- prettyprinter >= 1.7 && < 2 - profunctors >= 5.6 && < 6 - QuickCheck >= 2.14 && < 3 - random >= 1.2 && < 2 @@ -99,6 +100,7 @@ tests: dependencies: - distributors - distributors-grammar + - free >= 5.1 && < 6 - hspec >= 2.7 && < 3 - megaparsec >= 9.0 && < 10 - QuickCheck >= 2.14 && < 3 diff --git a/distributors-grammar/src/Control/Lens/Grammar.hs b/distributors-grammar/src/Control/Lens/Grammar.hs index ae91a62b..71dc265f 100644 --- a/distributors-grammar/src/Control/Lens/Grammar.hs +++ b/distributors-grammar/src/Control/Lens/Grammar.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE ExplicitNamespaces, RequiredTypeArguments #-} {- | Module : Control.Lens.Grammar Description : grammar hierarchy @@ -13,20 +14,21 @@ See Chomsky, [On Certain Formal Properties of Grammars] module Control.Lens.Grammar ( -- * Regular grammar - RegGrammar - , Lexical - , RegString (..) - , regstringG - , regexGrammar + -- $regGrammar + RegGrammar (..) + , RegGrammatical + , regexG -- * Context-free grammar - , Grammar - , RegBnf (..) + -- $grammar + , Grammar (..) + , Grammatical , regbnfG - , regbnfGrammar , applicativeG , transducerG -- * Context-sensitive grammar - , CtxGrammar + -- $ctxGrammar + , CtxGrammar (..) + , CtxGrammatical , printG , parseG , unparseG @@ -34,6 +36,9 @@ module Control.Lens.Grammar , unparsecG , readG , monadG + -- * Numerals + , digit + , numeral -- * Utility , putStringLn -- * Re-exports @@ -44,13 +49,12 @@ import Control.Applicative import Control.Lens import Control.Lens.PartialIso import Control.Lens.Grammar.BackusNaur +import Control.Lens.Grammar.Class import Control.Lens.Grammar.Machine import Control.Lens.Grammar.RegEx import Control.Lens.Grammar.Token import Control.Lens.Grammar.Symbol import Data.Bifunctor.Joker -import Data.Maybe hiding (mapMaybe) -import Data.Monoid import Data.Monoid.Disjunctive import Data.Profunctor.Distributor import Data.Profunctor.Monoidal.Cocartesian @@ -59,17 +63,20 @@ import Data.Profunctor.Monadic as X import Data.Profunctor.Monoidal import Data.Profunctor.Grammar import Data.Profunctor.Grammar.Parsector -import Data.String import GHC.Exts import Prelude hiding (filter) -import Text.ParserCombinators.ReadP (ReadP, readP_to_S) +import Text.ParserCombinators.ReadP (ReadP) import Witherable -- Re-exports import Control.Lens.Cons as X import Control.Lens.Empty as X -import Control.Lens.Grammar.BackusNaur as X +import Control.Lens.Grammar.BackusNaur as X hiding + (RegGrammatical, Grammatical, CtxGrammatical) +import Control.Lens.Grammar.Analysis as X import Control.Lens.Grammar.Machine as X +import Control.Lens.Grammar.Prec as X +import Control.Lens.Grammar.Pretty as X import Control.Lens.Grammar.RegEx as X import Control.Lens.Grammar.Symbol as X import Control.Lens.Grammar.Token as X @@ -78,7 +85,9 @@ import Control.Lens.Bifocal as X import Control.Lens.Diopter as X import Control.Lens.Prismoid as X import Control.Lens.Varifocal as X -import Control.Monad.Fail.Try as X +import Control.Applicative as X (Alternative (..)) +import Control.Monad as X (MonadPlus (..), MonadFail (..)) +import Witherable as X (Filterable (..)) import Data.Monoid.Disjunctive as X import Data.Profunctor.Distributor as X import Data.Profunctor.Monoidal.Cocartesian as X @@ -90,12 +99,14 @@ import Data.Traversable.Homogeneous as X import Data.Traversable.Homogeneous.Enumerable as X -- $setup +-- >>> :set -XRequiredTypeArguments -XExplicitNamespaces -XTypeApplications -XMonoLocalBinds -- >>> import Data.String (fromString) -- >>> import GHC.Exts (toList) -{- | +{- $regGrammar A regular grammar may be constructed using -`Lexical` and `Alternator` combinators. +`terminal` symbols, `Tokenized` combinators, `tokenClass`es +and `Alternator` combinators. Let's see an example using [semantic versioning](https://semver.org/) syntax. @@ -138,7 +149,7 @@ Now we can build a `RegGrammar` for @SemVer@ using the "idiom" style of `Applicative` parsing with a couple modifications. >>> :{ -semverGrammar :: RegGrammar Char SemVer +semverGrammar :: RegGrammatical Char p => p SemVer SemVer semverGrammar = _SemVer >? numberG >*< terminal "." >* numberG @@ -146,14 +157,22 @@ semverGrammar = _SemVer >*< optionP _Empty (terminal "-" >* identifiersG) >*< optionP _Empty (terminal "+" >* identifiersG) where - numberG = iso show read >~ someP (asIn @Char DecimalNumber) + 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, @@ -187,45 +206,42 @@ because @_SemVer@ is an `Control.Lens.Iso.Iso`. | `optional` | `optionalP` | +------------+---------------+ -You can generate a t'RegString' from a `RegGrammar` -with `Control.Lens.Grammar.regstringG`. +You can generate a regular expression string, a `RegEx`, from a `RegGrammar` +with `Control.Lens.Grammar.regexG`. ->>> putStringLn (regstringG semverGrammar) -\p{Nd}+.\p{Nd}+.\p{Nd}+(-(\p{Ll}|\p{Lu}|\p{Nd}|-)+(.(\p{Ll}|\p{Lu}|\p{Nd}|-)+)*)?(\+(\p{Ll}|\p{Lu}|\p{Nd}|-)+(.(\p{Ll}|\p{Lu}|\p{Nd}|-)+)*)? +>>> 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 semverGrammar "2.1.5-rc.1+build.123"] +>>> [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 `uncons`es tokens left-to-right, from the beginning of a string. Unparsing, on the other hand, `snoc`s tokens left-to-right, to the end of a string. ->>> unparseG semverGrammar (SemVer 1 0 0 ["alpha"] []) "SemVer: " :: Maybe String +>>> unparseG (SemVer 1 0 0 ["alpha"] []) "SemVer: " :: Maybe String Just "SemVer: 1.0.0-alpha" Printing, on the gripping hand, `cons`es tokens right-to-left, to the beginning of a string. ->>> ($ " is the SemVer.") <$> printG semverGrammar (SemVer 1 2 3 [] []) :: Maybe String +>>> ($ " is the SemVer.") <$> printG (SemVer 1 2 3 [] []) :: Maybe String Just "1.2.3 is the SemVer." `Profunctor`ial combinators give us correct-by-construction invertible parsers. -New `RegGrammar` generators can be defined with new instances of `Lexical` `Alternator`s. +New `RegGrammar` generators can be defined with new `RegGrammatical` instances. -} -type RegGrammar token a = forall p. - ( Lexical token p - , Alternator p - ) => p a a -{- | Context-free `Grammar`s add two capabilities to `RegGrammar`s, + +{- $grammar +Context-free `Grammar`s add two capabilities to `RegGrammar`s, coming from the `BackusNaurForm` interface * `rule` abstraction, * and general recursion. -`Control.Lens.Grammar.regexGrammar` and -`Control.Lens.Grammar.regbnfGrammar` are examples of context-free -`Grammar`s. Regular expressions are a form of expression algebra. +The `Grammar`s of `RegEx`pressions & of their t'Bnf's, in +"Control.Lens.Grammar.RegEx", are examples of context-free `Grammar`s. Regular expressions are a form of expression algebra. Let's see a similar but simpler example, the algebra of arithmetic expressions of natural numbers. @@ -256,7 +272,7 @@ and tying the recursive loop with `ruleRec`. >>> :{ -arithGrammar :: Grammar Char Arith +arithGrammar :: Grammatical Char p => p Arith Arith arithGrammar = ruleRec "arith" sumG where sumG arith = rule "sum" $ @@ -266,23 +282,25 @@ arithGrammar = ruleRec "arith" sumG factorG arith = rule "factor" $ numberG >|< terminal "(" >* arith *< terminal ")" numberG = rule "number" $ - _Num . iso show read >? someP (asIn @Char DecimalNumber) + _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 arithGrammar) +>>> putStringLn (regbnfG Arith) {start} = \q{arith} {arith} = \q{sum} {factor} = \q{number}|\(\q{arith}\) -{number} = \p{Nd}+ +{number} = [0-9]+ {product} = \q{factor}(\*\q{factor})* {sum} = \q{product}(\+\q{product})* ->>> [x | (x,"") <- parseG arithGrammar "1+2*3+4"] +>>> [x | (x,"") <- parseG @Arith "1+2*3+4"] [Add (Add (Num 1) (Mul (Num 2) (Num 3))) (Num 4)] ->>> unparseG arithGrammar (Add (Num 1) (Mul (Num 2) (Num 3))) "" :: Maybe String +>>> unparseG (Add (Num 1) (Mul (Num 2) (Num 3))) "" :: Maybe String Just "1+2*3" ->>> do pr <- printG arithGrammar (Num 69); pure (pr "") :: Maybe String +>>> do pr <- printG (Num 69); pure (pr "") :: Maybe String Just "69" Operator tables with precedence, like @buildExpressionParser@'s, @@ -310,39 +328,41 @@ _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 :: Grammar Char Expr +exprGrammar :: Grammatical Char p => p Expr Expr exprGrammar = ruleRec "expr" $ \expr -> let atom = rule "atom" $ nat >|< terminal "(" >* expr *< terminal ")" - nat = rule "nat" $ _Nat . iso show read >? someP (asIn @Char DecimalNumber) + 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 exprGrammar "2^3^2"] +>>> [e | (e,"") <- parseG @Expr "2^3^2"] [Exp (Nat 2) (Exp (Nat 3) (Nat 2))] ->>> [e | (e,"") <- parseG exprGrammar "3-2-1"] +>>> [e | (e,"") <- parseG @Expr "3-2-1"] [Sub (Sub (Nat 3) (Nat 2)) (Nat 1)] ->>> [e | (e,"") <- parseG exprGrammar "2*3+4"] +>>> [e | (e,"") <- parseG @Expr "2*3+4"] [Add (Mul (Nat 2) (Nat 3)) (Nat 4)] ->>> [e | (e,"") <- parseG exprGrammar "2*(3+4)"] +>>> [e | (e,"") <- parseG @Expr "2*(3+4)"] [Mul (Nat 2) (Add (Nat 3) (Nat 4))] ->>> [e | (e,"") <- parseG exprGrammar "3!"] +>>> [e | (e,"") <- parseG @Expr "3!"] [Fac (Nat 3)] ->>> [e | (e,"") <- parseG exprGrammar "2^3!"] +>>> [e | (e,"") <- parseG @Expr "2^3!"] [Exp (Nat 2) (Fac (Nat 3))] Being bidirectional, the same grammar prints: ->>> unparseG exprGrammar (Exp (Nat 2) (Exp (Nat 3) (Nat 2))) "" :: Maybe String +>>> unparseG (Exp (Nat 2) (Exp (Nat 3) (Nat 2))) "" :: Maybe String Just "2^3^2" ->>> unparseG exprGrammar (Exp (Nat 2) (Fac (Nat 3))) "" :: Maybe String +>>> unparseG (Exp (Nat 2) (Fac (Nat 3))) "" :: Maybe String Just "2^3!" If all `rule`s are non-recursive, then a `Grammar` @@ -353,13 +373,10 @@ But it's recommended to use `Grammar`s for `rule` abstraction and generator support for `ruleRec`. -} -type Grammar token a = forall p. - ( Lexical token p - , Alternator p - , forall x y. BackusNaurForm (p x y) - ) => p a a -{- | For context-sensitivity, + +{- $ctxGrammar +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. @@ -378,14 +395,15 @@ _LenVec = iso (\LenVec {..} -> (length, vector)) (\(length, vector) -> LenVec {. >>> :set -XQualifiedDo >>> import qualified Data.Profunctor.Monadic.Do as P >>> :{ -lenvecGrammar :: CtxGrammar Char LenVec +lenvecGrammar :: CtxGrammatical Char p => p LenVec LenVec lenvecGrammar = _LenVec >? P.do let - numberG = iso show read >~ someP (asIn @Char DecimalNumber) + 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 @@ -403,17 +421,17 @@ 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 t'RegBnf' from a `CtxGrammar` since the `rule`s +We can't generate a t'Bnf' from a `CtxGrammar` since the `rule`s aren't static, but dynamic and contextual. We can generate parsers and printers as expected. ->>> [vec | (vec, "") <- parseG lenvecGrammar "3;1,2,3"] :: [LenVec] +>>> [vec | (vec, "") <- parseG "3;1,2,3"] :: [LenVec] [LenVec {length = 3, vector = [1,2,3]}] ->>> [vec | (vec, "") <- parseG lenvecGrammar "0;1,2,3"] :: [LenVec] +>>> [vec | (vec, "") <- parseG "0;1,2,3"] :: [LenVec] [] ->>> [pr "" | pr <- printG lenvecGrammar (LenVec 2 [6,7])] :: [String] +>>> [pr "" | pr <- printG (LenVec 2 [6,7])] :: [String] ["2;6,7"] ->>> [pr "" | pr <- printG lenvecGrammar (LenVec 200 [100])] :: [String] +>>> [pr "" | pr <- printG (LenVec 200 [100])] :: [String] [] In addition to context-sensitivity via `Monadic` combinators, @@ -423,12 +441,12 @@ And the `satisfied` pattern is used together with the `Choice` & `Data.Profunctor.Cochoice` applicator `>?<` for unrestricted filtration. >>> :{ -palindromeG :: CtxGrammar Char String +palindromeG :: CtxGrammatical Char p => p String String palindromeG = rule "palindrome" $ satisfied (\wrd -> reverse wrd == wrd) >?< manyP (anyToken @Char) :} ->>> [pal | word <- ["racecar", "word"], (pal, "") <- parseG palindromeG word] +>>> [pal | word <- ["racecar", "word"], (pal, "") <- parseP (palindromeG :: Parsor String [] String String) word] ["racecar"] Since `CtxGrammar`s are embedded in Haskell, @@ -448,7 +466,7 @@ equal to the opening tag, a language which isn't context-free. >>> :{ data Heredoc = Heredoc String [String] deriving (Eq, Show) -heredocG :: CtxGrammar Char Heredoc +heredocG :: CtxGrammatical Char p => p Heredoc Heredoc heredocG = lined >~ terminal "<<" >* contextually (delimitBy (==)) lineG where lineG = manyP (notOneOf "\n") *< terminal "\n" @@ -457,15 +475,16 @@ heredocG = lined >~ terminal "<<" >* contextually (delimitBy (==)) lineG (\case tag : rest -> Heredoc tag (if null rest then [] else init rest) [] -> Heredoc "" []) +instance CtxGrammar Char Heredoc where ctxGrammar = heredocG :} ->>> [pr "" | pr <- printG heredocG (Heredoc "EOF" ["hi"])] :: [String] +>>> [pr "" | pr <- printG (Heredoc "EOF" ["hi"])] :: [String] ["<>> [h | (h, "") <- parseG heredocG "<>> [h | (h, "") <- parseG @Heredoc "<>> parsecResult (parsecG heredocG "<>> parsecResult (parsecG @Heredoc "<>> [pr "" | pr <- printG heredocG (Heredoc "EOF" ["EOF"])] :: [String] +>>> [pr "" | pr <- printG (Heredoc "EOF" ["EOF"])] :: [String] [] Finally, `CtxGrammar`s support failure reporting and backtracking. @@ -484,432 +503,43 @@ restores full lookahead to t'Parsector'. Since both t'Parsor' & t'Parsector' are @LL@ parsers they diverge if the `CtxGrammar` they're run on is left-recursive. ->>> parsecG (rule "foo" (fail "bar") >|< fail "baz") "abc" +>>> 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} ->>> parsecG (manyP (token 'a') >*< asIn @Char DecimalNumber) "aaab" +>>> 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} ->>> unparsecG (tokens "abc") "abx" "" +>>> unparsecP (tokens "abc") "abx" "" ParsecState {parsecLooked = True, parsecOffset = 2, parsecStream = "ab", parsecFailure = ParsecFailure {parsecExpect = TokenClass (OneOf (fromList "c")), parsecLabels = []}, parsecResult = Nothing} -} -type CtxGrammar token a = forall p. - ( Lexical token p - , Alternator p - , Filtrator p - , MonadicTry p - ) => p a a -{- | -`Lexical` combinators include `terminal` symbols, -`Tokenized` combinators and `tokenClass`es. --} -type Lexical token p = - ( forall x y. (x ~ (), y ~ ()) => TerminalSymbol token (p x y) - , forall x y. (x ~ token, y ~ token) => TokenAlgebra token (p x y) - ) :: Constraint - -{- | t'RegString's are an embedded domain specific language -of regular expression strings. - -Since they are strings, they have a string-like interface. - ->>> let rex = fromString "ab|c" :: RegString ->>> putStringLn rex -ab|c ->>> rex -"ab|c" - -t'RegString's can be generated from `RegGrammar`s -with `Control.Lens.Grammar.regstringG`. - ->>> regstringG (terminal "a" >* terminal "b" >|< terminal "c") -"ab|c" - -t'RegString's are actually stored as an algebraic datatype, `RegEx`. - ->>> runRegString rex -RegExam (Alternate (Sequence (RegExam (OneOf (fromList "a"))) (RegExam (OneOf (fromList "b"))) []) (RegExam (OneOf (fromList "c"))) []) - -t'RegString's are similar to regular expression strings in many other -programming languages. We can use them to see if a word and pattern -are `Matching`. - ->>> "ab" =~ rex -True ->>> "c" =~ rex -True ->>> "xyz" =~ rex -False - -Like `RegGrammar`s, t'RegString's can use all the `Lexical` combinators. -Unlike `RegGrammar`s, instead of using `Monoidal` and `Alternator` combinators, -t'RegString's use `Monoid` and `KleeneStarAlgebra` combinators. - ->>> terminal "a" <> terminal "b" >|< terminal "c" :: RegString -"ab|c" ->>> mempty :: RegString -"" - -Since t'RegString's are a `KleeneStarAlgebra`, -they support Kleene quantifiers. - ->>> starK rex -"(ab|c)*" ->>> plusK rex -"(ab|c)+" ->>> optK rex -"(ab|c)?" - -Like other regular expression languages, t'RegString's support -character classes. - ->>> oneOf "abc" :: RegString -"[abc]" ->>> notOneOf "abc" :: RegString -"[^abc]" - -The character classes are used for failure, matching no character or string, -as well as the wildcard, matching any single character. - ->>> falseP :: RegString -"[]" ->>> anyToken :: RegString -"[^]" - -Additional forms of character classes test for a character's `GeneralCategory`. - ->>> asIn LowercaseLetter :: RegString -"\\p{Ll}" ->>> notAsIn Control :: RegString -"\\P{Cc}" - -`KleeneStarAlgebra`s support alternation `>|<`, -and the `Tokenized` combinators are all negatable. -However, we'd like to be able to take the -intersection of character classes as well. -t'RegString's can combine characters' `tokenClass`es -using `BooleanAlgebra` combinators. - ->>> tokenClass (notOneOf "abc" >&< notOneOf "xyz") :: RegString -"[^abcxyz]" ->>> tokenClass (oneOf "abcxyz" >&< notOneOf "xyz") :: RegString -"[abc]" ->>> tokenClass (notOneOf "#$%" >&< notAsIn Control) :: RegString -"[^#$%\\P{Cc}]" ->>> tokenClass (allP notAsIn [MathSymbol, Control]) :: RegString -"\\P{Sm|Cc}" ->>> tokenClass (notP (oneOf "xyz")) :: RegString -"[^xyz]" - -Ill-formed t'RegString's normalize to failure. - ->>> fromString ")(" :: RegString -"[]" --} -newtype RegString = RegString {runRegString :: RegEx Char} - deriving newtype - ( Eq, Ord - , Semigroup, Monoid, DisjunctiveMonoid, KleeneStarAlgebra - , Tokenized Char, TokenAlgebra Char - , TerminalSymbol Char, NonTerminalSymbol - , Matching String - ) -{- | t'RegBnf's are an embedded domain specific language -of Backus-Naur forms extended by regular expression strings. -A t'RegBnf' consists of a distinguished t'RegString' "start" rule, -and a set of named t'RegString' `rule`s. - ->>> putStringLn (rule "baz" (terminal "foo" >|< terminal "bar") :: RegBnf) -{start} = \q{baz} -{baz} = foo|bar - -Like t'RegString's they have a string-like interface. - ->>> let bnf = fromString "{start} = foo|bar" :: RegBnf ->>> putStringLn bnf -{start} = foo|bar ->>> bnf -"{start} = foo|bar" ->>> :type toList bnf -toList bnf :: [Char] - -t'RegBnf's can be generated from context-free `Grammar`s -with `Control.Lens.Grammar.regbnfG`. - ->>> :type regbnfG regbnfGrammar -regbnfG regbnfGrammar :: RegBnf - -Like t'RegString's, t'RegBnf's can be constructed using -`Lexical`, `Monoid` and `KleeneStarAlgebra` combinators. -But they also support `BackusNaurForm` `rule`s and `ruleRec`s. - ->>> putStringLn (rule "baz" (bnf >|< terminal "baz")) -{start} = \q{baz} -{baz} = foo|bar|baz ->>> putStringLn (ruleRec "∞-loop" (\x -> x) :: RegBnf) -{start} = \q{∞-loop} -{∞-loop} = \q{∞-loop} --} -newtype RegBnf = RegBnf {runRegBnf :: Bnf RegString} - deriving newtype - ( Eq, Ord - , Semigroup, Monoid, DisjunctiveMonoid, KleeneStarAlgebra - , Tokenized Char, TokenAlgebra Char - , TerminalSymbol Char, NonTerminalSymbol - , BackusNaurForm - ) -instance Matching String RegBnf where - word =~ pattern = word =~ liftBnf1 runRegString (runRegBnf pattern) - -makeNestedPrisms ''Bnf -makeNestedPrisms ''RegEx -makeNestedPrisms ''TokenExam -makeNestedPrisms ''CategoryTest -makeNestedPrisms ''GeneralCategory -makeNestedPrisms ''RegString -makeNestedPrisms ''RegBnf - -{- | `regexGrammar` is a context-free `Grammar` for t'RegString's. -It can't be a `RegGrammar`, since t'RegString's include parenthesization. -But [balanceBy parentheses](https://en.wikipedia.org/wiki/Dyck_language) -are a context-free language. - ->>> putStringLn (regbnfG regexGrammar) -{start} = \q{regex} -{alternate} = \q{sequence}(\|\q{sequence})* -{atom} = \\q\q{nonterminal}|\q{class}|\(\q{regex}\) -{category} = Ll|Lu|Lt|Lm|Lo|Mn|Mc|Me|Nd|Nl|No|Pc|Pd|Ps|Pe|Pi|Pf|Po|Sm|Sc|Sk|So|Zs|Zl|Zp|Cc|Cf|Cs|Co|Cn -{char} = [^\(\)\*\+\?\[\\\]\^\{\|\}\P{Cc}]|\\\q{char-escaped} -{char-control} = NUL|SOH|STX|ETX|EOT|ENQ|ACK|BEL|BS|HT|LF|VT|FF|CR|SO|SI|DLE|DC1|DC2|DC3|DC4|NAK|SYN|ETB|CAN|EM|SUB|ESC|FS|GS|RS|US|DEL|PAD|HOP|BPH|NBH|IND|NEL|SSA|ESA|HTS|HTJ|VTS|PLD|PLU|RI|SS2|SS3|DCS|PU1|PU2|STS|CCH|MW|SPA|EPA|SOS|SGCI|SCI|CSI|ST|OSC|PM|APC -{char-escaped} = [\(\)\*\+\?\[\\\]\^\{\|\}]|\q{char-control} -{class} = \q{class-one-of}|\q{class-not-one-of} -{class-category} = \\p\{\q{category}\}|\\P\{\q{category}(\|\q{category})*\} -{class-not-one-of} = \q{class-category}|\[\^\q{char}*\q{class-category}?\] -{class-one-of} = \q{char}|\[\q{char}*\] -{expression} = \q{atom}\?|\q{atom}\*|\q{atom}\+|\q{atom} -{nonterminal} = \{\q{char}*\} -{regex} = \q{alternate} -{sequence} = \q{expression}* --} -regexGrammar :: Grammar Char RegString -regexGrammar = _RegString >~ ruleRec "regex" altG - where - altG rex = rule "alternate" $ - iso alternativesOf (foldr1 (>|<) :: [RegEx Char] -> RegEx Char) - >~ sepWith "|" (atLeast 1) (seqG rex) - - seqG rex = rule "sequence" $ - iso itemsOf mconcat >~ manyP (exprG rex) - - alternativesOf = \case - RegExam (Alternate rex0 rex1 rexes) -> rex0 : rex1 : rexes - rex -> [rex] - - itemsOf = \case - SeqEmpty -> [] - Sequence rex0 rex1 rexes -> rex0 : rex1 : rexes - rex -> [rex] - - exprG rex = rule "expression" $ orP - [ _KleeneOpt >? atomG rex *< terminal "?" - , _KleeneStar >? atomG rex *< terminal "*" - , _KleenePlus >? atomG rex *< terminal "+" - , atomG rex - ] - - atomG rex = rule "atom" $ orP - [ _NonTerminal >? terminal "\\q" >* nonterminalG - , _RegExam >? classG - , terminal "(" >* rex *< terminal ")" - ] - - categoryG = rule "category" $ orP - [ _LowercaseLetter >? terminal "Ll" - , _UppercaseLetter >? terminal "Lu" - , _TitlecaseLetter >? terminal "Lt" - , _ModifierLetter >? terminal "Lm" - , _OtherLetter >? terminal "Lo" - , _NonSpacingMark >? terminal "Mn" - , _SpacingCombiningMark >? terminal "Mc" - , _EnclosingMark >? terminal "Me" - , _DecimalNumber >? terminal "Nd" - , _LetterNumber >? terminal "Nl" - , _OtherNumber >? terminal "No" - , _ConnectorPunctuation >? terminal "Pc" - , _DashPunctuation >? terminal "Pd" - , _OpenPunctuation >? terminal "Ps" - , _ClosePunctuation >? terminal "Pe" - , _InitialQuote >? terminal "Pi" - , _FinalQuote >? terminal "Pf" - , _OtherPunctuation >? terminal "Po" - , _MathSymbol >? terminal "Sm" - , _CurrencySymbol >? terminal "Sc" - , _ModifierSymbol >? terminal "Sk" - , _OtherSymbol >? terminal "So" - , _Space >? terminal "Zs" - , _LineSeparator >? terminal "Zl" - , _ParagraphSeparator >? terminal "Zp" - , _Control >? terminal "Cc" - , _Format >? terminal "Cf" - , _Surrogate >? terminal "Cs" - , _PrivateUse >? terminal "Co" - , _NotAssigned >? terminal "Cn" - ] - - classG = rule "class" $ orP - [ _OneOf >? classOneOfG - , _NotOneOf >? classNotOneOfG - ] - - classCatG = rule "class-category" $ orP - [ _AndAsIn >? terminal "\\p{" >* categoryG *< terminal "}" - , _AndNotAsIn . from listed >? - terminal "\\P{" >* sepWith "|" (atLeast 1) categoryG *< terminal "}" - ] - - classOneOfG = rule "class-one-of" $ orP - [ onlyOne charG - , terminal "[" >* (listed ~< manyP charG) *< terminal "]" - ] - - classNotOneOfG = rule "class-not-one-of" $ orP - [ asEmpty >*< classCatG - , terminal "[^" >* (listed ~< manyP charG) >*< - optionP (_AndNotAsIn . _Empty) classCatG *< terminal "]" - ] - -nonterminalG :: Grammar Char String -nonterminalG = rule "nonterminal" $ - terminal "{" >* manyP charG *< terminal "}" - -charG :: Grammar Char Char -charG = rule "char" $ - tokenClass (notOneOf charsReserved >&< notAsIn Control) - >|< terminal "\\" >* charEscapedG - where - charEscapedG = rule "char-escaped" $ - oneOf charsReserved >|< charControlG - - charsReserved = "()*+?[\\]^{|}" - - charControlG = rule "char-control" $ orP - [ only '\NUL' >? terminal "NUL" - , only '\SOH' >? terminal "SOH" - , only '\STX' >? terminal "STX" - , only '\ETX' >? terminal "ETX" - , only '\EOT' >? terminal "EOT" - , only '\ENQ' >? terminal "ENQ" - , only '\ACK' >? terminal "ACK" - , only '\BEL' >? terminal "BEL" - , only '\BS' >? terminal "BS" - , only '\HT' >? terminal "HT" - , only '\LF' >? terminal "LF" - , only '\VT' >? terminal "VT" - , only '\FF' >? terminal "FF" - , only '\CR' >? terminal "CR" - , only '\SO' >? terminal "SO" - , only '\SI' >? terminal "SI" - , only '\DLE' >? terminal "DLE" - , only '\DC1' >? terminal "DC1" - , only '\DC2' >? terminal "DC2" - , only '\DC3' >? terminal "DC3" - , only '\DC4' >? terminal "DC4" - , only '\NAK' >? terminal "NAK" - , only '\SYN' >? terminal "SYN" - , only '\ETB' >? terminal "ETB" - , only '\CAN' >? terminal "CAN" - , only '\EM' >? terminal "EM" - , only '\SUB' >? terminal "SUB" - , only '\ESC' >? terminal "ESC" - , only '\FS' >? terminal "FS" - , only '\GS' >? terminal "GS" - , only '\RS' >? terminal "RS" - , only '\US' >? terminal "US" - , only '\DEL' >? terminal "DEL" - , only '\x80' >? terminal "PAD" - , only '\x81' >? terminal "HOP" - , only '\x82' >? terminal "BPH" - , only '\x83' >? terminal "NBH" - , only '\x84' >? terminal "IND" - , only '\x85' >? terminal "NEL" - , only '\x86' >? terminal "SSA" - , only '\x87' >? terminal "ESA" - , only '\x88' >? terminal "HTS" - , only '\x89' >? terminal "HTJ" - , only '\x8A' >? terminal "VTS" - , only '\x8B' >? terminal "PLD" - , only '\x8C' >? terminal "PLU" - , only '\x8D' >? terminal "RI" - , only '\x8E' >? terminal "SS2" - , only '\x8F' >? terminal "SS3" - , only '\x90' >? terminal "DCS" - , only '\x91' >? terminal "PU1" - , only '\x92' >? terminal "PU2" - , only '\x93' >? terminal "STS" - , only '\x94' >? terminal "CCH" - , only '\x95' >? terminal "MW" - , only '\x96' >? terminal "SPA" - , only '\x97' >? terminal "EPA" - , only '\x98' >? terminal "SOS" - , only '\x99' >? terminal "SGCI" - , only '\x9A' >? terminal "SCI" - , only '\x9B' >? terminal "CSI" - , only '\x9C' >? terminal "ST" - , only '\x9D' >? terminal "OSC" - , only '\x9E' >? terminal "PM" - , only '\x9F' >? terminal "APC" - ] - -{- | -`regbnfGrammar` is a context-free `Grammar` for t'RegBnf's. -That means that it can generate a self-hosted definition. - ->>> putStringLn (regbnfG regbnfGrammar) -{start} = \q{regbnf} -{alternate} = \q{sequence}(\|\q{sequence})* -{atom} = \\q\q{nonterminal}|\q{class}|\(\q{regex}\) -{category} = Ll|Lu|Lt|Lm|Lo|Mn|Mc|Me|Nd|Nl|No|Pc|Pd|Ps|Pe|Pi|Pf|Po|Sm|Sc|Sk|So|Zs|Zl|Zp|Cc|Cf|Cs|Co|Cn -{char} = [^\(\)\*\+\?\[\\\]\^\{\|\}\P{Cc}]|\\\q{char-escaped} -{char-control} = NUL|SOH|STX|ETX|EOT|ENQ|ACK|BEL|BS|HT|LF|VT|FF|CR|SO|SI|DLE|DC1|DC2|DC3|DC4|NAK|SYN|ETB|CAN|EM|SUB|ESC|FS|GS|RS|US|DEL|PAD|HOP|BPH|NBH|IND|NEL|SSA|ESA|HTS|HTJ|VTS|PLD|PLU|RI|SS2|SS3|DCS|PU1|PU2|STS|CCH|MW|SPA|EPA|SOS|SGCI|SCI|CSI|ST|OSC|PM|APC -{char-escaped} = [\(\)\*\+\?\[\\\]\^\{\|\}]|\q{char-control} -{class} = \q{class-one-of}|\q{class-not-one-of} -{class-category} = \\p\{\q{category}\}|\\P\{\q{category}(\|\q{category})*\} -{class-not-one-of} = \q{class-category}|\[\^\q{char}*\q{class-category}?\] -{class-one-of} = \q{char}|\[\q{char}*\] -{expression} = \q{atom}\?|\q{atom}\*|\q{atom}\+|\q{atom} -{nonterminal} = \{\q{char}*\} -{regbnf} = \{start\} = \q{regex}(\LF\q{nonterminal} = \q{regex})* -{regex} = \q{alternate} -{sequence} = \q{expression}* --} -regbnfGrammar :: Grammar Char RegBnf -regbnfGrammar = rule "regbnf" $ _RegBnf . _Bnf >~ - terminal "{start} = " >* regexGrammar >*< (listed ~< manyP - (terminal "\n" >* nonterminalG *< terminal " = " >*< regexGrammar)) - - -{- | `regstringG` generates a t'RegString' from a regular grammar. +{- | `regexG` generates a `RegEx`pression from a regular grammar, +over any token, a regular expression string over characters. Since context-free `Grammar`s and `CtxGrammar`s aren't necessarily regular, -the type system will prevent `regstringG` from being applied to them. +the type system will prevent `regexG` from being applied to them. -} -regstringG :: RegGrammar Char a -> RegString -regstringG rex = runGrammor rex +regexG + :: forall token. forall a -> (Categorized token, RegGrammar token a) + => RegEx token +regexG a = runGrammor (regGrammar @token @a) -{- | `regbnfG` generates a t'RegBnf' from a context-free `Grammar`. +{- | `regbnfG` generates a t'Bnf' of `RegEx`pressions from a context-free +`Grammar`, over any token, of regular expression strings over characters. Since `CtxGrammar`s aren't context-free, the type system will prevent `regbnfG` from being applied to a `CtxGrammar`. It can apply to a `RegGrammar`. -} -regbnfG :: Grammar Char a -> RegBnf -regbnfG bnf = runGrammor bnf +regbnfG + :: forall token. forall a -> (Categorized token, Grammar token a) + => Bnf (RegEx token) +regbnfG a = runGrammor (grammar @token @a) {- | Compile a `Grammar` into a t'Transducer'. ->>> let regexMachine = transducerG @Char regexGrammar +>>> let regexMachine = transducerG @Char (RegEx Char) A transducer is a form of finite state machine, usable as an intermediary for further generators like @@ -969,8 +599,10 @@ usable as an intermediary for further generators like @ -} -transducerG :: Categorized token => Grammar token a -> Transducer token -transducerG bnf = transducer (runGrammor bnf) +transducerG + :: forall token. forall a -> (Categorized token, Grammar token a) + => Transducer token +transducerG a = transducer (runGrammor (grammar @token @a)) {- | `printG` generates a printer from a `CtxGrammar`. Since both `RegGrammar`s and context-free `Grammar`s are `CtxGrammar`s, @@ -980,13 +612,13 @@ that `cons`es tokens at the beginning of an input string, from right to left. -} printG - :: Cons string string token token + :: 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) - => CtxGrammar token a - -> a {- ^ syntax -} + => a {- ^ syntax -} -> m (string -> string) -printG printor = printP printor +printG = printP (ctxGrammar @token @a) {- | `parseG` generates a parser from a @LL(∞)@ `CtxGrammar`. Since both `RegGrammar`s and context-free `Grammar`s are `CtxGrammar`s, @@ -996,13 +628,13 @@ tokens from the beginning of an input string from left to right, returning a syntax value and the remaining output string. -} parseG - :: (Cons string string token token, Snoc string string token token) + :: 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) - => CtxGrammar token a - -> string {- ^ input -} + => string {- ^ input -} -> m (a, string) -parseG parsor = parseP parsor +parseG = parseP (ctxGrammar @token @a) {- | `unparseG` generates a printer from a @LL(∞)@ `CtxGrammar`. Since both `RegGrammar`s and context-free `Grammar`s are `CtxGrammar`s, @@ -1015,14 +647,14 @@ Print to a string with a constant time `snoc`, like a making printing to a `String` quadratic. -} unparseG - :: (Cons string string token token, Snoc string string token token) + :: 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) - => CtxGrammar token a - -> a {- ^ syntax -} + => a {- ^ syntax -} -> string {- ^ input -} -> m string -unparseG parsor = unparseP parsor +unparseG = unparseP (ctxGrammar @token @a) {- | `parsecG` generates a parser from a @LL(1)@ `CtxGrammar`, with `try` for restoring full @LL(∞)@ lookahead. @@ -1035,12 +667,12 @@ an output syntax value, with parse failure stored in `parsecFailure`, and a remaining output `parsecStream`. -} parsecG - :: (Cons string string token token, Snoc string string token token) + :: forall a string token. CtxGrammar token a + => (Cons string string token token, Snoc string string token token) => (Item string ~ token, Categorized token) - => CtxGrammar token a - -> string {- ^ input -} + => string {- ^ input -} -> ParsecState string a -parsecG parsector = parsecP parsector +parsecG = parsecP (ctxGrammar @token @a) {- | `unparsecG` generates a printer from a @LL(1)@ `CtxGrammar`, with `try` for restoring full @LL(∞)@ lookahead. @@ -1055,13 +687,13 @@ Print to a string with a constant time `snoc`, like a making printing to a `String` quadratic. -} unparsecG - :: (Cons string string token token, Snoc string string token token) + :: forall a string token. CtxGrammar token a + => (Cons string string token token, Snoc string string token token) => (Item string ~ token, Categorized token) - => CtxGrammar token a - -> a {- ^ syntax -} + => a {- ^ syntax -} -> string {- ^ input -} -> ParsecState string a -unparsecG parsector = unparsecP parsector +unparsecG = unparsecP (ctxGrammar @token @a) {- | Generate any `Applicative` parser backend from a `Grammar` with `applicativeG`. @@ -1071,18 +703,20 @@ That permits backends to use algorithms that can only parse context-free `Grammar`s. -} applicativeG - :: ( Alternative f + :: forall token a f. + ( Grammar token a + , Alternative f , TokenAlgebra token (f token) , TerminalSymbol token (f ()) , forall x. BackusNaurForm (f x) + , forall x. Tried (f x) ) - => Grammar token a -- ^ context-free grammar - -> f a -applicativeG joker = runJoker joker + => f a +applicativeG = runJoker (grammar @token @a) {- | Generate a `ReadP` backend from a `CtxGrammar` `Char`. -} -readG :: CtxGrammar Char a -> ReadP a -readG joker = monadG joker +readG :: CtxGrammar Char a => ReadP a +readG = monadG @Char {- | Generate any parser `Monad` backend from a `CtxGrammar` with `monadG`. @@ -1110,81 +744,33 @@ instance Tokenized Char (WrapMega Char) where 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 BackusNaurForm (WrapMega a) where +instance Ruled (WrapMega a) where rule lbl (WrapMega p) = WrapMega (M.label lbl p) - ruleRec lbl = rule lbl . fix +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 -instance MonadTry WrapMega where - try (WrapMega p) = WrapMega (M.try p) -megaparsecG - :: CtxGrammar Char a - -> M.Parsec String String a -megaparsecG gram = unwrapMega (monadG gram) +megaparsecG :: CtxGrammar Char a => M.Parsec String String a +megaparsecG = unwrapMega (monadG @Char) @ -} monadG - :: ( MonadTry m + :: forall token a m. + ( 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 ()) ) - => CtxGrammar token a -- ^ context-sensitive grammar - -> m a -monadG joker = runJoker joker + => m a +monadG = runJoker (ctxGrammar @token @a) {- | `putStringLn` is a utility that generalizes `putStrLn` -to string-like interfaces such as t'RegString' and t'RegBnf'. +to string-like interfaces such as `RegEx` and t'Bnf' of `Char`s. -} putStringLn :: (IsList string, Item string ~ Char) => string -> IO () putStringLn = putStrLn . toList - -instance IsList RegString where - type Item RegString = Char - fromList - = fromMaybe falseP - . listToMaybe - . mapMaybe prsF - . readP_to_S (readG regexGrammar) - where - prsF (rex,"") = Just rex - prsF _ = Nothing - toList - = maybe "[]" ($ "") - . printP regexGrammar -instance IsString RegString where - fromString = fromList -instance Show RegString where - showsPrec precision = showsPrec precision . toList -instance Read RegString where - readsPrec = readsGrammar regexGrammar -instance IsList RegBnf where - type Item RegBnf = Char - fromList - = fromMaybe falseP - . listToMaybe - . mapMaybe prsF - . readP_to_S (readG regbnfGrammar) - where - prsF (regbnf,"") = Just regbnf - prsF _ = Nothing - toList - = maybe "{start} = []" ($ "") - . printP regbnfGrammar -instance IsString RegBnf where - fromString = fromList -instance Show RegBnf where - showsPrec precision = showsPrec precision . toList -instance Read RegBnf where - readsPrec = readsGrammar regbnfGrammar - -{- | Read a string literal, as `String`'s `readsPrec` does, -& its text by a `Grammar`, so that @read . show = id@. --} -readsGrammar :: Grammar Char a -> Int -> ReadS a -readsGrammar grammar precision str = - [ (a, rest) - | (text, rest) <- readsPrec @String precision str - , a <- take 1 [a | (a, "") <- readP_to_S (readG grammar) text] - ] diff --git a/distributors-grammar/src/Control/Lens/Grammar/Analysis.hs b/distributors-grammar/src/Control/Lens/Grammar/Analysis.hs new file mode 100644 index 00000000..de8e704e --- /dev/null +++ b/distributors-grammar/src/Control/Lens/Grammar/Analysis.hs @@ -0,0 +1,349 @@ +{- | +Module : Control.Lens.Grammar.Analysis +Description : static analyses of grammars +Copyright : (C) 2026 - Eitan Chatav +License : BSD-style (see the file LICENSE) +Maintainer : Eitan Chatav +Stability : provisional +Portability : non-portable + +Static analyses of `RegEx`tended t'Bnf's, as generated from context-free +grammars by @Control.Lens.Grammar.regbnfG@, over any token. + +A `RegEx` is the free `KleeneStarAlgebra` of token classes & +nonterminals, so an analysis which composes, like nullability or the +first tokens of a word, is the unique homomorphism out of it, `foldRegEx`, +into another `KleeneStarAlgebra`, with a least fixpoint, `fixRules`, +for the rules naming each other. An analysis which depends on context, +like the tokens which may follow a rule, flows down from its callers, +in `follows`. The @LL(1)@ conflicts, `ll1Conflicts`, are built of them. +-} + +module Control.Lens.Grammar.Analysis + ( -- * Folding + foldRegEx + , bnfRules + , fixRules + -- * Leading atoms + , Leading (..) + , firsts + , firstOf + , leftRecursive + -- * Guards + , Guard (..) + , follows + -- * LL(1) + , ll1Conflicts + , LL1Conflict (..) + , LL1ConflictSort (..) + ) where + +import Control.Lens.Grammar.RegEx +import Control.Lens.Grammar.Token +import Data.Map.Strict (Map) +import qualified Data.Map.Strict as Map +import Data.Monoid.Disjunctive +import Data.Set (Set) +import qualified Data.Set as Set + +-- $setup +-- >>> :set -XOverloadedStrings +-- >>> import Control.Lens.Grammar + +{- | The homomorphism out of the free `KleeneStarAlgebra` of token +classes & nonterminals, a `RegEx`, into any other, given the +interpretations of its token classes & its nonterminals. + +> prop> foldRegEx tokenClass nonTerminal = id +-} +foldRegEx + :: KleeneStarAlgebra k + => (TokenClass token -> k) -- ^ token classes + -> (String -> k) -- ^ nonterminals + -> RegEx token -> k +foldRegEx tok nonterm = go + where + go = \case + SeqEmpty -> mempty + Sequence x y zs -> mconcat (map go (x : y : zs)) + NonTerminal name -> nonterm name + KleeneStar x -> starK (go x) + KleeneOpt x -> optK (go x) + KleenePlus x -> plusK (go x) + KleeneTimes lo hi x -> quantK lo hi (go x) + Backtracking x -> go x + RegExam (OneOf toks) -> tok (TokenClass (OneOf toks)) + RegExam (NotOneOf toks test) -> tok (TokenClass (NotOneOf toks test)) + RegExam (Alternate x y zs) -> foldr1 (>|<) (map go (x : y : zs)) + +{- | The rules of a t'Bnf', by name, +a name's rules joined as alternatives. +-} +bnfRules :: Categorized token => Bnf (RegEx token) -> Map String (RegEx token) +bnfRules = Map.fromListWith (flip (>|<)) . Set.toList . rulesBnf + +{- | The least fixpoint of an analysis of the rules of a t'Bnf', +from @bottom@, interpreting each rule's body given the analyses of the +rules it names, until they stabilize, as they do for a monotone analysis +into a lattice of finite height. +-} +fixRules + :: (Categorized token, Eq k) + => k -- ^ bottom + -> (Map String k -> RegEx token -> k) -- ^ a body, given the rules + -> Bnf (RegEx token) -> Map String k +fixRules bottom analyze bnf = go (bottom <$ rules) + where + rules = bnfRules bnf + go env = let env' = analyze env <$> rules in + if env' == env then env else go env' + +{- | Whether a word can be empty, & the atoms it can lead with, +a `KleeneStarAlgebra` which, at token classes, is the first tokens of +words, & at sets of rule names, their left corners. + +>>> foldRegEx (Leading False) (const falseP) ("a*b|c?" :: RegEx Char) +Leading {leadingNullable = True, leadingAtoms = TokenClass (OneOf (fromList "abc"))} +-} +data Leading a = Leading + { leadingNullable :: Bool -- ^ whether a word can be empty + , leadingAtoms :: a -- ^ the atoms a word can lead with + } deriving stock (Eq, Ord, Show, Read) +instance DisjunctiveMonoid a => Semigroup (Leading a) where + Leading null0 atoms0 <> Leading null1 atoms1 = + Leading (null0 && null1) (if null0 then atoms0 >|< atoms1 else atoms0) +instance DisjunctiveMonoid a => Monoid (Leading a) where + mempty = Leading True falseP +instance DisjunctiveMonoid a => DisjunctiveMonoid (Leading a) where + falseP = Leading False falseP + Leading null0 atoms0 >|< Leading null1 atoms1 = + Leading (null0 || null1) (atoms0 >|< atoms1) +instance DisjunctiveMonoid a => KleeneStarAlgebra (Leading a) where + starK (Leading _ atoms) = Leading True atoms + plusK = id + optK (Leading _ atoms) = Leading True atoms + +{- | The nullability & first tokens of each rule of a t'Bnf'. -} +firsts + :: Categorized token + => Bnf (RegEx token) -> Map String (Leading (TokenClass token)) +firsts = fixRules falseP firstOf + +{- | The nullability & first tokens of a `RegEx`, +given those of the rules it names. +-} +firstOf + :: Categorized token + => Map String (Leading (TokenClass token)) + -> RegEx token -> Leading (TokenClass token) +firstOf rules = + foldRegEx (Leading False) (\name -> Map.findWithDefault falseP name rules) + +{- | The rules of a t'Bnf' which can name themselves +before reading a token, on which a predictive parser diverges. +-} +leftRecursive :: Categorized token => Bnf (RegEx token) -> Set String +leftRecursive bnf = Set.filter (\name -> name `Set.member` reach name) names + where + rules = bnfRules bnf + names = Map.keysSet rules + nullables = leadingNullable <$> firsts bnf + -- the rules a body can name before reading a token + corners = foldRegEx (const falseP) $ \name -> + Leading (Map.findWithDefault False name nullables) (Set.singleton name) + leftCorners = leadingAtoms . corners <$> rules + reach name = search Set.empty (corners' name) + corners' name = Set.toList (Map.findWithDefault Set.empty name leftCorners) + search seen = \case + [] -> seen + next : rest + | next `Set.member` seen -> search seen rest + | otherwise -> search (Set.insert next seen) (corners' next <> rest) + +{- | A guard on the next token, or the end of the input, +a `BooleanAlgebra`, by which a predictive parser decides. +The tokens which may follow a rule are a t'Guard'. +-} +data Guard token = Guard + { guardEnd :: Bool -- ^ whether the input may end + , guardNext :: TokenClass token -- ^ which tokens may be next + } +deriving stock instance Categorized token => Eq (Guard token) +deriving stock instance Categorized token => Ord (Guard token) +deriving stock instance + (Categorized token, Show token, Show (Categorize token)) + => Show (Guard token) +instance Categorized token => DisjunctiveMonoid (Guard token) where + falseP = Guard False falseP + Guard end0 next0 >|< Guard end1 next1 = Guard (end0 || end1) (next0 >|< next1) +instance Categorized token => BooleanAlgebra (Guard token) where + trueP = Guard True trueP + notP (Guard end next) = Guard (not end) (notP next) + Guard end0 next0 >&< Guard end1 next1 = Guard (end0 && end1) (next0 >&< next1) + +-- the guard of a word, then of what follows it +guardOf + :: Categorized token + => Leading (TokenClass token) -> Guard token -> Guard token +guardOf (Leading nullable atoms) after + | nullable = Guard False atoms >|< after + | otherwise = Guard False atoms + +-- each of a sequence's items, with the guard of what follows it +sequenced + :: Categorized token + => (RegEx token -> Leading (TokenClass token)) + -> Guard token -> [RegEx token] -> [(RegEx token, Guard token)] +sequenced first after = snd . foldr step (after, []) + where + step item (guard, acc) = (guardOf (first item) guard, (item, guard) : acc) + +{- | The tokens which may follow each rule of a t'Bnf', +& whether its input may end, the least fixpoint of their callers'. + +>>> follows ("{start} = \\q{a}b|\\q{a}\n{a} = c" :: Bnf (RegEx Char)) +fromList [("a",Guard {guardEnd = True, guardNext = TokenClass (OneOf (fromList "b"))})] +-} +follows :: Categorized token => Bnf (RegEx token) -> Map String (Guard token) +follows bnf = go (falseP <$ rules) + where + rules = bnfRules bnf + first = firstOf (firsts bnf) + go env = let env' = Map.unionWith (>|<) (falseP <$ rules) (callers env) in + if env' == env then env else go env' + callers env = Map.unionsWith (>|<) $ + followed (Guard True falseP) (startBnf bnf) + : [ followed (Map.findWithDefault falseP name env) body + | (name, body) <- Map.toList rules ] + followed after = \case + Sequence x y zs -> Map.unionsWith (>|<) + [followed guard item | (item, guard) <- sequenced first after (x : y : zs)] + NonTerminal name -> Map.singleton name after + KleeneStar x -> followed (again x) x + KleenePlus x -> followed (again x) x + Backtracking x -> followed after x + KleeneTimes lo hi x -> followed after (unrolled lo hi x) + KleeneOpt x -> followed after x + RegExam (Alternate x y zs) -> Map.unionsWith (>|<) (map (followed after) (x : y : zs)) + _ -> Map.empty + where + again x = Guard False (leadingAtoms (first x)) >|< after + +{- | The conflicts which keep a `RegEx`tended t'Bnf' from being @LL(1)@, +that is, from being parsed predictively by one token of lookahead, +committing to an alternative by its first token, as +t'Data.Profunctor.Grammar.Parsector.Parsector' does. +An empty list means the grammar is @LL(1)@. + +Alternatives are tried in order, so besides the usual conditions, +that alternatives start with distinct tokens & that repetitions +& options start with tokens which can't follow them, +a nullable alternative mustn't precede one which can consume tokens, +since it would succeed first, without consuming them. +Left recursion is reported too, since a predictive parser diverges on it. +A conflict which a `try` resolves isn't reported: of alternatives, +the first of which backtracks, or of a repetition which backtracks, +since a predictive parser then tries what follows anew. + +>>> map conflictSort (ll1Conflicts ("{start} = ab|ac" :: Bnf (RegEx Char))) +[LL1FirstFirst] +>>> ll1Conflicts ("{start} = ab|c" :: Bnf (RegEx Char)) +[] +-} +ll1Conflicts + :: Categorized token => Bnf (RegEx token) -> [LL1Conflict token] +ll1Conflicts bnf = + [ LL1Conflict (Just name) LL1LeftRecursion falseP (NonTerminal name) + | name <- Set.toList (leftRecursive bnf) + ] + <> check Nothing (startBnf bnf) (Guard True falseP) + <> concat + [ check (Just name) body (Map.findWithDefault falseP name followers) + | (name, body) <- Map.toList (bnfRules bnf) + ] + where + first = firstOf (firsts bnf) + followers = follows bnf + nullable = leadingNullable . first + atoms = leadingAtoms . first + check name rex after = case rex of + Sequence x y zs -> concat + [check name item guard | (item, guard) <- sequenced first after (x : y : zs)] + KleeneStar x -> repetition x <> check name x (again x) + KleenePlus x -> repetition x <> check name x (again x) + KleeneOpt x -> repetition x <> check name x after + Backtracking x -> check name x after + KleeneTimes lo hi x -> check name (unrolled lo hi x) after + RegExam (Alternate x y zs) -> + concat [alternation a b | (a, bs) <- pairs (x : y : zs), b <- bs] + <> concatMap (\a -> check name a after) (x : y : zs) + _ -> [] + where + conflict sort toks = LL1Conflict name sort toks rex + again x = Guard False (atoms x) >|< after + overlapping toks + | toks == falseP = [] + | otherwise = [toks] + repetition x = + [ conflict LL1NullableRepetition falseP | nullable x ] + <> [ conflict LL1FirstFollow toks + | not (tried x) + , toks <- overlapping (atoms x >&< guardNext after) ] + -- an alternative, & one after it + alternation a b = + [ conflict LL1FirstFirst toks + | not (tried a) + , toks <- overlapping (atoms a >&< atoms b) ] + <> [ conflict LL1NullableAlternatives falseP + | nullable a, nullable b ] + <> [ conflict LL1NullableFirst (atoms b) + | nullable a, not (nullable b), atoms b /= falseP ] + <> [ conflict LL1FirstFollow toks + | nullable b, not (nullable a), not (tried a) + , toks <- overlapping (atoms a >&< guardNext after) ] + pairs = \case + [] -> [] + a : bs -> (a, bs) : pairs bs + -- a pattern which backtracks, after reading tokens, by `try` + tried = \case + Backtracking _ -> True + _ -> False + +{- | A conflict keeping a grammar from being @LL(1)@, +in a rule, or `Nothing` for the start expression, +of a sort, with the tokens in conflict, at a subexpression. +-} +data LL1Conflict token = LL1Conflict + { conflictRule :: Maybe String + , conflictSort :: LL1ConflictSort + , conflictTokens :: TokenClass token + , conflictAt :: RegEx token + } +deriving stock instance Categorized token => Eq (LL1Conflict token) +deriving stock instance + (Categorized token, Show token, Show (Categorize token)) + => Show (LL1Conflict token) + +-- | Sorts of `LL1Conflict`s. +data LL1ConflictSort + = LL1FirstFirst + -- ^ alternatives which start with the same tokens + | LL1FirstFollow + -- ^ an option, repetition or nullable alternative which starts + -- with tokens which may follow it + | LL1NullableAlternatives + -- ^ alternatives which both match the empty word + | LL1NullableFirst + -- ^ a nullable alternative before one which consumes tokens + | LL1NullableRepetition + -- ^ an option or repetition of a pattern which matches the empty word + | LL1LeftRecursion + -- ^ a rule which names itself before reading a token + deriving stock (Eq, Ord, Show, Read, Enum, Bounded) + +-- | Counts, unrolled, @x{lo,hi}@ as @lo@ times @x@ & then +-- @x*@, or @hi - lo@ nested options. +unrolled :: Categorized token => Int -> Maybe Int -> RegEx token -> RegEx token +unrolled lo hi x = mconcat (replicate lo x) <> case hi of + Nothing -> starK x + Just m -> foldr (\_ rest -> optK (x <> rest)) mempty [lo + 1 .. m] diff --git a/distributors-grammar/src/Control/Lens/Grammar/BackusNaur.hs b/distributors-grammar/src/Control/Lens/Grammar/BackusNaur.hs index 8b4146bc..ab8f883c 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/BackusNaur.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/BackusNaur.hs @@ -14,26 +14,30 @@ See Naur & Backus, et al. module Control.Lens.Grammar.BackusNaur ( -- * BackusNaurForm - BackusNaurForm (..), failBnf - , Bnf (..) - , liftBnf0 - , liftBnf1 - , liftBnf2 - , diffB + BackusNaurForm (..) + , Ruled (..), failP, ruleTyped + , Tried (..) + -- * Grammatical + , RegGrammatical + , Grammatical + , CtxGrammatical ) where import Control.Lens -import Control.Lens.Grammar.RegEx import Control.Lens.Grammar.Token import Control.Lens.Grammar.Symbol +import Control.Monad (MonadPlus) import Data.Bifunctor.Joker -import Data.Coerce +import Data.Kind (Constraint) +import Data.Profunctor.Distributor (Alternator) +import Data.Profunctor.Filtrator (Filtrator) import Data.Function -import Data.MemoTrie +import Data.List (intercalate, isPrefixOf) +import Data.Maybe (isNothing) +import Type.Reflection (SomeTypeRep (..), Typeable, splitApps, tyConModule, tyConName, typeRep) import Data.Monoid.Disjunctive -import qualified Data.Set as Set -import Data.Set (Set) import Text.ParserCombinators.ReadP (ReadP) +import Text.ParserCombinators.ReadPrec (ReadPrec) {- | `BackusNaurForm` grammar combinators formalize traced `rule` abstraction and general recursion with `ruleRec`, @@ -50,10 +54,10 @@ and second as a `Debug.Trace.trace`-like label for `rule` abstraction. The category @(->)@ already has a traced @(,)@-monoidal structure in the form of `Data.Profunctor.unfirst` @=@ `Control.Arrow.loop` or equivalently the fixpoint function `fix`, -determining default methods for a `BackusNaurForm`. +determining the default method for a `BackusNaurForm`, +by which the invariant holds for any `Ruled` `rule`. -> prop> rule _ = id -> prop> ruleRec _ = fix +> prop> ruleRec label = rule label . fix The `BackusNaurForm` interface permits overloading these methods, and tracing them with a label. @@ -66,146 +70,117 @@ See Breitner, [Showcasing Applicative] for the original interface. -} -class BackusNaurForm bnf where - - {- | Rule abstraction. -} - rule :: String -> bnf -> bnf - rule _ = id +class Ruled bnf => BackusNaurForm bnf where {- | General recursion. -} ruleRec :: String -> (bnf -> bnf) -> bnf - ruleRec _ = fix + ruleRec label = rule label . fix --- | A nonterminal symbol to indicate a failure. -failBnf :: (BackusNaurForm bnf, DisjunctiveMonoid bnf) => String -> bnf -failBnf msg = rule msg falseP - -{- | A t'Bnf' consists of a distinguished starting rule -and a set of named rules. When a t'Bnf' supports `NonTerminalSymbol`s, -then it supports the `BackusNaurForm` interface -by replacing recursive calls with `nonTerminal`s. - -> prop> ruleRec label f = rule label (f (nonTerminal label)) +{- | `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 -} -data Bnf rule = Bnf - { startBnf :: rule - , rulesBnf :: Set (String, rule) - } deriving stock (Eq, Ord, Show, Read) - -{- | Lift a rule to a t'Bnf'. -} -liftBnf0 :: Ord a => a -> Bnf a -liftBnf0 a = Bnf a mempty - -{- | Lift a function of rules to t'Bnf's. -} -liftBnf1 :: (Coercible a b, Ord b) => (a -> b) -> Bnf a -> Bnf b -liftBnf1 f (Bnf start rules) = Bnf (f start) (Set.map coerce rules) - -{- | Lift a binary function of rules to t'Bnf's. -} -liftBnf2 - :: (Coercible a c, Coercible b c, Ord c) - => (a -> b -> c) -> Bnf a -> Bnf b -> Bnf c -liftBnf2 f (Bnf start0 rules0) (Bnf start1 rules1) = - Bnf (f start0 start1) (Set.map coerce rules0 <> Set.map coerce rules1) +class Ruled p where -{- | -The [Brzozowski derivative] -(https://dl.acm.org/doi/pdf/10.1145/321239.321249) of a -`RegEx`tended t'Bnf', with memoization. - -> prop> word =~ diffB prefix pattern = prefix <> word =~ pattern + {- | Subgrammar abstraction. -} + rule :: String -> p -> p + rule _ = id -Unfortunately, despite elegance & optimization, Brzozowski's -pattern matching algorithm is worst case exponential in grammar size. -See Might, Darais & Spiewak, [Parsing With Derivatives] -(https://matt.might.net/papers/might2011derivatives.pdf). +-- | A nonterminal symbol to indicate a failure. +failP :: (Ruled p, DisjunctiveMonoid p) => String -> p +failP msg = rule msg falseP + +{- | 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@. -} -diffB - :: (Categorized token, HasTrie token) - => [token] -> Bnf (RegEx token) -> Bnf (RegEx token) -diffB prefix (Bnf start rules) = - Bnf (foldl' (flip diff1B) start prefix) rules +ruleTyped :: forall a p. (Typeable a, Ruled (p a a)) => p a a -> p a a +ruleTyped = rule (qualifiedName (SomeTypeRep (typeRep @a))) +{-# INLINE ruleTyped #-} + +-- | A type, `show`n with its type constructors qualified by their modules. +qualifiedName :: SomeTypeRep -> String +qualifiedName (SomeTypeRep rep) = case (bracketed tyCon, args) of + (Just "List", [arg]) -> "[" <> qualifiedName arg <> "]" + (Just "Unit", []) -> "()" + (Just _, _ : _ : _) -> + "(" <> intercalate "," (map qualifiedName args) <> ")" + _ -> unwords (qualified : map typeArgument args) where - -- derivative wrt 1 token, memoized - diff1B = memo2 $ \x -> \case - SeqEmpty -> falseP - NonTerminal nameY -> anyP (diff1B x) (rulesNamed nameY rules) - Sequence y1 y ys -> - if δ (Bnf y1 rules) then y1'y2 >|< y1y2' else y1'y2 - where - y2 = mconcat (y : ys) - y1'y2 = diff1B x y1 <> y2 - y1y2' = y1 <> diff1B x y2 - KleeneStar y -> diff1B x y <> starK y - KleeneOpt y -> diff1B x y - KleenePlus y -> diff1B x y <> starK y - RegExam (OneOf chars) -> - if x `elem` chars then mempty else falseP - RegExam (NotOneOf chars (AndAsIn cat)) -> - if elem x chars || categorize x /= cat - then falseP else mempty - RegExam (NotOneOf chars (AndNotAsIn cats)) -> - if elem x chars || elem (categorize x) cats - then falseP else mempty - RegExam (Alternate y1 y2 ys) -> anyP (diff1B x) (y1 : y2 : ys) - --- | Does a pattern match the empty word? -δ :: (Categorized token, HasTrie token) - => Bnf (RegEx token) -> Bool -δ (Bnf start rules) = ν start where - ν = memo $ \case - SeqEmpty -> True - KleeneStar _ -> True - KleeneOpt _ -> True - KleenePlus y -> ν y - Sequence y1 y2 ys -> all ν (y1 : y2 : ys) - RegExam (Alternate y1 y2 ys) -> any ν (y1 : y2 : ys) - NonTerminal nameY -> any ν (rulesNamed nameY rules) - _ -> False - -rulesNamed :: Ord rule => String -> Set (String, rule) -> Set rule -rulesNamed nameX = foldl' (flip inserter) Set.empty where - inserter (nameY,y) = - if nameX == nameY then Set.insert y else id + (tyCon, args) = splitApps rep + qualified = tyConModule tyCon <> "." <> tyConName tyCon + typeArgument arg@(SomeTypeRep argRep) = case splitApps argRep of + (argCon, _ : _) | isNothing (bracketed argCon) -> + "(" <> qualifiedName arg <> ")" + _ -> qualifiedName arg + -- The constructors of lists & tuples, which bracket their arguments. + bracketed con = case (tyConModule con, tyConName con) of + ("GHC.Types", "List") -> Just "List" + ("GHC.Tuple", name) | name == "Unit" || "Tuple" `isPrefixOf` name -> + Just name + _ -> Nothing + +{- | `Tried` grammar combinators mark subgrammars to backtrack +upon failure, by `try`, in a predictive parser, +like t'Data.Profunctor.Grammar.Parsector.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 +-} +class Tried p where + + {- | Backtracking upon failure. -} + try :: p -> p + try = id + +{- | The `Alternator`s of `terminal` symbols, `Tokenized` combinators +& `tokenClass`es, which are `Tried`, & run +@Control.Lens.Grammar.RegGrammar@s. -} +type RegGrammatical token p = + ( 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) + ) :: Constraint + +{- | The `RegGrammatical` `BackusNaurForm`s, which run `Grammar`s. -} +type Grammatical token p = + ( RegGrammatical token p + , forall x y. BackusNaurForm (p x y) + ) :: Constraint + +{- | The `Grammatical` `Filtrator`s, `MonadPlus`es & `MonadFail`s, +which run `CtxGrammar`s. -} +type CtxGrammatical token p = + ( Grammatical token p + , Filtrator p + , forall x. MonadPlus (p x) + , forall x. MonadFail (p x) + ) :: Constraint + -- instances -instance (Ord rule, NonTerminalSymbol rule) - => BackusNaurForm (Bnf rule) where - rule label (Bnf newRule oldRules) = (nonTerminal label) - {rulesBnf = Set.insert (label, newRule) oldRules} - ruleRec label f = rule label (f (nonTerminal label)) +instance (forall x. Ruled (f x)) => Ruled (Joker f a b) where + rule name = Joker . rule name . runJoker instance (forall x. BackusNaurForm (f x)) => BackusNaurForm (Joker f a b) where - rule name = Joker . rule name . runJoker ruleRec name = Joker . ruleRec name . dimap Joker runJoker +instance (forall x. Tried (f x)) => Tried (Joker f a b) where + try = Joker . try . runJoker +instance Ruled (ReadP a) instance BackusNaurForm (ReadP a) -instance (Ord rule, TerminalSymbol token rule) - => TerminalSymbol token (Bnf rule) where - terminal = liftBnf0 . terminal -instance (Ord rule, NonTerminalSymbol rule) - => NonTerminalSymbol (Bnf rule) where - nonTerminal = liftBnf0 . nonTerminal -instance (Ord rule, Tokenized token rule) - => Tokenized token (Bnf rule) where - anyToken = liftBnf0 anyToken - token = liftBnf0 . token - oneOf = liftBnf0 . oneOf - notOneOf = liftBnf0 . notOneOf - asIn = liftBnf0 . asIn - notAsIn = liftBnf0 . notAsIn -instance (Ord rule, TokenAlgebra token rule) - => TokenAlgebra token (Bnf rule) where - tokenClass = liftBnf0 . tokenClass -instance (Ord rule, KleeneStarAlgebra rule) - => KleeneStarAlgebra (Bnf rule) where - starK = liftBnf1 starK - plusK = liftBnf1 plusK - optK = liftBnf1 optK -instance (Ord rule, DisjunctiveMonoid rule) - => DisjunctiveMonoid (Bnf rule) where - falseP = liftBnf0 falseP - (>|<) = liftBnf2 (>|<) -instance (Ord rule, Monoid rule) => Monoid (Bnf rule) where - mempty = liftBnf0 mempty -instance (Ord rule, Semigroup rule) => Semigroup (Bnf rule) where - (<>) = liftBnf2 (<>) +instance Tried (ReadP a) +instance Ruled (ReadPrec a) +instance BackusNaurForm (ReadPrec a) +instance Tried (ReadPrec a) diff --git a/distributors-grammar/src/Control/Lens/Grammar/Class.hs b/distributors-grammar/src/Control/Lens/Grammar/Class.hs new file mode 100644 index 00000000..046125e8 --- /dev/null +++ b/distributors-grammar/src/Control/Lens/Grammar/Class.hs @@ -0,0 +1,84 @@ +{- | +Module : Control.Lens.Grammar.Class +Description : grammar classes & numerals +Copyright : (C) 2026 - Eitan Chatav +License : BSD-style (see the file LICENSE) +Maintainer : Eitan Chatav +Stability : provisional +Portability : non-portable + +The classes of types' grammars, over their tokens, regular, context-free +& context-sensitive, & numerals, by their digits. Haskell types' grammars, +equivalent to their `Read` & `Show` instances, are in +"Control.Lens.Grammar.Prec". +-} + +module Control.Lens.Grammar.Class + ( RegGrammar (..) + , Grammar (..) + , CtxGrammar (..) + -- * Numerals + , digit + , numeral + ) where + +import Control.Lens +import Control.Lens.PartialIso +import Control.Lens.Grammar.BackusNaur +import Control.Lens.Grammar.Token +import Data.Char (isDigit, isLetter, ord, toLower, toUpper) +import Data.Profunctor.Distributor + +-- $setup +-- >>> import Control.Lens.Grammar + +{- | A type's regular grammar, over its tokens, which is also its +context-free & context-sensitive grammar. -} +class Grammar token a => RegGrammar token a where + regGrammar :: RegGrammatical token p => p a a + +{- | A type's context-free grammar, over its tokens, which is also its +context-sensitive grammar; its regular grammar, by default. -} +class CtxGrammar token a => Grammar token a where + grammar :: Grammatical token p => p a a + default grammar :: (RegGrammar token a, Grammatical token p) => p a a + grammar = regGrammar @token + +{- | A type's context-sensitive grammar, over its tokens; +its context-free grammar, by default. -} +class CtxGrammar token a where + ctxGrammar :: CtxGrammatical token p => p a a + default ctxGrammar :: (Grammar token a, CtxGrammatical token p) => p a a + ctxGrammar = grammar @token + +{- | 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] +-} +digit :: (Integral n, Choice p, Tokenized Char (p Char Char)) => n -> p n n +digit base = prism' valueOf charOf >? oneOf chars + where + values = take (fromIntegral base) (['0' .. '9'] <> ['a' .. 'z']) + chars = values <> [toUpper c | c <- values, isLetter c] + valueOf c + | isDigit c = fromIntegral (ord c - ord '0') + | otherwise = fromIntegral (ord (toLower c) - ord 'a' + 10) + charOf d + | 0 <= d && d < base = Just (values !! fromIntegral d) + | otherwise = Nothing + +{- | 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) 255 +Just "ff" +-} +numeral :: (Integral n, Alternator p, Tokenized Char (p Char Char)) => n -> p n n +numeral base = iso digitsOf (foldl' (\n d -> n * base + d) 0) >~ someP (digit base) + where + digitsOf n + | n < base = [n] + | otherwise = let (q, r) = n `quotRem` base in digitsOf q <> [r] diff --git a/distributors-grammar/src/Control/Lens/Grammar/Machine.hs b/distributors-grammar/src/Control/Lens/Grammar/Machine.hs index d2f702bb..99331c24 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/Machine.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/Machine.hs @@ -23,7 +23,6 @@ module Control.Lens.Grammar.Machine import Control.Lens import Control.Lens.Extras -import Control.Lens.Grammar.BackusNaur import Control.Lens.Grammar.RegEx import Control.Lens.Grammar.Token import Data.Foldable @@ -124,6 +123,8 @@ transducer (Bnf start rules) = Transducer KleeneStar _ -> True KleeneOpt _ -> True KleenePlus x -> rexNullable nm x + KleeneTimes lo _ x -> lo == 0 || rexNullable nm x + Backtracking x -> rexNullable nm x RegExam (Alternate x y zs) -> any (rexNullable nm) (x : y : zs) RegExam (OneOf _) -> False RegExam (NotOneOf _ _) -> False @@ -209,6 +210,9 @@ transducer (Bnf start rules) = Transducer (firsts, states, nextId', bypass) = thompson rex0 nextId (firsts <> dests) in (firsts, states, nextId', bypass) + Backtracking rex0 -> thompson rex0 nextId dests + -- counts unroll, growing the machine by them + KleeneTimes lo hi rex0 -> thompson (unrolled lo hi rex0) nextId dests RegExam (OneOf chars) | Set.null chars -> (IntSet.empty, [], nextId, False) | otherwise -> @@ -562,3 +566,16 @@ closeChartAt et j initialChart0 = loop initialWork initialChart0 IntMap.empty eJ' = IntMap.insert state (IntSet.insert origin os) eJ acc' = IntMap.insert j eJ' acc in (acc', (state, origin) : new) + +-- | Counts, unrolled, @x{lo,hi}@ as @lo@ times @x@ & then +-- @x*@, or @hi - lo@ nested options. +unrolled :: Int -> Maybe Int -> RegEx token -> RegEx token +unrolled lo hi x = joined (replicate lo x <> [rest]) + where + rest = case hi of + Nothing -> KleeneStar x + Just m -> foldr (\_ r -> KleeneOpt (joined [x, r])) SeqEmpty [lo + 1 .. m] + joined items = case filter (\case SeqEmpty -> False; _ -> True) items of + [] -> SeqEmpty + [item] -> item + item0 : item1 : items' -> Sequence item0 item1 items' diff --git a/distributors-grammar/src/Control/Lens/Grammar/Prec.hs b/distributors-grammar/src/Control/Lens/Grammar/Prec.hs new file mode 100644 index 00000000..6ed24e63 --- /dev/null +++ b/distributors-grammar/src/Control/Lens/Grammar/Prec.hs @@ -0,0 +1,768 @@ +{-# LANGUAGE CPP #-} +{- | +Module : Control.Lens.Grammar.Prec +Description : grammars of Haskell types, as Read & Show +Copyright : (C) 2026 - Eitan Chatav +License : BSD-style (see the file LICENSE) +Maintainer : Eitan Chatav +Stability : provisional +Portability : non-portable + +Grammars of Haskell types, equivalent to their stock `Read` & `Show` +instances, by precedence, as `Text.ParserCombinators.ReadPrec` reads, & +`showsPrec` shows: `PrecGrammar`s, run by `PrecGrammatical`s, like +t'Precedence', which `readsPrecG` & `showsPrecG` run. +-} + +module Control.Lens.Grammar.Prec + ( -- * PrecGrammar + PrecGrammar (..) + , PrecGrammatical (..) + , precParens + , precList + -- * NotFollowedBy + , NotFollowedBy (..) + , eof + , munch + , munch1 + , skipSpaces + -- * Precedence + , Precedence (..) + , precG + , readsPrecG + , showsPrecG + ) where + +import Control.Applicative +import Control.Monad ((>=>)) +import Control.Lens +import Control.Lens.Diopter (skippedMany) +import Control.Lens.Grammar.BackusNaur +import Control.Lens.Grammar.Class +import Control.Lens.Grammar.RegEx +import Control.Lens.Grammar.Symbol +import Control.Lens.Grammar.Token +import Control.Lens.PartialIso +import Control.Lens.Prismoid ((>?*)) +import Data.Char (isDigit, isLetter, toUpper) +import Data.Int (Int8, Int16, Int32, Int64) +import Data.List (nub) +import Data.Maybe (isJust) +import Data.Monoid.Disjunctive +import Data.Profunctor.Distributor +import Data.Profunctor.Grammar +import Data.Profunctor.Monoidal +import Data.Profunctor.Monoidal.Cocartesian +import Data.Ratio ((%)) +import Data.String (IsString (..)) +import Data.Word (Word8, Word16, Word32, Word64) +import Data.Proxy (Proxy (..)) +import GHC.Generics hiding (from, to) +import qualified GHC.Generics as Generic +import Numeric (floatToDigits) +import Numeric.Natural (Natural) + +{- | A Haskell type's grammar, by precedence, equivalent to its stock `Read` +& `Show` instances, `readsPrec` & `showsPrec`. -} +class PrecGrammar a where + precGrammar :: PrecGrammatical p => p a a + default precGrammar + :: (Generic a, GPrecSum (Rep a), PrecGrammatical p) => p a a + precGrammar = iso Generic.from Generic.to >~ precParens gPrecSum + {- | Lists of the type, as `readListPrec` & `showList`, in brackets, by + `precList`, by default, & strings, for `Char`. -} + precListGrammar :: PrecGrammatical p => p [a] [a] + precListGrammar = precList precGrammar + +{- | `Grammatical` interpreters of precedence, as +`Text.ParserCombinators.ReadPrec` has, where a grammar runs in a +precedence context, from 0 to 11, as `showsPrec`'s is. -} +class + ( Grammatical Char p, NotFollowedBy p + , forall x y. (x ~ (), y ~ ()) => IsString (p x y) ) + => PrecGrammatical p where + {- | At a precedence, failing in a context above it, as + `Text.ParserCombinators.ReadPrec.prec` does. -} + precP :: Int -> p a b -> p a b + {- | In a context one higher, for arguments, as + `Text.ParserCombinators.ReadPrec.step` does. -} + precStep :: p a b -> p a b + {- | In the context 0, within brackets, as + `Text.ParserCombinators.ReadPrec.reset` does. -} + precReset :: p a b -> p a b + {- | By the context's precedence. -} + precWith :: (Int -> p a b) -> p a b + +{- | Within any parentheses, after whitespace, as `GHC.Read.parens` reads, +& within parentheses where it doesn't print bare, as `showParen` shows. -} +precParens :: PrecGrammatical p => p a b -> p a b +precParens p = skipSpaces >* precParenthesized p + +{- Bare, or within parentheses, without leading whitespace, so that no two +places skip the same whitespace, which `read` skips once, greedily. -} +precParenthesized :: PrecGrammatical p => p a b -> p a b +precParenthesized p = p >|< terminal "(" >* precReset (precParens p) *< skipSpaces *< terminal ")" + +{- | A list, in brackets, its items separated by commas, after whitespace, +at precedence 0, within any parentheses, as `GHC.Read.list` reads & +`showList` shows. -} +precList :: PrecGrammatical p => p a a -> p [a] [a] +precList = precParens . precBrackets + +-- Items in brackets, separated by commas, after whitespace, at precedence 0. +precBrackets :: PrecGrammatical p => p a a -> p [a] [a] +precBrackets x = terminal "[" >* orP + [ _Empty >? oneP + , _Cons >? precReset x >*< manyP (skipSpaces >* terminal "," >* precReset x) + ] *< skipSpaces *< terminal "]" + +{- | Negative lookahead, as `read`'s lexer munches lexemes maximally. -} +class NotFollowedBy p where + {- | Not followed by a string a pattern matches, consuming nothing, & + printing nothing; nonterminals match nothing. -} + notFollowedBy :: RegEx Char -> p () () +instance (Alternative f, Cons s s Char Char) => NotFollowedBy (Parsor s f) where + notFollowedBy rex = Parsor $ \mode s -> case mode of + Nothing | not (null (prefixes rex (0 :: Int, s))) -> empty + _ -> pure ((), s) + where + -- the rests after each prefix a pattern matches, counting tokens, + -- so that repetitions of empty matches end + prefixes = \case + SeqEmpty -> pure + Sequence x y zs -> foldr ((>=>) . prefixes) pure (x : y : zs) + NonTerminal _ -> const [] + KleeneStar x -> star x + KleeneOpt x -> upTo 1 x + KleenePlus x -> prefixes x >=> star x + KleeneTimes lo hi x -> foldr (>=>) pure (replicate lo (prefixes x)) + >=> maybe (star x) (\m -> upTo (m - lo) x) hi + Backtracking x -> prefixes x + RegExam (Alternate x y zs) -> + \pos -> concatMap (`prefixes` pos) (x : y : zs) + RegExam (OneOf toks) -> one (TokenClass (OneOf toks)) + RegExam (NotOneOf toks test) -> one (TokenClass (NotOneOf toks test)) + one cls (n, str) = case uncons str of + Just (c, str') | tokenClass cls c -> [(n + 1, str')] + _ -> [] + star x pos = pos : + [end | pos' <- prefixes x pos, fst pos' > fst pos, end <- star x pos'] + upTo m x pos + | m <= 0 = [pos] + | otherwise = pos : (prefixes x pos >>= upTo (m - 1) x) +instance Applicative f => NotFollowedBy (Printor s f) where + notFollowedBy _ = Printor (\_ -> pure ((), id)) +instance NotFollowedBy p => NotFollowedBy (Precedence p) where + notFollowedBy = Precedence . const . notFollowedBy + +{- | At the end of input, not followed by any token. -} +eof :: NotFollowedBy p => p () () +eof = notFollowedBy anyToken + +{- | Tokens of a class, as many as follow, as +`Text.ParserCombinators.ReadP.munch` parses, & printing them. -} +munch + :: (RegGrammatical Char p, NotFollowedBy p) + => TokenClass Char -> p String String +munch cls = manyP (tokenClass cls) *< notFollowedBy (tokenClass cls) + +{- | Tokens of a class, one or more, as many as follow, as +`Text.ParserCombinators.ReadP.munch1` parses, & printing them. -} +munch1 + :: (RegGrammatical Char p, NotFollowedBy p) + => TokenClass Char -> p String String +munch1 cls = someP (tokenClass cls) *< notFollowedBy (tokenClass cls) + +{- | Whitespace, by `Data.Char.isSpace`, as many as follow, as +`Text.ParserCombinators.ReadP.skipSpaces` parses, & printing none. -} +skipSpaces :: (RegGrammatical Char p, NotFollowedBy p) => p () () +skipSpaces = dimap (const "") (const ()) (munch precSpaceClass) + +{- | A grammar in a precedence context, a `PrecGrammatical` interpreter of +any `Grammatical` one, each of whose structures it lifts pointwise. -} +newtype Precedence p a b = Precedence {runPrecedence :: Int -> p a b} + +instance Profunctor p => Profunctor (Precedence p) where + dimap f g (Precedence h) = Precedence (dimap f g . h) +instance Functor (p a) => Functor (Precedence p a) where + fmap f (Precedence h) = Precedence (fmap f . h) +instance Applicative (p a) => Applicative (Precedence p a) where + pure x = Precedence (const (pure x)) + Precedence f <*> Precedence x = Precedence (\d -> f d <*> x d) +instance Alternative (p a) => Alternative (Precedence p a) where + empty = Precedence (const empty) + Precedence x <|> Precedence y = Precedence (\d -> x d <|> y d) + many (Precedence x) = Precedence (many . x) + some (Precedence x) = Precedence (some . x) +instance Choice p => Choice (Precedence p) where + left' (Precedence h) = Precedence (left' . h) + right' (Precedence h) = Precedence (right' . h) +instance DisjunctiveMonoid (p a b) => DisjunctiveMonoid (Precedence p a b) where + falseP = Precedence (const falseP) + Precedence x >|< Precedence y = Precedence (\d -> x d >|< y d) +instance CocartesianMonoidal p => CocartesianMonoidal (Precedence p) where + zeroP = Precedence (const zeroP) + Precedence x >+< Precedence y = Precedence (\d -> x d >+< y d) +instance CocartesianChoice p => CocartesianChoice (Precedence p) where + alternate = \case + Left (Precedence x) -> Precedence (alternate . Left . x) + Right (Precedence y) -> Precedence (alternate . Right . y) +instance Distributor p => Distributor (Precedence p) where + optionalP (Precedence x) = Precedence (optionalP . x) + manyP (Precedence x) = Precedence (manyP . x) +instance Alternator p => Alternator (Precedence p) where + someP (Precedence x) = Precedence (someP . x) + optionP def (Precedence x) = Precedence (optionP def . x) + manyTillP (Precedence x) (Precedence y) = Precedence (\d -> manyTillP (x d) (y d)) + quantP lo hi (Precedence x) = Precedence (quantP lo hi . x) +instance TerminalSymbol token (p a b) => TerminalSymbol token (Precedence p a b) where + terminal = Precedence . const . terminal +instance Tokenized token (p a b) => Tokenized token (Precedence p a b) where + anyToken = Precedence (const anyToken) + token = Precedence . const . token + oneOf = Precedence . const . oneOf + notOneOf = Precedence . const . notOneOf + asIn = Precedence . const . asIn + notAsIn = Precedence . const . notAsIn +instance TokenAlgebra token (p a b) => TokenAlgebra token (Precedence p a b) where + tokenClass = Precedence . const . tokenClass +instance Tried (p a b) => Tried (Precedence p a b) where + try (Precedence x) = Precedence (try . x) +instance Ruled (p a b) => Ruled (Precedence p a b) where + rule name (Precedence x) = Precedence (rule name . x) +instance BackusNaurForm (p a b) => BackusNaurForm (Precedence p a b) +instance (a ~ (), b ~ (), TerminalSymbol Char (p () ())) + => IsString (Precedence p a b) where + fromString = Precedence . const . terminal +instance (Grammatical Char p, NotFollowedBy p) + => PrecGrammatical (Precedence p) where + precP n (Precedence x) = Precedence (\d -> if d <= n then x n else falseP) + precStep (Precedence x) = Precedence (x . (+ 1)) + precReset (Precedence x) = Precedence (const (x 0)) + precWith k = Precedence (\d -> runPrecedence (k d) d) + +{- | A type's `PrecGrammar` at a precedence, at any `Grammatical` +interpreter which parses or prints. -} +precG :: forall a p. (PrecGrammar a, Grammatical Char p, NotFollowedBy p) => Int -> p a a +precG = runPrecedence precGrammar + +{- | Read at a precedence, as `readsPrec` does. -} +readsPrecG :: forall a. PrecGrammar a => Int -> ReadS a +readsPrecG d = parseP (precG d :: Parsor String [] a a) + +{- | Show at a precedence, as `showsPrec` does, if it shows. -} +showsPrecG :: forall a. PrecGrammar a => Int -> a -> Maybe ShowS +showsPrecG d = printP (precG d :: Printor String Maybe a a) + +-- Base types -- + +{- The base types' grammars, equivalent to their `Read` & `Show` +instances: lexemes, within any parentheses, as `read` accepts them, & +negative numbers, which `showsPrec` parenthesizes above 6, & `read` +accepts bare at any precedence. -} + +instance PrecGrammar Char where + precGrammar = precParens precChar + -- strings, or brackets, as `read` reads, & strings, as `show` shows + precListGrammar = precParens (precString >|< precParenthesized (precBrackets precGrammar)) +instance PrecGrammar a => PrecGrammar [a] where + precGrammar = precListGrammar +instance PrecGrammar Bool +instance PrecGrammar Ordering +instance PrecGrammar a => PrecGrammar (Maybe a) +instance (PrecGrammar a, PrecGrammar b) => PrecGrammar (Either a b) +instance PrecGrammar () where + precGrammar = precParens (terminal "(" >* skipSpaces *< terminal ")") +instance (PrecGrammar a, PrecGrammar b) => PrecGrammar (a, b) where + precGrammar = precTupled (precItem >*< precComma >* precItem) +instance (PrecGrammar a, PrecGrammar b, PrecGrammar c) => PrecGrammar (a, b, c) where + precGrammar = precTupled $ iso (\(a, b, c) -> (a, (b, c))) (\(a, (b, c)) -> (a, b, c)) + >~ precItem >*< precComma >* precItem >*< precComma >* precItem +instance (PrecGrammar a, PrecGrammar b, PrecGrammar c, PrecGrammar d) + => PrecGrammar (a, b, c, d) where + precGrammar = precTupled $ iso + (\(a, b, c, d) -> (a, (b, (c, d)))) (\(a, (b, (c, d))) -> (a, b, c, d)) + >~ precItem >*< precComma >* precItem >*< precComma >* precItem >*< precComma >* precItem +instance (PrecGrammar a, PrecGrammar b, PrecGrammar c, PrecGrammar d, PrecGrammar e) + => PrecGrammar (a, b, c, d, e) where + precGrammar = precTupled $ iso + (\(a, b, c, d, e) -> (a, (b, (c, (d, e))))) + (\(a, (b, (c, (d, e)))) -> (a, b, c, d, e)) + >~ precItem >*< precComma >* precItem >*< precComma >* precItem >*< precComma >* precItem + >*< precComma >* precItem + +-- A tuple, within parentheses, its items at precedence 0, as `read`'s +-- @wrap_tup@ reads & `show` shows. +precTupled :: PrecGrammatical p => p a a -> p a a +precTupled items' = precParens (terminal "(" >* items' *< skipSpaces *< terminal ")") + +precItem :: (PrecGrammar a, PrecGrammatical p) => p a a +precItem = precReset precGrammar + +precComma :: PrecGrammatical p => p () () +precComma = skipSpaces >* terminal "," + +-- Generics -- + +{- A sum of constructors, as derived `Read` & `Show` instances read & show +them, by `GHC.Generics`. -} +class GPrecSum f where + gPrecSum :: PrecGrammatical p => p (f x) (f x) +instance GPrecSum f => GPrecSum (M1 D c f) where + gPrecSum = iso unM1 M1 >~ gPrecSum +instance (GPrecSum f, GPrecSum g) => GPrecSum (f :+: g) where + gPrecSum = iso + (\case L1 x -> Left x; R1 y -> Right y) + (either L1 R1) + >~ gPrecSum >+< gPrecSum +instance GPrecSum V1 where + gPrecSum = falseP +instance (Constructor c, GPrecFields f) => GPrecSum (M1 C c f) where + gPrecSum = iso unM1 M1 >~ case conFixity con of + Infix _ n -> precP n (gPrecFields (InfixFields (precOperator name))) + Prefix + | conIsRecord con -> precWith $ \d -> + let body = precName name >* precSpaced >* terminal "{" >* skipSpaces + >* gPrecFields RecordFields *< skipSpaces *< terminal "}" + in if d <= 10 then body else if d == 11 then precUnprinted >? body else falseP + | gArity (Proxy @f) == 0 -> precName name >* gPrecFields PrefixFields + | otherwise -> precP 10 (precName name >* gPrecFields PrefixFields) + where + con = undefined :: M1 C c f () + name = conName con + +-- How a constructor's fields are written. +data FieldsStyle p + = PrefixFields + | BareField + | RecordFields + | InfixFields (p () ()) + +{- The fields of a constructor: prefix, after spaces, at the next precedence; +in records, named, at precedence 0, separated by commas; or infix, about an +operator, at the next precedence. -} +class GPrecFields f where + gPrecFields :: PrecGrammatical p => FieldsStyle p -> p (f x) (f x) + gArity :: Proxy f -> Int +instance GPrecFields U1 where + gPrecFields _ = iso (const ()) (const U1) >~ oneP + gArity _ = 0 +instance (GPrecFields f, GPrecFields g) => GPrecFields (f :*: g) where + gPrecFields style = iso (\(x :*: y) -> (x, y)) (uncurry (:*:)) >~ case style of + RecordFields -> + gPrecFields RecordFields >*< skipSpaces >* terminal "," >* precSpaced >* gPrecFields RecordFields + InfixFields operator -> gPrecFields BareField >*< operator >* gPrecFields BareField + _ -> gPrecFields style >*< gPrecFields style + gArity _ = gArity (Proxy @f) + gArity (Proxy @g) +instance (Selector s, PrecGrammar a) => GPrecFields (M1 S s (K1 R a)) where + gPrecFields style = iso (unK1 . unM1) (M1 . K1) >~ case style of + RecordFields -> precName field >* precSpaced >* precSymbol "=" >* precSpace >* precReset precGrammar + BareField -> precStep precGrammar + _ -> precSpace >* precStep precGrammar + where + field = selName (undefined :: M1 S s (K1 R a) ()) + gArity _ = 1 + +-- A name, an identifier, or a symbol within parentheses. +precName :: PrecGrammatical p => String -> p () () +precName name + | precSymbolic name = + terminal "(" >* skipSpaces >* precSymbol name *< skipSpaces *< terminal ")" + | otherwise = precIdent name + +-- An infix operator, a symbol, or an identifier within backquotes. +precOperator :: PrecGrammatical p => String -> p () () +precOperator name + | precSymbolic name = precSpaced >* precSymbol name >* precSpace + | otherwise = precSpaced >* terminal "`" >* skipSpaces >* precIdent name + *< skipSpaces *< terminal "`" >* precSpace + +precSymbolic :: String -> Bool +precSymbolic = \case + c : _ -> c == ':' || tokenClass precSymbolClass c + [] -> False +instance PrecGrammar Natural where precGrammar = precParens precNatural +instance PrecGrammar Integer where + precGrammar = precParens (precWith (\d -> precSigned >~ precNegativeAt d >*< precMagnitude)) +instance PrecGrammar Double where precGrammar = precParens (precWith precFloating) +instance PrecGrammar Float where precGrammar = precParens (precWith precFloating) +instance PrecGrammar Int where precGrammar = precIntegral +instance PrecGrammar Int8 where precGrammar = precIntegral +instance PrecGrammar Int16 where precGrammar = precIntegral +instance PrecGrammar Int32 where precGrammar = precIntegral +instance PrecGrammar Int64 where precGrammar = precIntegral +instance PrecGrammar Word where precGrammar = precIntegral +instance PrecGrammar Word8 where precGrammar = precIntegral +instance PrecGrammar Word16 where precGrammar = precIntegral +instance PrecGrammar Word32 where precGrammar = precIntegral +instance PrecGrammar Word64 where precGrammar = precIntegral + +-- Sized integers read as `Integer`s, wrapping out of range, as `read` does. +precIntegral :: (Integral a, PrecGrammatical p) => p a a +precIntegral = iso toInteger fromInteger >~ precGrammar @Integer + +-- A minus, printing bare up to precedence 6, & parsing bare at any. +precNegativeAt :: (RegGrammatical Char p, NotFollowedBy p) => Int -> p Bool Bool +precNegativeAt d + | d <= 6 = precNegative + | otherwise = orP + [ only False >? oneP + , only True . precUnprinted >? terminal "-" >* skipSpaces ] + +-- A prism which never matches, so that its alternative parses, but never prints. +precUnprinted :: Prism' a a +precUnprinted = prism' id (const Nothing) + +-- One of two terminals, printing the first, & parsing either. +precEitherOf :: RegGrammatical Char p => String -> String -> p () () +precEitherOf printed parsed = terminal printed >|< (precUnprinted >? terminal parsed) + +-- A minus, a lexeme of its own, as whether a number is negative. +precNegative :: (RegGrammatical Char p, NotFollowedBy p) => p Bool Bool +precNegative = iso (\b -> if b then Just () else Nothing) isJust + >~ optionalP (terminal "-" >* skipSpaces) + +-- Whitespace, by `Data.Char.isSpace`. +precSpaceClass :: TokenClass Char +precSpaceClass = oneOf "\t\n\v\f\r" >|< asIn Space + +-- A token of a class, as unit, for lookahead. +precToken :: RegGrammatical Char p => TokenClass Char -> p () () +precToken cls = dimap (const ' ') (const ()) (tokenClass cls) + +-- The digits of a base, in either case. +precDigitClass :: Int -> TokenClass Char +precDigitClass base = oneOf (concat + [ [c, toUpper c] | c <- take base (['0' .. '9'] <> ['a' .. 'z']) ]) + +-- Identifiers' & symbols' characters, which `read`'s lexer munches. +precIdfClass, precSymbolClass :: TokenClass Char +precIdfClass = anyP asIn + [ UppercaseLetter, LowercaseLetter, TitlecaseLetter, ModifierLetter + , OtherLetter, DecimalNumber, LetterNumber, OtherNumber ] + >|< oneOf "_'" +precSymbolClass = notOneOf ",;()[]{}`" >&< orP + [ anyP asIn [MathSymbol, CurrencySymbol, ModifierSymbol, OtherSymbol, DashPunctuation] + , asIn OtherPunctuation >&< notOneOf "'\"" + , asIn ConnectorPunctuation >&< notOneOf "_" ] + +-- An identifier, & a symbol, munched maximally. +precIdent, precSymbol :: (RegGrammatical Char p, NotFollowedBy p) => String -> p () () +precIdent name = terminal name *< notFollowedBy (tokenClass precIdfClass) +precSymbol name = terminal name *< notFollowedBy (tokenClass precSymbolClass) + +-- A space, where `show` separates lexemes, printing one, & parsing one +-- whitespace character, or none where none follows, the rest of it +-- skipped before the next lexeme. +precSpace :: (RegGrammatical Char p, NotFollowedBy p) => p () () +precSpace = orP + [ terminal " " + , precUnprinted >? precToken (precSpaceClass >&< notOneOf " ") + , precUnprinted >? notFollowedBy (tokenClass precSpaceClass) ] + +-- A space, printing one, & parsing any whitespace. +precSpaced :: (RegGrammatical Char p, NotFollowedBy p) => p () () +precSpaced = precSpace >* skipSpaces + +-- Signed, by an improper iso, where @-0@ parses too. +precSigned :: (Num a, Ord a) => Iso' a (Bool, a) +precSigned = iso + (\n -> (n < 0, abs n)) + (\(negative, n) -> if negative then negate n else n) + +-- A number's lexeme without a fraction or exponent: decimal, printed, +-- or binary, octal or hexadecimal, after @0b@, @0o@ or @0x@, in either +-- case, parsed & tried first, as `read`'s lexer does. Binary is only +-- read from base-4.21 (GHC 9.12) on, as `read`'s lexer only reads it +-- from then. +precMagnitude :: (RegGrammatical Char p, NotFollowedBy p) => p Integer Integer +precMagnitude = (precUnprinted >? try (terminal "0" >* precBased)) + >|< numeral 10 *< precDecimalEnd + +-- Where a decimal integer ends: not before a fraction, nor an exponent. +precDecimalEnd :: (RegGrammatical Char p, NotFollowedBy p) => p () () +precDecimalEnd = notFollowedBy (tokenClass (precDigitClass 10)) + *< precNotFraction *< precNotExponent + +-- Not before a fraction. +precNotFraction :: NotFollowedBy p => p () () +precNotFraction = notFollowedBy (terminal "." <> tokenClass (precDigitClass 10)) + +-- Not before an exponent. +precNotExponent :: NotFollowedBy p => p () () +precNotExponent = notFollowedBy + (oneOf "eE" <> optK (oneOf "+-") <> tokenClass (precDigitClass 10)) + +precBased :: forall p. (RegGrammatical Char p, NotFollowedBy p) => p Integer Integer +precBased = orP + [ +#if MIN_VERSION_base(4,21,0) + precEitherOf "b" "B" >* munched 2, +#endif + precEitherOf "o" "O" >* munched 8 + , precEitherOf "x" "X" >* munched 16 + ] + where + munched :: Int -> p Integer Integer + munched base = numeral (toInteger base) + *< notFollowedBy (tokenClass (precDigitClass base)) + +-- Natural numbers, & negative zero, as `read` reads integers & keeps +-- those which aren't negative. +precNatural :: (RegGrammatical Char p, NotFollowedBy p) => p Natural Natural +precNatural = (iso toInteger fromInteger >~ precMagnitude) + >|< (precUnprinted . only 0 >? terminal "-" >* skipSpaces >* zerosG) + where + zerosG = terminal "0" >* orP + [ zeros *< precDecimalEnd +#if MIN_VERSION_base(4,21,0) + , orP (map terminal ["b", "B"]) >* terminal "0" >* zeros + *< notFollowedBy (tokenClass (precDigitClass 2)) +#endif + , orP (map terminal ["o", "O"]) >* terminal "0" >* zeros + *< notFollowedBy (tokenClass (precDigitClass 8)) + , orP (map terminal ["x", "X"]) >* terminal "0" >* zeros + *< notFollowedBy (tokenClass (precDigitClass 16)) + ] + zeros = skippedMany >?* terminal "0" + +-- A floating point number's lexeme, without its sign. +data FloatLexeme + = NotANumber + | Infinite + -- | digits, a fraction's digits, & an exponent + | Decimal [Int] (Maybe [Int]) (Maybe Integer) + -- | binary, octal or hexadecimal, parsed only + | Based Integer + deriving stock Eq + +_Decimal :: Prism' FloatLexeme ([Int], (Maybe [Int], Maybe Integer)) +_Decimal = prism' (\(ds, (fraction, ex)) -> Decimal ds fraction ex) $ \case + Decimal ds fraction ex -> Just (ds, (fraction, ex)) + _ -> Nothing + +_Based :: Prism' FloatLexeme Integer +_Based = prism' Based $ \case + Based n -> Just n + _ -> Nothing + +{- Floating point numbers, printing as `show` does, by `floatToDigits`, +in fixed notation, or in exponent notation outside @0.1 <= x < 10^7@, & +parsing as `read` does, by `fromRational`, rounding correctly. -} +precFloating :: (RealFloat a, RegGrammatical Char p, NotFollowedBy p) => Int -> p a a +precFloating d = iso precToLexeme precFromLexeme >~ precNegativeAt d >*< orP + [ only NotANumber >? precIdent "NaN" + , only Infinite >? precIdent "Infinity" + , precUnprinted . _Based >? try (terminal "0" >* precBased) + , _Decimal >? digitsG + >*< orP + [ _Just >? terminal "." >* digitsG + , _Nothing >? precNotFraction ] + >*< orP + [ _Just >? precEitherOf "e" "E" >* (precSigned >~ exponentSignG >*< numeral 10 + *< notFollowedBy (tokenClass (precDigitClass 10))) + , _Nothing >? precNotExponent ] + ] + where + digitsG = someP (digit 10) *< notFollowedBy (tokenClass (precDigitClass 10)) + exponentSignG = orP + [ only True >? terminal "-" + , only False . precUnprinted >? terminal "+" + , only False >? oneP + ] + +precToLexeme :: RealFloat a => a -> (Bool, FloatLexeme) +precToLexeme x + | isNaN x = (False, NotANumber) + | isInfinite x = (x < 0, Infinite) + | otherwise = (x < 0 || isNegativeZero x, generic (floatToDigits 10 (abs x))) + where + generic (ds, e) + | e < 0 || e > 7 = case ds of + d : ds'@(_ : _) -> Decimal [d] (Just ds') (Just (toInteger e - 1)) + _ -> Decimal (take 1 ds <> [0 | null ds]) (Just [0]) (Just (toInteger e - 1)) + | otherwise = + let (whole, fraction) = splitAt e (ds <> replicate (e - length ds) 0) + in Decimal (orZero whole) (Just (orZero fraction)) Nothing + orZero ds = if null ds then [0] else ds + +precFromLexeme :: RealFloat a => (Bool, FloatLexeme) -> a +precFromLexeme (negative, lexeme) = (if negative then negate else id) value + where + value = case lexeme of + NotANumber -> 0 / 0 + Infinite -> 1 / 0 + Based n -> fromInteger n + Decimal whole fraction ex -> case ex of + Nothing -> fromRational (rational whole fraction 0) + -- `read` bounds exponents by the type's range, before computing + Just e -> case firstDigit whole fraction of + Nothing -> 0 + Just first + | toInteger first + e > toInteger (snd range + 3) -> 1 / 0 + | toInteger first + e < toInteger (fst range - 3) -> 0 + | otherwise -> fromRational (rational whole fraction e) + range = floatRange value + rational whole fraction e = + let + ds = whole <> concat fraction + scale = e - toInteger (length (concat fraction)) + n = foldl' (\acc d -> acc * 10 + toInteger d) 0 ds + in if scale >= 0 then fromInteger (n * 10 ^ scale) else n % (10 ^ negate scale) + firstDigit whole fraction = case dropWhile (== 0) whole of + significant@(_ : _) -> Just (length significant) + [] -> case span (== 0) (concat fraction) of + (_, []) -> Nothing + (zeros, _) -> Just (negate (length zeros)) + +-- A character's literal, between single quotes. +precChar :: (RegGrammatical Char p, NotFollowedBy p) => p Char Char +precChar = terminal "'" >* precLitChar '\'' *< terminal "'" + +{- A character within a literal, printing as `show` does, by `showLitChar`, +& parsing as `read` does: unescaped, but for @\\@ & the literal's quote; +by a named escape; or by its decimal, octal or hexadecimal code, up to +`maxBound`, or as a control, @\\^@@ to @\\^_@. -} +precLitChar :: (RegGrammatical Char p, NotFollowedBy p) => Char -> p Char Char +precLitChar quote = precRaw [quote] >|< terminal "\\" >* orP + [precFixedEsc True, precDecimalEsc, precOctalEsc, precHexEsc, precControlEsc] + +-- Unescaped, but for @\\@ & some others, printing only printable ASCII. +precRaw :: RegGrammatical Char p => String -> p Char Char +precRaw excluded = tokenClass (oneOf [' ' .. '~'] >&< notOneOf ('\\' : excluded)) + >|< precUnprinted >? tokenClass (notOneOf ('\\' : excluded <> [' ' .. '~'])) + +-- Named escapes, with @SO@ or not. +precFixedEsc :: (RegGrammatical Char p, NotFollowedBy p) => Bool -> p Char Char +precFixedEsc withSO = precEscapes $ + [('\'', "'"), ('\a', "a"), ('\b', "b"), ('\f', "f"), ('\n', "n")] + <> [('\r', "r"), ('\t', "t"), ('\v', "v"), ('\\', "\\"), ('"', "\"")] + <> [e | e@(c, _) <- zip ['\NUL' ..] asciiNames, withSO || c /= '\SO'] + <> [(' ', "SP"), ('\DEL', "DEL")] + where + asciiNames = + [ "NUL", "SOH", "STX", "ETX", "EOT", "ENQ", "ACK", "BEL" + , "BS", "HT", "LF", "VT", "FF", "CR", "SO", "SI" + , "DLE", "DC1", "DC2", "DC3", "DC4", "NAK", "SYN", "ETB" + , "CAN", "EM", "SUB", "ESC", "FS", "GS", "RS", "US" ] + +-- Codes up to `maxBound`, decimal, printing above @\\DEL@, octal & hexadecimal. +precDecimalEsc, precOctalEsc, precHexEsc :: RegGrammatical Char p => p Char Char +precDecimalEsc = prism' toEnum (\c -> if c > '\DEL' then Just (fromEnum c) else Nothing) + >? precBoundedNumeral 10 (fromEnum (maxBound :: Char)) +precOctalEsc = precUnprinted . prism' toEnum (Just . fromEnum) + >? precEitherOf "o" "O" >* precBoundedNumeral 8 (fromEnum (maxBound :: Char)) +precHexEsc = precUnprinted . prism' toEnum (Just . fromEnum) + >? precEitherOf "x" "X" >* precBoundedNumeral 16 (fromEnum (maxBound :: Char)) +precControlEsc :: RegGrammatical Char p => p Char Char +precControlEsc = precUnprinted . iso (\c -> toEnum (fromEnum c + 64)) (\c -> toEnum (fromEnum c - 64)) + >? terminal "^" >* tokenClass (oneOf ['@' .. '_']) + +-- A string literal's items: characters, & empty escapes. +data StrItem = StrChar Char | StrEmpty + deriving stock Eq + +_StrChar :: Prism' StrItem Char +_StrChar = prism' StrChar $ \case + StrChar c -> Just c + StrEmpty -> Nothing + +{- A string's literal, between double quotes, printing as `show` does, by +`showLitString`, with an empty escape, @\\&@, after a numeric escape +before a digit, or after @\\SO@ before @H@, & parsing as `read` does, with +empty escapes, & gaps, @\\@, whitespace & @\\@, anywhere, an improper iso, +& with numeric escapes' digits & @\\SOH@ maximally munched, as `read`'s +lexer does, so that an escape is never followed by what would continue it. -} +precString :: forall p. (RegGrammatical Char p, NotFollowedBy p) => p String String +precString = iso items (\xs -> [c | StrChar c <- xs]) + >~ terminal "\"" >* free *< terminal "\"" + where + -- items, after which a character mustn't continue the last escape + free, afterDecimal, afterOctal, afterHex, afterSO :: p [StrItem] [StrItem] + free = itemsG "" + afterDecimal = itemsG ['0' .. '9'] + afterOctal = itemsG ['0' .. '7'] + afterHex = itemsG (['0' .. '9'] <> ['a' .. 'f'] <> ['A' .. 'F']) + afterSO = itemsG "H" + itemsG :: String -> p [StrItem] [StrItem] + itemsG continuing = orP + [ _Empty >? oneP + , itemThen emptyG free + , itemThen (_StrChar >? precRaw ('"' : continuing)) free + , itemThen (_StrChar >? terminal "\\" >* orP [precFixedEsc False, precControlEsc]) free + , itemThen (_StrChar . only '\SO' >? terminal "\\SO") afterSO + , itemThen (_StrChar >? terminal "\\" >* precDecimalEsc) afterDecimal + , itemThen (_StrChar >? terminal "\\" >* precOctalEsc) afterOctal + , itemThen (_StrChar >? terminal "\\" >* precHexEsc) afterHex + ] + itemThen :: p StrItem StrItem -> p [StrItem] [StrItem] -> p [StrItem] [StrItem] + itemThen item rest = _Cons >? item >*< rest + emptyG :: p StrItem StrItem + emptyG = only StrEmpty >? (terminal "\\&" >|< precUnprinted >? terminal "\\" + >* dimap (const ' ') (const ()) (tokenClass (oneOf "\t\n\v\f\r" >|< asIn Space)) + >* skipSpaces *< terminal "\\") + items = \case + c : cs@(c' : _) | protected c c' -> StrChar c : StrEmpty : items cs + c : cs -> StrChar c : items cs + [] -> [] + protected c c' = (c > '\DEL' && isDigit c') || (c == '\SO' && c' == 'H') + +-- Escapes by fixed strings, as a trie, which is LL(1), maximally munched, +-- like @\\SO@ & @\\SOH@, each character printing by its first string. +precEscapes :: (RegGrammatical Char p, NotFollowedBy p) => [(Char, String)] -> p Char Char +precEscapes escapes = orP $ + [only c >? oneP | (c, "") <- take 1 [e | e@(_, "") <- escapes]] + <> [ terminal [first] >* precEscapes [(c, rest) | (c, x : rest) <- escapes, x == first] + | first <- nub [x | (_, x : _) <- escapes] ] + +{- A natural number in a base, up to a bound, with leading zeros, which +parse, as `read`'s lexer does, but don't print; a regular grammar, by the +bound's digits, so that a number beyond it fails to parse. -} +precBoundedNumeral :: forall n p. (Integral n, RegGrammatical Char p) => n -> n -> p n n +precBoundedNumeral base bound + = (precUnprinted >? try (terminal "0" >* zerosG >* positiveG)) + >|< (only 0 >? terminal "0" >* zerosG) + >|< positiveG + where + zerosG :: p () () + zerosG = skippedMany >?* terminal "0" + width :: Int + width = length (takeWhile (<= bound) (iterate (* base) 1)) + -- without leading zeros, by their number of digits, tried longest first + positiveG :: p n n + positiveG = orP $ + try (ranged (base ^ (width - 1)) bound (upTo width bound True)) + : [ try $ ranged (base ^ (j - 1)) (base ^ j - 1) + (headed [1 .. base - 1] (j - 1) (exactly' (j - 1))) + | j <- [width - 1, width - 2 .. 1] ] + ranged :: n -> n -> p n n -> p n n + ranged lo hi = (prism' id (\n -> if lo <= n && n <= hi then Just n else Nothing) >?) + -- a first digit, & the rest of so many digits + headed :: [n] -> Int -> p n n -> p n n + headed firsts rest restG = orP + [ prism' (\r -> d * base ^ rest + r) + (\n -> if n `div` base ^ rest == d then Just (n `mod` base ^ rest) else Nothing) + >? digitIs d >* restG + | d <- firsts ] + -- exactly so many digits, any + exactly' :: Int -> p n n + exactly' k = iso (\n -> [n `div` base ^ i `mod` base | i <- [k - 1, k - 2 .. 0]]) + (foldl' (\acc d -> acc * base + d) 0) >~ replicateP k (digit base) + -- so many digits, up to a bound, the first nonzero when leading + upTo :: Int -> n -> Bool -> p n n + upTo 0 _ _ = only 0 >? oneP + upTo k hi leading = + let + w = base ^ (k - 1) + top = hi `div` w + lowers = [if leading then 1 else 0 .. top - 1] + in + headed lowers (k - 1) (exactly' (k - 1)) + >|< (prism' (\r -> top * w + r) + (\n -> if n `div` w == top then Just (n `mod` w) else Nothing) + >? digitIs top >* upTo (k - 1) (hi `mod` w) False) + -- a digit, by its value, in either case + digitIs :: n -> p () () + digitIs d = + let c = (['0' .. '9'] <> ['a' .. 'z']) !! fromIntegral d + in if isLetter c then precEitherOf [c] [toUpper c] else terminal [c] diff --git a/distributors-grammar/src/Control/Lens/Grammar/Pretty.hs b/distributors-grammar/src/Control/Lens/Grammar/Pretty.hs new file mode 100644 index 00000000..5c8addb3 --- /dev/null +++ b/distributors-grammar/src/Control/Lens/Grammar/Pretty.hs @@ -0,0 +1,260 @@ +{- | +Module : Control.Lens.Grammar.Pretty +Description : grammars laid out, as Wadler-Leijen pretty printers +Copyright : (C) 2026 - Eitan Chatav +License : BSD-style (see the file LICENSE) +Maintainer : Eitan Chatav +Stability : provisional +Portability : non-portable + +Grammars which lay themselves out, by the layout combinators of +Wadler, [A prettier printer] +(https://homepages.inf.ed.ac.uk/wadler/papers/prettier/prettier.pdf), +printing a `Doc` of the @prettyprinter@ package, which chooses, by the +page's width, between their flat & broken layouts, & parsing every layout +they print, with any indentation. +-} + +module Control.Lens.Grammar.Pretty + ( -- * PrettyGrammar + PrettyGrammar (..) + , prettyG + , layoutG + , LayoutStyle (..) + -- * Layout + , Lined (..) + , LaidOut (..) + , lineP + , lineP' + , softlineP + -- * Prettor + , Prettor (..) + ) where + +import Control.Applicative +import Control.Lens +import Control.Lens.Grammar.BackusNaur +import Control.Lens.Grammar.RegEx +import Control.Lens.Grammar.Symbol +import Control.Lens.Grammar.Token +import Data.List (intersperse) +import Data.Monoid.Disjunctive +import Data.Profunctor +import Data.Profunctor.Distributor +import Data.Profunctor.Grammar +import Data.Profunctor.Monoidal +import Data.Profunctor.Monoidal.Cocartesian +import Data.String (IsString (..)) +import Data.Void (absurd) +import GHC.Exts (IsList, Item) +import Prettyprinter + ( Doc, LayoutOptions, align, flatAlt, group, hardline, layoutCompact + , layoutPretty, layoutSmart, nest ) +import Prettyprinter.Render.String (renderString) +import Witherable (Filterable) + +{- | A type's grammar, laid out by `Lined` & `LaidOut` combinators. -} +class PrettyGrammar a where + prettyGrammar :: + ( Grammatical Char p + , forall x y. (x ~ (), y ~ ()) => Lined (p x y) + , forall x y. (x ~ (), y ~ ()) => IsString (p x y) + , forall x y. LaidOut (p x y) + ) => p a a + +{- | A type's `PrettyGrammar`, printed to a `Doc`, if it prints. -} +prettyG :: PrettyGrammar a => a -> Maybe (Doc ann) +prettyG = fmap snd . runPrettor prettyGrammar + +{- | A layout style of a `Doc`, as @prettyprinter@ lays them out. -} +data LayoutStyle + = PrettyLayout LayoutOptions + -- ^ by `layoutPretty`, fitting the rest of a line + | SmartLayout LayoutOptions + -- ^ by `layoutSmart`, fitting more than the rest of a line + | CompactLayout + -- ^ by `layoutCompact`, broken & unindented + +{- | A type's `PrettyGrammar`, printed in a `LayoutStyle`, if it prints. -} +layoutG :: PrettyGrammar a => LayoutStyle -> a -> Maybe String +layoutG style a = renderString . laidOut <$> (prettyG a :: Maybe (Doc ())) + where + laidOut = case style of + PrettyLayout opts -> layoutPretty opts + SmartLayout opts -> layoutSmart opts + CompactLayout -> layoutCompact + +{- | Grammars with a hard line break. -} +class Lined p where + {- | A newline, which no flat layout removes. -} + hardlineP :: p + +{- | Grammars laid out by Wadler-Leijen layout combinators, +choosing between flat & broken layouts. + +> prop> nestP 0 = id +> prop> nestP i . nestP j = nestP (i + j) +-} +class LaidOut p where + {- | A broken layout, by default, & a flat one, where it's grouped flat. -} + flatAltP :: p -> p -> p + {- | Indented further after its line breaks. -} + nestP :: Int -> p -> p + {- | Flat, where it fits. -} + groupP :: p -> p + {- | Indented to the current column after its line breaks. -} + alignP :: p -> p + +{- | A line break, or a space, where it's grouped flat. -} +lineP :: (Lined p, LaidOut p, IsString p) => p +lineP = flatAltP hardlineP (fromString " ") + +{- | A line break, or nothing, where it's grouped flat. -} +lineP' :: (Lined p, LaidOut p, IsString p) => p +lineP' = flatAltP hardlineP (fromString "") + +{- | A space, or a line break, where it doesn't fit. -} +softlineP :: (Lined p, LaidOut p, IsString p) => p +softlineP = groupP lineP + +-- Doc instances -- + +instance Lined (Doc ann) where + hardlineP = hardline +instance LaidOut (Doc ann) where + flatAltP = flatAlt + nestP = nest + groupP = group + alignP = align + +-- RegEx & Bnf instances, the languages of every layout -- + +-- | A newline, then any indentation. +instance Lined (RegEx Char) where + hardlineP = terminal "\n" <> starK (token ' ') +-- | Either layout, any indentation. +instance Categorized token => LaidOut (RegEx token) where + flatAltP = (>|<) + nestP _ = id + groupP = id + alignP = id +instance (Ord rule, Lined rule) => Lined (Bnf rule) where + hardlineP = liftBnf0 hardlineP +instance (Ord rule, LaidOut rule) => LaidOut (Bnf rule) where + flatAltP = liftBnf2 flatAltP + nestP n = liftBnf1 (nestP n) + groupP = liftBnf1 groupP + alignP = liftBnf1 alignP + +-- Grammor instances -- + +instance Lined k => Lined (Grammor k a b) where + hardlineP = Grammor hardlineP +instance LaidOut k => LaidOut (Grammor k a b) where + flatAltP (Grammor x) (Grammor y) = Grammor (flatAltP x y) + nestP n = Grammor . nestP n . runGrammor + groupP = Grammor . groupP . runGrammor + alignP = Grammor . alignP . runGrammor + +-- Parsor instances, parsing every layout -- + +-- | A newline, then any indentation, unparsing none. +instance + ( Char ~ Item s, IsList s + , Cons s s Char Char, Snoc s s Char Char + , Filterable m, Alternative m, Monad m + ) => Lined (Parsor s m () ()) where + hardlineP = newline >* dimap (const "") (const ()) (manyP space) + where + newline = terminal "\n" :: Parsor s m () () + space = token ' ' :: Parsor s m Char Char +-- | Either layout, any indentation. +instance (Alternative m, Monad m) => LaidOut (Parsor s m a b) where + flatAltP = (>|<) + nestP _ = id + groupP = id + alignP = id + +{- | t'Prettor' is a printer `Profunctor` into a `Monoid`, like a `Doc`, +whose `Lined` & `LaidOut` methods it lifts. -} +newtype Prettor w f a b = Prettor {runPrettor :: a -> f (b, w)} + +-- The text of a string, its newlines hard. +linedString :: (IsString w, Lined w, Monoid w) => String -> w +linedString = mconcat . intersperse hardlineP . map fromString . splitLines + where + splitLines str = case break (== '\n') str of + (ln, _ : rest) -> ln : splitLines rest + (ln, []) -> [ln] + +-- Prettor instances +instance Functor f => Functor (Prettor w f a) where + fmap f (Prettor p) = Prettor (fmap (first' f) . p) +instance Functor f => Profunctor (Prettor w f) where + dimap f g (Prettor p) = Prettor (fmap (first' g) . p . f) +instance (Monoid w, Applicative f) => Applicative (Prettor w f a) where + pure b = Prettor (\_ -> pure (b, mempty)) + Prettor f <*> Prettor x = Prettor $ \c -> + liftA2 (\(g, v) (a, w) -> (g a, v <> w)) (f c) (x c) +instance (Monoid w, Alternative f) => Alternative (Prettor w f a) where + empty = Prettor (const empty) + Prettor p <|> Prettor q = Prettor (\a -> p a <|> q a) +instance Functor f => CocartesianMonoidal (Prettor w f) where + zeroP = Prettor absurd + Prettor p >+< Prettor q = Prettor $ + either (fmap (first' Left) . p) (fmap (first' Right) . q) +{- | `manyP` & `optionalP` print their elements in turn. -} +instance (Monoid w, Applicative f) => Distributor (Prettor w f) where + manyP (Prettor p) = Prettor $ \as -> + (\printed -> (map fst printed, foldMap snd printed)) <$> traverse p as + optionalP (Prettor p) = Prettor $ \case + Nothing -> pure (Nothing, mempty) + Just a -> first' Just <$> p a +instance (Monoid w, Alternative f) => DisjunctiveMonoid (Prettor w f a b) +instance (Monoid w, Alternative f) => CocartesianChoice (Prettor w f) where + alternate = \case + Left (Prettor p) -> Prettor $ + either (fmap (first' Left) . p) (const empty) + Right (Prettor p) -> Prettor $ + either (const empty) (fmap (first' Right) . p) +instance (Monoid w, Alternative f) => Alternator (Prettor w f) where + optionP def p = pureP def <|> p +instance (Monoid w, Alternative f) => Choice (Prettor w f) where + left' = alternate . Left + right' = alternate . Right +instance (IsString w, Lined w, Monoid w, Alternative f) + => Tokenized Char (Prettor w f Char Char) where + anyToken = Prettor (\c -> pure (c, linedString [c])) + token t = tokenClass (token t) + oneOf ts = tokenClass (oneOf ts) + notOneOf ts = tokenClass (notOneOf ts) + asIn cat = tokenClass (asIn cat) + notAsIn cat = tokenClass (notAsIn cat) +instance (IsString w, Lined w, Monoid w, Alternative f) + => TokenAlgebra Char (Prettor w f Char Char) where + -- | The test is made once, rather than for each token. + tokenClass test = matches `seq` Prettor (\c -> + if matches c then pure (c, linedString [c]) else empty) + where + matches :: Char -> Bool + matches = tokenClass test +instance (IsString w, Lined w, Monoid w, Applicative f) + => TerminalSymbol Char (Prettor w f () ()) where + terminal str = Prettor (\_ -> pure ((), printed)) + where + printed = linedString str +instance (IsString w, Lined w, Monoid w, Applicative f) + => IsString (Prettor w f () ()) where + fromString = terminal +instance Ruled (Prettor w f a b) +instance BackusNaurForm (Prettor w f a b) +instance Tried (Prettor w f a b) +instance (Lined w, Applicative f) => Lined (Prettor w f () ()) where + hardlineP = Prettor (\_ -> pure ((), hardlineP)) +{- | Both layouts print a value, the layout of their prints chosen. -} +instance (LaidOut w, Applicative f) => LaidOut (Prettor w f a b) where + flatAltP (Prettor p) (Prettor q) = Prettor $ \a -> + liftA2 (\(b, v) (_, w) -> (b, flatAltP v w)) (p a) (q a) + nestP n (Prettor p) = Prettor (fmap (fmap (nestP n)) . p) + groupP (Prettor p) = Prettor (fmap (fmap groupP) . p) + alignP (Prettor p) = Prettor (fmap (fmap alignP) . p) diff --git a/distributors-grammar/src/Control/Lens/Grammar/RegEx.hs b/distributors-grammar/src/Control/Lens/Grammar/RegEx.hs index 1246cd55..ce6b2f30 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/RegEx.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/RegEx.hs @@ -15,17 +15,46 @@ Regular expressions form a Kleene star algebra. See Kleene, module Control.Lens.Grammar.RegEx ( -- * RegEx RegEx (..) + -- * Bnf + , Bnf (..) + , liftBnf0 + , liftBnf1 + , liftBnf2 + , diffB + -- * Regular expression strings ) where +import Control.Lens hiding (Empty, rewrite) +import Control.Lens.PartialIso +import Control.Lens.Prismoid (atLeast) +import Control.Lens.Grammar.BackusNaur +import Control.Lens.Grammar.Class import Control.Lens.Grammar.Symbol import Control.Lens.Grammar.Token +import Data.Char (generalCategory) +import Data.Coerce +import Data.Bifunctor.Joker import Data.Foldable import Data.List (nub) import Data.MemoTrie import Data.Monoid.Disjunctive import Data.Profunctor import qualified Data.Set as Set -import GHC.Generics +import Data.Set (Set) +import Data.Maybe (fromMaybe, listToMaybe, mapMaybe) +import Data.Profunctor.Distributor +import Data.Profunctor.Grammar.Printor +import Data.Profunctor.Monoidal +import Data.String (IsString (..)) +import qualified GHC.Exts as Exts +import GHC.Generics (Generic) +import Text.ParserCombinators.ReadP (readP_to_S) + +-- $setup +-- >>> :set -XOverloadedStrings -XRequiredTypeArguments -XTypeApplications -XExplicitNamespaces +-- >>> import Control.Lens.Grammar +-- >>> import Data.String (fromString) +-- >>> import GHC.Exts (toList) {- | The `RegEx`pression type forms the prototypical `KleeneStarAlgebra`. It is also a `TokenAlgebra` and `tokenClass` acts homomorphically on disjunction. @@ -40,6 +69,14 @@ data RegEx token | KleeneStar (RegEx token) | KleeneOpt (RegEx token) | KleenePlus (RegEx token) + {- | Between some numbers of times, inclusive, @x{lo,hi}@ or @x{lo,}@, + normalized by `quantK`: either unbounded, at least twice, or bounded, + at most twice or more, never below its lower bound, at least none; + other counts being `KleeneStar`, `KleenePlus`, `KleeneOpt`, the item + itself, or empty; of an item neither empty nor failing. -} + | KleeneTimes Int (Maybe Int) (RegEx token) + -- | A pattern to backtrack from, by `try`, whose language is its own. + | Backtracking (RegEx token) | RegExam (TokenExam token (RegEx token)) @@ -89,6 +126,17 @@ instance Categorized token => KleeneStarAlgebra (RegEx token) where plusK (RegExam exam) | isFailExam exam = falseP plusK SeqEmpty = mempty plusK rex = KleenePlus rex + quantK lo0 hi rex = case (max 0 lo0, hi) of + (lo, Just m) | lo > m -> falseP + _ | SeqEmpty <- rex -> mempty + (lo, _) | RegExam exam <- rex, isFailExam exam -> + if lo == 0 then mempty else falseP + (0, Nothing) -> starK rex + (1, Nothing) -> plusK rex + (_, Just 0) -> mempty + (0, Just 1) -> optK rex + (1, Just 1) -> rex + (lo, _) -> KleeneTimes lo hi rex instance (Categorized token, HasTrie token) => HasTrie (RegEx token) where data (RegEx token :->: b) = RegExTrie @@ -99,6 +147,8 @@ instance (Categorized token, HasTrie token) , kleeneStarTrie :: RegEx token :->: b , kleeneOptTrie :: RegEx token :->: b , kleenePlusTrie :: RegEx token :->: b + , kleeneTimesTrie :: ((Int, Maybe Int), RegEx token) :->: b + , backtrackingTrie :: RegEx token :->: b , oneOfTrie :: [token] :->: b , notOneOfTrie :: ([token], Either Int [Int]) :->: b } @@ -110,6 +160,8 @@ instance (Categorized token, HasTrie token) , kleeneStarTrie = trie (f . starK) , kleeneOptTrie = trie (f . optK) , kleenePlusTrie = trie (f . plusK) + , kleeneTimesTrie = trie (f . \((lo, hi), x) -> quantK lo hi x) + , backtrackingTrie = trie (f . try) , oneOfTrie = trie (f . oneOf) , notOneOfTrie = trie (f . testNotOneOf) } @@ -120,6 +172,8 @@ instance (Categorized token, HasTrie token) KleeneStar x -> untrie (kleeneStarTrie rex) x KleenePlus x -> untrie (kleenePlusTrie rex) x KleeneOpt x -> untrie (kleeneOptTrie rex) x + KleeneTimes lo hi x -> untrie (kleeneTimesTrie rex) ((lo, hi), x) + Backtracking x -> untrie (backtrackingTrie rex) x RegExam (OneOf chars) -> untrie (oneOfTrie rex) (Set.toList chars) RegExam (NotOneOf chars (AndAsIn cat)) -> untrie (notOneOfTrie rex) (Set.toList chars, Left (fromEnum cat)) @@ -135,6 +189,9 @@ instance (Categorized token, HasTrie token) , first' KleeneStar <$> enumerate (kleeneStarTrie rex) , first' KleeneOpt <$> enumerate (kleeneOptTrie rex) , first' KleenePlus <$> enumerate (kleenePlusTrie rex) + , first' (\((lo, hi), x) -> KleeneTimes lo hi x) + <$> enumerate (kleeneTimesTrie rex) + , first' Backtracking <$> enumerate (backtrackingTrie rex) , first' (RegExam . OneOf . Set.fromList) <$> enumerate (oneOfTrie rex) , first' testNotOneOf <$> enumerate (notOneOfTrie rex) ] @@ -252,3 +309,552 @@ alternated rexes = Just (TokenClass (NotOneOf tokens' test)) _ -> Nothing +{- | A t'Bnf' consists of a distinguished starting rule +and a set of named rules. When a t'Bnf' supports `NonTerminalSymbol`s, +then it supports the `BackusNaurForm` interface +by replacing recursive calls with `nonTerminal`s. + +> prop> ruleRec label f = rule label (f (nonTerminal label)) + +-} +data Bnf rule = Bnf + { startBnf :: rule + , rulesBnf :: Set (String, rule) + } deriving stock (Eq, Ord, Show, Read) + +{- | Lift a rule to a t'Bnf'. -} +liftBnf0 :: Ord a => a -> Bnf a +liftBnf0 a = Bnf a mempty + +{- | Lift a function of rules to t'Bnf's. -} +liftBnf1 :: (Coercible a b, Ord b) => (a -> b) -> Bnf a -> Bnf b +liftBnf1 f (Bnf start rules) = Bnf (f start) (Set.map coerce rules) + +{- | Lift a binary function of rules to t'Bnf's. -} +liftBnf2 + :: (Coercible a c, Coercible b c, Ord c) + => (a -> b -> c) -> Bnf a -> Bnf b -> Bnf c +liftBnf2 f (Bnf start0 rules0) (Bnf start1 rules1) = + Bnf (f start0 start1) (Set.map coerce rules0 <> Set.map coerce rules1) + +{- | +The [Brzozowski derivative] +(https://dl.acm.org/doi/pdf/10.1145/321239.321249) of a +`RegEx`tended t'Bnf', with memoization. + +> prop> word =~ diffB prefix pattern = prefix <> word =~ pattern + +Unfortunately, despite elegance & optimization, Brzozowski's +pattern matching algorithm is worst case exponential in grammar size. +See Might, Darais & Spiewak, [Parsing With Derivatives] +(https://matt.might.net/papers/might2011derivatives.pdf). +-} +diffB + :: (Categorized token, HasTrie token) + => [token] -> Bnf (RegEx token) -> Bnf (RegEx token) +diffB prefix (Bnf start rules) = + Bnf (foldl' (flip diff1B) start prefix) rules + where + -- derivative wrt 1 token, memoized + diff1B = memo2 $ \x -> \case + SeqEmpty -> falseP + NonTerminal nameY -> anyP (diff1B x) (rulesNamed nameY rules) + Sequence y1 y ys -> + if δ (Bnf y1 rules) then y1'y2 >|< y1y2' else y1'y2 + where + y2 = mconcat (y : ys) + y1'y2 = diff1B x y1 <> y2 + y1y2' = y1 <> diff1B x y2 + KleeneStar y -> diff1B x y <> starK y + KleeneOpt y -> diff1B x y + Backtracking y -> diff1B x y + KleenePlus y -> diff1B x y <> starK y + KleeneTimes lo hi y -> + diff1B x y <> quantK (lo - 1) (subtract 1 <$> hi) y + RegExam (OneOf chars) -> + if x `elem` chars then mempty else falseP + RegExam (NotOneOf chars (AndAsIn cat)) -> + if elem x chars || categorize x /= cat + then falseP else mempty + RegExam (NotOneOf chars (AndNotAsIn cats)) -> + if elem x chars || elem (categorize x) cats + then falseP else mempty + RegExam (Alternate y1 y2 ys) -> anyP (diff1B x) (y1 : y2 : ys) + +-- | Does a pattern match the empty word? +δ :: (Categorized token, HasTrie token) + => Bnf (RegEx token) -> Bool +δ (Bnf start rules) = ν start where + ν = memo $ \case + SeqEmpty -> True + KleeneStar _ -> True + KleeneOpt _ -> True + Backtracking y -> ν y + KleenePlus y -> ν y + KleeneTimes lo _ y -> lo == 0 || ν y + Sequence y1 y2 ys -> all ν (y1 : y2 : ys) + RegExam (Alternate y1 y2 ys) -> any ν (y1 : y2 : ys) + NonTerminal nameY -> any ν (rulesNamed nameY rules) + _ -> False + +rulesNamed :: Ord rule => String -> Set (String, rule) -> Set rule +rulesNamed nameX = foldl' (flip inserter) Set.empty where + inserter (nameY,y) = + if nameX == nameY then Set.insert y else id + +-- Bnf instances +instance (Ord rule, NonTerminalSymbol rule) => Ruled (Bnf rule) where + rule label (Bnf newRule oldRules) = (nonTerminal label) + {rulesBnf = Set.insert (label, newRule) oldRules} +instance (Ord rule, NonTerminalSymbol rule) + => BackusNaurForm (Bnf rule) where + ruleRec label f = rule label (f (nonTerminal label)) +-- | `try` the start of a t'Bnf', recording it as its rules do. +instance Tried rule => Tried (Bnf rule) where + try (Bnf start rules) = Bnf (try start) rules +-- | A `RegEx` records `try`, but for patterns of the empty word +-- or none, which can't fail after reading a token. +instance Tried (RegEx token) where + try rex = case rex of + Backtracking _ -> rex + SeqEmpty -> rex + RegExam exam | isFailExam exam -> rex + _ -> Backtracking rex +instance (Ord rule, TerminalSymbol token rule) + => TerminalSymbol token (Bnf rule) where + terminal = liftBnf0 . terminal +instance (Ord rule, NonTerminalSymbol rule) + => NonTerminalSymbol (Bnf rule) where + nonTerminal = liftBnf0 . nonTerminal +instance (Ord rule, Tokenized token rule) + => Tokenized token (Bnf rule) where + anyToken = liftBnf0 anyToken + token = liftBnf0 . token + oneOf = liftBnf0 . oneOf + notOneOf = liftBnf0 . notOneOf + asIn = liftBnf0 . asIn + notAsIn = liftBnf0 . notAsIn +instance (Ord rule, TokenAlgebra token rule) + => TokenAlgebra token (Bnf rule) where + tokenClass = liftBnf0 . tokenClass +instance (Ord rule, KleeneStarAlgebra rule) + => KleeneStarAlgebra (Bnf rule) where + starK = liftBnf1 starK + plusK = liftBnf1 plusK + optK = liftBnf1 optK +instance (Ord rule, DisjunctiveMonoid rule) + => DisjunctiveMonoid (Bnf rule) where + falseP = liftBnf0 falseP + (>|<) = liftBnf2 (>|<) +instance (Ord rule, Monoid rule) => Monoid (Bnf rule) where + mempty = liftBnf0 mempty +instance (Ord rule, Semigroup rule) => Semigroup (Bnf rule) where + (<>) = liftBnf2 (<>) + +makeNestedPrisms ''Bnf +makeNestedPrisms ''RegEx +makeNestedPrisms ''TokenExam +makeNestedPrisms ''CategoryTest +makeNestedPrisms ''GeneralCategory + +{- | The context-free `Grammar` +of `RegEx`pressions of characters, in the syntax of regular +expression strings, by which they're `IsString` & `IsList`. +It can't be a @Control.Lens.Grammar.RegGrammar@, +since regular expression strings include parenthesization. +But [balanceBy parentheses](https://en.wikipedia.org/wiki/Dyck_language) +are a context-free language. + +`RegEx`pressions of characters are an embedded domain specific +language of regular expression strings. + +Since they are strings, they have a string-like interface. + +>>> let rex = fromString "ab|c" :: RegEx Char +>>> putStringLn rex +ab|c +>>> toList rex +"ab|c" + +They can be generated from @Control.Lens.Grammar.RegGrammar@s +with @Control.Lens.Grammar.regexG@. + +>>> toList (runGrammor (terminal "a" >* terminal "b" >|< terminal "c") :: RegEx Char) +"ab|c" + +A regular expression string is stored as an algebraic datatype, a `RegEx`. + +>>> rex +RegExam (Alternate (Sequence (RegExam (OneOf (fromList "a"))) (RegExam (OneOf (fromList "b"))) []) (RegExam (OneOf (fromList "c"))) []) + +They're similar to regular expression strings in many other +programming languages. We can use them to see if a word and pattern +are `Matching`. + +>>> "ab" =~ rex +True +>>> "c" =~ rex +True +>>> "xyz" =~ rex +False + +Like @Control.Lens.Grammar.RegGrammar@s, they can use all the `terminal` & `Tokenized` combinators. +Unlike @Control.Lens.Grammar.RegGrammar@s, instead of using `Monoidal` and `Alternator` combinators, +they use `Monoid` and `KleeneStarAlgebra` combinators. + +>>> toList (terminal "a" <> terminal "b" >|< terminal "c" :: RegEx Char) +"ab|c" +>>> toList (mempty :: RegEx Char) +"" + +Since they're a `KleeneStarAlgebra`, +they support Kleene quantifiers. + +>>> toList (starK rex) +"(ab|c)*" +>>> toList (plusK rex) +"(ab|c)+" +>>> toList (optK rex) +"(ab|c)?" + +Like other regular expression languages, they support +character classes. + +>>> toList (oneOf "abc" :: RegEx Char) +"[a-c]" +>>> toList (notOneOf "abc" :: RegEx Char) +"[^a-c]" + +The character classes are used for failure, matching no character or string, +as well as the wildcard, matching any single character. + +>>> toList (falseP :: RegEx Char) +"[]" +>>> toList (anyToken :: RegEx Char) +"[^]" + +Additional forms of character classes test for a character's `GeneralCategory`. + +>>> toList (asIn LowercaseLetter :: RegEx Char) +"\\p{Ll}" +>>> toList (notAsIn Control :: RegEx Char) +"\\P{Cc}" + +`KleeneStarAlgebra`s support alternation `>|<`, +and the `Tokenized` combinators are all negatable. +However, we'd like to be able to take the +intersection of character classes as well. +they can combine characters' `tokenClass`es +using `BooleanAlgebra` combinators. + +>>> toList (tokenClass (notOneOf "abc" >&< notOneOf "xyz") :: RegEx Char) +"[^a-cx-z]" +>>> toList (tokenClass (oneOf "abcxyz" >&< notOneOf "xyz") :: RegEx Char) +"[a-c]" +>>> toList (tokenClass (notOneOf "#$%" >&< notAsIn Control) :: RegEx Char) +"[^#-%\\P{Cc}]" +>>> toList (tokenClass (allP notAsIn [MathSymbol, Control]) :: RegEx Char) +"\\P{Sm|Cc}" +>>> toList (tokenClass (notP (oneOf "xyz")) :: RegEx Char) +"[^x-z]" + +Ill-formed regular expression strings normalize to failure. + +>>> toList (fromString ")(" :: RegEx Char) +"[]" + +>>> putStringLn (regbnfG (RegEx Char)) +{start} = \q{regex} +{alternate} = \q{sequence}(\|\q{sequence})* +{atom} = \\q\q{nonterminal}|\\t\{\q{regex}\}|\q{class}|\(\q{regex}\) +{bounds} = \q{count}(,\q{count}?)? +{category} = Ll|Lu|Lt|Lm|Lo|Mn|Mc|Me|Nd|Nl|No|Pc|Pd|Ps|Pe|Pi|Pf|Po|Sm|Sc|Sk|So|Zs|Zl|Zp|Cc|Cf|Cs|Co|Cn +{char} = [^\(\)\*\+\?\[\\\]\^\{\|\}\P{Cc}]|\\\q{char-escaped} +{char-control} = x\{[0-9A-Fa-f]+\} +{char-escaped} = [\(\)\*\+\?\[\\\]\^\{\|\}]|\q{char-control} +{class} = \q{class-one-of}|\q{class-not-one-of} +{class-category} = \\p\{\q{category}\}|\\P\{\q{category}(\|\q{category})*\} +{class-char} = [^\(\)\*\+\-\?\[\\\]\^\{\|\}\P{Cc}]|\\\q{class-char-escaped} +{class-char-escaped} = [\(\)\*\+\-\?\[\\\]\^\{\|\}]|\q{char-control} +{class-not-one-of} = \q{class-category}|\[\^\q{class-range}*\q{class-category}?\] +{class-one-of} = \q{char}|\[\q{class-range}*\] +{class-range} = \q{class-char}(-\q{class-char})? +{count} = [0-9]+ +{expression} = \q{atom}\?|\q{atom}\*|\q{atom}\+|\q{atom}\{\q{bounds}\}|\q{atom} +{nonterminal} = \{\q{char}*\} +{regex} = \q{alternate} +{sequence} = \q{expression}* +-} +instance Grammar Char (RegEx Char) where grammar = regexGrammar +instance CtxGrammar Char (RegEx Char) + +-- | The `Grammar` of `RegEx`pressions of characters. +regexGrammar :: Grammatical Char p => p (RegEx Char) (RegEx Char) +regexGrammar = ruleRec "regex" altG + where + altG rex = rule "alternate" $ + iso alternativesOf (foldr1 (>|<) :: [RegEx Char] -> RegEx Char) + >~ sepWith "|" (atLeast 1) (seqG rex) + + seqG rex = rule "sequence" $ + iso itemsOf mconcat >~ manyP (exprG rex) + + alternativesOf = \case + RegExam (Alternate rex0 rex1 rexes) -> rex0 : rex1 : rexes + rex -> [rex] + + itemsOf = \case + SeqEmpty -> [] + Sequence rex0 rex1 rexes -> rex0 : rex1 : rexes + rex -> [rex] + + exprG rex = rule "expression" $ orP + [ _KleeneOpt >? atomG rex *< terminal "?" + , _KleeneStar >? atomG rex *< terminal "*" + , _KleenePlus >? atomG rex *< terminal "+" + , _Times >? atomG rex >*< terminal "{" >* boundsG *< terminal "}" + , atomG rex + ] + + -- improper, normalizing counts by `quantK` + _Times = prism' (\(x, (lo, hi)) -> quantK lo hi x) $ \case + KleeneTimes lo hi x -> Just (x, (lo, hi)) + _ -> Nothing + + -- @{n}@ for exactly @n@ times, @{n,}@ or @{n,m}@ + boundsG = rule "bounds" $ iso bounded unbounded + >~ countG >*< optionalP (terminal "," >* optionalP countG) + bounded (lo, hi) = if hi == Just lo then (lo, Nothing) else (lo, Just hi) + unbounded (lo, hi) = (lo, fromMaybe (Just lo) hi) + countG = rule "count" $ numeral (10 :: Int) + + atomG rex = rule "atom" $ orP + [ _NonTerminal >? terminal "\\q" >* nonterminalG + , _Backtracking >? terminal "\\t{" >* rex *< terminal "}" + , _RegExam >? classG + , terminal "(" >* rex *< terminal ")" + ] + + categoryG = rule "category" $ orP + [ _LowercaseLetter >? terminal "Ll" + , _UppercaseLetter >? terminal "Lu" + , _TitlecaseLetter >? terminal "Lt" + , _ModifierLetter >? terminal "Lm" + , _OtherLetter >? terminal "Lo" + , _NonSpacingMark >? terminal "Mn" + , _SpacingCombiningMark >? terminal "Mc" + , _EnclosingMark >? terminal "Me" + , _DecimalNumber >? terminal "Nd" + , _LetterNumber >? terminal "Nl" + , _OtherNumber >? terminal "No" + , _ConnectorPunctuation >? terminal "Pc" + , _DashPunctuation >? terminal "Pd" + , _OpenPunctuation >? terminal "Ps" + , _ClosePunctuation >? terminal "Pe" + , _InitialQuote >? terminal "Pi" + , _FinalQuote >? terminal "Pf" + , _OtherPunctuation >? terminal "Po" + , _MathSymbol >? terminal "Sm" + , _CurrencySymbol >? terminal "Sc" + , _ModifierSymbol >? terminal "Sk" + , _OtherSymbol >? terminal "So" + , _Space >? terminal "Zs" + , _LineSeparator >? terminal "Zl" + , _ParagraphSeparator >? terminal "Zp" + , _Control >? terminal "Cc" + , _Format >? terminal "Cf" + , _Surrogate >? terminal "Cs" + , _PrivateUse >? terminal "Co" + , _NotAssigned >? terminal "Cn" + ] + + classG = rule "class" $ orP + [ _OneOf >? classOneOfG + , _NotOneOf >? classNotOneOfG + ] + + classCatG = rule "class-category" $ orP + [ _AndAsIn >? terminal "\\p{" >* categoryG *< terminal "}" + , _AndNotAsIn . from listed >? + terminal "\\P{" >* sepWith "|" (atLeast 1) categoryG *< terminal "}" + ] + + classOneOfG = rule "class-one-of" $ orP + [ onlyOne charG + , terminal "[" >* rangedG *< terminal "]" + ] + + classNotOneOfG = rule "class-not-one-of" $ orP + [ asEmpty >*< classCatG + , terminal "[^" >* rangedG >*< + optionP (_AndNotAsIn . _Empty) classCatG *< terminal "]" + ] + -- a set of characters by runs, of three or more as ranges + -- between characters which aren't escaped, an improper iso, + -- parsing any runs, overlapping or empty + rangedG = iso runsOf (foldMap runOf) >~ manyP (rule "class-range" $ + classCharG >*< optionalP (terminal "-" >* classCharG)) + runOf (lo, hi) = Set.fromList [lo .. fromMaybe lo hi] + runsOf = concatMap run . groupRuns . Set.toAscList + groupRuns = foldr consRun [] + consRun c = \case + (lo, hi) : runs | succ c == lo -> (c, hi) : runs + runs -> (c, c) : runs + -- a run's escaped ends are listed, & the rest ranged + run (lo, hi) = case (firstPlain lo, lastPlain hi) of + (Just lo', Just hi') | lo' <= hi' -> + singles (Just lo) (pred' lo') <> ranged lo' hi' + <> singles (succ' hi') (Just hi) + _ -> singles (Just lo) (Just hi) + where + firstPlain c + | c > hi = Nothing + | plain c = Just c + | c == hi = Nothing + | otherwise = firstPlain (succ c) + lastPlain c + | c < lo = Nothing + | plain c = Just c + | c == lo = Nothing + | otherwise = lastPlain (pred c) + pred' c = if c == minBound then Nothing else Just (pred c) + succ' c = if c == maxBound then Nothing else Just (succ c) + singles start end = case (start, end) of + (Just a, Just b) -> [(c, Nothing) | c <- [a .. b]] + _ -> [] + ranged lo hi + | fromEnum hi - fromEnum lo >= 2 = [(lo, Just hi)] + | otherwise = [(c, Nothing) | c <- [lo .. hi]] + plain c = c `notElem` ('-' : charsReserved) && categorize c /= Control + +nonterminalG :: Grammatical Char p => p String String +nonterminalG = rule "nonterminal" $ + terminal "{" >* manyP charG *< terminal "}" + +charG :: Grammatical Char p => p Char Char +charG = charWith "char" charsReserved + +-- characters in a bracket class, where a range's dash is reserved too +classCharG :: Grammatical Char p => p Char Char +classCharG = charWith "class-char" ('-' : charsReserved) + +charsReserved :: String +charsReserved = "()*+?[\\]^{|}" + +-- characters but reserved ones, which are escaped, as are controls +charWith :: Grammatical Char p => String -> String -> p Char Char +charWith name reserved = rule name $ + tokenClass (notOneOf reserved >&< notAsIn Control) + >|< terminal "\\" >* rule (name <> "-escaped") + (oneOf reserved >|< charControlG) + +charControlG :: Grammatical Char p => p Char Char +charControlG = rule "char-control" $ + prism' fromCode controlCode >? terminal "x{" >* numeral 16 *< terminal "}" + where + -- control characters print by their hexadecimal codes, & any parses so + controlCode c = if generalCategory c == Control then Just (fromEnum c) else Nothing + fromCode code = toEnum (min (fromEnum (maxBound :: Char)) code) + +{- | +The context-free `Grammar` +of t'Bnf's of `RegEx`pressions of characters, +by which they're `IsString` & `IsList`. +That means that it can generate a self-hosted definition. + +t'Bnf's of `RegEx`pressions of characters are an embedded domain specific +language of Backus-Naur forms extended by regular expression strings. + +Such a t'Bnf' consists of a distinguished "start" `RegEx`, +and a set of named `RegEx` `rule`s. + +>>> putStringLn (rule "baz" (terminal "foo" >|< terminal "bar") :: Bnf (RegEx Char)) +{start} = \q{baz} +{baz} = foo|bar + +Like `RegEx`pressions, they have a string-like interface. + +>>> let bnf = fromString "{start} = foo|bar" :: Bnf (RegEx Char) +>>> putStringLn bnf +{start} = foo|bar +>>> toList bnf +"{start} = foo|bar" +>>> :type toList bnf +toList bnf :: [Char] + +They can be generated from context-free @Control.Lens.Grammar.Grammar@s +with @Control.Lens.Grammar.regbnfG@. + +Like `RegEx`pressions, they can be constructed using +`terminal`, `Tokenized`, `Monoid` and `KleeneStarAlgebra` combinators. +But they also support `BackusNaurForm` `rule`s and `ruleRec`s. + +>>> putStringLn (rule "baz" (bnf >|< terminal "baz")) +{start} = \q{baz} +{baz} = foo|bar|baz +>>> putStringLn (ruleRec "∞-loop" (\x -> x) :: Bnf (RegEx Char)) +{start} = \q{∞-loop} +{∞-loop} = \q{∞-loop} + +>>> putStringLn (regbnfG (type (Bnf (RegEx Char)))) +{start} = \q{regbnf} +{alternate} = \q{sequence}(\|\q{sequence})* +{atom} = \\q\q{nonterminal}|\\t\{\q{regex}\}|\q{class}|\(\q{regex}\) +{bounds} = \q{count}(,\q{count}?)? +{category} = Ll|Lu|Lt|Lm|Lo|Mn|Mc|Me|Nd|Nl|No|Pc|Pd|Ps|Pe|Pi|Pf|Po|Sm|Sc|Sk|So|Zs|Zl|Zp|Cc|Cf|Cs|Co|Cn +{char} = [^\(\)\*\+\?\[\\\]\^\{\|\}\P{Cc}]|\\\q{char-escaped} +{char-control} = x\{[0-9A-Fa-f]+\} +{char-escaped} = [\(\)\*\+\?\[\\\]\^\{\|\}]|\q{char-control} +{class} = \q{class-one-of}|\q{class-not-one-of} +{class-category} = \\p\{\q{category}\}|\\P\{\q{category}(\|\q{category})*\} +{class-char} = [^\(\)\*\+\-\?\[\\\]\^\{\|\}\P{Cc}]|\\\q{class-char-escaped} +{class-char-escaped} = [\(\)\*\+\-\?\[\\\]\^\{\|\}]|\q{char-control} +{class-not-one-of} = \q{class-category}|\[\^\q{class-range}*\q{class-category}?\] +{class-one-of} = \q{char}|\[\q{class-range}*\] +{class-range} = \q{class-char}(-\q{class-char})? +{count} = [0-9]+ +{expression} = \q{atom}\?|\q{atom}\*|\q{atom}\+|\q{atom}\{\q{bounds}\}|\q{atom} +{nonterminal} = \{\q{char}*\} +{regbnf} = \{start\} = \q{regex}(\x{a}\q{nonterminal} = \q{regex})* +{regex} = \q{alternate} +{sequence} = \q{expression}* +-} +instance Grammar Char (Bnf (RegEx Char)) where grammar = regbnfGrammar +instance CtxGrammar Char (Bnf (RegEx Char)) + +-- | The `Grammar` of t'Bnf's of `RegEx`pressions of characters. +regbnfGrammar :: Grammatical Char p => p (Bnf (RegEx Char)) (Bnf (RegEx Char)) +regbnfGrammar = rule "regbnf" $ _Bnf >~ + terminal "{start} = " >* regexGrammar >*< (listed ~< manyP + (terminal "\n" >* nonterminalG *< terminal " = " >*< regexGrammar)) + +-- | A regular expression string, by its `Grammar`. +instance token ~ Char => Exts.IsList (RegEx token) where + type Item (RegEx token) = token + fromList + = fromMaybe falseP + . listToMaybe + . mapMaybe parsed + . readP_to_S (runJoker regexGrammar) + where + parsed (rex, "") = Just rex + parsed _ = Nothing + toList = maybe "[]" ($ "") . printP + (regexGrammar :: Printor String Maybe (RegEx Char) (RegEx Char)) +instance token ~ Char => IsString (RegEx token) where + fromString = Exts.fromList +-- | A t'Bnf' of regular expression strings, by its `Grammar`. +instance rule ~ RegEx Char => Exts.IsList (Bnf rule) where + type Item (Bnf rule) = Char + fromList + = fromMaybe falseP + . listToMaybe + . mapMaybe parsed + . readP_to_S (runJoker regbnfGrammar) + where + parsed (bnf, "") = Just bnf + parsed _ = Nothing + toList = maybe "{start} = []" ($ "") . printP + (regbnfGrammar :: Printor String Maybe (Bnf (RegEx Char)) (Bnf (RegEx Char))) +instance rule ~ RegEx Char => IsString (Bnf rule) where + fromString = Exts.fromList diff --git a/distributors-grammar/src/Control/Lens/Grammar/Symbol.hs b/distributors-grammar/src/Control/Lens/Grammar/Symbol.hs index e19789d8..3c024b6f 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/Symbol.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/Symbol.hs @@ -25,6 +25,7 @@ import Data.Profunctor import Data.Profunctor.Distributor (Alternator) import Data.Profunctor.Monoidal import Text.ParserCombinators.ReadP (ReadP, string) +import Text.ParserCombinators.ReadPrec (ReadPrec, lift) -- | A `terminal` symbol in a grammar. class TerminalSymbol token s | s -> token where @@ -54,3 +55,5 @@ instance TerminalSymbol token (f ()) terminal = Joker . terminal @token instance TerminalSymbol Char (ReadP ()) where terminal str = string str *> pure () +instance TerminalSymbol Char (ReadPrec ()) where + terminal = lift . terminal diff --git a/distributors-grammar/src/Control/Lens/Grammar/Token.hs b/distributors-grammar/src/Control/Lens/Grammar/Token.hs index 95905283..7f244647 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/Token.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/Token.hs @@ -46,6 +46,9 @@ import Test.QuickCheck.Gen (Gen) import qualified Test.QuickCheck.Gen as Gen import Text.ParserCombinators.ReadP (ReadP) import qualified Text.ParserCombinators.ReadP as ReadP +import Text.ParserCombinators.ReadPrec (ReadPrec) +import qualified Text.ParserCombinators.ReadPrec as ReadPrec +import Data.Functor.Contravariant (Predicate (..)) {- | `Categorized` provides a type family `Categorize` and a function to `categorize` tokens into disjoint categories. @@ -158,6 +161,15 @@ instance Tokenized Char (ReadP Char) where notOneOf = ReadP.satisfy . notOneOf asIn = ReadP.satisfy . asIn notAsIn = ReadP.satisfy . notAsIn +instance Tokenized Char (ReadPrec Char) where + anyToken = ReadPrec.lift anyToken + token = ReadPrec.lift . token + oneOf = ReadPrec.lift . oneOf + notOneOf = ReadPrec.lift . notOneOf + asIn = ReadPrec.lift . asIn + notAsIn = ReadPrec.lift . notAsIn +deriving via (token -> Bool) instance Categorized token + => Tokenized token (Predicate token) instance (Categorized token, Arbitrary token) => Tokenized token (Gen token) where anyToken = arbitrary @token token = pure @@ -330,6 +342,10 @@ instance TokenAlgebra token (f token) tokenClass = Joker . tokenClass instance TokenAlgebra Char (ReadP Char) where tokenClass = ReadP.satisfy . tokenClass +instance TokenAlgebra Char (ReadPrec Char) where + tokenClass = ReadPrec.lift . tokenClass +deriving via (token -> Bool) instance Categorized token + => TokenAlgebra token (Predicate token) instance (Categorized token, Arbitrary token) => TokenAlgebra token (Gen token) where tokenClass = foldTokenClass $ \case OneOf xs -> oneOf xs diff --git a/distributors-grammar/src/Control/Monad/Fail/Try.hs b/distributors-grammar/src/Control/Monad/Fail/Try.hs deleted file mode 100644 index e2bbb273..00000000 --- a/distributors-grammar/src/Control/Monad/Fail/Try.hs +++ /dev/null @@ -1,65 +0,0 @@ -{-| -Module : Control.Monad.Fail.Try -Description : try & fail -Copyright : (C) 2026 - Eitan Chatav -License : BSD-style (see the file LICENSE) -Maintainer : Eitan Chatav -Stability : provisional -Portability : non-portable --} - -module Control.Monad.Fail.Try - ( -- * MonadTry - MonadTry (..) - , MonadicTry - -- * MonadFail - , MonadFail (..) - -- * MonadPlus - , MonadPlus (..) - -- * Alternative - , Alternative (..) - -- * Filterable - , Filterable (..) - ) where - -import Control.Applicative -import Control.Lens.Grammar.BackusNaur -import Control.Lens.PartialIso () -import Control.Monad -import Data.Bifunctor.Joker -import Data.Profunctor (Profunctor) -import Text.ParserCombinators.ReadP (ReadP) -import Witherable - -{- | `MonadTry` is a failure handling interface, with `fail` & `try` -and redundant alternation & filtration operators. - -> prop> empty = mzero -> prop> (<|>) = mplus -> prop> filter = mfilter - -`MonadTry` also supports the `BackusNaurForm` interface -for tracing failures and the following invariant should hold. - -> prop> fail label = rule label empty - --} -class - ( MonadFail m, MonadPlus m, Filterable m - , forall x. BackusNaurForm (m x) - ) => MonadTry m where - - {- | A handler for failures. - Used for backtracking state on failure in - t'Data.Profunctor.Grammar.Parsector.Parsector'. - -} - try :: m a -> m a - default try :: m a -> m a - try = id - -{- | A `Profunctor` which is also a `MonadTry`. -} -type MonadicTry p = (Profunctor p, forall x. MonadTry (p x)) - -instance MonadTry m => MonadTry (Joker m a) where - try = Joker . try . runJoker -instance MonadTry ReadP diff --git a/distributors-grammar/src/Data/Profunctor/Grammar.hs b/distributors-grammar/src/Data/Profunctor/Grammar.hs index 507a6cec..3945a1d9 100644 --- a/distributors-grammar/src/Data/Profunctor/Grammar.hs +++ b/distributors-grammar/src/Data/Profunctor/Grammar.hs @@ -10,8 +10,7 @@ Portability : non-portable module Data.Profunctor.Grammar ( -- * Printor - Printor (..) - , printP + module Data.Profunctor.Grammar.Printor -- * Parsor , Parsor (..) , unparseP @@ -30,7 +29,6 @@ import Control.Lens.Grammar.Machine import Control.Lens.Grammar.Symbol import Control.Lens.Grammar.Token import Control.Monad -import Control.Monad.Fail.Try import Data.Coerce import Data.Monoid import Data.Monoid.Disjunctive @@ -40,18 +38,10 @@ import Data.Profunctor.Monoidal.Cocartesian import Data.Profunctor.Filtrator import Data.Profunctor.Monoidal import Data.Profunctor.Monadic (MonadicTrans (..)) -import Data.Void import Prelude hiding (id, (.)) import GHC.Exts - --- | t'Printor' is a simple printer `Profunctor`. -newtype Printor s f a b = Printor {runPrintor :: a -> f (b, s -> s)} - --- | Run the printer on a value, returning a function --- that `cons`es tokens at the beginning of an input string, --- from right to left. -printP :: Functor f => Printor s f a b -> a -> f (s -> s) -printP (Printor f) = fmap snd . f +import Witherable (Filterable (..)) +import Data.Profunctor.Grammar.Printor -- | t'Parsor' is a simple invertible parser `Profunctor`. newtype Parsor s f a b = Parsor {runParsor :: Maybe a -> s -> f (b,s)} @@ -206,153 +196,17 @@ instance , Filterable m, Alternative m, Monad m ) => IsString (Parsor s m s s) where fromString = tokens +instance Ruled (Parsor s m a b) instance BackusNaurForm (Parsor s m a b) +instance Tried (Parsor s m a b) instance (Alternative m, Monad m) => MonadFail (Parsor s m a) where fail _ = empty -instance (Alternative m, Monad m, Filterable m) - => MonadTry (Parsor s m a) instance AsEmpty s => Matching s (Parsor s [] a b) where word =~ p = case [ () | (_, remaining) <- runParsor p Nothing word , is _Empty remaining ] of [] -> False; _:_ -> True --- Printor instances -instance Functor f => Functor (Printor s f a) where - fmap f = Printor . fmap (fmap (first' f)) . runPrintor -instance Functor f => Profunctor (Printor s f) where - dimap f g (Printor p) = Printor $ \a -> (\(b, q) -> (g b, q)) <$> p (f a) - lmap f (Printor p) = Printor (p . f) - rmap g (Printor p) = Printor $ \a -> (\(b, q) -> (g b, q)) <$> p a -instance Applicative f => Applicative (Printor s f a) where - pure b = Printor (\_ -> pure (b, id)) - Printor f <*> Printor x = Printor $ \c -> - liftA2 (\(g, p) (a, q) -> (g a, p . q)) (f c) (x c) -instance Alternative f => Alternative (Printor s f a) where - empty = Printor (\_ -> empty) - Printor p <|> Printor q = Printor (\a -> p a <|> q a) -instance Filterable f => Filterable (Printor s f a) where - mapMaybe f (Printor p) = Printor $ - mapMaybe (\(a,q) -> fmap (, q) (f a)) . p -instance Monad f => Monad (Printor s f a) where - return = pure - Printor mx >>= f = Printor $ \a -> do - (a1,g) <- mx a - (b,h) <- runPrintor (f a1) a - return (b, g . h) -instance (Alternative f, Monad f) => MonadPlus (Printor s f a) -instance MonadicTrans (Printor s) where - liftP mb = Printor (\_ -> (, id) <$> mb) -instance Functor f => CocartesianMonoidal (Printor s f) where - zeroP = Printor absurd - Printor p >+< Printor q = Printor $ - either (fmap (first' Left) . p) (fmap (first' Right) . q) -{- | `manyP` & `optionalP` print their elements in turn, -rather than through isomorphisms & sums. --} -instance Applicative f => Distributor (Printor s f) where - manyP (Printor p) = Printor $ \as -> - (\printed -> (map fst printed, \str -> foldr (\(_, q) -> q) str printed)) - <$> traverse p as - optionalP (Printor p) = Printor $ \case - Nothing -> pure (Nothing, id) - Just a -> (\(b, q) -> (Just b, q)) <$> p a -instance Alternative f => DisjunctiveMonoid (Printor s f a b) -instance Alternative f => CocartesianChoice (Printor s f) where - alternate = \case - Left (Printor p) -> Printor $ - either (fmap (first' Left) . p) (\_ -> empty) - Right (Printor p) -> Printor $ - either (\_ -> empty) (fmap (first' Right) . p) -instance Alternative f => Alternator (Printor s f) where - optionP def p = pureP def <|> p -instance Filterable f => Filtrator (Printor s f) where - filtrate (Printor p) = - let - leftMaybe = \case - (Left b, q) -> Just (b, q) - _ -> Nothing - rightMaybe = \case - (Right b, q) -> Just (b, q) - _ -> Nothing - in - ( Printor (mapMaybe leftMaybe . p . Left) - , Printor (mapMaybe rightMaybe . p . Right) - ) -instance Alternative f => Choice (Printor s f) where - left' = alternate . Left - right' = alternate . Right -instance Filterable f => Cochoice (Printor s f) where - unleft = fst . filtrate - unright = snd . filtrate -instance Functor f => Strong (Printor s f) where - first' (Printor p) = - Printor (\(a,c) -> fmap (\(b,q) -> ((b,c),q)) (p a)) - second' (Printor p) = - Printor (\(c,a) -> fmap (\(b,q) -> ((c,b),q)) (p a)) -instance Monad f => Category (Printor s f) where - id = Printor $ \a -> return (a, id) - Printor q . Printor p = Printor $ \a -> do - (b, p') <- p a - (c, q') <- q b - return (c, q' . p') -instance Monad f => Arrow (Printor s f) where - arr f = Printor (return . (, id) . f) - (***) = (>*<) - first = first' - second = second' -instance (Alternative f, Monad f) => ArrowZero (Printor s f) where - zeroArrow = empty -instance (Alternative f, Monad f) => ArrowPlus (Printor s f) where - (<+>) = (<|>) -instance (Alternative f, Monad f) => ArrowChoice (Printor s f) where - (+++) = (>+<) - left = left' - right = right' -instance - ( Categorized a, a ~ Item s, IsList s, Cons s s a a - , Filterable m, Alternative m, Monad m - ) => Tokenized a (Printor s m a a) where - {-# SPECIALISE instance Tokenized Char (Printor String Maybe Char Char) #-} - anyToken = Printor (\b -> pure (b, cons b)) - token t = tokenClass (token t) - oneOf ts = tokenClass (oneOf ts) - notOneOf ts = tokenClass (notOneOf ts) - asIn cat = tokenClass (asIn cat) - notAsIn cat = tokenClass (notAsIn cat) -instance - ( Categorized a, a ~ Item s, IsList s, Cons s s a a - , Filterable m, Alternative m, Monad m - ) => TokenAlgebra a (Printor s m a a) where - {-# SPECIALISE instance - TokenAlgebra Char (Printor String Maybe Char Char) #-} - -- | The test is made once, rather than for each token. - tokenClass test = matches `seq` Printor (\b -> - if matches b then pure (b, cons b) else empty) - where - matches :: a -> Bool - matches = tokenClass test -instance (a ~ Item s, Cons s s a a, Applicative m) - => TerminalSymbol a (Printor s m () ()) where - {-# SPECIALISE instance TerminalSymbol Char (Printor String Maybe () ()) #-} - -- | Its tokens are printed together, rather than one at a time. - terminal str = Printor (\_ -> pure ((), printed)) - where - printed rest = foldr cons rest str -instance (Char ~ Item s, Cons s s Char Char, Applicative m) - => IsString (Printor s m () ()) where - fromString = terminal -instance - ( Char ~ Item s, IsList s, Cons s s Char Char, AsEmpty s - , Filterable m, Alternative m, Monad m - ) => IsString (Printor s m s s) where - fromString = tokens -instance BackusNaurForm (Printor s m a b) -instance (Alternative m, Monad m) => MonadFail (Printor s m a) where - fail _ = empty -instance (Alternative m, Monad m, Filterable m) - => MonadTry (Printor s m a) - -- Grammor instances instance Functor (Grammor k a) where fmap _ = coerce instance Contravariant (Grammor k a) where contramap _ = coerce @@ -382,6 +236,7 @@ instance KleeneStarAlgebra k => Alternator (Grammor k) where someP (Grammor rex) = Grammor (plusK rex) optionP _ (Grammor rex) = Grammor (optK rex) manyTillP (Grammor rex) (Grammor rest) = Grammor (starK rex <> rest) + quantP lo hi (Grammor rex) = Grammor (quantK lo hi rex) instance Tokenized token k => Tokenized token (Grammor k a b) where anyToken = Grammor anyToken token = Grammor . token @@ -394,8 +249,13 @@ instance TokenAlgebra a k => TokenAlgebra a (Grammor k a b) where instance TerminalSymbol token k => TerminalSymbol token (Grammor k a b) where terminal = Grammor . terminal -instance BackusNaurForm k => BackusNaurForm (Grammor k a b) where +instance TerminalSymbol Char k => IsString (Grammor k () ()) where + fromString = terminal +instance Ruled k => Ruled (Grammor k a b) where rule name = Grammor . rule name . runGrammor +instance BackusNaurForm k => BackusNaurForm (Grammor k a b) where ruleRec name = Grammor . ruleRec name . dimap Grammor runGrammor +instance Tried k => Tried (Grammor k a b) where + try = Grammor . try . runGrammor instance Matching s k => Matching s (Grammor k a b) where word =~ pattern = word =~ runGrammor pattern diff --git a/distributors-grammar/src/Data/Profunctor/Grammar/Parsector.hs b/distributors-grammar/src/Data/Profunctor/Grammar/Parsector.hs index 2f6cf602..5b603547 100644 --- a/distributors-grammar/src/Data/Profunctor/Grammar/Parsector.hs +++ b/distributors-grammar/src/Data/Profunctor/Grammar/Parsector.hs @@ -24,14 +24,12 @@ module Data.Profunctor.Grammar.Parsector import Control.Applicative import Control.Arrow import Control.Category -import Data.Function (fix) import Control.Lens import Control.Lens.Grammar.BackusNaur import Control.Lens.Grammar.Symbol import Control.Lens.Grammar.Token import Control.Lens.PartialIso import Control.Monad -import Control.Monad.Fail.Try import Data.Monoid.Disjunctive import Data.Profunctor import Data.Profunctor.Unsafe ((#.), (.#)) @@ -42,6 +40,7 @@ import Data.Profunctor.Monoidal import Data.Tree import GHC.Exts import Prelude hiding (id, (.)) +import Witherable (Filterable (..)) {- | t'Parsector' is an invertible @LL(1)@ parser which is intended to provide detailed failure information, based on [Parsec] @@ -221,7 +220,8 @@ instance matches = tokenClass test noFailure = mempty failure = ParsecFailure test [] -instance BackusNaurForm (Parsector s a b) where +instance BackusNaurForm (Parsector s a b) +instance Ruled (Parsector s a b) where -- | Wraps inner `parsecLabels` in a new `Node name` on failure. -- Has no effect on success. rule name p = Parsector $ \callback query -> @@ -233,7 +233,6 @@ instance BackusNaurForm (Parsector s a b) where in ParsecFailure expect [Node name labels] } Just _ -> reply - ruleRec name = rule name . fix instance ( Categorized token, Item s ~ token , Cons s s token token, Snoc s s token token @@ -345,7 +344,7 @@ instance Categorized (Item s) => Alternative (Parsector s a) where instance Categorized (Item s) => MonadPlus (Parsector s a) instance Categorized (Item s) => MonadFail (Parsector s a) where fail msg = rule msg empty -instance Categorized (Item s) => MonadTry (Parsector s a) where +instance Tried (Parsector s a b) where -- | On failure, resets `parsecLooked` to @False@, allowing -- the enclosing `<|>` to try the next alternative even if @p@ -- consumed input. Also restores the stream/offset decision state. diff --git a/distributors-grammar/src/Data/Profunctor/Grammar/Printor.hs b/distributors-grammar/src/Data/Profunctor/Grammar/Printor.hs new file mode 100644 index 00000000..9357946d --- /dev/null +++ b/distributors-grammar/src/Data/Profunctor/Grammar/Printor.hs @@ -0,0 +1,180 @@ +{-| +Module : Data.Profunctor.Grammar.Printor +Description : printor +Copyright : (C) 2026 - Eitan Chatav +License : BSD-style (see the file LICENSE) +Maintainer : Eitan Chatav +Stability : provisional +Portability : non-portable +-} + +module Data.Profunctor.Grammar.Printor + ( -- * Printor + Printor (..) + , printP + ) where + +import Control.Applicative +import Control.Arrow +import Control.Category +import Control.Lens +import Control.Lens.Grammar.BackusNaur +import Control.Lens.Grammar.Symbol +import Control.Lens.Grammar.Token +import Control.Monad +import Data.Monoid.Disjunctive +import Data.Profunctor +import Data.Profunctor.Distributor +import Data.Profunctor.Monoidal.Cocartesian +import Data.Profunctor.Filtrator +import Data.Profunctor.Monoidal +import Data.Profunctor.Monadic (MonadicTrans (..)) +import Data.Void +import Prelude hiding (id, (.)) +import GHC.Exts +import Witherable (Filterable (..)) + +-- | t'Printor' is a simple printer `Profunctor`. +newtype Printor s f a b = Printor {runPrintor :: a -> f (b, s -> s)} + +-- | Run the printer on a value, returning a function +-- that `cons`es tokens at the beginning of an input string, +-- from right to left. +printP :: Functor f => Printor s f a b -> a -> f (s -> s) +printP (Printor f) = fmap snd . f + +-- Printor instances +instance Functor f => Functor (Printor s f a) where + fmap f = Printor . fmap (fmap (first' f)) . runPrintor +instance Functor f => Profunctor (Printor s f) where + dimap f g (Printor p) = Printor $ \a -> (\(b, q) -> (g b, q)) <$> p (f a) + lmap f (Printor p) = Printor (p . f) + rmap g (Printor p) = Printor $ \a -> (\(b, q) -> (g b, q)) <$> p a +instance Applicative f => Applicative (Printor s f a) where + pure b = Printor (\_ -> pure (b, id)) + Printor f <*> Printor x = Printor $ \c -> + liftA2 (\(g, p) (a, q) -> (g a, p . q)) (f c) (x c) +instance Alternative f => Alternative (Printor s f a) where + empty = Printor (\_ -> empty) + Printor p <|> Printor q = Printor (\a -> p a <|> q a) +instance Filterable f => Filterable (Printor s f a) where + mapMaybe f (Printor p) = Printor $ + mapMaybe (\(a,q) -> fmap (, q) (f a)) . p +instance Monad f => Monad (Printor s f a) where + return = pure + Printor mx >>= f = Printor $ \a -> do + (a1,g) <- mx a + (b,h) <- runPrintor (f a1) a + return (b, g . h) +instance (Alternative f, Monad f) => MonadPlus (Printor s f a) +instance MonadicTrans (Printor s) where + liftP mb = Printor (\_ -> (, id) <$> mb) +instance Functor f => CocartesianMonoidal (Printor s f) where + zeroP = Printor absurd + Printor p >+< Printor q = Printor $ + either (fmap (first' Left) . p) (fmap (first' Right) . q) +{- | `manyP` & `optionalP` print their elements in turn, +rather than through isomorphisms & sums. +-} +instance Applicative f => Distributor (Printor s f) where + manyP (Printor p) = Printor $ \as -> + (\printed -> (map fst printed, \str -> foldr (\(_, q) -> q) str printed)) + <$> traverse p as + optionalP (Printor p) = Printor $ \case + Nothing -> pure (Nothing, id) + Just a -> (\(b, q) -> (Just b, q)) <$> p a +instance Alternative f => DisjunctiveMonoid (Printor s f a b) +instance Alternative f => CocartesianChoice (Printor s f) where + alternate = \case + Left (Printor p) -> Printor $ + either (fmap (first' Left) . p) (\_ -> empty) + Right (Printor p) -> Printor $ + either (\_ -> empty) (fmap (first' Right) . p) +instance Alternative f => Alternator (Printor s f) where + optionP def p = pureP def <|> p +instance Filterable f => Filtrator (Printor s f) where + filtrate (Printor p) = + let + leftMaybe = \case + (Left b, q) -> Just (b, q) + _ -> Nothing + rightMaybe = \case + (Right b, q) -> Just (b, q) + _ -> Nothing + in + ( Printor (mapMaybe leftMaybe . p . Left) + , Printor (mapMaybe rightMaybe . p . Right) + ) +instance Alternative f => Choice (Printor s f) where + left' = alternate . Left + right' = alternate . Right +instance Filterable f => Cochoice (Printor s f) where + unleft = fst . filtrate + unright = snd . filtrate +instance Functor f => Strong (Printor s f) where + first' (Printor p) = + Printor (\(a,c) -> fmap (\(b,q) -> ((b,c),q)) (p a)) + second' (Printor p) = + Printor (\(c,a) -> fmap (\(b,q) -> ((c,b),q)) (p a)) +instance Monad f => Category (Printor s f) where + id = Printor $ \a -> return (a, id) + Printor q . Printor p = Printor $ \a -> do + (b, p') <- p a + (c, q') <- q b + return (c, q' . p') +instance Monad f => Arrow (Printor s f) where + arr f = Printor (return . (, id) . f) + (***) = (>*<) + first = first' + second = second' +instance (Alternative f, Monad f) => ArrowZero (Printor s f) where + zeroArrow = empty +instance (Alternative f, Monad f) => ArrowPlus (Printor s f) where + (<+>) = (<|>) +instance (Alternative f, Monad f) => ArrowChoice (Printor s f) where + (+++) = (>+<) + left = left' + right = right' +instance + ( Categorized a, a ~ Item s, IsList s, Cons s s a a + , Filterable m, Alternative m, Monad m + ) => Tokenized a (Printor s m a a) where + {-# SPECIALISE instance Tokenized Char (Printor String Maybe Char Char) #-} + anyToken = Printor (\b -> pure (b, cons b)) + token t = tokenClass (token t) + oneOf ts = tokenClass (oneOf ts) + notOneOf ts = tokenClass (notOneOf ts) + asIn cat = tokenClass (asIn cat) + notAsIn cat = tokenClass (notAsIn cat) +instance + ( Categorized a, a ~ Item s, IsList s, Cons s s a a + , Filterable m, Alternative m, Monad m + ) => TokenAlgebra a (Printor s m a a) where + {-# SPECIALISE instance + TokenAlgebra Char (Printor String Maybe Char Char) #-} + -- | The test is made once, rather than for each token. + tokenClass test = matches `seq` Printor (\b -> + if matches b then pure (b, cons b) else empty) + where + matches :: a -> Bool + matches = tokenClass test +instance (a ~ Item s, Cons s s a a, Applicative m) + => TerminalSymbol a (Printor s m () ()) where + {-# SPECIALISE instance TerminalSymbol Char (Printor String Maybe () ()) #-} + -- | Its tokens are printed together, rather than one at a time. + terminal str = Printor (\_ -> pure ((), printed)) + where + printed rest = foldr cons rest str +instance (Char ~ Item s, Cons s s Char Char, Applicative m) + => IsString (Printor s m () ()) where + fromString = terminal +instance + ( Char ~ Item s, IsList s, Cons s s Char Char, AsEmpty s + , Filterable m, Alternative m, Monad m + ) => IsString (Printor s m s s) where + fromString = tokens +instance Ruled (Printor s m a b) +instance BackusNaurForm (Printor s m a b) +instance Tried (Printor s m a b) +instance (Alternative m, Monad m) => MonadFail (Printor s m a) where + fail _ = empty diff --git a/distributors-grammar/test/Examples/Arithmetic.hs b/distributors-grammar/test/Examples/Arithmetic.hs index 27046118..bc532d28 100644 --- a/distributors-grammar/test/Examples/Arithmetic.hs +++ b/distributors-grammar/test/Examples/Arithmetic.hs @@ -16,7 +16,7 @@ data Arith makePrisms ''Arith -arithGrammar :: Grammar Char Arith +arithGrammar :: Grammatical Char p => p Arith Arith arithGrammar = ruleRec "arith" sumG where sumG arith = rule "sum" $ @@ -26,7 +26,7 @@ arithGrammar = ruleRec "arith" sumG factorG arith = rule "factor" $ number >|< terminal "(" >* arith *< terminal ")" number = rule "number" $ - _Num . iso show read >? someP (asIn @Char DecimalNumber) + _Num >? numeral 10 arithExamples :: [(Arith, String)] arithExamples = @@ -36,3 +36,6 @@ arithExamples = , (Mul (Num 2) (Add (Num 3) (Num 4)), "2*(3+4)") , (Add (Add (Num 1) (Mul (Num 2) (Num 3))) (Num 4), "1+2*3+4") ] + +instance CtxGrammar Char Arith +instance Grammar Char Arith where grammar = arithGrammar diff --git a/distributors-grammar/test/Examples/Chain.hs b/distributors-grammar/test/Examples/Chain.hs index 8c397264..10514941 100644 --- a/distributors-grammar/test/Examples/Chain.hs +++ b/distributors-grammar/test/Examples/Chain.hs @@ -15,7 +15,7 @@ data Chain makePrisms ''Chain -chainGrammar :: Grammar Char Chain +chainGrammar :: Grammatical Char p => p Chain Chain chainGrammar = ruleRec "chain" seqG where seqG chn = rule "seq" $ @@ -33,3 +33,6 @@ chainExamples = , (Seq (Char 'x') (Seq (Char 'y') (Char 'z')), "x(yz)") , (Emp, "") ] + +instance CtxGrammar Char Chain +instance Grammar Char Chain where grammar = chainGrammar diff --git a/distributors-grammar/test/Examples/Expression.hs b/distributors-grammar/test/Examples/Expression.hs index 0f626c10..f6c0266e 100644 --- a/distributors-grammar/test/Examples/Expression.hs +++ b/distributors-grammar/test/Examples/Expression.hs @@ -32,13 +32,13 @@ makePrisms ''Expr -- exactly once regardless of associativity, so this is LL1 and is tested -- against the predictive @parsecG@ / megaparsec backends too -- (@testCfg True@). -exprGrammar :: Grammar Char Expr +exprGrammar :: Grammatical Char p => p Expr Expr exprGrammar = ruleRec "expr" $ \expr -> let atom = rule "atom" $ nat >|< terminal "(" >* expr *< terminal ")" nat = rule "nat" $ - _Nat . iso show read >? someP (asIn @Char DecimalNumber) + _Nat >? numeral 10 in withOperators [ [ Postfix _Fac (terminal "!") ] , [ Infix RightAssoc _Exp (terminal "^") ] @@ -68,13 +68,13 @@ exprExamples = -- so it exercises `chainr1` / `difoldr` independently of `withOperators`. -- This is a regression test for the right-fold: @2^3^2@ must associate as -- @Exp 2 (Exp 3 2)@, not @Exp 3 (Exp 2 2)@. -powGrammar :: Grammar Char Expr +powGrammar :: Grammatical Char p => p Expr Expr powGrammar = ruleRec "pow" $ \e -> let atom = rule "atom" $ nat >|< terminal "(" >* e *< terminal ")" nat = rule "nat" $ - _Nat . iso show read >? someP (asIn @Char DecimalNumber) + _Nat >? numeral 10 in sepWith "^" (chain1 Right _Exp) atom powExamples :: [(Expr, String)] @@ -88,13 +88,13 @@ powExamples = -- | A purely left-associative expression grammar (no right-associative -- exponent) built with `withOperators`, tested against the predictive -- @parsecG@ / megaparsec backends (@testCfg True@) as a minimal case. -leftGrammar :: Grammar Char Expr +leftGrammar :: Grammatical Char p => p Expr Expr leftGrammar = ruleRec "expr" $ \expr -> let atom = rule "atom" $ nat >|< terminal "(" >* expr *< terminal ")" nat = rule "nat" $ - _Nat . iso show read >? someP (asIn @Char DecimalNumber) + _Nat >? numeral 10 in withOperators [ [ Infix LeftAssoc _Mul (terminal "*"), Infix LeftAssoc _Div (terminal "/") ] , [ Infix LeftAssoc _Add (terminal "+"), Infix LeftAssoc _Sub (terminal "-") ] @@ -108,3 +108,6 @@ leftExamples = , (Sub (Add (Nat 1) (Mul (Nat 2) (Nat 3))) (Nat 4), "1+2*3-4") , (Mul (Add (Nat 1) (Nat 2)) (Nat 3), "(1+2)*3") ] + +instance CtxGrammar Char Expr +instance Grammar Char Expr where grammar = exprGrammar diff --git a/distributors-grammar/test/Examples/Heredoc.hs b/distributors-grammar/test/Examples/Heredoc.hs index 0fb9de08..4770810d 100644 --- a/distributors-grammar/test/Examples/Heredoc.hs +++ b/distributors-grammar/test/Examples/Heredoc.hs @@ -37,7 +37,7 @@ heredocP = heredocLines >~ symbol "<<" >* contextuallyT (delimitBy (==)) lineP -- | Heredocs as a `CtxGrammar`, applying `delimitBy` `contextually`, -- so it runs as any `CtxGrammar` does, by `Parsector` too. -heredocG :: CtxGrammar Char Heredoc +heredocG :: CtxGrammatical Char p => p Heredoc Heredoc heredocG = heredocLines >~ terminal "<<" >* contextually (delimitBy (==)) lineG where lineG = manyP (notOneOf "\n") *< terminal "\n" @@ -48,3 +48,5 @@ heredocExamples = , (Heredoc "X" [], "< p Json Json jsonGrammar = rule "json" elementG where elementG = ruleRec "element" $ \json -> @@ -79,7 +79,8 @@ jsonGrammar = rule "json" elementG -- character = '0020' . '10FFFF' - '"' - '\' | '\' escape characterG = rule "character" $ - tokenClass (oneOf ['\x0020' .. '\x10FFFF'] >&< notOneOf ['\"','\\']) + -- by complement, 34 tokens rather than a million + tokenClass (notOneOf ('\"' : '\\' : ['\x0000' .. '\x001F'])) >|< terminal "\\" >* escapeG -- escape = '"' | '\' | '/' | 'b' | 'f' | 'n' | 'r' | 't' @@ -96,7 +97,7 @@ jsonGrammar = rule "json" elementG -- number = decimal natural number numberG = rule "number" $ - iso show read >~ someP (asIn @Char DecimalNumber) + numeral 10 -- Simplified: zero or more whitespace characters ws = rule "ws" $ @@ -131,3 +132,6 @@ jsonExamples = JObject (Map.fromList [("x", JNumber 2)])], "[{\"x\":1},{\"x\":2}]") ] + +instance CtxGrammar Char Json +instance Grammar Char Json where grammar = jsonGrammar diff --git a/distributors-grammar/test/Examples/Lambda.hs b/distributors-grammar/test/Examples/Lambda.hs index 82d0c3c4..753f09b5 100644 --- a/distributors-grammar/test/Examples/Lambda.hs +++ b/distributors-grammar/test/Examples/Lambda.hs @@ -18,7 +18,7 @@ data Lambda makePrisms ''Lambda -- | Grammar for untyped lambda calculus -lambdaGrammar :: Grammar Char Lambda +lambdaGrammar :: Grammatical Char p => p Lambda Lambda lambdaGrammar = ruleRec "lambda" termG where -- Top level term: lambda abstraction or application @@ -28,7 +28,7 @@ lambdaGrammar = ruleRec "lambda" termG ] -- Lambda abstraction: \x.body - lamG term = rule "lambda" $ + lamG term = rule "abstraction" $ _Lam >? terminal "\\" >* varNameG *< terminal "." >*< term -- Application: left-associative chain of atoms @@ -99,3 +99,6 @@ lambdaExamples = (Lam "x" (App (Var "f") (App (Var "x") (Var "x"))))), "\\f.(\\x.f (x x)) (\\x.f (x x))") ] + +instance CtxGrammar Char Lambda +instance Grammar Char Lambda where grammar = lambdaGrammar diff --git a/distributors-grammar/test/Examples/LenVec.hs b/distributors-grammar/test/Examples/LenVec.hs index 8ea2716c..7e15a7e3 100644 --- a/distributors-grammar/test/Examples/LenVec.hs +++ b/distributors-grammar/test/Examples/LenVec.hs @@ -13,10 +13,10 @@ data LenVec = LenVec {length :: Natural, vector :: [Natural]} makeNestedPrisms ''LenVec -lenvecGrammar :: CtxGrammar Char LenVec +lenvecGrammar :: CtxGrammatical Char p => p LenVec LenVec lenvecGrammar = _LenVec >? P.do let - numberG = iso show read >~ someP (asIn @Char DecimalNumber) + numberG = numeral 10 vectorG n = sepWith "," (exactly n) numberG len <- numberG -- bonds to _LenVec terminal ";" -- doesn't bond @@ -27,3 +27,5 @@ lenvecExamples = [ (LenVec 3 [1,2,3], "3;1,2,3") , (LenVec 0 [], "0;") ] + +instance CtxGrammar Char LenVec where ctxGrammar = lenvecGrammar diff --git a/distributors-grammar/test/Examples/RegString.hs b/distributors-grammar/test/Examples/RegString.hs index 1069a603..07cc73cd 100644 --- a/distributors-grammar/test/Examples/RegString.hs +++ b/distributors-grammar/test/Examples/RegString.hs @@ -4,7 +4,7 @@ module Examples.RegString import Control.Lens.Grammar -regexExamples :: [(RegString, String)] +regexExamples :: [(RegEx Char, String)] regexExamples = [ (terminal "abc123etc.", "abc123etc.") , (terminal "x" <> terminal "y", "xy") @@ -15,8 +15,8 @@ regexExamples = , (starK (terminal "x"), "x*") , (plusK (terminal "x"), "x+") , (anyToken, "[^]") - , (oneOf "abc", "[abc]") - , (notOneOf "abc", "[^abc]") + , (oneOf "abc", "[a-c]") + , (notOneOf "abc", "[^a-c]") , (asIn UppercaseLetter, "\\p{Lu}") , (notAsIn LowercaseLetter, "\\P{Ll}") , (nonTerminal "rule-name", "\\q{rule-name}") @@ -25,36 +25,36 @@ regexExamples = , (optK (terminal "abc") <> nonTerminal "xyz", "(abc)?\\q{xyz}") -- Boolean OR (>|<) operations - , (tokenClass (oneOf "abc" >|< oneOf "xyz"), "[abcxyz]") - , (tokenClass (oneOf "abc" >|< notOneOf "xyz"), "[abc]|[^xyz]") - , (tokenClass (notOneOf "abc" >|< oneOf "xyz"), "[^abc]|[xyz]") + , (tokenClass (oneOf "abc" >|< oneOf "xyz"), "[a-cx-z]") + , (tokenClass (oneOf "abc" >|< notOneOf "xyz"), "[a-c]|[^x-z]") + , (tokenClass (notOneOf "abc" >|< oneOf "xyz"), "[^a-c]|[x-z]") , (tokenClass (asIn UppercaseLetter >|< asIn LowercaseLetter), "\\p{Lu}|\\p{Ll}") - , (tokenClass (oneOf "abc" >|< asIn DecimalNumber), "[abc]|\\p{Nd}") + , (tokenClass (oneOf "abc" >|< asIn DecimalNumber), "[a-c]|\\p{Nd}") -- Boolean AND (>&<) operations - , (tokenClass (oneOf "abcdef" >&< oneOf "def123"), "[def]") - , (tokenClass (notOneOf "abc" >&< notOneOf "xyz"), "[^abcxyz]") + , (tokenClass (oneOf "abcdef" >&< oneOf "def123"), "[d-f]") + , (tokenClass (notOneOf "abc" >&< notOneOf "xyz"), "[^a-cx-z]") , (tokenClass (oneOf "abcd" >&< notOneOf "cd"), "[ab]") - , (tokenClass (notOneOf "abc" >&< asIn LowercaseLetter), "[^abc\\p{Ll}]") - , (tokenClass (notOneOf "abc" >&< notAsIn Control), "[^abc\\P{Cc}]") - , (tokenClass (asIn UppercaseLetter >&< notOneOf "XYZ"), "[^XYZ\\p{Lu}]") + , (tokenClass (notOneOf "abc" >&< asIn LowercaseLetter), "[^a-c\\p{Ll}]") + , (tokenClass (notOneOf "abc" >&< notAsIn Control), "[^a-c\\P{Cc}]") + , (tokenClass (asIn UppercaseLetter >&< notOneOf "XYZ"), "[^X-Z\\p{Lu}]") , (tokenClass (notAsIn Control >&< notAsIn Space), "\\P{Zs|Cc}") - , (tokenClass (oneOf "0123456789xyz" >&< asIn DecimalNumber), "[0123456789]") + , (tokenClass (oneOf "0123456789xyz" >&< asIn DecimalNumber), "[0-9]") -- Boolean NOT (notP) operations - , (tokenClass (notP (oneOf "abc")), "[^abc]") - , (tokenClass (notP (notOneOf "abc")), "[abc]") - , (tokenClass (notP (oneOf "abc" >|< oneOf "xyz")), "[^abcxyz]") + , (tokenClass (notP (oneOf "abc")), "[^a-c]") + , (tokenClass (notP (notOneOf "abc")), "[a-c]") + , (tokenClass (notP (oneOf "abc" >|< oneOf "xyz")), "[^a-cx-z]") , (tokenClass (notP (asIn UppercaseLetter)), "\\P{Lu}") , (tokenClass (notP (notAsIn Control)), "\\p{Cc}") - , (tokenClass (notP (notOneOf "abc" >&< asIn LowercaseLetter)), "[abc]|\\P{Ll}") + , (tokenClass (notP (notOneOf "abc" >&< asIn LowercaseLetter)), "[a-c]|\\P{Ll}") -- trueP & falseP , (tokenClass trueP, "[^]") , (tokenClass falseP, "[]") -- Complex combinations - , (tokenClass (notOneOf "abc" >&< (asIn LowercaseLetter >|< asIn UppercaseLetter)), "[^abc\\p{Ll}]|\\p{Lu}") - , (tokenClass ((oneOf "123" >|< asIn DecimalNumber) >&< notOneOf "789"), "[123]|[^789\\p{Nd}]") - , (tokenClass (notP (oneOf "abc" >|< asIn MathSymbol)), "[^abc\\P{Sm}]") + , (tokenClass (notOneOf "abc" >&< (asIn LowercaseLetter >|< asIn UppercaseLetter)), "[^a-c\\p{Ll}]|\\p{Lu}") + , (tokenClass ((oneOf "123" >|< asIn DecimalNumber) >&< notOneOf "789"), "[1-3]|[^7-9\\p{Nd}]") + , (tokenClass (notP (oneOf "abc" >|< asIn MathSymbol)), "[^a-c\\P{Sm}]") ] diff --git a/distributors-grammar/test/Examples/Rho.hs b/distributors-grammar/test/Examples/Rho.hs new file mode 100644 index 00000000..6325f8df --- /dev/null +++ b/distributors-grammar/test/Examples/Rho.hs @@ -0,0 +1,146 @@ +module Examples.Rho + ( Proc (..) + , Name (..) + , rhoGrammar + , rhoExamples + , rholangGrammar + , rholangExamples + ) where + +import Control.Lens +import Control.Lens.Grammar + +-- | Processes of Meredith & Radestock's reflective higher-order calculus, +-- the ρ-calculus, "A reflective higher-order calculus", FInCo 2005. +data Proc + = Zero -- ^ null process, @0@ + | Input Name Name Proc -- ^ input, @x(y).P@ + | Lift Name Proc -- ^ lift, @x⟨|P|⟩@ + | Drop Name -- ^ drop, @⌝x⌜@ + | Par Proc Proc -- ^ parallel, @P | Q@ + deriving stock (Eq, Ord, Show, Read) + +-- | Names are quoted processes, @⌜P⌝@. +newtype Name = Quote Proc + deriving stock (Eq, Ord, Show, Read) + +makeNestedPrisms ''Proc +makePrisms ''Name + +-- | What follows an action's subject name, an input's or a lift's. +data Act = InputAct Name Proc | LiftAct Proc + +makeNestedPrisms ''Act + +-- | An action, by its subject name & what follows it. +_Act :: Prism' Proc (Name, Act) +_Act = prism' build match + where + build (x, InputAct y p) = Input x y p + build (x, LiftAct p) = Lift x p + match = \case + Input x y p -> Just (x, InputAct y p) + Lift x p -> Just (x, LiftAct p) + _ -> Nothing + +-- | The paper's notation, factoring an action's subject name, which +-- inputs & lifts share, to be @LL(1)@. +rhoGrammar :: forall p. Grammatical Char p => p Proc Proc +rhoGrammar = ruleRec "proc" $ \rho -> rule "par" $ + sepWith " | " (chain1 Left _Par) (ruleRec "atom" (atomG rho)) + where + atomG :: p Proc Proc -> p Proc Proc -> p Proc Proc + actG :: p Proc Proc -> p Proc Proc -> p Act Act + nameG :: p Proc Proc -> p Name Name + atomG rho atom = orP + [ _Zero >? terminal "0" + , _Drop >? terminal "⌝" >* nameG rho *< terminal "⌜" + , _Act >? nameG rho >*< actG rho atom + , terminal "(" >* rho *< terminal ")" + ] + actG rho atom = rule "act" $ + _InputAct >? terminal "(" >* nameG rho *< terminal ")." >*< atom + >|< _LiftAct >? terminal "⟨|" >* rho *< terminal "|⟩" + nameG rho = rule "name" $ + _Quote >? terminal "⌜" >* rho *< terminal "⌝" + +-- | An ASCII notation, after Rholang's: @\@P@ quotes, @*x@ drops, +-- @x!(P)@ lifts & @for(y <- x){P}@ inputs. +rholangGrammar :: forall p. Grammatical Char p => p Proc Proc +rholangGrammar = ruleRec "proc" $ \rho -> rule "par" $ + sepWith " | " (chain1 Left _Par) (ruleRec "atom" (atomG rho)) + where + atomG :: p Proc Proc -> p Proc Proc -> p Proc Proc + nameG :: p Proc Proc -> p Name Name + atomG rho atom = orP + [ _Zero >? terminal "0" + , _Drop >? terminal "*" >* nameG atom + , _Lift >? nameG atom *< terminal "!(" >*< rho *< terminal ")" + , _Input . swapped' >? terminal "for(" >* nameG atom + *< terminal " <- " >*< nameG atom *< terminal "){" >*< rho *< terminal "}" + , terminal "(" >* rho *< terminal ")" + ] + nameG atom = rule "name" $ _Quote >? terminal "@" >* atom + -- @for(y <- x)@ binds @y@ first, as @x(y)@ doesn't + swapped' = iso (\(x, (y, p)) -> (y, (x, p))) (\(y, (x, p)) -> (x, (y, p))) + +-- | @⌜0⌝@, the first name. +zeroName :: Name +zeroName = Quote Zero + +-- | Output's sugar, @x[y] = x⟨|⌝y⌜|⟩@. +output :: Name -> Name -> Proc +output x y = Lift x (Drop y) + +-- | The replicator, @D(x) = x(y).(x[y] | ⌝y⌜)@, at @y = ⌜0⌝@. +dup :: Name -> Proc +dup x = Input x zeroName (Par (output x zeroName) (Drop zeroName)) + +-- | Replication, @!P(x) = x⟨|D(x) | P|⟩ | D(x)@. +replicate' :: Proc -> Name -> Proc +replicate' p x = Par (Lift x (Par (dup x) p)) (dup x) + +rhoSamples :: [Proc] +rhoSamples = + [ Zero + , output zeroName zeroName + , Input zeroName zeroName Zero + , Drop zeroName + , Par Zero (Par Zero Zero) + , Par (Par Zero Zero) Zero + , Input zeroName zeroName (Par Zero Zero) + , Lift (Quote (output zeroName zeroName)) (Input zeroName zeroName Zero) + , dup zeroName + , replicate' Zero zeroName + ] + +rhoExamples :: [(Proc, String)] +rhoExamples = zip rhoSamples + [ "0" + , "⌜0⌝⟨|⌝⌜0⌝⌜|⟩" + , "⌜0⌝(⌜0⌝).0" + , "⌝⌜0⌝⌜" + , "0 | (0 | 0)" + , "0 | 0 | 0" + , "⌜0⌝(⌜0⌝).(0 | 0)" + , "⌜⌜0⌝⟨|⌝⌜0⌝⌜|⟩⌝⟨|⌜0⌝(⌜0⌝).0|⟩" + , "⌜0⌝(⌜0⌝).(⌜0⌝⟨|⌝⌜0⌝⌜|⟩ | ⌝⌜0⌝⌜)" + , "⌜0⌝⟨|⌜0⌝(⌜0⌝).(⌜0⌝⟨|⌝⌜0⌝⌜|⟩ | ⌝⌜0⌝⌜) | 0|⟩ | ⌜0⌝(⌜0⌝).(⌜0⌝⟨|⌝⌜0⌝⌜|⟩ | ⌝⌜0⌝⌜)" + ] + +rholangExamples :: [(Proc, String)] +rholangExamples = zip rhoSamples + [ "0" + , "@0!(*@0)" + , "for(@0 <- @0){0}" + , "*@0" + , "0 | (0 | 0)" + , "0 | 0 | 0" + , "for(@0 <- @0){0 | 0}" + , "@@0!(*@0)!(for(@0 <- @0){0})" + , "for(@0 <- @0){@0!(*@0) | *@0}" + , "@0!(for(@0 <- @0){@0!(*@0) | *@0} | 0) | for(@0 <- @0){@0!(*@0) | *@0}" + ] + +instance CtxGrammar Char Proc +instance Grammar Char Proc where grammar = rhoGrammar diff --git a/distributors-grammar/test/Examples/SExpr.hs b/distributors-grammar/test/Examples/SExpr.hs index 6fdc9bde..5a0a6656 100644 --- a/distributors-grammar/test/Examples/SExpr.hs +++ b/distributors-grammar/test/Examples/SExpr.hs @@ -1,11 +1,13 @@ module Examples.SExpr ( SExpr (..) , sexprGrammar + , sexprPrettyGrammar , sexprExamples ) where import Control.Lens hiding (List) import Control.Lens.Grammar hiding (List) +import Data.String (IsString) -- | Abstract syntax tree for S-expressions data SExpr @@ -17,10 +19,10 @@ data SExpr makePrisms ''SExpr -- | Grammar for S-expressions -sexprGrammar :: Grammar Char SExpr +sexprGrammar :: Grammatical Char p => p SExpr SExpr sexprGrammar = ruleRec "sexpr" $ \sexpr -> orP [ _Atom >? atomG - , _List >? listG sexpr + , _List >? sexprListG sexpr ] where -- Atom: one or more alphanumeric or symbol characters @@ -28,7 +30,7 @@ sexprGrammar = ruleRec "sexpr" $ \sexpr -> orP -- List: parenthesized sequence of S-expressions -- Elements are separated by whitespace - listG sexpr = rule "list" $ + sexprListG sexpr = rule "list" $ terminal "(" >* sepWith " " several sexpr *< terminal ")" -- Characters allowed in atoms: letters, digits, and symbols @@ -56,3 +58,27 @@ sexprExamples = List [Atom "else-branch"]], "(if test (then-branch) (else-branch))") ] + +instance CtxGrammar Char SExpr + +{- | Pretty grammar for S-expressions: a list is flat, if it fits, or else +each of its elements on a line of its own, aligned after its parenthesis. +-} +sexprPrettyGrammar :: + ( Grammatical Char p + , forall x y. (x ~ (), y ~ ()) => Lined (p x y) + , forall x y. (x ~ (), y ~ ()) => IsString (p x y) + , forall x y. LaidOut (p x y) + ) => p SExpr SExpr +sexprPrettyGrammar = ruleRec "sexpr" $ \sexpr -> orP + [ _Atom >? rule "atom" (someP (tokenClass atomChars)) + , _List >? rule "list" + (terminal "(" >* groupP (alignP (sepBy lineP several sexpr)) *< terminal ")") + ] + where + atomChars = + oneOf (['a'..'z'] ++ ['A'..'Z'] ++ ['0'..'9'] ++ "_+-*/<>=!?") + +instance PrettyGrammar SExpr where + prettyGrammar = sexprPrettyGrammar +instance Grammar Char SExpr where grammar = sexprGrammar diff --git a/distributors-grammar/test/Examples/SemVer.hs b/distributors-grammar/test/Examples/SemVer.hs index 087f325b..980a43ca 100644 --- a/distributors-grammar/test/Examples/SemVer.hs +++ b/distributors-grammar/test/Examples/SemVer.hs @@ -32,7 +32,7 @@ makeNestedPrisms ''SemVer -- prerelease = identifier ("." identifier)* -- buildmetadata = identifier ("." identifier)* -- identifier = [0-9A-Za-z-]+ -semverGrammar :: RegGrammar Char SemVer +semverGrammar :: RegGrammatical Char p => p SemVer SemVer semverGrammar = _SemVer >? numberG >*< terminal "." >* numberG @@ -40,7 +40,7 @@ semverGrammar = _SemVer >*< optionP _Empty (terminal "-" >* identifiersG) >*< optionP _Empty (terminal "+" >* identifiersG) where - numberG = iso show read >~ someP (asIn @Char DecimalNumber) + numberG = numeral 10 identifiersG = sepWith "." (atLeast 1) (someP charG) charG = asIn LowercaseLetter >|< asIn UppercaseLetter @@ -48,10 +48,10 @@ semverGrammar = _SemVer >|< token '-' -- Context-sensitive SemVer to test qualified-do -semverCtxGrammar :: CtxGrammar Char SemVer +semverCtxGrammar :: CtxGrammatical Char p => p SemVer SemVer semverCtxGrammar = _SemVer >? P.do let - numberG = iso show read >~ someP (asIn @Char DecimalNumber) + numberG = numeral 10 identifiersG = sepWith "." (atLeast 1) (someP charG) charG = asIn LowercaseLetter >|< asIn UppercaseLetter @@ -90,3 +90,7 @@ semverExamples = , (SemVer 2 1 5 ["rc", "1"] ["build", "123"], "2.1.5-rc.1+build.123") ] + +instance CtxGrammar Char SemVer +instance Grammar Char SemVer +instance RegGrammar Char SemVer where regGrammar = semverGrammar diff --git a/distributors-grammar/test/Main.hs b/distributors-grammar/test/Main.hs index 68902791..2f34e797 100644 --- a/distributors-grammar/test/Main.hs +++ b/distributors-grammar/test/Main.hs @@ -2,12 +2,18 @@ module Main (main) where import Data.Foldable hiding (toList) import Control.Lens.Grammar +import Data.Bifunctor.Joker (Joker (..)) import Control.Monad (when) -import Data.Function (fix) import Data.List (genericLength) import Data.Tree (Tree (..)) +import Data.String (fromString) +import GHC.Exts (toList) +import Text.ParserCombinators.ReadP (readP_to_S) +import Text.ParserCombinators.ReadPrec (ReadPrec, readPrec_to_S) +import Data.Functor.Contravariant (Predicate (..)) import Test.Hspec -import Test.QuickCheck (generate) +import Test.Hspec.QuickCheck (modifyMaxSize, prop) +import Test.QuickCheck (choose, elements, forAll, generate, listOf, oneof, (===)) import qualified Text.Megaparsec as M import Examples.Arithmetic @@ -17,14 +23,17 @@ import Examples.Json import Examples.Lambda import Examples.LenVec import Examples.RegString +import Examples.Rho import Examples.SemVer import Examples.SExpr +import Properties.Base import Properties.Kleene +import Properties.Pretty import Properties.Varifocal main :: IO () main = hspec $ do - describe "regexGrammar" $ testCfg False regexExamples regexGrammar + describe "regexGrammar" $ testCfg False regexExamples (grammar @Char) describe "semverGrammar" $ testCfg True semverExamples semverGrammar describe "semverCtxGrammar" $ testCsg True semverExamples semverCtxGrammar describe "arithGrammar" $ testCfg True arithExamples arithGrammar @@ -36,15 +45,110 @@ main = hspec $ do describe "exprGrammar" $ testCfg True exprExamples exprGrammar describe "powGrammar" $ testCfg False powExamples powGrammar describe "leftGrammar" $ testCfg True leftExamples leftGrammar + describe "rhoGrammar" $ testCfg True rhoExamples rhoGrammar + describe "rholangGrammar" $ testCfg True rholangExamples rholangGrammar describe "parseForest" parseForestTests describe "Parsector try rollback" tryRollbackTests describe "Kleene" kleeneProperties describe "Varifocal" varifocalProperties + describe "class runners, at Arith's Grammar" classRunnerTests + describe "ReadPrec & Predicate" readPrecTests + describe "base types" baseProperties + describe "RegEx ranges & try" regexRangeTryTests + describe "RegEx quantifiers" regexQuantifierTests + describe "PrettyGrammar, at SExpr" prettyProperties + +regexRangeTryTests :: Spec +regexRangeTryTests = do + it "parses classes listed or ranged alike" $ do + (fromString "[abc]" :: RegEx Char) `shouldBe` oneOf "abc" + (fromString "[a-c]" :: RegEx Char) `shouldBe` oneOf "abc" + (fromString "[c-ab]" :: RegEx Char) `shouldBe` oneOf "b" + it "escapes a literal dash in a class" $ do + toList (oneOf "+-" :: RegEx Char) `shouldBe` "[\\+\\-]" + (fromString "[\\+\\-]" :: RegEx Char) `shouldBe` oneOf "+-" + it "renders a huge class by its runs" $ + toList (tokenClass (oneOf ['\x20' .. '\x10FFFF'] >&< notOneOf "\"\\") :: RegEx Char) + `shouldSatisfy` ((< 40) . length) + it "escapes controls by hexadecimal codes, unambiguously" $ do + toList (token '\SO' <> token 'H' :: RegEx Char) `shouldBe` "\\x{e}H" + (fromString "\\x{E}H" :: RegEx Char) `shouldBe` (token '\SO' <> token 'H') + (fromString "\\x{e}" :: RegEx Char) `shouldBe` token '\SO' + it "records try, rendering it" $ do + let rex = try (terminal "ab") >|< terminal "ac" :: RegEx Char + toList rex `shouldBe` "\\t{ab}|ac" + fromString (toList rex) `shouldBe` rex + "ac" =~ rex `shouldBe` True + it "resolves an LL(1) conflict by try" $ do + map conflictSort (ll1Conflicts (fromString "{start} = ab|ac" :: Bnf (RegEx Char))) + `shouldBe` [LL1FirstFirst] + ll1Conflicts (fromString "{start} = \\t{ab}|ac" :: Bnf (RegEx Char)) `shouldBe` [] + +regexQuantifierTests :: Spec +regexQuantifierTests = do + let rendered :: Prismoid String String Char Char -> String + rendered pat = toList (runGrammor (pat >?* Grammor (token 'a')) :: RegEx Char) + it "renders counted Prismoids by their counts" $ do + rendered (exactly 4) `shouldBe` "a{4}" + rendered (atLeast 2) `shouldBe` "a{2,}" + rendered (inRange 2 (Just 5)) `shouldBe` "a{2,5}" + rendered (atMost 3) `shouldBe` "a{0,3}" + it "renders the counts Kleene operators have by them" $ do + rendered (atLeast 0) `shouldBe` "a*" + rendered (atLeast 1) `shouldBe` "a+" + rendered (atMost 1) `shouldBe` "a?" + rendered (exactly 1) `shouldBe` "a" + rendered (exactly 0) `shouldBe` "" + rendered (inRange 3 (Just 2)) `shouldBe` "[]" + it "parses counts, normalizing them" $ do + (fromString "a{2,3}" :: RegEx Char) `shouldBe` quantK 2 (Just 3) (token 'a') + toList (fromString "a{0,}" :: RegEx Char) `shouldBe` "a*" + toList (fromString "a{1}" :: RegEx Char) `shouldBe` "a" + toList (fromString "(ab){3}" :: RegEx Char) `shouldBe` "(ab){3}" + it "matches counts" $ do + let rex = fromString "a{2,3}" :: RegEx Char + map (=~ rex) ["a", "aa", "aaa", "aaaa"] `shouldBe` [False, True, True, False] + map (=~ (fromString "a{2,}" :: RegEx Char)) ["a", "aa", "aaaaa"] + `shouldBe` [False, True, True] + it "agrees on counts, negative or out of order, as RegEx, Grammor & Parsor" $ + for_ [(lo, hi) | lo <- [-3 .. 3], hi <- Nothing : map Just [-3 .. 3]] $ \(lo, hi) -> + for_ (map (`replicate` 'a') [0 .. 4]) $ \w -> do + let rex = quantK lo hi (token 'a') :: RegEx Char + parsed = not (null [() | (_, "") <- parseP (inRange lo hi >?* (token 'a' :: Parsor String [] Char Char)) w]) + expected = length w >= lo && maybe True (length w <=) hi + (w =~ rex, parsed) `shouldBe` (expected, expected) + rendered (inRange lo hi) `shouldBe` toList rex + prop "quantK n (Just n) x matches as n times x" $ \(x :: RegEx Char) -> + forAll (choose (0, 3)) $ \n -> forAll (listOf (elements "ab")) $ \w -> + (w =~ quantK n (Just n) x) === (w =~ mconcat (replicate n x)) + modifyMaxSize (const 8) $ prop "x{lo,hi} round trips through its string" $ \(x :: RegEx Char) -> + forAll (choose (0, 3)) $ \lo -> forAll (oneof [pure Nothing, Just <$> choose (lo, 4)]) $ \hi -> + let rex = quantK lo hi x in fromString (toList rex) === rex + +readPrecTests :: Spec +readPrecTests = do + it "runs a grammar at ReadPrec as at ReadP" $ for_ arithExamples $ \(syntax, string) -> + [x | (x, "") <- readPrec_to_S (runJoker (arithGrammar :: Joker ReadPrec Arith Arith)) 0 string] + `shouldBe` [syntax] + it "tests a token class as a Predicate, as a function" $ do + let cls = oneOf "abc" >&< notOneOf "b" :: TokenClass Char + map (getPredicate (tokenClass cls)) "abcd" `shouldBe` map (tokenClass cls) "abcd" + +classRunnerTests :: Spec +classRunnerTests = for_ arithExamples $ \(syntax, string) -> + it ("run as arithGrammar does, on " <> string) $ do + [x | (x, "") <- parseG string] `shouldBe` [syntax] + (($ "") <$> printG syntax) `shouldBe` Just string + unparseG syntax "" `shouldBe` Just string + parsecResult (parsecG string) `shouldBe` Just syntax + parsecStream (unparsecG syntax "") `shouldBe` string + regbnfG Arith `shouldBe` (runGrammor arithGrammar :: Bnf (RegEx Char)) + [x | (x, "") <- readP_to_S (readG @Arith) string] `shouldBe` [syntax] parseForestTests :: Spec parseForestTests = do it "returns the nested rule forest for a full parse" $ do - let (actualForest, actualRest) = parseForest (transducerG arithGrammar) "2*3+4;;;" + let (actualForest, actualRest) = parseForest (transducerG Arith) "2*3+4;;;" actualForest `shouldBe` [ Node ("arith", 0, 5, "2*3+4") [ Node ("sum", 0, 5, "2*3+4") @@ -66,64 +170,77 @@ parseForestTests = do tryRollbackTests :: Spec tryRollbackTests = do it "rolls back parse stream/offset on failed try" $ do - let actual = parsecG (try (tokens "ab")) "ax" + let actual = parsecP (try (tokens "ab")) "ax" parsecLooked actual `shouldBe` False parsecOffset actual `shouldBe` 0 parsecStream actual `shouldBe` "ax" parsecResult actual `shouldBe` (Nothing :: Maybe String) it "rolls back unparse stream/offset on failed try" $ do - let actual = unparsecG (try (tokens "ab")) "ax" "" + let actual = unparsecP (try (tokens "ab")) "ax" "" parsecLooked actual `shouldBe` False parsecOffset actual `shouldBe` 0 parsecStream actual `shouldBe` "" parsecResult actual `shouldBe` (Nothing :: Maybe String) -testCfg :: (Show a, Eq a) => Bool -> [(a, String)] -> Grammar Char a -> Spec -testCfg isLL1 examples grammar = do +testCfg + :: forall a. (Show a, Eq a) + => Bool -> [(a, String)] -> (forall p. Grammatical Char p => p a a) -> Spec +testCfg isLL1 examples gram = do describe "examples" $ for_ examples $ \(expectedSyntax, expectedString) -> do - testCtxGrammar isLL1 grammar (expectedSyntax, expectedString) + testCtxGrammar isLL1 gram (expectedSyntax, expectedString) it ("should match " <> expectedString <> " correctly") $ do - let actualMatch = expectedString =~ regbnfG grammar + let actualMatch = expectedString =~ (runGrammor gram :: Bnf (RegEx Char)) actualMatch `shouldBe` True + it ("should " <> (if isLL1 then "" else "not ") <> "be LL(1), statically") $ + ll1Conflicts (runGrammor gram :: Bnf (RegEx Char)) + `shouldSatisfy` (if isLL1 then null else not . null) describe "transducerG" $ do it "should generate the hundred shorted valid words in a language" $ do - generated <- generate (take 100 <$> languageSample (transducerG grammar)) + let machine = transducer (runGrammor gram) :: Transducer Char + generated <- generate (take 100 <$> languageSample machine) for_ generated $ \word -> do - let fullParses = [() | (_, "") <- parseG grammar word] + let fullParses = [() | (_, "") <- parseP (gram :: Parsor String [] a a) word] fullParses `shouldBe` [()] -testCsg :: (Show a, Eq a) => Bool -> [(a, String)] -> CtxGrammar Char a -> Spec -testCsg isLL1 examples grammar = - describe "examples" $ for_ examples $ testCtxGrammar isLL1 grammar +testCsg + :: (Show a, Eq a) + => Bool -> [(a, String)] -> (forall p. CtxGrammatical Char p => p a a) -> Spec +testCsg isLL1 examples gram = + describe "examples" $ for_ examples $ testCtxGrammar isLL1 gram -testCtxGrammar :: (Show a, Eq a) => Bool -> CtxGrammar Char a -> (a, String) -> Spec -testCtxGrammar isLL1 grammar (expectedSyntax, expectedString) = do +testCtxGrammar + :: forall a. (Show a, Eq a) + => Bool -> (forall p. CtxGrammatical Char p => p a a) -> (a, String) -> Spec +testCtxGrammar isLL1 gram (expectedSyntax, expectedString) = do it ("should parseG from " <> expectedString <> " correctly") $ do - let actualSyntax = [parsed | (parsed, "") <- parseG grammar expectedString] + let actualSyntax = + [parsed | (parsed, "") <- parseP (gram :: Parsor String [] a a) expectedString] actualSyntax `shouldBe` [expectedSyntax] it ("should unparseG to " <> expectedString <> " correctly") $ do - let actualString = unparseG grammar expectedSyntax "" + let actualString = + unparseP (gram :: Parsor String Maybe a a) expectedSyntax "" actualString `shouldBe` Just expectedString it ("should printG to " <> expectedString <> " correctly") $ do - let actualString = ($ "") <$> printG grammar expectedSyntax + let actualString = + ($ "") <$> printP (gram :: Printor String Maybe a a) expectedSyntax actualString `shouldBe` Just expectedString when isLL1 $ do it ("should parsecG from " <> expectedString <> " correctly") $ do - let actualSyntax = parsecG grammar expectedString + let actualSyntax = parsecP (gram :: Parsector String a a) expectedString let expectedLength = genericLength expectedString let actualLooked = parsecLooked actualSyntax let actualFailure = parsecFailure actualSyntax actualSyntax `shouldBe` (ParsecState actualLooked expectedLength "" actualFailure (Just expectedSyntax)) it ("should unparsecG to " <> expectedString <> " correctly") $ do - let actualString = unparsecG grammar expectedSyntax "" + let actualString = unparsecP (gram :: Parsector String a a) expectedSyntax "" let expectedLength = genericLength expectedString let actualLooked = parsecLooked actualString let actualFailure = parsecFailure actualString actualString `shouldBe` (ParsecState actualLooked expectedLength expectedString actualFailure (Just expectedSyntax)) it ("should parse with megaparsec to " <> expectedString <> " correctly") $ do - let megaparsec = unwrapMega (monadG grammar) + let megaparsec = unwrapMega (runJoker (gram :: Joker WrapMega a a)) let actualSyntax = M.parse megaparsec "" expectedString actualSyntax `shouldBe` Right expectedSyntax @@ -145,10 +262,10 @@ instance Tokenized Char (WrapMega Char) where (M.satisfy (tokenClass (asIn cat))) notAsIn cat = WrapMega $ M.label ("not in category " ++ show cat) (M.satisfy (tokenClass (notAsIn cat))) -instance BackusNaurForm (WrapMega a) where +instance Ruled (WrapMega a) where rule lbl (WrapMega p) = WrapMega (M.label lbl p) - ruleRec lbl = rule lbl . fix +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 -instance MonadTry WrapMega where - try (WrapMega p) = WrapMega (M.try p) diff --git a/distributors-grammar/test/Properties/Base.hs b/distributors-grammar/test/Properties/Base.hs new file mode 100644 index 00000000..3a22d552 --- /dev/null +++ b/distributors-grammar/test/Properties/Base.hs @@ -0,0 +1,218 @@ +module Properties.Base (baseProperties, readShowEquivalence) where + +import Control.Lens.Grammar +import Data.Char (intToDigit, isAscii, isControl, isSpace, ord, toUpper) +import Data.Int (Int8, Int16, Int32, Int64) +import Data.Foldable (for_) +import Control.Monad ((>=>)) +import Data.List (intercalate, sort) +import Data.Word (Word8, Word16, Word32, Word64) +import GHC.Generics (Generic) +import Numeric (showHex, showIntAtBase, showOct) +import Numeric.Natural (Natural) +import Test.Hspec +import Test.Hspec.QuickCheck (modifyMaxSuccess, prop) +import Test.QuickCheck + +{- | Equivalence with a type's stock `Read` & `Show` instances, at each +precedence: showing is `showsPrec`, & reading is `readsPrec`, all of a +string but whitespace, for strings of its values, by its lexical variants, +decorated by whitespace & parentheses, & mutated, so that strings which +`read` rejects are tried too. Each new instance runs it. +-} +readShowEquivalence + :: forall a. (PrecGrammar a, Read a, Show a) + => String -> Gen a -> (a -> Gen String) -> Spec +readShowEquivalence name values variants = describe name $ + for_ [0, 6, 7, 11] $ \d -> describe ("at precedence " <> show d) $ do + prop "shows as showsPrec does" $ forAll values $ \a -> + (($ "") <$> showsPrecG d a) === Just (showsPrec d a "") + modifyMaxSuccess (const 1000) $ prop "reads as readsPrec does" $ + forAll (values >>= variants >>= decorated >>= mutated) $ \str -> + complete (readsPrecG @a d str) === complete (readsPrec @a d str) + where + complete parses = sort [show a | (a, rest) <- parses, all isSpace rest] + +-- | Whitespace, `isSpace` & not, often none. +spaces :: Gen String +spaces = frequency + [ (3, pure "") + , (1, listOf1 (elements " \t\n\v\f\r\xa0\x2003\x3000")) + , (1, pure "\x2028") ] + +-- | Within any parentheses, amid whitespace. +decorated :: String -> Gen String +decorated str = do + depth <- frequency [(4, pure 0), (2, pure 1), (1, pure 2)] + go depth + where + spaced s = do + lead <- spaces + trail <- spaces + pure (lead <> s <> trail) + go :: Int -> Gen String + go 0 = spaced str + go n = go (n - 1) >>= \s -> spaced ("(" <> s <> ")") + +-- | Edited, once or twice, or not. +mutated :: String -> Gen String +mutated str = frequency [(2, pure str), (1, edit str), (1, edit str >>= edit)] + where + edit s = do + i <- choose (0, length s) + c <- elements "0123456789aefxXoObBeE+-.()' \\\"^NSOHDL\x2028" + let (front, back) = splitAt i s + elements + [ front <> [c] <> back + , front <> drop 1 back + , front <> [c] <> drop 1 back ] + +-- | An integer's strings: decimal or based, with leading zeros, & signed. +integral :: Integral a => a -> Gen String +integral x = do + let n = toInteger x + magnitude <- oneof + [ pure (show (abs n)) + , (<> show (abs n)) <$> zeros + , do + (prefix, base) <- elements [("b", 2), ("o", 8), ("x", 16)] + upper <- arbitrary + digits <- (<> showIntAtBase base intToDigit (abs n) "") <$> zeros + let cased = if upper then map toUpper else id + pure ("0" <> cased prefix <> cased digits) ] + sign <- if n < 0 then pure True else frequency [(5, pure False), (1, pure True)] + gap <- spaces + pure (if sign then "-" <> gap <> magnitude else magnitude) + where + zeros = flip replicate '0' <$> choose (0, 2) + +-- | A floating point number's strings: shown, with its exponent's `E` & +-- @+@, & zeros, or as an integer. +floating :: (RealFloat a, Show a) => a -> Gen String +floating x = oneof + [ pure (show x) + , pure (map (\c -> if c == 'e' then 'E' else c) (show x)) + , pure (concatMap (\c -> if c == 'e' then "e+" else [c]) (show x)) + , pure ("0" <> show x) + , pure (show x <> "0") + , integral (truncate x :: Integer) ] + +-- | A character's literals: shown, raw, or by a code, in any base. +character :: Char -> Gen String +character c = do + escape <- oneof $ + [ pure (drop 1 (init (show c))) ] + <> [pure [c] | c `notElem` "\\'"] + <> [ pure ("\\" <> show (ord c)) + , pure ("\\o" <> showOct (ord c) "") + , pure ("\\x" <> showHex (ord c) "") + , pure ("\\X" <> map toUpper (showHex (ord c) "")) ] + <> [pure ['\\', '^', toEnum (ord c + 64)] | ord c < 32] + pure ("'" <> escape <> "'") + +-- | A list's strings: in brackets, its items' variants, amid whitespace. +listing :: (a -> Gen String) -> [a] -> Gen String +listing itemVariant xs = do + items <- traverse (itemVariant >=> decorated) xs + pure ("[" <> intercalate "," items <> "]") + +-- | A string's literals: shown, by its characters' escapes, with empty +-- escapes & gaps, or listed, as characters. +string :: String -> Gen String +string s = oneof [pure (show s), literal, listing character s] + where + literal = do + parts <- traverse piece s + pure ("\"" <> concat parts <> "\"") + piece c = do + lead <- frequency [(8, pure ""), (1, pure "\\&"), (1, pure "\\ \n\\")] + escape <- oneof $ + [pure (drop 1 (init (show [c])))] + <> [pure [c] | c `notElem` "\\\""] + <> [ pure ("\\" <> show (ord c)) + , pure ("\\o" <> showOct (ord c) "") + , pure ("\\x" <> showHex (ord c) "") ] + pure (lead <> escape) + +-- | A value's strings, shown, at precedence 0 or 11, its lexemes rejoined +-- by whitespace, or none, by `lex`. +relexed :: Show a => a -> Gen String +relexed x = do + shown <- elements [show x, showsPrec 11 x ""] + oneof [pure shown, rejoin (lexemes shown)] + where + lexemes str = case lex str of + [(lexeme, rest)] | not (null lexeme) -> lexeme : lexemes rest + _ -> [] + rejoin = fmap concat . traverse (\lexeme -> (lexeme <>) <$> gap) + gap = frequency [(2, pure ""), (2, pure " "), (1, spaces)] + +-- | A type of each shape of constructor, deriving `Read` & `Show`. +data Shapes + = Nullary + | Prefixed Int Bool + | Record {field :: Int, other :: Maybe Char} + | Operators {(+++) :: Integer} + | Int :+: Integer + | Int `Named` Bool + | (:%) Int Int + deriving stock (Eq, Show, Read, Generic) +infixl 6 :+: +infix 4 `Named` +instance PrecGrammar Shapes +instance Arbitrary Shapes where + arbitrary = oneof + [ pure Nullary + , Prefixed <$> arbitrary <*> arbitrary + , Record <$> arbitrary <*> arbitrary + , Operators <$> arbitrary + , (:+:) <$> arbitrary <*> arbitrary + , Named <$> arbitrary <*> arbitrary + , (:%) <$> arbitrary <*> arbitrary ] + +characters :: Gen Char +characters = frequency + [ (3, arbitraryASCIIChar) + , (2, elements "\\'\"\SO\SOH\DEL\NUL ") + , (1, arbitrary `suchThat` (\c -> isControl c || not (isAscii c))) + , (1, arbitraryUnicodeChar) ] + +-- | Including the special values. +floats :: (Arbitrary a, RealFloat a) => Gen a +floats = frequency + [ (6, arbitrary) + , (1, elements [0 / 0, 1 / 0, -(1 / 0), -0.0, 0, 0.1, 1.0e7, 9999999]) ] + +baseProperties :: Spec +baseProperties = describe "equivalent to Read & Show" $ do + readShowEquivalence "Char" characters character + readShowEquivalence "Natural" + (fromInteger . getNonNegative <$> arbitrary :: Gen Natural) integral + readShowEquivalence "Integer" (arbitrary :: Gen Integer) integral + readShowEquivalence "Int" (arbitrary :: Gen Int) integral + readShowEquivalence "Int8" (arbitrary :: Gen Int8) integral + readShowEquivalence "Int16" (arbitrary :: Gen Int16) integral + readShowEquivalence "Int32" (arbitrary :: Gen Int32) integral + readShowEquivalence "Int64" (arbitrary :: Gen Int64) integral + readShowEquivalence "Word" (arbitrary :: Gen Word) integral + readShowEquivalence "Word8" (arbitrary :: Gen Word8) integral + readShowEquivalence "Word16" (arbitrary :: Gen Word16) integral + readShowEquivalence "Word32" (arbitrary :: Gen Word32) integral + readShowEquivalence "Word64" (arbitrary :: Gen Word64) integral + readShowEquivalence "Double" (floats :: Gen Double) floating + readShowEquivalence "Float" (floats :: Gen Float) floating + readShowEquivalence "String" (listOf characters) string + readShowEquivalence "[Int]" (arbitrary :: Gen [Int]) (listing integral) + readShowEquivalence "[[Integer]]" (arbitrary :: Gen [[Integer]]) (listing (listing integral)) + readShowEquivalence "Bool" (arbitrary :: Gen Bool) relexed + readShowEquivalence "Ordering" (arbitrary :: Gen Ordering) relexed + readShowEquivalence "()" (arbitrary :: Gen ()) relexed + readShowEquivalence "Maybe Int" (arbitrary :: Gen (Maybe Int)) relexed + readShowEquivalence "Either Int Bool" (arbitrary :: Gen (Either Int Bool)) relexed + readShowEquivalence "(Int, Bool)" (arbitrary :: Gen (Int, Bool)) relexed + readShowEquivalence "(Char, String, Integer)" (arbitrary :: Gen (Char, String, Integer)) relexed + readShowEquivalence "[Maybe (Either Bool Integer)]" + (arbitrary :: Gen [Maybe (Either Bool Integer)]) relexed + readShowEquivalence "Maybe (Maybe Double)" (arbitrary :: Gen (Maybe (Maybe Double))) relexed + readShowEquivalence "Shapes" (arbitrary :: Gen Shapes) relexed + readShowEquivalence "Maybe Shapes" (arbitrary :: Gen (Maybe Shapes)) relexed diff --git a/distributors-grammar/test/Properties/Kleene.hs b/distributors-grammar/test/Properties/Kleene.hs index fddc561a..03602fef 100644 --- a/distributors-grammar/test/Properties/Kleene.hs +++ b/distributors-grammar/test/Properties/Kleene.hs @@ -58,16 +58,16 @@ kleeneProperties :: Spec kleeneProperties = do -- Small regular expressions, since `readG` backtracks exponentially. describe "Read & Show, as of strings" $ modifyMaxSize (const 8) $ do - prop "read . show = id for RegString" $ \(x :: RegEx Char) -> - let r = reparsed (RegString x) in read (show r) === r - prop "reads a RegString within a list & a Maybe" $ \(x :: RegEx Char) -> - let r = reparsed (RegString x) + prop "read . show = id for RegEx Char" $ \(x :: RegEx Char) -> + let r = reparsed x in read (show r) === r + prop "reads a RegEx Char within a list & a Maybe" $ \(x :: RegEx Char) -> + let r = reparsed x in read (show [r, r]) === [r, r] .&&. read (show (Just r)) === Just r - prop "reads a RegString, leaving the rest" $ \(x :: RegEx Char) -> - let r = reparsed (RegString x) + prop "reads a RegEx Char, leaving the rest" $ \(x :: RegEx Char) -> + let r = reparsed x in reads (show r <> " rest") === [(r, " rest")] - it "read . show = id for RegBnf" $ do - let bnf = fromString "{start} = \\q{a}|b*\n{a} = a" :: RegBnf + it "read . show = id for Bnf (RegEx Char)" $ do + let bnf = fromString "{start} = \\q{a}|b*\n{a} = a" :: Bnf (RegEx Char) read (show bnf) `shouldBe` bnf read (show [bnf]) `shouldBe` [bnf] describe "KleeneStarAlgebra" $ do @@ -215,8 +215,8 @@ kleeneProperties = do prop "x >&< x = x" $ \(x :: TokenClass Char) -> (x >&< x) == x --- | A `RegString` as its printed text parses, which `read` reads. -reparsed :: RegString -> RegString +-- | A `RegEx Char` as its printed text parses, which `read` reads. +reparsed :: RegEx Char -> RegEx Char reparsed = fromList . toList diff --git a/distributors-grammar/test/Properties/Pretty.hs b/distributors-grammar/test/Properties/Pretty.hs new file mode 100644 index 00000000..9dd70689 --- /dev/null +++ b/distributors-grammar/test/Properties/Pretty.hs @@ -0,0 +1,34 @@ +module Properties.Pretty (prettyProperties) where + +import Control.Lens.Grammar hiding (List) +import Data.Foldable (for_) +import Prettyprinter (LayoutOptions (..), PageWidth (..)) +import Examples.SExpr +import Test.Hspec + +prettyProperties :: Spec +prettyProperties = do + let + width n = LayoutOptions (AvailablePerLine n 1) + styles = + [ PrettyLayout (width 80), PrettyLayout (width 10) + , SmartLayout (width 10), CompactLayout ] + parsed = parseP (prettyGrammar :: Parsor String Maybe SExpr SExpr) + bnf = runGrammor (prettyGrammar :: Grammor (Bnf (RegEx Char)) SExpr SExpr) + define = List + [ Atom "define", List [Atom "square", Atom "x"] + , List [Atom "*", Atom "x", Atom "x"] ] + it "prints flat where it fits" $ + for_ sexprExamples $ \(sexpr, str) -> + layoutG (PrettyLayout (width 80)) sexpr `shouldBe` Just str + it "breaks lines where it doesn't fit, aligned" $ + layoutG (PrettyLayout (width 20)) define + `shouldBe` Just "(define\n (square x)\n (* x x))" + it "parses what it prints, in every layout style" $ + for_ sexprExamples $ \(sexpr, _) -> for_ styles $ \style -> + (layoutG style sexpr >>= parsed) `shouldBe` Just (sexpr, "") + it "parses any indentation" $ + parsed "(define\n(square x)\n (* x x))" `shouldBe` Just (define, "") + it "describes every layout it prints, as a Bnf" $ + for_ sexprExamples $ \(sexpr, _) -> for_ styles $ \style -> + fmap (=~ bnf) (layoutG style sexpr) `shouldBe` Just True diff --git a/distributors-grammar/test/Properties/Varifocal.hs b/distributors-grammar/test/Properties/Varifocal.hs index c4d7e535..8edab3ad 100644 --- a/distributors-grammar/test/Properties/Varifocal.hs +++ b/distributors-grammar/test/Properties/Varifocal.hs @@ -1,9 +1,12 @@ module Properties.Varifocal (varifocalProperties) where -import Control.Lens.Grammar +import Control.Comonad.Cofree (Cofree (..)) +import Control.Lens.Grammar hiding ((:<)) import Data.Char (digitToInt, isDigit) import Data.Foldable (for_) import Data.Maybe (fromMaybe) +import Data.Sequence (Seq) +import qualified Data.Sequence as Seq import Text.Read (readMaybe) import Examples.Heredoc import Test.Hspec @@ -49,6 +52,27 @@ varifocalProperties = do prop "doesn't print an early end" $ forAll plain $ \s -> forAll plain $ \t -> printed ended (s ++ "." ++ t ++ ".") === Nothing + describe "ctxList, over any Cons stream" $ + it "terminates a Seq as it does a list" $ do + let seqTerminated :: Varifocal' (Seq Char) Char + seqTerminated = terminateBy (== '.') + parseP (contextuallyT seqTerminated (anyToken :: Parsor String Maybe Char Char)) "ab.c" + `shouldBe` Just (Seq.fromList "ab.", "c") + (($ "") <$> printP (contextuallyT seqTerminated (anyToken :: Printor String Maybe Char Char)) (Seq.fromList "ab.")) + `shouldBe` Just "ab." + describe "ctxTree, by arityWith" $ do + let + counted :: Varifocal' (Cofree [] Char) Char + counted = arityWith digitToInt + tree = '2' :< ['1' :< ['0' :< []], '0' :< []] + parsedT = parseP (contextuallyT counted (anyToken :: Parsor String Maybe Char Char)) + printedT = fmap ($ "") . printP (contextuallyT counted (anyToken :: Printor String Maybe Char Char)) + it "parses a count-prefixed tree, in preorder" $ + parsedT "2100rest" `shouldBe` Just (tree, "rest") + it "prints it, in preorder" $ + printedT tree `shouldBe` Just "2100" + it "won't print a node with other than its count of children" $ + map printedT ['1' :< [], '0' :< ['0' :< []]] `shouldBe` [Nothing, Nothing] describe "balanceBy & countWith, by ctxList" $ do let nested :: Varifocal' String Char @@ -160,14 +184,14 @@ varifocalProperties = do describe "contextually, in a CtxGrammar" $ do for_ heredocExamples $ \(h, str) -> it ("parses, prints & parsecs " <> show str <> " as heredocP does") $ do - [x | (x, "") <- parseG heredocG str] `shouldBe` [h] - [pr "" | pr <- printG heredocG h] `shouldBe` [str] - parsecResult (parsecG heredocG str) `shouldBe` Just h - parsecResult (unparsecG heredocG h "") `shouldBe` Just h + [x | (x, "") <- parseG str] `shouldBe` [h] + [pr "" | pr <- printG h] `shouldBe` [str] + parsecResult (parsecG str) `shouldBe` Just h + parsecResult (unparsecG h "") `shouldBe` Just h it "doesn't print a body line equal to its tag" $ - [pr "" | pr <- printG heredocG (Heredoc "EOF" ["EOF"])] `shouldBe` [] + [pr "" | pr <- printG (Heredoc "EOF" ["EOF"])] `shouldBe` [] it "backtracks by Parsector, closing at the first line equal to its tag" $ - parsecResult (parsecG heredocG "<?<*, Bifocal's applicator" $ do prop "applies a Prismoid as >?* does" $ \(s :: String) -> parseP (atLeast 1 >?<* (anyToken :: Parsor String Maybe Char Char)) s diff --git a/distributors-json/CHANGELOG.md b/distributors-json/CHANGELOG.md index 12750ac0..7394bdfb 100644 --- a/distributors-json/CHANGELOG.md +++ b/distributors-json/CHANGELOG.md @@ -3,6 +3,7 @@ ## 0.1.0.0 - Split out of `distributors` as its own package. +- Types' rules are named by `ruleTyped`, of `distributors-grammar`. - `jsonType` types a type's JSON as a `Bnf` of `JsonType`s, `jsonTsDeclarations` declares them in TypeScript, & `jsonTsPut` puts those declarations to a handle, replacing `jsonTypes`. diff --git a/distributors-json/bench/Main.hs b/distributors-json/bench/Main.hs index db0d5f49..d01ae310 100644 --- a/distributors-json/bench/Main.hs +++ b/distributors-json/bench/Main.hs @@ -309,6 +309,6 @@ tsTypes as = Text.pack (tsSource (jsonTsDeclarations as)) -- | Print declarations as tokens, & tokens as characters, by Parsector. tsSource :: [TsDeclaration] -> String -tsSource declarations = toList $ parsecStream $ unparsecG tsTokensGrammar - (toList (parsecStream (unparsecG tsGrammar declarations (Seq.empty @TsToken)))) +tsSource declarations = toList $ parsecStream $ unparsecG + (toList (parsecStream (unparsecG declarations (Seq.empty @TsToken)))) (Seq.empty @Char) diff --git a/distributors-json/src/Control/Lens/Grammar/Json.hs b/distributors-json/src/Control/Lens/Grammar/Json.hs index 357f463c..59b61677 100644 --- a/distributors-json/src/Control/Lens/Grammar/Json.hs +++ b/distributors-json/src/Control/Lens/Grammar/Json.hs @@ -51,13 +51,13 @@ instance Json Pet where = Grammars A grammar is written once, with the combinators of `JsonVal`, -`JsonObj`, `JsonTup` & `JsonStr`, & `jsonTyped` names its type. +`JsonObj`, `JsonTup` & `JsonStr`, & `ruleTyped` names its type. >>> :{ data Point = Point Double Double deriving stock Show instance Json Point where - json = jsonTyped $ iso (\(Point x y) -> (x, y)) (uncurry Point) + json = ruleTyped $ iso (\(Point x y) -> (x, y)) (uncurry Point) >~ jsonObject ("x" !: json >*< "y" ?: json != 0) :} @@ -77,7 +77,7 @@ _Circle = prism' Circle (\case Circle r -> Just r; _ -> Nothing) _Rectangle :: Prism' Shape (Double, Double) _Rectangle = prism' (uncurry Rectangle) (\case Rectangle w h -> Just (w, h); _ -> Nothing) instance Json Shape where - json = jsonTyped $ orP + json = ruleTyped $ orP [ _Circle >? jsonObject ("kind" !: "circle" >* "radius" !: json) , _Rectangle >? jsonObject ("kind" !: "rectangle" >* "size" !: jsonTuple (jsonElem json >*< jsonElem json)) ] @@ -112,7 +112,7 @@ module Control.Lens.Grammar.Json , jsonErrorEncode , ViaJson (..) -- * Grammar - , JsonVal (..), jsonTyped + , JsonVal (..) , JsonObj (..), (!=) , JsonTup (..) , JsonStr (..), jsonEnum @@ -178,7 +178,7 @@ import Data.IntSet qualified as IntSet import Data.Kind import Data.Type.Bool (type (&&)) import Data.List - (find, findIndices, intercalate, isPrefixOf, nub, sortOn, stripPrefix) + (find, findIndices, intercalate, nub, sortOn, stripPrefix) import Data.List.NonEmpty (NonEmpty, nonEmpty) import Data.Map (Map) import Data.Map qualified as Map @@ -509,7 +509,7 @@ class jsonObjectStrict obj = jsonObject (obj *< dimap (const []) (const ()) (jsonDict jsonText zeroP)) jsonValue :: p Value Value - jsonValue = jsonTyped $ orP + jsonValue = ruleTyped $ orP [ _Null >? jsonNull , _Bool >? jsonBool , _Number >? jsonNumber @@ -519,45 +519,8 @@ class >? jsonObject (jsonDict jsonKeyText jsonValue) ] -{- | 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, and displays it unqualified, -as @x@, in error messages & TypeScript, 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@. --} -jsonTyped - :: forall a p. (Typeable a, JsonStr p) => p a a -> p a a -jsonTyped = rule (qualifiedName (SomeTypeRep (typeRep @a))) -{-# INLINE jsonTyped #-} - --- | A type, `show`n with its type constructors qualified by their modules. -qualifiedName :: SomeTypeRep -> String -qualifiedName (SomeTypeRep rep) = case (bracketed tyCon, args) of - (Just "List", [arg]) -> "[" <> qualifiedName arg <> "]" - (Just "Unit", []) -> "()" - (Just _, _ : _ : _) -> - "(" <> intercalate "," (map qualifiedName args) <> ")" - _ -> unwords (qualified : map typeArgument args) - where - (tyCon, args) = splitApps rep - qualified = tyConModule tyCon <> "." <> tyConName tyCon - typeArgument arg@(SomeTypeRep argRep) = case splitApps argRep of - (argCon, _ : _) | isNothing (bracketed argCon) -> - "(" <> qualifiedName arg <> ")" - _ -> qualifiedName arg - -- The constructors of lists & tuples, which bracket their arguments. - bracketed con = case (tyConModule con, tyConName con) of - ("GHC.Types", "List") -> Just "List" - ("GHC.Tuple", name) | name == "Unit" || "Tuple" `isPrefixOf` name -> - Just name - _ -> Nothing - {- | A rule name's display, with its module-qualified words unqualified, -by the naming convention of `jsonTyped`. +by the naming convention of `Control.Lens.Grammar.BackusNaur.ruleTyped`. -} unqualified :: String -> String unqualified = \case @@ -925,9 +888,10 @@ instance DisjunctiveMonoid (JsonParsor a b) where where -- An array which the first alternative parses, element by element. array = jsonParsorArray p -instance BackusNaurForm (JsonParsor a b) where +instance Ruled (JsonParsor a b) where rule name p = (mapParsing (onFailure (jsonRelabel (unqualified name)) .) p) {jsonParsorArray = jsonParsorArray p, jsonParsorText = jsonParsorText p} +instance BackusNaurForm (JsonParsor a b) where ruleRec name f = fix (rule name . f) instance (x ~ (), y ~ ()) => IsString (JsonParsor x y) where fromString s = JsonParsor @@ -1219,8 +1183,8 @@ instance (AesonStr key, x ~ (), y ~ ()) => IsString (KeyPrintor key x y) where where literal = aesonLiteral (Text.pack s) -- | A key's `rule` names nothing to print. +instance Ruled (KeyPrintor key a b) instance BackusNaurForm (KeyPrintor key a b) where - rule _ = id ruleRec _ = fix instance AesonStr key => JsonStr (KeyPrintor key) where jsonText = KeyPrintor aesonText @@ -1560,14 +1524,15 @@ instance AesonVal val => DisjunctiveMonoid (JsonPrintor val a b) where Its totality assumes the rules being determined are total, by induction on the values printed. -} -instance BackusNaurForm (JsonPrintor val a b) where +instance Ruled (JsonPrintor val a b) where rule name p = p { printorTotal = \rules -> Set.member name rules || printorTotal p (Set.insert name rules) , printorCheck = onFailure (jsonRelabel (unqualified name)) . printorCheck p } - ruleRec name f = fix (rule name . f) {-# INLINE rule #-} +instance BackusNaurForm (JsonPrintor val a b) where + ruleRec name f = fix (rule name . f) instance (AesonStr val, x ~ (), y ~ ()) => IsString (JsonPrintor val x y) where fromString s = printing (const literal) @@ -2146,9 +2111,9 @@ jsonTsPut as handle = case (parsecResult printed, parsecResult source) of _ -> hPutStr handle (toList (parsecStream source)) where -- Printed into sequences, which grow at their ends in constant time. - printed = unparsecG tsGrammar (jsonTsDeclarations as) (Seq.empty @TsToken) + printed = unparsecG (jsonTsDeclarations as) (Seq.empty @TsToken) source = - unparsecG tsTokensGrammar (toList (parsecStream printed)) (Seq.empty @Char) + unparsecG (toList (parsecStream printed)) (Seq.empty @Char) unprinted layer stage = ioError $ userError $ "jsonTsPut: cannot print " <> layer <> " at " <> show (parsecOffset stage) <> ", expecting " @@ -2215,8 +2180,9 @@ instance CocartesianChoice JsonTypor where instance DisjunctiveMonoid (JsonTypor a b) where falseP = typing falseP JsonTypor t0 >|< JsonTypor t1 = JsonTypor (liftA2 (>|<) t0 t1) -instance BackusNaurForm (JsonTypor a b) where +instance Ruled (JsonTypor a b) where rule = typeRule +instance BackusNaurForm (JsonTypor a b) where ruleRec name f = rule name (f (typeRule name falseP)) instance (x ~ (), y ~ ()) => IsString (JsonTypor x y) where fromString = typing . JsonLiteral . Text.pack @@ -2662,7 +2628,7 @@ instance Json Bool where {-# INLINE json #-} jsonKey = Just (jsonEnumerated (\b -> if b then "true" else "false")) instance Json Ordering where - json = jsonTyped (jsonEnumerated (Text.pack . show)) + json = ruleTyped (jsonEnumerated (Text.pack . show)) instance Json () where json = jsonTuple oneP jsonOmitField = Just (only ()) @@ -2678,7 +2644,7 @@ jsonChar = prism' Text.singleton single ?< jsonText _ -> Nothing instance Json Char where - json = jsonTyped jsonChar + json = ruleTyped jsonChar jsonList = jsonString jsonKey = Just jsonChar jsonKeyList = Just jsonString @@ -2692,10 +2658,10 @@ instance Json a => Json (Maybe a) where instance (Json a, Json b) => Json (Either a b) where json = jsonTag "Left" json >+< jsonTag "Right" json instance Json Double where - json = jsonTyped (jsonRealFloat jsonDouble) + json = ruleTyped (jsonRealFloat jsonDouble) jsonKey = Just jsonRealFloatKey instance Json Float where - json = jsonTyped $ + json = ruleTyped $ jsonRealFloat (iso fromFloatDigits toRealFloat >~ jsonNumber) jsonKey = Just jsonRealFloatKey instance (Integral a, Json a) => Json (Ratio a) where @@ -2707,41 +2673,41 @@ instance HasResolution a => Json (Fixed a) where json = jsonRealFrac jsonKey = Just (iso realToFrac realToFrac >~ jsonScientificKey) instance Json Int where - json = jsonTyped jsonInt + json = ruleTyped jsonInt {-# INLINE json #-} jsonKey = Just (jsonIntKey _BoundedInteger) instance Json Int8 where - json = jsonTyped jsonInt8 + json = ruleTyped jsonInt8 jsonKey = Just (jsonIntKey _BoundedInteger) instance Json Int16 where - json = jsonTyped jsonInt16 + json = ruleTyped jsonInt16 jsonKey = Just (jsonIntKey _BoundedInteger) instance Json Int32 where - json = jsonTyped jsonInt32 + json = ruleTyped jsonInt32 jsonKey = Just (jsonIntKey _BoundedInteger) instance Json Int64 where - json = jsonTyped jsonInt64 + json = ruleTyped jsonInt64 jsonKey = Just (jsonIntKey _BoundedInteger) instance Json Word where - json = jsonTyped jsonWord + json = ruleTyped jsonWord jsonKey = Just (jsonIntKey _BoundedInteger) instance Json Word8 where - json = jsonTyped jsonWord8 + json = ruleTyped jsonWord8 jsonKey = Just (jsonIntKey _BoundedInteger) instance Json Word16 where - json = jsonTyped jsonWord16 + json = ruleTyped jsonWord16 jsonKey = Just (jsonIntKey _BoundedInteger) instance Json Word32 where - json = jsonTyped jsonWord32 + json = ruleTyped jsonWord32 jsonKey = Just (jsonIntKey _BoundedInteger) instance Json Word64 where - json = jsonTyped jsonWord64 + json = ruleTyped jsonWord64 jsonKey = Just (jsonIntKey _BoundedInteger) instance Json Integer where - json = jsonTyped jsonInteger + json = ruleTyped jsonInteger jsonKey = Just (jsonIntKey _Integer) instance Json Natural where - json = jsonTyped jsonNatural + json = ruleTyped jsonNatural jsonKey = Just (jsonIntKey _Natural) instance Json CTime where json = coerced >~ json @Int64 @@ -2752,7 +2718,7 @@ jsonVersion = prism' (Text.pack . showVersion) version ?< jsonText listToMaybe [v | (v, "") <- readP_to_S parseVersion (Text.unpack t)] instance Json Version where - json = jsonTyped jsonVersion + json = ruleTyped jsonVersion jsonKey = Just jsonVersion instance Json a => Json (NonEmpty a) where json = prism' toList nonEmpty ?< jsonTuple (someP (jsonElem json)) @@ -3029,7 +2995,7 @@ instance (Ord k, Json k, Json v) => Json (Map k v) where Just key -> jsonMap key json Nothing -> iso Map.toList Map.fromList >~ json instance (Typeable a, Json a) => Json (Tree a) where - json = jsonTyped gtuple + json = ruleTyped gtuple -- dlist instance Json a => Json (DList a) where @@ -3073,7 +3039,7 @@ instance Json v => Json (KeyMap v) where instance Json Value where json = jsonValue instance Json DotNetTime where - json = jsonTyped (prism' render parse ?< jsonText) + json = ruleTyped (prism' render parse ?< jsonText) where render (DotNetTime t) = Text.pack ( formatTime defaultTimeLocale "/Date(%s" t @@ -3100,48 +3066,48 @@ encodedTime f g = prism _Day :: Prism Text (Text, Encoding.Encoding' Text) Day Day _Day = encodedTime Encoding.day TimeText.parseDay instance Json Day where - json = jsonTyped (jsonEncodedText _Day) + json = ruleTyped (jsonEncodedText _Day) jsonKey = Just (jsonEncodedText _Day) _Month :: Prism Text (Text, Encoding.Encoding' Text) Month Month _Month = encodedTime Encoding.month TimeText.parseMonth instance Json Month where - json = jsonTyped (jsonEncodedText _Month) + json = ruleTyped (jsonEncodedText _Month) jsonKey = Just (jsonEncodedText _Month) _Quarter :: Prism Text (Text, Encoding.Encoding' Text) Quarter Quarter _Quarter = encodedTime Encoding.quarter TimeText.parseQuarter instance Json Quarter where - json = jsonTyped (jsonEncodedText _Quarter) + json = ruleTyped (jsonEncodedText _Quarter) jsonKey = Just (jsonEncodedText _Quarter) _TimeOfDay :: Prism Text (Text, Encoding.Encoding' Text) TimeOfDay TimeOfDay _TimeOfDay = encodedTime Encoding.timeOfDay TimeText.parseTimeOfDay instance Json TimeOfDay where - json = jsonTyped (jsonEncodedText _TimeOfDay) + json = ruleTyped (jsonEncodedText _TimeOfDay) jsonKey = Just (jsonEncodedText _TimeOfDay) _LocalTime :: Prism Text (Text, Encoding.Encoding' Text) LocalTime LocalTime _LocalTime = encodedTime Encoding.localTime TimeText.parseLocalTime instance Json LocalTime where - json = jsonTyped (jsonEncodedText _LocalTime) + json = ruleTyped (jsonEncodedText _LocalTime) jsonKey = Just (jsonEncodedText _LocalTime) _ZonedTime :: Prism Text (Text, Encoding.Encoding' Text) ZonedTime ZonedTime _ZonedTime = encodedTime Encoding.zonedTime TimeText.parseZonedTime instance Json ZonedTime where - json = jsonTyped (jsonEncodedText _ZonedTime) + json = ruleTyped (jsonEncodedText _ZonedTime) jsonKey = Just (jsonEncodedText _ZonedTime) _UTCTime :: Prism Text (Text, Encoding.Encoding' Text) UTCTime UTCTime _UTCTime = encodedTime Encoding.utcTime TimeText.parseUTCTime instance Json UTCTime where - json = jsonTyped (jsonEncodedText _UTCTime) + json = ruleTyped (jsonEncodedText _UTCTime) jsonKey = Just (jsonEncodedText _UTCTime) -instance Json NominalDiffTime where json = jsonTyped jsonRealFrac -instance Json DiffTime where json = jsonTyped jsonRealFrac +instance Json NominalDiffTime where json = ruleTyped jsonRealFrac +instance Json DiffTime where json = ruleTyped jsonRealFrac instance Json SystemTime where - json = jsonTyped (prism' render parse ?< jsonNumber) + json = ruleTyped (prism' render parse ?< jsonNumber) where render (MkSystemTime s ns) = realToFrac (fromIntegral s + fromIntegral ns / 1000000000 :: Nano) @@ -3166,16 +3132,16 @@ weekdays = jsonEnumWith (\day -> fromEnum day - 1) ] instance Json DayOfWeek where - json = jsonTyped weekdays - jsonKey = Just (jsonTyped weekdays) + json = ruleTyped weekdays + jsonKey = Just (ruleTyped weekdays) -- | Quarters of the year, named as @aeson@ names them. quarters :: JsonStr p => p QuarterOfYear QuarterOfYear quarters = jsonEnumerated (Text.toLower . Text.pack . show) instance Json QuarterOfYear where - json = jsonTyped quarters - jsonKey = Just (jsonTyped quarters) + json = ruleTyped quarters + jsonKey = Just (ruleTyped quarters) -- uuid-types @@ -3183,7 +3149,7 @@ jsonUUID :: JsonStr p => p UUID UUID jsonUUID = prism' UUID.toText UUID.fromText ?< jsonText instance Json UUID where - json = jsonTyped jsonUUID + json = ruleTyped jsonUUID jsonKey = Just jsonUUID -- network-uri @@ -3195,12 +3161,12 @@ jsonURI = prism' ?< jsonText instance Json URI where - json = jsonTyped jsonURI + json = ruleTyped jsonURI jsonKey = Just jsonURI -- data-fix instance (Typeable f, Json (f (Fix f))) => Json (Fix f) where - json = jsonTyped (iso unFix Fix >~ json) + json = ruleTyped (iso unFix Fix >~ json) instance (Functor f, Typeable f, Json (f (Fix f))) => Json (Mu f) where json = iso (foldMu Fix) (unfoldMu unFix) >~ json @(Fix f) instance (Functor f, Typeable f, Json (f (Fix f))) => Json (Nu f) where @@ -3265,7 +3231,7 @@ jsonGeneric . ( GHC.Generic a, GHC.Rep a ~ GHC.D1 d f, GSum f, Typeable a , EnumTag (AllNullary f) a, JsonVal p ) => Aeson.Options -> p a a -jsonGeneric opts = jsonTyped $ case (enumIndex @(AllNullary f) @a, gtable @f opts) of +jsonGeneric opts = ruleTyped $ case (enumIndex @(AllNullary f) @a, gtable @f opts) of (Just indexOf, Just table) | Aeson.allNullaryToStringTag opts , gconCount @f > 1 || Aeson.tagSingleConstructors opts -> diff --git a/distributors-json/src/Control/Lens/Grammar/TypeScript.hs b/distributors-json/src/Control/Lens/Grammar/TypeScript.hs index f81edb19..e95ce796 100644 --- a/distributors-json/src/Control/Lens/Grammar/TypeScript.hs +++ b/distributors-json/src/Control/Lens/Grammar/TypeScript.hs @@ -23,11 +23,11 @@ syntax needs more lookahead. Here, a declaration prints as tokens, >>> :set -XOverloadedStrings >>> let point = ObjectType [PropertySignature [] (PropertyIdentifier "x") False (Just (KeywordType NumberKeyword))] ->>> let printed = unparsecG tsGrammar [TypeAliasDeclaration [ExportKeyword] "Point" [] point] ([] :: [TsToken]) ->>> let source = parsecStream (unparsecG tsTokensGrammar (parsecStream printed) ("" :: String)) +>>> let printed = unparsecG [TypeAliasDeclaration [ExportKeyword] "Point" [] point] ([] :: [TsToken]) +>>> let source = parsecStream (unparsecG (parsecStream printed) ("" :: String)) >>> putStr source export type Point = { x: number }; ->>> parsecResult (parsecG tsGrammar (concat (parsecResult (parsecG tsTokensGrammar source)))) == Just [TypeAliasDeclaration [ExportKeyword] "Point" [] point] +>>> parsecResult (parsecG @[TsDeclaration] (concat (parsecResult (parsecG @[TsToken] source)))) == Just [TypeAliasDeclaration [ExportKeyword] "Point" [] point] True -} @@ -66,11 +66,10 @@ module Control.Lens.Grammar.TypeScript import Control.Lens import Control.Lens.Grammar import Data.Char (chr, ord) -import Data.Maybe (fromMaybe, listToMaybe) +import Data.Maybe (fromMaybe) import Data.Profunctor.Monadic.Do qualified as P import Data.Text (Text) import Data.Text qualified as Text -import Numeric (readHex, showHex) -- $setup -- >>> import Control.Lens.Grammar @@ -472,7 +471,7 @@ as in @0xFF@, @1_000.5@ or @1n@, but not by a signed exponent. It's a `RegGrammar`, since each token's spelling is a regular language. -} -tsTokenGrammar :: RegGrammar Char TsToken +tsTokenGrammar :: RegGrammatical Char p => p TsToken TsToken tsTokenGrammar = orP [ kindOf WhitespaceTrivia >? someP (oneOf @Char (" \t\f\v" :: String)) , kindOf NewLineTrivia >? orP @@ -524,7 +523,7 @@ tsTokenGrammar = orP ) *< terminal "/" -identifierStart :: RegGrammar Char Char +identifierStart :: RegGrammatical Char p => p Char Char identifierStart = orP [ asIn @Char UppercaseLetter, asIn @Char LowercaseLetter , asIn @Char TitlecaseLetter, asIn @Char ModifierLetter @@ -532,7 +531,7 @@ identifierStart = orP , oneOf @Char ("_$" :: String) ] -stringChar :: Char -> RegGrammar Char Char +stringChar :: RegGrammatical Char p => Char -> p Char Char stringChar quote = orP [ notOneOf @Char (quote : '\\' : ['\0' .. '\31']) , terminal "\\" >* orP @@ -540,13 +539,11 @@ stringChar quote = orP , only '\b' >? terminal "b", only '\f' >? terminal "f" , only '\n' >? terminal "n", only '\r' >? terminal "r" , only '\t' >? terminal "t" - , terminal "u" >* (_HexCode >? replicateP 4 (oneOf @Char hexDigits)) + , terminal "u" >* (_HexCode >? replicateP 4 (digit (16 :: Int))) ] ] - where - hexDigits = "0123456789abcdefABCDEF" :: String -templateChar :: RegGrammar Char Char +templateChar :: RegGrammatical Char p => p Char Char templateChar = orP [ notOneOf @Char ("`$\\" :: String) , terminal "\\" >* oneOf @Char ("`$\\" :: String) @@ -563,7 +560,7 @@ It's a `CtxGrammar` by monadic bonding: each token is scanned in the context of the tokens before it, whose braces & templates bond, by @P.@`Data.Profunctor.Monadic.Do.>>=`, the depths that a @}@ is scanned by. -} -tsTokensGrammar :: CtxGrammar Char [TsToken] +tsTokensGrammar :: CtxGrammatical Char p => p [TsToken] [TsToken] tsTokensGrammar = rmap (\scanned -> [t | t <- scanned, tokenCategory t `notElem` trivial]) (tokensWithin []) @@ -577,7 +574,7 @@ tsTokensGrammar = rmap within each, innermost first. -} tokensWithin - :: (Lexical Char p, Alternator p, Filtrator p, MonadicTry p) + :: CtxGrammatical Char p => [Int] -> p [TsToken] [TsToken] tokensWithin depths = orP [ _Cons >? (tokenWithin P.>>= tokensWithin . within depths) @@ -685,20 +682,17 @@ _Template = prism' templates = [NoSubstitutionTemplateLiteral, TemplateHead, TemplateMiddle, TemplateTail] --- | A character, by the hexadecimal digits of a @\\u@ escape. -_HexCode :: Prism' Char String +-- | A character, by the four hexadecimal digits of a @\\u@ escape. +_HexCode :: Prism' Char [Int] _HexCode = prism' - (\digits -> chr (maybe 0 fst (listToMaybe (readHex digits)))) + (chr . foldl' (\n d -> n * 16 + d) 0) (\c -> if ord c < 0x10000 - then Just (pad (showHex (ord c) "")) else Nothing) - where - pad digits = replicate (4 - length digits) '0' <> digits + then Just [ord c `div` 16 ^ k `mod` 16 | k <- [3, 2, 1, 0 :: Int]] else Nothing) -- Syntax -- -- | The interpreters of TypeScript's syntax. -type TsGrammatical p = - (Lexical TsToken p, Alternator p, Filtrator p, MonadicTry p) +type TsGrammatical p = CtxGrammatical TsToken p {- | The declarations of a declaration file, of tokens, by the TypeScript compiler's syntax, printed one per line, indented within blocks, & with @@ -718,7 +712,7 @@ Printing a file, of many tokens, is linear into a stream which grows at its end in constant time, like a `Data.Sequence.Seq`, rather than a list. -} -tsGrammar :: CtxGrammar TsToken [TsDeclaration] +tsGrammar :: CtxGrammatical TsToken p => p [TsDeclaration] [TsDeclaration] tsGrammar = manyP (declaration 0 *< newline) -- | A declaration, at a depth of indentation. @@ -1307,6 +1301,7 @@ literal = orP , _BigIntegerLiteral >? signed BigIntLiteral ] where + signed :: RegGrammatical TsToken q => TsTokenCategory -> q Text Text signed category = orP [ _Negative >? tokenOf oneP MinusToken oneP >* textOf category , textOf category @@ -1437,29 +1432,35 @@ _Conditional = iso -- Trivia -- -- | Trivia, of whitespace & newlines, printed as some trivia. -trivia :: (Lexical TsToken p, Alternator p) => [TsToken] -> p () () +trivia :: RegGrammatical TsToken p => [TsToken] -> p () () trivia shown = dimap (const shown) (const ()) (manyP (asIn @TsToken WhitespaceTrivia >|< asIn @TsToken NewLineTrivia)) -space :: (Lexical TsToken p, Alternator p) => p () () +space :: RegGrammatical TsToken p => p () () space = trivia [TsToken WhitespaceTrivia " "] -newline :: (Lexical TsToken p, Alternator p) => p () () +newline :: RegGrammatical TsToken p => p () () newline = trivia [TsToken NewLineTrivia "\n"] -- | A newline, indented four spaces for each depth. -indented :: (Lexical TsToken p, Alternator p) => Int -> p () () +indented :: RegGrammatical TsToken p => Int -> p () () indented depth = trivia $ TsToken NewLineTrivia "\n" : [TsToken WhitespaceTrivia (Text.replicate (4 * depth) " ") | depth > 0] -- | A punctuation or keyword token, between trivia, or `oneP`. tokenOf - :: (Lexical TsToken p, Alternator p) + :: RegGrammatical TsToken p => p () () -> TsTokenCategory -> p () () -> p () () tokenOf before category after = before >* terminal [symbol category] *< after -- | The text of a token of a category. textOf - :: (Lexical TsToken p, Alternator p) => TsTokenCategory -> p Text Text + :: RegGrammatical TsToken p => TsTokenCategory -> p Text Text textOf category = iso (TsToken category) tokenText >~ asIn @TsToken category + +instance CtxGrammar Char TsToken +instance Grammar Char TsToken +instance RegGrammar Char TsToken where regGrammar = tsTokenGrammar +instance CtxGrammar Char [TsToken] where ctxGrammar = tsTokensGrammar +instance CtxGrammar TsToken [TsDeclaration] where ctxGrammar = tsGrammar diff --git a/distributors-json/test/Properties/Json.hs b/distributors-json/test/Properties/Json.hs index 93d84ee0..1b9ff352 100644 --- a/distributors-json/test/Properties/Json.hs +++ b/distributors-json/test/Properties/Json.hs @@ -22,7 +22,7 @@ module Properties.Json import Control.Lens (coerced, only, prism') import Control.Lens.Grammar ( ParsecState (..), dimap, falseP, lmap, manyP, optK, optionP, optionalP - , parsecG, plusK, rule, someP, starK, unparsecG + , parsecG, plusK, rule, ruleTyped, someP, starK, unparsecG , (>*<), (>+<), (>?), (>|<), (>~) ) import Control.Lens.Grammar.Json @@ -173,35 +173,35 @@ instance (Typeable a, Json a) => Json (Box a) newtype Dup = Dup (Int, Int) deriving stock Show instance Json Dup where - json = jsonTyped $ dimap (\(Dup p) -> p) Dup + json = ruleTyped $ dimap (\(Dup p) -> p) Dup (jsonObject (("k" !: json) >*< ("k" !: json))) -- | A limit, @10@ by default, which is missing exactly when it's @10@. newtype Limit = Limit Int deriving stock (Eq, Show) instance Json Limit where - json = jsonTyped $ dimap (\(Limit n) -> n) Limit $ + json = ruleTyped $ dimap (\(Limit n) -> n) Limit $ jsonObject ("limit" ?: json != 10) -- | An identifier and the rest of the properties, booleans. newtype Extra = Extra (Int, [(Text, Bool)]) deriving stock (Eq, Show) instance Json Extra where - json = jsonTyped $ dimap (\(Extra p) -> p) Extra $ + json = ruleTyped $ dimap (\(Extra p) -> p) Extra $ jsonObject ("id" !: json >*< jsonDict jsonText json) -- | A count, positive, filtered from numbers. newtype Counted = Counted Int deriving stock (Eq, Show) instance Json Counted where - json = jsonTyped $ dimap (\(Counted n) -> n) Counted $ + json = ruleTyped $ dimap (\(Counted n) -> n) Counted $ Witherable.mapMaybe (\n -> if n > 0 then Just n else Nothing) json -- | A pet, by an object of a single field, named by its constructor. data Pet = Cat Text | Dog Int deriving stock (Eq, Show) instance Json Pet where - json = jsonTyped $ dimap + json = ruleTyped $ dimap (\case Cat n -> Left n; Dog age -> Right age) (either Cat Dog) (jsonObject ("Cat" !: json >+< "Dog" !: json)) @@ -210,7 +210,7 @@ instance Json Pet where newtype Tally = Tally (Int, [(Bool, Int)]) deriving stock (Eq, Show) instance Json Tally where - json = jsonTyped $ dimap (\(Tally p) -> p) Tally $ jsonObject + json = ruleTyped $ dimap (\(Tally p) -> p) Tally $ jsonObject ( "total" !: json >*< jsonDict (jsonEnumWith fromEnum [("no", False), ("yes", True)]) json @@ -220,7 +220,7 @@ instance Json Tally where newtype Votes = Votes (Int, [(Bool, Int)]) deriving stock (Eq, Show) instance Json Votes where - json = jsonTyped $ dimap (\(Votes p) -> p) Votes $ jsonObject + json = ruleTyped $ dimap (\(Votes p) -> p) Votes $ jsonObject ( "yes" !: json >*< jsonDict (jsonEnumWith fromEnum [("no", False), ("yes", True)]) json @@ -230,7 +230,7 @@ instance Json Votes where newtype Scores = Scores (Text, [(Int, Bool)]) deriving stock (Eq, Show) instance Json Scores where - json = jsonTyped $ dimap (\(Scores p) -> p) Scores $ case jsonKey @Int of + json = ruleTyped $ dimap (\(Scores p) -> p) Scores $ case jsonKey @Int of Just key -> jsonObject ("name" !: json >*< jsonDict key json) Nothing -> error "Int has a key" @@ -238,7 +238,7 @@ instance Json Scores where newtype Closed = Closed Int deriving stock (Eq, Show) instance Json Closed where - json = jsonTyped $ dimap (\(Closed n) -> n) Closed $ + json = ruleTyped $ dimap (\(Closed n) -> n) Closed $ jsonObjectStrict ("id" !: json) jsonObjectSpec :: Spec @@ -331,35 +331,35 @@ jsonObjectSpec = describe "jsonObject" $ do newtype Rest = Rest (Scientific, [Text]) deriving stock (Eq, Show) instance Json Rest where - json = jsonTyped $ dimap (\(Rest p) -> p) Rest $ + json = ruleTyped $ dimap (\(Rest p) -> p) Rest $ jsonTuple (jsonElem json >*< manyP (jsonElem json)) -- | Leading rest strings and a number, @[...string[], number]@. newtype Leading = Leading ([Text], Scientific) deriving stock (Eq, Show) instance Json Leading where - json = jsonTyped $ dimap (\(Leading p) -> p) Leading $ + json = ruleTyped $ dimap (\(Leading p) -> p) Leading $ jsonTuple (manyP (jsonElem json) >*< jsonElem json) -- | A number and an optional string, @[number, string?]@. newtype Trailing = Trailing (Scientific, Maybe Text) deriving stock (Eq, Show) instance Json Trailing where - json = jsonTyped $ dimap (\(Trailing p) -> p) Trailing $ + json = ruleTyped $ dimap (\(Trailing p) -> p) Trailing $ jsonTuple (jsonElem json >*< optionalP (jsonElem json)) -- | An optional string before a number, @[string, number] | [number]@. newtype Before = Before (Maybe Text, Scientific) deriving stock (Eq, Show) instance Json Before where - json = jsonTyped $ dimap (\(Before p) -> p) Before $ + json = ruleTyped $ dimap (\(Before p) -> p) Before $ jsonTuple (optionalP (jsonElem json) >*< jsonElem json) -- | Two rests, @(number | string)[]@. newtype Rests = Rests ([Scientific], [Text]) deriving stock (Eq, Show) instance Json Rests where - json = jsonTyped $ dimap (\(Rests p) -> p) Rests $ + json = ruleTyped $ dimap (\(Rests p) -> p) Rests $ jsonTuple (manyP (jsonElem json) >*< manyP (jsonElem json)) -- | Rest strings and an optional number, @@ -367,28 +367,28 @@ instance Json Rests where newtype RestOptional = RestOptional ([Text], Maybe Scientific) deriving stock (Eq, Show) instance Json RestOptional where - json = jsonTyped $ dimap (\(RestOptional p) -> p) RestOptional $ + json = ruleTyped $ dimap (\(RestOptional p) -> p) RestOptional $ jsonTuple (manyP (jsonElem json) >*< optionalP (jsonElem json)) -- | Alternative elements, @[number | string]@. newtype Alternative = Alternative (Either Scientific Text) deriving stock (Eq, Show) instance Json Alternative where - json = jsonTyped $ dimap (\(Alternative e) -> e) Alternative $ + json = ruleTyped $ dimap (\(Alternative e) -> e) Alternative $ jsonTuple (jsonElem json >+< jsonElem json) -- | Alternative rests, @[...number[]] | [...string[]]@, not mixed. newtype AlternativeRests = AlternativeRests (Either [Scientific] [Text]) deriving stock (Eq, Show) instance Json AlternativeRests where - json = jsonTyped $ dimap (\(AlternativeRests e) -> e) AlternativeRests $ + json = ruleTyped $ dimap (\(AlternativeRests e) -> e) AlternativeRests $ jsonTuple (manyP (jsonElem json) >+< manyP (jsonElem json)) -- | A rest element in the middle, @[number, ...string[], boolean]@. newtype Middle = Middle (Scientific, [Text], Bool) deriving stock (Eq, Show) instance Json Middle where - json = jsonTyped $ dimap + json = ruleTyped $ dimap (\(Middle (a, b, c)) -> (a, (b, c))) (\(a, (b, c)) -> Middle (a, b, c)) (jsonTuple (jsonElem json >*< manyP (jsonElem json) >*< jsonElem json)) @@ -397,21 +397,21 @@ instance Json Middle where newtype AtLeastOne = AtLeastOne [Scientific] deriving stock (Eq, Show) instance Json AtLeastOne where - json = jsonTyped $ dimap (\(AtLeastOne xs) -> xs) AtLeastOne + json = ruleTyped $ dimap (\(AtLeastOne xs) -> xs) AtLeastOne (jsonTuple (someP (jsonElem json))) -- | Alternative shapes, @[number, number?]@. newtype Coord = Coord (Scientific, Scientific) deriving stock (Eq, Show) instance Json Coord where - json = jsonTyped $ dimap (\(Coord xy) -> xy) Coord $ jsonTuple $ + json = ruleTyped $ dimap (\(Coord xy) -> xy) Coord $ jsonTuple $ jsonElem json >*< jsonElem json >|< dimap fst (, 0) (jsonElem json) -- | A defaulted element, @[number, number?]@. newtype Defaulted = Defaulted (Scientific, Scientific) deriving stock (Eq, Show) instance Json Defaulted where - json = jsonTyped $ dimap (\(Defaulted xy) -> xy) Defaulted $ jsonTuple $ + json = ruleTyped $ dimap (\(Defaulted xy) -> xy) Defaulted $ jsonTuple $ jsonElem json >*< optionP (only 0) (jsonElem json) jsonTupleChoiceSpec :: Spec @@ -523,10 +523,10 @@ which parse as the declarations which print them. declares :: forall a -> Json a => [Text] -> Expectation declares a declarations = do tsTypes [a] `shouldBe` Text.unlines declarations - parsecResult (parsecG tsGrammar scanned) `shouldBe` Just declared + parsecResult (parsecG @[TsDeclaration] scanned) `shouldBe` Just declared where declared = jsonTsDeclarations [a] - scanned = concat (parsecResult (parsecG tsTokensGrammar (tsSource declared))) + scanned = concat (parsecResult (parsecG @[TsToken] (tsSource declared))) jsonTypeSpec :: Spec jsonTypeSpec = describe "jsonTsDeclarations" $ do @@ -639,11 +639,11 @@ jsonTypeSpec = describe "jsonTsDeclarations" $ do declares (type Chain) ["export type Chain = null;"] declares (type Loop) ["export type Loop = never;"] --- | A rule of a rule, `jsonTyped` twice. +-- | A rule of a rule, `ruleTyped` twice. newtype Retyped = Retyped Scientific deriving stock Show instance Json Retyped where - json = jsonTyped (jsonTyped (dimap (\(Retyped n) -> n) Retyped json)) + json = ruleTyped (ruleTyped (dimap (\(Retyped n) -> n) Retyped json)) -- | Unguarded recursion, which only encodes as @null@. newtype Chain = Chain (Maybe Chain) @@ -667,7 +667,7 @@ instance (Typeable a, Json a) => Json (Twice a) data Collide = Collide {named :: Scientific, typed :: Point} deriving stock Show instance Json Collide where - json = jsonTyped $ jsonObject $ Collide + json = ruleTyped $ jsonObject $ Collide <$> lmap named ("named" !: rule "Point" jsonNumber) <*> lmap typed ("typed" !: json) @@ -691,7 +691,7 @@ newtype Exclude = Exclude Scientific data Optional = Optional Scientific (Maybe (Either Text Scientific)) deriving stock (Eq, Show) instance Json Optional where - json = jsonTyped $ jsonObject $ Optional + json = ruleTyped $ jsonObject $ Optional <$> lmap (\(Optional a _) -> a) ("a" !: json) <*> lmap (\(Optional _ b) -> b) ("b c" ?: (jsonText >+< jsonNumber)) @@ -1207,8 +1207,8 @@ tsTypes as = Text.pack (tsSource (jsonTsDeclarations as)) -- | Print declarations as tokens, & tokens as characters, by Parsector. tsSource :: [TsDeclaration] -> String -tsSource declarations = toList $ parsecStream $ unparsecG tsTokensGrammar - (toList (parsecStream (unparsecG tsGrammar declarations (Seq.empty @TsToken)))) +tsSource declarations = toList $ parsecStream $ unparsecG + (toList (parsecStream (unparsecG declarations (Seq.empty @TsToken)))) (Seq.empty @Char) -- | The `KleeneStarAlgebra` laws of `JsonElements`. diff --git a/distributors-json/test/Properties/TypeScript.hs b/distributors-json/test/Properties/TypeScript.hs index c243a3dd..562b0863 100644 --- a/distributors-json/test/Properties/TypeScript.hs +++ b/distributors-json/test/Properties/TypeScript.hs @@ -18,21 +18,21 @@ typeScriptSpec = describe "tsGrammar" $ do golden <- readFile "test/Properties/fixture.golden.d.ts" fmap source (declarations golden) `shouldBe` Just golden it "locates failures" $ - parsecOffset (parsecG tsGrammar (tokens "interface A { a: number; b: }")) + parsecOffset (parsecG @[TsDeclaration] (tokens "interface A { a: number; b: }")) `shouldBe` 9 -- | Tokens, scanned without their trivia. tokens :: String -> [TsToken] -tokens = concat . parsecResult . parsecG tsTokensGrammar +tokens = concat . parsecResult . parsecG @[TsToken] -- | Declarations, parsed from all of their tokens. declarations :: String -> Maybe [TsDeclaration] -declarations text = case parsecG tsGrammar (tokens text) of +declarations text = case parsecG @[TsDeclaration] (tokens text) of parsed | null (parsecStream parsed) -> parsecResult parsed _ -> Nothing -- | Print declarations, as tokens & characters, into sequences. source :: [TsDeclaration] -> String -source decls = toList $ parsecStream $ unparsecG tsTokensGrammar - (toList (parsecStream (unparsecG tsGrammar decls (Seq.empty @TsToken)))) +source decls = toList $ parsecStream $ unparsecG + (toList (parsecStream (unparsecG decls (Seq.empty @TsToken)))) (Seq.empty @Char)