From b91642cd386a6ba8b5d19477aed96a75422c49a1 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Fri, 13 Nov 2026 17:11:09 -0800 Subject: [PATCH 01/51] Grammar classes: RegGrammar, Grammar & CtxGrammar; *Grammatical constraints RegGrammar, Grammar & CtxGrammar become classes of a type's grammar over a token, regGrammar, grammar & ctxGrammar, each defaulting to the more restrictive (RegGrammar => Grammar => CtxGrammar). RegGrammatical, Grammatical & CtxGrammatical are the constraints on the profunctors which run them, typing grammar values (p a a). Runners take the grammar from the class: printG, parseG, unparseG, parsecG, unparsecG, applicativeG, monadG & readG infer the type; regstringG, regbnfG & transducerG take it as a required type argument, (type T) where a constructor shares its name. Grammar values run by the backends' own runners (parseP, printP, parsecP & co.). Instances: RegString & RegBnf (their Read & IsList use them), the TypeScript token & declaration grammars, & the test examples' canonical grammars; alternatives (powGrammar, leftGrammar, semverCtxGrammar) stay values, run by the test harness on each backend. Co-Authored-By: Claude Opus 5.5 --- distributors-grammar/CHANGELOG.md | 10 + distributors-grammar/bench/Main.hs | 28 +- .../src/Control/Lens/Grammar.hs | 253 ++++++++++-------- .../test/Examples/Arithmetic.hs | 5 +- distributors-grammar/test/Examples/Chain.hs | 5 +- .../test/Examples/Expression.hs | 9 +- distributors-grammar/test/Examples/Heredoc.hs | 4 +- distributors-grammar/test/Examples/Json.hs | 5 +- distributors-grammar/test/Examples/Lambda.hs | 5 +- distributors-grammar/test/Examples/LenVec.hs | 4 +- distributors-grammar/test/Examples/SExpr.hs | 5 +- distributors-grammar/test/Examples/SemVer.hs | 8 +- distributors-grammar/test/Main.hs | 54 ++-- .../test/Properties/Varifocal.hs | 12 +- distributors-json/bench/Main.hs | 4 +- .../src/Control/Lens/Grammar/Json.hs | 4 +- .../src/Control/Lens/Grammar/TypeScript.hs | 24 +- distributors-json/test/Properties/Json.hs | 8 +- .../test/Properties/TypeScript.hs | 10 +- 19 files changed, 283 insertions(+), 174 deletions(-) diff --git a/distributors-grammar/CHANGELOG.md b/distributors-grammar/CHANGELOG.md index 77257c43..a674fcc1 100644 --- a/distributors-grammar/CHANGELOG.md +++ b/distributors-grammar/CHANGELOG.md @@ -2,6 +2,16 @@ ## Unreleased +- `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..a5f804b8 100644 --- a/distributors-grammar/bench/Main.hs +++ b/distributors-grammar/bench/Main.hs @@ -36,7 +36,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 +51,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 +73,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 @@ -146,8 +147,8 @@ examples = , Workload "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 +166,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 (show (runGrammor g :: RegString))) + (sepBy commaG several digitG) + , bench "regbnf json" $ whnf (\() -> length (show (regbnfG Json))) () + , bench "regbnf expr" $ whnf (\() -> length (show (regbnfG Expr))) () ] -- | Optics as lenses, at functions. diff --git a/distributors-grammar/src/Control/Lens/Grammar.hs b/distributors-grammar/src/Control/Lens/Grammar.hs index ae91a62b..a448c7d2 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,23 @@ See Chomsky, [On Certain Formal Properties of Grammars] module Control.Lens.Grammar ( -- * Regular grammar - RegGrammar + RegGrammar (..) + , RegGrammatical , Lexical , RegString (..) , regstringG , regexGrammar -- * Context-free grammar - , Grammar + , Grammar (..) + , Grammatical , RegBnf (..) , regbnfG , regbnfGrammar , applicativeG , transducerG -- * Context-sensitive grammar - , CtxGrammar + , CtxGrammar (..) + , CtxGrammatical , printG , parseG , unparseG @@ -90,6 +94,7 @@ import Data.Traversable.Homogeneous as X import Data.Traversable.Homogeneous.Enumerable as X -- $setup +-- >>> :set -XRequiredTypeArguments -XExplicitNamespaces -XTypeApplications -- >>> import Data.String (fromString) -- >>> import GHC.Exts (toList) @@ -138,7 +143,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 @@ -152,8 +157,16 @@ semverGrammar = _SemVer >|< 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, @@ -190,32 +203,36 @@ because @_SemVer@ is an `Control.Lens.Iso.Iso`. You can generate a t'RegString' from a `RegGrammar` with `Control.Lens.Grammar.regstringG`. ->>> putStringLn (regstringG semverGrammar) +>>> putStringLn (regstringG (type SemVer)) \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}|-)+)*)? 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. -} -type RegGrammar token a = forall p. +class Grammar token a => RegGrammar token a where + regGrammar :: RegGrammatical token p => p a a + +{- | The `Lexical` `Alternator`s, which run `RegGrammar`s. -} +type RegGrammatical token p = ( Lexical token p , Alternator p - ) => p a a + ) :: Constraint {- | Context-free `Grammar`s add two capabilities to `RegGrammar`s, coming from the `BackusNaurForm` interface @@ -256,7 +273,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" $ @@ -267,22 +284,24 @@ arithGrammar = ruleRec "arith" sumG numberG >|< terminal "(" >* arith *< terminal ")" numberG = rule "number" $ _Num . iso show read >? someP (asIn @Char DecimalNumber) +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}+ {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,7 +329,7 @@ _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) @@ -320,29 +339,31 @@ exprGrammar = ruleRec "expr" $ \expr -> , [ 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,11 +374,16 @@ 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 +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 + +{- | The `RegGrammatical` `BackusNaurForm`s, which run `Grammar`s. -} +type Grammatical token p = + ( RegGrammatical token p , forall x y. BackusNaurForm (p x y) - ) => p a a + ) :: Constraint {- | For context-sensitivity, the `Monadic` interface is used by importing "Data.Profunctor.Monadic.Do" @@ -378,7 +404,7 @@ _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) @@ -386,6 +412,7 @@ lenvecGrammar = _LenVec >? P.do 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 @@ -407,13 +434,13 @@ We can't generate a t'RegBnf' 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 +450,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 +475,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 +484,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,22 +512,28 @@ 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 +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 + +{- | The `Grammatical` `Filtrator`s & `MonadicTry`s, +which run `CtxGrammar`s. -} +type CtxGrammatical token p = + ( Grammatical token p , Filtrator p , MonadicTry p - ) => p a a + ) :: Constraint {- | `Lexical` combinators include `terminal` symbols, @@ -524,7 +558,7 @@ ab|c t'RegString's can be generated from `RegGrammar`s with `Control.Lens.Grammar.regstringG`. ->>> regstringG (terminal "a" >* terminal "b" >|< terminal "c") +>>> runGrammor (terminal "a" >* terminal "b" >|< terminal "c") :: RegString "ab|c" t'RegString's are actually stored as an algebraic datatype, `RegEx`. @@ -640,8 +674,8 @@ 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 +>>> :type regbnfG +regbnfG :: forall a -> Grammar Char a => RegBnf Like t'RegString's, t'RegBnf's can be constructed using `Lexical`, `Monoid` and `KleeneStarAlgebra` combinators. @@ -678,7 +712,7 @@ 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) +>>> putStringLn (regbnfG (type RegString)) {start} = \q{regex} {alternate} = \q{sequence}(\|\q{sequence})* {atom} = \\q\q{nonterminal}|\q{class}|\(\q{regex}\) @@ -695,7 +729,7 @@ are a context-free language. {regex} = \q{alternate} {sequence} = \q{expression}* -} -regexGrammar :: Grammar Char RegString +regexGrammar :: Grammatical Char p => p RegString RegString regexGrammar = _RegString >~ ruleRec "regex" altG where altG rex = rule "alternate" $ @@ -782,11 +816,11 @@ regexGrammar = _RegString >~ ruleRec "regex" altG optionP (_AndNotAsIn . _Empty) classCatG *< terminal "]" ] -nonterminalG :: Grammar Char String +nonterminalG :: Grammatical Char p => p String String nonterminalG = rule "nonterminal" $ terminal "{" >* manyP charG *< terminal "}" -charG :: Grammar Char Char +charG :: Grammatical Char p => p Char Char charG = rule "char" $ tokenClass (notOneOf charsReserved >&< notAsIn Control) >|< terminal "\\" >* charEscapedG @@ -868,7 +902,7 @@ charG = rule "char" $ `regbnfGrammar` is a context-free `Grammar` for t'RegBnf's. That means that it can generate a self-hosted definition. ->>> putStringLn (regbnfG regbnfGrammar) +>>> putStringLn (regbnfG (type RegBnf)) {start} = \q{regbnf} {alternate} = \q{sequence}(\|\q{sequence})* {atom} = \\q\q{nonterminal}|\q{class}|\(\q{regex}\) @@ -886,7 +920,7 @@ That means that it can generate a self-hosted definition. {regex} = \q{alternate} {sequence} = \q{expression}* -} -regbnfGrammar :: Grammar Char RegBnf +regbnfGrammar :: Grammatical Char p => p RegBnf RegBnf regbnfGrammar = rule "regbnf" $ _RegBnf . _Bnf >~ terminal "{start} = " >* regexGrammar >*< (listed ~< manyP (terminal "\n" >* nonterminalG *< terminal " = " >*< regexGrammar)) @@ -896,20 +930,20 @@ regbnfGrammar = rule "regbnf" $ _RegBnf . _Bnf >~ Since context-free `Grammar`s and `CtxGrammar`s aren't necessarily regular, the type system will prevent `regstringG` from being applied to them. -} -regstringG :: RegGrammar Char a -> RegString -regstringG rex = runGrammor rex +regstringG :: forall a -> RegGrammar Char a => RegString +regstringG a = runGrammor (regGrammar @Char @a) {- | `regbnfG` generates a t'RegBnf' from a context-free `Grammar`. 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 a -> Grammar Char a => RegBnf +regbnfG a = runGrammor (grammar @Char @a) {- | Compile a `Grammar` into a t'Transducer'. ->>> let regexMachine = transducerG @Char regexGrammar +>>> let regexMachine = transducerG @Char (type RegString) A transducer is a form of finite state machine, usable as an intermediary for further generators like @@ -969,8 +1003,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 +1016,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 +1032,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 +1051,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 +1071,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 +1091,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 +1107,19 @@ 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) ) - => 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`. @@ -1118,21 +1155,20 @@ instance Filterable WrapMega where 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 + , MonadTry m , 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'. @@ -1146,45 +1182,50 @@ instance IsList RegString where = fromMaybe falseP . listToMaybe . mapMaybe prsF - . readP_to_S (readG regexGrammar) + . readP_to_S (readG @RegString) where prsF (rex,"") = Just rex prsF _ = Nothing toList = maybe "[]" ($ "") - . printP regexGrammar + . printP (grammar @Char @RegString) instance IsString RegString where fromString = fromList instance Show RegString where showsPrec precision = showsPrec precision . toList instance Read RegString where - readsPrec = readsGrammar regexGrammar + readsPrec = readsGrammar @RegString instance IsList RegBnf where type Item RegBnf = Char fromList = fromMaybe falseP . listToMaybe . mapMaybe prsF - . readP_to_S (readG regbnfGrammar) + . readP_to_S (readG @RegBnf) where prsF (regbnf,"") = Just regbnf prsF _ = Nothing toList = maybe "{start} = []" ($ "") - . printP regbnfGrammar + . printP (grammar @Char @RegBnf) instance IsString RegBnf where fromString = fromList instance Show RegBnf where showsPrec precision = showsPrec precision . toList instance Read RegBnf where - readsPrec = readsGrammar regbnfGrammar + readsPrec = readsGrammar @RegBnf {- | 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 = +readsGrammar :: forall a. Grammar Char a => Int -> ReadS a +readsGrammar precision str = [ (a, rest) | (text, rest) <- readsPrec @String precision str - , a <- take 1 [a | (a, "") <- readP_to_S (readG grammar) text] + , a <- take 1 [a | (a, "") <- readP_to_S (readG @a) text] ] + +instance CtxGrammar Char RegString +instance Grammar Char RegString where grammar = regexGrammar +instance CtxGrammar Char RegBnf +instance Grammar Char RegBnf where grammar = regbnfGrammar diff --git a/distributors-grammar/test/Examples/Arithmetic.hs b/distributors-grammar/test/Examples/Arithmetic.hs index 27046118..ecee1b46 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" $ @@ -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..14872b24 100644 --- a/distributors-grammar/test/Examples/Expression.hs +++ b/distributors-grammar/test/Examples/Expression.hs @@ -32,7 +32,7 @@ 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" $ @@ -68,7 +68,7 @@ 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" $ @@ -88,7 +88,7 @@ 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" $ @@ -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 -> @@ -131,3 +131,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..73625474 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 @@ -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..174cd8a7 100644 --- a/distributors-grammar/test/Examples/LenVec.hs +++ b/distributors-grammar/test/Examples/LenVec.hs @@ -13,7 +13,7 @@ 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) @@ -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/SExpr.hs b/distributors-grammar/test/Examples/SExpr.hs index 6fdc9bde..e0d4a4e3 100644 --- a/distributors-grammar/test/Examples/SExpr.hs +++ b/distributors-grammar/test/Examples/SExpr.hs @@ -17,7 +17,7 @@ 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 @@ -56,3 +56,6 @@ sexprExamples = List [Atom "else-branch"]], "(if test (then-branch) (else-branch))") ] + +instance CtxGrammar Char SExpr +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..f9afde78 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 @@ -48,7 +48,7 @@ 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) @@ -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..cf0935c2 100644 --- a/distributors-grammar/test/Main.hs +++ b/distributors-grammar/test/Main.hs @@ -2,10 +2,12 @@ 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 Text.ParserCombinators.ReadP (readP_to_S) import Test.Hspec import Test.QuickCheck (generate) import qualified Text.Megaparsec as M @@ -40,11 +42,23 @@ main = hspec $ do describe "Parsector try rollback" tryRollbackTests describe "Kleene" kleeneProperties describe "Varifocal" varifocalProperties + describe "class runners, at Arith's Grammar" classRunnerTests + +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 :: RegBnf) + [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 +80,74 @@ 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 + :: forall a. (Show a, Eq a) + => Bool -> [(a, String)] -> (forall p. Grammatical Char p => p a a) -> Spec testCfg isLL1 examples grammar = do describe "examples" $ for_ examples $ \(expectedSyntax, expectedString) -> do testCtxGrammar isLL1 grammar (expectedSyntax, expectedString) it ("should match " <> expectedString <> " correctly") $ do - let actualMatch = expectedString =~ regbnfG grammar + let actualMatch = expectedString =~ (runGrammor grammar :: RegBnf) actualMatch `shouldBe` True 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 grammar) :: Transducer Char + generated <- generate (take 100 <$> languageSample machine) for_ generated $ \word -> do - let fullParses = [() | (_, "") <- parseG grammar word] + let fullParses = [() | (_, "") <- parseP (grammar :: Parsor String [] a a) word] fullParses `shouldBe` [()] -testCsg :: (Show a, Eq a) => Bool -> [(a, String)] -> CtxGrammar Char a -> Spec +testCsg + :: (Show a, Eq a) + => Bool -> [(a, String)] -> (forall p. CtxGrammatical Char p => p a a) -> Spec testCsg isLL1 examples grammar = describe "examples" $ for_ examples $ testCtxGrammar isLL1 grammar -testCtxGrammar :: (Show a, Eq a) => Bool -> CtxGrammar Char a -> (a, String) -> Spec +testCtxGrammar + :: forall a. (Show a, Eq a) + => Bool -> (forall p. CtxGrammatical Char p => p a a) -> (a, String) -> Spec testCtxGrammar isLL1 grammar (expectedSyntax, expectedString) = do it ("should parseG from " <> expectedString <> " correctly") $ do - let actualSyntax = [parsed | (parsed, "") <- parseG grammar expectedString] + let actualSyntax = + [parsed | (parsed, "") <- parseP (grammar :: Parsor String [] a a) expectedString] actualSyntax `shouldBe` [expectedSyntax] it ("should unparseG to " <> expectedString <> " correctly") $ do - let actualString = unparseG grammar expectedSyntax "" + let actualString = + unparseP (grammar :: 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 (grammar :: 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 (grammar :: 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 (grammar :: 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 (grammar :: Joker WrapMega a a)) let actualSyntax = M.parse megaparsec "" expectedString actualSyntax `shouldBe` Right expectedSyntax diff --git a/distributors-grammar/test/Properties/Varifocal.hs b/distributors-grammar/test/Properties/Varifocal.hs index d4f96b64..84446ee7 100644 --- a/distributors-grammar/test/Properties/Varifocal.hs +++ b/distributors-grammar/test/Properties/Varifocal.hs @@ -160,14 +160,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/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..1aeb4b00 100644 --- a/distributors-json/src/Control/Lens/Grammar/Json.hs +++ b/distributors-json/src/Control/Lens/Grammar/Json.hs @@ -2146,9 +2146,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 " diff --git a/distributors-json/src/Control/Lens/Grammar/TypeScript.hs b/distributors-json/src/Control/Lens/Grammar/TypeScript.hs index f81edb19..cac1b512 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 -} @@ -472,7 +472,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 +524,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 +532,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 @@ -546,7 +546,7 @@ stringChar quote = orP 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 +563,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 []) @@ -718,7 +718,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. @@ -1463,3 +1463,9 @@ tokenOf before category after = textOf :: (Lexical TsToken p, Alternator 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..a7deeeaf 100644 --- a/distributors-json/test/Properties/Json.hs +++ b/distributors-json/test/Properties/Json.hs @@ -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 @@ -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) From 784aafa83effa390d998b4da05153f14daec8e01 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Fri, 13 Nov 2026 17:26:44 -0800 Subject: [PATCH 02/51] Ruled, BackusNaurForm & Tried; remove Control.Monad.Fail.Try Implements SCRATCHBackusNaur: Ruled (rule) is split from BackusNaurForm, now its subclass, with ruleRec defaulting to rule label . fix, so its invariant holds for any rule; failBnf becomes failP; Tried generalizes MonadTry's try to any grammar, defaulting to id. Parsector backtracks by Tried, Grammor & Joker delegate, a Bnf tries its start, & a RegEx doesn't record try, for now (try = id). Control.Monad.Fail.Try, MonadTry & MonadicTry are removed: Grammatical requires Tried, & CtxGrammatical, MonadPlus & MonadFail of Filtrators. Control.Lens.Grammar still re-exports Alternative, MonadPlus, MonadFail & Filterable. The Json package's profunctors keep their own ruleRec, by separate Ruled & BackusNaurForm instances; they aren't Grammatical, so they needn't be Tried. Instances ported from wadler-leijen eaa473d. Co-Authored-By: Claude Opus 5.5 --- distributors-grammar/CHANGELOG.md | 14 ++++ .../distributors-grammar.cabal | 1 - .../src/Control/Lens/Grammar.hs | 30 ++++++--- .../src/Control/Lens/Grammar/BackusNaur.hs | 67 ++++++++++++++----- .../src/Control/Monad/Fail/Try.hs | 65 ------------------ .../src/Data/Profunctor/Grammar.hs | 15 +++-- .../src/Data/Profunctor/Grammar/Parsector.hs | 9 ++- distributors-grammar/test/Main.hs | 37 +++++----- .../src/Control/Lens/Grammar/Json.hs | 13 ++-- .../src/Control/Lens/Grammar/TypeScript.hs | 5 +- 10 files changed, 126 insertions(+), 130 deletions(-) delete mode 100644 distributors-grammar/src/Control/Monad/Fail/Try.hs diff --git a/distributors-grammar/CHANGELOG.md b/distributors-grammar/CHANGELOG.md index a674fcc1..3d24dba6 100644 --- a/distributors-grammar/CHANGELOG.md +++ b/distributors-grammar/CHANGELOG.md @@ -2,6 +2,20 @@ ## Unreleased +- `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` diff --git a/distributors-grammar/distributors-grammar.cabal b/distributors-grammar/distributors-grammar.cabal index cae63344..07c25bf7 100644 --- a/distributors-grammar/distributors-grammar.cabal +++ b/distributors-grammar/distributors-grammar.cabal @@ -34,7 +34,6 @@ library Control.Lens.Grammar.RegEx Control.Lens.Grammar.Symbol Control.Lens.Grammar.Token - Control.Monad.Fail.Try Data.Profunctor.Grammar Data.Profunctor.Grammar.Parsector other-modules: diff --git a/distributors-grammar/src/Control/Lens/Grammar.hs b/distributors-grammar/src/Control/Lens/Grammar.hs index a448c7d2..070f78fd 100644 --- a/distributors-grammar/src/Control/Lens/Grammar.hs +++ b/distributors-grammar/src/Control/Lens/Grammar.hs @@ -82,7 +82,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 @@ -379,10 +381,12 @@ class CtxGrammar token a => Grammar token a where default grammar :: (RegGrammar token a, Grammatical token p) => p a a grammar = regGrammar @token -{- | The `RegGrammatical` `BackusNaurForm`s, which run `Grammar`s. -} +{- | The `RegGrammatical` `BackusNaurForm`s, which are `Tried`, +& run `Grammar`s. -} type Grammatical token p = ( RegGrammatical token p , forall x y. BackusNaurForm (p x y) + , forall x y. Tried (p x y) ) :: Constraint {- | For context-sensitivity, @@ -527,12 +531,13 @@ class CtxGrammar token a where default ctxGrammar :: (Grammar token a, CtxGrammatical token p) => p a a ctxGrammar = grammar @token -{- | The `Grammatical` `Filtrator`s & `MonadicTry`s, +{- | The `Grammatical` `Filtrator`s, `MonadPlus`es & `MonadFail`s, which run `CtxGrammar`s. -} type CtxGrammatical token p = ( Grammatical token p , Filtrator p - , MonadicTry p + , forall x. MonadPlus (p x) + , forall x. MonadFail (p x) ) :: Constraint {- | @@ -648,7 +653,7 @@ newtype RegString = RegString {runRegString :: RegEx Char} , Semigroup, Monoid, DisjunctiveMonoid, KleeneStarAlgebra , Tokenized Char, TokenAlgebra Char , TerminalSymbol Char, NonTerminalSymbol - , Matching String + , Matching String, Tried ) {- | t'RegBnf's are an embedded domain specific language @@ -694,7 +699,7 @@ newtype RegBnf = RegBnf {runRegBnf :: Bnf RegString} , Semigroup, Monoid, DisjunctiveMonoid, KleeneStarAlgebra , Tokenized Char, TokenAlgebra Char , TerminalSymbol Char, NonTerminalSymbol - , BackusNaurForm + , Ruled, BackusNaurForm, Tried ) instance Matching String RegBnf where word =~ pattern = word =~ liftBnf1 runRegString (runRegBnf pattern) @@ -1113,6 +1118,7 @@ applicativeG , TokenAlgebra token (f token) , TerminalSymbol token (f ()) , forall x. BackusNaurForm (f x) + , forall x. Tried (f x) ) => f a applicativeG = runJoker (grammar @token @a) @@ -1147,13 +1153,13 @@ 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 = unwrapMega (monadG @Char) @@ -1163,7 +1169,9 @@ megaparsecG = unwrapMega (monadG @Char) monadG :: forall token a m. ( CtxGrammar token a - , MonadTry m + , MonadPlus m, MonadFail m, Filterable m + , forall x. BackusNaurForm (m x) + , forall x. Tried (m x) , TokenAlgebra token (m token) , TerminalSymbol token (m ()) ) diff --git a/distributors-grammar/src/Control/Lens/Grammar/BackusNaur.hs b/distributors-grammar/src/Control/Lens/Grammar/BackusNaur.hs index 8b4146bc..795450b9 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/BackusNaur.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/BackusNaur.hs @@ -14,7 +14,9 @@ See Naur & Backus, et al. module Control.Lens.Grammar.BackusNaur ( -- * BackusNaurForm - BackusNaurForm (..), failBnf + BackusNaurForm (..) + , Ruled (..), failP + , Tried (..) , Bnf (..) , liftBnf0 , liftBnf1 @@ -50,10 +52,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,19 +68,43 @@ 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 + +{- | `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 +-} +class Ruled p where + + {- | Subgrammar abstraction. -} + rule :: String -> p -> p + rule _ = id -- | A nonterminal symbol to indicate a failure. -failBnf :: (BackusNaurForm bnf, DisjunctiveMonoid bnf) => String -> bnf -failBnf msg = rule msg falseP +failP :: (Ruled p, DisjunctiveMonoid p) => String -> p +failP msg = rule msg falseP + +{- | `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 {- | A t'Bnf' consists of a distinguished starting rule and a set of named rules. When a t'Bnf' supports `NonTerminalSymbol`s, @@ -169,16 +195,27 @@ rulesNamed nameX = foldl' (flip inserter) Set.empty where if nameX == nameY then Set.insert y else id -- 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 - rule label (Bnf newRule oldRules) = (nonTerminal label) - {rulesBnf = Set.insert (label, newRule) oldRules} 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` doesn't record `try`, for now. +instance Tried (RegEx token) +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 Tried (ReadP a) instance (Ord rule, TerminalSymbol token rule) => TerminalSymbol token (Bnf rule) where terminal = liftBnf0 . terminal 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..b1133986 100644 --- a/distributors-grammar/src/Data/Profunctor/Grammar.hs +++ b/distributors-grammar/src/Data/Profunctor/Grammar.hs @@ -30,7 +30,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 @@ -43,6 +42,7 @@ 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)} @@ -206,11 +206,11 @@ 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 @@ -347,11 +347,11 @@ instance , 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 -instance (Alternative m, Monad m, Filterable m) - => MonadTry (Printor s m a) -- Grammor instances instance Functor (Grammor k a) where fmap _ = coerce @@ -394,8 +394,11 @@ 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 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/test/Main.hs b/distributors-grammar/test/Main.hs index cf0935c2..452d0429 100644 --- a/distributors-grammar/test/Main.hs +++ b/distributors-grammar/test/Main.hs @@ -4,7 +4,6 @@ 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 Text.ParserCombinators.ReadP (readP_to_S) @@ -95,59 +94,59 @@ tryRollbackTests = do testCfg :: forall a. (Show a, Eq a) => Bool -> [(a, String)] -> (forall p. Grammatical Char p => p a a) -> Spec -testCfg isLL1 examples grammar = do +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 =~ (runGrammor grammar :: RegBnf) + let actualMatch = expectedString =~ (runGrammor gram :: RegBnf) actualMatch `shouldBe` True describe "transducerG" $ do it "should generate the hundred shorted valid words in a language" $ do - let machine = transducer (runGrammor grammar) :: Transducer Char + let machine = transducer (runGrammor gram) :: Transducer Char generated <- generate (take 100 <$> languageSample machine) for_ generated $ \word -> do - let fullParses = [() | (_, "") <- parseP (grammar :: Parsor String [] a a) word] + let fullParses = [() | (_, "") <- parseP (gram :: Parsor String [] a a) word] fullParses `shouldBe` [()] testCsg :: (Show a, Eq a) => Bool -> [(a, String)] -> (forall p. CtxGrammatical Char p => p a a) -> Spec -testCsg isLL1 examples grammar = - describe "examples" $ for_ examples $ testCtxGrammar isLL1 grammar +testCsg isLL1 examples gram = + describe "examples" $ for_ examples $ testCtxGrammar isLL1 gram testCtxGrammar :: forall a. (Show a, Eq a) => Bool -> (forall p. CtxGrammatical Char p => p a a) -> (a, String) -> Spec -testCtxGrammar isLL1 grammar (expectedSyntax, expectedString) = do +testCtxGrammar isLL1 gram (expectedSyntax, expectedString) = do it ("should parseG from " <> expectedString <> " correctly") $ do let actualSyntax = - [parsed | (parsed, "") <- parseP (grammar :: Parsor String [] a a) expectedString] + [parsed | (parsed, "") <- parseP (gram :: Parsor String [] a a) expectedString] actualSyntax `shouldBe` [expectedSyntax] it ("should unparseG to " <> expectedString <> " correctly") $ do let actualString = - unparseP (grammar :: Parsor String Maybe a a) expectedSyntax "" + unparseP (gram :: Parsor String Maybe a a) expectedSyntax "" actualString `shouldBe` Just expectedString it ("should printG to " <> expectedString <> " correctly") $ do let actualString = - ($ "") <$> printP (grammar :: Printor String Maybe a a) expectedSyntax + ($ "") <$> printP (gram :: Printor String Maybe a a) expectedSyntax actualString `shouldBe` Just expectedString when isLL1 $ do it ("should parsecG from " <> expectedString <> " correctly") $ do - let actualSyntax = parsecP (grammar :: Parsector String a a) 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 = unparsecP (grammar :: Parsector String a a) 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 (runJoker (grammar :: Joker WrapMega a a)) + let megaparsec = unwrapMega (runJoker (gram :: Joker WrapMega a a)) let actualSyntax = M.parse megaparsec "" expectedString actualSyntax `shouldBe` Right expectedSyntax @@ -169,10 +168,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-json/src/Control/Lens/Grammar/Json.hs b/distributors-json/src/Control/Lens/Grammar/Json.hs index 1aeb4b00..7c742d69 100644 --- a/distributors-json/src/Control/Lens/Grammar/Json.hs +++ b/distributors-json/src/Control/Lens/Grammar/Json.hs @@ -925,9 +925,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 +1220,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 +1561,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) @@ -2215,8 +2217,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 diff --git a/distributors-json/src/Control/Lens/Grammar/TypeScript.hs b/distributors-json/src/Control/Lens/Grammar/TypeScript.hs index cac1b512..0d158bbc 100644 --- a/distributors-json/src/Control/Lens/Grammar/TypeScript.hs +++ b/distributors-json/src/Control/Lens/Grammar/TypeScript.hs @@ -577,7 +577,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) @@ -697,8 +697,7 @@ _HexCode = prism' -- 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 From afcbced070124e6fb18269f5cc0e3fd107058a5b Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Fri, 13 Nov 2026 17:42:16 -0800 Subject: [PATCH 03/51] Varifocal stepping over any Cons stream MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit stepping, terminateBy, delimitBy, balanceBy & countWith are generic in their stream, (Cons s s a a, AsEmpty s), as their bodies only use _Cons & asEmpty, so they step through a Seq or Text as through a list (tested at Seq). Varifocal requires a Filterable monad, for Bifocal ⊂ Varifocal, which these needn't use; the module disables the redundant-constraint warning that now reports it, as explained there. Co-Authored-By: Claude Opus 5.5 --- distributors-core/CHANGELOG.md | 3 ++ .../src/Control/Lens/Varifocal.hs | 30 ++++++++++++------- .../test/Properties/Varifocal.hs | 10 +++++++ 3 files changed, 33 insertions(+), 10 deletions(-) diff --git a/distributors-core/CHANGELOG.md b/distributors-core/CHANGELOG.md index e0a26bba..d95cd28f 100644 --- a/distributors-core/CHANGELOG.md +++ b/distributors-core/CHANGELOG.md @@ -4,6 +4,9 @@ ### New APIs +- `stepping` & its combinators, `terminateBy`, `delimitBy`, `balanceBy` + & `countWith`, step through any stream, @(Cons s s a a, AsEmpty s)@, + like a `Data.Sequence.Seq` or `Data.Text.Text`, not only lists. - `Enumerable`, in `Data.Traversable.Homogeneous`, of `Homogeneous` countable sums of single copies, sequenced `enumerably` by `CocartesianMonoidal`s, with generic defaults by `Generic1`. diff --git a/distributors-core/src/Control/Lens/Varifocal.hs b/distributors-core/src/Control/Lens/Varifocal.hs index 1741ac5a..b4cc605b 100644 --- a/distributors-core/src/Control/Lens/Varifocal.hs +++ b/distributors-core/src/Control/Lens/Varifocal.hs @@ -1,3 +1,7 @@ +-- `Varifocal` requires a `Filterable` monad, so that every +-- `Control.Lens.Bifocal.Bifocal` is a `Varifocal`, which the stepping +-- combinators, generic in their streams, needn't use. +{-# OPTIONS_GHC -Wno-redundant-constraints #-} {- | Module : Control.Lens.Varifocal Description : varifocals @@ -294,9 +298,12 @@ contextuallyT vari p = joinP (vari (rmap pure p)) deciding by each focus built whether to continue, @`Right` state@, to stop there, @`Left` `True`@, or to reject, @`Left` `False`@, as no `Control.Lens.Bifocal.Bifocal` can. -A list matches when its last focus, & no earlier one, stops it. +A stream, like a list, matches when its last focus, +& no earlier one, stops it. -} -stepping :: st -> (st -> a -> Either Bool st) -> Varifocal' [a] a +stepping + :: (Cons s s a a, AsEmpty s) + => st -> (st -> a -> Either Bool st) -> Varifocal' s a stepping st0 step q = rmap pure (go st0) where go st = _Cons >? P.do @@ -308,11 +315,11 @@ stepping st0 step q = rmap pure (go st0) {- | Zero or more foci, then one which @end@s them, deciding by each focus built, like a sentinel-terminated sequence, a C string's. -A list which doesn't end by its first ending focus doesn't match. +A stream which doesn't end by its first ending focus doesn't match. > prop> terminateBy end = stepping () (\() -> bool (Right ()) (Left True) . end) -} -terminateBy :: (a -> Bool) -> Varifocal' [a] a +terminateBy :: (Cons s s a a, AsEmpty s) => (a -> Bool) -> Varifocal' s a terminateBy end = stepping () (\() -> bool (Right ()) (Left True) . end) {- | Foci opened by the first, & closed by the first after it @@ -320,9 +327,9 @@ which matches it, deciding by the opening focus built, like a [heredoc](https://en.wikipedia.org/wiki/Here_document)'s tag, or a fenced code block's fence, whose language, of matching delimiters, isn't context-free. -A list which doesn't close by its first match doesn't match. +A stream which doesn't close by its first match doesn't match. -} -delimitBy :: (a -> a -> Bool) -> Varifocal' [a] a +delimitBy :: (Cons s s a a, AsEmpty s) => (a -> a -> Bool) -> Varifocal' s a delimitBy same = stepping Nothing $ \st b -> case st of Nothing -> Right (Just b) Just open -> bool (Right st) (Left True) (same open b) @@ -331,9 +338,11 @@ delimitBy same = stepping Nothing $ \st b -> case st of at the same nesting depth, like nested comments, @/* /* */ */@, or a balanceBy block, whose language, of nested pairs, isn't regular. A focus may not both @open@ & @close@. -A list which doesn't open first, or close only last, doesn't match. +A stream which doesn't open first, or close only last, doesn't match. -} -balanceBy :: (a -> Bool) -> (a -> Bool) -> Varifocal' [a] a +balanceBy + :: (Cons s s a a, AsEmpty s) + => (a -> Bool) -> (a -> Bool) -> Varifocal' s a balanceBy open close = stepping (0 :: Int) step where step depth b @@ -345,9 +354,10 @@ balanceBy open close = stepping (0 :: Int) step {- | A focus counting how many foci follow it, then those, like a length-prefixed record of bytes in a binary format. -A list which doesn't have as many as its first focus counts doesn't match. +A stream which doesn't have as many as its first focus counts +doesn't match. -} -countWith :: (a -> Int) -> Varifocal' [a] a +countWith :: (Cons s s a a, AsEmpty s) => (a -> Int) -> Varifocal' s a countWith count = stepping Nothing $ \st b -> case st of Nothing -> if count b <= 0 then Left True else Right (Just (count b)) Just n -> if n <= 1 then Left True else Right (Just (n - 1)) diff --git a/distributors-grammar/test/Properties/Varifocal.hs b/distributors-grammar/test/Properties/Varifocal.hs index 84446ee7..370bcab4 100644 --- a/distributors-grammar/test/Properties/Varifocal.hs +++ b/distributors-grammar/test/Properties/Varifocal.hs @@ -4,6 +4,8 @@ import Control.Lens.Grammar 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 +51,14 @@ varifocalProperties = do prop "doesn't print an early end" $ forAll plain $ \s -> forAll plain $ \t -> printed ended (s ++ "." ++ t ++ ".") === Nothing + describe "stepping, 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 "balanceBy & countWith, by stepping" $ do let nested :: Varifocal' String Char From b03fe7d0017ec013d3698cb995adad5c13b81e69 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Fri, 13 Nov 2026 17:51:43 -0800 Subject: [PATCH 04/51] steppingTree & arityWith: stepping through cofree trees steppingTree generalizes stepping from streams to the cofree comonad of any Traversable g: from a state, each node's focus decides its children's states, a g-shape of them, or rejects. Foci go in preorder; printing checks each node's children have the decided shape (Eq (g ())), so a tree prints only as it parses. stepping is its case at Maybe, of non-empty streams, but stays direct: through Cofree it was 1.6-1.8x slower. arityWith, count-prefixed trees, is the tree version of countWith, tested at Parsor & Printor. Adds free, already a dependency of lens, for Cofree. Co-Authored-By: Claude Opus 5.5 --- distributors-core/CHANGELOG.md | 5 ++ distributors-core/distributors.cabal | 3 ++ distributors-core/package.yaml | 1 + .../src/Control/Lens/Varifocal.hs | 50 ++++++++++++++++++- .../distributors-grammar.cabal | 1 + distributors-grammar/package.yaml | 1 + .../test/Properties/Varifocal.hs | 16 +++++- 7 files changed, 74 insertions(+), 3 deletions(-) diff --git a/distributors-core/CHANGELOG.md b/distributors-core/CHANGELOG.md index d95cd28f..6a1e6f6b 100644 --- a/distributors-core/CHANGELOG.md +++ b/distributors-core/CHANGELOG.md @@ -7,6 +7,11 @@ - `stepping` & its combinators, `terminateBy`, `delimitBy`, `balanceBy` & `countWith`, step through any stream, @(Cons s s a a, AsEmpty s)@, like a `Data.Sequence.Seq` or `Data.Text.Text`, not only lists. +- `steppingTree`, a deterministic top-down tree machine over the cofree + comonad of a `Traversable`, deciding by each node's focus its children's + states, of which `stepping` is the case of `Maybe`, of non-empty streams; + & `arityWith`, count-prefixed trees, each node's focus counting its + children, as `countWith` counts a stream's. - `Enumerable`, in `Data.Traversable.Homogeneous`, of `Homogeneous` countable sums of single copies, sequenced `enumerably` by `CocartesianMonoidal`s, with generic defaults by `Generic1`. diff --git a/distributors-core/distributors.cabal b/distributors-core/distributors.cabal index 2f2b41c5..867661ef 100644 --- a/distributors-core/distributors.cabal +++ b/distributors-core/distributors.cabal @@ -100,6 +100,7 @@ library , containers >=0.6 && <1 , contravariant >=1.5 && <2 , distributive >=0.6 && <1 + , free >=5.1 && <6 , lens >=5.0 && <6 , profunctors >=5.6 && <6 , tagged >=0.8 && <1 @@ -167,6 +168,7 @@ test-suite doctests , distributive >=0.6 && <1 , distributors , doctest-parallel >=0.3 && <1 + , free >=5.1 && <6 , lens >=5.0 && <6 , profunctors >=5.6 && <6 , tagged >=0.8 && <1 @@ -238,6 +240,7 @@ test-suite test , contravariant >=1.5 && <2 , distributive >=0.6 && <1 , distributors + , free >=5.1 && <6 , hspec >=2.7 && <3 , lens >=5.0 && <6 , profunctors >=5.6 && <6 diff --git a/distributors-core/package.yaml b/distributors-core/package.yaml index 4e1f822f..713bcf89 100644 --- a/distributors-core/package.yaml +++ b/distributors-core/package.yaml @@ -25,6 +25,7 @@ dependencies: - containers >= 0.6 && < 1 - contravariant >= 1.5 && < 2 - distributive >= 0.6 && < 1 +- free >= 5.1 && < 6 - lens >= 5.0 && < 6 - transformers >= 0.5 && < 1 - profunctors >= 5.6 && < 6 diff --git a/distributors-core/src/Control/Lens/Varifocal.hs b/distributors-core/src/Control/Lens/Varifocal.hs index b4cc605b..86ff870f 100644 --- a/distributors-core/src/Control/Lens/Varifocal.hs +++ b/distributors-core/src/Control/Lens/Varifocal.hs @@ -31,17 +31,23 @@ module Control.Lens.Varifocal , contextuallyT -- * Combinators , stepping + , steppingTree , terminateBy , delimitBy , balanceBy , countWith + , arityWith ) where import Control.Applicative (Alternative (..)) -import Control.Lens -import Control.Lens.PartialIso ((>?)) +import Control.Comonad.Cofree (Cofree (..)) +import Control.Lens hiding ((:<)) +import Control.Lens.PartialIso ((>?), (>~)) import Control.Monad (MonadPlus (..), ap) import Data.Bool (bool) +import Data.Foldable (toList) +import Data.Functor (void) +import Data.Traversable (mapAccumL) import Data.Monoid.Disjunctive (DisjunctiveMonoid (..)) import Data.Profunctor (Cochoice (..)) import Data.Profunctor.Distributor @@ -313,6 +319,37 @@ stepping st0 step q = rmap pure (go st0) Left True -> asEmpty Left False -> empty +{- | Foci stepped through by a deterministic top-down tree machine, +from a state, deciding by each node's focus built which children +it has, a state for each position of a `Traversable` @g@, +or rejecting it, by `Nothing`, as no `Control.Lens.Bifocal.Bifocal` can. +Foci are visited in preorder, a node's before its children's. +A tree matches when each node's children have the shape +its focus decides, so that it parses as it prints. + +`stepping` is `steppingTree` at `Maybe`, of non-empty streams, +as the cofree comonad of `Maybe`, by which +@`Left` `False`@, @`Left` `True`@ & @`Right` state@ +decide `Nothing`, @`Just` `Nothing`@ & @`Just` (`Just` state)@; +`stepping` steps through a stream directly, rather than through +a `Cofree`, & needn't check a shape, as a stream's is its focus's. +-} +steppingTree + :: (Traversable g, Eq (g ())) + => st -> (st -> a -> Maybe (g st)) -> Varifocal' (Cofree g a) a +steppingTree st0 step q = rmap pure (go st0) + where + go st = cofreed >~ P.do + b <- joinP q + maybe empty offspring (step st b) + offspring states = shaped states >? sequenceA + (snd (mapAccumL (\i st -> (i + 1, child i st)) (0 :: Int) states)) + -- after shaping, the child at a position of the children + child i st = lmap (\kids -> toList kids !! i) (go st) + shaped states = prism' id $ \kids -> + if void kids == void states then Just kids else Nothing + cofreed = iso (\(b :< kids) -> (b, kids)) (uncurry (:<)) + {- | Zero or more foci, then one which @end@s them, deciding by each focus built, like a sentinel-terminated sequence, a C string's. A stream which doesn't end by its first ending focus doesn't match. @@ -361,3 +398,12 @@ countWith :: (Cons s s a a, AsEmpty s) => (a -> Int) -> Varifocal' s a countWith count = stepping Nothing $ \st b -> case st of Nothing -> if count b <= 0 then Left True else Right (Just (count b)) Just n -> if n <= 1 then Left True else Right (Just (n - 1)) + +{- | A tree whose nodes' foci each count their children, +like a count-prefixed tree of records in a binary format, +by `steppingTree`, as `countWith` counts a stream's. +A node counting fewer than none doesn't match. +-} +arityWith :: (a -> Int) -> Varifocal' (Cofree [] a) a +arityWith arity = steppingTree () $ \() b -> + if arity b < 0 then Nothing else Just (replicate (arity b) ()) diff --git a/distributors-grammar/distributors-grammar.cabal b/distributors-grammar/distributors-grammar.cabal index 07c25bf7..72dd2997 100644 --- a/distributors-grammar/distributors-grammar.cabal +++ b/distributors-grammar/distributors-grammar.cabal @@ -229,6 +229,7 @@ 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 diff --git a/distributors-grammar/package.yaml b/distributors-grammar/package.yaml index c29da918..ad1143a4 100644 --- a/distributors-grammar/package.yaml +++ b/distributors-grammar/package.yaml @@ -99,6 +99,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/test/Properties/Varifocal.hs b/distributors-grammar/test/Properties/Varifocal.hs index 370bcab4..416f0e3b 100644 --- a/distributors-grammar/test/Properties/Varifocal.hs +++ b/distributors-grammar/test/Properties/Varifocal.hs @@ -1,6 +1,7 @@ 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) @@ -59,6 +60,19 @@ varifocalProperties = do `shouldBe` Just (Seq.fromList "ab.", "c") (($ "") <$> printP (contextuallyT seqTerminated (anyToken :: Printor String Maybe Char Char)) (Seq.fromList "ab.")) `shouldBe` Just "ab." + describe "steppingTree, 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 stepping" $ do let nested :: Varifocal' String Char From 1de747da3ca36e6a934f6de5e5e27b5d71fbb730 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Fri, 13 Nov 2026 18:04:12 -0800 Subject: [PATCH 05/51] Varifocus: many & some by manyP & someP Varifocus's Alternative defaulted many & some, building recursive AltsP & BindP trees, which broke the Alternator law many = lmap repeat . manyP & lost the target's own manyP & someP when run. They're now ManyP & SomeP, as in the other Alternators. Co-Authored-By: Claude Opus 5.5 --- distributors-core/src/Control/Lens/Varifocal.hs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/distributors-core/src/Control/Lens/Varifocal.hs b/distributors-core/src/Control/Lens/Varifocal.hs index 86ff870f..a7c144c9 100644 --- a/distributors-core/src/Control/Lens/Varifocal.hs +++ b/distributors-core/src/Control/Lens/Varifocal.hs @@ -137,6 +137,8 @@ instance Monad m => Monad (Varifocus a b m s) where instance Monad m => Alternative (Varifocus a b m s) where empty = AltsP [] x <|> y = AltsP [x, y] + many = lmap repeat . manyP + some = lmap repeat . someP instance Monad m => DisjunctiveMonoid (Varifocus a b m s t) instance Monad m => Choice (Varifocus a b m) where left' = AlternateP . Left From 34b3f34505b5994927b9875a6d58c2f6080010de Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Fri, 13 Nov 2026 18:48:35 -0800 Subject: [PATCH 06/51] Remove RegString & RegBnf: RegEx & Bnf, without orphans RegEx Char & Bnf (RegEx Char) replace the newtypes: IsString & IsList by the string syntax of regexGrammar & regbnfGrammar, Grammar Char instances, & stock Show & Read (render by toList or putStringLn). regstringG becomes regexG; regexG & regbnfG generate over any token. To keep every instance with its type, the modules are restructured: - BackusNaur: Ruled, BackusNaurForm, Tried, failP, & the Lexical & *Grammatical constraints (no longer importing RegEx); - RegEx: RegEx & Bnf, liftBnf*, diffB, the string grammars & their IsString & IsList instances; - Data.Profunctor.Grammar.Printor: Printor, re-exported by Data.Profunctor.Grammar, so RegEx can print without a cycle. Control.Lens.Grammar re-exports all of it. The HLint baseline follows Printor's moved code. Co-Authored-By: Claude Opus 5.5 --- .hlint.yaml | 2 + distributors-grammar/CHANGELOG.md | 13 + distributors-grammar/bench/Main.hs | 7 +- .../distributors-grammar.cabal | 1 + .../src/Control/Lens/Grammar.hs | 517 +--------------- .../src/Control/Lens/Grammar/BackusNaur.hs | 174 ++---- .../src/Control/Lens/Grammar/Machine.hs | 1 - .../src/Control/Lens/Grammar/RegEx.hs | 553 +++++++++++++++++- .../src/Data/Profunctor/Grammar.hs | 150 +---- .../src/Data/Profunctor/Grammar/Printor.hs | 180 ++++++ .../test/Examples/RegString.hs | 2 +- distributors-grammar/test/Main.hs | 4 +- .../test/Properties/Kleene.hs | 20 +- 13 files changed, 834 insertions(+), 790 deletions(-) create mode 100644 distributors-grammar/src/Data/Profunctor/Grammar/Printor.hs 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/distributors-grammar/CHANGELOG.md b/distributors-grammar/CHANGELOG.md index 3d24dba6..15504ffd 100644 --- a/distributors-grammar/CHANGELOG.md +++ b/distributors-grammar/CHANGELOG.md @@ -2,6 +2,19 @@ ## Unreleased +- `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 `Lexical`, `RegGrammatical`, + `Grammatical` & `CtxGrammatical` constraints; `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, diff --git a/distributors-grammar/bench/Main.hs b/distributors-grammar/bench/Main.hs index a5f804b8..d3287fb7 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 @@ -166,10 +167,10 @@ examples = -- | Building static grammars, as regular expressions & Backus-Naur forms. statics :: Benchmark statics = bgroup "static" - [ bench "regstring sepBy" $ whnf (\g -> length (show (runGrammor g :: RegString))) + [ bench "regstring sepBy" $ whnf (\g -> length (Exts.toList (runGrammor g :: RegEx Char))) (sepBy commaG several digitG) - , bench "regbnf json" $ whnf (\() -> length (show (regbnfG Json))) () - , bench "regbnf expr" $ whnf (\() -> length (show (regbnfG Expr))) () + , 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 72dd2997..ead06d00 100644 --- a/distributors-grammar/distributors-grammar.cabal +++ b/distributors-grammar/distributors-grammar.cabal @@ -36,6 +36,7 @@ library Control.Lens.Grammar.Token Data.Profunctor.Grammar Data.Profunctor.Grammar.Parsector + Data.Profunctor.Grammar.Printor other-modules: Paths_distributors_grammar autogen-modules: diff --git a/distributors-grammar/src/Control/Lens/Grammar.hs b/distributors-grammar/src/Control/Lens/Grammar.hs index 070f78fd..d1d90507 100644 --- a/distributors-grammar/src/Control/Lens/Grammar.hs +++ b/distributors-grammar/src/Control/Lens/Grammar.hs @@ -17,15 +17,11 @@ module Control.Lens.Grammar RegGrammar (..) , RegGrammatical , Lexical - , RegString (..) - , regstringG - , regexGrammar + , regexG -- * Context-free grammar , Grammar (..) , Grammatical - , RegBnf (..) , regbnfG - , regbnfGrammar , applicativeG , transducerG -- * Context-sensitive grammar @@ -53,8 +49,6 @@ 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 @@ -63,16 +57,16 @@ 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 + (Lexical, RegGrammatical, Grammatical, CtxGrammatical) import Control.Lens.Grammar.Machine as X import Control.Lens.Grammar.RegEx as X import Control.Lens.Grammar.Symbol as X @@ -202,10 +196,10 @@ 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 (type SemVer)) +>>> putStringLn (regexG (type SemVer)) \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}|-)+)*)? You can also generate parsers and printers. @@ -230,11 +224,6 @@ New `RegGrammar` generators can be defined with new instances of `Lexical` `Alte class Grammar token a => RegGrammar token a where regGrammar :: RegGrammatical token p => p a a -{- | The `Lexical` `Alternator`s, which run `RegGrammar`s. -} -type RegGrammatical token p = - ( Lexical token p - , Alternator p - ) :: Constraint {- | Context-free `Grammar`s add two capabilities to `RegGrammar`s, coming from the `BackusNaurForm` interface @@ -242,8 +231,8 @@ coming from the `BackusNaurForm` interface * `rule` abstraction, * and general recursion. -`Control.Lens.Grammar.regexGrammar` and -`Control.Lens.Grammar.regbnfGrammar` are examples of context-free +`Control.Lens.Grammar.RegEx.regexGrammar` and +`Control.Lens.Grammar.RegEx.regbnfGrammar` 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. @@ -381,13 +370,6 @@ class CtxGrammar token a => Grammar token a where default grammar :: (RegGrammar token a, Grammatical token p) => p a a grammar = regGrammar @token -{- | The `RegGrammatical` `BackusNaurForm`s, which are `Tried`, -& run `Grammar`s. -} -type Grammatical token p = - ( RegGrammatical token p - , forall x y. BackusNaurForm (p x y) - , forall x y. Tried (p x y) - ) :: Constraint {- | For context-sensitivity, the `Monadic` interface is used by importing "Data.Profunctor.Monadic.Do" @@ -434,7 +416,7 @@ 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. @@ -531,424 +513,32 @@ class CtxGrammar token a where default ctxGrammar :: (Grammar token a, CtxGrammatical token p) => p a a ctxGrammar = grammar @token -{- | 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 -{- | -`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`. - ->>> runGrammor (terminal "a" >* terminal "b" >|< terminal "c") :: RegString -"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, Tried - ) - -{- | 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 -regbnfG :: forall a -> Grammar Char a => 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 - , Ruled, BackusNaurForm, Tried - ) -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 (type RegString)) -{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 :: Grammatical Char p => p RegString 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 :: Grammatical Char p => p String String -nonterminalG = rule "nonterminal" $ - terminal "{" >* manyP charG *< terminal "}" - -charG :: Grammatical Char p => p 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 (type RegBnf)) -{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 :: Grammatical Char p => p RegBnf 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 :: forall a -> RegGrammar Char a => RegString -regstringG a = runGrammor (regGrammar @Char @a) +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 :: forall a -> Grammar Char a => RegBnf -regbnfG a = runGrammor (grammar @Char @a) +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 (type RegString) +>>> let regexMachine = transducerG @Char (RegEx Char) A transducer is a form of finite state machine, usable as an intermediary for further generators like @@ -1179,61 +769,12 @@ monadG 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 @RegString) - where - prsF (rex,"") = Just rex - prsF _ = Nothing - toList - = maybe "[]" ($ "") - . printP (grammar @Char @RegString) -instance IsString RegString where - fromString = fromList -instance Show RegString where - showsPrec precision = showsPrec precision . toList -instance Read RegString where - readsPrec = readsGrammar @RegString -instance IsList RegBnf where - type Item RegBnf = Char - fromList - = fromMaybe falseP - . listToMaybe - . mapMaybe prsF - . readP_to_S (readG @RegBnf) - where - prsF (regbnf,"") = Just regbnf - prsF _ = Nothing - toList - = maybe "{start} = []" ($ "") - . printP (grammar @Char @RegBnf) -instance IsString RegBnf where - fromString = fromList -instance Show RegBnf where - showsPrec precision = showsPrec precision . toList -instance Read RegBnf where - readsPrec = readsGrammar @RegBnf - -{- | Read a string literal, as `String`'s `readsPrec` does, -& its text by a `Grammar`, so that @read . show = id@. --} -readsGrammar :: forall a. Grammar Char a => Int -> ReadS a -readsGrammar precision str = - [ (a, rest) - | (text, rest) <- readsPrec @String precision str - , a <- take 1 [a | (a, "") <- readP_to_S (readG @a) text] - ] - -instance CtxGrammar Char RegString -instance Grammar Char RegString where grammar = regexGrammar -instance CtxGrammar Char RegBnf -instance Grammar Char RegBnf where grammar = regbnfGrammar +instance CtxGrammar Char (RegEx Char) +instance Grammar Char (RegEx Char) where grammar = regexGrammar +instance CtxGrammar Char (Bnf (RegEx Char)) +instance Grammar Char (Bnf (RegEx Char)) where grammar = regbnfGrammar diff --git a/distributors-grammar/src/Control/Lens/Grammar/BackusNaur.hs b/distributors-grammar/src/Control/Lens/Grammar/BackusNaur.hs index 795450b9..41a0ed23 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/BackusNaur.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/BackusNaur.hs @@ -17,24 +17,23 @@ module Control.Lens.Grammar.BackusNaur BackusNaurForm (..) , Ruled (..), failP , Tried (..) - , Bnf (..) - , liftBnf0 - , liftBnf1 - , liftBnf2 - , diffB + -- * Grammatical + , Lexical + , 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.Monoid.Disjunctive -import qualified Data.Set as Set -import Data.Set (Set) import Text.ParserCombinators.ReadP (ReadP) {- | `BackusNaurForm` grammar combinators formalize traced @@ -106,106 +105,39 @@ class Tried p where try :: p -> p try = id -{- | 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). +`Lexical` combinators include `terminal` symbols, +`Tokenized` combinators and `tokenClass`es. -} -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 - 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 +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 + +{- | The `Lexical` `Alternator`s, which run `RegGrammar`s. -} +type RegGrammatical token p = + ( Lexical token p + , Alternator p + ) :: Constraint + +{- | The `RegGrammatical` `BackusNaurForm`s, which are `Tried`, +& run `Grammar`s. -} +type Grammatical token p = + ( RegGrammatical token p + , forall x y. BackusNaurForm (p x y) + , forall x y. Tried (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) => 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` doesn't record `try`, for now. -instance Tried (RegEx token) instance (forall x. Ruled (f x)) => Ruled (Joker f a b) where rule name = Joker . rule name . runJoker instance (forall x. BackusNaurForm (f x)) @@ -216,33 +148,3 @@ instance (forall x. Tried (f x)) => Tried (Joker f a b) where instance Ruled (ReadP a) instance BackusNaurForm (ReadP a) instance Tried (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 (<>) diff --git a/distributors-grammar/src/Control/Lens/Grammar/Machine.hs b/distributors-grammar/src/Control/Lens/Grammar/Machine.hs index d2f702bb..289b5477 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 diff --git a/distributors-grammar/src/Control/Lens/Grammar/RegEx.hs b/distributors-grammar/src/Control/Lens/Grammar/RegEx.hs index 1246cd55..d4ad57d0 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 + , regexGrammar + , regbnfGrammar ) 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.Symbol import Control.Lens.Grammar.Token +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. @@ -252,3 +281,525 @@ 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 + 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 + +-- 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` doesn't record `try`, for now. +instance Tried (RegEx token) +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 + +{- | `regexGrammar` is a context-free @Control.Lens.Grammar.Grammar@ +for `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 `Lexical` 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) +"[abc]" +>>> toList (notOneOf "abc" :: RegEx Char) +"[^abc]" + +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) +"[^abcxyz]" +>>> toList (tokenClass (oneOf "abcxyz" >&< notOneOf "xyz") :: RegEx Char) +"[abc]" +>>> 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) +"[^xyz]" + +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}|\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 :: 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 "+" + , 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 :: Grammatical Char p => p String String +nonterminalG = rule "nonterminal" $ + terminal "{" >* manyP charG *< terminal "}" + +charG :: Grammatical Char p => p 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 @Control.Lens.Grammar.Grammar@ +for 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 +`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) :: 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}|\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 :: 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 `regexGrammar`. +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 `regbnfGrammar`. +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/Data/Profunctor/Grammar.hs b/distributors-grammar/src/Data/Profunctor/Grammar.hs index b1133986..dd5ad179 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 @@ -39,19 +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 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 +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)} @@ -217,142 +207,6 @@ instance AsEmpty s => Matching s (Parsor s [] a b) where , 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 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 - -- Grammor instances instance Functor (Grammor k a) where fmap _ = coerce instance Contravariant (Grammor k a) where contramap _ = coerce 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/RegString.hs b/distributors-grammar/test/Examples/RegString.hs index 1069a603..c4d2e06b 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") diff --git a/distributors-grammar/test/Main.hs b/distributors-grammar/test/Main.hs index 452d0429..330b7a0c 100644 --- a/distributors-grammar/test/Main.hs +++ b/distributors-grammar/test/Main.hs @@ -51,7 +51,7 @@ classRunnerTests = for_ arithExamples $ \(syntax, string) -> unparseG syntax "" `shouldBe` Just string parsecResult (parsecG string) `shouldBe` Just syntax parsecStream (unparsecG syntax "") `shouldBe` string - regbnfG Arith `shouldBe` (runGrammor arithGrammar :: RegBnf) + regbnfG Arith `shouldBe` (runGrammor arithGrammar :: Bnf (RegEx Char)) [x | (x, "") <- readP_to_S (readG @Arith) string] `shouldBe` [syntax] parseForestTests :: Spec @@ -98,7 +98,7 @@ testCfg isLL1 examples gram = do describe "examples" $ for_ examples $ \(expectedSyntax, expectedString) -> do testCtxGrammar isLL1 gram (expectedSyntax, expectedString) it ("should match " <> expectedString <> " correctly") $ do - let actualMatch = expectedString =~ (runGrammor gram :: RegBnf) + let actualMatch = expectedString =~ (runGrammor gram :: Bnf (RegEx Char)) actualMatch `shouldBe` True describe "transducerG" $ do it "should generate the hundred shorted valid words in a language" $ do 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 From 68f0bf07f9028acffffe6a3a85e66bab00df5580 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Fri, 13 Nov 2026 18:59:44 -0800 Subject: [PATCH 07/51] Control.Lens.Grammar.Analysis: FIRST, FOLLOW & LL(1), by folds Static analyses of RegEx-tended Bnfs, over any token, in parts: - foldRegEx: the homomorphism out of RegEx, the free KleeneStarAlgebra of token classes & nonterminals, into any other; - bnfRules & fixRules: rules by name, & least fixpoints over them; - Leading: nullability & leading atoms, a KleeneStarAlgebra: at token classes, firsts; at rule names, left corners, for leftRecursive; - Guard: a BooleanAlgebra of one-token lookahead & end of input, for follows, inherited from callers to a fixpoint; - ll1Conflicts, rebuilt of them from textual's, overlaps by one >&<. Every example's LL(1) flag is checked statically; the lambda example's abstraction rule shared the grammar's name, & is renamed. Sets are a DisjunctiveMonoid by union, for left corners. Co-Authored-By: Claude Opus 5.5 --- distributors-core/CHANGELOG.md | 1 + .../src/Data/Monoid/Disjunctive.hs | 6 + distributors-grammar/CHANGELOG.md | 9 + .../distributors-grammar.cabal | 1 + .../src/Control/Lens/Grammar.hs | 1 + .../src/Control/Lens/Grammar/Analysis.hs | 328 ++++++++++++++++++ distributors-grammar/test/Examples/Lambda.hs | 2 +- distributors-grammar/test/Main.hs | 3 + 8 files changed, 350 insertions(+), 1 deletion(-) create mode 100644 distributors-grammar/src/Control/Lens/Grammar/Analysis.hs diff --git a/distributors-core/CHANGELOG.md b/distributors-core/CHANGELOG.md index 6a1e6f6b..a43f6084 100644 --- a/distributors-core/CHANGELOG.md +++ b/distributors-core/CHANGELOG.md @@ -4,6 +4,7 @@ ### New APIs +- `Set`s are a `DisjunctiveMonoid` by union. - `stepping` & its combinators, `terminateBy`, `delimitBy`, `balanceBy` & `countWith`, step through any stream, @(Cons s s a a, AsEmpty s)@, like a `Data.Sequence.Seq` or `Data.Text.Text`, not only lists. diff --git a/distributors-core/src/Data/Monoid/Disjunctive.hs b/distributors-core/src/Data/Monoid/Disjunctive.hs index 8f0406da..5d9716f1 100644 --- a/distributors-core/src/Data/Monoid/Disjunctive.hs +++ b/distributors-core/src/Data/Monoid/Disjunctive.hs @@ -41,6 +41,8 @@ import Data.Profunctor.Cayley import Data.Profunctor.Monad import Data.Profunctor.Yoneda import Data.Proxy +import Data.Set (Set) +import qualified Data.Set as Set import GHC.Conc (STM) import GHC.Generics import Text.ParserCombinators.ReadP (ReadP) @@ -235,6 +237,10 @@ deriving via Generically (Const a b) deriving via Generically (Proxy a) instance DisjunctiveMonoid (Proxy a) deriving via Generically (Proxy a) instance BooleanAlgebra (Proxy a) deriving via Generically (Proxy a) instance KleeneStarAlgebra (Proxy a) +-- | Sets, by union, disjoin their members. +instance Ord a => DisjunctiveMonoid (Set a) where + falseP = Set.empty + (>|<) = Set.union instance DisjunctiveMonoid (Maybe a) instance DisjunctiveMonoid (IO a) instance DisjunctiveMonoid (STM a) diff --git a/distributors-grammar/CHANGELOG.md b/distributors-grammar/CHANGELOG.md index 15504ffd..ce51a340 100644 --- a/distributors-grammar/CHANGELOG.md +++ b/distributors-grammar/CHANGELOG.md @@ -2,6 +2,15 @@ ## Unreleased +- `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` diff --git a/distributors-grammar/distributors-grammar.cabal b/distributors-grammar/distributors-grammar.cabal index ead06d00..1d8281e9 100644 --- a/distributors-grammar/distributors-grammar.cabal +++ b/distributors-grammar/distributors-grammar.cabal @@ -29,6 +29,7 @@ source-repository head library exposed-modules: Control.Lens.Grammar + Control.Lens.Grammar.Analysis Control.Lens.Grammar.BackusNaur Control.Lens.Grammar.Machine Control.Lens.Grammar.RegEx diff --git a/distributors-grammar/src/Control/Lens/Grammar.hs b/distributors-grammar/src/Control/Lens/Grammar.hs index d1d90507..f72804c4 100644 --- a/distributors-grammar/src/Control/Lens/Grammar.hs +++ b/distributors-grammar/src/Control/Lens/Grammar.hs @@ -67,6 +67,7 @@ import Control.Lens.Cons as X import Control.Lens.Empty as X import Control.Lens.Grammar.BackusNaur as X hiding (Lexical, RegGrammatical, Grammatical, CtxGrammatical) +import Control.Lens.Grammar.Analysis as X import Control.Lens.Grammar.Machine as X import Control.Lens.Grammar.RegEx as X import Control.Lens.Grammar.Symbol as X 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..61fc2ea6 --- /dev/null +++ b/distributors-grammar/src/Control/Lens/Grammar/Analysis.hs @@ -0,0 +1,328 @@ +{- | +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) + 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 + 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 `RegEx` doesn't record @try@, so conflicts resolved by it are reported. + +>>> 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 + 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 + | toks <- overlapping (atoms x >&< guardNext after) ] + -- an alternative, & one after it + alternation a b = + [ conflict LL1FirstFirst toks + | 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) + , toks <- overlapping (atoms a >&< guardNext after) ] + pairs = \case + [] -> [] + a : bs -> (a, bs) : pairs bs + +{- | 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) diff --git a/distributors-grammar/test/Examples/Lambda.hs b/distributors-grammar/test/Examples/Lambda.hs index 73625474..753f09b5 100644 --- a/distributors-grammar/test/Examples/Lambda.hs +++ b/distributors-grammar/test/Examples/Lambda.hs @@ -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 diff --git a/distributors-grammar/test/Main.hs b/distributors-grammar/test/Main.hs index 330b7a0c..e0307e80 100644 --- a/distributors-grammar/test/Main.hs +++ b/distributors-grammar/test/Main.hs @@ -100,6 +100,9 @@ testCfg isLL1 examples gram = do it ("should match " <> expectedString <> " correctly") $ do 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 let machine = transducer (runGrammor gram) :: Transducer Char From d94485bd955769ac0ab100264c7343bd38429275 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Fri, 13 Nov 2026 19:10:49 -0800 Subject: [PATCH 08/51] Fold Lexical into RegGrammatical Lexical was only ever used beside Alternator, which together are RegGrammatical, so its constraints are RegGrammatical's own, & the TypeScript helpers are RegGrammatical TsToken. Co-Authored-By: Claude Opus 5.5 --- distributors-grammar/CHANGELOG.md | 5 +++-- distributors-grammar/src/Control/Lens/Grammar.hs | 8 ++++---- .../src/Control/Lens/Grammar/BackusNaur.hs | 14 +++----------- .../src/Control/Lens/Grammar/RegEx.hs | 4 ++-- .../src/Control/Lens/Grammar/TypeScript.hs | 12 ++++++------ 5 files changed, 18 insertions(+), 25 deletions(-) diff --git a/distributors-grammar/CHANGELOG.md b/distributors-grammar/CHANGELOG.md index ce51a340..27bab963 100644 --- a/distributors-grammar/CHANGELOG.md +++ b/distributors-grammar/CHANGELOG.md @@ -18,8 +18,9 @@ `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 `Lexical`, `RegGrammatical`, - `Grammatical` & `CtxGrammatical` constraints; `Control.Lens.Grammar.RegEx` + `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 diff --git a/distributors-grammar/src/Control/Lens/Grammar.hs b/distributors-grammar/src/Control/Lens/Grammar.hs index f72804c4..01caec72 100644 --- a/distributors-grammar/src/Control/Lens/Grammar.hs +++ b/distributors-grammar/src/Control/Lens/Grammar.hs @@ -16,7 +16,6 @@ module Control.Lens.Grammar ( -- * Regular grammar RegGrammar (..) , RegGrammatical - , Lexical , regexG -- * Context-free grammar , Grammar (..) @@ -66,7 +65,7 @@ import Witherable import Control.Lens.Cons as X import Control.Lens.Empty as X import Control.Lens.Grammar.BackusNaur as X hiding - (Lexical, RegGrammatical, Grammatical, CtxGrammatical) + (RegGrammatical, Grammatical, CtxGrammatical) import Control.Lens.Grammar.Analysis as X import Control.Lens.Grammar.Machine as X import Control.Lens.Grammar.RegEx as X @@ -97,7 +96,8 @@ import Data.Traversable.Homogeneous.Enumerable as X {- | 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. @@ -220,7 +220,7 @@ Printing, on the gripping hand, `cons`es tokens right-to-left, to the beginning 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. -} class Grammar token a => RegGrammar token a where regGrammar :: RegGrammatical token p => p a a diff --git a/distributors-grammar/src/Control/Lens/Grammar/BackusNaur.hs b/distributors-grammar/src/Control/Lens/Grammar/BackusNaur.hs index 41a0ed23..de5ba041 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/BackusNaur.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/BackusNaur.hs @@ -18,7 +18,6 @@ module Control.Lens.Grammar.BackusNaur , Ruled (..), failP , Tried (..) -- * Grammatical - , Lexical , RegGrammatical , Grammatical , CtxGrammatical @@ -105,18 +104,11 @@ class Tried p where try :: p -> p try = id -{- | -`Lexical` combinators include `terminal` symbols, -`Tokenized` combinators and `tokenClass`es. --} -type Lexical token p = +{- | The `Alternator`s of `terminal` symbols, `Tokenized` combinators +& `tokenClass`es, which 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) - ) :: Constraint - -{- | The `Lexical` `Alternator`s, which run `RegGrammar`s. -} -type RegGrammatical token p = - ( Lexical token p , Alternator p ) :: Constraint diff --git a/distributors-grammar/src/Control/Lens/Grammar/RegEx.hs b/distributors-grammar/src/Control/Lens/Grammar/RegEx.hs index d4ad57d0..4cf12114 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/RegEx.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/RegEx.hs @@ -459,7 +459,7 @@ True >>> "xyz" =~ rex False -Like @Control.Lens.Grammar.RegGrammar@s, they can use all the `Lexical` combinators. +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. @@ -740,7 +740,7 @@ 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 -`Lexical`, `Monoid` and `KleeneStarAlgebra` combinators. +`terminal`, `Tokenized`, `Monoid` and `KleeneStarAlgebra` combinators. But they also support `BackusNaurForm` `rule`s and `ruleRec`s. >>> putStringLn (rule "baz" (bnf >|< terminal "baz")) diff --git a/distributors-json/src/Control/Lens/Grammar/TypeScript.hs b/distributors-json/src/Control/Lens/Grammar/TypeScript.hs index 0d158bbc..30088469 100644 --- a/distributors-json/src/Control/Lens/Grammar/TypeScript.hs +++ b/distributors-json/src/Control/Lens/Grammar/TypeScript.hs @@ -1436,31 +1436,31 @@ _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 From 2099c53b6a4769e9c58059e9b4aca5f7a3d9e2bf Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Fri, 13 Nov 2026 19:18:36 -0800 Subject: [PATCH 09/51] DisjunctiveMonoid for every Alternative, & for Set & Map by <> Every Alternative of base, containers & vector is a DisjunctiveMonoid, by deriving anyclass, adding lists, Seq & Vector; & Set, IntSet, Map & IntMap disjoin by their monoids, of union. Co-Authored-By: Claude Opus 5.5 --- distributors-core/CHANGELOG.md | 5 +- .../src/Data/Monoid/Disjunctive.hs | 46 +++++++++++++------ 2 files changed, 36 insertions(+), 15 deletions(-) diff --git a/distributors-core/CHANGELOG.md b/distributors-core/CHANGELOG.md index a43f6084..d779006c 100644 --- a/distributors-core/CHANGELOG.md +++ b/distributors-core/CHANGELOG.md @@ -4,7 +4,10 @@ ### New APIs -- `Set`s are a `DisjunctiveMonoid` by union. +- More `DisjunctiveMonoid` instances: every `Alternative` of `base`, + `containers` & `vector`, by `empty` & `<|>`, now with lists, `Seq`s & + `Vector`s; & `Set`s, `IntSet`s, `Map`s & `IntMap`s, by their monoids, + of union. - `stepping` & its combinators, `terminateBy`, `delimitBy`, `balanceBy` & `countWith`, step through any stream, @(Cons s s a a, AsEmpty s)@, like a `Data.Sequence.Seq` or `Data.Text.Text`, not only lists. diff --git a/distributors-core/src/Data/Monoid/Disjunctive.hs b/distributors-core/src/Data/Monoid/Disjunctive.hs index 5d9716f1..bf71766a 100644 --- a/distributors-core/src/Data/Monoid/Disjunctive.hs +++ b/distributors-core/src/Data/Monoid/Disjunctive.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE DeriveAnyClass #-} {- | Module : Data.Monoid.Disjunctive Description : disjunctive monoids, Boolean & Kleene star algebras @@ -41,8 +42,12 @@ import Data.Profunctor.Cayley import Data.Profunctor.Monad import Data.Profunctor.Yoneda import Data.Proxy +import Data.IntMap (IntMap) +import Data.IntSet (IntSet) +import Data.Map (Map) +import Data.Sequence (Seq) import Data.Set (Set) -import qualified Data.Set as Set +import Data.Vector (Vector) import GHC.Conc (STM) import GHC.Generics import Text.ParserCombinators.ReadP (ReadP) @@ -237,20 +242,33 @@ deriving via Generically (Const a b) deriving via Generically (Proxy a) instance DisjunctiveMonoid (Proxy a) deriving via Generically (Proxy a) instance BooleanAlgebra (Proxy a) deriving via Generically (Proxy a) instance KleeneStarAlgebra (Proxy a) --- | Sets, by union, disjoin their members. +-- | Sets & maps disjoin by their monoids, of union. instance Ord a => DisjunctiveMonoid (Set a) where - falseP = Set.empty - (>|<) = Set.union -instance DisjunctiveMonoid (Maybe a) -instance DisjunctiveMonoid (IO a) -instance DisjunctiveMonoid (STM a) -instance DisjunctiveMonoid (ZipList a) -instance DisjunctiveMonoid (ReadP a) -instance DisjunctiveMonoid (ReadPrec a) -instance DisjunctiveMonoid (U1 p) -instance MonadPlus m => DisjunctiveMonoid (WrappedMonad m a) -instance ArrowPlus a => DisjunctiveMonoid (WrappedArrow a b c) -instance ArrowPlus a => DisjunctiveMonoid (ArrowMonad a b) + falseP = mempty + (>|<) = (<>) +instance DisjunctiveMonoid IntSet where + falseP = mempty + (>|<) = (<>) +instance Ord k => DisjunctiveMonoid (Map k v) where + falseP = mempty + (>|<) = (<>) +instance DisjunctiveMonoid (IntMap v) where + falseP = mempty + (>|<) = (<>) +-- `Alternative`s disjoin by `empty` & `<|>`. +deriving anyclass instance DisjunctiveMonoid [a] +deriving anyclass instance DisjunctiveMonoid (Maybe a) +deriving anyclass instance DisjunctiveMonoid (IO a) +deriving anyclass instance DisjunctiveMonoid (STM a) +deriving anyclass instance DisjunctiveMonoid (ZipList a) +deriving anyclass instance DisjunctiveMonoid (ReadP a) +deriving anyclass instance DisjunctiveMonoid (ReadPrec a) +deriving anyclass instance DisjunctiveMonoid (U1 p) +deriving anyclass instance DisjunctiveMonoid (Seq a) +deriving anyclass instance DisjunctiveMonoid (Vector a) +deriving anyclass instance MonadPlus m => DisjunctiveMonoid (WrappedMonad m a) +deriving anyclass instance ArrowPlus a => DisjunctiveMonoid (WrappedArrow a b c) +deriving anyclass instance ArrowPlus a => DisjunctiveMonoid (ArrowMonad a b) instance DisjunctiveMonoid (f a) => DisjunctiveMonoid (Alt f a) where falseP = Alt falseP Alt x >|< Alt y = Alt (x >|< y) From 4524d22d2502202bfe52583c3b04005bd3b2db15 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Fri, 13 Nov 2026 19:26:48 -0800 Subject: [PATCH 10/51] DisjunctiveMonoid for every Alternative of the dependencies Exhaustive by GHCi's :info: all 48 Alternative instances visible through core's dependencies are DisjunctiveMonoids, adding transformers' monad transformers (each variant), free's Free, F, FreeT, FT & Alt, lens's ReifiedFold & witherable's WrappedFoldable, by deriving anyclass with their Alternative instances' contexts, in the class's module. Co-Authored-By: Claude Opus 5.5 --- distributors-core/CHANGELOG.md | 9 +-- .../src/Data/Monoid/Disjunctive.hs | 61 +++++++++++++++++++ 2 files changed, 66 insertions(+), 4 deletions(-) diff --git a/distributors-core/CHANGELOG.md b/distributors-core/CHANGELOG.md index d779006c..009667f8 100644 --- a/distributors-core/CHANGELOG.md +++ b/distributors-core/CHANGELOG.md @@ -4,10 +4,11 @@ ### New APIs -- More `DisjunctiveMonoid` instances: every `Alternative` of `base`, - `containers` & `vector`, by `empty` & `<|>`, now with lists, `Seq`s & - `Vector`s; & `Set`s, `IntSet`s, `Map`s & `IntMap`s, by their monoids, - of union. +- More `DisjunctiveMonoid` instances: every `Alternative` of the + dependencies, `base`, `containers`, `vector`, `transformers`, `free`, + `lens` & `witherable`, by `empty` & `<|>`, now with lists, `Seq`s, + `Vector`s, monad transformers, free monads & `ReifiedFold`s; & `Set`s, + `IntSet`s, `Map`s & `IntMap`s, by their monoids, of union. - `stepping` & its combinators, `terminateBy`, `delimitBy`, `balanceBy` & `countWith`, step through any stream, @(Cons s s a a, AsEmpty s)@, like a `Data.Sequence.Seq` or `Data.Text.Text`, not only lists. diff --git a/distributors-core/src/Data/Monoid/Disjunctive.hs b/distributors-core/src/Data/Monoid/Disjunctive.hs index bf71766a..9556a2c7 100644 --- a/distributors-core/src/Data/Monoid/Disjunctive.hs +++ b/distributors-core/src/Data/Monoid/Disjunctive.hs @@ -42,6 +42,29 @@ import Data.Profunctor.Cayley import Data.Profunctor.Monad import Data.Profunctor.Yoneda import Data.Proxy +import Control.Alternative.Free qualified as FreeAlt +import Control.Applicative.Backwards (Backwards) +import Control.Applicative.Lift (Lift) +import Control.Lens (ReifiedFold) +import Control.Monad.Free (Free) +import Control.Monad.Free.Church qualified as Church +import Control.Monad.Trans.Accum (AccumT) +import Control.Monad.Trans.Except (ExceptT) +import Control.Monad.Trans.Free (FreeT) +import Control.Monad.Trans.Free.Church (FT) +import Control.Monad.Trans.Identity (IdentityT) +import Control.Monad.Trans.Maybe (MaybeT) +import Control.Monad.Trans.Reader (ReaderT) +import Control.Monad.Trans.RWS.CPS qualified as CPSRWS +import Control.Monad.Trans.RWS.Lazy qualified as LazyRWS +import Control.Monad.Trans.RWS.Strict qualified as StrictRWS +import Control.Monad.Trans.Select (SelectT) +import Control.Monad.Trans.State.Lazy qualified as Lazy +import Control.Monad.Trans.State.Strict qualified as Strict +import Control.Monad.Trans.Writer.CPS qualified as CPSW +import Control.Monad.Trans.Writer.Lazy qualified as LazyW +import Control.Monad.Trans.Writer.Strict qualified as StrictW +import Data.Functor.Reverse (Reverse) import Data.IntMap (IntMap) import Data.IntSet (IntSet) import Data.Map (Map) @@ -52,6 +75,7 @@ import GHC.Conc (STM) import GHC.Generics import Text.ParserCombinators.ReadP (ReadP) import Text.ParserCombinators.ReadPrec (ReadPrec) +import Witherable (WrappedFoldable) {- | A `DisjunctiveMonoid` is simply a monoid, the only difference from `Monoid` being its semantics @@ -269,6 +293,43 @@ deriving anyclass instance DisjunctiveMonoid (Vector a) deriving anyclass instance MonadPlus m => DisjunctiveMonoid (WrappedMonad m a) deriving anyclass instance ArrowPlus a => DisjunctiveMonoid (WrappedArrow a b c) deriving anyclass instance ArrowPlus a => DisjunctiveMonoid (ArrowMonad a b) +deriving anyclass instance Alternative f => DisjunctiveMonoid (Backwards f a) +deriving anyclass instance Alternative f => DisjunctiveMonoid (Lift f a) +deriving anyclass instance Alternative f => DisjunctiveMonoid (Reverse f a) +deriving anyclass instance Alternative m => DisjunctiveMonoid (IdentityT m a) +deriving anyclass instance Alternative m => DisjunctiveMonoid (ReaderT r m a) +deriving anyclass instance (Functor m, Monad m) + => DisjunctiveMonoid (MaybeT m a) +deriving anyclass instance (Functor m, Monad m, Monoid e) + => DisjunctiveMonoid (ExceptT e m a) +deriving anyclass instance (Functor m, MonadPlus m) + => DisjunctiveMonoid (Lazy.StateT s m a) +deriving anyclass instance (Functor m, MonadPlus m) + => DisjunctiveMonoid (Strict.StateT s m a) +deriving anyclass instance (Monoid w, Alternative m) + => DisjunctiveMonoid (LazyW.WriterT w m a) +deriving anyclass instance (Monoid w, Alternative m) + => DisjunctiveMonoid (StrictW.WriterT w m a) +deriving anyclass instance (Functor m, MonadPlus m) + => DisjunctiveMonoid (CPSW.WriterT w m a) +deriving anyclass instance (Monoid w, Functor m, MonadPlus m) + => DisjunctiveMonoid (LazyRWS.RWST r w s m a) +deriving anyclass instance (Monoid w, Functor m, MonadPlus m) + => DisjunctiveMonoid (StrictRWS.RWST r w s m a) +deriving anyclass instance (Functor m, MonadPlus m) + => DisjunctiveMonoid (CPSRWS.RWST r w s m a) +deriving anyclass instance (Monoid w, Functor m, MonadPlus m) + => DisjunctiveMonoid (AccumT w m a) +deriving anyclass instance (Functor m, MonadPlus m) + => DisjunctiveMonoid (SelectT r m a) +deriving anyclass instance Alternative v => DisjunctiveMonoid (Free v a) +deriving anyclass instance Alternative f => DisjunctiveMonoid (Church.F f a) +deriving anyclass instance (Functor f, MonadPlus m) + => DisjunctiveMonoid (FreeT f m a) +deriving anyclass instance Alternative m => DisjunctiveMonoid (FT f m a) +deriving anyclass instance DisjunctiveMonoid (FreeAlt.Alt f a) +deriving anyclass instance DisjunctiveMonoid (ReifiedFold s a) +deriving anyclass instance Alternative f => DisjunctiveMonoid (WrappedFoldable f a) instance DisjunctiveMonoid (f a) => DisjunctiveMonoid (Alt f a) where falseP = Alt falseP Alt x >|< Alt y = Alt (x >|< y) From e48aa8dd701802384f7ac05ef2da2c0866d92b29 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Fri, 13 Nov 2026 19:32:21 -0800 Subject: [PATCH 11/51] Bits as BooleanAlgebras; Predicate & Ap Kleene; ReadPrec & Predicate tokens - Bits types are BooleanAlgebras of bit vectors (.|., .&., complement), by a private Bitwise newtype: every Int & Word, Integer, IntPtr, WordPtr & the Foreign.C.Types integers; Natural, lacking complement, only disjoins. - KleeneStarAlgebras: Predicate (star true, as a Boolean algebra is) & Ap of an Alternative of Monoids (languages, star by many, a near-semiring, documented). - Predicate is Tokenized & a TokenAlgebra, via token -> Bool; ReadPrec runs grammars as ReadP does (Tokenized, TokenAlgebra, TerminalSymbol, Ruled, BackusNaurForm, Tried; Filterable in core's Orphanage). Laws tested at Int, Int8, Word8, Integer & Natural; Ap's star at ReadP; a grammar at ReadPrec as at ReadP; a token class as a Predicate. Co-Authored-By: Claude Opus 5.5 --- distributors-core/CHANGELOG.md | 7 ++ distributors-core/distributors.cabal | 1 + .../Lens/Internal/Distributor/Orphanage.hs | 3 + .../src/Data/Monoid/Disjunctive.hs | 112 ++++++++++++++++++ distributors-core/test/Main.hs | 2 + .../test/Properties/Disjunctive.hs | 47 ++++++++ distributors-grammar/CHANGELOG.md | 3 + .../src/Control/Lens/Grammar/BackusNaur.hs | 4 + .../src/Control/Lens/Grammar/Symbol.hs | 3 + .../src/Control/Lens/Grammar/Token.hs | 16 +++ distributors-grammar/test/Main.hs | 12 ++ 11 files changed, 210 insertions(+) create mode 100644 distributors-core/test/Properties/Disjunctive.hs diff --git a/distributors-core/CHANGELOG.md b/distributors-core/CHANGELOG.md index 009667f8..f4e9792e 100644 --- a/distributors-core/CHANGELOG.md +++ b/distributors-core/CHANGELOG.md @@ -9,6 +9,13 @@ `lens` & `witherable`, by `empty` & `<|>`, now with lists, `Seq`s, `Vector`s, monad transformers, free monads & `ReifiedFold`s; & `Set`s, `IntSet`s, `Map`s & `IntMap`s, by their monoids, of union. +- `Bits` types are `BooleanAlgebra`s of bit vectors, by `.|.`, `.&.` & + `complement`: every `Int` & `Word`, `Integer`, `IntPtr`, `WordPtr` & the + integers of `Foreign.C.Types`; & `Natural`, without `complement`, only a + `DisjunctiveMonoid`. +- `KleeneStarAlgebra`s: `Predicate`s, whose star is true, & `Ap`s of + `Alternative`s of `Monoid`s, languages, starred by `many`, a + near-semiring. `ReadPrec` is `Filterable`. - `stepping` & its combinators, `terminateBy`, `delimitBy`, `balanceBy` & `countWith`, step through any stream, @(Cons s s a a, AsEmpty s)@, like a `Data.Sequence.Seq` or `Data.Text.Text`, not only lists. diff --git a/distributors-core/distributors.cabal b/distributors-core/distributors.cabal index 867661ef..1a519709 100644 --- a/distributors-core/distributors.cabal +++ b/distributors-core/distributors.cabal @@ -183,6 +183,7 @@ test-suite test type: exitcode-stdio-1.0 main-is: Main.hs other-modules: + Properties.Disjunctive Properties.Homogeneous Properties.Nested Properties.Parsing diff --git a/distributors-core/src/Control/Lens/Internal/Distributor/Orphanage.hs b/distributors-core/src/Control/Lens/Internal/Distributor/Orphanage.hs index bb0ebc0d..d160e6c3 100644 --- a/distributors-core/src/Control/Lens/Internal/Distributor/Orphanage.hs +++ b/distributors-core/src/Control/Lens/Internal/Distributor/Orphanage.hs @@ -33,6 +33,7 @@ import Data.Profunctor.Composition import Data.Profunctor.Monad import Data.Profunctor.Yoneda import Text.ParserCombinators.ReadP (ReadP) +import Text.ParserCombinators.ReadPrec (ReadPrec) import Witherable -- Orphanage -- @@ -76,6 +77,8 @@ instance Filterable f => Cochoice (Joker f) where (mapMaybe (either (const Nothing) Just) x) instance Filterable ReadP where catMaybes m = m >>= maybe empty pure +instance Filterable ReadPrec where + catMaybes m = m >>= maybe empty pure deriving via Compose (p a) f instance (Profunctor p, Applicative (p a), Applicative f) => Applicative (WrappedPafb f p a) diff --git a/distributors-core/src/Data/Monoid/Disjunctive.hs b/distributors-core/src/Data/Monoid/Disjunctive.hs index 9556a2c7..0caab65b 100644 --- a/distributors-core/src/Data/Monoid/Disjunctive.hs +++ b/distributors-core/src/Data/Monoid/Disjunctive.hs @@ -65,13 +65,19 @@ import Control.Monad.Trans.Writer.CPS qualified as CPSW import Control.Monad.Trans.Writer.Lazy qualified as LazyW import Control.Monad.Trans.Writer.Strict qualified as StrictW import Data.Functor.Reverse (Reverse) +import Data.Bits (Bits (..)) +import Data.Int (Int8, Int16, Int32, Int64) import Data.IntMap (IntMap) import Data.IntSet (IntSet) import Data.Map (Map) import Data.Sequence (Seq) import Data.Set (Set) import Data.Vector (Vector) +import Data.Word (Word8, Word16, Word32, Word64) +import Foreign.C.Types +import Foreign.Ptr (IntPtr, WordPtr) import GHC.Conc (STM) +import Numeric.Natural (Natural) import GHC.Generics import Text.ParserCombinators.ReadP (ReadP) import Text.ParserCombinators.ReadPrec (ReadPrec) @@ -266,6 +272,112 @@ deriving via Generically (Const a b) deriving via Generically (Proxy a) instance DisjunctiveMonoid (Proxy a) deriving via Generically (Proxy a) instance BooleanAlgebra (Proxy a) deriving via Generically (Proxy a) instance KleeneStarAlgebra (Proxy a) +{- | Bits disjoin by `.|.`, & conjoin by `.&.`, of a Boolean algebra +of bit vectors, `Integer`'s of infinitely many bits, two's complement. +`Natural` has no `complement`, so it only disjoins. +-} +newtype Bitwise a = Bitwise a +instance Bits a => DisjunctiveMonoid (Bitwise a) where + falseP = Bitwise zeroBits + Bitwise x >|< Bitwise y = Bitwise (x .|. y) +instance Bits a => BooleanAlgebra (Bitwise a) where + trueP = Bitwise (complement zeroBits) + notP (Bitwise x) = Bitwise (complement x) + Bitwise x >&< Bitwise y = Bitwise (x .&. y) +deriving via Bitwise Int instance DisjunctiveMonoid Int +deriving via Bitwise Int instance BooleanAlgebra Int +deriving via Bitwise Int8 instance DisjunctiveMonoid Int8 +deriving via Bitwise Int8 instance BooleanAlgebra Int8 +deriving via Bitwise Int16 instance DisjunctiveMonoid Int16 +deriving via Bitwise Int16 instance BooleanAlgebra Int16 +deriving via Bitwise Int32 instance DisjunctiveMonoid Int32 +deriving via Bitwise Int32 instance BooleanAlgebra Int32 +deriving via Bitwise Int64 instance DisjunctiveMonoid Int64 +deriving via Bitwise Int64 instance BooleanAlgebra Int64 +deriving via Bitwise Word instance DisjunctiveMonoid Word +deriving via Bitwise Word instance BooleanAlgebra Word +deriving via Bitwise Word8 instance DisjunctiveMonoid Word8 +deriving via Bitwise Word8 instance BooleanAlgebra Word8 +deriving via Bitwise Word16 instance DisjunctiveMonoid Word16 +deriving via Bitwise Word16 instance BooleanAlgebra Word16 +deriving via Bitwise Word32 instance DisjunctiveMonoid Word32 +deriving via Bitwise Word32 instance BooleanAlgebra Word32 +deriving via Bitwise Word64 instance DisjunctiveMonoid Word64 +deriving via Bitwise Word64 instance BooleanAlgebra Word64 +deriving via Bitwise Integer instance DisjunctiveMonoid Integer +deriving via Bitwise Integer instance BooleanAlgebra Integer +deriving via Bitwise IntPtr instance DisjunctiveMonoid IntPtr +deriving via Bitwise IntPtr instance BooleanAlgebra IntPtr +deriving via Bitwise WordPtr instance DisjunctiveMonoid WordPtr +deriving via Bitwise WordPtr instance BooleanAlgebra WordPtr +deriving via Bitwise CChar instance DisjunctiveMonoid CChar +deriving via Bitwise CChar instance BooleanAlgebra CChar +deriving via Bitwise CSChar instance DisjunctiveMonoid CSChar +deriving via Bitwise CSChar instance BooleanAlgebra CSChar +deriving via Bitwise CUChar instance DisjunctiveMonoid CUChar +deriving via Bitwise CUChar instance BooleanAlgebra CUChar +deriving via Bitwise CShort instance DisjunctiveMonoid CShort +deriving via Bitwise CShort instance BooleanAlgebra CShort +deriving via Bitwise CUShort instance DisjunctiveMonoid CUShort +deriving via Bitwise CUShort instance BooleanAlgebra CUShort +deriving via Bitwise CInt instance DisjunctiveMonoid CInt +deriving via Bitwise CInt instance BooleanAlgebra CInt +deriving via Bitwise CUInt instance DisjunctiveMonoid CUInt +deriving via Bitwise CUInt instance BooleanAlgebra CUInt +deriving via Bitwise CLong instance DisjunctiveMonoid CLong +deriving via Bitwise CLong instance BooleanAlgebra CLong +deriving via Bitwise CULong instance DisjunctiveMonoid CULong +deriving via Bitwise CULong instance BooleanAlgebra CULong +deriving via Bitwise CLLong instance DisjunctiveMonoid CLLong +deriving via Bitwise CLLong instance BooleanAlgebra CLLong +deriving via Bitwise CULLong instance DisjunctiveMonoid CULLong +deriving via Bitwise CULLong instance BooleanAlgebra CULLong +deriving via Bitwise CPtrdiff instance DisjunctiveMonoid CPtrdiff +deriving via Bitwise CPtrdiff instance BooleanAlgebra CPtrdiff +deriving via Bitwise CSize instance DisjunctiveMonoid CSize +deriving via Bitwise CSize instance BooleanAlgebra CSize +deriving via Bitwise CWchar instance DisjunctiveMonoid CWchar +deriving via Bitwise CWchar instance BooleanAlgebra CWchar +deriving via Bitwise CSigAtomic instance DisjunctiveMonoid CSigAtomic +deriving via Bitwise CSigAtomic instance BooleanAlgebra CSigAtomic +deriving via Bitwise CIntPtr instance DisjunctiveMonoid CIntPtr +deriving via Bitwise CIntPtr instance BooleanAlgebra CIntPtr +deriving via Bitwise CUIntPtr instance DisjunctiveMonoid CUIntPtr +deriving via Bitwise CUIntPtr instance BooleanAlgebra CUIntPtr +deriving via Bitwise CIntMax instance DisjunctiveMonoid CIntMax +deriving via Bitwise CIntMax instance BooleanAlgebra CIntMax +deriving via Bitwise CUIntMax instance DisjunctiveMonoid CUIntMax +deriving via Bitwise CUIntMax instance BooleanAlgebra CUIntMax +deriving via Bitwise CBool instance DisjunctiveMonoid CBool +deriving via Bitwise CBool instance BooleanAlgebra CBool +deriving via Bitwise Natural instance DisjunctiveMonoid Natural + +{- | A `Predicate` is a Kleene algebra, as a Boolean algebra is, +of conjunction, `Predicate`'s `Monoid`, & disjunction, +whose star is true. + +> prop> starK p = trueP +-} +instance KleeneStarAlgebra (Predicate a) where + starK _ = trueP + plusK = id + optK _ = trueP + +{- | An `Alternative` of `Monoid`s is a Kleene algebra of languages, +like a parser of words: its sequence is `Ap`'s `Monoid`, its +alternation `<|>`, & its star `many` concatenated. It's a near-semiring, +whose left distribution, @(x >|< y) <> z = (x <> z) >|< (y <> z)@, +a left-biased `Alternative` may not keep, & its star diverges where +`many` does, as of a non-empty list's. + +> prop> starK (Ap x) = Ap (mconcat <$> many x) +> prop> plusK (Ap x) = Ap (mconcat <$> some x) +-} +instance (Alternative f, Monoid a, DisjunctiveMonoid (f a)) + => KleeneStarAlgebra (Ap f a) where + starK (Ap x) = Ap (mconcat <$> many x) + plusK (Ap x) = Ap (mconcat <$> some x) + -- | Sets & maps disjoin by their monoids, of union. instance Ord a => DisjunctiveMonoid (Set a) where falseP = mempty diff --git a/distributors-core/test/Main.hs b/distributors-core/test/Main.hs index 55429b23..838ca7a8 100644 --- a/distributors-core/test/Main.hs +++ b/distributors-core/test/Main.hs @@ -5,6 +5,7 @@ import Data.Profunctor.Monoidal (meander) import Data.Profunctor.Types (Star (..)) import Test.Hspec +import Properties.Disjunctive import Properties.Homogeneous import Properties.Nested import Properties.PartialIso @@ -12,6 +13,7 @@ import Properties.Parsing main :: IO () main = hspec $ do + describe "Disjunctive" disjunctiveProperties describe "Homogeneous" homogeneousProperties describe "PartialIso" partialIsoProperties describe "Nested" nestedProperties diff --git a/distributors-core/test/Properties/Disjunctive.hs b/distributors-core/test/Properties/Disjunctive.hs new file mode 100644 index 00000000..d872d9c6 --- /dev/null +++ b/distributors-core/test/Properties/Disjunctive.hs @@ -0,0 +1,47 @@ +module Properties.Disjunctive (disjunctiveProperties) where + +import Data.Functor.Contravariant (Predicate (..)) +import Data.Int (Int8) +import Data.Monoid (Ap (..)) +import Data.Monoid.Disjunctive +import Data.Word (Word8) +import Numeric.Natural (Natural) +import Test.Hspec +import Test.Hspec.QuickCheck (prop) +import Test.QuickCheck +import Text.ParserCombinators.ReadP (ReadP, readP_to_S, string) + +disjunctiveProperties :: Spec +disjunctiveProperties = do + describe "Bits, as a BooleanAlgebra of bit vectors" $ do + booleanLaws "Int" (arbitrary :: Gen Int) + booleanLaws "Int8" (arbitrary :: Gen Int8) + booleanLaws "Word8" (arbitrary :: Gen Word8) + booleanLaws "Integer" (arbitrary :: Gen Integer) + prop "Natural disjoins as a monoid" $ \(NonNegative (x :: Integer)) y -> + let n = fromInteger x :: Natural + m = fromInteger (getNonNegative y) :: Natural + in (falseP >|< n) === n .&&. (n >|< m) === (m >|< n) + describe "Predicate, as a Kleene algebra" $ + prop "its star is true" $ \(Fun _ p) (x :: Int) -> + getPredicate (starK (Predicate p)) x === True + .&&. getPredicate (optK (Predicate p)) x === True + describe "Ap, as a Kleene algebra of languages" $ + it "stars by many, concatenated" $ do + let star = getAp (starK (Ap (string "ab"))) :: ReadP String + [w | (w, "") <- readP_to_S star "ababab"] `shouldBe` ["ababab"] + [w | (w, "") <- readP_to_S star ""] `shouldBe` [""] + let plus = getAp (plusK (Ap (string "ab"))) :: ReadP String + [w | (w, "") <- readP_to_S plus ""] `shouldBe` [] + +booleanLaws + :: (Show b, Eq b, BooleanAlgebra b) => String -> Gen b -> Spec +booleanLaws name gen = describe name $ do + prop "x >&< notP x = falseP & x >|< notP x = trueP" $ + forAll gen $ \x -> + (x >&< notP x) === falseP .&&. (x >|< notP x) === trueP + prop "de Morgan" $ forAll gen $ \x -> forAll gen $ \y -> + notP (x >|< y) === (notP x >&< notP y) + prop "notP . notP = id" $ forAll gen $ \x -> notP (notP x) === x + prop "units" $ forAll gen $ \x -> + (x >|< falseP) === x .&&. (x >&< trueP) === x diff --git a/distributors-grammar/CHANGELOG.md b/distributors-grammar/CHANGELOG.md index 27bab963..32ba7239 100644 --- a/distributors-grammar/CHANGELOG.md +++ b/distributors-grammar/CHANGELOG.md @@ -2,6 +2,9 @@ ## Unreleased +- `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`, diff --git a/distributors-grammar/src/Control/Lens/Grammar/BackusNaur.hs b/distributors-grammar/src/Control/Lens/Grammar/BackusNaur.hs index de5ba041..06dc655b 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/BackusNaur.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/BackusNaur.hs @@ -34,6 +34,7 @@ import Data.Profunctor.Filtrator (Filtrator) import Data.Function import Data.Monoid.Disjunctive import Text.ParserCombinators.ReadP (ReadP) +import Text.ParserCombinators.ReadPrec (ReadPrec) {- | `BackusNaurForm` grammar combinators formalize traced `rule` abstraction and general recursion with `ruleRec`, @@ -140,3 +141,6 @@ instance (forall x. Tried (f x)) => Tried (Joker f a b) where instance Ruled (ReadP a) instance BackusNaurForm (ReadP a) 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/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/test/Main.hs b/distributors-grammar/test/Main.hs index e0307e80..c00a3435 100644 --- a/distributors-grammar/test/Main.hs +++ b/distributors-grammar/test/Main.hs @@ -7,6 +7,8 @@ import Control.Monad (when) import Data.List (genericLength) import Data.Tree (Tree (..)) 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 qualified Text.Megaparsec as M @@ -42,6 +44,16 @@ main = hspec $ do describe "Kleene" kleeneProperties describe "Varifocal" varifocalProperties describe "class runners, at Arith's Grammar" classRunnerTests + describe "ReadPrec & Predicate" readPrecTests + +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) -> From bf19bfc4a5ea0b516aa4e883314c174636f2eaa8 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Fri, 13 Nov 2026 19:45:50 -0800 Subject: [PATCH 12/51] Grammars of base types RegGrammar Char instances, each Grammar a rule named by its type: Char (any token), String (any tokens), Natural (ASCII digits), Integer (optional minus, digits), Double & Float (NaN, or signed Infinity or decimals with optional fraction & exponent), printing canonically as show does & parsing more as read does, by improper isos of hidden helpers. Sized Ints & Words are CtxGrammars: an out-of-range literal fails to build, which needs a Filtrator (?<), so they have no regex. Tested: round trips (incl. NaN, infinities, -0.0), improper parses (007, -0, 1E+5, 1.50), range failures, & static LL(1) by ll1Conflicts. Co-Authored-By: Claude Opus 5.5 --- distributors-grammar/CHANGELOG.md | 8 ++ .../distributors-grammar.cabal | 1 + .../src/Control/Lens/Grammar.hs | 108 ++++++++++++++++++ distributors-grammar/test/Main.hs | 2 + distributors-grammar/test/Properties/Base.hs | 67 +++++++++++ 5 files changed, 186 insertions(+) create mode 100644 distributors-grammar/test/Properties/Base.hs diff --git a/distributors-grammar/CHANGELOG.md b/distributors-grammar/CHANGELOG.md index 32ba7239..b1af5a81 100644 --- a/distributors-grammar/CHANGELOG.md +++ b/distributors-grammar/CHANGELOG.md @@ -2,6 +2,14 @@ ## Unreleased +- Grammars of base types, each a rule named by its type: `Char`, any + token; `String`, any tokens; `Natural`, ASCII digits; `Integer`, an + optional minus & digits; `Double` & `Float`, @NaN@, or signed @Infinity@ + or decimals with an optional fraction & exponent; printing canonically, + as `show` does, & parsing more, as `read` does, by improper isos. Sized + integers, `Int`s & `Word`s, are `CtxGrammar`s, failing out of range by + their `Filtrator`, so they have no regular expressions or Backus-Naur + forms. - `Predicate`s are `Tokenized` & `TokenAlgebra`s, as predicates are; & `ReadPrec` runs grammars as `ReadP` does, `Tokenized`, a `TokenAlgebra`, `TerminalSymbol`, `Ruled`, `BackusNaurForm` & `Tried`. diff --git a/distributors-grammar/distributors-grammar.cabal b/distributors-grammar/distributors-grammar.cabal index 1d8281e9..8dca6ecb 100644 --- a/distributors-grammar/distributors-grammar.cabal +++ b/distributors-grammar/distributors-grammar.cabal @@ -177,6 +177,7 @@ test-suite test Examples.RegString Examples.SemVer Examples.SExpr + Properties.Base Properties.Kleene Properties.Varifocal Paths_distributors_grammar diff --git a/distributors-grammar/src/Control/Lens/Grammar.hs b/distributors-grammar/src/Control/Lens/Grammar.hs index 01caec72..dce46be8 100644 --- a/distributors-grammar/src/Control/Lens/Grammar.hs +++ b/distributors-grammar/src/Control/Lens/Grammar.hs @@ -48,6 +48,10 @@ import Control.Lens.Grammar.RegEx import Control.Lens.Grammar.Token import Control.Lens.Grammar.Symbol import Data.Bifunctor.Joker +import Data.Bits (Bits, toIntegralSized) +import Data.Char (isDigit) +import Data.Int (Int8, Int16, Int32, Int64) +import Data.Maybe (isJust) import Data.Monoid.Disjunctive import Data.Profunctor.Distributor import Data.Profunctor.Monoidal.Cocartesian @@ -56,7 +60,9 @@ import Data.Profunctor.Monadic as X import Data.Profunctor.Monoidal import Data.Profunctor.Grammar import Data.Profunctor.Grammar.Parsector +import Data.Word (Word8, Word16, Word32, Word64) import GHC.Exts +import Numeric.Natural (Natural) import Prelude hiding (filter) import Text.ParserCombinators.ReadP (ReadP) import Witherable @@ -775,6 +781,108 @@ to string-like interfaces such as `RegEx` and t'Bnf' of `Char`s. putStringLn :: (IsList string, Item string ~ Char) => string -> IO () putStringLn = putStrLn . toList +-- Base types -- + +instance CtxGrammar Char Char +instance Grammar Char Char where grammar = rule "Char" (regGrammar @Char) +instance RegGrammar Char Char where regGrammar = anyToken @Char + +instance CtxGrammar Char String +instance Grammar Char String where grammar = rule "String" (regGrammar @Char) +instance RegGrammar Char String where regGrammar = manyP (anyToken @Char) + +instance CtxGrammar Char Natural +instance Grammar Char Natural where grammar = rule "Natural" (regGrammar @Char) +instance RegGrammar Char Natural where regGrammar = naturalG + +instance CtxGrammar Char Integer +instance Grammar Char Integer where grammar = rule "Integer" (regGrammar @Char) +instance RegGrammar Char Integer where regGrammar = integerG + +instance CtxGrammar Char Double +instance Grammar Char Double where grammar = rule "Double" (regGrammar @Char) +instance RegGrammar Char Double where regGrammar = floatingG + +instance CtxGrammar Char Float +instance Grammar Char Float where grammar = rule "Float" (regGrammar @Char) +instance RegGrammar Char Float where regGrammar = floatingG + +{- Sized integers' syntax is `Integer`'s, but a literal out of their range +fails to build, which only a `CtxGrammar`'s `Filtrator` can, so they have +no regular expression or Backus-Naur form. -} +instance CtxGrammar Char Int where ctxGrammar = rule "Int" sizedG +instance CtxGrammar Char Int8 where ctxGrammar = rule "Int8" sizedG +instance CtxGrammar Char Int16 where ctxGrammar = rule "Int16" sizedG +instance CtxGrammar Char Int32 where ctxGrammar = rule "Int32" sizedG +instance CtxGrammar Char Int64 where ctxGrammar = rule "Int64" sizedG +instance CtxGrammar Char Word where ctxGrammar = rule "Word" sizedG +instance CtxGrammar Char Word8 where ctxGrammar = rule "Word8" sizedG +instance CtxGrammar Char Word16 where ctxGrammar = rule "Word16" sizedG +instance CtxGrammar Char Word32 where ctxGrammar = rule "Word32" sizedG +instance CtxGrammar Char Word64 where ctxGrammar = rule "Word64" sizedG + +-- ASCII decimal digits, at least one. +decimalG :: RegGrammatical Char p => p String String +decimalG = someP (oneOf ['0' .. '9']) + +-- An optional minus, as whether a number is negative. +negativeG :: RegGrammatical Char p => p Bool Bool +negativeG = iso (\b -> if b then Just () else Nothing) isJust + >~ optionalP (terminal "-") + +-- Printing canonically, parsing leading zeros too, an improper iso. +naturalG :: RegGrammatical Char p => p Natural Natural +naturalG = iso show read >~ decimalG + +-- Printing canonically, parsing leading zeros & -0 too, an improper iso. +integerG :: RegGrammatical Char p => p Integer Integer +integerG = iso + (\n -> (n < 0, show (abs n))) + (\(negative, digits) -> (if negative then negate else id) (read digits)) + >~ negativeG >*< decimalG + +-- Integers in a range, failing to build out of it. +sizedG + :: forall a p. (Integral a, Bits a, CtxGrammatical Char p) => p a a +sizedG = prism' toInteger toIntegralSized ?< integerG + +{- Floating point numbers, @NaN@, or signed @Infinity@ or decimals with +an optional fraction & exponent, printing as `show` does & parsing as +`read` does, an improper iso, keeping the sign of zero. -} +floatingG + :: (RealFloat a, Read a, Show a, RegGrammatical Char p) => p a a +floatingG = iso toFloating fromFloating >~ + terminal "NaN" >+< negativeG >*< (terminal "Infinity" >+< numberG) + where + numberG = decimalG + >*< optionalP (terminal "." >* decimalG) + >*< optionalP (oneOf "eE" >*< optionalP (oneOf "+-") >*< decimalG) + toFloating x + | isNaN x = Left () + | otherwise = Right + ( x < 0 || isNegativeZero x + , if isInfinite x then Left () else Right (split (show (abs x))) ) + fromFloating = \case + Left () -> 0 / 0 + Right (negative, magnitude) -> (if negative then negate else id) $ + either (const (1 / 0)) (read . unsplit) magnitude + split shown = + let + (whole, rest) = span isDigit shown + (fraction, rest') = case rest of + '.' : more -> let (ds, more') = span isDigit more in (Just ds, more') + _ -> (Nothing, rest) + exponent' = case rest' of + e : more | e `elem` ("eE" :: String) -> case more of + s : ds | s `elem` ("+-" :: String) -> Just (e, (Just s, ds)) + ds -> Just (e, (Nothing, ds)) + _ -> Nothing + in + (whole, (fraction, exponent')) + unsplit (whole, (fraction, exponent')) = whole + <> maybe "" ('.' :) fraction + <> maybe "" (\(e, (s, ds)) -> e : maybe "" pure s <> ds) exponent' + instance CtxGrammar Char (RegEx Char) instance Grammar Char (RegEx Char) where grammar = regexGrammar instance CtxGrammar Char (Bnf (RegEx Char)) diff --git a/distributors-grammar/test/Main.hs b/distributors-grammar/test/Main.hs index c00a3435..efda25fe 100644 --- a/distributors-grammar/test/Main.hs +++ b/distributors-grammar/test/Main.hs @@ -22,6 +22,7 @@ import Examples.LenVec import Examples.RegString import Examples.SemVer import Examples.SExpr +import Properties.Base import Properties.Kleene import Properties.Varifocal @@ -45,6 +46,7 @@ main = hspec $ do describe "Varifocal" varifocalProperties describe "class runners, at Arith's Grammar" classRunnerTests describe "ReadPrec & Predicate" readPrecTests + describe "base types" baseProperties readPrecTests :: Spec readPrecTests = do diff --git a/distributors-grammar/test/Properties/Base.hs b/distributors-grammar/test/Properties/Base.hs new file mode 100644 index 00000000..bf2f4e60 --- /dev/null +++ b/distributors-grammar/test/Properties/Base.hs @@ -0,0 +1,67 @@ +module Properties.Base (baseProperties) where + +import Control.Lens.Grammar +import Data.Int (Int8) +import GHC.Exts (toList) +import Data.Word (Word8) +import Numeric.Natural (Natural) +import Test.Hspec +import Test.Hspec.QuickCheck (prop) +import Test.QuickCheck + +-- | Parse all of a string, if it parses. +parsed :: forall a. CtxGrammar Char a => String -> [a] +parsed str = [a | (a, "") <- parseG @a str] + +-- | Print a value, if it prints. +printed :: CtxGrammar Char a => a -> Maybe String +printed a = ($ "") <$> printG a + +-- | Printing then parsing round-trips, compared by @eq@. +roundTrips :: forall a. (CtxGrammar Char a, Show a) => a -> Property +roundTrips a = case printed a of + Nothing -> counterexample ("doesn't print: " <> show a) False + Just str -> map show (parsed @a str) === [show a] + +baseProperties :: Spec +baseProperties = do + describe "round trips, printing then parsing" $ do + prop "Char" $ roundTrips @Char + prop "String" $ roundTrips @String + prop "Natural" $ \(NonNegative (n :: Integer)) -> roundTrips (fromInteger n :: Natural) + prop "Integer" $ roundTrips @Integer + prop "Int" $ roundTrips @Int + prop "Int8" $ roundTrips @Int8 + prop "Word8" $ roundTrips @Word8 + prop "Double" $ roundTrips @Double + prop "Float" $ roundTrips @Float + it "Double's NaN, infinities & negative zero" $ + mapM_ (\x -> map show (parsed @Double =<< maybe [] pure (printed x)) `shouldBe` [show x]) + [0 / 0, 1 / 0, -(1 / 0), -0.0 :: Double] + describe "parsing more than printing, by improper isos" $ do + it "Natural, with leading zeros" $ parsed @Natural "007" `shouldBe` [7] + it "Integer, -0" $ parsed @Integer "-0" `shouldBe` [0] + it "Double, exponents & fractions" $ do + parsed @Double "1E+5" `shouldBe` [100000] + parsed @Double "1.50" `shouldBe` [1.5] + parsed @Double "2e-1" `shouldBe` [0.2] + it "prints canonically" $ do + printed (7 :: Natural) `shouldBe` Just "7" + printed (1.5 :: Double) `shouldBe` Just "1.5" + describe "sized integers, failing out of range" $ do + it "Word8" $ do + parsed @Word8 "255" `shouldBe` [255] + parsed @Word8 "256" `shouldBe` [] + parsed @Word8 "-1" `shouldBe` [] + it "Int8" $ do + parsed @Int8 "-128" `shouldBe` [-128] + parsed @Int8 "128" `shouldBe` [] + describe "statically LL(1), by ll1Conflicts" $ do + it "Char" $ ll1Conflicts (regbnfG @Char Char) `shouldBe` [] + it "String" $ ll1Conflicts (regbnfG @Char String) `shouldBe` [] + it "Natural" $ ll1Conflicts (regbnfG @Char Natural) `shouldBe` [] + it "Integer" $ ll1Conflicts (regbnfG @Char Integer) `shouldBe` [] + it "Double" $ ll1Conflicts (regbnfG @Char Double) `shouldBe` [] + describe "regular expressions" $ do + it "Natural" $ toList (regexG @Char Natural) `shouldBe` "[0123456789]+" + it "Integer" $ toList (regexG @Char Integer) `shouldBe` "-?[0123456789]+" From aa01b2bd1c202420ca75f40697294fbd68c68bde Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Fri, 13 Nov 2026 20:15:39 -0800 Subject: [PATCH 13/51] RegEx records try & renders class ranges Co-Authored-By: Claude Opus 5.5 --- distributors-grammar/CHANGELOG.md | 5 + .../src/Control/Lens/Grammar/Analysis.hs | 19 ++- .../src/Control/Lens/Grammar/BackusNaur.hs | 8 +- .../src/Control/Lens/Grammar/Machine.hs | 2 + .../src/Control/Lens/Grammar/RegEx.hs | 114 ++++++++++++++---- .../test/Examples/RegString.hs | 38 +++--- distributors-grammar/test/Main.hs | 25 ++++ distributors-grammar/test/Properties/Base.hs | 4 +- .../src/Control/Lens/Grammar/TypeScript.hs | 1 + 9 files changed, 163 insertions(+), 53 deletions(-) diff --git a/distributors-grammar/CHANGELOG.md b/distributors-grammar/CHANGELOG.md index b1af5a81..58fa575a 100644 --- a/distributors-grammar/CHANGELOG.md +++ b/distributors-grammar/CHANGELOG.md @@ -2,6 +2,11 @@ ## Unreleased +- `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, @\\-@. - Grammars of base types, each a rule named by its type: `Char`, any token; `String`, any tokens; `Natural`, ASCII digits; `Integer`, an optional minus & digits; `Double` & `Float`, @NaN@, or signed @Infinity@ diff --git a/distributors-grammar/src/Control/Lens/Grammar/Analysis.hs b/distributors-grammar/src/Control/Lens/Grammar/Analysis.hs index 61fc2ea6..81b3a58a 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/Analysis.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/Analysis.hs @@ -70,6 +70,7 @@ foldRegEx tok nonterm = go KleeneStar x -> starK (go x) KleeneOpt x -> optK (go x) KleenePlus x -> plusK (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)) @@ -219,6 +220,7 @@ follows bnf = go (falseP <$ rules) NonTerminal name -> Map.singleton name after KleeneStar x -> followed (again x) x KleenePlus x -> followed (again x) x + Backtracking x -> followed after x KleeneOpt x -> followed after x RegExam (Alternate x y zs) -> Map.unionsWith (>|<) (map (followed after) (x : y : zs)) _ -> Map.empty @@ -237,7 +239,9 @@ that alternatives start with distinct tokens & that repetitions 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 `RegEx` doesn't record @try@, so conflicts resolved by it are reported. +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] @@ -266,6 +270,7 @@ ll1Conflicts bnf = 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 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) @@ -279,21 +284,27 @@ ll1Conflicts bnf = repetition x = [ conflict LL1NullableRepetition falseP | nullable x ] <> [ conflict LL1FirstFollow toks - | toks <- overlapping (atoms x >&< guardNext after) ] + | not (tried x) + , toks <- overlapping (atoms x >&< guardNext after) ] -- an alternative, & one after it alternation a b = [ conflict LL1FirstFirst toks - | toks <- overlapping (atoms a >&< atoms b) ] + | 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) + | 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, diff --git a/distributors-grammar/src/Control/Lens/Grammar/BackusNaur.hs b/distributors-grammar/src/Control/Lens/Grammar/BackusNaur.hs index 06dc655b..bec49290 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/BackusNaur.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/BackusNaur.hs @@ -106,19 +106,19 @@ class Tried p where try = id {- | The `Alternator`s of `terminal` symbols, `Tokenized` combinators -& `tokenClass`es, which run @Control.Lens.Grammar.RegGrammar@s. -} +& `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 are `Tried`, -& run `Grammar`s. -} +{- | The `RegGrammatical` `BackusNaurForm`s, which run `Grammar`s. -} type Grammatical token p = ( RegGrammatical token p , forall x y. BackusNaurForm (p x y) - , forall x y. Tried (p x y) ) :: Constraint {- | The `Grammatical` `Filtrator`s, `MonadPlus`es & `MonadFail`s, diff --git a/distributors-grammar/src/Control/Lens/Grammar/Machine.hs b/distributors-grammar/src/Control/Lens/Grammar/Machine.hs index 289b5477..f3e93db1 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/Machine.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/Machine.hs @@ -123,6 +123,7 @@ transducer (Bnf start rules) = Transducer KleeneStar _ -> True KleeneOpt _ -> True KleenePlus x -> 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 @@ -208,6 +209,7 @@ 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 RegExam (OneOf chars) | Set.null chars -> (IntSet.empty, [], nextId, False) | otherwise -> diff --git a/distributors-grammar/src/Control/Lens/Grammar/RegEx.hs b/distributors-grammar/src/Control/Lens/Grammar/RegEx.hs index 4cf12114..39e41f0b 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/RegEx.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/RegEx.hs @@ -69,6 +69,8 @@ data RegEx token | KleeneStar (RegEx token) | KleeneOpt (RegEx token) | KleenePlus (RegEx token) + -- | A pattern to backtrack from, by `try`, whose language is its own. + | Backtracking (RegEx token) | RegExam (TokenExam token (RegEx token)) @@ -128,6 +130,7 @@ instance (Categorized token, HasTrie token) , kleeneStarTrie :: RegEx token :->: b , kleeneOptTrie :: RegEx token :->: b , kleenePlusTrie :: RegEx token :->: b + , backtrackingTrie :: RegEx token :->: b , oneOfTrie :: [token] :->: b , notOneOfTrie :: ([token], Either Int [Int]) :->: b } @@ -139,6 +142,7 @@ instance (Categorized token, HasTrie token) , kleeneStarTrie = trie (f . starK) , kleeneOptTrie = trie (f . optK) , kleenePlusTrie = trie (f . plusK) + , backtrackingTrie = trie (f . try) , oneOfTrie = trie (f . oneOf) , notOneOfTrie = trie (f . testNotOneOf) } @@ -149,6 +153,7 @@ instance (Categorized token, HasTrie token) KleeneStar x -> untrie (kleeneStarTrie rex) x KleenePlus x -> untrie (kleenePlusTrie rex) x KleeneOpt x -> untrie (kleeneOptTrie rex) 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)) @@ -164,6 +169,7 @@ instance (Categorized token, HasTrie token) , first' KleeneStar <$> enumerate (kleeneStarTrie rex) , first' KleeneOpt <$> enumerate (kleeneOptTrie rex) , first' KleenePlus <$> enumerate (kleenePlusTrie rex) + , first' Backtracking <$> enumerate (backtrackingTrie rex) , first' (RegExam . OneOf . Set.fromList) <$> enumerate (oneOfTrie rex) , first' testNotOneOf <$> enumerate (notOneOfTrie rex) ] @@ -339,6 +345,7 @@ diffB prefix (Bnf start rules) = 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 RegExam (OneOf chars) -> if x `elem` chars then mempty else falseP @@ -358,6 +365,7 @@ diffB prefix (Bnf start rules) = SeqEmpty -> True KleeneStar _ -> True KleeneOpt _ -> True + Backtracking y -> ν y KleenePlus y -> ν y Sequence y1 y2 ys -> all ν (y1 : y2 : ys) RegExam (Alternate y1 y2 ys) -> any ν (y1 : y2 : ys) @@ -379,8 +387,14 @@ instance (Ord rule, NonTerminalSymbol rule) -- | `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` doesn't record `try`, for now. -instance Tried (RegEx token) +-- | 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 @@ -482,9 +496,9 @@ Like other regular expression languages, they support character classes. >>> toList (oneOf "abc" :: RegEx Char) -"[abc]" +"[a-c]" >>> toList (notOneOf "abc" :: RegEx Char) -"[^abc]" +"[^a-c]" The character classes are used for failure, matching no character or string, as well as the wildcard, matching any single character. @@ -509,15 +523,15 @@ they can combine characters' `tokenClass`es using `BooleanAlgebra` combinators. >>> toList (tokenClass (notOneOf "abc" >&< notOneOf "xyz") :: RegEx Char) -"[^abcxyz]" +"[^a-cx-z]" >>> toList (tokenClass (oneOf "abcxyz" >&< notOneOf "xyz") :: RegEx Char) -"[abc]" +"[a-c]" >>> toList (tokenClass (notOneOf "#$%" >&< notAsIn Control) :: RegEx Char) -"[^#$%\\P{Cc}]" +"[^#-%\\P{Cc}]" >>> toList (tokenClass (allP notAsIn [MathSymbol, Control]) :: RegEx Char) "\\P{Sm|Cc}" >>> toList (tokenClass (notP (oneOf "xyz")) :: RegEx Char) -"[^xyz]" +"[^x-z]" Ill-formed regular expression strings normalize to failure. @@ -527,15 +541,18 @@ Ill-formed regular expression strings normalize to failure. >>> putStringLn (regbnfG (RegEx Char)) {start} = \q{regex} {alternate} = \q{sequence}(\|\q{sequence})* -{atom} = \\q\q{nonterminal}|\q{class}|\(\q{regex}\) +{atom} = \\q\q{nonterminal}|\\t\{\q{regex}\}|\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}*\] +{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})? {expression} = \q{atom}\?|\q{atom}\*|\q{atom}\+|\q{atom} {nonterminal} = \{\q{char}*\} {regex} = \q{alternate} @@ -569,6 +586,7 @@ regexGrammar = ruleRec "regex" altG atomG rex = rule "atom" $ orP [ _NonTerminal >? terminal "\\q" >* nonterminalG + , _Backtracking >? terminal "\\t{" >* rex *< terminal "}" , _RegExam >? classG , terminal "(" >* rex *< terminal ")" ] @@ -619,30 +637,75 @@ regexGrammar = ruleRec "regex" altG classOneOfG = rule "class-one-of" $ orP [ onlyOne charG - , terminal "[" >* (listed ~< manyP charG) *< terminal "]" + , terminal "[" >* rangedG *< terminal "]" ] classNotOneOfG = rule "class-not-one-of" $ orP [ asEmpty >*< classCatG - , terminal "[^" >* (listed ~< manyP charG) >*< + , 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 = rule "char" $ - tokenClass (notOneOf charsReserved >&< notAsIn Control) - >|< terminal "\\" >* charEscapedG - where - charEscapedG = rule "char-escaped" $ - oneOf charsReserved >|< charControlG +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 = "()*+?[\\]^{|}" - 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 = rule "char-control" $ orP +charControlG :: Grammatical Char p => p Char Char +charControlG = rule "char-control" $ orP [ only '\NUL' >? terminal "NUL" , only '\SOH' >? terminal "SOH" , only '\STX' >? terminal "STX" @@ -753,15 +816,18 @@ But they also support `BackusNaurForm` `rule`s and `ruleRec`s. >>> putStringLn (regbnfG (type (Bnf (RegEx Char)))) {start} = \q{regbnf} {alternate} = \q{sequence}(\|\q{sequence})* -{atom} = \\q\q{nonterminal}|\q{class}|\(\q{regex}\) +{atom} = \\q\q{nonterminal}|\\t\{\q{regex}\}|\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}*\] +{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})? {expression} = \q{atom}\?|\q{atom}\*|\q{atom}\+|\q{atom} {nonterminal} = \{\q{char}*\} {regbnf} = \{start\} = \q{regex}(\LF\q{nonterminal} = \q{regex})* diff --git a/distributors-grammar/test/Examples/RegString.hs b/distributors-grammar/test/Examples/RegString.hs index c4d2e06b..07cc73cd 100644 --- a/distributors-grammar/test/Examples/RegString.hs +++ b/distributors-grammar/test/Examples/RegString.hs @@ -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/Main.hs b/distributors-grammar/test/Main.hs index efda25fe..9ece5fa8 100644 --- a/distributors-grammar/test/Main.hs +++ b/distributors-grammar/test/Main.hs @@ -6,6 +6,8 @@ import Data.Bifunctor.Joker (Joker (..)) import Control.Monad (when) 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 (..)) @@ -47,6 +49,29 @@ main = hspec $ do describe "class runners, at Arith's Grammar" classRunnerTests describe "ReadPrec & Predicate" readPrecTests describe "base types" baseProperties + describe "RegEx ranges & try" regexRangeTryTests + +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 "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` [] readPrecTests :: Spec readPrecTests = do diff --git a/distributors-grammar/test/Properties/Base.hs b/distributors-grammar/test/Properties/Base.hs index bf2f4e60..ef1651e4 100644 --- a/distributors-grammar/test/Properties/Base.hs +++ b/distributors-grammar/test/Properties/Base.hs @@ -63,5 +63,5 @@ baseProperties = do it "Integer" $ ll1Conflicts (regbnfG @Char Integer) `shouldBe` [] it "Double" $ ll1Conflicts (regbnfG @Char Double) `shouldBe` [] describe "regular expressions" $ do - it "Natural" $ toList (regexG @Char Natural) `shouldBe` "[0123456789]+" - it "Integer" $ toList (regexG @Char Integer) `shouldBe` "-?[0123456789]+" + it "Natural" $ toList (regexG @Char Natural) `shouldBe` "[0-9]+" + it "Integer" $ toList (regexG @Char Integer) `shouldBe` "-?[0-9]+" diff --git a/distributors-json/src/Control/Lens/Grammar/TypeScript.hs b/distributors-json/src/Control/Lens/Grammar/TypeScript.hs index 30088469..e51d71e9 100644 --- a/distributors-json/src/Control/Lens/Grammar/TypeScript.hs +++ b/distributors-json/src/Control/Lens/Grammar/TypeScript.hs @@ -1306,6 +1306,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 From ead7a7003eaba908591d4379641cb7a5a213db46 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Fri, 13 Nov 2026 20:57:41 -0800 Subject: [PATCH 14/51] Rho calculus grammars, in the paper's & an ASCII notation Co-Authored-By: Claude Opus 5.5 --- .../distributors-grammar.cabal | 1 + distributors-grammar/test/Examples/Rho.hs | 146 ++++++++++++++++++ distributors-grammar/test/Main.hs | 3 + 3 files changed, 150 insertions(+) create mode 100644 distributors-grammar/test/Examples/Rho.hs diff --git a/distributors-grammar/distributors-grammar.cabal b/distributors-grammar/distributors-grammar.cabal index 8dca6ecb..958d9928 100644 --- a/distributors-grammar/distributors-grammar.cabal +++ b/distributors-grammar/distributors-grammar.cabal @@ -175,6 +175,7 @@ test-suite test Examples.Lambda Examples.LenVec Examples.RegString + Examples.Rho Examples.SemVer Examples.SExpr Properties.Base 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/Main.hs b/distributors-grammar/test/Main.hs index 9ece5fa8..80660533 100644 --- a/distributors-grammar/test/Main.hs +++ b/distributors-grammar/test/Main.hs @@ -22,6 +22,7 @@ import Examples.Json import Examples.Lambda import Examples.LenVec import Examples.RegString +import Examples.Rho import Examples.SemVer import Examples.SExpr import Properties.Base @@ -42,6 +43,8 @@ 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 From 9f5eadee4156bd67e0a2201c8025cb39cc2dcbf6 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Fri, 13 Nov 2026 21:03:20 -0800 Subject: [PATCH 15/51] Json example's character class by complement Co-Authored-By: Claude Opus 5.5 --- distributors-grammar/test/Examples/Json.hs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/distributors-grammar/test/Examples/Json.hs b/distributors-grammar/test/Examples/Json.hs index 451503ac..423ddf28 100644 --- a/distributors-grammar/test/Examples/Json.hs +++ b/distributors-grammar/test/Examples/Json.hs @@ -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' From 710874d679df0cbded597e2ec68da81116b7f459 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Fri, 13 Nov 2026 21:21:20 -0800 Subject: [PATCH 16/51] RegEx quantifiers, by timesK & timesP Co-Authored-By: Claude Opus 5.5 --- distributors-core/CHANGELOG.md | 5 ++ .../src/Control/Lens/Prismoid.hs | 15 +----- .../src/Data/Monoid/Disjunctive.hs | 23 ++++++++++ .../src/Data/Profunctor/Distributor.hs | 30 ++++++++++++ distributors-grammar/CHANGELOG.md | 4 ++ .../src/Control/Lens/Grammar/Analysis.hs | 10 ++++ .../src/Control/Lens/Grammar/Machine.hs | 16 +++++++ .../src/Control/Lens/Grammar/RegEx.hs | 46 ++++++++++++++++++- .../src/Data/Profunctor/Grammar.hs | 1 + distributors-grammar/test/Main.hs | 37 ++++++++++++++- 10 files changed, 171 insertions(+), 16 deletions(-) diff --git a/distributors-core/CHANGELOG.md b/distributors-core/CHANGELOG.md index f4e9792e..8787f286 100644 --- a/distributors-core/CHANGELOG.md +++ b/distributors-core/CHANGELOG.md @@ -4,6 +4,11 @@ ### New APIs +- `timesK`, a `KleeneStarAlgebra` method, & `timesP`, an `Alternator` + method, repeat between some numbers of times, @x{lo,hi}@ or @x{lo,}@, + defaulting to their unfoldings, so static `Alternator`s & Kleene algebras + may keep counts. `inRange`, & so `exactly`, `atLeast` & `atMost`, are + `timesP`. - More `DisjunctiveMonoid` instances: every `Alternative` of the dependencies, `base`, `containers`, `vector`, `transformers`, `free`, `lens` & `witherable`, by `empty` & `<|>`, now with lists, `Seq`s, diff --git a/distributors-core/src/Control/Lens/Prismoid.hs b/distributors-core/src/Control/Lens/Prismoid.hs index f3715ed7..1e89a101 100644 --- a/distributors-core/src/Control/Lens/Prismoid.hs +++ b/distributors-core/src/Control/Lens/Prismoid.hs @@ -42,7 +42,7 @@ module Control.Lens.Prismoid import Control.Applicative import Control.Monad (void) -import Data.Maybe (fromMaybe, isJust) +import Data.Maybe (fromMaybe) import Control.Lens import Control.Lens.Internal.Profunctor import Control.Lens.PartialIso @@ -255,18 +255,7 @@ It never matches where @lo > hi@. ["12","123"] -} inRange :: Int -> Maybe Int -> Prismoid [a] [b] a b -inRange lo hi = rmap sequenceA . go lo hi - where - go :: Alternator p => Int -> Maybe Int -> p a b -> p [a] [b] - go l h p - | maybe False (l >) h = empty - | l > 1 || (l == 1 && isJust h) = p >:< go (l - 1) (subtract 1 <$> h) p - | l == 1 = someP p - | otherwise = case h of - Nothing -> manyP p - Just m - | m <= 0 -> eotList . swapped >~ empty >+< oneP - | otherwise -> eotList . swapped >~ p >*< go 0 (Just (m - 1)) p >+< oneP +inRange lo hi = rmap sequenceA . timesP lo hi {- | One or zero with default. -} opted :: APrism a b () () -> Prismoid a b a b diff --git a/distributors-core/src/Data/Monoid/Disjunctive.hs b/distributors-core/src/Data/Monoid/Disjunctive.hs index 0caab65b..af266924 100644 --- a/distributors-core/src/Data/Monoid/Disjunctive.hs +++ b/distributors-core/src/Data/Monoid/Disjunctive.hs @@ -66,6 +66,7 @@ import Control.Monad.Trans.Writer.Lazy qualified as LazyW import Control.Monad.Trans.Writer.Strict qualified as StrictW import Data.Functor.Reverse (Reverse) import Data.Bits (Bits (..)) +import Data.Maybe (isJust) import Data.Int (Int8, Int16, Int32, Int64) import Data.IntMap (IntMap) import Data.IntSet (IntSet) @@ -177,6 +178,28 @@ class (Monoid k, DisjunctiveMonoid k) => KleeneStarAlgebra k where plusK x = x <> starK x optK x = mempty >|< x + {- | Between some numbers of times, inclusive, at least a lower bound, + & at most an upper bound, if there's one, like a regular expression's + @x{lo,hi}@, or @x{lo,}@; never where @lo > hi@. + + > prop> timesK 0 Nothing = starK + > prop> timesK 1 Nothing = plusK + > prop> timesK 0 (Just 1) = optK + > prop> timesK n (Just n) x = mconcat (replicate n x) + > prop> timesK (n + 1) hi x = x <> timesK n (subtract 1 <$> hi) x + -} + timesK :: Int -> Maybe Int -> k -> k + timesK lo hi x + | maybe False (lo >) hi = falseP + | lo > 1 || (lo == 1 && isJust hi) = + x <> timesK (lo - 1) (subtract 1 <$> hi) x + | lo == 1 = plusK x + | otherwise = case hi of + Nothing -> starK x + Just m + | m <= 0 -> mempty + | otherwise -> optK (x <> timesK 0 (Just (m - 1)) x) + --instances instance DisjunctiveMonoid Bool where falseP = False diff --git a/distributors-core/src/Data/Profunctor/Distributor.hs b/distributors-core/src/Data/Profunctor/Distributor.hs index 341fb694..c41c9932 100644 --- a/distributors-core/src/Data/Profunctor/Distributor.hs +++ b/distributors-core/src/Data/Profunctor/Distributor.hs @@ -37,6 +37,7 @@ import Data.Profunctor.Monad import Data.Profunctor.Monoidal import Data.Profunctor.Yoneda import Data.Profunctor.Monoidal.Cocartesian +import Data.Maybe (isJust) -- $setup -- >>> import Data.Bifunctor.Joker (Joker (..)) @@ -193,18 +194,47 @@ class (Distributor p, CocartesianChoice p, forall x. Alternative (p x)) manyTillP :: p a b -> p [a] [b] -> p [a] [b] manyTillP p q = let r = q >|< p >:< r in r + {- | Between some numbers of times, inclusive, at least a lower bound, + & at most an upper bound, if there's one, like a regular expression's + @{lo,hi}@, or @{lo,}@. It takes the mandatory times first, then, + unbounded, `someP` or `manyP`, or, bounded, the optional times, + trying more first. It never matches where @lo > hi@. + + It mirrors a `KleeneStarAlgebra`'s `timesK`, so that a static + `Alternator` may keep its counts, rather than unfolding them. + + > prop> timesP 0 Nothing = manyP + > prop> timesP 1 Nothing = someP + > prop> timesP n (Just n) = replicateP n + -} + timesP :: Int -> Maybe Int -> p a b -> p [a] [b] + timesP lo hi p + | maybe False (lo >) hi = empty + | lo > 1 || (lo == 1 && isJust hi) = + p >:< timesP (lo - 1) (subtract 1 <$> hi) p + | lo == 1 = someP p + | otherwise = case hi of + Nothing -> manyP p + Just m + | m <= 0 -> eotList . swapped >~ empty >+< oneP + | otherwise -> + eotList . swapped >~ p >*< timesP 0 (Just (m - 1)) p >+< oneP + instance (Alternator p, Applicative f) => Alternator (WrappedPafb f p) where someP (WrapPafb x) = WrapPafb (rmap sequenceA (someP x)) optionP def (WrapPafb x) = WrapPafb (optionP (prism pure pure . def) x) + timesP lo hi (WrapPafb x) = WrapPafb (rmap sequenceA (timesP lo hi x)) instance Alternator p => Alternator (Coyoneda p) where someP = proreturn . someP . proextract optionP def = proreturn . optionP def . proextract manyTillP p q = proreturn (manyTillP (proextract p) (proextract q)) + timesP lo hi = proreturn . timesP lo hi . proextract instance Alternator p => Alternator (Yoneda p) where someP = proreturn . someP . proextract optionP def = proreturn . optionP def . proextract manyTillP p q = proreturn (manyTillP (proextract p) (proextract q)) + timesP lo hi = proreturn . timesP lo hi . proextract instance Alternative f => Alternator (Joker f) where someP (Joker x) = Joker (some x) optionP def (Joker x) = diff --git a/distributors-grammar/CHANGELOG.md b/distributors-grammar/CHANGELOG.md index 58fa575a..71574b4d 100644 --- a/distributors-grammar/CHANGELOG.md +++ b/distributors-grammar/CHANGELOG.md @@ -2,6 +2,10 @@ ## Unreleased +- `RegEx` has counts, a `KleeneTimes` constructor, normalized by `timesK`, + 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`. diff --git a/distributors-grammar/src/Control/Lens/Grammar/Analysis.hs b/distributors-grammar/src/Control/Lens/Grammar/Analysis.hs index 81b3a58a..acf6d674 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/Analysis.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/Analysis.hs @@ -70,6 +70,7 @@ foldRegEx tok nonterm = go KleeneStar x -> starK (go x) KleeneOpt x -> optK (go x) KleenePlus x -> plusK (go x) + KleeneTimes lo hi x -> timesK lo hi (go x) Backtracking x -> go x RegExam (OneOf toks) -> tok (TokenClass (OneOf toks)) RegExam (NotOneOf toks test) -> tok (TokenClass (NotOneOf toks test)) @@ -221,6 +222,7 @@ follows bnf = go (falseP <$ rules) 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 @@ -271,6 +273,7 @@ ll1Conflicts bnf = 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) @@ -337,3 +340,10 @@ data LL1ConflictSort | 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/Machine.hs b/distributors-grammar/src/Control/Lens/Grammar/Machine.hs index f3e93db1..99331c24 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/Machine.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/Machine.hs @@ -123,6 +123,7 @@ 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 @@ -210,6 +211,8 @@ transducer (Bnf start rules) = Transducer 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 -> @@ -563,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/RegEx.hs b/distributors-grammar/src/Control/Lens/Grammar/RegEx.hs index 39e41f0b..5b1f171b 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/RegEx.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/RegEx.hs @@ -69,6 +69,12 @@ 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 `timesK`: 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)) @@ -120,6 +126,17 @@ instance Categorized token => KleeneStarAlgebra (RegEx token) where plusK (RegExam exam) | isFailExam exam = falseP plusK SeqEmpty = mempty plusK rex = KleenePlus rex + timesK 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 @@ -130,6 +147,7 @@ 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 @@ -142,6 +160,7 @@ instance (Categorized token, HasTrie token) , kleeneStarTrie = trie (f . starK) , kleeneOptTrie = trie (f . optK) , kleenePlusTrie = trie (f . plusK) + , kleeneTimesTrie = trie (f . \((lo, hi), x) -> timesK lo hi x) , backtrackingTrie = trie (f . try) , oneOfTrie = trie (f . oneOf) , notOneOfTrie = trie (f . testNotOneOf) @@ -153,6 +172,7 @@ 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)) -> @@ -169,6 +189,8 @@ 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) @@ -347,6 +369,8 @@ diffB prefix (Bnf start rules) = KleeneOpt y -> diff1B x y Backtracking y -> diff1B x y KleenePlus y -> diff1B x y <> starK y + KleeneTimes lo hi y -> + diff1B x y <> timesK (lo - 1) (subtract 1 <$> hi) y RegExam (OneOf chars) -> if x `elem` chars then mempty else falseP RegExam (NotOneOf chars (AndAsIn cat)) -> @@ -367,6 +391,7 @@ diffB prefix (Bnf start rules) = 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) @@ -542,6 +567,7 @@ Ill-formed regular expression strings normalize to failure. {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} = 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 @@ -553,7 +579,8 @@ Ill-formed regular expression strings normalize to failure. {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})? -{expression} = \q{atom}\?|\q{atom}\*|\q{atom}\+|\q{atom} +{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}* @@ -581,9 +608,22 @@ regexGrammar = ruleRec "regex" altG [ _KleeneOpt >? atomG rex *< terminal "?" , _KleeneStar >? atomG rex *< terminal "*" , _KleenePlus >? atomG rex *< terminal "+" + , _Times >? atomG rex >*< terminal "{" >* boundsG *< terminal "}" , atomG rex ] + -- improper, normalizing counts by `timesK` + _Times = prism' (\(x, (lo, hi)) -> timesK 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" $ iso show read >~ someP (oneOf ['0' .. '9']) + atomG rex = rule "atom" $ orP [ _NonTerminal >? terminal "\\q" >* nonterminalG , _Backtracking >? terminal "\\t{" >* rex *< terminal "}" @@ -817,6 +857,7 @@ But they also support `BackusNaurForm` `rule`s and `ruleRec`s. {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} = 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 @@ -828,7 +869,8 @@ But they also support `BackusNaurForm` `rule`s and `ruleRec`s. {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})? -{expression} = \q{atom}\?|\q{atom}\*|\q{atom}\+|\q{atom} +{count} = [0-9]+ +{expression} = \q{atom}\?|\q{atom}\*|\q{atom}\+|\q{atom}\{\q{bounds}\}|\q{atom} {nonterminal} = \{\q{char}*\} {regbnf} = \{start\} = \q{regex}(\LF\q{nonterminal} = \q{regex})* {regex} = \q{alternate} diff --git a/distributors-grammar/src/Data/Profunctor/Grammar.hs b/distributors-grammar/src/Data/Profunctor/Grammar.hs index dd5ad179..2ea554e4 100644 --- a/distributors-grammar/src/Data/Profunctor/Grammar.hs +++ b/distributors-grammar/src/Data/Profunctor/Grammar.hs @@ -236,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) + timesP lo hi (Grammor rex) = Grammor (timesK lo hi rex) instance Tokenized token k => Tokenized token (Grammor k a b) where anyToken = Grammor anyToken token = Grammor . token diff --git a/distributors-grammar/test/Main.hs b/distributors-grammar/test/Main.hs index 80660533..e5f23da6 100644 --- a/distributors-grammar/test/Main.hs +++ b/distributors-grammar/test/Main.hs @@ -12,7 +12,8 @@ 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 @@ -53,6 +54,7 @@ main = hspec $ do describe "ReadPrec & Predicate" readPrecTests describe "base types" baseProperties describe "RegEx ranges & try" regexRangeTryTests + describe "RegEx quantifiers" regexQuantifierTests regexRangeTryTests :: Spec regexRangeTryTests = do @@ -76,6 +78,39 @@ regexRangeTryTests = do `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` timesK 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] + prop "timesK n (Just n) x matches as n times x" $ \(x :: RegEx Char) -> + forAll (choose (0, 3)) $ \n -> forAll (listOf (elements "ab")) $ \w -> + (w =~ timesK 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 = timesK 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) -> From b1690c1e126cd0af64495af628f9c050530b79b7 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Fri, 13 Nov 2026 21:26:39 -0800 Subject: [PATCH 17/51] Counts are those n >= 0 within bounds, alike across instances Co-Authored-By: Claude Opus 5.5 --- distributors-core/src/Control/Lens/Prismoid.hs | 4 ++-- distributors-core/src/Data/Monoid/Disjunctive.hs | 11 ++++++++--- distributors-core/src/Data/Profunctor/Distributor.hs | 7 +++++-- distributors-grammar/test/Main.hs | 8 ++++++++ 4 files changed, 23 insertions(+), 7 deletions(-) diff --git a/distributors-core/src/Control/Lens/Prismoid.hs b/distributors-core/src/Control/Lens/Prismoid.hs index 1e89a101..534e15ae 100644 --- a/distributors-core/src/Control/Lens/Prismoid.hs +++ b/distributors-core/src/Control/Lens/Prismoid.hs @@ -204,7 +204,7 @@ withPrismoid pat k = {- | Exactly some number of times, or separated by `sepBy`. > prop> exactly n = inRange n (Just n) -> prop> exactly n >?* p = replicateP n p +> prop> exactly n >?* p = replicateP n p, for @n >= 0@ -} exactly :: Int -> Prismoid [a] [b] a b exactly n = inRange n (Just n) @@ -246,7 +246,7 @@ atMost n = inRange 0 (Just n) It takes the mandatory times first, then, unbounded, the `Alternator`'s own `someP` or `manyP`, or, bounded, the optional times, trying more first. -It never matches where @lo > hi@. +It never matches where @lo > hi@, nor where @hi@ is negative. >>> let digits lo hi = runJoker (inRange lo hi >?* Joker (satisfy isDigit)) :: ReadP String >>> [ds | (ds, "") <- readP_to_S (digits 2 (Just 3)) "123"] diff --git a/distributors-core/src/Data/Monoid/Disjunctive.hs b/distributors-core/src/Data/Monoid/Disjunctive.hs index af266924..ebffe693 100644 --- a/distributors-core/src/Data/Monoid/Disjunctive.hs +++ b/distributors-core/src/Data/Monoid/Disjunctive.hs @@ -180,16 +180,21 @@ class (Monoid k, DisjunctiveMonoid k) => KleeneStarAlgebra k where {- | Between some numbers of times, inclusive, at least a lower bound, & at most an upper bound, if there's one, like a regular expression's - @x{lo,hi}@, or @x{lo,}@; never where @lo > hi@. + @x{lo,hi}@, or @x{lo,}@. Its counts are those @n >= 0@ within its + bounds, so it fails where they're out of order, or all negative, + as regular expression languages reject such quantifiers. > prop> timesK 0 Nothing = starK > prop> timesK 1 Nothing = plusK > prop> timesK 0 (Just 1) = optK - > prop> timesK n (Just n) x = mconcat (replicate n x) - > prop> timesK (n + 1) hi x = x <> timesK n (subtract 1 <$> hi) x + > prop> timesK n (Just n) x = mconcat (replicate n x), for @n >= 0@ + > prop> timesK (n + 1) hi x = x <> timesK n (subtract 1 <$> hi) x, for @n >= 0@ + > prop> timesK (-1) hi = timesK 0 hi + > prop> timesK 0 (Just (-1)) x = falseP -} timesK :: Int -> Maybe Int -> k -> k timesK lo hi x + | lo < 0 = timesK 0 hi x | maybe False (lo >) hi = falseP | lo > 1 || (lo == 1 && isJust hi) = x <> timesK (lo - 1) (subtract 1 <$> hi) x diff --git a/distributors-core/src/Data/Profunctor/Distributor.hs b/distributors-core/src/Data/Profunctor/Distributor.hs index c41c9932..37139d20 100644 --- a/distributors-core/src/Data/Profunctor/Distributor.hs +++ b/distributors-core/src/Data/Profunctor/Distributor.hs @@ -198,17 +198,20 @@ class (Distributor p, CocartesianChoice p, forall x. Alternative (p x)) & at most an upper bound, if there's one, like a regular expression's @{lo,hi}@, or @{lo,}@. It takes the mandatory times first, then, unbounded, `someP` or `manyP`, or, bounded, the optional times, - trying more first. It never matches where @lo > hi@. + trying more first. It never matches where @lo > hi@, + nor where @hi@ is negative, its counts being those @n >= 0@ within + its bounds. It mirrors a `KleeneStarAlgebra`'s `timesK`, so that a static `Alternator` may keep its counts, rather than unfolding them. > prop> timesP 0 Nothing = manyP > prop> timesP 1 Nothing = someP - > prop> timesP n (Just n) = replicateP n + > prop> timesP n (Just n) = replicateP n, for @n >= 0@ -} timesP :: Int -> Maybe Int -> p a b -> p [a] [b] timesP lo hi p + | lo < 0 = timesP 0 hi p | maybe False (lo >) hi = empty | lo > 1 || (lo == 1 && isJust hi) = p >:< timesP (lo - 1) (subtract 1 <$> hi) p diff --git a/distributors-grammar/test/Main.hs b/distributors-grammar/test/Main.hs index e5f23da6..f5b5141a 100644 --- a/distributors-grammar/test/Main.hs +++ b/distributors-grammar/test/Main.hs @@ -104,6 +104,14 @@ regexQuantifierTests = do 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 = timesK 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 "timesK n (Just n) x matches as n times x" $ \(x :: RegEx Char) -> forAll (choose (0, 3)) $ \n -> forAll (listOf (elements "ab")) $ \w -> (w =~ timesK n (Just n) x) === (w =~ mconcat (replicate n x)) From 4d09da1fc517185326ef411c11deeec9f07a5ec8 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Fri, 13 Nov 2026 21:44:08 -0800 Subject: [PATCH 18/51] TokenSets: Char's classes by ranges, of range-set-list Co-Authored-By: Claude Opus 5.5 --- distributors-grammar/CHANGELOG.md | 9 + .../distributors-grammar.cabal | 4 + distributors-grammar/package.yaml | 1 + .../src/Control/Lens/Grammar/Analysis.hs | 4 +- .../src/Control/Lens/Grammar/Machine.hs | 4 +- .../src/Control/Lens/Grammar/RegEx.hs | 56 +++--- .../src/Control/Lens/Grammar/Token.hs | 169 +++++++++++++----- .../src/Data/Profunctor/Grammar/Parsector.hs | 8 +- 8 files changed, 169 insertions(+), 86 deletions(-) diff --git a/distributors-grammar/CHANGELOG.md b/distributors-grammar/CHANGELOG.md index 71574b4d..09da904f 100644 --- a/distributors-grammar/CHANGELOG.md +++ b/distributors-grammar/CHANGELOG.md @@ -2,6 +2,15 @@ ## Unreleased +- `Categorized` has a `TokenSet` type of its tokens' sets, a `Set` by default, + with `tokenMember`, `tokenIntersection` & `tokenDifference`, empty by + `falseP`, unioned by `>|<` & listed by `IsList`; `Char`'s are `Ranges`, + sets of ranges, by + [range-set-list](https://hackage.haskell.org/package/range-set-list), + so huge classes, like `oneOf ['\x20' .. '\x10FFFF']`, intersect, compare & + render by their ranges, not their tokens. Their `Show` & `Read` are a + `Set`'s. Derived `Show` & `Read` instances require `Show (TokenSet token)` + or `Read (TokenSet token)` rather than `Show token` or `Read token`. - `RegEx` has counts, a `KleeneTimes` constructor, normalized by `timesK`, rendered @x{n}@, @x{n,}@ & @x{n,m}@, & parsed so, normalizing; `Grammor`s keep counts, so `exactly`, `atLeast`, `atMost` & `inRange` render by them. diff --git a/distributors-grammar/distributors-grammar.cabal b/distributors-grammar/distributors-grammar.cabal index 958d9928..fdf73db7 100644 --- a/distributors-grammar/distributors-grammar.cabal +++ b/distributors-grammar/distributors-grammar.cabal @@ -89,6 +89,7 @@ library , base >=4.20 && <5 , bifunctors >=5.5 && <6 , containers >=0.6 && <1 + , range-set-list >=0.1.4 && <0.2 , distributors ==0.7.* , lens >=5.0 && <6 , monad-loops >=0.4.3 && <1 @@ -152,6 +153,7 @@ test-suite doctests , base >=4.20 && <5 , bifunctors >=5.5 && <6 , containers >=0.6 && <1 + , range-set-list >=0.1.4 && <0.2 , distributors ==0.7.* , distributors-grammar , doctest-parallel >=0.3 && <1 @@ -231,6 +233,7 @@ test-suite test , base >=4.20 && <5 , bifunctors >=5.5 && <6 , containers >=0.6 && <1 + , range-set-list >=0.1.4 && <0.2 , distributors , distributors-grammar , free >=5.1 && <6 @@ -303,6 +306,7 @@ benchmark core , base >=4.20 && <5 , bifunctors >=5.5 && <6 , containers >=0.6 && <1 + , range-set-list >=0.1.4 && <0.2 , distributors , distributors-grammar , lens >=5.0 && <6 diff --git a/distributors-grammar/package.yaml b/distributors-grammar/package.yaml index ad1143a4..1f57fd4c 100644 --- a/distributors-grammar/package.yaml +++ b/distributors-grammar/package.yaml @@ -22,6 +22,7 @@ dependencies: - base >= 4.20 && < 5 - bifunctors >= 5.5 && < 6 - containers >= 0.6 && < 1 +- range-set-list >= 0.1.4 && < 0.2 - distributors >= 0.7 && < 0.8 - lens >= 5.0 && < 6 - MemoTrie >= 0.6 && < 1 diff --git a/distributors-grammar/src/Control/Lens/Grammar/Analysis.hs b/distributors-grammar/src/Control/Lens/Grammar/Analysis.hs index acf6d674..f97851b2 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/Analysis.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/Analysis.hs @@ -171,7 +171,7 @@ data Guard token = Guard 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)) + (Categorized token, Show (TokenSet token), Show (Categorize token)) => Show (Guard token) instance Categorized token => DisjunctiveMonoid (Guard token) where falseP = Guard False falseP @@ -321,7 +321,7 @@ data LL1Conflict token = LL1Conflict } deriving stock instance Categorized token => Eq (LL1Conflict token) deriving stock instance - (Categorized token, Show token, Show (Categorize token)) + (Categorized token, Show (TokenSet token), Show (Categorize token)) => Show (LL1Conflict token) -- | Sorts of `LL1Conflict`s. diff --git a/distributors-grammar/src/Control/Lens/Grammar/Machine.hs b/distributors-grammar/src/Control/Lens/Grammar/Machine.hs index 99331c24..c09b99ba 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/Machine.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/Machine.hs @@ -97,7 +97,7 @@ A transducer is a form of finite state machine that can be run in various ways like `=~`, `expectNext`, `languageSample`, `parseForest` & `unreachableRules`. -} -transducer :: Bnf (RegEx token) -> Transducer token +transducer :: Categorized token => Bnf (RegEx token) -> Transducer token transducer (Bnf start rules) = Transducer { transducerRelations = IntMap.fromList allStates , transducerRules = Map.fromList @@ -214,7 +214,7 @@ transducer (Bnf start rules) = Transducer -- 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) + | chars == falseP -> (IntSet.empty, [], nextId, False) | otherwise -> ( IntSet.singleton nextId , [(nextId, TransitionTokenClass (TokenClass (OneOf chars)) dests)] diff --git a/distributors-grammar/src/Control/Lens/Grammar/RegEx.hs b/distributors-grammar/src/Control/Lens/Grammar/RegEx.hs index 5b1f171b..56aa16f0 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/RegEx.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/RegEx.hs @@ -40,6 +40,7 @@ import Data.MemoTrie import Data.Monoid.Disjunctive import Data.Profunctor import qualified Data.Set as Set +import qualified Data.RangeSet.Map as RSet import Data.Set (Set) import Data.Maybe (fromMaybe, listToMaybe, mapMaybe) import Data.Profunctor.Distributor @@ -85,10 +86,10 @@ deriving stock instance Generic (RegEx token) deriving stock instance Categorized token => Eq (RegEx token) deriving stock instance Categorized token => Ord (RegEx token) deriving stock instance - (Categorized token, Read token, Read (Categorize token)) + (Categorized token, Read (TokenSet token), Read (Categorize token)) => Read (RegEx token) deriving stock instance - (Categorized token, Show token, Show (Categorize token)) + (Categorized token, Show (TokenSet token), Show (Categorize token)) => Show (RegEx token) instance Categorized token => TerminalSymbol token (RegEx token) where terminal = foldl (\acc t -> acc <> token t) mempty @@ -96,12 +97,11 @@ instance NonTerminalSymbol (RegEx token) where nonTerminal = NonTerminal instance Categorized token => Tokenized token (RegEx token) where anyToken = RegExam anyToken - token a = RegExam (OneOf (Set.singleton a)) - oneOf as = RegExam (OneOf (Set.fromList (toList as))) - notOneOf as = - RegExam (NotOneOf (Set.fromList (toList as)) (AndNotAsIn Set.empty)) - asIn cat = RegExam (NotOneOf Set.empty (AndAsIn cat)) - notAsIn cat = RegExam (NotOneOf Set.empty (AndNotAsIn (Set.singleton cat))) + token = RegExam . token + oneOf = RegExam . oneOf + notOneOf = RegExam . notOneOf + asIn = RegExam . asIn + notAsIn = RegExam . notAsIn instance Categorized token => TokenAlgebra token (RegEx token) where tokenClass = foldTokenClass RegExam instance Categorized token => Monoid (RegEx token) where @@ -111,7 +111,7 @@ instance Categorized token => Semigroup (RegEx token) where rex0 <> rex1 = sequenced (items rex0 <> items rex1) -- | Alternatives are associative, as normalized by `alternated`. instance Categorized token => DisjunctiveMonoid (RegEx token) where - falseP = RegExam (OneOf Set.empty) + falseP = RegExam (OneOf falseP) rex0 >|< rex1 = alternated (alternatives rex0 <> alternatives rex1) instance Categorized token => KleeneStarAlgebra (RegEx token) where optK (RegExam exam) | isFailExam exam = mempty @@ -174,12 +174,12 @@ instance (Categorized token, HasTrie token) 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 (OneOf chars) -> untrie (oneOfTrie rex) (Exts.toList chars) RegExam (NotOneOf chars (AndAsIn cat)) -> - untrie (notOneOfTrie rex) (Set.toList chars, Left (fromEnum cat)) + untrie (notOneOfTrie rex) (Exts.toList chars, Left (fromEnum cat)) RegExam (NotOneOf chars (AndNotAsIn cats)) -> untrie (notOneOfTrie rex) - (Set.toList chars, Right (Set.toList (Set.map fromEnum cats))) + (Exts.toList chars, Right (Set.toList (Set.map fromEnum cats))) RegExam (Alternate x y zs) -> untrie (alternateTrie rex) (x : y : zs) enumerate rex = mconcat [ [(SeqEmpty, seqEmptyTrie rex)] @@ -192,20 +192,20 @@ instance (Categorized token, HasTrie token) , 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' (RegExam . OneOf . Exts.fromList) <$> enumerate (oneOfTrie rex) , first' testNotOneOf <$> enumerate (notOneOfTrie rex) ] testNotOneOf :: Categorized token => ([token], Either Int [Int]) -> RegEx token testNotOneOf (chars, catTest) = RegExam $ NotOneOf - (Set.fromList chars) + (Exts.fromList chars) (either (AndAsIn . toEnum) (AndNotAsIn . Set.map toEnum . Set.fromList) catTest) -- | Whether a token examination fails to match any token. -isFailExam :: TokenExam token alg -> Bool +isFailExam :: Categorized token => TokenExam token alg -> Bool isFailExam = \case - OneOf tokens' -> Set.null tokens' + OneOf tokens' -> tokens' == falseP _ -> False -- | The items of a sequence. @@ -273,9 +273,9 @@ sequenced rexes [] -> Nothing -- | The alternatives of an alternation, with the empty word for an option. -alternatives :: RegEx token -> [RegEx token] +alternatives :: Categorized token => RegEx token -> [RegEx token] alternatives = \case - RegExam (OneOf tokens') | Set.null tokens' -> [] + RegExam (OneOf tokens') | tokens' == falseP -> [] RegExam (Alternate rex0 rex1 rexes) -> rex0 : rex1 : rexes KleeneOpt rex -> alternatives rex <> [SeqEmpty] KleeneStar rex -> [KleenePlus rex, SeqEmpty] @@ -372,12 +372,12 @@ diffB prefix (Bnf start rules) = KleeneTimes lo hi y -> diff1B x y <> timesK (lo - 1) (subtract 1 <$> hi) y RegExam (OneOf chars) -> - if x `elem` chars then mempty else falseP + if tokenMember x chars then mempty else falseP RegExam (NotOneOf chars (AndAsIn cat)) -> - if elem x chars || categorize x /= cat + if tokenMember x chars || categorize x /= cat then falseP else mempty RegExam (NotOneOf chars (AndNotAsIn cats)) -> - if elem x chars || elem (categorize x) cats + if tokenMember x chars || elem (categorize x) cats then falseP else mempty RegExam (Alternate y1 y2 ys) -> anyP (diff1B x) (y1 : y2 : ys) @@ -414,7 +414,7 @@ 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 +instance Categorized token => Tried (RegEx token) where try rex = case rex of Backtracking _ -> rex SeqEmpty -> rex @@ -688,14 +688,12 @@ regexGrammar = ruleRec "regex" altG -- 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" $ + rangedG = iso runsOf (foldr ((>|<) . runOf) falseP) >~ 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 + -- ranges, of the set's own form, are never enumerated + runOf (lo, hi0) = let hi = fromMaybe lo hi0 in + if lo > hi then falseP else Ranges (RSet.singletonRange (lo, hi)) + runsOf (Ranges chars) = concatMap run (RSet.toRangeList chars) -- 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' -> diff --git a/distributors-grammar/src/Control/Lens/Grammar/Token.hs b/distributors-grammar/src/Control/Lens/Grammar/Token.hs index 7f244647..cf01fe76 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/Token.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/Token.hs @@ -15,6 +15,7 @@ module Control.Lens.Grammar.Token , tokens -- * Categorized , Categorized (..) + , Ranges (..) , GeneralCategory (..) -- * TokenAlgebra , TokenAlgebra (..) @@ -37,6 +38,12 @@ import Data.Profunctor.Distributor import Data.Profunctor.Monoidal import Data.Set (Set) import qualified Data.Set as Set +import Data.RangeSet.Map (RSet) +import qualified Data.RangeSet.Map as RSet +import GHC.Exts (IsList (Item)) +import qualified GHC.Exts as Exts +import qualified Text.Read as Read +import Text.Read (readPrec) import GHC.Generics (Generic, Generic1) import Data.Word import Control.Monad.State (StateT, state) @@ -60,19 +67,79 @@ Categorize Char :: * >>> categorize 'a' LowercaseLetter -} -class (Ord token, Ord (Categorize token), Enum (Categorize token)) - => Categorized token where +class + ( Ord token, Ord (Categorize token), Enum (Categorize token) + , Ord (TokenSet token), DisjunctiveMonoid (TokenSet token) + , IsList (TokenSet token), Item (TokenSet token) ~ token + ) => Categorized token where type Categorize token type Categorize token = () categorize :: token -> Categorize token default categorize :: Categorize token ~ () => token -> Categorize token categorize _ = () + + {- | Sets of tokens, a `Set` by default, each set having one form, + so that its `Eq` is its sets' equality; empty by `falseP`, + unioned by `>|<`, & listed by `IsList`, in ascending order. -} + type TokenSet token + type TokenSet token = Set token + {- | Is a token a member of a set? -} + tokenMember :: token -> TokenSet token -> Bool + default tokenMember + :: TokenSet token ~ Set token => token -> TokenSet token -> Bool + tokenMember = Set.member + {- | The tokens of both sets. -} + tokenIntersection :: TokenSet token -> TokenSet token -> TokenSet token + default tokenIntersection + :: TokenSet token ~ Set token + => TokenSet token -> TokenSet token -> TokenSet token + tokenIntersection = Set.intersection + {- | The tokens of a set, but not of another. -} + tokenDifference :: TokenSet token -> TokenSet token -> TokenSet token + default tokenDifference + :: TokenSet token ~ Set token + => TokenSet token -> TokenSet token -> TokenSet token + tokenDifference = Set.difference instance Categorized Char where type Categorize Char = GeneralCategory categorize = generalCategory + type TokenSet Char = Ranges Char + tokenMember x (Ranges xs) = RSet.member x xs + tokenIntersection (Ranges xs) (Ranges ys) = Ranges (RSet.intersection xs ys) + tokenDifference (Ranges xs) (Ranges ys) = Ranges (RSet.difference xs ys) instance Categorized Word8 instance Categorized () +{- | Sets of enumerable tokens, by their disjoint ranges, of +[range-set-list](https://hackage.haskell.org/package/range-set-list), +each set having one form, so that its `Eq` is its sets' equality; +a `BooleanAlgebra` of bounded tokens. They `Show` & `Read` as a `Set` +does, by their tokens' list. +-} +newtype Ranges token = Ranges (RSet token) + deriving newtype (Eq, Ord) +instance (Ord token, Enum token) => IsList (Ranges token) where + type Item (Ranges token) = token + fromList = Ranges . RSet.fromList + toList (Ranges xs) = RSet.toList xs +instance AsEmpty (Ranges token) where + _Empty = nearly (Ranges RSet.empty) (\(Ranges xs) -> RSet.null xs) +instance (Ord token, Enum token) => DisjunctiveMonoid (Ranges token) where + falseP = Ranges RSet.empty + Ranges xs >|< Ranges ys = Ranges (RSet.union xs ys) +instance (Ord token, Enum token, Bounded token) + => BooleanAlgebra (Ranges token) where + trueP = Ranges RSet.full + notP (Ranges xs) = Ranges (RSet.complement xs) + Ranges xs >&< Ranges ys = Ranges (RSet.intersection xs ys) +instance (Ord token, Enum token, Show token) => Show (Ranges token) where + showsPrec d xs = showParen (d > 10) $ + showString "fromList " . shows (Exts.toList xs) +instance (Ord token, Enum token, Read token) => Read (Ranges token) where + readPrec = Read.parens $ ReadPrec.prec 10 $ do + Read.Ident "fromList" <- Read.lexP + Exts.fromList <$> ReadPrec.step readPrec + {- | `Tokenized` combinators for constructing lexical tokens. -} class Categorized token => Tokenized token p | p -> token where {- | Any single token. -} @@ -194,25 +261,25 @@ of an algebra, whose fixed point is t'TokenClass'. Both t'TokenClass'es & `Control.Lens.Grammar.RegEx.RegEx`pressions are algebras over it. -} data TokenExam token alg - = OneOf (Set token) - | NotOneOf (Set token) (CategoryTest token) + = OneOf (TokenSet token) + | NotOneOf (TokenSet token) (CategoryTest token) {- | Two or more alternatives, none of them alternatives, in the order they're written. -} | Alternate alg alg [alg] -failExam :: TokenExam token alg -failExam = OneOf Set.empty +failExam :: Categorized token => TokenExam token alg +failExam = OneOf falseP -passExam :: TokenExam token alg -passExam = NotOneOf Set.empty (AndNotAsIn Set.empty) +passExam :: Categorized token => TokenExam token alg +passExam = NotOneOf falseP (AndNotAsIn Set.empty) -isFailExam :: TokenExam token alg -> Bool -isFailExam (OneOf xs) = Set.null xs +isFailExam :: Categorized token => TokenExam token alg -> Bool +isFailExam (OneOf xs) = xs == falseP isFailExam _ = False -isPassExam :: TokenExam token alg -> Bool -isPassExam (NotOneOf xs (AndNotAsIn ys)) = Set.null xs && Set.null ys +isPassExam :: Categorized token => TokenExam token alg -> Bool +isPassExam (NotOneOf xs (AndNotAsIn ys)) = xs == falseP && Set.null ys isPassExam _ = False -- | The alternatives of an examination of t'TokenClass'es. @@ -240,7 +307,7 @@ alternatives exams where unionOneOfs xs = case [tokens' | OneOf tokens' <- xs] of [] -> xs - tokenss -> placeFirst (OneOf (Set.unions tokenss)) xs + tokenss -> placeFirst (OneOf (foldr (>|<) falseP tokenss)) xs placeFirst union = \case OneOf _ : rest -> union : [x | x <- rest, not (isOneOf x)] x : rest -> x : placeFirst union rest @@ -300,11 +367,11 @@ class Tokenized token p => TokenAlgebra token p where -- Sets of tokens are tested by `Set.member`, logarithmically, -- rather than by `oneOf`'s & `notOneOf`'s `Foldable`, linearly. tokenClass = foldTokenClass $ \case - OneOf chars -> satisfy (`Set.member` chars) + OneOf chars -> satisfy (`tokenMember` chars) NotOneOf chars (AndAsIn cat) -> - satisfy ((`Set.notMember` chars) >&< asIn cat) + satisfy (notP (`tokenMember` chars) >&< asIn cat) NotOneOf chars (AndNotAsIn cats) -> - satisfy ((`Set.notMember` chars) >&< allP notAsIn cats) + satisfy (notP (`tokenMember` chars) >&< allP notAsIn cats) Alternate p q ps -> foldr1 (>|<) (p : q : ps) deriving stock instance Generic (TokenExam token alg) @@ -312,10 +379,10 @@ deriving stock instance Generic1 (TokenExam token) deriving stock instance Generic (TokenClass token) deriving stock instance Generic (CategoryTest token) deriving stock instance - (Categorized token, Read token, Read (Categorize token)) + (Categorized token, Read (TokenSet token), Read (Categorize token)) => Read (TokenClass token) deriving stock instance - (Categorized token, Show token, Show (Categorize token)) + (Categorized token, Show (TokenSet token), Show (Categorize token)) => Show (TokenClass token) deriving newtype instance Categorized token => Eq (TokenClass token) deriving newtype instance Categorized token => Ord (TokenClass token) @@ -331,11 +398,11 @@ instance Categorized token tokenClass (TokenClass exam) = exam instance Categorized token => TokenAlgebra token (token -> Bool) where tokenClass = foldTokenClass . flip $ \x -> \case - OneOf xs -> Set.member x xs + OneOf xs -> tokenMember x xs NotOneOf xs (AndAsIn y) -> - Set.notMember x xs && categorize x == y + not (tokenMember x xs) && categorize x == y NotOneOf xs (AndNotAsIn ys) -> - Set.notMember x xs && Set.notMember (categorize x) ys + not (tokenMember x xs) && Set.notMember (categorize x) ys Alternate p q ps -> any ($ x) (p : q : ps) instance TokenAlgebra token (f token) => TokenAlgebra token (Joker f token token) where @@ -348,33 +415,33 @@ 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 + OneOf xs -> oneOf (Exts.toList xs) NotOneOf xs (AndAsIn cat) -> arbitrary `Gen.suchThat` - (\x -> x `notElem` xs && categorize x == cat) + (\x -> not (tokenMember x xs) && categorize x == cat) NotOneOf xs (AndNotAsIn cats) -> arbitrary `Gen.suchThat` - (\x -> x `notElem` xs && categorize x `notElem` cats) + (\x -> not (tokenMember x xs) && categorize x `notElem` cats) Alternate p q ps -> Gen.oneof (p : q : ps) instance (RandomGen g, Monad m, Categorized token, Random token) => TokenAlgebra token (StateT g m token) where tokenClass = foldTokenClass $ \case - OneOf xs -> oneOf xs + OneOf xs -> oneOf (Exts.toList xs) NotOneOf xs (AndAsIn cat) -> - iterateUntil (\x -> x `notElem` xs && categorize x == cat) anyToken + iterateUntil (\x -> not (tokenMember x xs) && categorize x == cat) anyToken NotOneOf xs (AndNotAsIn cats) -> - iterateUntil (\x -> x `notElem` xs && categorize x `notElem` cats) anyToken + iterateUntil (\x -> not (tokenMember x xs) && categorize x `notElem` cats) anyToken Alternate p q ps -> do i <- state (randomR (0, length ps + 1)) (p : q : ps) !! i instance Categorized token => Tokenized token (TokenExam token alg) where anyToken = passExam - token a = OneOf (Set.singleton a) + token a = OneOf (Exts.fromList [a]) oneOf as | null as = failExam - oneOf as = OneOf (Set.fromList (toList as)) + oneOf as = OneOf (Exts.fromList (toList as)) notOneOf as | null as = passExam notOneOf as = - NotOneOf (Set.fromList (toList as)) (AndNotAsIn Set.empty) - asIn cat = NotOneOf Set.empty (AndAsIn cat) - notAsIn cat = NotOneOf Set.empty (AndNotAsIn (Set.singleton cat)) + NotOneOf (Exts.fromList (toList as)) (AndNotAsIn Set.empty) + asIn cat = NotOneOf falseP (AndAsIn cat) + notAsIn cat = NotOneOf falseP (AndNotAsIn (Set.singleton cat)) instance Categorized token => DisjunctiveMonoid (TokenExam token (TokenClass token)) where falseP = failExam @@ -386,9 +453,9 @@ instance Categorized token notP exam | isPassExam exam = failExam notP (Alternate x y zs) = foldr1 (>&<) [notP exam | TokenClass exam <- x : y : zs] - notP (OneOf xs) = notOneOf xs - notP (NotOneOf xs (AndAsIn y)) = oneOf xs >|< notAsIn y - notP (NotOneOf xs (AndNotAsIn ys)) = oneOf xs >|< anyP asIn ys + notP (OneOf xs) = notOneOf (Exts.toList xs) + notP (NotOneOf xs (AndAsIn y)) = oneOf (Exts.toList xs) >|< notAsIn y + notP (NotOneOf xs (AndNotAsIn ys)) = oneOf (Exts.toList xs) >|< anyP asIn ys x >&< y | x == y = x _ >&< exam | isFailExam exam = failExam exam >&< _ | isFailExam exam = failExam @@ -398,37 +465,37 @@ instance Categorized token foldr1 (>|<) [x >&< exam | TokenClass exam <- y : z : ws] Alternate x y ws >&< z = foldr1 (>|<) [exam >&< z | TokenClass exam <- x : y : ws] - OneOf xs >&< OneOf ys = OneOf (Set.intersection xs ys) + OneOf xs >&< OneOf ys = OneOf (tokenIntersection xs ys) OneOf xs >&< NotOneOf ys (AndAsIn z) = OneOf - (Set.filter (\x -> categorize x == z) (Set.difference xs ys)) + (filterTokens (\x -> categorize x == z) (tokenDifference xs ys)) NotOneOf xs (AndAsIn y) >&< OneOf zs = OneOf - (Set.filter (\z -> categorize z == y) (Set.difference zs xs)) + (filterTokens (\z -> categorize z == y) (tokenDifference zs xs)) OneOf xs >&< NotOneOf ys (AndNotAsIn zs) = OneOf - (Set.filter (\x -> categorize x `notElem` zs) (Set.difference xs ys)) + (filterTokens (\x -> categorize x `notElem` zs) (tokenDifference xs ys)) NotOneOf xs (AndNotAsIn ys) >&< OneOf zs = OneOf - (Set.filter (\z -> categorize z `notElem` ys) (Set.difference zs xs)) + (filterTokens (\z -> categorize z `notElem` ys) (tokenDifference zs xs)) NotOneOf xs (AndAsIn y) >&< NotOneOf ws (AndAsIn z) = if y /= z then failExam else NotOneOf - (Set.filter (\x -> categorize x == y) (Set.union xs ws)) (AndAsIn y) + (filterTokens (\x -> categorize x == y) (xs >|< ws)) (AndAsIn y) NotOneOf xs (AndAsIn y) >&< NotOneOf ws (AndNotAsIn zs) = if y `elem` zs then failExam else NotOneOf - (Set.filter (\x -> categorize x == y) (Set.union xs ws)) (AndAsIn y) + (filterTokens (\x -> categorize x == y) (xs >|< ws)) (AndAsIn y) NotOneOf xs (AndNotAsIn ys) >&< NotOneOf ws (AndAsIn z) = if z `elem` ys then failExam else NotOneOf - (Set.filter (\x -> categorize x == z) (Set.union xs ws)) (AndAsIn z) + (filterTokens (\x -> categorize x == z) (xs >|< ws)) (AndAsIn z) NotOneOf xs (AndNotAsIn ys) >&< NotOneOf ws (AndNotAsIn zs) = let - xws = Set.union xs ws + xws = xs >|< ws yzs = Set.union ys zs in NotOneOf - (Set.filter (\x -> categorize x `notElem` yzs) xws) + (filterTokens (\x -> categorize x `notElem` yzs) xws) (AndNotAsIn yzs) deriving stock instance - (Categorized token, Read token, Read alg, Read (Categorize token)) + (Categorized token, Read (TokenSet token), Read alg, Read (Categorize token)) => Read (TokenExam token alg) deriving stock instance - (Categorized token, Show token, Show alg, Show (Categorize token)) + (Categorized token, Show (TokenSet token), Show alg, Show (Categorize token)) => Show (TokenExam token alg) deriving stock instance Functor (TokenExam token) deriving stock instance Foldable (TokenExam token) @@ -438,8 +505,12 @@ deriving stock instance (Categorized token, Ord alg) => Ord (TokenExam token alg deriving stock instance Categorized token => Eq (CategoryTest token) deriving stock instance Categorized token => Ord (CategoryTest token) deriving stock instance - (Categorized token, Read token, Read (Categorize token)) + (Categorized token, Read (TokenSet token), Read (Categorize token)) => Read (CategoryTest token) deriving stock instance - (Categorized token, Show token, Show (Categorize token)) + (Categorized token, Show (TokenSet token), Show (Categorize token)) => Show (CategoryTest token) + +-- | The tokens of a set satisfying a predicate. +filterTokens :: Categorized token => (token -> Bool) -> TokenSet token -> TokenSet token +filterTokens p = Exts.fromList . filter p . Exts.toList diff --git a/distributors-grammar/src/Data/Profunctor/Grammar/Parsector.hs b/distributors-grammar/src/Data/Profunctor/Grammar/Parsector.hs index 5b603547..19dc0d80 100644 --- a/distributors-grammar/src/Data/Profunctor/Grammar/Parsector.hs +++ b/distributors-grammar/src/Data/Profunctor/Grammar/Parsector.hs @@ -135,11 +135,11 @@ data ParsecFailure s = ParsecFailure -- ParsecFailure instances deriving stock instance ( Categorized (Item s) - , Show (Item s), Show (Categorize (Item s)) + , Show (Item s), Show (Categorize (Item s)), Show (TokenSet (Item s)) ) => Show (ParsecFailure s) deriving stock instance ( Categorized (Item s) - , Read (Item s), Read (Categorize (Item s)) + , Read (Item s), Read (Categorize (Item s)), Read (TokenSet (Item s)) ) => Read (ParsecFailure s) deriving stock instance Categorized (Item s) => Eq (ParsecFailure s) deriving stock instance Categorized (Item s) => Ord (ParsecFailure s) @@ -154,12 +154,12 @@ deriving stock instance Foldable (ParsecState s) deriving stock instance Traversable (ParsecState s) deriving stock instance ( Categorized (Item s) - , Show (Item s), Show (Categorize (Item s)) + , Show (Item s), Show (Categorize (Item s)), Show (TokenSet (Item s)) , Show a, Show s ) => Show (ParsecState s a) deriving stock instance ( Categorized (Item s) - , Read (Item s), Read (Categorize (Item s)) + , Read (Item s), Read (Categorize (Item s)), Read (TokenSet (Item s)) , Read a, Read s ) => Read (ParsecState s a) deriving stock instance From 33de5c3148f1a06d58537d74959a3da11477d5e6 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Fri, 13 Nov 2026 21:51:21 -0800 Subject: [PATCH 19/51] tokenRange, a token between two, by its ends Co-Authored-By: Claude Opus 5.5 --- distributors-grammar/CHANGELOG.md | 5 ++++ .../src/Control/Lens/Grammar.hs | 1 + .../src/Control/Lens/Grammar/RegEx.hs | 3 +- .../src/Control/Lens/Grammar/Token.hs | 29 +++++++++++++++++++ .../src/Data/Profunctor/Grammar.hs | 1 + .../src/Data/Profunctor/Grammar/Parsector.hs | 1 + .../src/Data/Profunctor/Grammar/Printor.hs | 1 + distributors-grammar/test/Examples/Json.hs | 3 +- distributors-grammar/test/Main.hs | 21 +++++++++++++- 9 files changed, 61 insertions(+), 4 deletions(-) diff --git a/distributors-grammar/CHANGELOG.md b/distributors-grammar/CHANGELOG.md index 09da904f..050504e9 100644 --- a/distributors-grammar/CHANGELOG.md +++ b/distributors-grammar/CHANGELOG.md @@ -2,6 +2,11 @@ ## Unreleased +- `Tokenized` has `tokenRange lo hi`, a single token between two, inclusive, + for `Enum`erable tokens, as `oneOf [lo .. hi]` but taking only its ends: + predicates & parsers compare, generators choose, & token classes & regular + expressions keep one range, by `Categorized`'s `tokenRangeSet`. The Json + example's character is its spec's, by `tokenRange`. - `Categorized` has a `TokenSet` type of its tokens' sets, a `Set` by default, with `tokenMember`, `tokenIntersection` & `tokenDifference`, empty by `falseP`, unioned by `>|<` & listed by `IsList`; `Char`'s are `Ranges`, diff --git a/distributors-grammar/src/Control/Lens/Grammar.hs b/distributors-grammar/src/Control/Lens/Grammar.hs index dce46be8..d11a58b4 100644 --- a/distributors-grammar/src/Control/Lens/Grammar.hs +++ b/distributors-grammar/src/Control/Lens/Grammar.hs @@ -750,6 +750,7 @@ 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)) + tokenRange lo hi = WrapMega $ M.label ("in range " ++ show (lo, hi)) (M.satisfy (tokenRange lo hi)) instance Ruled (WrapMega a) where rule lbl (WrapMega p) = WrapMega (M.label lbl p) instance BackusNaurForm (WrapMega a) diff --git a/distributors-grammar/src/Control/Lens/Grammar/RegEx.hs b/distributors-grammar/src/Control/Lens/Grammar/RegEx.hs index 56aa16f0..24d9ceac 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/RegEx.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/RegEx.hs @@ -34,7 +34,6 @@ import Control.Lens.Grammar.Symbol import Control.Lens.Grammar.Token import Data.Coerce import Data.Bifunctor.Joker -import Data.Foldable import Data.List (nub) import Data.MemoTrie import Data.Monoid.Disjunctive @@ -102,6 +101,7 @@ instance Categorized token => Tokenized token (RegEx token) where notOneOf = RegExam . notOneOf asIn = RegExam . asIn notAsIn = RegExam . notAsIn + tokenRange lo = RegExam . tokenRange lo instance Categorized token => TokenAlgebra token (RegEx token) where tokenClass = foldTokenClass RegExam instance Categorized token => Monoid (RegEx token) where @@ -434,6 +434,7 @@ instance (Ord rule, Tokenized token rule) notOneOf = liftBnf0 . notOneOf asIn = liftBnf0 . asIn notAsIn = liftBnf0 . notAsIn + tokenRange lo = liftBnf0 . tokenRange lo instance (Ord rule, TokenAlgebra token rule) => TokenAlgebra token (Bnf rule) where tokenClass = liftBnf0 . tokenClass diff --git a/distributors-grammar/src/Control/Lens/Grammar/Token.hs b/distributors-grammar/src/Control/Lens/Grammar/Token.hs index cf01fe76..6a3d17bf 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/Token.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/Token.hs @@ -100,6 +100,13 @@ class :: TokenSet token ~ Set token => TokenSet token -> TokenSet token -> TokenSet token tokenDifference = Set.difference + {- | The tokens between two, inclusive, by their enumeration, none where + they're out of order. -} + tokenRangeSet :: Enum token => token -> token -> TokenSet token + default tokenRangeSet + :: (Enum token, TokenSet token ~ Set token) + => token -> token -> TokenSet token + tokenRangeSet lo hi = Set.fromList [lo .. hi] instance Categorized Char where type Categorize Char = GeneralCategory categorize = generalCategory @@ -107,6 +114,9 @@ instance Categorized Char where tokenMember x (Ranges xs) = RSet.member x xs tokenIntersection (Ranges xs) (Ranges ys) = Ranges (RSet.intersection xs ys) tokenDifference (Ranges xs) (Ranges ys) = Ranges (RSet.difference xs ys) + tokenRangeSet lo hi + | lo > hi = falseP + | otherwise = Ranges (RSet.singletonRange (lo, hi)) instance Categorized Word8 instance Categorized () @@ -188,6 +198,18 @@ class Categorized token => Tokenized token p | p -> token where => Categorize token -> p notAsIn = satisfy . notAsIn + {- | A single token between two, inclusive, by their enumeration, + for tokens whose `Enum` & `Ord` agree, taking no more than its ends, + where `oneOf` takes every token of a range. + + > prop> tokenRange lo hi = oneOf [lo .. hi] + -} + tokenRange :: Enum token => token -> token -> p + default tokenRange + :: (Enum token, p ~ q token token, Choice q, Cochoice q) + => token -> token -> p + tokenRange lo hi = satisfy (tokenRange lo hi) + {- | A single token that satisfies a predicate. -} satisfy :: (Tokenized a (p a a), Choice p, Cochoice p) @@ -213,6 +235,7 @@ instance Categorized token => Tokenized token (token -> Bool) where where members = Set.fromList (toList xs) asIn = lmap categorize . (==) notAsIn = lmap categorize . (/=) + tokenRange lo hi x = lo <= x && x <= hi instance Tokenized token (f token) => Tokenized token (Joker f token token) where anyToken = Joker (anyToken @token) @@ -221,6 +244,7 @@ instance Tokenized token (f token) notOneOf = Joker . notOneOf @token asIn = Joker . asIn @token notAsIn = Joker . notAsIn @token + tokenRange lo hi = Joker (tokenRange @token lo hi) instance Tokenized Char (ReadP Char) where anyToken = ReadP.get token = ReadP.char @@ -228,6 +252,7 @@ instance Tokenized Char (ReadP Char) where notOneOf = ReadP.satisfy . notOneOf asIn = ReadP.satisfy . asIn notAsIn = ReadP.satisfy . notAsIn + tokenRange lo hi = ReadP.satisfy (tokenRange lo hi) instance Tokenized Char (ReadPrec Char) where anyToken = ReadPrec.lift anyToken token = ReadPrec.lift . token @@ -235,6 +260,7 @@ instance Tokenized Char (ReadPrec Char) where notOneOf = ReadPrec.lift . notOneOf asIn = ReadPrec.lift . asIn notAsIn = ReadPrec.lift . notAsIn + tokenRange lo hi = ReadPrec.lift (tokenRange lo hi) deriving via (token -> Bool) instance Categorized token => Tokenized token (Predicate token) instance (Categorized token, Arbitrary token) => Tokenized token (Gen token) where @@ -244,6 +270,7 @@ instance (Categorized token, Arbitrary token) => Tokenized token (Gen token) whe notOneOf xs = arbitrary `Gen.suchThat` (`notElem` xs) asIn cat = arbitrary `Gen.suchThat` ((==) cat . categorize) notAsIn cat = arbitrary `Gen.suchThat` ((/=) cat . categorize) + tokenRange lo hi = toEnum <$> Gen.chooseInt (fromEnum lo, fromEnum hi) instance (RandomGen g, Monad m, Categorized token, Random token) => Tokenized token (StateT g m token) where anyToken = state random @@ -255,6 +282,7 @@ instance (RandomGen g, Monad m, Categorized token, Random token) notOneOf xs = iterateUntil (`notElem` xs) anyToken asIn cat = iterateUntil ((== cat) . categorize) anyToken notAsIn cat = iterateUntil ((/= cat) . categorize) anyToken + tokenRange lo hi = toEnum <$> state (randomR (fromEnum lo, fromEnum hi)) {- | A token examination, by the tokens it accepts, & the alternatives of an algebra, whose fixed point is t'TokenClass'. Both t'TokenClass'es & @@ -442,6 +470,7 @@ instance Categorized token => Tokenized token (TokenExam token alg) where NotOneOf (Exts.fromList (toList as)) (AndNotAsIn Set.empty) asIn cat = NotOneOf falseP (AndAsIn cat) notAsIn cat = NotOneOf falseP (AndNotAsIn (Set.singleton cat)) + tokenRange lo hi = OneOf (tokenRangeSet lo hi) instance Categorized token => DisjunctiveMonoid (TokenExam token (TokenClass token)) where falseP = failExam diff --git a/distributors-grammar/src/Data/Profunctor/Grammar.hs b/distributors-grammar/src/Data/Profunctor/Grammar.hs index 2ea554e4..207a6553 100644 --- a/distributors-grammar/src/Data/Profunctor/Grammar.hs +++ b/distributors-grammar/src/Data/Profunctor/Grammar.hs @@ -244,6 +244,7 @@ instance Tokenized token k => Tokenized token (Grammor k a b) where notOneOf = Grammor . notOneOf asIn = Grammor . asIn notAsIn = Grammor . notAsIn + tokenRange lo = Grammor . tokenRange lo instance TokenAlgebra a k => TokenAlgebra a (Grammor k a b) where tokenClass = Grammor . tokenClass instance TerminalSymbol token k diff --git a/distributors-grammar/src/Data/Profunctor/Grammar/Parsector.hs b/distributors-grammar/src/Data/Profunctor/Grammar/Parsector.hs index 19dc0d80..23c33989 100644 --- a/distributors-grammar/src/Data/Profunctor/Grammar/Parsector.hs +++ b/distributors-grammar/src/Data/Profunctor/Grammar/Parsector.hs @@ -182,6 +182,7 @@ instance notOneOf ts = tokenClass (notOneOf ts) asIn cat = tokenClass (asIn cat) notAsIn cat = tokenClass (notAsIn cat) + tokenRange lo hi = tokenClass (tokenRange lo hi) instance ( Categorized token, Item s ~ token , Cons s s token token, Snoc s s token token diff --git a/distributors-grammar/src/Data/Profunctor/Grammar/Printor.hs b/distributors-grammar/src/Data/Profunctor/Grammar/Printor.hs index 9357946d..39d13336 100644 --- a/distributors-grammar/src/Data/Profunctor/Grammar/Printor.hs +++ b/distributors-grammar/src/Data/Profunctor/Grammar/Printor.hs @@ -146,6 +146,7 @@ instance notOneOf ts = tokenClass (notOneOf ts) asIn cat = tokenClass (asIn cat) notAsIn cat = tokenClass (notAsIn cat) + tokenRange lo hi = tokenClass (tokenRange lo hi) instance ( Categorized a, a ~ Item s, IsList s, Cons s s a a , Filterable m, Alternative m, Monad m diff --git a/distributors-grammar/test/Examples/Json.hs b/distributors-grammar/test/Examples/Json.hs index 423ddf28..e49d6835 100644 --- a/distributors-grammar/test/Examples/Json.hs +++ b/distributors-grammar/test/Examples/Json.hs @@ -79,8 +79,7 @@ jsonGrammar = rule "json" elementG -- character = '0020' . '10FFFF' - '"' - '\' | '\' escape characterG = rule "character" $ - -- by complement, 34 tokens rather than a million - tokenClass (notOneOf ('\"' : '\\' : ['\x0000' .. '\x001F'])) + tokenClass (tokenRange '\x0020' '\x10FFFF' >&< notOneOf ['\"','\\']) >|< terminal "\\" >* escapeG -- escape = '"' | '\' | '/' | 'b' | 'f' | 'n' | 'r' | 't' diff --git a/distributors-grammar/test/Main.hs b/distributors-grammar/test/Main.hs index f5b5141a..7d94f2f2 100644 --- a/distributors-grammar/test/Main.hs +++ b/distributors-grammar/test/Main.hs @@ -13,7 +13,7 @@ import Text.ParserCombinators.ReadPrec (ReadPrec, readPrec_to_S) import Data.Functor.Contravariant (Predicate (..)) import Test.Hspec import Test.Hspec.QuickCheck (modifyMaxSize, prop) -import Test.QuickCheck (choose, elements, forAll, generate, listOf, oneof, (===)) +import Test.QuickCheck (Gen, choose, elements, forAll, generate, listOf, oneof, (===)) import qualified Text.Megaparsec as M import Examples.Arithmetic @@ -55,6 +55,7 @@ main = hspec $ do describe "base types" baseProperties describe "RegEx ranges & try" regexRangeTryTests describe "RegEx quantifiers" regexQuantifierTests + describe "tokenRange" tokenRangeTests regexRangeTryTests :: Spec regexRangeTryTests = do @@ -78,6 +79,23 @@ regexRangeTryTests = do `shouldBe` [LL1FirstFirst] ll1Conflicts (fromString "{start} = \\t{ab}|ac" :: Bnf (RegEx Char)) `shouldBe` [] +tokenRangeTests :: Spec +tokenRangeTests = do + prop "tokenRange lo hi = oneOf [lo .. hi], as TokenClass" $ \(lo :: Char) hi -> + (tokenRange lo hi :: TokenClass Char) === oneOf [lo .. hi] + prop "tokenRange lo hi = oneOf [lo .. hi], as a predicate" $ \(lo :: Char) hi x -> + tokenRange lo hi x === (oneOf [lo .. hi] :: Char -> Bool) x + it "renders as a range, & parses so" $ do + toList (tokenRange 'a' 'z' :: RegEx Char) `shouldBe` "[a-z]" + (fromString "[a-z]" :: RegEx Char) `shouldBe` tokenRange 'a' 'z' + toList (tokenRange 'z' 'a' :: RegEx Char) `shouldBe` "[]" + it "takes all of Unicode by its ends" $ do + let rex = tokenClass (tokenRange '\x20' '\x10FFFF' >&< notOneOf "\"\\") :: RegEx Char + toList rex `shouldBe` "[ !#-Z\\[\\]\\^_-\1114111]" + map (=~ rex) ["a", "\"", "\x10FFFF", "\x1F"] `shouldBe` [True, False, True, False] + prop "generates tokens in range" $ forAll (choose ('a', 'm')) $ \lo -> + forAll (tokenRange lo 'z' :: Gen Char) $ \x -> lo <= x && x <= 'z' + regexQuantifierTests :: Spec regexQuantifierTests = do let rendered :: Prismoid String String Char Char -> String @@ -256,6 +274,7 @@ 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))) + tokenRange lo hi = WrapMega $ M.label ("in range " ++ show (lo, hi)) (M.satisfy (tokenRange lo hi)) instance Ruled (WrapMega a) where rule lbl (WrapMega p) = WrapMega (M.label lbl p) instance BackusNaurForm (WrapMega a) From 43c1a3df06d850f48c52fc9f68f4fc03dd6c7b8b Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Fri, 13 Nov 2026 22:00:38 -0800 Subject: [PATCH 20/51] Token classes intersect & sample without listing large sets Co-Authored-By: Claude Opus 5.5 --- .../src/Control/Lens/Grammar/Token.hs | 23 +++++++++++++++---- distributors-grammar/test/Main.hs | 5 ++-- 2 files changed, 22 insertions(+), 6 deletions(-) diff --git a/distributors-grammar/src/Control/Lens/Grammar/Token.hs b/distributors-grammar/src/Control/Lens/Grammar/Token.hs index 6a3d17bf..c7807fed 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/Token.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/Token.hs @@ -32,6 +32,7 @@ import Data.Bifunctor.Joker import Data.Char import Data.Foldable import Data.List (nub) +import Data.Maybe (fromMaybe) import Data.Profunctor import Data.Monoid.Disjunctive import Data.Profunctor.Distributor @@ -443,7 +444,12 @@ 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 (Exts.toList xs) + -- a small set is chosen of uniformly, & a large one, by trying + -- arbitrary tokens, or else its least tokens, never listing it all + OneOf xs -> case splitAt 256 (Exts.toList xs) of + (few, []) -> Gen.elements few + (few, _) -> fromMaybe <$> Gen.elements few + <*> arbitrary `Gen.suchThatMaybe` (`tokenMember` xs) NotOneOf xs (AndAsIn cat) -> arbitrary `Gen.suchThat` (\x -> not (tokenMember x xs) && categorize x == cat) NotOneOf xs (AndNotAsIn cats) -> arbitrary `Gen.suchThat` @@ -500,9 +506,9 @@ instance Categorized token NotOneOf xs (AndAsIn y) >&< OneOf zs = OneOf (filterTokens (\z -> categorize z == y) (tokenDifference zs xs)) OneOf xs >&< NotOneOf ys (AndNotAsIn zs) = OneOf - (filterTokens (\x -> categorize x `notElem` zs) (tokenDifference xs ys)) + (notInCategories zs (tokenDifference xs ys)) NotOneOf xs (AndNotAsIn ys) >&< OneOf zs = OneOf - (filterTokens (\z -> categorize z `notElem` ys) (tokenDifference zs xs)) + (notInCategories ys (tokenDifference zs xs)) NotOneOf xs (AndAsIn y) >&< NotOneOf ws (AndAsIn z) = if y /= z then failExam else NotOneOf (filterTokens (\x -> categorize x == y) (xs >|< ws)) (AndAsIn y) @@ -518,7 +524,7 @@ instance Categorized token yzs = Set.union ys zs in NotOneOf - (filterTokens (\x -> categorize x `notElem` yzs) xws) + (notInCategories yzs xws) (AndNotAsIn yzs) deriving stock instance (Categorized token, Read (TokenSet token), Read alg, Read (Categorize token)) @@ -543,3 +549,12 @@ deriving stock instance -- | The tokens of a set satisfying a predicate. filterTokens :: Categorized token => (token -> Bool) -> TokenSet token -> TokenSet token filterTokens p = Exts.fromList . filter p . Exts.toList + +-- | The tokens of a set not in any of some categories, +-- not listing the set where there are none. +notInCategories + :: Categorized token + => Set (Categorize token) -> TokenSet token -> TokenSet token +notInCategories cats + | Set.null cats = id + | otherwise = filterTokens (\x -> categorize x `Set.notMember` cats) diff --git a/distributors-grammar/test/Main.hs b/distributors-grammar/test/Main.hs index 7d94f2f2..7190b0e6 100644 --- a/distributors-grammar/test/Main.hs +++ b/distributors-grammar/test/Main.hs @@ -81,9 +81,10 @@ regexRangeTryTests = do tokenRangeTests :: Spec tokenRangeTests = do - prop "tokenRange lo hi = oneOf [lo .. hi], as TokenClass" $ \(lo :: Char) hi -> + let near = choose ('\0', '\x3FF') + prop "tokenRange lo hi = oneOf [lo .. hi], as TokenClass" $ forAll near $ \lo -> forAll near $ \hi -> (tokenRange lo hi :: TokenClass Char) === oneOf [lo .. hi] - prop "tokenRange lo hi = oneOf [lo .. hi], as a predicate" $ \(lo :: Char) hi x -> + prop "tokenRange lo hi = oneOf [lo .. hi], as a predicate" $ forAll near $ \lo -> forAll near $ \hi -> forAll near $ \x -> tokenRange lo hi x === (oneOf [lo .. hi] :: Char -> Bool) x it "renders as a range, & parses so" $ do toList (tokenRange 'a' 'z' :: RegEx Char) `shouldBe` "[a-z]" From 3e72c8bc6d186690fcf2fafee95cb744842b85b7 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Fri, 13 Nov 2026 23:32:47 -0800 Subject: [PATCH 21/51] Grammar classes in Control.Lens.Grammar.Class; RegEx grammars as instances; Varifocus runs alternatives by anyP Co-Authored-By: Claude Opus 5.5 --- .../src/Control/Lens/Varifocal.hs | 14 +- distributors-grammar/CHANGELOG.md | 6 + .../distributors-grammar.cabal | 1 + .../src/Control/Lens/Grammar.hs | 140 ++-------------- .../src/Control/Lens/Grammar/BackusNaur.hs | 1 + .../src/Control/Lens/Grammar/Class.hs | 155 ++++++++++++++++++ .../src/Control/Lens/Grammar/RegEx.hs | 23 ++- distributors-grammar/test/Main.hs | 2 +- 8 files changed, 194 insertions(+), 148 deletions(-) create mode 100644 distributors-grammar/src/Control/Lens/Grammar/Class.hs diff --git a/distributors-core/src/Control/Lens/Varifocal.hs b/distributors-core/src/Control/Lens/Varifocal.hs index a7c144c9..675016ce 100644 --- a/distributors-core/src/Control/Lens/Varifocal.hs +++ b/distributors-core/src/Control/Lens/Varifocal.hs @@ -48,7 +48,7 @@ import Data.Bool (bool) import Data.Foldable (toList) import Data.Functor (void) import Data.Traversable (mapAccumL) -import Data.Monoid.Disjunctive (DisjunctiveMonoid (..)) +import Data.Monoid.Disjunctive (DisjunctiveMonoid (..), anyP) import Data.Profunctor (Cochoice (..)) import Data.Profunctor.Distributor import Data.Profunctor.Filtrator (Filtrator (..), mfiltrate) @@ -195,14 +195,10 @@ runVarifocus v p = go v go :: Varifocus a b [] s' t' -> p s' t' go = \case FocusP -> p - LiftP xs -> case map pure xs of - [] -> empty - ys -> foldr1 (<|>) ys + LiftP xs -> anyP pure xs BindP x k -> go x >>= go . k LmapP f x -> lmap f (go x) - AltsP xs -> case map go xs of - [] -> empty - ys -> foldr1 (<|>) ys + AltsP xs -> anyP go xs AlternateP e -> alternate (either (Left . go) (Right . go) e) ManyP x -> manyP (go x) OptionalP x -> optionalP (go x) @@ -224,9 +220,7 @@ runVarifocusT v p = go v LiftP mt -> liftP mt BindP x k -> go x >>= go . k LmapP f x -> lmap f (go x) - AltsP xs -> case map go xs of - [] -> empty - ys -> foldr1 (<|>) ys + AltsP xs -> anyP go xs AlternateP e -> alternate (either (Left . go) (Right . go) e) ManyP x -> manyP (go x) OptionalP x -> optionalP (go x) diff --git a/distributors-grammar/CHANGELOG.md b/distributors-grammar/CHANGELOG.md index 050504e9..8efb9656 100644 --- a/distributors-grammar/CHANGELOG.md +++ b/distributors-grammar/CHANGELOG.md @@ -2,6 +2,12 @@ ## Unreleased +- `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. - `Tokenized` has `tokenRange lo hi`, a single token between two, inclusive, for `Enum`erable tokens, as `oneOf [lo .. hi]` but taking only its ends: predicates & parsers compare, generators choose, & token classes & regular diff --git a/distributors-grammar/distributors-grammar.cabal b/distributors-grammar/distributors-grammar.cabal index fdf73db7..fc5218c5 100644 --- a/distributors-grammar/distributors-grammar.cabal +++ b/distributors-grammar/distributors-grammar.cabal @@ -31,6 +31,7 @@ library Control.Lens.Grammar Control.Lens.Grammar.Analysis Control.Lens.Grammar.BackusNaur + Control.Lens.Grammar.Class Control.Lens.Grammar.Machine Control.Lens.Grammar.RegEx Control.Lens.Grammar.Symbol diff --git a/distributors-grammar/src/Control/Lens/Grammar.hs b/distributors-grammar/src/Control/Lens/Grammar.hs index d11a58b4..274d1a83 100644 --- a/distributors-grammar/src/Control/Lens/Grammar.hs +++ b/distributors-grammar/src/Control/Lens/Grammar.hs @@ -14,16 +14,19 @@ See Chomsky, [On Certain Formal Properties of Grammars] module Control.Lens.Grammar ( -- * Regular grammar + -- $regGrammar RegGrammar (..) , RegGrammatical , regexG -- * Context-free grammar + -- $grammar , Grammar (..) , Grammatical , regbnfG , applicativeG , transducerG -- * Context-sensitive grammar + -- $ctxGrammar , CtxGrammar (..) , CtxGrammatical , printG @@ -43,15 +46,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.Bits (Bits, toIntegralSized) -import Data.Char (isDigit) -import Data.Int (Int8, Int16, Int32, Int64) -import Data.Maybe (isJust) import Data.Monoid.Disjunctive import Data.Profunctor.Distributor import Data.Profunctor.Monoidal.Cocartesian @@ -60,9 +60,7 @@ import Data.Profunctor.Monadic as X import Data.Profunctor.Monoidal import Data.Profunctor.Grammar import Data.Profunctor.Grammar.Parsector -import Data.Word (Word8, Word16, Word32, Word64) import GHC.Exts -import Numeric.Natural (Natural) import Prelude hiding (filter) import Text.ParserCombinators.ReadP (ReadP) import Witherable @@ -100,7 +98,7 @@ import Data.Traversable.Homogeneous.Enumerable as X -- >>> import Data.String (fromString) -- >>> import GHC.Exts (toList) -{- | +{- $regGrammar A regular grammar may be constructed using `terminal` symbols, `Tokenized` combinators, `tokenClass`es and `Alternator` combinators. @@ -228,19 +226,17 @@ 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 `RegGrammatical` instances. -} -class Grammar token a => RegGrammar token a where - regGrammar :: RegGrammatical token 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.RegEx.regexGrammar` and -`Control.Lens.Grammar.RegEx.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. @@ -372,13 +368,10 @@ But it's recommended to use `Grammar`s for `rule` abstraction and generator support for `ruleRec`. -} -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 -{- | 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. @@ -515,10 +508,6 @@ ParsecState {parsecLooked = True, parsecOffset = 3, parsecStream = "b", parsecFa ParsecState {parsecLooked = True, parsecOffset = 2, parsecStream = "ab", parsecFailure = ParsecFailure {parsecExpect = TokenClass (OneOf (fromList "c")), parsecLabels = []}, parsecResult = Nothing} -} -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 @@ -781,110 +770,3 @@ to string-like interfaces such as `RegEx` and t'Bnf' of `Char`s. -} putStringLn :: (IsList string, Item string ~ Char) => string -> IO () putStringLn = putStrLn . toList - --- Base types -- - -instance CtxGrammar Char Char -instance Grammar Char Char where grammar = rule "Char" (regGrammar @Char) -instance RegGrammar Char Char where regGrammar = anyToken @Char - -instance CtxGrammar Char String -instance Grammar Char String where grammar = rule "String" (regGrammar @Char) -instance RegGrammar Char String where regGrammar = manyP (anyToken @Char) - -instance CtxGrammar Char Natural -instance Grammar Char Natural where grammar = rule "Natural" (regGrammar @Char) -instance RegGrammar Char Natural where regGrammar = naturalG - -instance CtxGrammar Char Integer -instance Grammar Char Integer where grammar = rule "Integer" (regGrammar @Char) -instance RegGrammar Char Integer where regGrammar = integerG - -instance CtxGrammar Char Double -instance Grammar Char Double where grammar = rule "Double" (regGrammar @Char) -instance RegGrammar Char Double where regGrammar = floatingG - -instance CtxGrammar Char Float -instance Grammar Char Float where grammar = rule "Float" (regGrammar @Char) -instance RegGrammar Char Float where regGrammar = floatingG - -{- Sized integers' syntax is `Integer`'s, but a literal out of their range -fails to build, which only a `CtxGrammar`'s `Filtrator` can, so they have -no regular expression or Backus-Naur form. -} -instance CtxGrammar Char Int where ctxGrammar = rule "Int" sizedG -instance CtxGrammar Char Int8 where ctxGrammar = rule "Int8" sizedG -instance CtxGrammar Char Int16 where ctxGrammar = rule "Int16" sizedG -instance CtxGrammar Char Int32 where ctxGrammar = rule "Int32" sizedG -instance CtxGrammar Char Int64 where ctxGrammar = rule "Int64" sizedG -instance CtxGrammar Char Word where ctxGrammar = rule "Word" sizedG -instance CtxGrammar Char Word8 where ctxGrammar = rule "Word8" sizedG -instance CtxGrammar Char Word16 where ctxGrammar = rule "Word16" sizedG -instance CtxGrammar Char Word32 where ctxGrammar = rule "Word32" sizedG -instance CtxGrammar Char Word64 where ctxGrammar = rule "Word64" sizedG - --- ASCII decimal digits, at least one. -decimalG :: RegGrammatical Char p => p String String -decimalG = someP (oneOf ['0' .. '9']) - --- An optional minus, as whether a number is negative. -negativeG :: RegGrammatical Char p => p Bool Bool -negativeG = iso (\b -> if b then Just () else Nothing) isJust - >~ optionalP (terminal "-") - --- Printing canonically, parsing leading zeros too, an improper iso. -naturalG :: RegGrammatical Char p => p Natural Natural -naturalG = iso show read >~ decimalG - --- Printing canonically, parsing leading zeros & -0 too, an improper iso. -integerG :: RegGrammatical Char p => p Integer Integer -integerG = iso - (\n -> (n < 0, show (abs n))) - (\(negative, digits) -> (if negative then negate else id) (read digits)) - >~ negativeG >*< decimalG - --- Integers in a range, failing to build out of it. -sizedG - :: forall a p. (Integral a, Bits a, CtxGrammatical Char p) => p a a -sizedG = prism' toInteger toIntegralSized ?< integerG - -{- Floating point numbers, @NaN@, or signed @Infinity@ or decimals with -an optional fraction & exponent, printing as `show` does & parsing as -`read` does, an improper iso, keeping the sign of zero. -} -floatingG - :: (RealFloat a, Read a, Show a, RegGrammatical Char p) => p a a -floatingG = iso toFloating fromFloating >~ - terminal "NaN" >+< negativeG >*< (terminal "Infinity" >+< numberG) - where - numberG = decimalG - >*< optionalP (terminal "." >* decimalG) - >*< optionalP (oneOf "eE" >*< optionalP (oneOf "+-") >*< decimalG) - toFloating x - | isNaN x = Left () - | otherwise = Right - ( x < 0 || isNegativeZero x - , if isInfinite x then Left () else Right (split (show (abs x))) ) - fromFloating = \case - Left () -> 0 / 0 - Right (negative, magnitude) -> (if negative then negate else id) $ - either (const (1 / 0)) (read . unsplit) magnitude - split shown = - let - (whole, rest) = span isDigit shown - (fraction, rest') = case rest of - '.' : more -> let (ds, more') = span isDigit more in (Just ds, more') - _ -> (Nothing, rest) - exponent' = case rest' of - e : more | e `elem` ("eE" :: String) -> case more of - s : ds | s `elem` ("+-" :: String) -> Just (e, (Just s, ds)) - ds -> Just (e, (Nothing, ds)) - _ -> Nothing - in - (whole, (fraction, exponent')) - unsplit (whole, (fraction, exponent')) = whole - <> maybe "" ('.' :) fraction - <> maybe "" (\(e, (s, ds)) -> e : maybe "" pure s <> ds) exponent' - -instance CtxGrammar Char (RegEx Char) -instance Grammar Char (RegEx Char) where grammar = regexGrammar -instance CtxGrammar Char (Bnf (RegEx Char)) -instance Grammar Char (Bnf (RegEx Char)) where grammar = regbnfGrammar diff --git a/distributors-grammar/src/Control/Lens/Grammar/BackusNaur.hs b/distributors-grammar/src/Control/Lens/Grammar/BackusNaur.hs index bec49290..9fb8c5ac 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/BackusNaur.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/BackusNaur.hs @@ -130,6 +130,7 @@ type CtxGrammatical token p = , forall x. MonadFail (p x) ) :: Constraint + -- instances instance (forall x. Ruled (f x)) => Ruled (Joker f a b) where rule name = Joker . rule name . runJoker 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..d568e61b --- /dev/null +++ b/distributors-grammar/src/Control/Lens/Grammar/Class.hs @@ -0,0 +1,155 @@ +{- | +Module : Control.Lens.Grammar.Class +Description : grammar classes & base types' grammars +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, & the grammars of base types. +-} + +module Control.Lens.Grammar.Class + ( RegGrammar (..) + , Grammar (..) + , CtxGrammar (..) + ) where + +import Control.Lens +import Control.Lens.PartialIso +import Control.Lens.Grammar.BackusNaur +import Control.Lens.Grammar.Symbol +import Control.Lens.Grammar.Token +import Data.Bits (Bits, toIntegralSized) +import Data.Char (isDigit) +import Data.Int (Int8, Int16, Int32, Int64) +import Data.Maybe (isJust) +import Data.Profunctor.Distributor +import Data.Profunctor.Monoidal +import Data.Profunctor.Monoidal.Cocartesian +import Data.Word (Word8, Word16, Word32, Word64) +import Numeric.Natural (Natural) + +{- | 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 + +-- Base types -- + +instance CtxGrammar Char Char +instance Grammar Char Char where grammar = rule "Char" (regGrammar @Char) +instance RegGrammar Char Char where regGrammar = anyToken @Char + +instance CtxGrammar Char String +instance Grammar Char String where grammar = rule "String" (regGrammar @Char) +instance RegGrammar Char String where regGrammar = manyP (anyToken @Char) + +instance CtxGrammar Char Natural +instance Grammar Char Natural where grammar = rule "Natural" (regGrammar @Char) +instance RegGrammar Char Natural where regGrammar = naturalG + +instance CtxGrammar Char Integer +instance Grammar Char Integer where grammar = rule "Integer" (regGrammar @Char) +instance RegGrammar Char Integer where regGrammar = integerG + +instance CtxGrammar Char Double +instance Grammar Char Double where grammar = rule "Double" (regGrammar @Char) +instance RegGrammar Char Double where regGrammar = floatingG + +instance CtxGrammar Char Float +instance Grammar Char Float where grammar = rule "Float" (regGrammar @Char) +instance RegGrammar Char Float where regGrammar = floatingG + +{- Sized integers' syntax is `Integer`'s, but a literal out of their range +fails to build, which only a `CtxGrammar`'s `Filtrator` can, so they have +no regular expression or Backus-Naur form. -} +instance CtxGrammar Char Int where ctxGrammar = rule "Int" sizedG +instance CtxGrammar Char Int8 where ctxGrammar = rule "Int8" sizedG +instance CtxGrammar Char Int16 where ctxGrammar = rule "Int16" sizedG +instance CtxGrammar Char Int32 where ctxGrammar = rule "Int32" sizedG +instance CtxGrammar Char Int64 where ctxGrammar = rule "Int64" sizedG +instance CtxGrammar Char Word where ctxGrammar = rule "Word" sizedG +instance CtxGrammar Char Word8 where ctxGrammar = rule "Word8" sizedG +instance CtxGrammar Char Word16 where ctxGrammar = rule "Word16" sizedG +instance CtxGrammar Char Word32 where ctxGrammar = rule "Word32" sizedG +instance CtxGrammar Char Word64 where ctxGrammar = rule "Word64" sizedG + +-- ASCII decimal digits, at least one. +decimalG :: RegGrammatical Char p => p String String +decimalG = someP (oneOf ['0' .. '9']) + +-- An optional minus, as whether a number is negative. +negativeG :: RegGrammatical Char p => p Bool Bool +negativeG = iso (\b -> if b then Just () else Nothing) isJust + >~ optionalP (terminal "-") + +-- Printing canonically, parsing leading zeros too, an improper iso. +naturalG :: RegGrammatical Char p => p Natural Natural +naturalG = iso show read >~ decimalG + +-- Printing canonically, parsing leading zeros & -0 too, an improper iso. +integerG :: RegGrammatical Char p => p Integer Integer +integerG = iso + (\n -> (n < 0, show (abs n))) + (\(negative, digits) -> (if negative then negate else id) (read digits)) + >~ negativeG >*< decimalG + +-- Integers in a range, failing to build out of it. +sizedG + :: forall a p. (Integral a, Bits a, CtxGrammatical Char p) => p a a +sizedG = prism' toInteger toIntegralSized ?< integerG + +{- Floating point numbers, @NaN@, or signed @Infinity@ or decimals with +an optional fraction & exponent, printing as `show` does & parsing as +`read` does, an improper iso, keeping the sign of zero. -} +floatingG + :: (RealFloat a, Read a, Show a, RegGrammatical Char p) => p a a +floatingG = iso toFloating fromFloating >~ + terminal "NaN" >+< negativeG >*< (terminal "Infinity" >+< numberG) + where + numberG = decimalG + >*< optionalP (terminal "." >* decimalG) + >*< optionalP (oneOf "eE" >*< optionalP (oneOf "+-") >*< decimalG) + toFloating x + | isNaN x = Left () + | otherwise = Right + ( x < 0 || isNegativeZero x + , if isInfinite x then Left () else Right (split (show (abs x))) ) + fromFloating = \case + Left () -> 0 / 0 + Right (negative, magnitude) -> (if negative then negate else id) $ + either (const (1 / 0)) (read . unsplit) magnitude + split shown = + let + (whole, rest) = span isDigit shown + (fraction, rest') = case rest of + '.' : more -> let (ds, more') = span isDigit more in (Just ds, more') + _ -> (Nothing, rest) + exponent' = case rest' of + e : more | e `elem` ("eE" :: String) -> case more of + s : ds | s `elem` ("+-" :: String) -> Just (e, (Just s, ds)) + ds -> Just (e, (Nothing, ds)) + _ -> Nothing + in + (whole, (fraction, exponent')) + unsplit (whole, (fraction, exponent')) = whole + <> maybe "" ('.' :) fraction + <> maybe "" (\(e, (s, ds)) -> e : maybe "" pure s <> ds) exponent' + diff --git a/distributors-grammar/src/Control/Lens/Grammar/RegEx.hs b/distributors-grammar/src/Control/Lens/Grammar/RegEx.hs index 24d9ceac..ec500d5d 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/RegEx.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/RegEx.hs @@ -22,14 +22,13 @@ module Control.Lens.Grammar.RegEx , liftBnf2 , diffB -- * Regular expression strings - , regexGrammar - , regbnfGrammar ) 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.Coerce @@ -458,8 +457,8 @@ makeNestedPrisms ''TokenExam makeNestedPrisms ''CategoryTest makeNestedPrisms ''GeneralCategory -{- | `regexGrammar` is a context-free @Control.Lens.Grammar.Grammar@ -for `RegEx`pressions of characters, in the syntax of regular +{- | 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. @@ -586,6 +585,10 @@ Ill-formed regular expression strings normalize to failure. {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 @@ -813,8 +816,8 @@ charControlG = rule "char-control" $ orP ] {- | -`regbnfGrammar` is a context-free @Control.Lens.Grammar.Grammar@ -for t'Bnf's of `RegEx`pressions of characters, +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. @@ -875,12 +878,16 @@ But they also support `BackusNaurForm` `rule`s and `ruleRec`s. {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 `regexGrammar`. +-- | A regular expression string, by its `Grammar`. instance token ~ Char => Exts.IsList (RegEx token) where type Item (RegEx token) = token fromList @@ -895,7 +902,7 @@ instance token ~ Char => Exts.IsList (RegEx token) where (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 `regbnfGrammar`. +-- | 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 diff --git a/distributors-grammar/test/Main.hs b/distributors-grammar/test/Main.hs index 7190b0e6..c76631e3 100644 --- a/distributors-grammar/test/Main.hs +++ b/distributors-grammar/test/Main.hs @@ -32,7 +32,7 @@ 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 From e145f94e8d8a95a07ec53ede5ab4ea8b2d260350 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sat, 14 Nov 2026 00:12:43 -0800 Subject: [PATCH 22/51] Lexical: per-token Boolean algebras of tests; Tokenized absorbs TokenAlgebra Co-Authored-By: Claude Opus 5.5 --- distributors-grammar/CHANGELOG.md | 13 + distributors-grammar/bench/Main.hs | 4 +- .../src/Control/Lens/Grammar.hs | 40 +- .../src/Control/Lens/Grammar/Analysis.hs | 47 +- .../src/Control/Lens/Grammar/BackusNaur.hs | 2 +- .../src/Control/Lens/Grammar/Class.hs | 4 +- .../src/Control/Lens/Grammar/Machine.hs | 41 +- .../src/Control/Lens/Grammar/RegEx.hs | 216 ++--- .../src/Control/Lens/Grammar/Token.hs | 782 ++++++++---------- .../src/Data/Profunctor/Grammar.hs | 14 +- .../src/Data/Profunctor/Grammar/Parsector.hs | 89 +- .../src/Data/Profunctor/Grammar/Printor.hs | 28 +- .../test/Examples/RegString.hs | 8 +- distributors-grammar/test/Main.hs | 26 +- .../test/Properties/Kleene.hs | 12 +- .../test/Properties/Varifocal.hs | 46 +- .../src/Control/Lens/Grammar/TypeScript.hs | 34 +- 17 files changed, 665 insertions(+), 741 deletions(-) diff --git a/distributors-grammar/CHANGELOG.md b/distributors-grammar/CHANGELOG.md index 8efb9656..ee3c6bbf 100644 --- a/distributors-grammar/CHANGELOG.md +++ b/distributors-grammar/CHANGELOG.md @@ -2,6 +2,19 @@ ## Unreleased +- `Categorized` is `Lexical`, with a `BooleanAlgebra` of `TokenTest`s per + token type, generated by `testOneOf`, `testKinds` & `testRange`, & + tested by `tokenTest`, a homomorphism, each test having one form, so + that `Eq` is exact: `TokenRanges` for `Char`, whose `GeneralCategory`s + are ranges of a table, & `Word8`, `Cofinite` sets by default, & + `ByKind` tests for tokens tagged by kinds, like `TsToken`. `Categorize` + is `TokenKind`, & `categorize` is `tokenKind`. `TokenClass` wraps a + `TokenTest`. `TokenAlgebra` is merged into `Tokenized`, whose methods, + `tokenClass`, `tokenAny` (was `anyToken`) & the rest, default by + `tokenClass`. `TokenExam`, `CategoryTest` & `TokenSet` are removed. + `RegEx` has its own `Alternate`, & `RegExam` holds a `TokenClass`; + classes print in their shortest form, or as alternatives where shorter, + & alternatives of classes are one class. - `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 diff --git a/distributors-grammar/bench/Main.hs b/distributors-grammar/bench/Main.hs index d3287fb7..3986fa30 100644 --- a/distributors-grammar/bench/Main.hs +++ b/distributors-grammar/bench/Main.hs @@ -125,9 +125,9 @@ separates = -- | Varifocals, applied by contextually. varifocals :: [Workload] varifocals = - [ Workload "terminateBy" (contextually (terminateBy (== '.')) (anyToken @Char)) + [ Workload "terminateBy" (contextually (terminateBy (== '.')) (tokenAny @Char)) (digits <> ".") (digits <> ".") - , Workload "balanceBy" (contextually (balanceBy (== '(') (== ')')) (anyToken @Char)) + , Workload "balanceBy" (contextually (balanceBy (== '(') (== ')')) (tokenAny @Char)) nested nested , Workload "heredoc" heredocG heredocStr heredoc ] diff --git a/distributors-grammar/src/Control/Lens/Grammar.hs b/distributors-grammar/src/Control/Lens/Grammar.hs index 274d1a83..18022a2c 100644 --- a/distributors-grammar/src/Control/Lens/Grammar.hs +++ b/distributors-grammar/src/Control/Lens/Grammar.hs @@ -205,7 +205,7 @@ You can generate a regular expression string, a `RegEx`, from a `RegGrammar` with `Control.Lens.Grammar.regexG`. >>> putStringLn (regexG (type SemVer)) -\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}|-)+)*)? +\p{Nd}+.\p{Nd}+.\p{Nd}+(-(-|\p{Lu}|\p{Ll}|\p{Nd})+(.(-|\p{Lu}|\p{Ll}|\p{Nd})+)*)?(\+(-|\p{Lu}|\p{Ll}|\p{Nd})+(.(-|\p{Lu}|\p{Ll}|\p{Nd})+)*)? You can also generate parsers and printers. @@ -438,7 +438,7 @@ And the `satisfied` pattern is used together with the `Choice` & >>> :{ palindromeG :: CtxGrammatical Char p => p String String palindromeG = rule "palindrome" $ - satisfied (\wrd -> reverse wrd == wrd) >?< manyP (anyToken @Char) + satisfied (\wrd -> reverse wrd == wrd) >?< manyP (tokenAny @Char) :} >>> [pal | word <- ["racecar", "word"], (pal, "") <- parseP (palindromeG :: Parsor String [] String String) word] @@ -499,13 +499,14 @@ Since both t'Parsor' & t'Parsector' are @LL@ parsers they diverge if the `CtxGrammar` they're run on is left-recursive. >>> parsecP (rule "foo" (fail "bar") >|< fail "baz") "abc" -ParsecState {parsecLooked = False, parsecOffset = 0, parsecStream = "abc", parsecFailure = ParsecFailure {parsecExpect = TokenClass (OneOf (fromList "")), parsecLabels = [Node {rootLabel = "foo", subForest = [Node {rootLabel = "bar", subForest = []}]},Node {rootLabel = "baz", subForest = []}]}, parsecResult = Nothing} +ParsecState {parsecLooked = False, parsecOffset = 0, parsecStream = "abc", parsecFailure = ParsecFailure {parsecExpect = fromRangeList [], parsecLabels = [Node {rootLabel = "foo", subForest = [Node {rootLabel = "bar", subForest = []}]},Node {rootLabel = "baz", subForest = []}]}, parsecResult = Nothing} ->>> parsecP (manyP (token 'a') >*< asIn @Char DecimalNumber :: Parsector String (String, Char) (String, Char)) "aaab" -ParsecState {parsecLooked = True, parsecOffset = 3, parsecStream = "b", parsecFailure = ParsecFailure {parsecExpect = TokenClass (Alternate (TokenClass (OneOf (fromList "a"))) (TokenClass (NotOneOf (fromList "") (AndAsIn DecimalNumber))) []), parsecLabels = []}, parsecResult = Nothing} +>>> let failed = parsecP (manyP (token 'a') >*< asIn @Char DecimalNumber :: Parsector String (String, Char) (String, Char)) "aaab" +>>> (parsecOffset failed, parsecStream failed, toList (tokenClass (parsecExpect (parsecFailure failed)) :: RegEx Char)) +(3,"b","a|\\p{Nd}") >>> unparsecP (tokens "abc") "abx" "" -ParsecState {parsecLooked = True, parsecOffset = 2, parsecStream = "ab", parsecFailure = ParsecFailure {parsecExpect = TokenClass (OneOf (fromList "c")), parsecLabels = []}, parsecResult = Nothing} +ParsecState {parsecLooked = True, parsecOffset = 2, parsecStream = "ab", parsecFailure = ParsecFailure {parsecExpect = fromRangeList [('c','c')], parsecLabels = []}, parsecResult = Nothing} -} @@ -517,7 +518,7 @@ Since context-free `Grammar`s and `CtxGrammar`s aren't necessarily regular, the type system will prevent `regexG` from being applied to them. -} regexG - :: forall token. forall a -> (Categorized token, RegGrammar token a) + :: forall token. forall a -> (Lexical token, RegGrammar token a) => RegEx token regexG a = runGrammor (regGrammar @token @a) @@ -528,7 +529,7 @@ the type system will prevent `regbnfG` from being applied to a `CtxGrammar`. It can apply to a `RegGrammar`. -} regbnfG - :: forall token. forall a -> (Categorized token, Grammar token a) + :: forall token. forall a -> (Lexical token, Grammar token a) => Bnf (RegEx token) regbnfG a = runGrammor (grammar @token @a) @@ -549,7 +550,7 @@ usable as an intermediary for further generators like >>> import System.Random >>> let gen = mkStdGen 69 >>> evalState (take 15 <$> regexLang) gen -["","|","\776269","()","[]","\\[","||","|\249908","\770923*","\1008821+","\318904?","\845807|","\477898\1026934","()*","()+"] +["","\818925","|","\291433\946528","\464496*","\1028123+","\912199?","\314471|","()","[]","\\(","|\464083","||","\32659\96026\1004166","\793549\38404*"] >>> import Data.Tree (drawForest) @@ -595,7 +596,7 @@ usable as an intermediary for further generators like -} transducerG - :: forall token. forall a -> (Categorized token, Grammar token a) + :: forall token. forall a -> (Lexical token, Grammar token a) => Transducer token transducerG a = transducer (runGrammor (grammar @token @a)) @@ -609,7 +610,7 @@ from right to left. printG :: forall a string token m. CtxGrammar token a => Cons string string token token - => (IsList string, Item string ~ token, Categorized token) + => (IsList string, Item string ~ token, Lexical token) => (Alternative m, Monad m, Filterable m) => a {- ^ syntax -} -> m (string -> string) @@ -625,7 +626,7 @@ returning a syntax value and the remaining output string. parseG :: forall a string token m. CtxGrammar token a => (Cons string string token token, Snoc string string token token) - => (IsList string, Item string ~ token, Categorized token) + => (IsList string, Item string ~ token, Lexical token) => (Alternative m, Monad m, Filterable m) => string {- ^ input -} -> m (a, string) @@ -644,7 +645,7 @@ making printing to a `String` quadratic. unparseG :: forall a string token m. CtxGrammar token a => (Cons string string token token, Snoc string string token token) - => (IsList string, Item string ~ token, Categorized token) + => (IsList string, Item string ~ token, Lexical token) => (Alternative m, Monad m, Filterable m) => a {- ^ syntax -} -> string {- ^ input -} @@ -664,7 +665,7 @@ and a remaining output `parsecStream`. parsecG :: forall a string token. CtxGrammar token a => (Cons string string token token, Snoc string string token token) - => (Item string ~ token, Categorized token) + => (Item string ~ token, Lexical token) => string {- ^ input -} -> ParsecState string a parsecG = parsecP (ctxGrammar @token @a) @@ -684,7 +685,7 @@ making printing to a `String` quadratic. unparsecG :: forall a string token. CtxGrammar token a => (Cons string string token token, Snoc string string token token) - => (Item string ~ token, Categorized token) + => (Item string ~ token, Lexical token) => a {- ^ syntax -} -> string {- ^ input -} -> ParsecState string a @@ -701,7 +702,7 @@ applicativeG :: forall token a f. ( Grammar token a , Alternative f - , TokenAlgebra token (f token) + , Tokenized token (f token) , TerminalSymbol token (f ()) , forall x. BackusNaurForm (f x) , forall x. Tried (f x) @@ -730,10 +731,9 @@ newtype WrapMega a = WrapMega {unwrapMega :: M.Parsec String String a} ) instance TerminalSymbol Char (WrapMega ()) where terminal str = WrapMega (M.chunk str *> pure ()) -instance TokenAlgebra Char (WrapMega Char) where - tokenClass exam = WrapMega $ M.label (show exam) (M.satisfy (tokenClass exam)) instance Tokenized Char (WrapMega Char) where - anyToken = WrapMega M.anySingle + tokenClass exam = WrapMega $ M.label (show exam) (M.satisfy (tokenClass exam)) + tokenAny = WrapMega M.anySingle token = WrapMega . M.single oneOf = WrapMega . M.oneOf notOneOf = WrapMega . M.noneOf @@ -759,7 +759,7 @@ monadG , MonadPlus m, MonadFail m, Filterable m , forall x. BackusNaurForm (m x) , forall x. Tried (m x) - , TokenAlgebra token (m token) + , Tokenized token (m token) , TerminalSymbol token (m ()) ) => m a diff --git a/distributors-grammar/src/Control/Lens/Grammar/Analysis.hs b/distributors-grammar/src/Control/Lens/Grammar/Analysis.hs index f97851b2..3a3c3e2b 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/Analysis.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/Analysis.hs @@ -72,14 +72,13 @@ foldRegEx tok nonterm = go KleenePlus x -> plusK (go x) KleeneTimes lo hi x -> timesK 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)) + RegExam cls -> tok cls + 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 :: Lexical 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', @@ -88,7 +87,7 @@ rules it names, until they stabilize, as they do for a monotone analysis into a lattice of finite height. -} fixRules - :: (Categorized token, Eq k) + :: (Lexical token, Eq k) => k -- ^ bottom -> (Map String k -> RegEx token -> k) -- ^ a body, given the rules -> Bnf (RegEx token) -> Map String k @@ -103,7 +102,7 @@ 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"))} +Leading {leadingNullable = True, leadingAtoms = fromRangeList [('a','c')]} -} data Leading a = Leading { leadingNullable :: Bool -- ^ whether a word can be empty @@ -125,7 +124,7 @@ instance DisjunctiveMonoid a => KleeneStarAlgebra (Leading a) where {- | The nullability & first tokens of each rule of a t'Bnf'. -} firsts - :: Categorized token + :: Lexical token => Bnf (RegEx token) -> Map String (Leading (TokenClass token)) firsts = fixRules falseP firstOf @@ -133,7 +132,7 @@ firsts = fixRules falseP firstOf given those of the rules it names. -} firstOf - :: Categorized token + :: Lexical token => Map String (Leading (TokenClass token)) -> RegEx token -> Leading (TokenClass token) firstOf rules = @@ -142,7 +141,7 @@ firstOf 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 :: Lexical token => Bnf (RegEx token) -> Set String leftRecursive bnf = Set.filter (\name -> name `Set.member` reach name) names where rules = bnfRules bnf @@ -168,22 +167,22 @@ 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 Lexical token => Eq (Guard token) +deriving stock instance Lexical token => Ord (Guard token) deriving stock instance - (Categorized token, Show (TokenSet token), Show (Categorize token)) + (Lexical token, Show (TokenTest token)) => Show (Guard token) -instance Categorized token => DisjunctiveMonoid (Guard token) where +instance Lexical 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 +instance Lexical 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 + :: Lexical token => Leading (TokenClass token) -> Guard token -> Guard token guardOf (Leading nullable atoms) after | nullable = Guard False atoms >|< after @@ -191,7 +190,7 @@ guardOf (Leading nullable atoms) after -- each of a sequence's items, with the guard of what follows it sequenced - :: Categorized token + :: Lexical token => (RegEx token -> Leading (TokenClass token)) -> Guard token -> [RegEx token] -> [(RegEx token, Guard token)] sequenced first after = snd . foldr step (after, []) @@ -202,9 +201,9 @@ sequenced first after = snd . foldr step (after, []) & 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"))})] +fromList [("a",Guard {guardEnd = True, guardNext = fromRangeList [('b','b')]})] -} -follows :: Categorized token => Bnf (RegEx token) -> Map String (Guard token) +follows :: Lexical token => Bnf (RegEx token) -> Map String (Guard token) follows bnf = go (falseP <$ rules) where rules = bnfRules bnf @@ -224,7 +223,7 @@ follows bnf = go (falseP <$ rules) 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)) + Alternate x y zs -> Map.unionsWith (>|<) (map (followed after) (x : y : zs)) _ -> Map.empty where again x = Guard False (leadingAtoms (first x)) >|< after @@ -251,7 +250,7 @@ since a predictive parser then tries what follows anew. [] -} ll1Conflicts - :: Categorized token => Bnf (RegEx token) -> [LL1Conflict token] + :: Lexical token => Bnf (RegEx token) -> [LL1Conflict token] ll1Conflicts bnf = [ LL1Conflict (Just name) LL1LeftRecursion falseP (NonTerminal name) | name <- Set.toList (leftRecursive bnf) @@ -274,7 +273,7 @@ ll1Conflicts bnf = 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) -> + 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) _ -> [] @@ -319,9 +318,9 @@ data LL1Conflict token = LL1Conflict , conflictTokens :: TokenClass token , conflictAt :: RegEx token } -deriving stock instance Categorized token => Eq (LL1Conflict token) +deriving stock instance Lexical token => Eq (LL1Conflict token) deriving stock instance - (Categorized token, Show (TokenSet token), Show (Categorize token)) + (Lexical token, Show (TokenTest token)) => Show (LL1Conflict token) -- | Sorts of `LL1Conflict`s. @@ -343,7 +342,7 @@ data LL1ConflictSort -- | 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 :: Lexical 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 9fb8c5ac..1d4a96ba 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/BackusNaur.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/BackusNaur.hs @@ -110,7 +110,7 @@ class Tried p where @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) + , forall x y. (x ~ token, y ~ token) => Tokenized token (p x y) , Alternator p , forall x y. Tried (p x y) ) :: Constraint diff --git a/distributors-grammar/src/Control/Lens/Grammar/Class.hs b/distributors-grammar/src/Control/Lens/Grammar/Class.hs index d568e61b..f8b693f0 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/Class.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/Class.hs @@ -55,11 +55,11 @@ class CtxGrammar token a where instance CtxGrammar Char Char instance Grammar Char Char where grammar = rule "Char" (regGrammar @Char) -instance RegGrammar Char Char where regGrammar = anyToken @Char +instance RegGrammar Char Char where regGrammar = tokenAny @Char instance CtxGrammar Char String instance Grammar Char String where grammar = rule "String" (regGrammar @Char) -instance RegGrammar Char String where regGrammar = manyP (anyToken @Char) +instance RegGrammar Char String where regGrammar = manyP (tokenAny @Char) instance CtxGrammar Char Natural instance Grammar Char Natural where grammar = rule "Natural" (regGrammar @Char) diff --git a/distributors-grammar/src/Control/Lens/Grammar/Machine.hs b/distributors-grammar/src/Control/Lens/Grammar/Machine.hs index c09b99ba..758aad1a 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/Machine.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/Machine.hs @@ -42,15 +42,15 @@ class Matching word pattern | pattern -> word where (=~) :: word -> pattern -> Bool infix 2 =~ -- instances -instance Categorized token +instance Lexical token => Matching [token] (Transducer token) where word =~ et = acceptsChart n chart where (n, chart) = prefixGen et word -instance Categorized token +instance Lexical token => Matching [token] (Bnf (RegEx token)) where word =~ bnf = word =~ transducer bnf -instance Categorized token +instance Lexical token => Matching [token] (RegEx token) where word =~ pattern = word =~ liftBnf0 pattern instance Matching s (APrism s t a b) where @@ -97,7 +97,7 @@ A transducer is a form of finite state machine that can be run in various ways like `=~`, `expectNext`, `languageSample`, `parseForest` & `unreachableRules`. -} -transducer :: Categorized token => Bnf (RegEx token) -> Transducer token +transducer :: Lexical token => Bnf (RegEx token) -> Transducer token transducer (Bnf start rules) = Transducer { transducerRelations = IntMap.fromList allStates , transducerRules = Map.fromList @@ -125,9 +125,8 @@ transducer (Bnf start rules) = Transducer 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 + Alternate x y zs -> any (rexNullable nm) (x : y : zs) + RegExam _ -> False ruleNames = Map.keys ruleMap @@ -213,25 +212,19 @@ transducer (Bnf start rules) = Transducer 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) - | chars == falseP -> (IntSet.empty, [], nextId, False) + RegExam cls + | cls == falseP -> (IntSet.empty, [], nextId, False) | otherwise -> ( IntSet.singleton nextId - , [(nextId, TransitionTokenClass (TokenClass (OneOf chars)) dests)] + , [(nextId, TransitionTokenClass cls dests)] , nextId + 1 , False ) - RegExam (NotOneOf chars catTest) -> - ( IntSet.singleton nextId - , [(nextId, TransitionTokenClass (TokenClass (NotOneOf chars catTest)) dests)] - , nextId + 1 - , False - ) - RegExam (Alternate rex0 rex1 rexes) -> + Alternate rex0 rex1 rexes -> let rest = case rexes of [] -> rex1 - rex2 : rexes' -> RegExam (Alternate rex1 rex2 rexes') + rex2 : rexes' -> Alternate rex1 rex2 rexes' (firsts1, states1, nextId1, bypass1) = thompson rest nextId dests (firsts0, states0, nextId0, bypass0) = thompson rex0 nextId1 dests in @@ -243,7 +236,7 @@ transducer (Bnf start rules) = Transducer {- | The parse forest of a string of tokens. -} parseForest - :: Categorized token + :: Lexical token => Transducer token -> [token] -- ^ string -> ([Tree (String, Int, Int, [token])], [token]) @@ -350,7 +343,7 @@ parseForest et word = (concat (itemForests Set.empty Nothing 0 acceptedLen 0), d ] prefixGen - :: Categorized token + :: Lexical token => Transducer token -> [token] -> (Int, IntMap (IntMap IntSet)) @@ -380,7 +373,7 @@ A `falseP` result means the current chart has no scanner transitions, i.e. the prefix is a dead end for recognition. -} expectNext - :: Categorized token + :: Lexical token => Transducer token -> [token] {- ^ prefix -} -> TokenClass token expectNext et word = anyP fst (scanClassOptions et n chart) where @@ -416,10 +409,10 @@ unreachableRules et = `languageSample` lazily produces all words in a language from shortest to longest. However since t'TokenClass'es can resolve to infinite sets of tokens, and the relevant case of `Char` tokens while not infinite is huge, -it samples tokens in an `Applicative` `TokenAlgebra`. +it samples tokens in an `Applicative` `Tokenized`. -} languageSample - :: (TokenAlgebra token (f token), Applicative f) + :: (Tokenized token (f token), Applicative f) => Transducer token -- ^ transducer -> f [[token]] languageSample et = sequenceA (fmap sampleWord classWords) @@ -473,7 +466,7 @@ acceptsChart j chart = IntSet.member 0 acceptOrigins -- Group all scanner moves from E_j by token class; each result also carries the -- closed successor chart at j+1. scanClassOptions - :: Categorized token + :: Lexical token => Transducer token -> Int -> IntMap (IntMap IntSet) diff --git a/distributors-grammar/src/Control/Lens/Grammar/RegEx.hs b/distributors-grammar/src/Control/Lens/Grammar/RegEx.hs index ec500d5d..702aa119 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/RegEx.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/RegEx.hs @@ -31,9 +31,11 @@ import Control.Lens.Grammar.BackusNaur import Control.Lens.Grammar.Class import Control.Lens.Grammar.Symbol import Control.Lens.Grammar.Token +import Data.Char (isAscii) import Data.Coerce import Data.Bifunctor.Joker -import Data.List (nub) +import Data.List (minimumBy, nub) +import Data.Ord (comparing) import Data.MemoTrie import Data.Monoid.Disjunctive import Data.Profunctor @@ -56,7 +58,7 @@ import Text.ParserCombinators.ReadP (readP_to_S) -- >>> import GHC.Exts (toList) {- | The `RegEx`pression type forms the prototypical `KleeneStarAlgebra`. -It is also a `TokenAlgebra` and `tokenClass` acts homomorphically on disjunction. +It is also a `Tokenized` and `tokenClass` acts homomorphically on disjunction. `RegEx`pressions may be understood as normalizations of `KleeneStarAlgebra` expressions generated by lexical token expressions. -} @@ -76,59 +78,54 @@ data RegEx token | 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)) + -- | Two or more alternatives, none of them alternatives, in order. + | Alternate (RegEx token) (RegEx token) [RegEx token] + -- | A single token of a class. + | RegExam (TokenClass token) --instances deriving stock instance Generic (RegEx token) -deriving stock instance Categorized token => Eq (RegEx token) -deriving stock instance Categorized token => Ord (RegEx token) +deriving stock instance Lexical token => Eq (RegEx token) +deriving stock instance Lexical token => Ord (RegEx token) deriving stock instance - (Categorized token, Read (TokenSet token), Read (Categorize token)) + (Lexical token, Read (TokenTest token)) => Read (RegEx token) deriving stock instance - (Categorized token, Show (TokenSet token), Show (Categorize token)) + (Lexical token, Show (TokenTest token)) => Show (RegEx token) -instance Categorized token => TerminalSymbol token (RegEx token) where +instance Lexical token => TerminalSymbol token (RegEx token) where terminal = foldl (\acc t -> acc <> token t) mempty instance NonTerminalSymbol (RegEx token) where nonTerminal = NonTerminal -instance Categorized token => Tokenized token (RegEx token) where - anyToken = RegExam anyToken - token = RegExam . token - oneOf = RegExam . oneOf - notOneOf = RegExam . notOneOf - asIn = RegExam . asIn - notAsIn = RegExam . notAsIn - tokenRange lo = RegExam . tokenRange lo -instance Categorized token => TokenAlgebra token (RegEx token) where - tokenClass = foldTokenClass RegExam -instance Categorized token => Monoid (RegEx token) where +instance Lexical token => Tokenized token (RegEx token) where + tokenClass = RegExam +instance Lexical token => Monoid (RegEx token) where mempty = SeqEmpty -- | Sequences are associative, as items normalized by `sequenced`. -instance Categorized token => Semigroup (RegEx token) where +instance Lexical token => Semigroup (RegEx token) where rex0 <> rex1 = sequenced (items rex0 <> items rex1) -- | Alternatives are associative, as normalized by `alternated`. -instance Categorized token => DisjunctiveMonoid (RegEx token) where - falseP = RegExam (OneOf falseP) +instance Lexical token => DisjunctiveMonoid (RegEx token) where + falseP = RegExam falseP rex0 >|< rex1 = alternated (alternatives rex0 <> alternatives rex1) -instance Categorized token => KleeneStarAlgebra (RegEx token) where - optK (RegExam exam) | isFailExam exam = mempty +instance Lexical token => KleeneStarAlgebra (RegEx token) where + optK (RegExam cls) | cls == falseP = mempty optK SeqEmpty = mempty optK (KleenePlus rex) = starK rex optK rex@(KleeneStar _) = rex optK rex@(KleeneOpt _) = rex optK rex = KleeneOpt rex - starK (RegExam exam) | isFailExam exam = mempty + starK (RegExam cls) | cls == falseP = mempty starK SeqEmpty = mempty starK rex = KleeneStar rex - plusK (RegExam exam) | isFailExam exam = falseP + plusK (RegExam cls) | cls == falseP = falseP plusK SeqEmpty = mempty plusK rex = KleenePlus rex timesK lo0 hi rex = case (max 0 lo0, hi) of (lo, Just m) | lo > m -> falseP _ | SeqEmpty <- rex -> mempty - (lo, _) | RegExam exam <- rex, isFailExam exam -> + (lo, _) | RegExam cls <- rex, cls == falseP -> if lo == 0 then mempty else falseP (0, Nothing) -> starK rex (1, Nothing) -> plusK rex @@ -136,7 +133,7 @@ instance Categorized token => KleeneStarAlgebra (RegEx token) where (0, Just 1) -> optK rex (1, Just 1) -> rex (lo, _) -> KleeneTimes lo hi rex -instance (Categorized token, HasTrie token) +instance (Lexical token, HasTrie token, HasTrie (TokenClass token)) => HasTrie (RegEx token) where data (RegEx token :->: b) = RegExTrie { seqEmptyTrie :: b @@ -148,8 +145,7 @@ instance (Categorized token, HasTrie token) , kleenePlusTrie :: RegEx token :->: b , kleeneTimesTrie :: ((Int, Maybe Int), RegEx token) :->: b , backtrackingTrie :: RegEx token :->: b - , oneOfTrie :: [token] :->: b - , notOneOfTrie :: ([token], Either Int [Int]) :->: b + , classTrie :: TokenClass token :->: b } trie f = RegExTrie { seqEmptyTrie = f mempty @@ -161,8 +157,7 @@ instance (Categorized token, HasTrie token) , kleenePlusTrie = trie (f . plusK) , kleeneTimesTrie = trie (f . \((lo, hi), x) -> timesK lo hi x) , backtrackingTrie = trie (f . try) - , oneOfTrie = trie (f . oneOf) - , notOneOfTrie = trie (f . testNotOneOf) + , classTrie = trie (f . RegExam) } untrie rex = \case SeqEmpty -> seqEmptyTrie rex @@ -173,13 +168,8 @@ instance (Categorized token, HasTrie token) 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) (Exts.toList chars) - RegExam (NotOneOf chars (AndAsIn cat)) -> - untrie (notOneOfTrie rex) (Exts.toList chars, Left (fromEnum cat)) - RegExam (NotOneOf chars (AndNotAsIn cats)) -> - untrie (notOneOfTrie rex) - (Exts.toList chars, Right (Set.toList (Set.map fromEnum cats))) - RegExam (Alternate x y zs) -> untrie (alternateTrie rex) (x : y : zs) + RegExam cls -> untrie (classTrie rex) cls + Alternate x y zs -> untrie (alternateTrie rex) (x : y : zs) enumerate rex = mconcat [ [(SeqEmpty, seqEmptyTrie rex)] , first' NonTerminal <$> enumerate (nonTerminalTrie rex) @@ -191,21 +181,8 @@ instance (Categorized token, HasTrie token) , first' (\((lo, hi), x) -> KleeneTimes lo hi x) <$> enumerate (kleeneTimesTrie rex) , first' Backtracking <$> enumerate (backtrackingTrie rex) - , first' (RegExam . OneOf . Exts.fromList) <$> enumerate (oneOfTrie rex) - , first' testNotOneOf <$> enumerate (notOneOfTrie rex) + , first' RegExam <$> enumerate (classTrie rex) ] -testNotOneOf - :: Categorized token - => ([token], Either Int [Int]) -> RegEx token -testNotOneOf (chars, catTest) = RegExam $ NotOneOf - (Exts.fromList chars) - (either (AndAsIn . toEnum) (AndNotAsIn . Set.map toEnum . Set.fromList) catTest) - --- | Whether a token examination fails to match any token. -isFailExam :: Categorized token => TokenExam token alg -> Bool -isFailExam = \case - OneOf tokens' -> tokens' == falseP - _ -> False -- | The items of a sequence. items :: RegEx token -> [RegEx token] @@ -223,7 +200,7 @@ items = \case so that sequences of sequences are associative. -} -sequenced :: Categorized token => [RegEx token] -> RegEx token +sequenced :: Lexical token => [RegEx token] -> RegEx token sequenced rexes | any isFail rexes = falseP | otherwise = case rewrite rexes of @@ -232,7 +209,7 @@ sequenced rexes rex0 : rex1 : rexes' -> Sequence rex0 rex1 rexes' where isFail = \case - RegExam exam -> isFailExam exam + RegExam cls -> cls == falseP _ -> False rewrite xs = maybe xs rewrite (step xs) step = \case @@ -272,10 +249,10 @@ sequenced rexes [] -> Nothing -- | The alternatives of an alternation, with the empty word for an option. -alternatives :: Categorized token => RegEx token -> [RegEx token] +alternatives :: Lexical token => RegEx token -> [RegEx token] alternatives = \case - RegExam (OneOf tokens') | tokens' == falseP -> [] - RegExam (Alternate rex0 rex1 rexes) -> rex0 : rex1 : rexes + RegExam cls | cls == falseP -> [] + Alternate rex0 rex1 rexes -> rex0 : rex1 : rexes KleeneOpt rex -> alternatives rex <> [SeqEmpty] KleeneStar rex -> [KleenePlus rex, SeqEmpty] rex -> [rex] @@ -285,13 +262,13 @@ in place of the first, the empty word makes them optional, & each is kept once, in order, so that alternatives of alternatives are associative. -} -alternated :: Categorized token => [RegEx token] -> RegEx token +alternated :: Lexical token => [RegEx token] -> RegEx token alternated rexes = (if SeqEmpty `elem` rexes then optK else id) $ case nub (unionTokens [rex | rex <- rexes, rex /= SeqEmpty]) of [] -> falseP [rex] -> rex - rex0 : rex1 : rexes' -> RegExam (Alternate rex0 rex1 rexes') + rex0 : rex1 : rexes' -> Alternate rex0 rex1 rexes' where unionTokens xs = case [cls | x <- xs, Just cls <- [tokenOf x]] of [] -> xs @@ -303,9 +280,7 @@ alternated rexes = x : rest -> x : placeFirst union rest [] -> [] tokenOf = \case - RegExam (OneOf tokens') -> Just (TokenClass (OneOf tokens')) - RegExam (NotOneOf tokens' test) -> - Just (TokenClass (NotOneOf tokens' test)) + RegExam cls -> Just cls _ -> Nothing {- | A t'Bnf' consists of a distinguished starting rule @@ -349,7 +324,7 @@ See Might, Darais & Spiewak, [Parsing With Derivatives] (https://matt.might.net/papers/might2011derivatives.pdf). -} diffB - :: (Categorized token, HasTrie token) + :: (Lexical token, HasTrie token, HasTrie (TokenClass token)) => [token] -> Bnf (RegEx token) -> Bnf (RegEx token) diffB prefix (Bnf start rules) = Bnf (foldl' (flip diff1B) start prefix) rules @@ -370,18 +345,11 @@ diffB prefix (Bnf start rules) = KleenePlus y -> diff1B x y <> starK y KleeneTimes lo hi y -> diff1B x y <> timesK (lo - 1) (subtract 1 <$> hi) y - RegExam (OneOf chars) -> - if tokenMember x chars then mempty else falseP - RegExam (NotOneOf chars (AndAsIn cat)) -> - if tokenMember x chars || categorize x /= cat - then falseP else mempty - RegExam (NotOneOf chars (AndNotAsIn cats)) -> - if tokenMember x chars || elem (categorize x) cats - then falseP else mempty - RegExam (Alternate y1 y2 ys) -> anyP (diff1B x) (y1 : y2 : ys) + RegExam cls -> if tokenClass cls x then mempty else falseP + Alternate y1 y2 ys -> anyP (diff1B x) (y1 : y2 : ys) -- | Does a pattern match the empty word? -δ :: (Categorized token, HasTrie token) +δ :: (Lexical token, HasTrie token, HasTrie (TokenClass token)) => Bnf (RegEx token) -> Bool δ (Bnf start rules) = ν start where ν = memo $ \case @@ -392,7 +360,7 @@ diffB prefix (Bnf start rules) = 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) + Alternate y1 y2 ys -> any ν (y1 : y2 : ys) NonTerminal nameY -> any ν (rulesNamed nameY rules) _ -> False @@ -413,11 +381,11 @@ 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 Categorized token => Tried (RegEx token) where +instance Lexical token => Tried (RegEx token) where try rex = case rex of Backtracking _ -> rex SeqEmpty -> rex - RegExam exam | isFailExam exam -> rex + RegExam cls | cls == falseP -> rex _ -> Backtracking rex instance (Ord rule, TerminalSymbol token rule) => TerminalSymbol token (Bnf rule) where @@ -427,15 +395,13 @@ instance (Ord rule, NonTerminalSymbol rule) nonTerminal = liftBnf0 . nonTerminal instance (Ord rule, Tokenized token rule) => Tokenized token (Bnf rule) where - anyToken = liftBnf0 anyToken + tokenAny = liftBnf0 tokenAny token = liftBnf0 . token oneOf = liftBnf0 . oneOf notOneOf = liftBnf0 . notOneOf asIn = liftBnf0 . asIn notAsIn = liftBnf0 . notAsIn tokenRange lo = liftBnf0 . tokenRange lo -instance (Ord rule, TokenAlgebra token rule) - => TokenAlgebra token (Bnf rule) where tokenClass = liftBnf0 . tokenClass instance (Ord rule, KleeneStarAlgebra rule) => KleeneStarAlgebra (Bnf rule) where @@ -453,8 +419,15 @@ instance (Ord rule, Semigroup rule) => Semigroup (Bnf rule) where makeNestedPrisms ''Bnf makeNestedPrisms ''RegEx -makeNestedPrisms ''TokenExam -makeNestedPrisms ''CategoryTest + +{- | The forms of a class of characters, in regular expression strings: +listed, or not listed, of a category, or of none of some categories. -} +data ClassForm + = ClassOneOf (TokenRanges Char) + | ClassNotOneOf (TokenRanges Char) KindForm +data KindForm = AndAsIn GeneralCategory | AndNotAsIn (Set GeneralCategory) +makeNestedPrisms ''ClassForm +makeNestedPrisms ''KindForm makeNestedPrisms ''GeneralCategory {- | The context-free `Grammar` @@ -485,7 +458,7 @@ with @Control.Lens.Grammar.regexG@. 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"))) []) +Alternate (Sequence (RegExam (fromRangeList [('a','a')])) (RegExam (fromRangeList [('b','b')])) []) (RegExam (fromRangeList [('c','c')])) [] They're similar to regular expression strings in many other programming languages. We can use them to see if a word and pattern @@ -530,7 +503,7 @@ as well as the wildcard, matching any single character. >>> toList (falseP :: RegEx Char) "[]" ->>> toList (anyToken :: RegEx Char) +>>> toList (tokenAny :: RegEx Char) "[^]" Additional forms of character classes test for a character's `GeneralCategory`. @@ -599,8 +572,16 @@ regexGrammar = ruleRec "regex" altG seqG rex = rule "sequence" $ iso itemsOf mconcat >~ manyP (exprG rex) - alternativesOf = \case - RegExam (Alternate rex0 rex1 rexes) -> rex0 : rex1 : rexes + -- a class which prints as one form; others print as alternatives + _RegExamOne = prism' RegExam $ \case + RegExam cls | [_] <- bestForms cls -> Just cls + _ -> Nothing + -- a class prints as alternatives where they're shorter, parsing back to it + alternativesOf = concatMap splitClass . \case + Alternate rex0 rex1 rexes -> rex0 : rex1 : rexes + rex -> [rex] + splitClass = \case + RegExam cls -> RegExam . classOfForm <$> bestForms cls rex -> [rex] itemsOf = \case @@ -631,7 +612,7 @@ regexGrammar = ruleRec "regex" altG atomG rex = rule "atom" $ orP [ _NonTerminal >? terminal "\\q" >* nonterminalG , _Backtracking >? terminal "\\t{" >* rex *< terminal "}" - , _RegExam >? classG + , _RegExamOne >? classG , terminal "(" >* rex *< terminal ")" ] @@ -668,9 +649,10 @@ regexGrammar = ruleRec "regex" altG , _NotAssigned >? terminal "Cn" ] - classG = rule "class" $ orP - [ _OneOf >? classOneOfG - , _NotOneOf >? classNotOneOfG + -- a class prints by its shortest form, & parses by any, an improper iso + classG = rule "class" $ iso bestForm classOfForm >~ orP + [ _ClassOneOf >? classOneOfG + , _ClassNotOneOf >? classNotOneOfG ] classCatG = rule "class-category" $ orP @@ -696,8 +678,8 @@ regexGrammar = ruleRec "regex" altG classCharG >*< optionalP (terminal "-" >* classCharG)) -- ranges, of the set's own form, are never enumerated runOf (lo, hi0) = let hi = fromMaybe lo hi0 in - if lo > hi then falseP else Ranges (RSet.singletonRange (lo, hi)) - runsOf (Ranges chars) = concatMap run (RSet.toRangeList chars) + if lo > hi then falseP else TokenRanges (RSet.singletonRange (lo, hi)) + runsOf (TokenRanges chars) = concatMap run (RSet.toRangeList chars) -- 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' -> @@ -723,7 +705,55 @@ regexGrammar = ruleRec "regex" altG 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 + plain c = c `notElem` ('-' : charsReserved) && tokenKind c /= Control + classOfForm = TokenClass . \case + ClassOneOf chars -> chars + ClassNotOneOf chars kinds -> notP chars >&< kindsOf kinds + kindsOf = \case + AndAsIn cat -> categoryOf cat + AndNotAsIn cats -> notP (testKinds @Char (TokenKinds cats)) + categoryOf cat = testKinds @Char (TokenKinds (Set.singleton cat)) + -- listed, or not listed & of none of the categories it excludes, + -- or not listed & of a category including it + bestForm :: TokenClass Char -> ClassForm + bestForm (TokenClass chars) = minimumBy (comparing formCost) $ + ClassOneOf chars + : ClassNotOneOf (notP chars >&< notP (testKinds @Char (TokenKinds outs))) (AndNotAsIn outs) + : [ ClassNotOneOf (categoryOf cat >&< notP chars) (AndAsIn cat) + | cat <- [minBound .. maxBound] + , chars >&< notP (categoryOf cat) == falseP ] + where + outs = Set.fromList + [cat | cat <- [minBound .. maxBound], categoryOf cat >&< chars == falseP] + -- a class as alternatives: its best form, or else the rest of it, + -- & the categories wholly within it, each, or by the others + bestForms :: TokenClass Char -> [ClassForm] + bestForms (TokenClass chars) + | null ins = [bestForm (TokenClass chars)] + | otherwise = minimumBy (comparing (sum . map formCost)) + [ [bestForm (TokenClass chars)] + , restForms <> map (ClassNotOneOf falseP . AndAsIn) ins + , restForms <> [ClassNotOneOf falseP (AndNotAsIn partials)] + ] + where + cats = [minBound .. maxBound] + ins = [cat | cat <- cats, categoryOf cat >&< notP chars == falseP] + partials = Set.fromList [cat | cat <- cats, cat `notElem` ins] + rest = chars >&< notP (testKinds @Char (TokenKinds (Set.fromList ins))) + restForms = [bestForm (TokenClass rest) | rest /= falseP] + -- the estimated length of a form's string + formCost = \case + ClassOneOf chars -> 2 + rangesCost chars + ClassNotOneOf chars kinds -> 3 + rangesCost chars + case kinds of + AndAsIn _ -> 5 + AndNotAsIn cats -> if Set.null cats then 0 else 4 + 3 * Set.size cats + rangesCost = sum . map runCost . runsOf + runCost (lo, hi) = charCost lo + maybe 0 ((1 +) . charCost) hi + charCost c + | not (isAscii c) = 10 + | plain c = 1 + | c `elem` ('-' : charsReserved) = 2 + | otherwise = 4 :: Int nonterminalG :: Grammatical Char p => p String String nonterminalG = rule "nonterminal" $ diff --git a/distributors-grammar/src/Control/Lens/Grammar/Token.hs b/distributors-grammar/src/Control/Lens/Grammar/Token.hs index c7807fed..f974a968 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/Token.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/Token.hs @@ -13,39 +13,36 @@ module Control.Lens.Grammar.Token Tokenized (..) , satisfy , tokens - -- * Categorized - , Categorized (..) - , Ranges (..) - , GeneralCategory (..) - -- * TokenAlgebra - , TokenAlgebra (..) + -- * Lexical + , Lexical (..) , TokenClass (..) - , foldTokenClass - , TokenExam (..) - , CategoryTest (..) + , GeneralCategory (..) + -- * Tests + , TokenKinds (..) + , TokenRanges (..) + , Cofinite (..) + , cofiniteMember + , ByKind (..) + , testByKind ) where import Control.Lens import Control.Lens.PartialIso import Control.Monad.Loops (iterateUntil) +import Data.Set (Set) +import qualified Data.Set as Set import Data.Bifunctor.Joker import Data.Char import Data.Foldable -import Data.List (nub) -import Data.Maybe (fromMaybe) import Data.Profunctor import Data.Monoid.Disjunctive -import Data.Profunctor.Distributor import Data.Profunctor.Monoidal -import Data.Set (Set) -import qualified Data.Set as Set import Data.RangeSet.Map (RSet) import qualified Data.RangeSet.Map as RSet import GHC.Exts (IsList (Item)) import qualified GHC.Exts as Exts import qualified Text.Read as Read import Text.Read (readPrec) -import GHC.Generics (Generic, Generic1) import Data.Word import Control.Monad.State (StateT, state) import System.Random (RandomGen, Random, random, randomR) @@ -58,164 +55,193 @@ 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. ->>> :kind! Categorize Char -Categorize Char :: * -= GeneralCategory ->>> categorize 'a' +import qualified Data.Map.Strict as Map +import Data.MemoTrie (HasTrie (..), (:->:)) +import Data.Bifunctor (first) +import Data.Map.Strict (Map) + +{- | `Lexical` tokens have kinds, telling their lexical roles, like +an identifier's or a keyword's, or a character's `GeneralCategory`, +& a `BooleanAlgebra` of tests of them, `TokenTest`s, generated by tests +of which tokens they are, of which kinds they are, & of which ranges +they're in, where they're enumerable. + +>>> tokenKind 'a' LowercaseLetter + +Each test has one form, so that `TokenTest`s are equal just when they +test alike, & `tokenTest` is a homomorphism of `BooleanAlgebra`s. + +> prop> tokenTest trueP = const True +> prop> tokenTest (notP x) = not . tokenTest x +> prop> tokenTest (x >|< y) t = tokenTest x t || tokenTest y t +> prop> tokenTest (x >&< y) t = tokenTest x t && tokenTest y t +> prop> tokenTest (testOneOf ts) = (`elem` ts) +> prop> tokenTest (testKinds (TokenKinds ks)) = (`Set.member` ks) . tokenKind +> prop> tokenTest (testRange lo hi) t = lo <= t && t <= hi -} class - ( Ord token, Ord (Categorize token), Enum (Categorize token) - , Ord (TokenSet token), DisjunctiveMonoid (TokenSet token) - , IsList (TokenSet token), Item (TokenSet token) ~ token - ) => Categorized token where - type Categorize token - type Categorize token = () - categorize :: token -> Categorize token - default categorize :: Categorize token ~ () => token -> Categorize token - categorize _ = () - - {- | Sets of tokens, a `Set` by default, each set having one form, - so that its `Eq` is its sets' equality; empty by `falseP`, - unioned by `>|<`, & listed by `IsList`, in ascending order. -} - type TokenSet token - type TokenSet token = Set token - {- | Is a token a member of a set? -} - tokenMember :: token -> TokenSet token -> Bool - default tokenMember - :: TokenSet token ~ Set token => token -> TokenSet token -> Bool - tokenMember = Set.member - {- | The tokens of both sets. -} - tokenIntersection :: TokenSet token -> TokenSet token -> TokenSet token - default tokenIntersection - :: TokenSet token ~ Set token - => TokenSet token -> TokenSet token -> TokenSet token - tokenIntersection = Set.intersection - {- | The tokens of a set, but not of another. -} - tokenDifference :: TokenSet token -> TokenSet token -> TokenSet token - default tokenDifference - :: TokenSet token ~ Set token - => TokenSet token -> TokenSet token -> TokenSet token - tokenDifference = Set.difference - {- | The tokens between two, inclusive, by their enumeration, none where - they're out of order. -} - tokenRangeSet :: Enum token => token -> token -> TokenSet token - default tokenRangeSet - :: (Enum token, TokenSet token ~ Set token) - => token -> token -> TokenSet token - tokenRangeSet lo hi = Set.fromList [lo .. hi] -instance Categorized Char where - type Categorize Char = GeneralCategory - categorize = generalCategory - type TokenSet Char = Ranges Char - tokenMember x (Ranges xs) = RSet.member x xs - tokenIntersection (Ranges xs) (Ranges ys) = Ranges (RSet.intersection xs ys) - tokenDifference (Ranges xs) (Ranges ys) = Ranges (RSet.difference xs ys) - tokenRangeSet lo hi - | lo > hi = falseP - | otherwise = Ranges (RSet.singletonRange (lo, hi)) -instance Categorized Word8 -instance Categorized () - -{- | Sets of enumerable tokens, by their disjoint ranges, of -[range-set-list](https://hackage.haskell.org/package/range-set-list), -each set having one form, so that its `Eq` is its sets' equality; -a `BooleanAlgebra` of bounded tokens. They `Show` & `Read` as a `Set` -does, by their tokens' list. + ( Ord token + , Ord (TokenKind token), Enum (TokenKind token), Bounded (TokenKind token) + , BooleanAlgebra (TokenTest token), Ord (TokenTest token) + ) => Lexical token where + + {- | The kinds of tokens, none but @()@ by default. -} + type TokenKind token + type TokenKind token = () + {- | A token's kind. -} + tokenKind :: token -> TokenKind token + default tokenKind :: TokenKind token ~ () => token -> TokenKind token + tokenKind _ = () + + {- | The tests of tokens, `Cofinite` sets of them by default. -} + type TokenTest token + type TokenTest token = Cofinite token + {- | Does a token pass a test? -} + tokenTest :: TokenTest token -> token -> Bool + default tokenTest + :: TokenTest token ~ Cofinite token => TokenTest token -> token -> Bool + tokenTest = flip cofiniteMember + {- | The test of being one of some tokens. -} + testOneOf :: [token] -> TokenTest token + default testOneOf + :: TokenTest token ~ Cofinite token => [token] -> TokenTest token + testOneOf = Finite . Set.fromList + {- | The test of being of one of some kinds. -} + testKinds :: TokenKinds (TokenKind token) -> TokenTest token + default testKinds + :: (TokenTest token ~ Cofinite token, TokenKind token ~ ()) + => TokenKinds (TokenKind token) -> TokenTest token + testKinds = kindless + {- | The test of being between two tokens, inclusive, by their + enumeration, for tokens whose `Enum` & `Ord` agree. -} + testRange :: Enum token => token -> token -> TokenTest token + testRange lo hi = testOneOf [lo .. hi] + {- | The tokens which pass a test, by their number & their index, + where they're finitely many & listable, so that generators sample them + uniformly, rather than by rejection. -} + testFinite :: TokenTest token -> Maybe (Int, Int -> token) + default testFinite + :: TokenTest token ~ Cofinite token + => TokenTest token -> Maybe (Int, Int -> token) + testFinite = \case + Finite ts -> Just (Set.size ts, (`Set.elemAt` ts)) + Cofinite _ -> Nothing + +instance Lexical Char where + type TokenKind Char = GeneralCategory + tokenKind = generalCategory + type TokenTest Char = TokenRanges Char + tokenTest = flip rangesMember + testOneOf = Exts.fromList + testKinds (TokenKinds cats) = foldr ((>|<) . categoryRanges) falseP cats + testRange = rangesBetween + testFinite = rangesFinite +instance Lexical Word8 where + type TokenTest Word8 = TokenRanges Word8 + tokenTest = flip rangesMember + testOneOf = Exts.fromList + testKinds = kindless + testRange = rangesBetween + testFinite = rangesFinite +instance Lexical () where + type TokenTest () = TokenRanges () + tokenTest = flip rangesMember + testOneOf = Exts.fromList + testKinds = kindless + testRange = rangesBetween + testFinite = rangesFinite + +-- | Tests of kinds, where there are none but @()@. +kindless :: BooleanAlgebra test => TokenKinds () -> test +kindless (TokenKinds ks) = if Set.null ks then falseP else trueP + +{- | A class of tokens, by their `TokenTest`, a `Tokenized` +`BooleanAlgebra`, such that the following hold. + +> prop> trueP = tokenAny +> prop> falseP = oneOf [] +> prop> notP . oneOf = notOneOf +> prop> notP . asIn = notAsIn -} -newtype Ranges token = Ranges (RSet token) - deriving newtype (Eq, Ord) -instance (Ord token, Enum token) => IsList (Ranges token) where - type Item (Ranges token) = token - fromList = Ranges . RSet.fromList - toList (Ranges xs) = RSet.toList xs -instance AsEmpty (Ranges token) where - _Empty = nearly (Ranges RSet.empty) (\(Ranges xs) -> RSet.null xs) -instance (Ord token, Enum token) => DisjunctiveMonoid (Ranges token) where - falseP = Ranges RSet.empty - Ranges xs >|< Ranges ys = Ranges (RSet.union xs ys) -instance (Ord token, Enum token, Bounded token) - => BooleanAlgebra (Ranges token) where - trueP = Ranges RSet.full - notP (Ranges xs) = Ranges (RSet.complement xs) - Ranges xs >&< Ranges ys = Ranges (RSet.intersection xs ys) -instance (Ord token, Enum token, Show token) => Show (Ranges token) where - showsPrec d xs = showParen (d > 10) $ - showString "fromList " . shows (Exts.toList xs) -instance (Ord token, Enum token, Read token) => Read (Ranges token) where - readPrec = Read.parens $ ReadPrec.prec 10 $ do - Read.Ident "fromList" <- Read.lexP - Exts.fromList <$> ReadPrec.step readPrec +newtype TokenClass token = TokenClass {classTest :: TokenTest token} +deriving newtype instance Lexical token => Eq (TokenClass token) +deriving newtype instance Lexical token => Ord (TokenClass token) +deriving newtype instance Lexical token => DisjunctiveMonoid (TokenClass token) +deriving newtype instance Lexical token => BooleanAlgebra (TokenClass token) +deriving newtype instance Show (TokenTest token) => Show (TokenClass token) +deriving newtype instance Read (TokenTest token) => Read (TokenClass token) +instance Lexical token => Tokenized token (TokenClass token) where + tokenClass = id + +{- | `Tokenized` combinators for constructing lexical tokens, +each a `tokenClass` by default. + +> prop> tokenAny = tokenClass trueP +> prop> token t = tokenClass (oneOf [t]) + +When a `Tokenized` is a `DisjunctiveMonoid`, then +`tokenClass` is expected to act homomorphically on disjunction. + +> prop> falseP = tokenClass falseP +> prop> tokenClass x >|< tokenClass y = tokenClass (x >|< y) +-} +class Lexical token => Tokenized token p | p -> token where + {-# MINIMAL tokenAny | tokenClass #-} + + {- | A single token of a class. -} + tokenClass :: TokenClass token -> p + default tokenClass + :: (p ~ q token token, Choice q, Cochoice q) + => TokenClass token -> p + tokenClass (TokenClass test) = satisfy (tokenTest test) -{- | `Tokenized` combinators for constructing lexical tokens. -} -class Categorized token => Tokenized token p | p -> token where {- | Any single token. -} - anyToken :: p + tokenAny :: p + tokenAny = tokenClass trueP {- | A single specified `token`. -} token :: token -> p - default token - :: (p ~ q token token, Choice q, Cochoice q) - => token -> p - token = satisfy . token + token t = tokenClass (TokenClass (testOneOf [t])) {- | A single token which is `oneOf` a set. > prop> token x = oneOf [x] - -} oneOf :: Foldable f => f token -> p - default oneOf - :: (p ~ q token token, Choice q, Cochoice q, Foldable f) - => f token -> p - oneOf = satisfy . oneOf + oneOf = tokenClass . TokenClass . testOneOf . toList {- | A single token which is `notOneOf` a set. - - > prop> anyToken = notOneOf [] - + + > prop> tokenAny = notOneOf [] -} notOneOf :: Foldable f => f token -> p - default notOneOf - :: (p ~ q token token, Choice q, Cochoice q, Foldable f) - => f token -> p - notOneOf = satisfy . notOneOf - - {- | A single token which is `asIn` a category. -} - asIn :: Categorize token -> p - default asIn - :: (p ~ q token token, Choice q, Cochoice q) - => Categorize token -> p - asIn = satisfy . asIn + notOneOf = tokenClass . TokenClass . notP . testOneOf . toList - {- | A single token which is `notAsIn` a category. -} - notAsIn :: Categorize token -> p - default notAsIn - :: (p ~ q token token, Choice q, Cochoice q) - => Categorize token -> p - notAsIn = satisfy . notAsIn + {- | A single token which is `asIn` a kind. -} + asIn :: TokenKind token -> p + asIn kind = tokenClass (TokenClass (testKinds @token (TokenKinds (Set.singleton kind)))) + + {- | A single token which is `notAsIn` a kind. -} + notAsIn :: TokenKind token -> p + notAsIn kind = + tokenClass (TokenClass (notP (testKinds @token (TokenKinds (Set.singleton kind))))) {- | A single token between two, inclusive, by their enumeration, - for tokens whose `Enum` & `Ord` agree, taking no more than its ends, - where `oneOf` takes every token of a range. + for tokens whose `Enum` & `Ord` agree. > prop> tokenRange lo hi = oneOf [lo .. hi] -} tokenRange :: Enum token => token -> token -> p - default tokenRange - :: (Enum token, p ~ q token token, Choice q, Cochoice q) - => token -> token -> p - tokenRange lo hi = satisfy (tokenRange lo hi) + tokenRange lo hi = tokenClass (TokenClass (testRange lo hi)) {- | A single token that satisfies a predicate. -} satisfy :: (Tokenized a (p a a), Choice p, Cochoice p) => (a -> Bool) -> p a a -satisfy f = satisfied f >?< anyToken +satisfy f = satisfied f >?< tokenAny {- | A specified stream of `tokens`. -} tokens @@ -227,19 +253,19 @@ tokens tokens = foldr ((>:<) . token) asEmpty -- instances -instance Categorized token => Tokenized token (token -> Bool) where - anyToken _ = True +instance Lexical token => Tokenized token (token -> Bool) where + tokenClass (TokenClass test) = tokenTest test + tokenAny _ = True token = (==) - -- Tokens are collected into a `Set` once, & tested logarithmically. - oneOf xs = (`Set.member` members) where members = Set.fromList (toList xs) - notOneOf xs = (`Set.notMember` members) - where members = Set.fromList (toList xs) - asIn = lmap categorize . (==) - notAsIn = lmap categorize . (/=) + asIn = lmap tokenKind . (==) + notAsIn = lmap tokenKind . (/=) tokenRange lo hi x = lo <= x && x <= hi +deriving via (token -> Bool) instance Lexical token + => Tokenized token (Predicate token) instance Tokenized token (f token) => Tokenized token (Joker f token token) where - anyToken = Joker (anyToken @token) + tokenClass = Joker . tokenClass @token + tokenAny = Joker (tokenAny @token) token = Joker . token @token oneOf = Joker . oneOf @token notOneOf = Joker . notOneOf @token @@ -247,314 +273,172 @@ instance Tokenized token (f token) notAsIn = Joker . notAsIn @token tokenRange lo hi = Joker (tokenRange @token lo hi) instance Tokenized Char (ReadP Char) where - anyToken = ReadP.get + tokenClass = ReadP.satisfy . tokenClass + tokenAny = ReadP.get token = ReadP.char - oneOf = ReadP.satisfy . oneOf - notOneOf = ReadP.satisfy . notOneOf - asIn = ReadP.satisfy . asIn - notAsIn = ReadP.satisfy . notAsIn - tokenRange lo hi = ReadP.satisfy (tokenRange lo hi) instance Tokenized Char (ReadPrec Char) where - anyToken = ReadPrec.lift anyToken + tokenClass = ReadPrec.lift . tokenClass + tokenAny = ReadPrec.lift tokenAny token = ReadPrec.lift . token - oneOf = ReadPrec.lift . oneOf - notOneOf = ReadPrec.lift . notOneOf - asIn = ReadPrec.lift . asIn - notAsIn = ReadPrec.lift . notAsIn - tokenRange lo hi = ReadPrec.lift (tokenRange lo hi) -deriving via (token -> Bool) instance Categorized token - => Tokenized token (Predicate token) -instance (Categorized token, Arbitrary token) => Tokenized token (Gen token) where - anyToken = arbitrary @token +instance (Lexical token, Arbitrary token) => Tokenized token (Gen token) where + -- finitely many tokens are sampled uniformly, & others by rejection + tokenClass (TokenClass test) = case testFinite test of + Just (n, nth) | n > 0 -> nth <$> Gen.chooseInt (0, n - 1) + _ -> arbitrary `Gen.suchThat` tokenTest test + tokenAny = arbitrary @token token = pure - oneOf = Gen.elements . toList - notOneOf xs = arbitrary `Gen.suchThat` (`notElem` xs) - asIn cat = arbitrary `Gen.suchThat` ((==) cat . categorize) - notAsIn cat = arbitrary `Gen.suchThat` ((/=) cat . categorize) - tokenRange lo hi = toEnum <$> Gen.chooseInt (fromEnum lo, fromEnum hi) -instance (RandomGen g, Monad m, Categorized token, Random token) +instance (RandomGen g, Monad m, Lexical token, Random token) => Tokenized token (StateT g m token) where - anyToken = state random + tokenClass (TokenClass test) = case testFinite test of + Just (n, nth) | n > 0 -> nth <$> state (randomR (0, n - 1)) + _ -> iterateUntil (tokenTest test) tokenAny + tokenAny = state random token = pure - oneOf xs = do - let ys = toList xs - i <- state (randomR (0, length ys - 1)) - pure (ys !! i) - notOneOf xs = iterateUntil (`notElem` xs) anyToken - asIn cat = iterateUntil ((== cat) . categorize) anyToken - notAsIn cat = iterateUntil ((/= cat) . categorize) anyToken - tokenRange lo hi = toEnum <$> state (randomR (fromEnum lo, fromEnum hi)) - -{- | A token examination, by the tokens it accepts, & the alternatives -of an algebra, whose fixed point is t'TokenClass'. Both t'TokenClass'es & -`Control.Lens.Grammar.RegEx.RegEx`pressions are algebras over it. --} -data TokenExam token alg - = OneOf (TokenSet token) - | NotOneOf (TokenSet token) (CategoryTest token) - {- | Two or more alternatives, none of them alternatives, - in the order they're written. - -} - | Alternate alg alg [alg] - -failExam :: Categorized token => TokenExam token alg -failExam = OneOf falseP - -passExam :: Categorized token => TokenExam token alg -passExam = NotOneOf falseP (AndNotAsIn Set.empty) - -isFailExam :: Categorized token => TokenExam token alg -> Bool -isFailExam (OneOf xs) = xs == falseP -isFailExam _ = False - -isPassExam :: Categorized token => TokenExam token alg -> Bool -isPassExam (NotOneOf xs (AndNotAsIn ys)) = xs == falseP && Set.null ys -isPassExam _ = False - --- | The alternatives of an examination of t'TokenClass'es. -examAlternatives - :: TokenExam token (TokenClass token) -> [TokenExam token (TokenClass token)] -examAlternatives = \case - Alternate x y zs -> [exam | TokenClass exam <- x : y : zs] - exam -> [exam] - -{- | Alternatives, normalized: any which passes every token passes, -those which fail none are dropped, those of `OneOf` some tokens are one, -in place of the first, & each is kept once, in order, so that the -alternatives of alternatives are associative. --} -alternatives - :: Categorized token - => [TokenExam token (TokenClass token)] -> TokenExam token (TokenClass token) -alternatives exams - | any isPassExam exams = passExam - | otherwise = case nub (unionOneOfs (filter (not . isFailExam) exams)) of - [] -> failExam - [exam] -> exam - exam0 : exam1 : exams' -> - Alternate (TokenClass exam0) (TokenClass exam1) (map TokenClass exams') - where - unionOneOfs xs = case [tokens' | OneOf tokens' <- xs] of - [] -> xs - tokenss -> placeFirst (OneOf (foldr (>|<) falseP tokenss)) xs - placeFirst union = \case - OneOf _ : rest -> union : [x | x <- rest, not (isOneOf x)] - x : rest -> x : placeFirst union rest - [] -> [] - isOneOf = \case - OneOf _ -> True - _ -> False - -{- | `CategoryTest`s for `Categorized` tokens, -taken in conjunction with `NotOneOf` some `Set` of tokens. --} -data CategoryTest token - = AndAsIn (Categorize token) - | AndNotAsIn (Set (Categorize token)) - -{- | t'TokenClass' forms a `Tokenized` `BooleanAlgebra`, -such that the following invariants hold. - -> prop> trueP = anyToken -> prop> trueP = notOneOf [] -> prop> falseP = oneOf [] -> prop> notP . oneOf = notOneOf -> prop> notP . notOneOf = oneOf -> prop> notP . asIn = notAsIn -> prop> notP . notAsIn = asIn -t'TokenClass' is the fixed point algebra of t'TokenExam'. -t'TokenClass'es may be understood as normalizations of -`BooleanAlgebra` expressions generated by `Tokenized` -expressions. +{- | Tests of kinds, any set of them, a `BooleanAlgebra` of bounded, +enumerable kinds, complementing within all of them. -} +newtype TokenKinds kind = TokenKinds (Set kind) + deriving stock (Eq, Ord, Show, Read) +instance Ord kind => DisjunctiveMonoid (TokenKinds kind) where + falseP = TokenKinds Set.empty + TokenKinds xs >|< TokenKinds ys = TokenKinds (Set.union xs ys) +instance (Ord kind, Enum kind, Bounded kind) + => BooleanAlgebra (TokenKinds kind) where + trueP = TokenKinds (Set.fromList [minBound .. maxBound]) + notP (TokenKinds xs) = TokenKinds (Set.fromList [minBound .. maxBound] Set.\\ xs) + TokenKinds xs >&< TokenKinds ys = TokenKinds (Set.intersection xs ys) + +{- | Tests of enumerable tokens, by their disjoint ranges, of +[range-set-list](https://hackage.haskell.org/package/range-set-list), +a `BooleanAlgebra` of bounded tokens, each test having one form. +They `Show` & `Read` by their ranges' list. -} -newtype TokenClass token = TokenClass (TokenExam token (TokenClass token)) - --- | Fold a t'TokenClass' by an algebra of its t'TokenExam's. -foldTokenClass :: (TokenExam token a -> a) -> TokenClass token -> a -foldTokenClass alg (TokenClass exam) = alg (foldTokenClass alg <$> exam) - -{- | `TokenAlgebra` extends `Tokenized` methods to support -`BooleanAlgebra` operations within a `tokenClass`. -When a `TokenAlgebra` is a `DisjunctiveMonoid`, -then `tokenClass` is expected to act homomorphically on disjunction. - -> prop> falseP = tokenClass falseP -> prop> tokenClass x >|< tokenClass y = tokenClass (x >|< y) +newtype TokenRanges token = TokenRanges (RSet token) + deriving newtype (Eq, Ord) +instance (Ord token, Enum token) => IsList (TokenRanges token) where + type Item (TokenRanges token) = token + fromList = TokenRanges . RSet.fromList + toList (TokenRanges xs) = RSet.toList xs +instance AsEmpty (TokenRanges token) where + _Empty = nearly (TokenRanges RSet.empty) (\(TokenRanges xs) -> RSet.null xs) +instance (Ord token, Enum token) => DisjunctiveMonoid (TokenRanges token) where + falseP = TokenRanges RSet.empty + TokenRanges xs >|< TokenRanges ys = TokenRanges (RSet.union xs ys) +instance (Ord token, Enum token, Bounded token) + => BooleanAlgebra (TokenRanges token) where + trueP = TokenRanges RSet.full + notP (TokenRanges xs) = TokenRanges (RSet.complement xs) + TokenRanges xs >&< TokenRanges ys = TokenRanges (RSet.intersection xs ys) +instance (Ord token, Enum token, Show token) => Show (TokenRanges token) where + showsPrec d (TokenRanges xs) = showParen (d > 10) $ + showString "fromRangeList " . shows (RSet.toRangeList xs) +instance (Ord token, Enum token, Read token) => Read (TokenRanges token) where + readPrec = Read.parens $ ReadPrec.prec 10 $ do + Read.Ident "fromRangeList" <- Read.lexP + TokenRanges . RSet.fromRangeList <$> ReadPrec.step readPrec -Likewise, when a `TokenAlgebra` is `Control.Applicative.Alternative`, +rangesMember :: Ord token => token -> TokenRanges token -> Bool +rangesMember x (TokenRanges xs) = RSet.member x xs -> prop> empty = tokenClass falseP -> prop> tokenClass x <|> tokenClass y = tokenClass (x >|< y) +rangesBetween :: Ord token => token -> token -> TokenRanges token +rangesBetween lo hi + | lo > hi = TokenRanges RSet.empty + | otherwise = TokenRanges (RSet.singletonRange (lo, hi)) --} -class Tokenized token p => TokenAlgebra token p where - tokenClass :: TokenClass token -> p - default tokenClass - :: (p ~ q token token, Alternator q, Cochoice q) - => TokenClass token -> p - -- Sets of tokens are tested by `Set.member`, logarithmically, - -- rather than by `oneOf`'s & `notOneOf`'s `Foldable`, linearly. - tokenClass = foldTokenClass $ \case - OneOf chars -> satisfy (`tokenMember` chars) - NotOneOf chars (AndAsIn cat) -> - satisfy (notP (`tokenMember` chars) >&< asIn cat) - NotOneOf chars (AndNotAsIn cats) -> - satisfy (notP (`tokenMember` chars) >&< allP notAsIn cats) - Alternate p q ps -> foldr1 (>|<) (p : q : ps) - -deriving stock instance Generic (TokenExam token alg) -deriving stock instance Generic1 (TokenExam token) -deriving stock instance Generic (TokenClass token) -deriving stock instance Generic (CategoryTest token) -deriving stock instance - (Categorized token, Read (TokenSet token), Read (Categorize token)) - => Read (TokenClass token) -deriving stock instance - (Categorized token, Show (TokenSet token), Show (Categorize token)) - => Show (TokenClass token) -deriving newtype instance Categorized token => Eq (TokenClass token) -deriving newtype instance Categorized token => Ord (TokenClass token) -deriving newtype instance Categorized token => Tokenized token (TokenClass token) -deriving newtype instance Categorized token - => DisjunctiveMonoid (TokenClass token) -deriving newtype instance Categorized token => BooleanAlgebra (TokenClass token) -instance Categorized token - => TokenAlgebra token (TokenClass token) where - tokenClass = id -instance Categorized token - => TokenAlgebra token (TokenExam token (TokenClass token)) where - tokenClass (TokenClass exam) = exam -instance Categorized token => TokenAlgebra token (token -> Bool) where - tokenClass = foldTokenClass . flip $ \x -> \case - OneOf xs -> tokenMember x xs - NotOneOf xs (AndAsIn y) -> - not (tokenMember x xs) && categorize x == y - NotOneOf xs (AndNotAsIn ys) -> - not (tokenMember x xs) && Set.notMember (categorize x) ys - Alternate p q ps -> any ($ x) (p : q : ps) -instance TokenAlgebra token (f token) - => TokenAlgebra token (Joker f token token) where - 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 - -- a small set is chosen of uniformly, & a large one, by trying - -- arbitrary tokens, or else its least tokens, never listing it all - OneOf xs -> case splitAt 256 (Exts.toList xs) of - (few, []) -> Gen.elements few - (few, _) -> fromMaybe <$> Gen.elements few - <*> arbitrary `Gen.suchThatMaybe` (`tokenMember` xs) - NotOneOf xs (AndAsIn cat) -> arbitrary `Gen.suchThat` - (\x -> not (tokenMember x xs) && categorize x == cat) - NotOneOf xs (AndNotAsIn cats) -> arbitrary `Gen.suchThat` - (\x -> not (tokenMember x xs) && categorize x `notElem` cats) - Alternate p q ps -> Gen.oneof (p : q : ps) -instance (RandomGen g, Monad m, Categorized token, Random token) - => TokenAlgebra token (StateT g m token) where - tokenClass = foldTokenClass $ \case - OneOf xs -> oneOf (Exts.toList xs) - NotOneOf xs (AndAsIn cat) -> - iterateUntil (\x -> not (tokenMember x xs) && categorize x == cat) anyToken - NotOneOf xs (AndNotAsIn cats) -> - iterateUntil (\x -> not (tokenMember x xs) && categorize x `notElem` cats) anyToken - Alternate p q ps -> do - i <- state (randomR (0, length ps + 1)) - (p : q : ps) !! i -instance Categorized token => Tokenized token (TokenExam token alg) where - anyToken = passExam - token a = OneOf (Exts.fromList [a]) - oneOf as | null as = failExam - oneOf as = OneOf (Exts.fromList (toList as)) - notOneOf as | null as = passExam - notOneOf as = - NotOneOf (Exts.fromList (toList as)) (AndNotAsIn Set.empty) - asIn cat = NotOneOf falseP (AndAsIn cat) - notAsIn cat = NotOneOf falseP (AndNotAsIn (Set.singleton cat)) - tokenRange lo hi = OneOf (tokenRangeSet lo hi) -instance Categorized token - => DisjunctiveMonoid (TokenExam token (TokenClass token)) where - falseP = failExam - x >|< y = alternatives (examAlternatives x <> examAlternatives y) -instance Categorized token - => BooleanAlgebra (TokenExam token (TokenClass token)) where - trueP = passExam - notP exam | isFailExam exam = passExam - notP exam | isPassExam exam = failExam - notP (Alternate x y zs) = - foldr1 (>&<) [notP exam | TokenClass exam <- x : y : zs] - notP (OneOf xs) = notOneOf (Exts.toList xs) - notP (NotOneOf xs (AndAsIn y)) = oneOf (Exts.toList xs) >|< notAsIn y - notP (NotOneOf xs (AndNotAsIn ys)) = oneOf (Exts.toList xs) >|< anyP asIn ys - x >&< y | x == y = x - _ >&< exam | isFailExam exam = failExam - exam >&< _ | isFailExam exam = failExam - x >&< exam | isPassExam exam = x - exam >&< z | isPassExam exam = z - x >&< Alternate y z ws = - foldr1 (>|<) [x >&< exam | TokenClass exam <- y : z : ws] - Alternate x y ws >&< z = - foldr1 (>|<) [exam >&< z | TokenClass exam <- x : y : ws] - OneOf xs >&< OneOf ys = OneOf (tokenIntersection xs ys) - OneOf xs >&< NotOneOf ys (AndAsIn z) = OneOf - (filterTokens (\x -> categorize x == z) (tokenDifference xs ys)) - NotOneOf xs (AndAsIn y) >&< OneOf zs = OneOf - (filterTokens (\z -> categorize z == y) (tokenDifference zs xs)) - OneOf xs >&< NotOneOf ys (AndNotAsIn zs) = OneOf - (notInCategories zs (tokenDifference xs ys)) - NotOneOf xs (AndNotAsIn ys) >&< OneOf zs = OneOf - (notInCategories ys (tokenDifference zs xs)) - NotOneOf xs (AndAsIn y) >&< NotOneOf ws (AndAsIn z) = - if y /= z then failExam else NotOneOf - (filterTokens (\x -> categorize x == y) (xs >|< ws)) (AndAsIn y) - NotOneOf xs (AndAsIn y) >&< NotOneOf ws (AndNotAsIn zs) = - if y `elem` zs then failExam else NotOneOf - (filterTokens (\x -> categorize x == y) (xs >|< ws)) (AndAsIn y) - NotOneOf xs (AndNotAsIn ys) >&< NotOneOf ws (AndAsIn z) = - if z `elem` ys then failExam else NotOneOf - (filterTokens (\x -> categorize x == z) (xs >|< ws)) (AndAsIn z) - NotOneOf xs (AndNotAsIn ys) >&< NotOneOf ws (AndNotAsIn zs) = - let - xws = xs >|< ws - yzs = Set.union ys zs - in - NotOneOf - (notInCategories yzs xws) - (AndNotAsIn yzs) -deriving stock instance - (Categorized token, Read (TokenSet token), Read alg, Read (Categorize token)) - => Read (TokenExam token alg) -deriving stock instance - (Categorized token, Show (TokenSet token), Show alg, Show (Categorize token)) - => Show (TokenExam token alg) -deriving stock instance Functor (TokenExam token) -deriving stock instance Foldable (TokenExam token) -deriving stock instance Traversable (TokenExam token) -deriving stock instance (Categorized token, Eq alg) => Eq (TokenExam token alg) -deriving stock instance (Categorized token, Ord alg) => Ord (TokenExam token alg) -deriving stock instance Categorized token => Eq (CategoryTest token) -deriving stock instance Categorized token => Ord (CategoryTest token) -deriving stock instance - (Categorized token, Read (TokenSet token), Read (Categorize token)) - => Read (CategoryTest token) -deriving stock instance - (Categorized token, Show (TokenSet token), Show (Categorize token)) - => Show (CategoryTest token) - --- | The tokens of a set satisfying a predicate. -filterTokens :: Categorized token => (token -> Bool) -> TokenSet token -> TokenSet token -filterTokens p = Exts.fromList . filter p . Exts.toList - --- | The tokens of a set not in any of some categories, --- not listing the set where there are none. -notInCategories - :: Categorized token - => Set (Categorize token) -> TokenSet token -> TokenSet token -notInCategories cats - | Set.null cats = id - | otherwise = filterTokens (\x -> categorize x `Set.notMember` cats) +-- | The tokens of ranges, by their number & index, listing the ranges. +rangesFinite :: Enum token => TokenRanges token -> Maybe (Int, Int -> token) +rangesFinite (TokenRanges xs) = Just (sum (map size runs), nth runs) + where + runs = RSet.toRangeList xs + size (lo, hi) = fromEnum hi - fromEnum lo + 1 + nth ((lo, hi) : rest) i + | i < size (lo, hi) = toEnum (fromEnum lo + i) + | otherwise = nth rest (i - size (lo, hi)) + nth [] _ = error "rangesFinite: out of range" + +-- | Each `GeneralCategory`'s characters, by their ranges, computed once. +categoryRanges :: GeneralCategory -> TokenRanges Char +categoryRanges cat = Map.findWithDefault falseP cat categoryTable + +categoryTable :: Map GeneralCategory (TokenRanges Char) +categoryTable = Map.fromListWith (>|<) + [ (generalCategory lo, TokenRanges (RSet.singletonRange (lo, hi))) + | (lo, hi) <- runs minBound ] + where + runs lo = + let + cat = generalCategory lo + hi = last' lo (takeWhile ((== cat) . generalCategory) [succ' lo ..]) + in (lo, hi) : if hi == maxBound then [] else runs (succ hi) + succ' c = if c == maxBound then c else succ c + last' x = \case + [] -> x + ys -> last ys + +{- | Tests of tokens, by finite sets of them, or their complements, +a `BooleanAlgebra` each test having one form, where tokens are +infinitely many; for finitely many, `TokenRanges` are. -} +data Cofinite token = Finite (Set token) | Cofinite (Set token) + deriving stock (Eq, Ord, Show, Read) +instance Ord token => DisjunctiveMonoid (Cofinite token) where + falseP = Finite Set.empty + Finite xs >|< Finite ys = Finite (Set.union xs ys) + Finite xs >|< Cofinite ys = Cofinite (ys Set.\\ xs) + Cofinite xs >|< Finite ys = Cofinite (xs Set.\\ ys) + Cofinite xs >|< Cofinite ys = Cofinite (Set.intersection xs ys) +instance Ord token => BooleanAlgebra (Cofinite token) where + trueP = Cofinite Set.empty + notP = \case + Finite xs -> Cofinite xs + Cofinite xs -> Finite xs + Finite xs >&< Finite ys = Finite (Set.intersection xs ys) + Finite xs >&< Cofinite ys = Finite (xs Set.\\ ys) + Cofinite xs >&< Finite ys = Finite (ys Set.\\ xs) + Cofinite xs >&< Cofinite ys = Cofinite (Set.union xs ys) + +cofiniteMember :: Ord token => token -> Cofinite token -> Bool +cofiniteMember x = \case + Finite xs -> Set.member x xs + Cofinite xs -> Set.notMember x xs + +{- | Tests of tokens tagged by their kinds, as a test of their tags +for each kind, a `BooleanAlgebra` of tests, pointwise, each test having +one form, where each kind's has, omitting kinds which `falseP` tests. -} +newtype ByKind kind test = ByKind (Map kind test) + deriving stock (Eq, Ord, Show, Read) +instance (Ord kind, DisjunctiveMonoid test) + => DisjunctiveMonoid (ByKind kind test) where + falseP = ByKind Map.empty + ByKind xs >|< ByKind ys = ByKind (Map.unionWith (>|<) xs ys) +instance (Ord kind, Enum kind, Bounded kind, BooleanAlgebra test, Eq test) + => BooleanAlgebra (ByKind kind test) where + trueP = ByKind (Map.fromList [(k, trueP) | k <- [minBound .. maxBound]]) + notP (ByKind xs) = ByKind $ Map.fromList + [ (k, test) | k <- [minBound .. maxBound] + , let test = notP (Map.findWithDefault falseP k xs), test /= falseP ] + ByKind xs >&< ByKind ys = + ByKind (Map.filter (/= falseP) (Map.intersectionWith (>&<) xs ys)) + +-- | Test a token, tagged by its kind, by its kind's test of its tag. +testByKind :: Ord kind => (test -> tag -> Bool) -> ByKind kind test -> kind -> tag -> Bool +testByKind tested (ByKind xs) kind tag = maybe False (`tested` tag) (Map.lookup kind xs) + +-- memo tries of tests, by their forms +instance HasTrie (TokenTest token) => HasTrie (TokenClass token) where + newtype (TokenClass token :->: b) = TokenClassTrie (TokenTest token :->: b) + trie f = TokenClassTrie (trie (f . TokenClass)) + untrie (TokenClassTrie t) (TokenClass test) = untrie t test + enumerate (TokenClassTrie t) = first TokenClass <$> enumerate t +instance (Ord token, Enum token, HasTrie token) => HasTrie (TokenRanges token) where + newtype (TokenRanges token :->: b) = TokenRangesTrie ([(token, token)] :->: b) + trie f = TokenRangesTrie (trie (f . TokenRanges . RSet.fromRangeList)) + untrie (TokenRangesTrie t) (TokenRanges xs) = untrie t (RSet.toRangeList xs) + enumerate (TokenRangesTrie t) = first (TokenRanges . RSet.fromRangeList) <$> enumerate t +instance (Ord token, HasTrie token) => HasTrie (Cofinite token) where + newtype (Cofinite token :->: b) = CofiniteTrie (Either [token] [token] :->: b) + trie f = CofiniteTrie (trie (f . either (Finite . Set.fromList) (Cofinite . Set.fromList))) + untrie (CofiniteTrie t) = untrie t . \case + Finite xs -> Left (Set.toList xs) + Cofinite xs -> Right (Set.toList xs) + enumerate (CofiniteTrie t) = + first (either (Finite . Set.fromList) (Cofinite . Set.fromList)) <$> enumerate t diff --git a/distributors-grammar/src/Data/Profunctor/Grammar.hs b/distributors-grammar/src/Data/Profunctor/Grammar.hs index 207a6553..89c6478b 100644 --- a/distributors-grammar/src/Data/Profunctor/Grammar.hs +++ b/distributors-grammar/src/Data/Profunctor/Grammar.hs @@ -167,20 +167,15 @@ instance (Alternative m, Monad m) => ArrowChoice (Parsor s m) where left = left' right = right' instance - ( Categorized a, a ~ Item s, IsList s + ( Lexical a, a ~ Item s, IsList s , Cons s s a a, Snoc s s a a , Filterable m, Alternative m, Monad m ) => Tokenized a (Parsor s m a a) where - anyToken = Parsor $ maybe + tokenAny = Parsor $ maybe (maybe empty pure . uncons) (\a -> pure . (a,) . flip snoc a) instance - ( Categorized a, a ~ Item s, IsList s - , Cons s s a a, Snoc s s a a - , Filterable m, Alternative m, Monad m - ) => TokenAlgebra a (Parsor s m a a) -instance - ( Categorized a, a ~ Item s, IsList s + ( Lexical a, a ~ Item s, IsList s , Cons s s a a, Snoc s s a a , Filterable m, Alternative m, Monad m ) => TerminalSymbol a (Parsor s m () ()) where @@ -238,14 +233,13 @@ instance KleeneStarAlgebra k => Alternator (Grammor k) where manyTillP (Grammor rex) (Grammor rest) = Grammor (starK rex <> rest) timesP lo hi (Grammor rex) = Grammor (timesK lo hi rex) instance Tokenized token k => Tokenized token (Grammor k a b) where - anyToken = Grammor anyToken + tokenAny = Grammor tokenAny token = Grammor . token oneOf = Grammor . oneOf notOneOf = Grammor . notOneOf asIn = Grammor . asIn notAsIn = Grammor . notAsIn tokenRange lo = Grammor . tokenRange lo -instance TokenAlgebra a k => TokenAlgebra a (Grammor k a b) where tokenClass = Grammor . tokenClass instance TerminalSymbol token k => TerminalSymbol token (Grammor k a b) where diff --git a/distributors-grammar/src/Data/Profunctor/Grammar/Parsector.hs b/distributors-grammar/src/Data/Profunctor/Grammar/Parsector.hs index 23c33989..0a2f0a2b 100644 --- a/distributors-grammar/src/Data/Profunctor/Grammar/Parsector.hs +++ b/distributors-grammar/src/Data/Profunctor/Grammar/Parsector.hs @@ -53,7 +53,7 @@ newtype Parsector s a b = Parsector left to right, returning a t'ParsecState' whose `parsecResult` is `Nothing` on failure and `Just` the output syntax value on success. -} parsecP - :: Categorized (Item s) + :: Lexical (Item s) => Parsector s a b -> s -- ^ input stream -> ParsecState s b @@ -65,7 +65,7 @@ returning a t'ParsecState' whose `parsecResult` is `Nothing` on failure or `Just` a successful output syntax value, in which case, `parsecStream` is the output stream. -} unparsecP - :: Categorized (Item s) + :: Lexical (Item s) => Parsector s a b -> a -- ^ input syntax -> s -- ^ input stream @@ -134,18 +134,18 @@ data ParsecFailure s = ParsecFailure -- ParsecFailure instances deriving stock instance - ( Categorized (Item s) - , Show (Item s), Show (Categorize (Item s)), Show (TokenSet (Item s)) + ( Lexical (Item s) + , Show (Item s), Show (TokenTest (Item s)) ) => Show (ParsecFailure s) deriving stock instance - ( Categorized (Item s) - , Read (Item s), Read (Categorize (Item s)), Read (TokenSet (Item s)) + ( Lexical (Item s) + , Read (Item s), Read (TokenTest (Item s)) ) => Read (ParsecFailure s) -deriving stock instance Categorized (Item s) => Eq (ParsecFailure s) -deriving stock instance Categorized (Item s) => Ord (ParsecFailure s) -instance Categorized (Item s) => Semigroup (ParsecFailure s) where +deriving stock instance Lexical (Item s) => Eq (ParsecFailure s) +deriving stock instance Lexical (Item s) => Ord (ParsecFailure s) +instance Lexical (Item s) => Semigroup (ParsecFailure s) where ParsecFailure e1 l1 <> ParsecFailure e2 l2 = ParsecFailure (e1 >|< e2) (l1 ++ l2) -instance Categorized (Item s) => Monoid (ParsecFailure s) where +instance Lexical (Item s) => Monoid (ParsecFailure s) where mempty = ParsecFailure falseP [] -- ParsecState instances @@ -153,41 +153,30 @@ deriving stock instance Functor (ParsecState s) deriving stock instance Foldable (ParsecState s) deriving stock instance Traversable (ParsecState s) deriving stock instance - ( Categorized (Item s) - , Show (Item s), Show (Categorize (Item s)), Show (TokenSet (Item s)) + ( Lexical (Item s) + , Show (Item s), Show (TokenTest (Item s)) , Show a, Show s ) => Show (ParsecState s a) deriving stock instance - ( Categorized (Item s) - , Read (Item s), Read (Categorize (Item s)), Read (TokenSet (Item s)) + ( Lexical (Item s) + , Read (Item s), Read (TokenTest (Item s)) , Read a, Read s ) => Read (ParsecState s a) deriving stock instance - ( Categorized (Item s) + ( Lexical (Item s) , Eq a, Eq s ) => Eq (ParsecState s a) deriving stock instance - ( Categorized (Item s) + ( Lexical (Item s) , Ord a, Ord s ) => Ord (ParsecState s a) -- Parsector instances instance - ( Categorized token, Item s ~ token + ( Lexical token, Item s ~ token , Cons s s token token, Snoc s s token token ) => Tokenized token (Parsector s token token) where - anyToken = tokenClass anyToken - 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) - tokenRange lo hi = tokenClass (tokenRange lo hi) -instance - ( Categorized token, Item s ~ token - , Cons s s token token, Snoc s s token token - ) => TokenAlgebra token (Parsector s token token) where - {-# SPECIALISE instance TokenAlgebra Char (Parsector String Char Char) #-} + {-# SPECIALISE instance Tokenized Char (Parsector String Char Char) #-} -- The test & failures are made once, rather than for each token. tokenClass test = matches `seq` Parsector (\callback query -> let @@ -235,7 +224,7 @@ instance Ruled (Parsector s a b) where } Just _ -> reply instance - ( Categorized token, Item s ~ token + ( Lexical token, Item s ~ token , Cons s s token token, Snoc s s token token ) => TerminalSymbol token (Parsector s () ()) where {-# SPECIALISE instance TerminalSymbol Char (Parsector String () ()) #-} @@ -274,7 +263,7 @@ instance fromString = terminal instance Functor (Parsector s a) where fmap = rmap -instance Categorized (Item s) => Applicative (Parsector s a) where +instance Lexical (Item s) => Applicative (Parsector s a) where pure b = Parsector $ \callback query -> callback query { parsecResult = Just b } (<*>) = liftA2 id @@ -287,7 +276,7 @@ instance Categorized (Item s) => Applicative (Parsector s a) where flip (runParsector q) (bound query reply) $ \qReply -> callback (rebound reply (f b <$> qReply)) -instance Categorized (Item s) => Monad (Parsector s a) where +instance Lexical (Item s) => Monad (Parsector s a) where return = pure p >>= f = Parsector $ \callback query -> flip (runParsector p) query $ \reply -> @@ -299,7 +288,7 @@ instance Categorized (Item s) => Monad (Parsector s a) where -- | The query of the second of a sequence, after the first's reply. bound - :: Categorized (Item s) + :: Lexical (Item s) => ParsecState s a -> ParsecState s b -> ParsecState s a bound query reply = reply { parsecLooked = False @@ -311,7 +300,7 @@ bound query reply = reply which keeps the first's hints when the second hasn't consumed. -} rebound - :: Categorized (Item s) + :: Lexical (Item s) => ParsecState s b -> ParsecState s c -> ParsecState s c rebound reply next | parsecLooked next = next @@ -320,7 +309,7 @@ rebound reply next , parsecFailure = parsecFailure reply <> parsecFailure next } -instance Categorized (Item s) => Alternative (Parsector s a) where +instance Lexical (Item s) => Alternative (Parsector s a) where -- | Always fails without consuming input; expects nothing. empty = Parsector $ \callback query -> callback query { parsecFailure = mempty, parsecResult = Nothing } @@ -342,8 +331,8 @@ instance Categorized (Item s) => Alternative (Parsector s a) where (False, Just _) -> replyQ { parsecFailure = errP <> parsecFailure replyQ } -- both empty fail: merge failures (False, Nothing) -> replyP { parsecFailure = errP <> parsecFailure replyQ } -instance Categorized (Item s) => MonadPlus (Parsector s a) -instance Categorized (Item s) => MonadFail (Parsector s a) where +instance Lexical (Item s) => MonadPlus (Parsector s a) +instance Lexical (Item s) => MonadFail (Parsector s a) where fail msg = rule msg empty instance Tried (Parsector s a b) where -- | On failure, resets `parsecLooked` to @False@, allowing @@ -359,21 +348,21 @@ instance Tried (Parsector s a b) where , parsecResult = Nothing } Just _ -> reply -instance Categorized (Item s) => Filterable (Parsector s a) where +instance Lexical (Item s) => Filterable (Parsector s a) where mapMaybe = dimapMaybe Just instance Category (Parsector s) where id = Parsector id Parsector q . Parsector p = Parsector (p . q) -instance Categorized (Item s) => Arrow (Parsector s) where +instance Lexical (Item s) => Arrow (Parsector s) where arr f = Parsector $ \callback reply -> callback (f <$> reply) (***) = (>*<) first = first' second = second' -instance Categorized (Item s) => ArrowZero (Parsector s) where +instance Lexical (Item s) => ArrowZero (Parsector s) where zeroArrow = empty -instance Categorized (Item s) => ArrowPlus (Parsector s) where +instance Lexical (Item s) => ArrowPlus (Parsector s) where (<+>) = (<|>) -instance Categorized (Item s) => ArrowChoice (Parsector s) where +instance Lexical (Item s) => ArrowChoice (Parsector s) where (+++) = (>+<) left = left' right = right' @@ -401,7 +390,7 @@ instance Strong (Parsector s) where <*> parsecResult reply1 } -- | Like `alternate`, without a sum of branches. -instance Categorized (Item s) => Choice (Parsector s) where +instance Lexical (Item s) => Choice (Parsector s) where left' (Parsector p) = Parsector $ \callback query -> case parsecResult query of Just (Right _) -> @@ -414,8 +403,8 @@ instance Categorized (Item s) => Choice (Parsector s) where callback query { parsecFailure = mempty, parsecResult = Nothing } result -> p (callback . fmap Right) query { parsecResult = either (const Nothing) Just =<< result } -instance Categorized (Item s) => CocartesianMonoidal (Parsector s) -instance Categorized (Item s) => Distributor (Parsector s) where +instance Lexical (Item s) => CocartesianMonoidal (Parsector s) +instance Lexical (Item s) => Distributor (Parsector s) where {- | Like @eotList . swapped >~ p >*< manyP p >+< oneP@, in one loop, with its hints: a failure of @p@ without consuming ends the list, merging its expectations with those of the last element. @@ -466,8 +455,8 @@ instance Categorized (Item s) => Distributor (Parsector s) where Nothing -> p parsedFirst query {parsecResult = Nothing} Just [] -> callback query {parsecResult = Just []} Just (a : as) -> p (printedFirst as) query {parsecResult = Just a} -instance Categorized (Item s) => DisjunctiveMonoid (Parsector s a b) -instance Categorized (Item s) => CocartesianChoice (Parsector s) where +instance Lexical (Item s) => DisjunctiveMonoid (Parsector s a b) +instance Lexical (Item s) => CocartesianChoice (Parsector s) where alternate (Left p) = Parsector $ \callback query -> callback $ let replyOk = query @@ -498,15 +487,15 @@ instance Categorized (Item s) => CocartesianChoice (Parsector s) where _________________ -> flip (runParsector p) replyOk $ \reply -> reply { parsecResult = fmap Right (parsecResult reply) } -instance Categorized (Item s) => Alternator (Parsector s) where +instance Lexical (Item s) => Alternator (Parsector s) where optionP def p = Parsector $ \callback query -> case parsecResult query of Nothing -> runParsector (p <|> pureP def) callback query Just _ -> runParsector (pureP def <|> p) callback query -instance Categorized (Item s) => Cochoice (Parsector s) where +instance Lexical (Item s) => Cochoice (Parsector s) where unleft = fst . filtrate unright = snd . filtrate -instance Categorized (Item s) => Filtrator (Parsector s) where +instance Lexical (Item s) => Filtrator (Parsector s) where filtrate p = ( Parsector $ \callback query -> flip (runParsector p) (Left <$> query) $ \reply -> diff --git a/distributors-grammar/src/Data/Profunctor/Grammar/Printor.hs b/distributors-grammar/src/Data/Profunctor/Grammar/Printor.hs index 39d13336..b57433ef 100644 --- a/distributors-grammar/src/Data/Profunctor/Grammar/Printor.hs +++ b/distributors-grammar/src/Data/Profunctor/Grammar/Printor.hs @@ -136,29 +136,17 @@ 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 + ( Lexical 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) - tokenRange lo hi = tokenClass (tokenRange lo hi) -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 + tokenAny = Printor (\b -> pure (b, cons b)) + -- | 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 () ()) #-} diff --git a/distributors-grammar/test/Examples/RegString.hs b/distributors-grammar/test/Examples/RegString.hs index 07cc73cd..e4dd4e93 100644 --- a/distributors-grammar/test/Examples/RegString.hs +++ b/distributors-grammar/test/Examples/RegString.hs @@ -14,7 +14,7 @@ regexExamples = , (optK (terminal "x"), "x?") , (starK (terminal "x"), "x*") , (plusK (terminal "x"), "x+") - , (anyToken, "[^]") + , (tokenAny, "[^]") , (oneOf "abc", "[a-c]") , (notOneOf "abc", "[^a-c]") , (asIn UppercaseLetter, "\\p{Lu}") @@ -26,8 +26,8 @@ regexExamples = -- Boolean OR (>|<) operations , (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 (oneOf "abc" >|< notOneOf "xyz"), "[^x-z]") + , (tokenClass (notOneOf "abc" >|< oneOf "xyz"), "[^a-c]") , (tokenClass (asIn UppercaseLetter >|< asIn LowercaseLetter), "\\p{Lu}|\\p{Ll}") , (tokenClass (oneOf "abc" >|< asIn DecimalNumber), "[a-c]|\\p{Nd}") @@ -55,6 +55,6 @@ regexExamples = -- Complex combinations , (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 ((oneOf "123" >|< asIn DecimalNumber) >&< notOneOf "789"), "[^7-9\\p{Nd}]") , (tokenClass (notP (oneOf "abc" >|< asIn MathSymbol)), "[^a-c\\P{Sm}]") ] diff --git a/distributors-grammar/test/Main.hs b/distributors-grammar/test/Main.hs index c76631e3..daa7b60e 100644 --- a/distributors-grammar/test/Main.hs +++ b/distributors-grammar/test/Main.hs @@ -13,7 +13,7 @@ import Text.ParserCombinators.ReadPrec (ReadPrec, readPrec_to_S) import Data.Functor.Contravariant (Predicate (..)) import Test.Hspec import Test.Hspec.QuickCheck (modifyMaxSize, prop) -import Test.QuickCheck (Gen, choose, elements, forAll, generate, listOf, oneof, (===)) +import Test.QuickCheck (Gen, (.&&.), choose, elements, forAll, generate, listOf, oneof, (===)) import qualified Text.Megaparsec as M import Examples.Arithmetic @@ -56,6 +56,7 @@ main = hspec $ do describe "RegEx ranges & try" regexRangeTryTests describe "RegEx quantifiers" regexQuantifierTests describe "tokenRange" tokenRangeTests + describe "Lexical laws" lexicalLaws regexRangeTryTests :: Spec regexRangeTryTests = do @@ -79,6 +80,24 @@ regexRangeTryTests = do `shouldBe` [LL1FirstFirst] ll1Conflicts (fromString "{start} = \\t{ab}|ac" :: Bnf (RegEx Char)) `shouldBe` [] +lexicalLaws :: Spec +lexicalLaws = do + let near = choose ('\0', '\x3FF') + tested :: TokenClass Char -> Char -> Bool + tested = tokenClass + prop "a class tests homomorphically" $ \(x :: TokenClass Char) y -> forAll near $ \c -> + tested (x >|< y) c === (tested x c || tested y c) + .&&. tested (x >&< y) c === (tested x c && tested y c) + .&&. tested (notP x) c === not (tested x c) + .&&. tested trueP c .&&. not (tested falseP c) + prop "its generators test as they say" $ forAll (listOf near) $ \cs -> + forAll near $ \lo -> forAll near $ \hi -> forAll near $ \c -> + tested (oneOf cs) c === (c `elem` cs) + .&&. tested (tokenRange lo hi) c === (lo <= c && c <= hi) + .&&. tested (asIn (tokenKind lo)) c === (tokenKind c == tokenKind lo) + prop "equal classes test alike, by their one form" $ \(x :: TokenClass Char) y -> + (x >|< y) >&< notP y === x >&< notP y + tokenRangeTests :: Spec tokenRangeTests = do let near = choose ('\0', '\x3FF') @@ -264,10 +283,9 @@ newtype WrapMega a = WrapMega {unwrapMega :: M.Parsec String String a} ) instance TerminalSymbol Char (WrapMega ()) where terminal str = WrapMega (M.chunk str *> pure ()) -instance TokenAlgebra Char (WrapMega Char) where - tokenClass exam = WrapMega $ M.label (show exam) (M.satisfy (tokenClass exam)) instance Tokenized Char (WrapMega Char) where - anyToken = WrapMega M.anySingle + tokenClass exam = WrapMega $ M.label (show exam) (M.satisfy (tokenClass exam)) + tokenAny = WrapMega M.anySingle token = WrapMega . M.single oneOf = WrapMega . M.oneOf notOneOf = WrapMega . M.noneOf diff --git a/distributors-grammar/test/Properties/Kleene.hs b/distributors-grammar/test/Properties/Kleene.hs index 03602fef..ea3388aa 100644 --- a/distributors-grammar/test/Properties/Kleene.hs +++ b/distributors-grammar/test/Properties/Kleene.hs @@ -123,9 +123,9 @@ kleeneProperties = do modifyMaxSize (const 8) $ do let printed :: Prismoid String String Char Char -> String -> Maybe String - printed pat s = ($ "") <$> printP (pat >?* (anyToken :: Printor String Maybe Char Char)) s + printed pat s = ($ "") <$> printP (pat >?* (tokenAny :: Printor String Maybe Char Char)) s parsed :: Prismoid String String Char Char -> String -> Maybe (String, String) - parsed pat s = parseP (pat >?* (anyToken :: Parsor String Maybe Char Char)) s + parsed pat s = parseP (pat >?* (tokenAny :: Parsor String Maybe Char Char)) s bounded lo hi s = lo <= length s && length s <= hi prop "inRange lo hi prints & parses exactly lo to hi tokens" $ \(s :: String) -> forAll (choose (0, 4)) $ \lo -> forAll (choose (0, 4)) $ \hi -> @@ -154,8 +154,8 @@ kleeneProperties = do ((tokenClass x :: RegEx Char) >|< tokenClass y) == tokenClass (x >|< y) describe "TokenAlgebra RegEx" $ do - it "anyToken = tokenClass anyToken" $ - (anyToken :: RegEx Char) `shouldBe` tokenClass anyToken + it "tokenAny = tokenClass tokenAny" $ + (tokenAny :: RegEx Char) `shouldBe` tokenClass tokenAny prop "token c = tokenClass (token c)" $ \(c :: Char) -> (token c :: RegEx Char) == tokenClass (token c) @@ -192,8 +192,8 @@ kleeneProperties = do for_ cases $ \(word, rex) -> (word =~ rex) `shouldBe` (word =~ liftBnf0 rex) describe "BooleanAlgebra TokenClass" $ do - it "trueP = anyToken" $ - (trueP :: TokenClass Char) `shouldBe` anyToken + it "trueP = tokenAny" $ + (trueP :: TokenClass Char) `shouldBe` tokenAny it "trueP = notOneOf []" $ (trueP :: TokenClass Char) `shouldBe` notOneOf [] it "falseP = oneOf []" $ diff --git a/distributors-grammar/test/Properties/Varifocal.hs b/distributors-grammar/test/Properties/Varifocal.hs index 416f0e3b..f3b6f8b6 100644 --- a/distributors-grammar/test/Properties/Varifocal.hs +++ b/distributors-grammar/test/Properties/Varifocal.hs @@ -18,9 +18,9 @@ varifocalProperties = do let printed :: Varifocal' String Char -> String -> Maybe String printed v s = - ($ "") <$> printP (contextuallyT v (anyToken :: Printor String Maybe Char Char)) s + ($ "") <$> printP (contextuallyT v (tokenAny :: Printor String Maybe Char Char)) s parsed :: Varifocal' String Char -> String -> Maybe (String, String) - parsed v = parseP (contextuallyT v (anyToken :: Parsor String Maybe Char Char)) + parsed v = parseP (contextuallyT v (tokenAny :: Parsor String Maybe Char Char)) ended :: Varifocal' String Char ended = terminateBy (== '.') plain = Prelude.filter (/= '.') <$> arbitrary @@ -30,8 +30,8 @@ varifocalProperties = do printing q c = fmap ($ "") <$> runPrintor q c parsing :: Parsor String Maybe Char b -> String -> Maybe (b, String) parsing = parseP - prToken = anyToken :: Printor String Maybe Char Char - paToken = anyToken :: Parsor String Maybe Char Char + prToken = tokenAny :: Printor String Maybe Char Char + paToken = tokenAny :: Parsor String Maybe Char Char prop "liftP . pure = pure" $ \(n :: Int) (c :: Char) (str :: String) -> printing (liftP (pure n)) c === printing (pure n) c .&&. parsing (liftP (pure n)) str === parsing (pure n) str @@ -56,17 +56,17 @@ varifocalProperties = do 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" + parseP (contextuallyT seqTerminated (tokenAny :: 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.")) + (($ "") <$> printP (contextuallyT seqTerminated (tokenAny :: Printor String Maybe Char Char)) (Seq.fromList "ab.")) `shouldBe` Just "ab." describe "steppingTree, 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)) + parsedT = parseP (contextuallyT counted (tokenAny :: Parsor String Maybe Char Char)) + printedT = fmap ($ "") . printP (contextuallyT counted (tokenAny :: Printor String Maybe Char Char)) it "parses a count-prefixed tree, in preorder" $ parsedT "2100rest" `shouldBe` Just (tree, "rest") it "prints it, in preorder" $ @@ -102,9 +102,9 @@ varifocalProperties = do let printedG :: Varifocal' s Char -> s -> Maybe String printedG v x = - ($ "") <$> printP (contextuallyT v (anyToken :: Printor String Maybe Char Char)) x + ($ "") <$> printP (contextuallyT v (tokenAny :: Printor String Maybe Char Char)) x parsedG :: Varifocal' s Char -> String -> Maybe (s, String) - parsedG v = parseP (contextuallyT v (anyToken :: Parsor String Maybe Char Char)) + parsedG v = parseP (contextuallyT v (tokenAny :: Parsor String Maybe Char Char)) crossed :: Varifocal' (String, String) Char crossed = crossVarifocal (terminateBy (== '.')) (delimitBy (==)) alted :: Varifocal' (Either String String) Char @@ -173,9 +173,9 @@ varifocalProperties = do composite = _Right . ended printedE :: Varifocal' (Either Int String) Char -> Either Int String -> Maybe String printedE v e = - ($ "") <$> printP (contextuallyT v (anyToken :: Printor String Maybe Char Char)) e + ($ "") <$> printP (contextuallyT v (tokenAny :: Printor String Maybe Char Char)) e parsedE :: Varifocal' (Either Int String) Char -> String -> Maybe (Either Int String, String) - parsedE v = parseP (contextuallyT v (anyToken :: Parsor String Maybe Char Char)) + parsedE v = parseP (contextuallyT v (tokenAny :: Parsor String Maybe Char Char)) prop "prints & parses as the composite does" $ forAll plain $ \s (n :: Int) -> let es = [Left n, Right s, Right (s ++ ".")] @@ -194,21 +194,21 @@ varifocalProperties = do parsecResult (parsecG "<?<*, Bifocal's applicator" $ do prop "applies a Prismoid as >?* does" $ \(s :: String) -> - parseP (atLeast 1 >?<* (anyToken :: Parsor String Maybe Char Char)) s - === parseP (atLeast 1 >?* (anyToken :: Parsor String Maybe Char Char)) s - .&&. (($ "") <$> printP (atLeast 1 >?<* (anyToken :: Printor String Maybe Char Char)) s) - === (($ "") <$> printP (atLeast 1 >?* (anyToken :: Printor String Maybe Char Char)) s) + parseP (atLeast 1 >?<* (tokenAny :: Parsor String Maybe Char Char)) s + === parseP (atLeast 1 >?* (tokenAny :: Parsor String Maybe Char Char)) s + .&&. (($ "") <$> printP (atLeast 1 >?<* (tokenAny :: Printor String Maybe Char Char)) s) + === (($ "") <$> printP (atLeast 1 >?* (tokenAny :: Printor String Maybe Char Char)) s) prop "applies a PartialIso as >?< does" $ \(s :: String) (c :: Char) -> - parseP (satisfied isDigit >?<* (anyToken :: Parsor String Maybe Char Char)) s - === parseP (satisfied isDigit >?< (anyToken :: Parsor String Maybe Char Char)) s - .&&. (($ "") <$> printP (satisfied isDigit >?<* (anyToken :: Printor String Maybe Char Char)) c) - === (($ "") <$> printP (satisfied isDigit >?< (anyToken :: Printor String Maybe Char Char)) c) + parseP (satisfied isDigit >?<* (tokenAny :: Parsor String Maybe Char Char)) s + === parseP (satisfied isDigit >?< (tokenAny :: Parsor String Maybe Char Char)) s + .&&. (($ "") <$> printP (satisfied isDigit >?<* (tokenAny :: Printor String Maybe Char Char)) c) + === (($ "") <$> printP (satisfied isDigit >?< (tokenAny :: Printor String Maybe Char Char)) c) it "keeps the target's own optionP, printing nothing for the default" $ - (($ "") <$> printP (opted (only '0') >?<* (anyToken :: Printor String Maybe Char Char)) '0') + (($ "") <$> printP (opted (only '0') >?<* (tokenAny :: Printor String Maybe Char Char)) '0') `shouldBe` Just "" describe "Bifocal ⊂ Varifocal" $ prop "a Prismoid applies contextuallyT as by >?*" $ \(s :: String) -> parsed (atLeast 1) s - === parseP (atLeast 1 >?* (anyToken :: Parsor String Maybe Char Char)) s + === parseP (atLeast 1 >?* (tokenAny :: Parsor String Maybe Char Char)) s .&&. printed (atLeast 1) s - === (($ "") <$> printP (atLeast 1 >?* (anyToken :: Printor String Maybe Char Char)) s) + === (($ "") <$> printP (atLeast 1 >?* (tokenAny :: Printor String Maybe Char Char)) s) diff --git a/distributors-json/src/Control/Lens/Grammar/TypeScript.hs b/distributors-json/src/Control/Lens/Grammar/TypeScript.hs index e51d71e9..625b4d2a 100644 --- a/distributors-json/src/Control/Lens/Grammar/TypeScript.hs +++ b/distributors-json/src/Control/Lens/Grammar/TypeScript.hs @@ -66,7 +66,9 @@ module Control.Lens.Grammar.TypeScript import Control.Lens import Control.Lens.Grammar import Data.Char (chr, ord) +import Data.Map.Strict qualified as Map import Data.Maybe (fromMaybe, listToMaybe) +import Data.Set qualified as Set import Data.Profunctor.Monadic.Do qualified as P import Data.Text (Text) import Data.Text qualified as Text @@ -280,9 +282,23 @@ data TsToken = TsToken , tokenText :: Text } deriving stock (Eq, Ord, Show, Read) -instance Categorized TsToken where - type Categorize TsToken = TsTokenCategory - categorize = tokenCategory +instance Lexical TsToken where + type TokenKind TsToken = TsTokenCategory + tokenKind = tokenCategory + -- tested by their kinds' tests of their texts + type TokenTest TsToken = ByKind TsTokenCategory (Cofinite Text) + tokenTest test (TsToken kind text) = testByKind (flip cofiniteMember) test kind text + testOneOf tokens' = ByKind $ Map.fromListWith (>|<) + [(kind, Finite (Set.singleton text)) | TsToken kind text <- tokens'] + testKinds (TokenKinds kinds) = ByKind (Map.fromSet (const trueP) kinds) + testFinite (ByKind tests) = case traverse finite (Map.toList tests) of + Just kinds -> + let tokens' = [TsToken kind text | (kind, texts) <- kinds, text <- texts] + in Just (length tokens', (tokens' !!)) + Nothing -> Nothing + where + finite (kind, Finite texts) = Just (kind, Set.toList texts) + finite _ = Nothing -- | The categories of t'TsToken's, by the TypeScript compiler's names. data TsTokenCategory @@ -474,18 +490,18 @@ It's a `RegGrammar`, since each token's spelling is a regular language. -} tsTokenGrammar :: RegGrammatical Char p => p TsToken TsToken tsTokenGrammar = orP - [ kindOf WhitespaceTrivia >? someP (oneOf @Char (" \t\f\v" :: String)) - , kindOf NewLineTrivia >? orP + [ ofKind WhitespaceTrivia >? someP (oneOf @Char (" \t\f\v" :: String)) + , ofKind NewLineTrivia >? orP [only "\n" >? terminal "\n", only "\r\n" >? terminal "\r\n"] , _Comment >? terminal "/" >* orP [ _Left >? terminal "/" >* manyP (notOneOf @Char ("\r\n" :: String)) , _Right >? blockComment ] , _Word >? identifierStart >:< manyP identifierPart - , kindOf PrivateIdentifier >? terminal "#" + , ofKind PrivateIdentifier >? terminal "#" >* (identifierStart >:< manyP identifierPart) , _Number >? asIn @Char DecimalNumber >:< manyP numberPart - , kindOf StringLiteral >? orP + , ofKind StringLiteral >? orP [ terminal "\"" >* manyP (stringChar '"') *< terminal "\"" , terminal "'" >* manyP (stringChar '\'') *< terminal "'" ] @@ -600,8 +616,8 @@ tokensWithin depths = orP _ -> ds -- | A token of a category, by its text. -kindOf :: TsTokenCategory -> Prism' TsToken String -kindOf category = prism' +ofKind :: TsTokenCategory -> Prism' TsToken String +ofKind category = prism' (TsToken category . Text.pack) (\(TsToken category' text) -> if category == category' then Just (Text.unpack text) else Nothing) From febcf9bf2f0bb6fc96f726310b1d2a712970384f Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sat, 14 Nov 2026 00:15:13 -0800 Subject: [PATCH 23/51] Lexical defaults to TokenRanges, so enumerable tokens' instances are empty Co-Authored-By: Claude Opus 5.5 --- .../src/Control/Lens/Grammar/Token.hs | 55 ++++++------------- .../src/Control/Lens/Grammar/TypeScript.hs | 1 + 2 files changed, 19 insertions(+), 37 deletions(-) diff --git a/distributors-grammar/src/Control/Lens/Grammar/Token.hs b/distributors-grammar/src/Control/Lens/Grammar/Token.hs index f974a968..81245dc3 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/Token.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/Token.hs @@ -96,67 +96,48 @@ class default tokenKind :: TokenKind token ~ () => token -> TokenKind token tokenKind _ = () - {- | The tests of tokens, `Cofinite` sets of them by default. -} + {- | The tests of tokens, by default `TokenRanges` of bounded, enumerable + tokens; `Cofinite` sets of others, or `ByKind` tests of tagged ones. -} type TokenTest token - type TokenTest token = Cofinite token + type TokenTest token = TokenRanges token {- | Does a token pass a test? -} tokenTest :: TokenTest token -> token -> Bool default tokenTest - :: TokenTest token ~ Cofinite token => TokenTest token -> token -> Bool - tokenTest = flip cofiniteMember + :: TokenTest token ~ TokenRanges token => TokenTest token -> token -> Bool + tokenTest = flip rangesMember {- | The test of being one of some tokens. -} testOneOf :: [token] -> TokenTest token default testOneOf - :: TokenTest token ~ Cofinite token => [token] -> TokenTest token - testOneOf = Finite . Set.fromList + :: (TokenTest token ~ TokenRanges token, Enum token) + => [token] -> TokenTest token + testOneOf = Exts.fromList {- | The test of being of one of some kinds. -} testKinds :: TokenKinds (TokenKind token) -> TokenTest token default testKinds - :: (TokenTest token ~ Cofinite token, TokenKind token ~ ()) - => TokenKinds (TokenKind token) -> TokenTest token - testKinds = kindless + :: TokenKind token ~ () => TokenKinds (TokenKind token) -> TokenTest token + testKinds (TokenKinds ks) = if Set.member () ks then trueP else falseP {- | The test of being between two tokens, inclusive, by their enumeration, for tokens whose `Enum` & `Ord` agree. -} testRange :: Enum token => token -> token -> TokenTest token - testRange lo hi = testOneOf [lo .. hi] + default testRange + :: TokenTest token ~ TokenRanges token + => token -> token -> TokenTest token + testRange = rangesBetween {- | The tokens which pass a test, by their number & their index, where they're finitely many & listable, so that generators sample them uniformly, rather than by rejection. -} testFinite :: TokenTest token -> Maybe (Int, Int -> token) default testFinite - :: TokenTest token ~ Cofinite token + :: (TokenTest token ~ TokenRanges token, Enum token) => TokenTest token -> Maybe (Int, Int -> token) - testFinite = \case - Finite ts -> Just (Set.size ts, (`Set.elemAt` ts)) - Cofinite _ -> Nothing + testFinite = rangesFinite instance Lexical Char where type TokenKind Char = GeneralCategory tokenKind = generalCategory - type TokenTest Char = TokenRanges Char - tokenTest = flip rangesMember - testOneOf = Exts.fromList testKinds (TokenKinds cats) = foldr ((>|<) . categoryRanges) falseP cats - testRange = rangesBetween - testFinite = rangesFinite -instance Lexical Word8 where - type TokenTest Word8 = TokenRanges Word8 - tokenTest = flip rangesMember - testOneOf = Exts.fromList - testKinds = kindless - testRange = rangesBetween - testFinite = rangesFinite -instance Lexical () where - type TokenTest () = TokenRanges () - tokenTest = flip rangesMember - testOneOf = Exts.fromList - testKinds = kindless - testRange = rangesBetween - testFinite = rangesFinite - --- | Tests of kinds, where there are none but @()@. -kindless :: BooleanAlgebra test => TokenKinds () -> test -kindless (TokenKinds ks) = if Set.null ks then falseP else trueP +instance Lexical Word8 +instance Lexical () {- | A class of tokens, by their `TokenTest`, a `Tokenized` `BooleanAlgebra`, such that the following hold. diff --git a/distributors-json/src/Control/Lens/Grammar/TypeScript.hs b/distributors-json/src/Control/Lens/Grammar/TypeScript.hs index 625b4d2a..471164eb 100644 --- a/distributors-json/src/Control/Lens/Grammar/TypeScript.hs +++ b/distributors-json/src/Control/Lens/Grammar/TypeScript.hs @@ -291,6 +291,7 @@ instance Lexical TsToken where testOneOf tokens' = ByKind $ Map.fromListWith (>|<) [(kind, Finite (Set.singleton text)) | TsToken kind text <- tokens'] testKinds (TokenKinds kinds) = ByKind (Map.fromSet (const trueP) kinds) + testRange lo hi = testOneOf [lo .. hi] testFinite (ByKind tests) = case traverse finite (Map.toList tests) of Just kinds -> let tokens' = [TsToken kind text | (kind, texts) <- kinds, text <- texts] From e3f47a0eb2aef4535a232cf870f9c2be1586cbee Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sat, 14 Nov 2026 00:21:13 -0800 Subject: [PATCH 24/51] Tagged tokens' Lexical methods by an iso to their kinds & tags Co-Authored-By: Claude Opus 5.5 --- .../src/Control/Lens/Grammar/Token.hs | 58 +++++++++++++++++-- .../src/Control/Lens/Grammar/TypeScript.hs | 22 +++---- 2 files changed, 62 insertions(+), 18 deletions(-) diff --git a/distributors-grammar/src/Control/Lens/Grammar/Token.hs b/distributors-grammar/src/Control/Lens/Grammar/Token.hs index 81245dc3..beedbc49 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/Token.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/Token.hs @@ -23,7 +23,12 @@ module Control.Lens.Grammar.Token , Cofinite (..) , cofiniteMember , ByKind (..) - , testByKind + -- * Tagged tokens + -- $tagged + , taggedTest + , taggedOneOf + , taggedKinds + , taggedFinite ) where import Control.Lens @@ -400,9 +405,54 @@ instance (Ord kind, Enum kind, Bounded kind, BooleanAlgebra test, Eq test) ByKind xs >&< ByKind ys = ByKind (Map.filter (/= falseP) (Map.intersectionWith (>&<) xs ys)) --- | Test a token, tagged by its kind, by its kind's test of its tag. -testByKind :: Ord kind => (test -> tag -> Bool) -> ByKind kind test -> kind -> tag -> Bool -testByKind tested (ByKind xs) kind tag = maybe False (`tested` tag) (Map.lookup kind xs) +{- $tagged +Tokens tagged by their kinds, isomorphic to pairs of a kind & a tag, +are tested by `ByKind` tests, of their kinds' `Cofinite` tests of their +tags, which these define a `Lexical` instance's methods by. + +> instance Lexical TsToken where +> type TokenKind TsToken = TsTokenCategory +> tokenKind = tokenCategory +> type TokenTest TsToken = ByKind TsTokenCategory (Cofinite Text) +> tokenTest = taggedTest tagged +> testOneOf = taggedOneOf tagged +> testKinds = taggedKinds +> testRange lo hi = testOneOf [lo .. hi] +> testFinite = taggedFinite tagged +> +> tagged :: Iso' TsToken (TsTokenCategory, Text) +> tagged = iso (\(TsToken category text) -> (category, text)) (uncurry TsToken) +-} + +-- | Does a tagged token pass its kind's test of its tag? +taggedTest + :: (Ord kind, Ord tag) + => Iso' token (kind, tag) -> ByKind kind (Cofinite tag) -> token -> Bool +taggedTest tagged (ByKind tests) token' = + let (kind, tag) = view tagged token' + in maybe False (cofiniteMember tag) (Map.lookup kind tests) + +-- | The test of being one of some tagged tokens. +taggedOneOf + :: (Ord kind, Ord tag) + => Iso' token (kind, tag) -> [token] -> ByKind kind (Cofinite tag) +taggedOneOf tagged tokens' = ByKind $ Map.fromListWith (>|<) + [(kind, Finite (Set.singleton tag)) | (kind, tag) <- map (view tagged) tokens'] + +-- | The test of being of one of some kinds, by any tag. +taggedKinds :: BooleanAlgebra test => TokenKinds kind -> ByKind kind test +taggedKinds (TokenKinds kinds) = ByKind (Map.fromSet (const trueP) kinds) + +-- | The tagged tokens which pass a test, where each kind's are finitely many. +taggedFinite + :: Iso' token (kind, tag) -> ByKind kind (Cofinite tag) -> Maybe (Int, Int -> token) +taggedFinite tagged (ByKind tests) = do + tokens' <- concat <$> traverse finite (Map.toList tests) + Just (length tokens', (tokens' !!)) + where + finite = \case + (kind, Finite tags) -> Just [review tagged (kind, tag) | tag <- Set.toList tags] + _ -> Nothing -- memo tries of tests, by their forms instance HasTrie (TokenTest token) => HasTrie (TokenClass token) where diff --git a/distributors-json/src/Control/Lens/Grammar/TypeScript.hs b/distributors-json/src/Control/Lens/Grammar/TypeScript.hs index 471164eb..6b5488e0 100644 --- a/distributors-json/src/Control/Lens/Grammar/TypeScript.hs +++ b/distributors-json/src/Control/Lens/Grammar/TypeScript.hs @@ -66,9 +66,7 @@ module Control.Lens.Grammar.TypeScript import Control.Lens import Control.Lens.Grammar import Data.Char (chr, ord) -import Data.Map.Strict qualified as Map import Data.Maybe (fromMaybe, listToMaybe) -import Data.Set qualified as Set import Data.Profunctor.Monadic.Do qualified as P import Data.Text (Text) import Data.Text qualified as Text @@ -287,19 +285,15 @@ instance Lexical TsToken where tokenKind = tokenCategory -- tested by their kinds' tests of their texts type TokenTest TsToken = ByKind TsTokenCategory (Cofinite Text) - tokenTest test (TsToken kind text) = testByKind (flip cofiniteMember) test kind text - testOneOf tokens' = ByKind $ Map.fromListWith (>|<) - [(kind, Finite (Set.singleton text)) | TsToken kind text <- tokens'] - testKinds (TokenKinds kinds) = ByKind (Map.fromSet (const trueP) kinds) + tokenTest = taggedTest tagged + testOneOf = taggedOneOf tagged + testKinds = taggedKinds testRange lo hi = testOneOf [lo .. hi] - testFinite (ByKind tests) = case traverse finite (Map.toList tests) of - Just kinds -> - let tokens' = [TsToken kind text | (kind, texts) <- kinds, text <- texts] - in Just (length tokens', (tokens' !!)) - Nothing -> Nothing - where - finite (kind, Finite texts) = Just (kind, Set.toList texts) - finite _ = Nothing + testFinite = taggedFinite tagged + +-- | A token, as its category & its text. +tagged :: Iso' TsToken (TsTokenCategory, Text) +tagged = iso (\(TsToken category text) -> (category, text)) (uncurry TsToken) -- | The categories of t'TsToken's, by the TypeScript compiler's names. data TsTokenCategory From 10e960b83753ac4c20d087efcc28ed23bde6f33a Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sat, 14 Nov 2026 00:44:36 -0800 Subject: [PATCH 25/51] Cut ranges from token class storage, & the Lexical algebras they forced Reverts e3f47a0, febcf9b, e145f94, 43c1a3d, 33de5c3 & 4d09da1: classes are stored as written again, OneOf & NotOneOf sets with category tests; [a-z] stays as regular expression syntax only. Co-Authored-By: Claude Opus 5.5 --- distributors-grammar/CHANGELOG.md | 27 - distributors-grammar/bench/Main.hs | 4 +- .../distributors-grammar.cabal | 4 - distributors-grammar/package.yaml | 1 - .../src/Control/Lens/Grammar.hs | 41 +- .../src/Control/Lens/Grammar/Analysis.hs | 47 +- .../src/Control/Lens/Grammar/BackusNaur.hs | 2 +- .../src/Control/Lens/Grammar/Class.hs | 4 +- .../src/Control/Lens/Grammar/Machine.hs | 41 +- .../src/Control/Lens/Grammar/RegEx.hs | 227 +++--- .../src/Control/Lens/Grammar/Token.hs | 732 +++++++++--------- .../src/Data/Profunctor/Grammar.hs | 15 +- .../src/Data/Profunctor/Grammar/Parsector.hs | 88 ++- .../src/Data/Profunctor/Grammar/Printor.hs | 27 +- distributors-grammar/test/Examples/Json.hs | 3 +- .../test/Examples/RegString.hs | 8 +- distributors-grammar/test/Main.hs | 46 +- .../test/Properties/Kleene.hs | 12 +- .../test/Properties/Varifocal.hs | 46 +- .../src/Control/Lens/Grammar/TypeScript.hs | 29 +- 20 files changed, 649 insertions(+), 755 deletions(-) diff --git a/distributors-grammar/CHANGELOG.md b/distributors-grammar/CHANGELOG.md index ee3c6bbf..d88b083d 100644 --- a/distributors-grammar/CHANGELOG.md +++ b/distributors-grammar/CHANGELOG.md @@ -2,39 +2,12 @@ ## Unreleased -- `Categorized` is `Lexical`, with a `BooleanAlgebra` of `TokenTest`s per - token type, generated by `testOneOf`, `testKinds` & `testRange`, & - tested by `tokenTest`, a homomorphism, each test having one form, so - that `Eq` is exact: `TokenRanges` for `Char`, whose `GeneralCategory`s - are ranges of a table, & `Word8`, `Cofinite` sets by default, & - `ByKind` tests for tokens tagged by kinds, like `TsToken`. `Categorize` - is `TokenKind`, & `categorize` is `tokenKind`. `TokenClass` wraps a - `TokenTest`. `TokenAlgebra` is merged into `Tokenized`, whose methods, - `tokenClass`, `tokenAny` (was `anyToken`) & the rest, default by - `tokenClass`. `TokenExam`, `CategoryTest` & `TokenSet` are removed. - `RegEx` has its own `Alternate`, & `RegExam` holds a `TokenClass`; - classes print in their shortest form, or as alternatives where shorter, - & alternatives of classes are one class. - `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. -- `Tokenized` has `tokenRange lo hi`, a single token between two, inclusive, - for `Enum`erable tokens, as `oneOf [lo .. hi]` but taking only its ends: - predicates & parsers compare, generators choose, & token classes & regular - expressions keep one range, by `Categorized`'s `tokenRangeSet`. The Json - example's character is its spec's, by `tokenRange`. -- `Categorized` has a `TokenSet` type of its tokens' sets, a `Set` by default, - with `tokenMember`, `tokenIntersection` & `tokenDifference`, empty by - `falseP`, unioned by `>|<` & listed by `IsList`; `Char`'s are `Ranges`, - sets of ranges, by - [range-set-list](https://hackage.haskell.org/package/range-set-list), - so huge classes, like `oneOf ['\x20' .. '\x10FFFF']`, intersect, compare & - render by their ranges, not their tokens. Their `Show` & `Read` are a - `Set`'s. Derived `Show` & `Read` instances require `Show (TokenSet token)` - or `Read (TokenSet token)` rather than `Show token` or `Read token`. - `RegEx` has counts, a `KleeneTimes` constructor, normalized by `timesK`, rendered @x{n}@, @x{n,}@ & @x{n,m}@, & parsed so, normalizing; `Grammor`s keep counts, so `exactly`, `atLeast`, `atMost` & `inRange` render by them. diff --git a/distributors-grammar/bench/Main.hs b/distributors-grammar/bench/Main.hs index 3986fa30..d3287fb7 100644 --- a/distributors-grammar/bench/Main.hs +++ b/distributors-grammar/bench/Main.hs @@ -125,9 +125,9 @@ separates = -- | Varifocals, applied by contextually. varifocals :: [Workload] varifocals = - [ Workload "terminateBy" (contextually (terminateBy (== '.')) (tokenAny @Char)) + [ Workload "terminateBy" (contextually (terminateBy (== '.')) (anyToken @Char)) (digits <> ".") (digits <> ".") - , Workload "balanceBy" (contextually (balanceBy (== '(') (== ')')) (tokenAny @Char)) + , Workload "balanceBy" (contextually (balanceBy (== '(') (== ')')) (anyToken @Char)) nested nested , Workload "heredoc" heredocG heredocStr heredoc ] diff --git a/distributors-grammar/distributors-grammar.cabal b/distributors-grammar/distributors-grammar.cabal index fc5218c5..012bc59d 100644 --- a/distributors-grammar/distributors-grammar.cabal +++ b/distributors-grammar/distributors-grammar.cabal @@ -90,7 +90,6 @@ library , base >=4.20 && <5 , bifunctors >=5.5 && <6 , containers >=0.6 && <1 - , range-set-list >=0.1.4 && <0.2 , distributors ==0.7.* , lens >=5.0 && <6 , monad-loops >=0.4.3 && <1 @@ -154,7 +153,6 @@ test-suite doctests , base >=4.20 && <5 , bifunctors >=5.5 && <6 , containers >=0.6 && <1 - , range-set-list >=0.1.4 && <0.2 , distributors ==0.7.* , distributors-grammar , doctest-parallel >=0.3 && <1 @@ -234,7 +232,6 @@ test-suite test , base >=4.20 && <5 , bifunctors >=5.5 && <6 , containers >=0.6 && <1 - , range-set-list >=0.1.4 && <0.2 , distributors , distributors-grammar , free >=5.1 && <6 @@ -307,7 +304,6 @@ benchmark core , base >=4.20 && <5 , bifunctors >=5.5 && <6 , containers >=0.6 && <1 - , range-set-list >=0.1.4 && <0.2 , distributors , distributors-grammar , lens >=5.0 && <6 diff --git a/distributors-grammar/package.yaml b/distributors-grammar/package.yaml index 1f57fd4c..ad1143a4 100644 --- a/distributors-grammar/package.yaml +++ b/distributors-grammar/package.yaml @@ -22,7 +22,6 @@ dependencies: - base >= 4.20 && < 5 - bifunctors >= 5.5 && < 6 - containers >= 0.6 && < 1 -- range-set-list >= 0.1.4 && < 0.2 - distributors >= 0.7 && < 0.8 - lens >= 5.0 && < 6 - MemoTrie >= 0.6 && < 1 diff --git a/distributors-grammar/src/Control/Lens/Grammar.hs b/distributors-grammar/src/Control/Lens/Grammar.hs index 18022a2c..e3a05b58 100644 --- a/distributors-grammar/src/Control/Lens/Grammar.hs +++ b/distributors-grammar/src/Control/Lens/Grammar.hs @@ -205,7 +205,7 @@ You can generate a regular expression string, a `RegEx`, from a `RegGrammar` with `Control.Lens.Grammar.regexG`. >>> putStringLn (regexG (type SemVer)) -\p{Nd}+.\p{Nd}+.\p{Nd}+(-(-|\p{Lu}|\p{Ll}|\p{Nd})+(.(-|\p{Lu}|\p{Ll}|\p{Nd})+)*)?(\+(-|\p{Lu}|\p{Ll}|\p{Nd})+(.(-|\p{Lu}|\p{Ll}|\p{Nd})+)*)? +\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}|-)+)*)? You can also generate parsers and printers. @@ -438,7 +438,7 @@ And the `satisfied` pattern is used together with the `Choice` & >>> :{ palindromeG :: CtxGrammatical Char p => p String String palindromeG = rule "palindrome" $ - satisfied (\wrd -> reverse wrd == wrd) >?< manyP (tokenAny @Char) + satisfied (\wrd -> reverse wrd == wrd) >?< manyP (anyToken @Char) :} >>> [pal | word <- ["racecar", "word"], (pal, "") <- parseP (palindromeG :: Parsor String [] String String) word] @@ -499,14 +499,13 @@ Since both t'Parsor' & t'Parsector' are @LL@ parsers they diverge if the `CtxGrammar` they're run on is left-recursive. >>> parsecP (rule "foo" (fail "bar") >|< fail "baz") "abc" -ParsecState {parsecLooked = False, parsecOffset = 0, parsecStream = "abc", parsecFailure = ParsecFailure {parsecExpect = fromRangeList [], parsecLabels = [Node {rootLabel = "foo", subForest = [Node {rootLabel = "bar", subForest = []}]},Node {rootLabel = "baz", subForest = []}]}, parsecResult = Nothing} +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} ->>> let failed = parsecP (manyP (token 'a') >*< asIn @Char DecimalNumber :: Parsector String (String, Char) (String, Char)) "aaab" ->>> (parsecOffset failed, parsecStream failed, toList (tokenClass (parsecExpect (parsecFailure failed)) :: RegEx Char)) -(3,"b","a|\\p{Nd}") +>>> parsecP (manyP (token 'a') >*< asIn @Char DecimalNumber :: Parsector String (String, Char) (String, Char)) "aaab" +ParsecState {parsecLooked = True, parsecOffset = 3, parsecStream = "b", parsecFailure = ParsecFailure {parsecExpect = TokenClass (Alternate (TokenClass (OneOf (fromList "a"))) (TokenClass (NotOneOf (fromList "") (AndAsIn DecimalNumber))) []), parsecLabels = []}, parsecResult = Nothing} >>> unparsecP (tokens "abc") "abx" "" -ParsecState {parsecLooked = True, parsecOffset = 2, parsecStream = "ab", parsecFailure = ParsecFailure {parsecExpect = fromRangeList [('c','c')], parsecLabels = []}, parsecResult = Nothing} +ParsecState {parsecLooked = True, parsecOffset = 2, parsecStream = "ab", parsecFailure = ParsecFailure {parsecExpect = TokenClass (OneOf (fromList "c")), parsecLabels = []}, parsecResult = Nothing} -} @@ -518,7 +517,7 @@ Since context-free `Grammar`s and `CtxGrammar`s aren't necessarily regular, the type system will prevent `regexG` from being applied to them. -} regexG - :: forall token. forall a -> (Lexical token, RegGrammar token a) + :: forall token. forall a -> (Categorized token, RegGrammar token a) => RegEx token regexG a = runGrammor (regGrammar @token @a) @@ -529,7 +528,7 @@ the type system will prevent `regbnfG` from being applied to a `CtxGrammar`. It can apply to a `RegGrammar`. -} regbnfG - :: forall token. forall a -> (Lexical token, Grammar token a) + :: forall token. forall a -> (Categorized token, Grammar token a) => Bnf (RegEx token) regbnfG a = runGrammor (grammar @token @a) @@ -550,7 +549,7 @@ usable as an intermediary for further generators like >>> import System.Random >>> let gen = mkStdGen 69 >>> evalState (take 15 <$> regexLang) gen -["","\818925","|","\291433\946528","\464496*","\1028123+","\912199?","\314471|","()","[]","\\(","|\464083","||","\32659\96026\1004166","\793549\38404*"] +["","|","\776269","()","[]","\\[","||","|\249908","\770923*","\1008821+","\318904?","\845807|","\477898\1026934","()*","()+"] >>> import Data.Tree (drawForest) @@ -596,7 +595,7 @@ usable as an intermediary for further generators like -} transducerG - :: forall token. forall a -> (Lexical token, Grammar token a) + :: forall token. forall a -> (Categorized token, Grammar token a) => Transducer token transducerG a = transducer (runGrammor (grammar @token @a)) @@ -610,7 +609,7 @@ from right to left. printG :: forall a string token m. CtxGrammar token a => Cons string string token token - => (IsList string, Item string ~ token, Lexical token) + => (IsList string, Item string ~ token, Categorized token) => (Alternative m, Monad m, Filterable m) => a {- ^ syntax -} -> m (string -> string) @@ -626,7 +625,7 @@ returning a syntax value and the remaining output string. parseG :: forall a string token m. CtxGrammar token a => (Cons string string token token, Snoc string string token token) - => (IsList string, Item string ~ token, Lexical token) + => (IsList string, Item string ~ token, Categorized token) => (Alternative m, Monad m, Filterable m) => string {- ^ input -} -> m (a, string) @@ -645,7 +644,7 @@ making printing to a `String` quadratic. unparseG :: forall a string token m. CtxGrammar token a => (Cons string string token token, Snoc string string token token) - => (IsList string, Item string ~ token, Lexical token) + => (IsList string, Item string ~ token, Categorized token) => (Alternative m, Monad m, Filterable m) => a {- ^ syntax -} -> string {- ^ input -} @@ -665,7 +664,7 @@ and a remaining output `parsecStream`. parsecG :: forall a string token. CtxGrammar token a => (Cons string string token token, Snoc string string token token) - => (Item string ~ token, Lexical token) + => (Item string ~ token, Categorized token) => string {- ^ input -} -> ParsecState string a parsecG = parsecP (ctxGrammar @token @a) @@ -685,7 +684,7 @@ making printing to a `String` quadratic. unparsecG :: forall a string token. CtxGrammar token a => (Cons string string token token, Snoc string string token token) - => (Item string ~ token, Lexical token) + => (Item string ~ token, Categorized token) => a {- ^ syntax -} -> string {- ^ input -} -> ParsecState string a @@ -702,7 +701,7 @@ applicativeG :: forall token a f. ( Grammar token a , Alternative f - , Tokenized token (f token) + , TokenAlgebra token (f token) , TerminalSymbol token (f ()) , forall x. BackusNaurForm (f x) , forall x. Tried (f x) @@ -731,15 +730,15 @@ newtype WrapMega a = WrapMega {unwrapMega :: M.Parsec String String a} ) instance TerminalSymbol Char (WrapMega ()) where terminal str = WrapMega (M.chunk str *> pure ()) -instance Tokenized Char (WrapMega Char) where +instance TokenAlgebra Char (WrapMega Char) where tokenClass exam = WrapMega $ M.label (show exam) (M.satisfy (tokenClass exam)) - tokenAny = WrapMega M.anySingle +instance Tokenized Char (WrapMega Char) where + anyToken = WrapMega M.anySingle token = WrapMega . M.single oneOf = WrapMega . M.oneOf notOneOf = WrapMega . M.noneOf asIn cat = WrapMega $ M.label ("in category " ++ show cat) (M.satisfy (asIn cat)) notAsIn cat = WrapMega $ M.label ("not in category " ++ show cat) (M.satisfy (notAsIn cat)) - tokenRange lo hi = WrapMega $ M.label ("in range " ++ show (lo, hi)) (M.satisfy (tokenRange lo hi)) instance Ruled (WrapMega a) where rule lbl (WrapMega p) = WrapMega (M.label lbl p) instance BackusNaurForm (WrapMega a) @@ -759,7 +758,7 @@ monadG , MonadPlus m, MonadFail m, Filterable m , forall x. BackusNaurForm (m x) , forall x. Tried (m x) - , Tokenized token (m token) + , TokenAlgebra token (m token) , TerminalSymbol token (m ()) ) => m a diff --git a/distributors-grammar/src/Control/Lens/Grammar/Analysis.hs b/distributors-grammar/src/Control/Lens/Grammar/Analysis.hs index 3a3c3e2b..acf6d674 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/Analysis.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/Analysis.hs @@ -72,13 +72,14 @@ foldRegEx tok nonterm = go KleenePlus x -> plusK (go x) KleeneTimes lo hi x -> timesK lo hi (go x) Backtracking x -> go x - RegExam cls -> tok cls - Alternate x y zs -> foldr1 (>|<) (map go (x : y : zs)) + 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 :: Lexical token => Bnf (RegEx token) -> Map String (RegEx token) +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', @@ -87,7 +88,7 @@ rules it names, until they stabilize, as they do for a monotone analysis into a lattice of finite height. -} fixRules - :: (Lexical token, Eq k) + :: (Categorized token, Eq k) => k -- ^ bottom -> (Map String k -> RegEx token -> k) -- ^ a body, given the rules -> Bnf (RegEx token) -> Map String k @@ -102,7 +103,7 @@ 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 = fromRangeList [('a','c')]} +Leading {leadingNullable = True, leadingAtoms = TokenClass (OneOf (fromList "abc"))} -} data Leading a = Leading { leadingNullable :: Bool -- ^ whether a word can be empty @@ -124,7 +125,7 @@ instance DisjunctiveMonoid a => KleeneStarAlgebra (Leading a) where {- | The nullability & first tokens of each rule of a t'Bnf'. -} firsts - :: Lexical token + :: Categorized token => Bnf (RegEx token) -> Map String (Leading (TokenClass token)) firsts = fixRules falseP firstOf @@ -132,7 +133,7 @@ firsts = fixRules falseP firstOf given those of the rules it names. -} firstOf - :: Lexical token + :: Categorized token => Map String (Leading (TokenClass token)) -> RegEx token -> Leading (TokenClass token) firstOf rules = @@ -141,7 +142,7 @@ firstOf rules = {- | The rules of a t'Bnf' which can name themselves before reading a token, on which a predictive parser diverges. -} -leftRecursive :: Lexical token => Bnf (RegEx token) -> Set String +leftRecursive :: Categorized token => Bnf (RegEx token) -> Set String leftRecursive bnf = Set.filter (\name -> name `Set.member` reach name) names where rules = bnfRules bnf @@ -167,22 +168,22 @@ data Guard token = Guard { guardEnd :: Bool -- ^ whether the input may end , guardNext :: TokenClass token -- ^ which tokens may be next } -deriving stock instance Lexical token => Eq (Guard token) -deriving stock instance Lexical token => Ord (Guard token) +deriving stock instance Categorized token => Eq (Guard token) +deriving stock instance Categorized token => Ord (Guard token) deriving stock instance - (Lexical token, Show (TokenTest token)) + (Categorized token, Show token, Show (Categorize token)) => Show (Guard token) -instance Lexical token => DisjunctiveMonoid (Guard token) where +instance Categorized token => DisjunctiveMonoid (Guard token) where falseP = Guard False falseP Guard end0 next0 >|< Guard end1 next1 = Guard (end0 || end1) (next0 >|< next1) -instance Lexical token => BooleanAlgebra (Guard token) where +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 - :: Lexical token + :: Categorized token => Leading (TokenClass token) -> Guard token -> Guard token guardOf (Leading nullable atoms) after | nullable = Guard False atoms >|< after @@ -190,7 +191,7 @@ guardOf (Leading nullable atoms) after -- each of a sequence's items, with the guard of what follows it sequenced - :: Lexical token + :: Categorized token => (RegEx token -> Leading (TokenClass token)) -> Guard token -> [RegEx token] -> [(RegEx token, Guard token)] sequenced first after = snd . foldr step (after, []) @@ -201,9 +202,9 @@ sequenced first after = snd . foldr step (after, []) & 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 = fromRangeList [('b','b')]})] +fromList [("a",Guard {guardEnd = True, guardNext = TokenClass (OneOf (fromList "b"))})] -} -follows :: Lexical token => Bnf (RegEx token) -> Map String (Guard token) +follows :: Categorized token => Bnf (RegEx token) -> Map String (Guard token) follows bnf = go (falseP <$ rules) where rules = bnfRules bnf @@ -223,7 +224,7 @@ follows bnf = go (falseP <$ rules) Backtracking x -> followed after x KleeneTimes lo hi x -> followed after (unrolled lo hi x) KleeneOpt x -> followed after x - Alternate x y zs -> Map.unionsWith (>|<) (map (followed after) (x : y : zs)) + RegExam (Alternate x y zs) -> Map.unionsWith (>|<) (map (followed after) (x : y : zs)) _ -> Map.empty where again x = Guard False (leadingAtoms (first x)) >|< after @@ -250,7 +251,7 @@ since a predictive parser then tries what follows anew. [] -} ll1Conflicts - :: Lexical token => Bnf (RegEx token) -> [LL1Conflict token] + :: Categorized token => Bnf (RegEx token) -> [LL1Conflict token] ll1Conflicts bnf = [ LL1Conflict (Just name) LL1LeftRecursion falseP (NonTerminal name) | name <- Set.toList (leftRecursive bnf) @@ -273,7 +274,7 @@ ll1Conflicts bnf = 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 - Alternate x y zs -> + 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) _ -> [] @@ -318,9 +319,9 @@ data LL1Conflict token = LL1Conflict , conflictTokens :: TokenClass token , conflictAt :: RegEx token } -deriving stock instance Lexical token => Eq (LL1Conflict token) +deriving stock instance Categorized token => Eq (LL1Conflict token) deriving stock instance - (Lexical token, Show (TokenTest token)) + (Categorized token, Show token, Show (Categorize token)) => Show (LL1Conflict token) -- | Sorts of `LL1Conflict`s. @@ -342,7 +343,7 @@ data LL1ConflictSort -- | Counts, unrolled, @x{lo,hi}@ as @lo@ times @x@ & then -- @x*@, or @hi - lo@ nested options. -unrolled :: Lexical token => Int -> Maybe Int -> RegEx token -> RegEx token +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 1d4a96ba..9fb8c5ac 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/BackusNaur.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/BackusNaur.hs @@ -110,7 +110,7 @@ class Tried p where @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) => Tokenized 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 diff --git a/distributors-grammar/src/Control/Lens/Grammar/Class.hs b/distributors-grammar/src/Control/Lens/Grammar/Class.hs index f8b693f0..d568e61b 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/Class.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/Class.hs @@ -55,11 +55,11 @@ class CtxGrammar token a where instance CtxGrammar Char Char instance Grammar Char Char where grammar = rule "Char" (regGrammar @Char) -instance RegGrammar Char Char where regGrammar = tokenAny @Char +instance RegGrammar Char Char where regGrammar = anyToken @Char instance CtxGrammar Char String instance Grammar Char String where grammar = rule "String" (regGrammar @Char) -instance RegGrammar Char String where regGrammar = manyP (tokenAny @Char) +instance RegGrammar Char String where regGrammar = manyP (anyToken @Char) instance CtxGrammar Char Natural instance Grammar Char Natural where grammar = rule "Natural" (regGrammar @Char) diff --git a/distributors-grammar/src/Control/Lens/Grammar/Machine.hs b/distributors-grammar/src/Control/Lens/Grammar/Machine.hs index 758aad1a..99331c24 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/Machine.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/Machine.hs @@ -42,15 +42,15 @@ class Matching word pattern | pattern -> word where (=~) :: word -> pattern -> Bool infix 2 =~ -- instances -instance Lexical token +instance Categorized token => Matching [token] (Transducer token) where word =~ et = acceptsChart n chart where (n, chart) = prefixGen et word -instance Lexical token +instance Categorized token => Matching [token] (Bnf (RegEx token)) where word =~ bnf = word =~ transducer bnf -instance Lexical token +instance Categorized token => Matching [token] (RegEx token) where word =~ pattern = word =~ liftBnf0 pattern instance Matching s (APrism s t a b) where @@ -97,7 +97,7 @@ A transducer is a form of finite state machine that can be run in various ways like `=~`, `expectNext`, `languageSample`, `parseForest` & `unreachableRules`. -} -transducer :: Lexical token => Bnf (RegEx token) -> Transducer token +transducer :: Bnf (RegEx token) -> Transducer token transducer (Bnf start rules) = Transducer { transducerRelations = IntMap.fromList allStates , transducerRules = Map.fromList @@ -125,8 +125,9 @@ transducer (Bnf start rules) = Transducer KleenePlus x -> rexNullable nm x KleeneTimes lo _ x -> lo == 0 || rexNullable nm x Backtracking x -> rexNullable nm x - Alternate x y zs -> any (rexNullable nm) (x : y : zs) - RegExam _ -> False + RegExam (Alternate x y zs) -> any (rexNullable nm) (x : y : zs) + RegExam (OneOf _) -> False + RegExam (NotOneOf _ _) -> False ruleNames = Map.keys ruleMap @@ -212,19 +213,25 @@ transducer (Bnf start rules) = Transducer 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 cls - | cls == falseP -> (IntSet.empty, [], nextId, False) + RegExam (OneOf chars) + | Set.null chars -> (IntSet.empty, [], nextId, False) | otherwise -> ( IntSet.singleton nextId - , [(nextId, TransitionTokenClass cls dests)] + , [(nextId, TransitionTokenClass (TokenClass (OneOf chars)) dests)] , nextId + 1 , False ) - Alternate rex0 rex1 rexes -> + RegExam (NotOneOf chars catTest) -> + ( IntSet.singleton nextId + , [(nextId, TransitionTokenClass (TokenClass (NotOneOf chars catTest)) dests)] + , nextId + 1 + , False + ) + RegExam (Alternate rex0 rex1 rexes) -> let rest = case rexes of [] -> rex1 - rex2 : rexes' -> Alternate rex1 rex2 rexes' + rex2 : rexes' -> RegExam (Alternate rex1 rex2 rexes') (firsts1, states1, nextId1, bypass1) = thompson rest nextId dests (firsts0, states0, nextId0, bypass0) = thompson rex0 nextId1 dests in @@ -236,7 +243,7 @@ transducer (Bnf start rules) = Transducer {- | The parse forest of a string of tokens. -} parseForest - :: Lexical token + :: Categorized token => Transducer token -> [token] -- ^ string -> ([Tree (String, Int, Int, [token])], [token]) @@ -343,7 +350,7 @@ parseForest et word = (concat (itemForests Set.empty Nothing 0 acceptedLen 0), d ] prefixGen - :: Lexical token + :: Categorized token => Transducer token -> [token] -> (Int, IntMap (IntMap IntSet)) @@ -373,7 +380,7 @@ A `falseP` result means the current chart has no scanner transitions, i.e. the prefix is a dead end for recognition. -} expectNext - :: Lexical token + :: Categorized token => Transducer token -> [token] {- ^ prefix -} -> TokenClass token expectNext et word = anyP fst (scanClassOptions et n chart) where @@ -409,10 +416,10 @@ unreachableRules et = `languageSample` lazily produces all words in a language from shortest to longest. However since t'TokenClass'es can resolve to infinite sets of tokens, and the relevant case of `Char` tokens while not infinite is huge, -it samples tokens in an `Applicative` `Tokenized`. +it samples tokens in an `Applicative` `TokenAlgebra`. -} languageSample - :: (Tokenized token (f token), Applicative f) + :: (TokenAlgebra token (f token), Applicative f) => Transducer token -- ^ transducer -> f [[token]] languageSample et = sequenceA (fmap sampleWord classWords) @@ -466,7 +473,7 @@ acceptsChart j chart = IntSet.member 0 acceptOrigins -- Group all scanner moves from E_j by token class; each result also carries the -- closed successor chart at j+1. scanClassOptions - :: Lexical token + :: Categorized token => Transducer token -> Int -> IntMap (IntMap IntSet) diff --git a/distributors-grammar/src/Control/Lens/Grammar/RegEx.hs b/distributors-grammar/src/Control/Lens/Grammar/RegEx.hs index 702aa119..92bb3322 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/RegEx.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/RegEx.hs @@ -31,16 +31,14 @@ import Control.Lens.Grammar.BackusNaur import Control.Lens.Grammar.Class import Control.Lens.Grammar.Symbol import Control.Lens.Grammar.Token -import Data.Char (isAscii) import Data.Coerce import Data.Bifunctor.Joker -import Data.List (minimumBy, nub) -import Data.Ord (comparing) +import Data.Foldable +import Data.List (nub) import Data.MemoTrie import Data.Monoid.Disjunctive import Data.Profunctor import qualified Data.Set as Set -import qualified Data.RangeSet.Map as RSet import Data.Set (Set) import Data.Maybe (fromMaybe, listToMaybe, mapMaybe) import Data.Profunctor.Distributor @@ -58,7 +56,7 @@ import Text.ParserCombinators.ReadP (readP_to_S) -- >>> import GHC.Exts (toList) {- | The `RegEx`pression type forms the prototypical `KleeneStarAlgebra`. -It is also a `Tokenized` and `tokenClass` acts homomorphically on disjunction. +It is also a `TokenAlgebra` and `tokenClass` acts homomorphically on disjunction. `RegEx`pressions may be understood as normalizations of `KleeneStarAlgebra` expressions generated by lexical token expressions. -} @@ -78,54 +76,59 @@ data RegEx token | KleeneTimes Int (Maybe Int) (RegEx token) -- | A pattern to backtrack from, by `try`, whose language is its own. | Backtracking (RegEx token) - -- | Two or more alternatives, none of them alternatives, in order. - | Alternate (RegEx token) (RegEx token) [RegEx token] - -- | A single token of a class. - | RegExam (TokenClass token) + | RegExam (TokenExam token (RegEx token)) --instances deriving stock instance Generic (RegEx token) -deriving stock instance Lexical token => Eq (RegEx token) -deriving stock instance Lexical token => Ord (RegEx token) +deriving stock instance Categorized token => Eq (RegEx token) +deriving stock instance Categorized token => Ord (RegEx token) deriving stock instance - (Lexical token, Read (TokenTest token)) + (Categorized token, Read token, Read (Categorize token)) => Read (RegEx token) deriving stock instance - (Lexical token, Show (TokenTest token)) + (Categorized token, Show token, Show (Categorize token)) => Show (RegEx token) -instance Lexical token => TerminalSymbol token (RegEx token) where +instance Categorized token => TerminalSymbol token (RegEx token) where terminal = foldl (\acc t -> acc <> token t) mempty instance NonTerminalSymbol (RegEx token) where nonTerminal = NonTerminal -instance Lexical token => Tokenized token (RegEx token) where - tokenClass = RegExam -instance Lexical token => Monoid (RegEx token) where +instance Categorized token => Tokenized token (RegEx token) where + anyToken = RegExam anyToken + token a = RegExam (OneOf (Set.singleton a)) + oneOf as = RegExam (OneOf (Set.fromList (toList as))) + notOneOf as = + RegExam (NotOneOf (Set.fromList (toList as)) (AndNotAsIn Set.empty)) + asIn cat = RegExam (NotOneOf Set.empty (AndAsIn cat)) + notAsIn cat = RegExam (NotOneOf Set.empty (AndNotAsIn (Set.singleton cat))) +instance Categorized token => TokenAlgebra token (RegEx token) where + tokenClass = foldTokenClass RegExam +instance Categorized token => Monoid (RegEx token) where mempty = SeqEmpty -- | Sequences are associative, as items normalized by `sequenced`. -instance Lexical token => Semigroup (RegEx token) where +instance Categorized token => Semigroup (RegEx token) where rex0 <> rex1 = sequenced (items rex0 <> items rex1) -- | Alternatives are associative, as normalized by `alternated`. -instance Lexical token => DisjunctiveMonoid (RegEx token) where - falseP = RegExam falseP +instance Categorized token => DisjunctiveMonoid (RegEx token) where + falseP = RegExam (OneOf Set.empty) rex0 >|< rex1 = alternated (alternatives rex0 <> alternatives rex1) -instance Lexical token => KleeneStarAlgebra (RegEx token) where - optK (RegExam cls) | cls == falseP = mempty +instance Categorized token => KleeneStarAlgebra (RegEx token) where + optK (RegExam exam) | isFailExam exam = mempty optK SeqEmpty = mempty optK (KleenePlus rex) = starK rex optK rex@(KleeneStar _) = rex optK rex@(KleeneOpt _) = rex optK rex = KleeneOpt rex - starK (RegExam cls) | cls == falseP = mempty + starK (RegExam exam) | isFailExam exam = mempty starK SeqEmpty = mempty starK rex = KleeneStar rex - plusK (RegExam cls) | cls == falseP = falseP + plusK (RegExam exam) | isFailExam exam = falseP plusK SeqEmpty = mempty plusK rex = KleenePlus rex timesK lo0 hi rex = case (max 0 lo0, hi) of (lo, Just m) | lo > m -> falseP _ | SeqEmpty <- rex -> mempty - (lo, _) | RegExam cls <- rex, cls == falseP -> + (lo, _) | RegExam exam <- rex, isFailExam exam -> if lo == 0 then mempty else falseP (0, Nothing) -> starK rex (1, Nothing) -> plusK rex @@ -133,7 +136,7 @@ instance Lexical token => KleeneStarAlgebra (RegEx token) where (0, Just 1) -> optK rex (1, Just 1) -> rex (lo, _) -> KleeneTimes lo hi rex -instance (Lexical token, HasTrie token, HasTrie (TokenClass token)) +instance (Categorized token, HasTrie token) => HasTrie (RegEx token) where data (RegEx token :->: b) = RegExTrie { seqEmptyTrie :: b @@ -145,7 +148,8 @@ instance (Lexical token, HasTrie token, HasTrie (TokenClass token)) , kleenePlusTrie :: RegEx token :->: b , kleeneTimesTrie :: ((Int, Maybe Int), RegEx token) :->: b , backtrackingTrie :: RegEx token :->: b - , classTrie :: TokenClass token :->: b + , oneOfTrie :: [token] :->: b + , notOneOfTrie :: ([token], Either Int [Int]) :->: b } trie f = RegExTrie { seqEmptyTrie = f mempty @@ -157,7 +161,8 @@ instance (Lexical token, HasTrie token, HasTrie (TokenClass token)) , kleenePlusTrie = trie (f . plusK) , kleeneTimesTrie = trie (f . \((lo, hi), x) -> timesK lo hi x) , backtrackingTrie = trie (f . try) - , classTrie = trie (f . RegExam) + , oneOfTrie = trie (f . oneOf) + , notOneOfTrie = trie (f . testNotOneOf) } untrie rex = \case SeqEmpty -> seqEmptyTrie rex @@ -168,8 +173,13 @@ instance (Lexical token, HasTrie token, HasTrie (TokenClass token)) KleeneOpt x -> untrie (kleeneOptTrie rex) x KleeneTimes lo hi x -> untrie (kleeneTimesTrie rex) ((lo, hi), x) Backtracking x -> untrie (backtrackingTrie rex) x - RegExam cls -> untrie (classTrie rex) cls - Alternate x y zs -> untrie (alternateTrie rex) (x : y : zs) + RegExam (OneOf chars) -> untrie (oneOfTrie rex) (Set.toList chars) + RegExam (NotOneOf chars (AndAsIn cat)) -> + untrie (notOneOfTrie rex) (Set.toList chars, Left (fromEnum cat)) + RegExam (NotOneOf chars (AndNotAsIn cats)) -> + untrie (notOneOfTrie rex) + (Set.toList chars, Right (Set.toList (Set.map fromEnum cats))) + RegExam (Alternate x y zs) -> untrie (alternateTrie rex) (x : y : zs) enumerate rex = mconcat [ [(SeqEmpty, seqEmptyTrie rex)] , first' NonTerminal <$> enumerate (nonTerminalTrie rex) @@ -181,8 +191,21 @@ instance (Lexical token, HasTrie token, HasTrie (TokenClass token)) , first' (\((lo, hi), x) -> KleeneTimes lo hi x) <$> enumerate (kleeneTimesTrie rex) , first' Backtracking <$> enumerate (backtrackingTrie rex) - , first' RegExam <$> enumerate (classTrie rex) + , first' (RegExam . OneOf . Set.fromList) <$> enumerate (oneOfTrie rex) + , first' testNotOneOf <$> enumerate (notOneOfTrie rex) ] +testNotOneOf + :: Categorized token + => ([token], Either Int [Int]) -> RegEx token +testNotOneOf (chars, catTest) = RegExam $ NotOneOf + (Set.fromList chars) + (either (AndAsIn . toEnum) (AndNotAsIn . Set.map toEnum . Set.fromList) catTest) + +-- | Whether a token examination fails to match any token. +isFailExam :: TokenExam token alg -> Bool +isFailExam = \case + OneOf tokens' -> Set.null tokens' + _ -> False -- | The items of a sequence. items :: RegEx token -> [RegEx token] @@ -200,7 +223,7 @@ items = \case so that sequences of sequences are associative. -} -sequenced :: Lexical token => [RegEx token] -> RegEx token +sequenced :: Categorized token => [RegEx token] -> RegEx token sequenced rexes | any isFail rexes = falseP | otherwise = case rewrite rexes of @@ -209,7 +232,7 @@ sequenced rexes rex0 : rex1 : rexes' -> Sequence rex0 rex1 rexes' where isFail = \case - RegExam cls -> cls == falseP + RegExam exam -> isFailExam exam _ -> False rewrite xs = maybe xs rewrite (step xs) step = \case @@ -249,10 +272,10 @@ sequenced rexes [] -> Nothing -- | The alternatives of an alternation, with the empty word for an option. -alternatives :: Lexical token => RegEx token -> [RegEx token] +alternatives :: RegEx token -> [RegEx token] alternatives = \case - RegExam cls | cls == falseP -> [] - Alternate rex0 rex1 rexes -> rex0 : rex1 : rexes + RegExam (OneOf tokens') | Set.null tokens' -> [] + RegExam (Alternate rex0 rex1 rexes) -> rex0 : rex1 : rexes KleeneOpt rex -> alternatives rex <> [SeqEmpty] KleeneStar rex -> [KleenePlus rex, SeqEmpty] rex -> [rex] @@ -262,13 +285,13 @@ in place of the first, the empty word makes them optional, & each is kept once, in order, so that alternatives of alternatives are associative. -} -alternated :: Lexical token => [RegEx token] -> RegEx token +alternated :: Categorized token => [RegEx token] -> RegEx token alternated rexes = (if SeqEmpty `elem` rexes then optK else id) $ case nub (unionTokens [rex | rex <- rexes, rex /= SeqEmpty]) of [] -> falseP [rex] -> rex - rex0 : rex1 : rexes' -> Alternate rex0 rex1 rexes' + rex0 : rex1 : rexes' -> RegExam (Alternate rex0 rex1 rexes') where unionTokens xs = case [cls | x <- xs, Just cls <- [tokenOf x]] of [] -> xs @@ -280,7 +303,9 @@ alternated rexes = x : rest -> x : placeFirst union rest [] -> [] tokenOf = \case - RegExam cls -> Just cls + RegExam (OneOf tokens') -> Just (TokenClass (OneOf tokens')) + RegExam (NotOneOf tokens' test) -> + Just (TokenClass (NotOneOf tokens' test)) _ -> Nothing {- | A t'Bnf' consists of a distinguished starting rule @@ -324,7 +349,7 @@ See Might, Darais & Spiewak, [Parsing With Derivatives] (https://matt.might.net/papers/might2011derivatives.pdf). -} diffB - :: (Lexical token, HasTrie token, HasTrie (TokenClass token)) + :: (Categorized token, HasTrie token) => [token] -> Bnf (RegEx token) -> Bnf (RegEx token) diffB prefix (Bnf start rules) = Bnf (foldl' (flip diff1B) start prefix) rules @@ -345,11 +370,18 @@ diffB prefix (Bnf start rules) = KleenePlus y -> diff1B x y <> starK y KleeneTimes lo hi y -> diff1B x y <> timesK (lo - 1) (subtract 1 <$> hi) y - RegExam cls -> if tokenClass cls x then mempty else falseP - Alternate y1 y2 ys -> anyP (diff1B x) (y1 : y2 : ys) + 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? -δ :: (Lexical token, HasTrie token, HasTrie (TokenClass token)) +δ :: (Categorized token, HasTrie token) => Bnf (RegEx token) -> Bool δ (Bnf start rules) = ν start where ν = memo $ \case @@ -360,7 +392,7 @@ diffB prefix (Bnf start rules) = KleenePlus y -> ν y KleeneTimes lo _ y -> lo == 0 || ν y Sequence y1 y2 ys -> all ν (y1 : y2 : ys) - Alternate y1 y2 ys -> any ν (y1 : y2 : ys) + RegExam (Alternate y1 y2 ys) -> any ν (y1 : y2 : ys) NonTerminal nameY -> any ν (rulesNamed nameY rules) _ -> False @@ -381,11 +413,11 @@ 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 Lexical token => Tried (RegEx token) where +instance Tried (RegEx token) where try rex = case rex of Backtracking _ -> rex SeqEmpty -> rex - RegExam cls | cls == falseP -> rex + RegExam exam | isFailExam exam -> rex _ -> Backtracking rex instance (Ord rule, TerminalSymbol token rule) => TerminalSymbol token (Bnf rule) where @@ -395,13 +427,14 @@ instance (Ord rule, NonTerminalSymbol rule) nonTerminal = liftBnf0 . nonTerminal instance (Ord rule, Tokenized token rule) => Tokenized token (Bnf rule) where - tokenAny = liftBnf0 tokenAny + anyToken = liftBnf0 anyToken token = liftBnf0 . token oneOf = liftBnf0 . oneOf notOneOf = liftBnf0 . notOneOf asIn = liftBnf0 . asIn notAsIn = liftBnf0 . notAsIn - tokenRange lo = liftBnf0 . tokenRange lo +instance (Ord rule, TokenAlgebra token rule) + => TokenAlgebra token (Bnf rule) where tokenClass = liftBnf0 . tokenClass instance (Ord rule, KleeneStarAlgebra rule) => KleeneStarAlgebra (Bnf rule) where @@ -419,15 +452,8 @@ instance (Ord rule, Semigroup rule) => Semigroup (Bnf rule) where makeNestedPrisms ''Bnf makeNestedPrisms ''RegEx - -{- | The forms of a class of characters, in regular expression strings: -listed, or not listed, of a category, or of none of some categories. -} -data ClassForm - = ClassOneOf (TokenRanges Char) - | ClassNotOneOf (TokenRanges Char) KindForm -data KindForm = AndAsIn GeneralCategory | AndNotAsIn (Set GeneralCategory) -makeNestedPrisms ''ClassForm -makeNestedPrisms ''KindForm +makeNestedPrisms ''TokenExam +makeNestedPrisms ''CategoryTest makeNestedPrisms ''GeneralCategory {- | The context-free `Grammar` @@ -458,7 +484,7 @@ with @Control.Lens.Grammar.regexG@. A regular expression string is stored as an algebraic datatype, a `RegEx`. >>> rex -Alternate (Sequence (RegExam (fromRangeList [('a','a')])) (RegExam (fromRangeList [('b','b')])) []) (RegExam (fromRangeList [('c','c')])) [] +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 @@ -503,7 +529,7 @@ as well as the wildcard, matching any single character. >>> toList (falseP :: RegEx Char) "[]" ->>> toList (tokenAny :: RegEx Char) +>>> toList (anyToken :: RegEx Char) "[^]" Additional forms of character classes test for a character's `GeneralCategory`. @@ -572,16 +598,8 @@ regexGrammar = ruleRec "regex" altG seqG rex = rule "sequence" $ iso itemsOf mconcat >~ manyP (exprG rex) - -- a class which prints as one form; others print as alternatives - _RegExamOne = prism' RegExam $ \case - RegExam cls | [_] <- bestForms cls -> Just cls - _ -> Nothing - -- a class prints as alternatives where they're shorter, parsing back to it - alternativesOf = concatMap splitClass . \case - Alternate rex0 rex1 rexes -> rex0 : rex1 : rexes - rex -> [rex] - splitClass = \case - RegExam cls -> RegExam . classOfForm <$> bestForms cls + alternativesOf = \case + RegExam (Alternate rex0 rex1 rexes) -> rex0 : rex1 : rexes rex -> [rex] itemsOf = \case @@ -612,7 +630,7 @@ regexGrammar = ruleRec "regex" altG atomG rex = rule "atom" $ orP [ _NonTerminal >? terminal "\\q" >* nonterminalG , _Backtracking >? terminal "\\t{" >* rex *< terminal "}" - , _RegExamOne >? classG + , _RegExam >? classG , terminal "(" >* rex *< terminal ")" ] @@ -649,10 +667,9 @@ regexGrammar = ruleRec "regex" altG , _NotAssigned >? terminal "Cn" ] - -- a class prints by its shortest form, & parses by any, an improper iso - classG = rule "class" $ iso bestForm classOfForm >~ orP - [ _ClassOneOf >? classOneOfG - , _ClassNotOneOf >? classNotOneOfG + classG = rule "class" $ orP + [ _OneOf >? classOneOfG + , _NotOneOf >? classNotOneOfG ] classCatG = rule "class-category" $ orP @@ -674,12 +691,14 @@ regexGrammar = ruleRec "regex" altG -- 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 (foldr ((>|<) . runOf) falseP) >~ manyP (rule "class-range" $ + rangedG = iso runsOf (foldMap runOf) >~ manyP (rule "class-range" $ classCharG >*< optionalP (terminal "-" >* classCharG)) - -- ranges, of the set's own form, are never enumerated - runOf (lo, hi0) = let hi = fromMaybe lo hi0 in - if lo > hi then falseP else TokenRanges (RSet.singletonRange (lo, hi)) - runsOf (TokenRanges chars) = concatMap run (RSet.toRangeList chars) + 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' -> @@ -705,55 +724,7 @@ regexGrammar = ruleRec "regex" altG ranged lo hi | fromEnum hi - fromEnum lo >= 2 = [(lo, Just hi)] | otherwise = [(c, Nothing) | c <- [lo .. hi]] - plain c = c `notElem` ('-' : charsReserved) && tokenKind c /= Control - classOfForm = TokenClass . \case - ClassOneOf chars -> chars - ClassNotOneOf chars kinds -> notP chars >&< kindsOf kinds - kindsOf = \case - AndAsIn cat -> categoryOf cat - AndNotAsIn cats -> notP (testKinds @Char (TokenKinds cats)) - categoryOf cat = testKinds @Char (TokenKinds (Set.singleton cat)) - -- listed, or not listed & of none of the categories it excludes, - -- or not listed & of a category including it - bestForm :: TokenClass Char -> ClassForm - bestForm (TokenClass chars) = minimumBy (comparing formCost) $ - ClassOneOf chars - : ClassNotOneOf (notP chars >&< notP (testKinds @Char (TokenKinds outs))) (AndNotAsIn outs) - : [ ClassNotOneOf (categoryOf cat >&< notP chars) (AndAsIn cat) - | cat <- [minBound .. maxBound] - , chars >&< notP (categoryOf cat) == falseP ] - where - outs = Set.fromList - [cat | cat <- [minBound .. maxBound], categoryOf cat >&< chars == falseP] - -- a class as alternatives: its best form, or else the rest of it, - -- & the categories wholly within it, each, or by the others - bestForms :: TokenClass Char -> [ClassForm] - bestForms (TokenClass chars) - | null ins = [bestForm (TokenClass chars)] - | otherwise = minimumBy (comparing (sum . map formCost)) - [ [bestForm (TokenClass chars)] - , restForms <> map (ClassNotOneOf falseP . AndAsIn) ins - , restForms <> [ClassNotOneOf falseP (AndNotAsIn partials)] - ] - where - cats = [minBound .. maxBound] - ins = [cat | cat <- cats, categoryOf cat >&< notP chars == falseP] - partials = Set.fromList [cat | cat <- cats, cat `notElem` ins] - rest = chars >&< notP (testKinds @Char (TokenKinds (Set.fromList ins))) - restForms = [bestForm (TokenClass rest) | rest /= falseP] - -- the estimated length of a form's string - formCost = \case - ClassOneOf chars -> 2 + rangesCost chars - ClassNotOneOf chars kinds -> 3 + rangesCost chars + case kinds of - AndAsIn _ -> 5 - AndNotAsIn cats -> if Set.null cats then 0 else 4 + 3 * Set.size cats - rangesCost = sum . map runCost . runsOf - runCost (lo, hi) = charCost lo + maybe 0 ((1 +) . charCost) hi - charCost c - | not (isAscii c) = 10 - | plain c = 1 - | c `elem` ('-' : charsReserved) = 2 - | otherwise = 4 :: Int + plain c = c `notElem` ('-' : charsReserved) && categorize c /= Control nonterminalG :: Grammatical Char p => p String String nonterminalG = rule "nonterminal" $ diff --git a/distributors-grammar/src/Control/Lens/Grammar/Token.hs b/distributors-grammar/src/Control/Lens/Grammar/Token.hs index beedbc49..7f244647 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/Token.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/Token.hs @@ -13,41 +13,31 @@ module Control.Lens.Grammar.Token Tokenized (..) , satisfy , tokens - -- * Lexical - , Lexical (..) - , TokenClass (..) + -- * Categorized + , Categorized (..) , GeneralCategory (..) - -- * Tests - , TokenKinds (..) - , TokenRanges (..) - , Cofinite (..) - , cofiniteMember - , ByKind (..) - -- * Tagged tokens - -- $tagged - , taggedTest - , taggedOneOf - , taggedKinds - , taggedFinite + -- * TokenAlgebra + , TokenAlgebra (..) + , TokenClass (..) + , foldTokenClass + , TokenExam (..) + , CategoryTest (..) ) where import Control.Lens import Control.Lens.PartialIso import Control.Monad.Loops (iterateUntil) -import Data.Set (Set) -import qualified Data.Set as Set import Data.Bifunctor.Joker import Data.Char import Data.Foldable +import Data.List (nub) import Data.Profunctor import Data.Monoid.Disjunctive +import Data.Profunctor.Distributor import Data.Profunctor.Monoidal -import Data.RangeSet.Map (RSet) -import qualified Data.RangeSet.Map as RSet -import GHC.Exts (IsList (Item)) -import qualified GHC.Exts as Exts -import qualified Text.Read as Read -import Text.Read (readPrec) +import Data.Set (Set) +import qualified Data.Set as Set +import GHC.Generics (Generic, Generic1) import Data.Word import Control.Monad.State (StateT, state) import System.Random (RandomGen, Random, random, randomR) @@ -60,174 +50,82 @@ 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. +>>> :kind! Categorize Char +Categorize Char :: * += GeneralCategory -import qualified Data.Map.Strict as Map -import Data.MemoTrie (HasTrie (..), (:->:)) -import Data.Bifunctor (first) -import Data.Map.Strict (Map) - -{- | `Lexical` tokens have kinds, telling their lexical roles, like -an identifier's or a keyword's, or a character's `GeneralCategory`, -& a `BooleanAlgebra` of tests of them, `TokenTest`s, generated by tests -of which tokens they are, of which kinds they are, & of which ranges -they're in, where they're enumerable. - ->>> tokenKind 'a' +>>> categorize 'a' LowercaseLetter - -Each test has one form, so that `TokenTest`s are equal just when they -test alike, & `tokenTest` is a homomorphism of `BooleanAlgebra`s. - -> prop> tokenTest trueP = const True -> prop> tokenTest (notP x) = not . tokenTest x -> prop> tokenTest (x >|< y) t = tokenTest x t || tokenTest y t -> prop> tokenTest (x >&< y) t = tokenTest x t && tokenTest y t -> prop> tokenTest (testOneOf ts) = (`elem` ts) -> prop> tokenTest (testKinds (TokenKinds ks)) = (`Set.member` ks) . tokenKind -> prop> tokenTest (testRange lo hi) t = lo <= t && t <= hi --} -class - ( Ord token - , Ord (TokenKind token), Enum (TokenKind token), Bounded (TokenKind token) - , BooleanAlgebra (TokenTest token), Ord (TokenTest token) - ) => Lexical token where - - {- | The kinds of tokens, none but @()@ by default. -} - type TokenKind token - type TokenKind token = () - {- | A token's kind. -} - tokenKind :: token -> TokenKind token - default tokenKind :: TokenKind token ~ () => token -> TokenKind token - tokenKind _ = () - - {- | The tests of tokens, by default `TokenRanges` of bounded, enumerable - tokens; `Cofinite` sets of others, or `ByKind` tests of tagged ones. -} - type TokenTest token - type TokenTest token = TokenRanges token - {- | Does a token pass a test? -} - tokenTest :: TokenTest token -> token -> Bool - default tokenTest - :: TokenTest token ~ TokenRanges token => TokenTest token -> token -> Bool - tokenTest = flip rangesMember - {- | The test of being one of some tokens. -} - testOneOf :: [token] -> TokenTest token - default testOneOf - :: (TokenTest token ~ TokenRanges token, Enum token) - => [token] -> TokenTest token - testOneOf = Exts.fromList - {- | The test of being of one of some kinds. -} - testKinds :: TokenKinds (TokenKind token) -> TokenTest token - default testKinds - :: TokenKind token ~ () => TokenKinds (TokenKind token) -> TokenTest token - testKinds (TokenKinds ks) = if Set.member () ks then trueP else falseP - {- | The test of being between two tokens, inclusive, by their - enumeration, for tokens whose `Enum` & `Ord` agree. -} - testRange :: Enum token => token -> token -> TokenTest token - default testRange - :: TokenTest token ~ TokenRanges token - => token -> token -> TokenTest token - testRange = rangesBetween - {- | The tokens which pass a test, by their number & their index, - where they're finitely many & listable, so that generators sample them - uniformly, rather than by rejection. -} - testFinite :: TokenTest token -> Maybe (Int, Int -> token) - default testFinite - :: (TokenTest token ~ TokenRanges token, Enum token) - => TokenTest token -> Maybe (Int, Int -> token) - testFinite = rangesFinite - -instance Lexical Char where - type TokenKind Char = GeneralCategory - tokenKind = generalCategory - testKinds (TokenKinds cats) = foldr ((>|<) . categoryRanges) falseP cats -instance Lexical Word8 -instance Lexical () - -{- | A class of tokens, by their `TokenTest`, a `Tokenized` -`BooleanAlgebra`, such that the following hold. - -> prop> trueP = tokenAny -> prop> falseP = oneOf [] -> prop> notP . oneOf = notOneOf -> prop> notP . asIn = notAsIn -} -newtype TokenClass token = TokenClass {classTest :: TokenTest token} -deriving newtype instance Lexical token => Eq (TokenClass token) -deriving newtype instance Lexical token => Ord (TokenClass token) -deriving newtype instance Lexical token => DisjunctiveMonoid (TokenClass token) -deriving newtype instance Lexical token => BooleanAlgebra (TokenClass token) -deriving newtype instance Show (TokenTest token) => Show (TokenClass token) -deriving newtype instance Read (TokenTest token) => Read (TokenClass token) -instance Lexical token => Tokenized token (TokenClass token) where - tokenClass = id - -{- | `Tokenized` combinators for constructing lexical tokens, -each a `tokenClass` by default. - -> prop> tokenAny = tokenClass trueP -> prop> token t = tokenClass (oneOf [t]) - -When a `Tokenized` is a `DisjunctiveMonoid`, then -`tokenClass` is expected to act homomorphically on disjunction. - -> prop> falseP = tokenClass falseP -> prop> tokenClass x >|< tokenClass y = tokenClass (x >|< y) --} -class Lexical token => Tokenized token p | p -> token where - {-# MINIMAL tokenAny | tokenClass #-} - - {- | A single token of a class. -} - tokenClass :: TokenClass token -> p - default tokenClass - :: (p ~ q token token, Choice q, Cochoice q) - => TokenClass token -> p - tokenClass (TokenClass test) = satisfy (tokenTest test) - +class (Ord token, Ord (Categorize token), Enum (Categorize token)) + => Categorized token where + type Categorize token + type Categorize token = () + categorize :: token -> Categorize token + default categorize :: Categorize token ~ () => token -> Categorize token + categorize _ = () +instance Categorized Char where + type Categorize Char = GeneralCategory + categorize = generalCategory +instance Categorized Word8 +instance Categorized () + +{- | `Tokenized` combinators for constructing lexical tokens. -} +class Categorized token => Tokenized token p | p -> token where {- | Any single token. -} - tokenAny :: p - tokenAny = tokenClass trueP + anyToken :: p {- | A single specified `token`. -} token :: token -> p - token t = tokenClass (TokenClass (testOneOf [t])) + default token + :: (p ~ q token token, Choice q, Cochoice q) + => token -> p + token = satisfy . token {- | A single token which is `oneOf` a set. > prop> token x = oneOf [x] + -} oneOf :: Foldable f => f token -> p - oneOf = tokenClass . TokenClass . testOneOf . toList + default oneOf + :: (p ~ q token token, Choice q, Cochoice q, Foldable f) + => f token -> p + oneOf = satisfy . oneOf {- | A single token which is `notOneOf` a set. - - > prop> tokenAny = notOneOf [] + + > prop> anyToken = notOneOf [] + -} notOneOf :: Foldable f => f token -> p - notOneOf = tokenClass . TokenClass . notP . testOneOf . toList - - {- | A single token which is `asIn` a kind. -} - asIn :: TokenKind token -> p - asIn kind = tokenClass (TokenClass (testKinds @token (TokenKinds (Set.singleton kind)))) - - {- | A single token which is `notAsIn` a kind. -} - notAsIn :: TokenKind token -> p - notAsIn kind = - tokenClass (TokenClass (notP (testKinds @token (TokenKinds (Set.singleton kind))))) - - {- | A single token between two, inclusive, by their enumeration, - for tokens whose `Enum` & `Ord` agree. + default notOneOf + :: (p ~ q token token, Choice q, Cochoice q, Foldable f) + => f token -> p + notOneOf = satisfy . notOneOf + + {- | A single token which is `asIn` a category. -} + asIn :: Categorize token -> p + default asIn + :: (p ~ q token token, Choice q, Cochoice q) + => Categorize token -> p + asIn = satisfy . asIn - > prop> tokenRange lo hi = oneOf [lo .. hi] - -} - tokenRange :: Enum token => token -> token -> p - tokenRange lo hi = tokenClass (TokenClass (testRange lo hi)) + {- | A single token which is `notAsIn` a category. -} + notAsIn :: Categorize token -> p + default notAsIn + :: (p ~ q token token, Choice q, Cochoice q) + => Categorize token -> p + notAsIn = satisfy . notAsIn {- | A single token that satisfies a predicate. -} satisfy :: (Tokenized a (p a a), Choice p, Cochoice p) => (a -> Bool) -> p a a -satisfy f = satisfied f >?< tokenAny +satisfy f = satisfied f >?< anyToken {- | A specified stream of `tokens`. -} tokens @@ -239,237 +137,309 @@ tokens tokens = foldr ((>:<) . token) asEmpty -- instances -instance Lexical token => Tokenized token (token -> Bool) where - tokenClass (TokenClass test) = tokenTest test - tokenAny _ = True +instance Categorized token => Tokenized token (token -> Bool) where + anyToken _ = True token = (==) - asIn = lmap tokenKind . (==) - notAsIn = lmap tokenKind . (/=) - tokenRange lo hi x = lo <= x && x <= hi -deriving via (token -> Bool) instance Lexical token - => Tokenized token (Predicate token) + -- Tokens are collected into a `Set` once, & tested logarithmically. + oneOf xs = (`Set.member` members) where members = Set.fromList (toList xs) + notOneOf xs = (`Set.notMember` members) + where members = Set.fromList (toList xs) + asIn = lmap categorize . (==) + notAsIn = lmap categorize . (/=) instance Tokenized token (f token) => Tokenized token (Joker f token token) where - tokenClass = Joker . tokenClass @token - tokenAny = Joker (tokenAny @token) + anyToken = Joker (anyToken @token) token = Joker . token @token oneOf = Joker . oneOf @token notOneOf = Joker . notOneOf @token asIn = Joker . asIn @token notAsIn = Joker . notAsIn @token - tokenRange lo hi = Joker (tokenRange @token lo hi) instance Tokenized Char (ReadP Char) where - tokenClass = ReadP.satisfy . tokenClass - tokenAny = ReadP.get + anyToken = ReadP.get token = ReadP.char + oneOf = ReadP.satisfy . oneOf + notOneOf = ReadP.satisfy . notOneOf + asIn = ReadP.satisfy . asIn + notAsIn = ReadP.satisfy . notAsIn instance Tokenized Char (ReadPrec Char) where - tokenClass = ReadPrec.lift . tokenClass - tokenAny = ReadPrec.lift tokenAny + anyToken = ReadPrec.lift anyToken token = ReadPrec.lift . token -instance (Lexical token, Arbitrary token) => Tokenized token (Gen token) where - -- finitely many tokens are sampled uniformly, & others by rejection - tokenClass (TokenClass test) = case testFinite test of - Just (n, nth) | n > 0 -> nth <$> Gen.chooseInt (0, n - 1) - _ -> arbitrary `Gen.suchThat` tokenTest test - tokenAny = arbitrary @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 -instance (RandomGen g, Monad m, Lexical token, Random token) + oneOf = Gen.elements . toList + notOneOf xs = arbitrary `Gen.suchThat` (`notElem` xs) + asIn cat = arbitrary `Gen.suchThat` ((==) cat . categorize) + notAsIn cat = arbitrary `Gen.suchThat` ((/=) cat . categorize) +instance (RandomGen g, Monad m, Categorized token, Random token) => Tokenized token (StateT g m token) where - tokenClass (TokenClass test) = case testFinite test of - Just (n, nth) | n > 0 -> nth <$> state (randomR (0, n - 1)) - _ -> iterateUntil (tokenTest test) tokenAny - tokenAny = state random + anyToken = state random token = pure + oneOf xs = do + let ys = toList xs + i <- state (randomR (0, length ys - 1)) + pure (ys !! i) + notOneOf xs = iterateUntil (`notElem` xs) anyToken + asIn cat = iterateUntil ((== cat) . categorize) anyToken + notAsIn cat = iterateUntil ((/= cat) . categorize) anyToken + +{- | A token examination, by the tokens it accepts, & the alternatives +of an algebra, whose fixed point is t'TokenClass'. Both t'TokenClass'es & +`Control.Lens.Grammar.RegEx.RegEx`pressions are algebras over it. +-} +data TokenExam token alg + = OneOf (Set token) + | NotOneOf (Set token) (CategoryTest token) + {- | Two or more alternatives, none of them alternatives, + in the order they're written. + -} + | Alternate alg alg [alg] + +failExam :: TokenExam token alg +failExam = OneOf Set.empty + +passExam :: TokenExam token alg +passExam = NotOneOf Set.empty (AndNotAsIn Set.empty) -{- | Tests of kinds, any set of them, a `BooleanAlgebra` of bounded, -enumerable kinds, complementing within all of them. -} -newtype TokenKinds kind = TokenKinds (Set kind) - deriving stock (Eq, Ord, Show, Read) -instance Ord kind => DisjunctiveMonoid (TokenKinds kind) where - falseP = TokenKinds Set.empty - TokenKinds xs >|< TokenKinds ys = TokenKinds (Set.union xs ys) -instance (Ord kind, Enum kind, Bounded kind) - => BooleanAlgebra (TokenKinds kind) where - trueP = TokenKinds (Set.fromList [minBound .. maxBound]) - notP (TokenKinds xs) = TokenKinds (Set.fromList [minBound .. maxBound] Set.\\ xs) - TokenKinds xs >&< TokenKinds ys = TokenKinds (Set.intersection xs ys) - -{- | Tests of enumerable tokens, by their disjoint ranges, of -[range-set-list](https://hackage.haskell.org/package/range-set-list), -a `BooleanAlgebra` of bounded tokens, each test having one form. -They `Show` & `Read` by their ranges' list. +isFailExam :: TokenExam token alg -> Bool +isFailExam (OneOf xs) = Set.null xs +isFailExam _ = False + +isPassExam :: TokenExam token alg -> Bool +isPassExam (NotOneOf xs (AndNotAsIn ys)) = Set.null xs && Set.null ys +isPassExam _ = False + +-- | The alternatives of an examination of t'TokenClass'es. +examAlternatives + :: TokenExam token (TokenClass token) -> [TokenExam token (TokenClass token)] +examAlternatives = \case + Alternate x y zs -> [exam | TokenClass exam <- x : y : zs] + exam -> [exam] + +{- | Alternatives, normalized: any which passes every token passes, +those which fail none are dropped, those of `OneOf` some tokens are one, +in place of the first, & each is kept once, in order, so that the +alternatives of alternatives are associative. -} -newtype TokenRanges token = TokenRanges (RSet token) - deriving newtype (Eq, Ord) -instance (Ord token, Enum token) => IsList (TokenRanges token) where - type Item (TokenRanges token) = token - fromList = TokenRanges . RSet.fromList - toList (TokenRanges xs) = RSet.toList xs -instance AsEmpty (TokenRanges token) where - _Empty = nearly (TokenRanges RSet.empty) (\(TokenRanges xs) -> RSet.null xs) -instance (Ord token, Enum token) => DisjunctiveMonoid (TokenRanges token) where - falseP = TokenRanges RSet.empty - TokenRanges xs >|< TokenRanges ys = TokenRanges (RSet.union xs ys) -instance (Ord token, Enum token, Bounded token) - => BooleanAlgebra (TokenRanges token) where - trueP = TokenRanges RSet.full - notP (TokenRanges xs) = TokenRanges (RSet.complement xs) - TokenRanges xs >&< TokenRanges ys = TokenRanges (RSet.intersection xs ys) -instance (Ord token, Enum token, Show token) => Show (TokenRanges token) where - showsPrec d (TokenRanges xs) = showParen (d > 10) $ - showString "fromRangeList " . shows (RSet.toRangeList xs) -instance (Ord token, Enum token, Read token) => Read (TokenRanges token) where - readPrec = Read.parens $ ReadPrec.prec 10 $ do - Read.Ident "fromRangeList" <- Read.lexP - TokenRanges . RSet.fromRangeList <$> ReadPrec.step readPrec - -rangesMember :: Ord token => token -> TokenRanges token -> Bool -rangesMember x (TokenRanges xs) = RSet.member x xs - -rangesBetween :: Ord token => token -> token -> TokenRanges token -rangesBetween lo hi - | lo > hi = TokenRanges RSet.empty - | otherwise = TokenRanges (RSet.singletonRange (lo, hi)) - --- | The tokens of ranges, by their number & index, listing the ranges. -rangesFinite :: Enum token => TokenRanges token -> Maybe (Int, Int -> token) -rangesFinite (TokenRanges xs) = Just (sum (map size runs), nth runs) +alternatives + :: Categorized token + => [TokenExam token (TokenClass token)] -> TokenExam token (TokenClass token) +alternatives exams + | any isPassExam exams = passExam + | otherwise = case nub (unionOneOfs (filter (not . isFailExam) exams)) of + [] -> failExam + [exam] -> exam + exam0 : exam1 : exams' -> + Alternate (TokenClass exam0) (TokenClass exam1) (map TokenClass exams') where - runs = RSet.toRangeList xs - size (lo, hi) = fromEnum hi - fromEnum lo + 1 - nth ((lo, hi) : rest) i - | i < size (lo, hi) = toEnum (fromEnum lo + i) - | otherwise = nth rest (i - size (lo, hi)) - nth [] _ = error "rangesFinite: out of range" - --- | Each `GeneralCategory`'s characters, by their ranges, computed once. -categoryRanges :: GeneralCategory -> TokenRanges Char -categoryRanges cat = Map.findWithDefault falseP cat categoryTable - -categoryTable :: Map GeneralCategory (TokenRanges Char) -categoryTable = Map.fromListWith (>|<) - [ (generalCategory lo, TokenRanges (RSet.singletonRange (lo, hi))) - | (lo, hi) <- runs minBound ] - where - runs lo = - let - cat = generalCategory lo - hi = last' lo (takeWhile ((== cat) . generalCategory) [succ' lo ..]) - in (lo, hi) : if hi == maxBound then [] else runs (succ hi) - succ' c = if c == maxBound then c else succ c - last' x = \case - [] -> x - ys -> last ys - -{- | Tests of tokens, by finite sets of them, or their complements, -a `BooleanAlgebra` each test having one form, where tokens are -infinitely many; for finitely many, `TokenRanges` are. -} -data Cofinite token = Finite (Set token) | Cofinite (Set token) - deriving stock (Eq, Ord, Show, Read) -instance Ord token => DisjunctiveMonoid (Cofinite token) where - falseP = Finite Set.empty - Finite xs >|< Finite ys = Finite (Set.union xs ys) - Finite xs >|< Cofinite ys = Cofinite (ys Set.\\ xs) - Cofinite xs >|< Finite ys = Cofinite (xs Set.\\ ys) - Cofinite xs >|< Cofinite ys = Cofinite (Set.intersection xs ys) -instance Ord token => BooleanAlgebra (Cofinite token) where - trueP = Cofinite Set.empty - notP = \case - Finite xs -> Cofinite xs - Cofinite xs -> Finite xs - Finite xs >&< Finite ys = Finite (Set.intersection xs ys) - Finite xs >&< Cofinite ys = Finite (xs Set.\\ ys) - Cofinite xs >&< Finite ys = Finite (ys Set.\\ xs) - Cofinite xs >&< Cofinite ys = Cofinite (Set.union xs ys) - -cofiniteMember :: Ord token => token -> Cofinite token -> Bool -cofiniteMember x = \case - Finite xs -> Set.member x xs - Cofinite xs -> Set.notMember x xs - -{- | Tests of tokens tagged by their kinds, as a test of their tags -for each kind, a `BooleanAlgebra` of tests, pointwise, each test having -one form, where each kind's has, omitting kinds which `falseP` tests. -} -newtype ByKind kind test = ByKind (Map kind test) - deriving stock (Eq, Ord, Show, Read) -instance (Ord kind, DisjunctiveMonoid test) - => DisjunctiveMonoid (ByKind kind test) where - falseP = ByKind Map.empty - ByKind xs >|< ByKind ys = ByKind (Map.unionWith (>|<) xs ys) -instance (Ord kind, Enum kind, Bounded kind, BooleanAlgebra test, Eq test) - => BooleanAlgebra (ByKind kind test) where - trueP = ByKind (Map.fromList [(k, trueP) | k <- [minBound .. maxBound]]) - notP (ByKind xs) = ByKind $ Map.fromList - [ (k, test) | k <- [minBound .. maxBound] - , let test = notP (Map.findWithDefault falseP k xs), test /= falseP ] - ByKind xs >&< ByKind ys = - ByKind (Map.filter (/= falseP) (Map.intersectionWith (>&<) xs ys)) - -{- $tagged -Tokens tagged by their kinds, isomorphic to pairs of a kind & a tag, -are tested by `ByKind` tests, of their kinds' `Cofinite` tests of their -tags, which these define a `Lexical` instance's methods by. - -> instance Lexical TsToken where -> type TokenKind TsToken = TsTokenCategory -> tokenKind = tokenCategory -> type TokenTest TsToken = ByKind TsTokenCategory (Cofinite Text) -> tokenTest = taggedTest tagged -> testOneOf = taggedOneOf tagged -> testKinds = taggedKinds -> testRange lo hi = testOneOf [lo .. hi] -> testFinite = taggedFinite tagged -> -> tagged :: Iso' TsToken (TsTokenCategory, Text) -> tagged = iso (\(TsToken category text) -> (category, text)) (uncurry TsToken) + unionOneOfs xs = case [tokens' | OneOf tokens' <- xs] of + [] -> xs + tokenss -> placeFirst (OneOf (Set.unions tokenss)) xs + placeFirst union = \case + OneOf _ : rest -> union : [x | x <- rest, not (isOneOf x)] + x : rest -> x : placeFirst union rest + [] -> [] + isOneOf = \case + OneOf _ -> True + _ -> False + +{- | `CategoryTest`s for `Categorized` tokens, +taken in conjunction with `NotOneOf` some `Set` of tokens. -} +data CategoryTest token + = AndAsIn (Categorize token) + | AndNotAsIn (Set (Categorize token)) --- | Does a tagged token pass its kind's test of its tag? -taggedTest - :: (Ord kind, Ord tag) - => Iso' token (kind, tag) -> ByKind kind (Cofinite tag) -> token -> Bool -taggedTest tagged (ByKind tests) token' = - let (kind, tag) = view tagged token' - in maybe False (cofiniteMember tag) (Map.lookup kind tests) - --- | The test of being one of some tagged tokens. -taggedOneOf - :: (Ord kind, Ord tag) - => Iso' token (kind, tag) -> [token] -> ByKind kind (Cofinite tag) -taggedOneOf tagged tokens' = ByKind $ Map.fromListWith (>|<) - [(kind, Finite (Set.singleton tag)) | (kind, tag) <- map (view tagged) tokens'] - --- | The test of being of one of some kinds, by any tag. -taggedKinds :: BooleanAlgebra test => TokenKinds kind -> ByKind kind test -taggedKinds (TokenKinds kinds) = ByKind (Map.fromSet (const trueP) kinds) - --- | The tagged tokens which pass a test, where each kind's are finitely many. -taggedFinite - :: Iso' token (kind, tag) -> ByKind kind (Cofinite tag) -> Maybe (Int, Int -> token) -taggedFinite tagged (ByKind tests) = do - tokens' <- concat <$> traverse finite (Map.toList tests) - Just (length tokens', (tokens' !!)) - where - finite = \case - (kind, Finite tags) -> Just [review tagged (kind, tag) | tag <- Set.toList tags] - _ -> Nothing - --- memo tries of tests, by their forms -instance HasTrie (TokenTest token) => HasTrie (TokenClass token) where - newtype (TokenClass token :->: b) = TokenClassTrie (TokenTest token :->: b) - trie f = TokenClassTrie (trie (f . TokenClass)) - untrie (TokenClassTrie t) (TokenClass test) = untrie t test - enumerate (TokenClassTrie t) = first TokenClass <$> enumerate t -instance (Ord token, Enum token, HasTrie token) => HasTrie (TokenRanges token) where - newtype (TokenRanges token :->: b) = TokenRangesTrie ([(token, token)] :->: b) - trie f = TokenRangesTrie (trie (f . TokenRanges . RSet.fromRangeList)) - untrie (TokenRangesTrie t) (TokenRanges xs) = untrie t (RSet.toRangeList xs) - enumerate (TokenRangesTrie t) = first (TokenRanges . RSet.fromRangeList) <$> enumerate t -instance (Ord token, HasTrie token) => HasTrie (Cofinite token) where - newtype (Cofinite token :->: b) = CofiniteTrie (Either [token] [token] :->: b) - trie f = CofiniteTrie (trie (f . either (Finite . Set.fromList) (Cofinite . Set.fromList))) - untrie (CofiniteTrie t) = untrie t . \case - Finite xs -> Left (Set.toList xs) - Cofinite xs -> Right (Set.toList xs) - enumerate (CofiniteTrie t) = - first (either (Finite . Set.fromList) (Cofinite . Set.fromList)) <$> enumerate t +{- | t'TokenClass' forms a `Tokenized` `BooleanAlgebra`, +such that the following invariants hold. + +> prop> trueP = anyToken +> prop> trueP = notOneOf [] +> prop> falseP = oneOf [] +> prop> notP . oneOf = notOneOf +> prop> notP . notOneOf = oneOf +> prop> notP . asIn = notAsIn +> prop> notP . notAsIn = asIn + +t'TokenClass' is the fixed point algebra of t'TokenExam'. +t'TokenClass'es may be understood as normalizations of +`BooleanAlgebra` expressions generated by `Tokenized` +expressions. +-} +newtype TokenClass token = TokenClass (TokenExam token (TokenClass token)) + +-- | Fold a t'TokenClass' by an algebra of its t'TokenExam's. +foldTokenClass :: (TokenExam token a -> a) -> TokenClass token -> a +foldTokenClass alg (TokenClass exam) = alg (foldTokenClass alg <$> exam) + +{- | `TokenAlgebra` extends `Tokenized` methods to support +`BooleanAlgebra` operations within a `tokenClass`. +When a `TokenAlgebra` is a `DisjunctiveMonoid`, +then `tokenClass` is expected to act homomorphically on disjunction. + +> prop> falseP = tokenClass falseP +> prop> tokenClass x >|< tokenClass y = tokenClass (x >|< y) + +Likewise, when a `TokenAlgebra` is `Control.Applicative.Alternative`, + +> prop> empty = tokenClass falseP +> prop> tokenClass x <|> tokenClass y = tokenClass (x >|< y) + +-} +class Tokenized token p => TokenAlgebra token p where + tokenClass :: TokenClass token -> p + default tokenClass + :: (p ~ q token token, Alternator q, Cochoice q) + => TokenClass token -> p + -- Sets of tokens are tested by `Set.member`, logarithmically, + -- rather than by `oneOf`'s & `notOneOf`'s `Foldable`, linearly. + tokenClass = foldTokenClass $ \case + OneOf chars -> satisfy (`Set.member` chars) + NotOneOf chars (AndAsIn cat) -> + satisfy ((`Set.notMember` chars) >&< asIn cat) + NotOneOf chars (AndNotAsIn cats) -> + satisfy ((`Set.notMember` chars) >&< allP notAsIn cats) + Alternate p q ps -> foldr1 (>|<) (p : q : ps) + +deriving stock instance Generic (TokenExam token alg) +deriving stock instance Generic1 (TokenExam token) +deriving stock instance Generic (TokenClass token) +deriving stock instance Generic (CategoryTest token) +deriving stock instance + (Categorized token, Read token, Read (Categorize token)) + => Read (TokenClass token) +deriving stock instance + (Categorized token, Show token, Show (Categorize token)) + => Show (TokenClass token) +deriving newtype instance Categorized token => Eq (TokenClass token) +deriving newtype instance Categorized token => Ord (TokenClass token) +deriving newtype instance Categorized token => Tokenized token (TokenClass token) +deriving newtype instance Categorized token + => DisjunctiveMonoid (TokenClass token) +deriving newtype instance Categorized token => BooleanAlgebra (TokenClass token) +instance Categorized token + => TokenAlgebra token (TokenClass token) where + tokenClass = id +instance Categorized token + => TokenAlgebra token (TokenExam token (TokenClass token)) where + tokenClass (TokenClass exam) = exam +instance Categorized token => TokenAlgebra token (token -> Bool) where + tokenClass = foldTokenClass . flip $ \x -> \case + OneOf xs -> Set.member x xs + NotOneOf xs (AndAsIn y) -> + Set.notMember x xs && categorize x == y + NotOneOf xs (AndNotAsIn ys) -> + Set.notMember x xs && Set.notMember (categorize x) ys + Alternate p q ps -> any ($ x) (p : q : ps) +instance TokenAlgebra token (f token) + => TokenAlgebra token (Joker f token token) where + 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 + NotOneOf xs (AndAsIn cat) -> arbitrary `Gen.suchThat` + (\x -> x `notElem` xs && categorize x == cat) + NotOneOf xs (AndNotAsIn cats) -> arbitrary `Gen.suchThat` + (\x -> x `notElem` xs && categorize x `notElem` cats) + Alternate p q ps -> Gen.oneof (p : q : ps) +instance (RandomGen g, Monad m, Categorized token, Random token) + => TokenAlgebra token (StateT g m token) where + tokenClass = foldTokenClass $ \case + OneOf xs -> oneOf xs + NotOneOf xs (AndAsIn cat) -> + iterateUntil (\x -> x `notElem` xs && categorize x == cat) anyToken + NotOneOf xs (AndNotAsIn cats) -> + iterateUntil (\x -> x `notElem` xs && categorize x `notElem` cats) anyToken + Alternate p q ps -> do + i <- state (randomR (0, length ps + 1)) + (p : q : ps) !! i +instance Categorized token => Tokenized token (TokenExam token alg) where + anyToken = passExam + token a = OneOf (Set.singleton a) + oneOf as | null as = failExam + oneOf as = OneOf (Set.fromList (toList as)) + notOneOf as | null as = passExam + notOneOf as = + NotOneOf (Set.fromList (toList as)) (AndNotAsIn Set.empty) + asIn cat = NotOneOf Set.empty (AndAsIn cat) + notAsIn cat = NotOneOf Set.empty (AndNotAsIn (Set.singleton cat)) +instance Categorized token + => DisjunctiveMonoid (TokenExam token (TokenClass token)) where + falseP = failExam + x >|< y = alternatives (examAlternatives x <> examAlternatives y) +instance Categorized token + => BooleanAlgebra (TokenExam token (TokenClass token)) where + trueP = passExam + notP exam | isFailExam exam = passExam + notP exam | isPassExam exam = failExam + notP (Alternate x y zs) = + foldr1 (>&<) [notP exam | TokenClass exam <- x : y : zs] + notP (OneOf xs) = notOneOf xs + notP (NotOneOf xs (AndAsIn y)) = oneOf xs >|< notAsIn y + notP (NotOneOf xs (AndNotAsIn ys)) = oneOf xs >|< anyP asIn ys + x >&< y | x == y = x + _ >&< exam | isFailExam exam = failExam + exam >&< _ | isFailExam exam = failExam + x >&< exam | isPassExam exam = x + exam >&< z | isPassExam exam = z + x >&< Alternate y z ws = + foldr1 (>|<) [x >&< exam | TokenClass exam <- y : z : ws] + Alternate x y ws >&< z = + foldr1 (>|<) [exam >&< z | TokenClass exam <- x : y : ws] + OneOf xs >&< OneOf ys = OneOf (Set.intersection xs ys) + OneOf xs >&< NotOneOf ys (AndAsIn z) = OneOf + (Set.filter (\x -> categorize x == z) (Set.difference xs ys)) + NotOneOf xs (AndAsIn y) >&< OneOf zs = OneOf + (Set.filter (\z -> categorize z == y) (Set.difference zs xs)) + OneOf xs >&< NotOneOf ys (AndNotAsIn zs) = OneOf + (Set.filter (\x -> categorize x `notElem` zs) (Set.difference xs ys)) + NotOneOf xs (AndNotAsIn ys) >&< OneOf zs = OneOf + (Set.filter (\z -> categorize z `notElem` ys) (Set.difference zs xs)) + NotOneOf xs (AndAsIn y) >&< NotOneOf ws (AndAsIn z) = + if y /= z then failExam else NotOneOf + (Set.filter (\x -> categorize x == y) (Set.union xs ws)) (AndAsIn y) + NotOneOf xs (AndAsIn y) >&< NotOneOf ws (AndNotAsIn zs) = + if y `elem` zs then failExam else NotOneOf + (Set.filter (\x -> categorize x == y) (Set.union xs ws)) (AndAsIn y) + NotOneOf xs (AndNotAsIn ys) >&< NotOneOf ws (AndAsIn z) = + if z `elem` ys then failExam else NotOneOf + (Set.filter (\x -> categorize x == z) (Set.union xs ws)) (AndAsIn z) + NotOneOf xs (AndNotAsIn ys) >&< NotOneOf ws (AndNotAsIn zs) = + let + xws = Set.union xs ws + yzs = Set.union ys zs + in + NotOneOf + (Set.filter (\x -> categorize x `notElem` yzs) xws) + (AndNotAsIn yzs) +deriving stock instance + (Categorized token, Read token, Read alg, Read (Categorize token)) + => Read (TokenExam token alg) +deriving stock instance + (Categorized token, Show token, Show alg, Show (Categorize token)) + => Show (TokenExam token alg) +deriving stock instance Functor (TokenExam token) +deriving stock instance Foldable (TokenExam token) +deriving stock instance Traversable (TokenExam token) +deriving stock instance (Categorized token, Eq alg) => Eq (TokenExam token alg) +deriving stock instance (Categorized token, Ord alg) => Ord (TokenExam token alg) +deriving stock instance Categorized token => Eq (CategoryTest token) +deriving stock instance Categorized token => Ord (CategoryTest token) +deriving stock instance + (Categorized token, Read token, Read (Categorize token)) + => Read (CategoryTest token) +deriving stock instance + (Categorized token, Show token, Show (Categorize token)) + => Show (CategoryTest token) diff --git a/distributors-grammar/src/Data/Profunctor/Grammar.hs b/distributors-grammar/src/Data/Profunctor/Grammar.hs index 89c6478b..2ea554e4 100644 --- a/distributors-grammar/src/Data/Profunctor/Grammar.hs +++ b/distributors-grammar/src/Data/Profunctor/Grammar.hs @@ -167,15 +167,20 @@ instance (Alternative m, Monad m) => ArrowChoice (Parsor s m) where left = left' right = right' instance - ( Lexical a, a ~ Item s, IsList s + ( Categorized a, a ~ Item s, IsList s , Cons s s a a, Snoc s s a a , Filterable m, Alternative m, Monad m ) => Tokenized a (Parsor s m a a) where - tokenAny = Parsor $ maybe + anyToken = Parsor $ maybe (maybe empty pure . uncons) (\a -> pure . (a,) . flip snoc a) instance - ( Lexical a, a ~ Item s, IsList s + ( Categorized a, a ~ Item s, IsList s + , Cons s s a a, Snoc s s a a + , Filterable m, Alternative m, Monad m + ) => TokenAlgebra a (Parsor s m a a) +instance + ( Categorized a, a ~ Item s, IsList s , Cons s s a a, Snoc s s a a , Filterable m, Alternative m, Monad m ) => TerminalSymbol a (Parsor s m () ()) where @@ -233,13 +238,13 @@ instance KleeneStarAlgebra k => Alternator (Grammor k) where manyTillP (Grammor rex) (Grammor rest) = Grammor (starK rex <> rest) timesP lo hi (Grammor rex) = Grammor (timesK lo hi rex) instance Tokenized token k => Tokenized token (Grammor k a b) where - tokenAny = Grammor tokenAny + anyToken = Grammor anyToken token = Grammor . token oneOf = Grammor . oneOf notOneOf = Grammor . notOneOf asIn = Grammor . asIn notAsIn = Grammor . notAsIn - tokenRange lo = Grammor . tokenRange lo +instance TokenAlgebra a k => TokenAlgebra a (Grammor k a b) where tokenClass = Grammor . tokenClass instance TerminalSymbol token k => TerminalSymbol token (Grammor k a b) where diff --git a/distributors-grammar/src/Data/Profunctor/Grammar/Parsector.hs b/distributors-grammar/src/Data/Profunctor/Grammar/Parsector.hs index 0a2f0a2b..5b603547 100644 --- a/distributors-grammar/src/Data/Profunctor/Grammar/Parsector.hs +++ b/distributors-grammar/src/Data/Profunctor/Grammar/Parsector.hs @@ -53,7 +53,7 @@ newtype Parsector s a b = Parsector left to right, returning a t'ParsecState' whose `parsecResult` is `Nothing` on failure and `Just` the output syntax value on success. -} parsecP - :: Lexical (Item s) + :: Categorized (Item s) => Parsector s a b -> s -- ^ input stream -> ParsecState s b @@ -65,7 +65,7 @@ returning a t'ParsecState' whose `parsecResult` is `Nothing` on failure or `Just` a successful output syntax value, in which case, `parsecStream` is the output stream. -} unparsecP - :: Lexical (Item s) + :: Categorized (Item s) => Parsector s a b -> a -- ^ input syntax -> s -- ^ input stream @@ -134,18 +134,18 @@ data ParsecFailure s = ParsecFailure -- ParsecFailure instances deriving stock instance - ( Lexical (Item s) - , Show (Item s), Show (TokenTest (Item s)) + ( Categorized (Item s) + , Show (Item s), Show (Categorize (Item s)) ) => Show (ParsecFailure s) deriving stock instance - ( Lexical (Item s) - , Read (Item s), Read (TokenTest (Item s)) + ( Categorized (Item s) + , Read (Item s), Read (Categorize (Item s)) ) => Read (ParsecFailure s) -deriving stock instance Lexical (Item s) => Eq (ParsecFailure s) -deriving stock instance Lexical (Item s) => Ord (ParsecFailure s) -instance Lexical (Item s) => Semigroup (ParsecFailure s) where +deriving stock instance Categorized (Item s) => Eq (ParsecFailure s) +deriving stock instance Categorized (Item s) => Ord (ParsecFailure s) +instance Categorized (Item s) => Semigroup (ParsecFailure s) where ParsecFailure e1 l1 <> ParsecFailure e2 l2 = ParsecFailure (e1 >|< e2) (l1 ++ l2) -instance Lexical (Item s) => Monoid (ParsecFailure s) where +instance Categorized (Item s) => Monoid (ParsecFailure s) where mempty = ParsecFailure falseP [] -- ParsecState instances @@ -153,30 +153,40 @@ deriving stock instance Functor (ParsecState s) deriving stock instance Foldable (ParsecState s) deriving stock instance Traversable (ParsecState s) deriving stock instance - ( Lexical (Item s) - , Show (Item s), Show (TokenTest (Item s)) + ( Categorized (Item s) + , Show (Item s), Show (Categorize (Item s)) , Show a, Show s ) => Show (ParsecState s a) deriving stock instance - ( Lexical (Item s) - , Read (Item s), Read (TokenTest (Item s)) + ( Categorized (Item s) + , Read (Item s), Read (Categorize (Item s)) , Read a, Read s ) => Read (ParsecState s a) deriving stock instance - ( Lexical (Item s) + ( Categorized (Item s) , Eq a, Eq s ) => Eq (ParsecState s a) deriving stock instance - ( Lexical (Item s) + ( Categorized (Item s) , Ord a, Ord s ) => Ord (ParsecState s a) -- Parsector instances instance - ( Lexical token, Item s ~ token + ( Categorized token, Item s ~ token , Cons s s token token, Snoc s s token token ) => Tokenized token (Parsector s token token) where - {-# SPECIALISE instance Tokenized Char (Parsector String Char Char) #-} + anyToken = tokenClass anyToken + 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 token, Item s ~ token + , Cons s s token token, Snoc s s token token + ) => TokenAlgebra token (Parsector s token token) where + {-# SPECIALISE instance TokenAlgebra Char (Parsector String Char Char) #-} -- The test & failures are made once, rather than for each token. tokenClass test = matches `seq` Parsector (\callback query -> let @@ -224,7 +234,7 @@ instance Ruled (Parsector s a b) where } Just _ -> reply instance - ( Lexical token, Item s ~ token + ( Categorized token, Item s ~ token , Cons s s token token, Snoc s s token token ) => TerminalSymbol token (Parsector s () ()) where {-# SPECIALISE instance TerminalSymbol Char (Parsector String () ()) #-} @@ -263,7 +273,7 @@ instance fromString = terminal instance Functor (Parsector s a) where fmap = rmap -instance Lexical (Item s) => Applicative (Parsector s a) where +instance Categorized (Item s) => Applicative (Parsector s a) where pure b = Parsector $ \callback query -> callback query { parsecResult = Just b } (<*>) = liftA2 id @@ -276,7 +286,7 @@ instance Lexical (Item s) => Applicative (Parsector s a) where flip (runParsector q) (bound query reply) $ \qReply -> callback (rebound reply (f b <$> qReply)) -instance Lexical (Item s) => Monad (Parsector s a) where +instance Categorized (Item s) => Monad (Parsector s a) where return = pure p >>= f = Parsector $ \callback query -> flip (runParsector p) query $ \reply -> @@ -288,7 +298,7 @@ instance Lexical (Item s) => Monad (Parsector s a) where -- | The query of the second of a sequence, after the first's reply. bound - :: Lexical (Item s) + :: Categorized (Item s) => ParsecState s a -> ParsecState s b -> ParsecState s a bound query reply = reply { parsecLooked = False @@ -300,7 +310,7 @@ bound query reply = reply which keeps the first's hints when the second hasn't consumed. -} rebound - :: Lexical (Item s) + :: Categorized (Item s) => ParsecState s b -> ParsecState s c -> ParsecState s c rebound reply next | parsecLooked next = next @@ -309,7 +319,7 @@ rebound reply next , parsecFailure = parsecFailure reply <> parsecFailure next } -instance Lexical (Item s) => Alternative (Parsector s a) where +instance Categorized (Item s) => Alternative (Parsector s a) where -- | Always fails without consuming input; expects nothing. empty = Parsector $ \callback query -> callback query { parsecFailure = mempty, parsecResult = Nothing } @@ -331,8 +341,8 @@ instance Lexical (Item s) => Alternative (Parsector s a) where (False, Just _) -> replyQ { parsecFailure = errP <> parsecFailure replyQ } -- both empty fail: merge failures (False, Nothing) -> replyP { parsecFailure = errP <> parsecFailure replyQ } -instance Lexical (Item s) => MonadPlus (Parsector s a) -instance Lexical (Item s) => MonadFail (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 Tried (Parsector s a b) where -- | On failure, resets `parsecLooked` to @False@, allowing @@ -348,21 +358,21 @@ instance Tried (Parsector s a b) where , parsecResult = Nothing } Just _ -> reply -instance Lexical (Item s) => Filterable (Parsector s a) where +instance Categorized (Item s) => Filterable (Parsector s a) where mapMaybe = dimapMaybe Just instance Category (Parsector s) where id = Parsector id Parsector q . Parsector p = Parsector (p . q) -instance Lexical (Item s) => Arrow (Parsector s) where +instance Categorized (Item s) => Arrow (Parsector s) where arr f = Parsector $ \callback reply -> callback (f <$> reply) (***) = (>*<) first = first' second = second' -instance Lexical (Item s) => ArrowZero (Parsector s) where +instance Categorized (Item s) => ArrowZero (Parsector s) where zeroArrow = empty -instance Lexical (Item s) => ArrowPlus (Parsector s) where +instance Categorized (Item s) => ArrowPlus (Parsector s) where (<+>) = (<|>) -instance Lexical (Item s) => ArrowChoice (Parsector s) where +instance Categorized (Item s) => ArrowChoice (Parsector s) where (+++) = (>+<) left = left' right = right' @@ -390,7 +400,7 @@ instance Strong (Parsector s) where <*> parsecResult reply1 } -- | Like `alternate`, without a sum of branches. -instance Lexical (Item s) => Choice (Parsector s) where +instance Categorized (Item s) => Choice (Parsector s) where left' (Parsector p) = Parsector $ \callback query -> case parsecResult query of Just (Right _) -> @@ -403,8 +413,8 @@ instance Lexical (Item s) => Choice (Parsector s) where callback query { parsecFailure = mempty, parsecResult = Nothing } result -> p (callback . fmap Right) query { parsecResult = either (const Nothing) Just =<< result } -instance Lexical (Item s) => CocartesianMonoidal (Parsector s) -instance Lexical (Item s) => Distributor (Parsector s) where +instance Categorized (Item s) => CocartesianMonoidal (Parsector s) +instance Categorized (Item s) => Distributor (Parsector s) where {- | Like @eotList . swapped >~ p >*< manyP p >+< oneP@, in one loop, with its hints: a failure of @p@ without consuming ends the list, merging its expectations with those of the last element. @@ -455,8 +465,8 @@ instance Lexical (Item s) => Distributor (Parsector s) where Nothing -> p parsedFirst query {parsecResult = Nothing} Just [] -> callback query {parsecResult = Just []} Just (a : as) -> p (printedFirst as) query {parsecResult = Just a} -instance Lexical (Item s) => DisjunctiveMonoid (Parsector s a b) -instance Lexical (Item s) => CocartesianChoice (Parsector s) where +instance Categorized (Item s) => DisjunctiveMonoid (Parsector s a b) +instance Categorized (Item s) => CocartesianChoice (Parsector s) where alternate (Left p) = Parsector $ \callback query -> callback $ let replyOk = query @@ -487,15 +497,15 @@ instance Lexical (Item s) => CocartesianChoice (Parsector s) where _________________ -> flip (runParsector p) replyOk $ \reply -> reply { parsecResult = fmap Right (parsecResult reply) } -instance Lexical (Item s) => Alternator (Parsector s) where +instance Categorized (Item s) => Alternator (Parsector s) where optionP def p = Parsector $ \callback query -> case parsecResult query of Nothing -> runParsector (p <|> pureP def) callback query Just _ -> runParsector (pureP def <|> p) callback query -instance Lexical (Item s) => Cochoice (Parsector s) where +instance Categorized (Item s) => Cochoice (Parsector s) where unleft = fst . filtrate unright = snd . filtrate -instance Lexical (Item s) => Filtrator (Parsector s) where +instance Categorized (Item s) => Filtrator (Parsector s) where filtrate p = ( Parsector $ \callback query -> flip (runParsector p) (Left <$> query) $ \reply -> diff --git a/distributors-grammar/src/Data/Profunctor/Grammar/Printor.hs b/distributors-grammar/src/Data/Profunctor/Grammar/Printor.hs index b57433ef..9357946d 100644 --- a/distributors-grammar/src/Data/Profunctor/Grammar/Printor.hs +++ b/distributors-grammar/src/Data/Profunctor/Grammar/Printor.hs @@ -136,17 +136,28 @@ instance (Alternative f, Monad f) => ArrowChoice (Printor s f) where left = left' right = right' instance - ( Lexical a, a ~ Item s, IsList s, Cons s s a a + ( 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) #-} - tokenAny = Printor (\b -> pure (b, cons b)) - -- | 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 + 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 () ()) #-} diff --git a/distributors-grammar/test/Examples/Json.hs b/distributors-grammar/test/Examples/Json.hs index e49d6835..423ddf28 100644 --- a/distributors-grammar/test/Examples/Json.hs +++ b/distributors-grammar/test/Examples/Json.hs @@ -79,7 +79,8 @@ jsonGrammar = rule "json" elementG -- character = '0020' . '10FFFF' - '"' - '\' | '\' escape characterG = rule "character" $ - tokenClass (tokenRange '\x0020' '\x10FFFF' >&< notOneOf ['\"','\\']) + -- by complement, 34 tokens rather than a million + tokenClass (notOneOf ('\"' : '\\' : ['\x0000' .. '\x001F'])) >|< terminal "\\" >* escapeG -- escape = '"' | '\' | '/' | 'b' | 'f' | 'n' | 'r' | 't' diff --git a/distributors-grammar/test/Examples/RegString.hs b/distributors-grammar/test/Examples/RegString.hs index e4dd4e93..07cc73cd 100644 --- a/distributors-grammar/test/Examples/RegString.hs +++ b/distributors-grammar/test/Examples/RegString.hs @@ -14,7 +14,7 @@ regexExamples = , (optK (terminal "x"), "x?") , (starK (terminal "x"), "x*") , (plusK (terminal "x"), "x+") - , (tokenAny, "[^]") + , (anyToken, "[^]") , (oneOf "abc", "[a-c]") , (notOneOf "abc", "[^a-c]") , (asIn UppercaseLetter, "\\p{Lu}") @@ -26,8 +26,8 @@ regexExamples = -- Boolean OR (>|<) operations , (tokenClass (oneOf "abc" >|< oneOf "xyz"), "[a-cx-z]") - , (tokenClass (oneOf "abc" >|< notOneOf "xyz"), "[^x-z]") - , (tokenClass (notOneOf "abc" >|< oneOf "xyz"), "[^a-c]") + , (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), "[a-c]|\\p{Nd}") @@ -55,6 +55,6 @@ regexExamples = -- Complex combinations , (tokenClass (notOneOf "abc" >&< (asIn LowercaseLetter >|< asIn UppercaseLetter)), "[^a-c\\p{Ll}]|\\p{Lu}") - , (tokenClass ((oneOf "123" >|< asIn DecimalNumber) >&< notOneOf "789"), "[^7-9\\p{Nd}]") + , (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/Main.hs b/distributors-grammar/test/Main.hs index daa7b60e..6d79673e 100644 --- a/distributors-grammar/test/Main.hs +++ b/distributors-grammar/test/Main.hs @@ -13,7 +13,7 @@ import Text.ParserCombinators.ReadPrec (ReadPrec, readPrec_to_S) import Data.Functor.Contravariant (Predicate (..)) import Test.Hspec import Test.Hspec.QuickCheck (modifyMaxSize, prop) -import Test.QuickCheck (Gen, (.&&.), choose, elements, forAll, generate, listOf, oneof, (===)) +import Test.QuickCheck (choose, elements, forAll, generate, listOf, oneof, (===)) import qualified Text.Megaparsec as M import Examples.Arithmetic @@ -55,8 +55,6 @@ main = hspec $ do describe "base types" baseProperties describe "RegEx ranges & try" regexRangeTryTests describe "RegEx quantifiers" regexQuantifierTests - describe "tokenRange" tokenRangeTests - describe "Lexical laws" lexicalLaws regexRangeTryTests :: Spec regexRangeTryTests = do @@ -80,42 +78,6 @@ regexRangeTryTests = do `shouldBe` [LL1FirstFirst] ll1Conflicts (fromString "{start} = \\t{ab}|ac" :: Bnf (RegEx Char)) `shouldBe` [] -lexicalLaws :: Spec -lexicalLaws = do - let near = choose ('\0', '\x3FF') - tested :: TokenClass Char -> Char -> Bool - tested = tokenClass - prop "a class tests homomorphically" $ \(x :: TokenClass Char) y -> forAll near $ \c -> - tested (x >|< y) c === (tested x c || tested y c) - .&&. tested (x >&< y) c === (tested x c && tested y c) - .&&. tested (notP x) c === not (tested x c) - .&&. tested trueP c .&&. not (tested falseP c) - prop "its generators test as they say" $ forAll (listOf near) $ \cs -> - forAll near $ \lo -> forAll near $ \hi -> forAll near $ \c -> - tested (oneOf cs) c === (c `elem` cs) - .&&. tested (tokenRange lo hi) c === (lo <= c && c <= hi) - .&&. tested (asIn (tokenKind lo)) c === (tokenKind c == tokenKind lo) - prop "equal classes test alike, by their one form" $ \(x :: TokenClass Char) y -> - (x >|< y) >&< notP y === x >&< notP y - -tokenRangeTests :: Spec -tokenRangeTests = do - let near = choose ('\0', '\x3FF') - prop "tokenRange lo hi = oneOf [lo .. hi], as TokenClass" $ forAll near $ \lo -> forAll near $ \hi -> - (tokenRange lo hi :: TokenClass Char) === oneOf [lo .. hi] - prop "tokenRange lo hi = oneOf [lo .. hi], as a predicate" $ forAll near $ \lo -> forAll near $ \hi -> forAll near $ \x -> - tokenRange lo hi x === (oneOf [lo .. hi] :: Char -> Bool) x - it "renders as a range, & parses so" $ do - toList (tokenRange 'a' 'z' :: RegEx Char) `shouldBe` "[a-z]" - (fromString "[a-z]" :: RegEx Char) `shouldBe` tokenRange 'a' 'z' - toList (tokenRange 'z' 'a' :: RegEx Char) `shouldBe` "[]" - it "takes all of Unicode by its ends" $ do - let rex = tokenClass (tokenRange '\x20' '\x10FFFF' >&< notOneOf "\"\\") :: RegEx Char - toList rex `shouldBe` "[ !#-Z\\[\\]\\^_-\1114111]" - map (=~ rex) ["a", "\"", "\x10FFFF", "\x1F"] `shouldBe` [True, False, True, False] - prop "generates tokens in range" $ forAll (choose ('a', 'm')) $ \lo -> - forAll (tokenRange lo 'z' :: Gen Char) $ \x -> lo <= x && x <= 'z' - regexQuantifierTests :: Spec regexQuantifierTests = do let rendered :: Prismoid String String Char Char -> String @@ -283,9 +245,10 @@ newtype WrapMega a = WrapMega {unwrapMega :: M.Parsec String String a} ) instance TerminalSymbol Char (WrapMega ()) where terminal str = WrapMega (M.chunk str *> pure ()) -instance Tokenized Char (WrapMega Char) where +instance TokenAlgebra Char (WrapMega Char) where tokenClass exam = WrapMega $ M.label (show exam) (M.satisfy (tokenClass exam)) - tokenAny = WrapMega M.anySingle +instance Tokenized Char (WrapMega Char) where + anyToken = WrapMega M.anySingle token = WrapMega . M.single oneOf = WrapMega . M.oneOf notOneOf = WrapMega . M.noneOf @@ -293,7 +256,6 @@ 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))) - tokenRange lo hi = WrapMega $ M.label ("in range " ++ show (lo, hi)) (M.satisfy (tokenRange lo hi)) instance Ruled (WrapMega a) where rule lbl (WrapMega p) = WrapMega (M.label lbl p) instance BackusNaurForm (WrapMega a) diff --git a/distributors-grammar/test/Properties/Kleene.hs b/distributors-grammar/test/Properties/Kleene.hs index ea3388aa..03602fef 100644 --- a/distributors-grammar/test/Properties/Kleene.hs +++ b/distributors-grammar/test/Properties/Kleene.hs @@ -123,9 +123,9 @@ kleeneProperties = do modifyMaxSize (const 8) $ do let printed :: Prismoid String String Char Char -> String -> Maybe String - printed pat s = ($ "") <$> printP (pat >?* (tokenAny :: Printor String Maybe Char Char)) s + printed pat s = ($ "") <$> printP (pat >?* (anyToken :: Printor String Maybe Char Char)) s parsed :: Prismoid String String Char Char -> String -> Maybe (String, String) - parsed pat s = parseP (pat >?* (tokenAny :: Parsor String Maybe Char Char)) s + parsed pat s = parseP (pat >?* (anyToken :: Parsor String Maybe Char Char)) s bounded lo hi s = lo <= length s && length s <= hi prop "inRange lo hi prints & parses exactly lo to hi tokens" $ \(s :: String) -> forAll (choose (0, 4)) $ \lo -> forAll (choose (0, 4)) $ \hi -> @@ -154,8 +154,8 @@ kleeneProperties = do ((tokenClass x :: RegEx Char) >|< tokenClass y) == tokenClass (x >|< y) describe "TokenAlgebra RegEx" $ do - it "tokenAny = tokenClass tokenAny" $ - (tokenAny :: RegEx Char) `shouldBe` tokenClass tokenAny + it "anyToken = tokenClass anyToken" $ + (anyToken :: RegEx Char) `shouldBe` tokenClass anyToken prop "token c = tokenClass (token c)" $ \(c :: Char) -> (token c :: RegEx Char) == tokenClass (token c) @@ -192,8 +192,8 @@ kleeneProperties = do for_ cases $ \(word, rex) -> (word =~ rex) `shouldBe` (word =~ liftBnf0 rex) describe "BooleanAlgebra TokenClass" $ do - it "trueP = tokenAny" $ - (trueP :: TokenClass Char) `shouldBe` tokenAny + it "trueP = anyToken" $ + (trueP :: TokenClass Char) `shouldBe` anyToken it "trueP = notOneOf []" $ (trueP :: TokenClass Char) `shouldBe` notOneOf [] it "falseP = oneOf []" $ diff --git a/distributors-grammar/test/Properties/Varifocal.hs b/distributors-grammar/test/Properties/Varifocal.hs index f3b6f8b6..416f0e3b 100644 --- a/distributors-grammar/test/Properties/Varifocal.hs +++ b/distributors-grammar/test/Properties/Varifocal.hs @@ -18,9 +18,9 @@ varifocalProperties = do let printed :: Varifocal' String Char -> String -> Maybe String printed v s = - ($ "") <$> printP (contextuallyT v (tokenAny :: Printor String Maybe Char Char)) s + ($ "") <$> printP (contextuallyT v (anyToken :: Printor String Maybe Char Char)) s parsed :: Varifocal' String Char -> String -> Maybe (String, String) - parsed v = parseP (contextuallyT v (tokenAny :: Parsor String Maybe Char Char)) + parsed v = parseP (contextuallyT v (anyToken :: Parsor String Maybe Char Char)) ended :: Varifocal' String Char ended = terminateBy (== '.') plain = Prelude.filter (/= '.') <$> arbitrary @@ -30,8 +30,8 @@ varifocalProperties = do printing q c = fmap ($ "") <$> runPrintor q c parsing :: Parsor String Maybe Char b -> String -> Maybe (b, String) parsing = parseP - prToken = tokenAny :: Printor String Maybe Char Char - paToken = tokenAny :: Parsor String Maybe Char Char + prToken = anyToken :: Printor String Maybe Char Char + paToken = anyToken :: Parsor String Maybe Char Char prop "liftP . pure = pure" $ \(n :: Int) (c :: Char) (str :: String) -> printing (liftP (pure n)) c === printing (pure n) c .&&. parsing (liftP (pure n)) str === parsing (pure n) str @@ -56,17 +56,17 @@ varifocalProperties = do it "terminates a Seq as it does a list" $ do let seqTerminated :: Varifocal' (Seq Char) Char seqTerminated = terminateBy (== '.') - parseP (contextuallyT seqTerminated (tokenAny :: Parsor String Maybe Char Char)) "ab.c" + parseP (contextuallyT seqTerminated (anyToken :: Parsor String Maybe Char Char)) "ab.c" `shouldBe` Just (Seq.fromList "ab.", "c") - (($ "") <$> printP (contextuallyT seqTerminated (tokenAny :: Printor String Maybe Char Char)) (Seq.fromList "ab.")) + (($ "") <$> printP (contextuallyT seqTerminated (anyToken :: Printor String Maybe Char Char)) (Seq.fromList "ab.")) `shouldBe` Just "ab." describe "steppingTree, by arityWith" $ do let counted :: Varifocal' (Cofree [] Char) Char counted = arityWith digitToInt tree = '2' :< ['1' :< ['0' :< []], '0' :< []] - parsedT = parseP (contextuallyT counted (tokenAny :: Parsor String Maybe Char Char)) - printedT = fmap ($ "") . printP (contextuallyT counted (tokenAny :: Printor String Maybe Char Char)) + 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" $ @@ -102,9 +102,9 @@ varifocalProperties = do let printedG :: Varifocal' s Char -> s -> Maybe String printedG v x = - ($ "") <$> printP (contextuallyT v (tokenAny :: Printor String Maybe Char Char)) x + ($ "") <$> printP (contextuallyT v (anyToken :: Printor String Maybe Char Char)) x parsedG :: Varifocal' s Char -> String -> Maybe (s, String) - parsedG v = parseP (contextuallyT v (tokenAny :: Parsor String Maybe Char Char)) + parsedG v = parseP (contextuallyT v (anyToken :: Parsor String Maybe Char Char)) crossed :: Varifocal' (String, String) Char crossed = crossVarifocal (terminateBy (== '.')) (delimitBy (==)) alted :: Varifocal' (Either String String) Char @@ -173,9 +173,9 @@ varifocalProperties = do composite = _Right . ended printedE :: Varifocal' (Either Int String) Char -> Either Int String -> Maybe String printedE v e = - ($ "") <$> printP (contextuallyT v (tokenAny :: Printor String Maybe Char Char)) e + ($ "") <$> printP (contextuallyT v (anyToken :: Printor String Maybe Char Char)) e parsedE :: Varifocal' (Either Int String) Char -> String -> Maybe (Either Int String, String) - parsedE v = parseP (contextuallyT v (tokenAny :: Parsor String Maybe Char Char)) + parsedE v = parseP (contextuallyT v (anyToken :: Parsor String Maybe Char Char)) prop "prints & parses as the composite does" $ forAll plain $ \s (n :: Int) -> let es = [Left n, Right s, Right (s ++ ".")] @@ -194,21 +194,21 @@ varifocalProperties = do parsecResult (parsecG "<?<*, Bifocal's applicator" $ do prop "applies a Prismoid as >?* does" $ \(s :: String) -> - parseP (atLeast 1 >?<* (tokenAny :: Parsor String Maybe Char Char)) s - === parseP (atLeast 1 >?* (tokenAny :: Parsor String Maybe Char Char)) s - .&&. (($ "") <$> printP (atLeast 1 >?<* (tokenAny :: Printor String Maybe Char Char)) s) - === (($ "") <$> printP (atLeast 1 >?* (tokenAny :: Printor String Maybe Char Char)) s) + parseP (atLeast 1 >?<* (anyToken :: Parsor String Maybe Char Char)) s + === parseP (atLeast 1 >?* (anyToken :: Parsor String Maybe Char Char)) s + .&&. (($ "") <$> printP (atLeast 1 >?<* (anyToken :: Printor String Maybe Char Char)) s) + === (($ "") <$> printP (atLeast 1 >?* (anyToken :: Printor String Maybe Char Char)) s) prop "applies a PartialIso as >?< does" $ \(s :: String) (c :: Char) -> - parseP (satisfied isDigit >?<* (tokenAny :: Parsor String Maybe Char Char)) s - === parseP (satisfied isDigit >?< (tokenAny :: Parsor String Maybe Char Char)) s - .&&. (($ "") <$> printP (satisfied isDigit >?<* (tokenAny :: Printor String Maybe Char Char)) c) - === (($ "") <$> printP (satisfied isDigit >?< (tokenAny :: Printor String Maybe Char Char)) c) + parseP (satisfied isDigit >?<* (anyToken :: Parsor String Maybe Char Char)) s + === parseP (satisfied isDigit >?< (anyToken :: Parsor String Maybe Char Char)) s + .&&. (($ "") <$> printP (satisfied isDigit >?<* (anyToken :: Printor String Maybe Char Char)) c) + === (($ "") <$> printP (satisfied isDigit >?< (anyToken :: Printor String Maybe Char Char)) c) it "keeps the target's own optionP, printing nothing for the default" $ - (($ "") <$> printP (opted (only '0') >?<* (tokenAny :: Printor String Maybe Char Char)) '0') + (($ "") <$> printP (opted (only '0') >?<* (anyToken :: Printor String Maybe Char Char)) '0') `shouldBe` Just "" describe "Bifocal ⊂ Varifocal" $ prop "a Prismoid applies contextuallyT as by >?*" $ \(s :: String) -> parsed (atLeast 1) s - === parseP (atLeast 1 >?* (tokenAny :: Parsor String Maybe Char Char)) s + === parseP (atLeast 1 >?* (anyToken :: Parsor String Maybe Char Char)) s .&&. printed (atLeast 1) s - === (($ "") <$> printP (atLeast 1 >?* (tokenAny :: Printor String Maybe Char Char)) s) + === (($ "") <$> printP (atLeast 1 >?* (anyToken :: Printor String Maybe Char Char)) s) diff --git a/distributors-json/src/Control/Lens/Grammar/TypeScript.hs b/distributors-json/src/Control/Lens/Grammar/TypeScript.hs index 6b5488e0..e51d71e9 100644 --- a/distributors-json/src/Control/Lens/Grammar/TypeScript.hs +++ b/distributors-json/src/Control/Lens/Grammar/TypeScript.hs @@ -280,20 +280,9 @@ data TsToken = TsToken , tokenText :: Text } deriving stock (Eq, Ord, Show, Read) -instance Lexical TsToken where - type TokenKind TsToken = TsTokenCategory - tokenKind = tokenCategory - -- tested by their kinds' tests of their texts - type TokenTest TsToken = ByKind TsTokenCategory (Cofinite Text) - tokenTest = taggedTest tagged - testOneOf = taggedOneOf tagged - testKinds = taggedKinds - testRange lo hi = testOneOf [lo .. hi] - testFinite = taggedFinite tagged - --- | A token, as its category & its text. -tagged :: Iso' TsToken (TsTokenCategory, Text) -tagged = iso (\(TsToken category text) -> (category, text)) (uncurry TsToken) +instance Categorized TsToken where + type Categorize TsToken = TsTokenCategory + categorize = tokenCategory -- | The categories of t'TsToken's, by the TypeScript compiler's names. data TsTokenCategory @@ -485,18 +474,18 @@ It's a `RegGrammar`, since each token's spelling is a regular language. -} tsTokenGrammar :: RegGrammatical Char p => p TsToken TsToken tsTokenGrammar = orP - [ ofKind WhitespaceTrivia >? someP (oneOf @Char (" \t\f\v" :: String)) - , ofKind NewLineTrivia >? orP + [ kindOf WhitespaceTrivia >? someP (oneOf @Char (" \t\f\v" :: String)) + , kindOf NewLineTrivia >? orP [only "\n" >? terminal "\n", only "\r\n" >? terminal "\r\n"] , _Comment >? terminal "/" >* orP [ _Left >? terminal "/" >* manyP (notOneOf @Char ("\r\n" :: String)) , _Right >? blockComment ] , _Word >? identifierStart >:< manyP identifierPart - , ofKind PrivateIdentifier >? terminal "#" + , kindOf PrivateIdentifier >? terminal "#" >* (identifierStart >:< manyP identifierPart) , _Number >? asIn @Char DecimalNumber >:< manyP numberPart - , ofKind StringLiteral >? orP + , kindOf StringLiteral >? orP [ terminal "\"" >* manyP (stringChar '"') *< terminal "\"" , terminal "'" >* manyP (stringChar '\'') *< terminal "'" ] @@ -611,8 +600,8 @@ tokensWithin depths = orP _ -> ds -- | A token of a category, by its text. -ofKind :: TsTokenCategory -> Prism' TsToken String -ofKind category = prism' +kindOf :: TsTokenCategory -> Prism' TsToken String +kindOf category = prism' (TsToken category . Text.pack) (\(TsToken category' text) -> if category == category' then Just (Text.unpack text) else Nothing) From d87d581d216232662e7eeaf8323f5975574815a9 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sat, 14 Nov 2026 00:56:01 -0800 Subject: [PATCH 26/51] Hexadecimal control escapes; digit & numeral rather than show & read Co-Authored-By: Claude Opus 5.5 --- distributors-grammar/CHANGELOG.md | 6 ++ .../src/Control/Lens/Grammar.hs | 17 ++-- .../src/Control/Lens/Grammar/Class.hs | 52 ++++++++++-- .../src/Control/Lens/Grammar/RegEx.hs | 82 +++---------------- .../test/Examples/Arithmetic.hs | 2 +- .../test/Examples/Expression.hs | 6 +- distributors-grammar/test/Examples/Json.hs | 2 +- distributors-grammar/test/Examples/LenVec.hs | 2 +- distributors-grammar/test/Examples/SemVer.hs | 4 +- distributors-grammar/test/Main.hs | 4 + .../src/Control/Lens/Grammar/TypeScript.hs | 17 ++-- 11 files changed, 90 insertions(+), 104 deletions(-) diff --git a/distributors-grammar/CHANGELOG.md b/distributors-grammar/CHANGELOG.md index d88b083d..eea3ae57 100644 --- a/distributors-grammar/CHANGELOG.md +++ b/distributors-grammar/CHANGELOG.md @@ -2,6 +2,12 @@ ## Unreleased +- 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 diff --git a/distributors-grammar/src/Control/Lens/Grammar.hs b/distributors-grammar/src/Control/Lens/Grammar.hs index e3a05b58..c9fc8409 100644 --- a/distributors-grammar/src/Control/Lens/Grammar.hs +++ b/distributors-grammar/src/Control/Lens/Grammar.hs @@ -36,6 +36,9 @@ module Control.Lens.Grammar , unparsecG , readG , monadG + -- * Numerals + , digit + , numeral -- * Utility , putStringLn -- * Re-exports @@ -94,7 +97,7 @@ import Data.Traversable.Homogeneous as X import Data.Traversable.Homogeneous.Enumerable as X -- $setup --- >>> :set -XRequiredTypeArguments -XExplicitNamespaces -XTypeApplications +-- >>> :set -XRequiredTypeArguments -XExplicitNamespaces -XTypeApplications -XMonoLocalBinds -- >>> import Data.String (fromString) -- >>> import GHC.Exts (toList) @@ -152,7 +155,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 @@ -205,7 +208,7 @@ You can generate a regular expression string, a `RegEx`, from a `RegGrammar` with `Control.Lens.Grammar.regexG`. >>> putStringLn (regexG (type SemVer)) -\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}|-)+)*)? +[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. @@ -277,7 +280,7 @@ 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 :} @@ -288,7 +291,7 @@ We can generate grammar strings, printers and parsers from @arithGrammar@. {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 @Arith "1+2*3+4"] @@ -326,7 +329,7 @@ _Sub = prism' (uncurry Sub) (\case Sub x y -> Just (x,y); _ -> Nothing) exprGrammar :: Grammatical Char p => p Expr Expr exprGrammar = ruleRec "expr" $ \expr -> let atom = rule "atom" $ nat >|< terminal "(" >* expr *< terminal ")" - nat = rule "nat" $ _Nat . iso show read >? someP (asIn @Char DecimalNumber) + nat = rule "nat" $ _Nat >? numeral 10 in withOperators [ [ Postfix _Fac (terminal "!") ] , [ Infix RightAssoc _Exp (terminal "^") ] @@ -393,7 +396,7 @@ _LenVec = iso (\LenVec {..} -> (length, vector)) (\(length, vector) -> 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 diff --git a/distributors-grammar/src/Control/Lens/Grammar/Class.hs b/distributors-grammar/src/Control/Lens/Grammar/Class.hs index d568e61b..bfcd4eb9 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/Class.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/Class.hs @@ -15,6 +15,9 @@ module Control.Lens.Grammar.Class ( RegGrammar (..) , Grammar (..) , CtxGrammar (..) + -- * Numerals + , digit + , numeral ) where import Control.Lens @@ -23,7 +26,7 @@ import Control.Lens.Grammar.BackusNaur import Control.Lens.Grammar.Symbol import Control.Lens.Grammar.Token import Data.Bits (Bits, toIntegralSized) -import Data.Char (isDigit) +import Data.Char (isDigit, isLetter, ord, toLower, toUpper) import Data.Int (Int8, Int16, Int32, Int64) import Data.Maybe (isJust) import Data.Profunctor.Distributor @@ -32,6 +35,9 @@ import Data.Profunctor.Monoidal.Cocartesian import Data.Word (Word8, Word16, Word32, Word64) import Numeric.Natural (Natural) +-- $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 @@ -91,7 +97,7 @@ instance CtxGrammar Char Word16 where ctxGrammar = rule "Word16" sizedG instance CtxGrammar Char Word32 where ctxGrammar = rule "Word32" sizedG instance CtxGrammar Char Word64 where ctxGrammar = rule "Word64" sizedG --- ASCII decimal digits, at least one. +-- ASCII decimal digits, at least one, of floating point numbers. decimalG :: RegGrammatical Char p => p String String decimalG = someP (oneOf ['0' .. '9']) @@ -100,16 +106,48 @@ negativeG :: RegGrammatical Char p => p Bool Bool negativeG = iso (\b -> if b then Just () else Nothing) isJust >~ optionalP (terminal "-") --- Printing canonically, parsing leading zeros too, an improper iso. +-- Printing canonically, parsing leading zeros too. naturalG :: RegGrammatical Char p => p Natural Natural -naturalG = iso show read >~ decimalG +naturalG = numeral 10 -- Printing canonically, parsing leading zeros & -0 too, an improper iso. integerG :: RegGrammatical Char p => p Integer Integer integerG = iso - (\n -> (n < 0, show (abs n))) - (\(negative, digits) -> (if negative then negate else id) (read digits)) - >~ negativeG >*< decimalG + (\n -> (n < 0, abs n)) + (\(negative, n) -> if negative then negate n else n) + >~ negativeG >*< numeral 10 + +{- | A digit in a base, from 2 to 36, by its value: -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] -- Integers in a range, failing to build out of it. sizedG diff --git a/distributors-grammar/src/Control/Lens/Grammar/RegEx.hs b/distributors-grammar/src/Control/Lens/Grammar/RegEx.hs index 92bb3322..e95f0e58 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/RegEx.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/RegEx.hs @@ -31,6 +31,7 @@ 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 @@ -569,7 +570,7 @@ Ill-formed regular expression strings normalize to failure. {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} = 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-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})*\} @@ -625,7 +626,7 @@ regexGrammar = ruleRec "regex" altG >~ 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" $ iso show read >~ someP (oneOf ['0' .. '9']) + countG = rule "count" $ numeral (10 :: Int) atomG rex = rule "atom" $ orP [ _NonTerminal >? terminal "\\q" >* nonterminalG @@ -748,73 +749,12 @@ charWith name reserved = rule name $ (oneOf reserved >|< charControlG) charControlG :: Grammatical Char p => p Char Char -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" - ] +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` @@ -863,7 +803,7 @@ But they also support `BackusNaurForm` `rule`s and `ruleRec`s. {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} = 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-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})*\} @@ -875,7 +815,7 @@ But they also support `BackusNaurForm` `rule`s and `ruleRec`s. {count} = [0-9]+ {expression} = \q{atom}\?|\q{atom}\*|\q{atom}\+|\q{atom}\{\q{bounds}\}|\q{atom} {nonterminal} = \{\q{char}*\} -{regbnf} = \{start\} = \q{regex}(\LF\q{nonterminal} = \q{regex})* +{regbnf} = \{start\} = \q{regex}(\x{a}\q{nonterminal} = \q{regex})* {regex} = \q{alternate} {sequence} = \q{expression}* -} diff --git a/distributors-grammar/test/Examples/Arithmetic.hs b/distributors-grammar/test/Examples/Arithmetic.hs index ecee1b46..bc532d28 100644 --- a/distributors-grammar/test/Examples/Arithmetic.hs +++ b/distributors-grammar/test/Examples/Arithmetic.hs @@ -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 = diff --git a/distributors-grammar/test/Examples/Expression.hs b/distributors-grammar/test/Examples/Expression.hs index 14872b24..f6c0266e 100644 --- a/distributors-grammar/test/Examples/Expression.hs +++ b/distributors-grammar/test/Examples/Expression.hs @@ -38,7 +38,7 @@ exprGrammar = ruleRec "expr" $ \expr -> 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 "^") ] @@ -74,7 +74,7 @@ powGrammar = ruleRec "pow" $ \e -> 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)] @@ -94,7 +94,7 @@ leftGrammar = ruleRec "expr" $ \expr -> 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 "-") ] diff --git a/distributors-grammar/test/Examples/Json.hs b/distributors-grammar/test/Examples/Json.hs index 423ddf28..97a55514 100644 --- a/distributors-grammar/test/Examples/Json.hs +++ b/distributors-grammar/test/Examples/Json.hs @@ -97,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" $ diff --git a/distributors-grammar/test/Examples/LenVec.hs b/distributors-grammar/test/Examples/LenVec.hs index 174cd8a7..7e15a7e3 100644 --- a/distributors-grammar/test/Examples/LenVec.hs +++ b/distributors-grammar/test/Examples/LenVec.hs @@ -16,7 +16,7 @@ makeNestedPrisms ''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 diff --git a/distributors-grammar/test/Examples/SemVer.hs b/distributors-grammar/test/Examples/SemVer.hs index f9afde78..980a43ca 100644 --- a/distributors-grammar/test/Examples/SemVer.hs +++ b/distributors-grammar/test/Examples/SemVer.hs @@ -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 @@ -51,7 +51,7 @@ semverGrammar = _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 diff --git a/distributors-grammar/test/Main.hs b/distributors-grammar/test/Main.hs index 6d79673e..2d1d3164 100644 --- a/distributors-grammar/test/Main.hs +++ b/distributors-grammar/test/Main.hs @@ -68,6 +68,10 @@ regexRangeTryTests = do 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" diff --git a/distributors-json/src/Control/Lens/Grammar/TypeScript.hs b/distributors-json/src/Control/Lens/Grammar/TypeScript.hs index e51d71e9..e95ce796 100644 --- a/distributors-json/src/Control/Lens/Grammar/TypeScript.hs +++ b/distributors-json/src/Control/Lens/Grammar/TypeScript.hs @@ -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 @@ -540,11 +539,9 @@ 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 :: RegGrammatical Char p => p Char Char templateChar = orP @@ -685,14 +682,12 @@ _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 -- From a80f0c7dedce5a250a01d3fd66a0c17f81fae9f6 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sat, 14 Nov 2026 00:58:01 -0800 Subject: [PATCH 27/51] Bench workloads' types, explicit for GHC 9.10 Co-Authored-By: Claude Opus 5.5 --- distributors-grammar/bench/Main.hs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/distributors-grammar/bench/Main.hs b/distributors-grammar/bench/Main.hs index d3287fb7..0c48bd97 100644 --- a/distributors-grammar/bench/Main.hs +++ b/distributors-grammar/bench/Main.hs @@ -139,13 +139,13 @@ 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 :: forall a. (forall p. CtxGrammatical Char p => p a a) -> String -> a From fea58142bdf90868a3dedc1125d779b008fd8101 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sat, 14 Nov 2026 01:03:06 -0800 Subject: [PATCH 28/51] ruleTyped, which was jsonTyped, in distributors-grammar, naming base types' rules Co-Authored-By: Claude Opus 5.5 --- distributors-grammar/CHANGELOG.md | 3 + .../src/Control/Lens/Grammar/BackusNaur.hs | 41 +++++- .../src/Control/Lens/Grammar/Class.hs | 32 ++--- distributors-json/CHANGELOG.md | 1 + .../src/Control/Lens/Grammar/Json.hs | 125 ++++++------------ distributors-json/test/Properties/Json.hs | 52 ++++---- 6 files changed, 130 insertions(+), 124 deletions(-) diff --git a/distributors-grammar/CHANGELOG.md b/distributors-grammar/CHANGELOG.md index eea3ae57..7d6e8be8 100644 --- a/distributors-grammar/CHANGELOG.md +++ b/distributors-grammar/CHANGELOG.md @@ -2,6 +2,9 @@ ## Unreleased +- `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. diff --git a/distributors-grammar/src/Control/Lens/Grammar/BackusNaur.hs b/distributors-grammar/src/Control/Lens/Grammar/BackusNaur.hs index 9fb8c5ac..ab8f883c 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/BackusNaur.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/BackusNaur.hs @@ -15,7 +15,7 @@ See Naur & Backus, et al. module Control.Lens.Grammar.BackusNaur ( -- * BackusNaurForm BackusNaurForm (..) - , Ruled (..), failP + , Ruled (..), failP, ruleTyped , Tried (..) -- * Grammatical , RegGrammatical @@ -32,6 +32,9 @@ import Data.Kind (Constraint) import Data.Profunctor.Distributor (Alternator) import Data.Profunctor.Filtrator (Filtrator) import Data.Function +import Data.List (intercalate, isPrefixOf) +import Data.Maybe (isNothing) +import Type.Reflection (SomeTypeRep (..), Typeable, splitApps, tyConModule, tyConName, typeRep) import Data.Monoid.Disjunctive import Text.ParserCombinators.ReadP (ReadP) import Text.ParserCombinators.ReadPrec (ReadPrec) @@ -90,6 +93,42 @@ class Ruled p where 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@. +-} +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 + (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'. diff --git a/distributors-grammar/src/Control/Lens/Grammar/Class.hs b/distributors-grammar/src/Control/Lens/Grammar/Class.hs index bfcd4eb9..5bcc617c 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/Class.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/Class.hs @@ -60,42 +60,42 @@ class CtxGrammar token a where -- Base types -- instance CtxGrammar Char Char -instance Grammar Char Char where grammar = rule "Char" (regGrammar @Char) +instance Grammar Char Char where grammar = ruleTyped (regGrammar @Char) instance RegGrammar Char Char where regGrammar = anyToken @Char instance CtxGrammar Char String -instance Grammar Char String where grammar = rule "String" (regGrammar @Char) +instance Grammar Char String where grammar = ruleTyped (regGrammar @Char) instance RegGrammar Char String where regGrammar = manyP (anyToken @Char) instance CtxGrammar Char Natural -instance Grammar Char Natural where grammar = rule "Natural" (regGrammar @Char) +instance Grammar Char Natural where grammar = ruleTyped (regGrammar @Char) instance RegGrammar Char Natural where regGrammar = naturalG instance CtxGrammar Char Integer -instance Grammar Char Integer where grammar = rule "Integer" (regGrammar @Char) +instance Grammar Char Integer where grammar = ruleTyped (regGrammar @Char) instance RegGrammar Char Integer where regGrammar = integerG instance CtxGrammar Char Double -instance Grammar Char Double where grammar = rule "Double" (regGrammar @Char) +instance Grammar Char Double where grammar = ruleTyped (regGrammar @Char) instance RegGrammar Char Double where regGrammar = floatingG instance CtxGrammar Char Float -instance Grammar Char Float where grammar = rule "Float" (regGrammar @Char) +instance Grammar Char Float where grammar = ruleTyped (regGrammar @Char) instance RegGrammar Char Float where regGrammar = floatingG {- Sized integers' syntax is `Integer`'s, but a literal out of their range fails to build, which only a `CtxGrammar`'s `Filtrator` can, so they have no regular expression or Backus-Naur form. -} -instance CtxGrammar Char Int where ctxGrammar = rule "Int" sizedG -instance CtxGrammar Char Int8 where ctxGrammar = rule "Int8" sizedG -instance CtxGrammar Char Int16 where ctxGrammar = rule "Int16" sizedG -instance CtxGrammar Char Int32 where ctxGrammar = rule "Int32" sizedG -instance CtxGrammar Char Int64 where ctxGrammar = rule "Int64" sizedG -instance CtxGrammar Char Word where ctxGrammar = rule "Word" sizedG -instance CtxGrammar Char Word8 where ctxGrammar = rule "Word8" sizedG -instance CtxGrammar Char Word16 where ctxGrammar = rule "Word16" sizedG -instance CtxGrammar Char Word32 where ctxGrammar = rule "Word32" sizedG -instance CtxGrammar Char Word64 where ctxGrammar = rule "Word64" sizedG +instance CtxGrammar Char Int where ctxGrammar = ruleTyped sizedG +instance CtxGrammar Char Int8 where ctxGrammar = ruleTyped sizedG +instance CtxGrammar Char Int16 where ctxGrammar = ruleTyped sizedG +instance CtxGrammar Char Int32 where ctxGrammar = ruleTyped sizedG +instance CtxGrammar Char Int64 where ctxGrammar = ruleTyped sizedG +instance CtxGrammar Char Word where ctxGrammar = ruleTyped sizedG +instance CtxGrammar Char Word8 where ctxGrammar = ruleTyped sizedG +instance CtxGrammar Char Word16 where ctxGrammar = ruleTyped sizedG +instance CtxGrammar Char Word32 where ctxGrammar = ruleTyped sizedG +instance CtxGrammar Char Word64 where ctxGrammar = ruleTyped sizedG -- ASCII decimal digits, at least one, of floating point numbers. decimalG :: RegGrammatical Char p => p String String 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/src/Control/Lens/Grammar/Json.hs b/distributors-json/src/Control/Lens/Grammar/Json.hs index 7c742d69..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 @@ -2665,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 ()) @@ -2681,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 @@ -2695,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 @@ -2710,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 @@ -2755,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)) @@ -3032,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 @@ -3076,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 @@ -3103,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) @@ -3169,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 @@ -3186,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 @@ -3198,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 @@ -3268,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/test/Properties/Json.hs b/distributors-json/test/Properties/Json.hs index a7deeeaf..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 @@ -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)) From f6d8ab821b4143650261f6c508efa32a252ac5f8 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sat, 14 Nov 2026 01:18:03 -0800 Subject: [PATCH 29/51] Base types' grammars at parity with Read & Show lexemes; no String instance Co-Authored-By: Claude Opus 5.5 --- distributors-grammar/CHANGELOG.md | 17 +- .../src/Control/Lens/Grammar/Class.hs | 285 +++++++++++++----- distributors-grammar/test/Properties/Base.hs | 91 +++--- 3 files changed, 265 insertions(+), 128 deletions(-) diff --git a/distributors-grammar/CHANGELOG.md b/distributors-grammar/CHANGELOG.md index 7d6e8be8..6c3df1a3 100644 --- a/distributors-grammar/CHANGELOG.md +++ b/distributors-grammar/CHANGELOG.md @@ -26,14 +26,15 @@ 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, @\\-@. -- Grammars of base types, each a rule named by its type: `Char`, any - token; `String`, any tokens; `Natural`, ASCII digits; `Integer`, an - optional minus & digits; `Double` & `Float`, @NaN@, or signed @Infinity@ - or decimals with an optional fraction & exponent; printing canonically, - as `show` does, & parsing more, as `read` does, by improper isos. Sized - integers, `Int`s & `Word`s, are `CtxGrammar`s, failing out of range by - their `Filtrator`, so they have no regular expressions or Backus-Naur - forms. +- Grammars of base types, each a rule named by its type by `ruleTyped`, + with parity with their `Read` & `Show` instances' lexemes, printing as + `show` does & parsing as `read` does, but for the whitespace & + parentheses which `read` accepts around any lexeme: `Char` literals, with + `showLitChar`'s escapes, & `read`'s named, numeric & control escapes; + `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`. They're regular & LL(1). + `String`, a list of characters, has no instance. - `Predicate`s are `Tokenized` & `TokenAlgebra`s, as predicates are; & `ReadPrec` runs grammars as `ReadP` does, `Tokenized`, a `TokenAlgebra`, `TerminalSymbol`, `Ruled`, `BackusNaurForm` & `Tried`. diff --git a/distributors-grammar/src/Control/Lens/Grammar/Class.hs b/distributors-grammar/src/Control/Lens/Grammar/Class.hs index 5bcc617c..6936bf08 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/Class.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/Class.hs @@ -25,13 +25,17 @@ import Control.Lens.PartialIso import Control.Lens.Grammar.BackusNaur import Control.Lens.Grammar.Symbol import Control.Lens.Grammar.Token -import Data.Bits (Bits, toIntegralSized) import Data.Char (isDigit, isLetter, ord, toLower, toUpper) +import Data.List (nub) +import Data.Ratio ((%)) +import Numeric (floatToDigits) +import Control.Lens.Diopter (skippedMany) +import Control.Lens.Prismoid ((>?*)) import Data.Int (Int8, Int16, Int32, Int64) import Data.Maybe (isJust) +import Data.Monoid.Disjunctive (orP, (>|<), (>&<)) import Data.Profunctor.Distributor import Data.Profunctor.Monoidal -import Data.Profunctor.Monoidal.Cocartesian import Data.Word (Word8, Word16, Word32, Word64) import Numeric.Natural (Natural) @@ -59,13 +63,13 @@ class CtxGrammar token a where -- Base types -- +{- The base types' grammars are their `Read` & `Show` instances' lexemes, +printing as `show` does, & parsing as `read` does, but for whitespace & +parentheses, which `read` accepts around any lexeme of any type. -} + instance CtxGrammar Char Char instance Grammar Char Char where grammar = ruleTyped (regGrammar @Char) -instance RegGrammar Char Char where regGrammar = anyToken @Char - -instance CtxGrammar Char String -instance Grammar Char String where grammar = ruleTyped (regGrammar @Char) -instance RegGrammar Char String where regGrammar = manyP (anyToken @Char) +instance RegGrammar Char Char where regGrammar = charG instance CtxGrammar Char Natural instance Grammar Char Natural where grammar = ruleTyped (regGrammar @Char) @@ -83,41 +87,211 @@ instance CtxGrammar Char Float instance Grammar Char Float where grammar = ruleTyped (regGrammar @Char) instance RegGrammar Char Float where regGrammar = floatingG -{- Sized integers' syntax is `Integer`'s, but a literal out of their range -fails to build, which only a `CtxGrammar`'s `Filtrator` can, so they have -no regular expression or Backus-Naur form. -} -instance CtxGrammar Char Int where ctxGrammar = ruleTyped sizedG -instance CtxGrammar Char Int8 where ctxGrammar = ruleTyped sizedG -instance CtxGrammar Char Int16 where ctxGrammar = ruleTyped sizedG -instance CtxGrammar Char Int32 where ctxGrammar = ruleTyped sizedG -instance CtxGrammar Char Int64 where ctxGrammar = ruleTyped sizedG -instance CtxGrammar Char Word where ctxGrammar = ruleTyped sizedG -instance CtxGrammar Char Word8 where ctxGrammar = ruleTyped sizedG -instance CtxGrammar Char Word16 where ctxGrammar = ruleTyped sizedG -instance CtxGrammar Char Word32 where ctxGrammar = ruleTyped sizedG -instance CtxGrammar Char Word64 where ctxGrammar = ruleTyped sizedG - --- ASCII decimal digits, at least one, of floating point numbers. -decimalG :: RegGrammatical Char p => p String String -decimalG = someP (oneOf ['0' .. '9']) - --- An optional minus, as whether a number is negative. +-- Sized integers read as `Integer`s, wrapping out of range, as `read` does. +instance CtxGrammar Char Int +instance Grammar Char Int where grammar = ruleTyped (regGrammar @Char) +instance RegGrammar Char Int where regGrammar = wrappedG +instance CtxGrammar Char Int8 +instance Grammar Char Int8 where grammar = ruleTyped (regGrammar @Char) +instance RegGrammar Char Int8 where regGrammar = wrappedG +instance CtxGrammar Char Int16 +instance Grammar Char Int16 where grammar = ruleTyped (regGrammar @Char) +instance RegGrammar Char Int16 where regGrammar = wrappedG +instance CtxGrammar Char Int32 +instance Grammar Char Int32 where grammar = ruleTyped (regGrammar @Char) +instance RegGrammar Char Int32 where regGrammar = wrappedG +instance CtxGrammar Char Int64 +instance Grammar Char Int64 where grammar = ruleTyped (regGrammar @Char) +instance RegGrammar Char Int64 where regGrammar = wrappedG +instance CtxGrammar Char Word +instance Grammar Char Word where grammar = ruleTyped (regGrammar @Char) +instance RegGrammar Char Word where regGrammar = wrappedG +instance CtxGrammar Char Word8 +instance Grammar Char Word8 where grammar = ruleTyped (regGrammar @Char) +instance RegGrammar Char Word8 where regGrammar = wrappedG +instance CtxGrammar Char Word16 +instance Grammar Char Word16 where grammar = ruleTyped (regGrammar @Char) +instance RegGrammar Char Word16 where regGrammar = wrappedG +instance CtxGrammar Char Word32 +instance Grammar Char Word32 where grammar = ruleTyped (regGrammar @Char) +instance RegGrammar Char Word32 where regGrammar = wrappedG +instance CtxGrammar Char Word64 +instance Grammar Char Word64 where grammar = ruleTyped (regGrammar @Char) +instance RegGrammar Char Word64 where regGrammar = wrappedG + +-- A prism which never matches, so that its alternative parses, but never prints. +unprinted :: Prism' a a +unprinted = prism' id (const Nothing) + +-- One of two terminals, printing the first, & parsing either. +eitherOf :: RegGrammatical Char p => String -> String -> p () () +eitherOf printed parsed = terminal printed >|< (unprinted >? terminal parsed) + +-- A minus, a lexeme of its own, as whether a number is negative. negativeG :: RegGrammatical Char p => p Bool Bool negativeG = iso (\b -> if b then Just () else Nothing) isJust >~ optionalP (terminal "-") --- Printing canonically, parsing leading zeros too. +-- Signed, by an improper iso, where @-0@ parses too. +signed :: (Num a, Ord a) => Iso' a (Bool, a) +signed = 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. +magnitudeG :: RegGrammatical Char p => p Integer Integer +magnitudeG = (unprinted >? try (terminal "0" >* basedG)) >|< numeral 10 + +basedG :: RegGrammatical Char p => p Integer Integer +basedG = orP + [ eitherOf "b" "B" >* numeral 2 + , eitherOf "o" "O" >* numeral 8 + , eitherOf "x" "X" >* numeral 16 + ] + +-- Natural numbers, & negative zero, as `read` reads integers & keeps +-- those which aren't negative. naturalG :: RegGrammatical Char p => p Natural Natural -naturalG = numeral 10 +naturalG = (iso toInteger fromInteger >~ magnitudeG) + >|< (unprinted . only 0 >? terminal "-" >* zerosG) + where + zerosG = terminal "0" >* orP + [ skippedMany >?* terminal "0" + , orP (map terminal ["b", "B", "o", "O", "x", "X"]) + >* terminal "0" >* (skippedMany >?* terminal "0") + ] --- Printing canonically, parsing leading zeros & -0 too, an improper iso. integerG :: RegGrammatical Char p => p Integer Integer -integerG = iso - (\n -> (n < 0, abs n)) - (\(negative, n) -> if negative then negate n else n) - >~ negativeG >*< numeral 10 +integerG = signed >~ negativeG >*< magnitudeG + +wrappedG :: (Integral a, RegGrammatical Char p) => p a a +wrappedG = iso toInteger fromInteger >~ integerG + +-- 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 -{- | A digit in a base, from 2 to 36, by its value: -9@, then letters, +_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. -} +floatingG :: (RealFloat a, RegGrammatical Char p) => p a a +floatingG = iso toLexeme fromLexeme >~ negativeG >*< orP + [ only NotANumber >? terminal "NaN" + , only Infinite >? terminal "Infinity" + , unprinted . _Based >? try (terminal "0" >* basedG) + , _Decimal >? someP (digit 10) + >*< optionalP (terminal "." >* someP (digit 10)) + >*< optionalP (eitherOf "e" "E" >* (signed >~ exponentSignG >*< numeral 10)) + ] + where + exponentSignG = orP + [ only True >? terminal "-" + , only False . unprinted >? terminal "+" + , only False >? oneP + ] + +toLexeme :: RealFloat a => a -> (Bool, FloatLexeme) +toLexeme 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 + +fromLexeme :: RealFloat a => (Bool, FloatLexeme) -> a +fromLexeme (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, printing as `show` does, +by `showLitChar`, & parsing as `read` does: unescaped, but for @\\@ & @'@; +by a named escape; or by its decimal, octal or hexadecimal code, or as a +control, @\\^@@ to @\\^_@. -} +charG :: RegGrammatical Char p => p Char Char +charG = terminal "'" >* orP + [ tokenClass (oneOf [' ' .. '~'] >&< notOneOf "\\'") + , unprinted >? tokenClass (notOneOf ("\\'" <> [' ' .. '~'])) + , terminal "\\" >* orP + [ escapesG + ( [('\'', "'"), ('\a', "a"), ('\b', "b"), ('\f', "f"), ('\n', "n")] + <> [('\r', "r"), ('\t', "t"), ('\v', "v"), ('\\', "\\"), ('"', "\"")] + <> zip ['\NUL' ..] asciiNames <> [(' ', "SP"), ('\DEL', "DEL")] ) + , prism' fromCode (\c -> if c > '\DEL' then Just (fromEnum c) else Nothing) + >? numeral 10 + , unprinted . codeOf >? eitherOf "o" "O" >* numeral 8 + , unprinted . codeOf >? eitherOf "x" "X" >* numeral 16 + , unprinted . iso (\c -> toEnum (fromEnum c + 64)) (\c -> toEnum (fromEnum c - 64)) + >? terminal "^" >* tokenClass (oneOf ['@' .. '_']) + ] + ] *< terminal "'" + where + codeOf = prism' fromCode (Just . fromEnum) + -- codes beyond `maxBound`, which `read` fails, are its, an improper prism + fromCode code = toEnum (min (fromEnum (maxBound :: Char)) code) + 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" ] + +-- Escapes by fixed strings, as a trie, which is LL(1), maximally munched, +-- like @\\SO@ & @\\SOH@, each character printing by its first string. +escapesG :: RegGrammatical Char p => [(Char, String)] -> p Char Char +escapesG escapes = orP $ + [only c >? oneP | (c, "") <- take 1 [e | e@(_, "") <- escapes]] + <> [ terminal [first] >* escapesG [(c, rest) | (c, x : rest) <- escapes, x == first] + | first <- nub [x | (_, x : _) <- escapes] ] + +{- | 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"] @@ -148,46 +322,3 @@ numeral base = iso digitsOf (foldl' (\n d -> n * base + d) 0) >~ someP (digit ba digitsOf n | n < base = [n] | otherwise = let (q, r) = n `quotRem` base in digitsOf q <> [r] - --- Integers in a range, failing to build out of it. -sizedG - :: forall a p. (Integral a, Bits a, CtxGrammatical Char p) => p a a -sizedG = prism' toInteger toIntegralSized ?< integerG - -{- Floating point numbers, @NaN@, or signed @Infinity@ or decimals with -an optional fraction & exponent, printing as `show` does & parsing as -`read` does, an improper iso, keeping the sign of zero. -} -floatingG - :: (RealFloat a, Read a, Show a, RegGrammatical Char p) => p a a -floatingG = iso toFloating fromFloating >~ - terminal "NaN" >+< negativeG >*< (terminal "Infinity" >+< numberG) - where - numberG = decimalG - >*< optionalP (terminal "." >* decimalG) - >*< optionalP (oneOf "eE" >*< optionalP (oneOf "+-") >*< decimalG) - toFloating x - | isNaN x = Left () - | otherwise = Right - ( x < 0 || isNegativeZero x - , if isInfinite x then Left () else Right (split (show (abs x))) ) - fromFloating = \case - Left () -> 0 / 0 - Right (negative, magnitude) -> (if negative then negate else id) $ - either (const (1 / 0)) (read . unsplit) magnitude - split shown = - let - (whole, rest) = span isDigit shown - (fraction, rest') = case rest of - '.' : more -> let (ds, more') = span isDigit more in (Just ds, more') - _ -> (Nothing, rest) - exponent' = case rest' of - e : more | e `elem` ("eE" :: String) -> case more of - s : ds | s `elem` ("+-" :: String) -> Just (e, (Just s, ds)) - ds -> Just (e, (Nothing, ds)) - _ -> Nothing - in - (whole, (fraction, exponent')) - unsplit (whole, (fraction, exponent')) = whole - <> maybe "" ('.' :) fraction - <> maybe "" (\(e, (s, ds)) -> e : maybe "" pure s <> ds) exponent' - diff --git a/distributors-grammar/test/Properties/Base.hs b/distributors-grammar/test/Properties/Base.hs index ef1651e4..561f7ea6 100644 --- a/distributors-grammar/test/Properties/Base.hs +++ b/distributors-grammar/test/Properties/Base.hs @@ -1,9 +1,8 @@ module Properties.Base (baseProperties) where import Control.Lens.Grammar -import Data.Int (Int8) -import GHC.Exts (toList) -import Data.Word (Word8) +import Data.Int (Int8, Int64) +import Data.Word (Word8, Word64) import Numeric.Natural (Natural) import Test.Hspec import Test.Hspec.QuickCheck (prop) @@ -17,51 +16,57 @@ parsed str = [a | (a, "") <- parseG @a str] printed :: CtxGrammar Char a => a -> Maybe String printed a = ($ "") <$> printG a --- | Printing then parsing round-trips, compared by @eq@. -roundTrips :: forall a. (CtxGrammar Char a, Show a) => a -> Property -roundTrips a = case printed a of - Nothing -> counterexample ("doesn't print: " <> show a) False - Just str -> map show (parsed @a str) === [show a] +-- | Printing is `show`, & parsing its print is the value, by `show`, +-- so that @NaN@ is itself. +showParity :: forall a. (CtxGrammar Char a, Show a) => a -> Property +showParity a = + printed a === Just (show a) .&&. map show (parsed @a (show a)) === [show a] + +-- | Parsing is `read`, for strings which `read` parses. +readParity :: forall a. (CtxGrammar Char a, Read a, Show a) => String -> Expectation +readParity str = map show (parsed @a str) `shouldBe` [show (read str :: a)] + +-- | Parsing fails, as `read` does. +readFails :: forall a. (CtxGrammar Char a, Show a) => String -> Expectation +readFails str = map show (parsed @a str) `shouldBe` [] baseProperties :: Spec baseProperties = do - describe "round trips, printing then parsing" $ do - prop "Char" $ roundTrips @Char - prop "String" $ roundTrips @String - prop "Natural" $ \(NonNegative (n :: Integer)) -> roundTrips (fromInteger n :: Natural) - prop "Integer" $ roundTrips @Integer - prop "Int" $ roundTrips @Int - prop "Int8" $ roundTrips @Int8 - prop "Word8" $ roundTrips @Word8 - prop "Double" $ roundTrips @Double - prop "Float" $ roundTrips @Float - it "Double's NaN, infinities & negative zero" $ - mapM_ (\x -> map show (parsed @Double =<< maybe [] pure (printed x)) `shouldBe` [show x]) - [0 / 0, 1 / 0, -(1 / 0), -0.0 :: Double] - describe "parsing more than printing, by improper isos" $ do - it "Natural, with leading zeros" $ parsed @Natural "007" `shouldBe` [7] - it "Integer, -0" $ parsed @Integer "-0" `shouldBe` [0] - it "Double, exponents & fractions" $ do - parsed @Double "1E+5" `shouldBe` [100000] - parsed @Double "1.50" `shouldBe` [1.5] - parsed @Double "2e-1" `shouldBe` [0.2] - it "prints canonically" $ do - printed (7 :: Natural) `shouldBe` Just "7" - printed (1.5 :: Double) `shouldBe` Just "1.5" - describe "sized integers, failing out of range" $ do - it "Word8" $ do - parsed @Word8 "255" `shouldBe` [255] - parsed @Word8 "256" `shouldBe` [] - parsed @Word8 "-1" `shouldBe` [] - it "Int8" $ do - parsed @Int8 "-128" `shouldBe` [-128] - parsed @Int8 "128" `shouldBe` [] + describe "prints as show does, & parses its print" $ do + prop "Char" $ showParity @Char + prop "Natural" $ \(NonNegative (n :: Integer)) -> showParity (fromInteger n :: Natural) + prop "Integer" $ showParity @Integer + prop "Int" $ showParity @Int + prop "Int8" $ showParity @Int8 + prop "Int64" $ showParity @Int64 + prop "Word8" $ showParity @Word8 + prop "Word64" $ showParity @Word64 + prop "Double" $ showParity @Double + prop "Float" $ showParity @Float + it "Double's & Float's specials" $ + conjoin (map (showParity @Double) [0 / 0, 1 / 0, -(1 / 0), -0.0, 0, 0.1, 1.0e7, 9999999, 5.0e-324]) + .&&. conjoin (map (showParity @Float) [0 / 0, 1 / 0, -0.0, 1.0e-2, 1.0e7]) + it "Char's escapes" $ + conjoin $ map (showParity @Char) (['\0' .. '\DEL'] <> ['\128', '\1234', '\1114111']) + describe "parses as read does" $ do + it "Natural" $ mapM_ (readParity @Natural) ["007", "0x1F", "0X1f", "0o17", "0O17", "0b101", "-0", "-0x00"] + it "Integer" $ mapM_ (readParity @Integer) ["-0", "-12", "0x1F", "-0o17", "0b0"] + it "sized integers, wrapping" $ do + mapM_ (readParity @Word8) ["255", "256", "-1", "0x1FF"] + mapM_ (readParity @Int8) ["127", "128", "-129"] + it "Double" $ mapM_ (readParity @Double) + [ "1E+5", "1.50", "2e-1", "0x10", "-Infinity", "Infinity", "NaN", "-NaN" + , "1e400", "1e-400", "0.000e99999999", "007.5", "1e-0" ] + it "Char" $ mapM_ (readParity @Char) + [ "'a'", "'\\n'", "'\\SOH'", "'\\SO'", "'\\1234'", "'\\x41'", "'\\X41'" + , "'\\o101'", "'\\^A'", "'\\^@'", "'\\DEL'", "'\"'", "'\\\"'", "'\\''" + , "'\\SP'", "'\\BEL'", "'\\a'", "'\n'" ] + describe "fails as read does" $ do + it "Natural" $ mapM_ (readFails @Natural) ["-1", "-0x1"] + it "Integer" $ mapM_ (readFails @Integer) ["1.5", "1e3", "0x", "--1", "+1"] + it "Char" $ mapM_ (readFails @Char) ["'''", "'\\&'", "'ab'", "''", "'\\q'"] describe "statically LL(1), by ll1Conflicts" $ do it "Char" $ ll1Conflicts (regbnfG @Char Char) `shouldBe` [] - it "String" $ ll1Conflicts (regbnfG @Char String) `shouldBe` [] it "Natural" $ ll1Conflicts (regbnfG @Char Natural) `shouldBe` [] it "Integer" $ ll1Conflicts (regbnfG @Char Integer) `shouldBe` [] it "Double" $ ll1Conflicts (regbnfG @Char Double) `shouldBe` [] - describe "regular expressions" $ do - it "Natural" $ toList (regexG @Char Natural) `shouldBe` "[0-9]+" - it "Integer" $ toList (regexG @Char Integer) `shouldBe` "-?[0-9]+" From 20a9264aae13f626d4383ac46435866f7048f054 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sat, 14 Nov 2026 01:25:36 -0800 Subject: [PATCH 30/51] wrappedG is integralG Co-Authored-By: Claude Opus 5.5 --- .../src/Control/Lens/Grammar/Class.hs | 24 +++++++++---------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/distributors-grammar/src/Control/Lens/Grammar/Class.hs b/distributors-grammar/src/Control/Lens/Grammar/Class.hs index 6936bf08..e694465c 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/Class.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/Class.hs @@ -90,34 +90,34 @@ instance RegGrammar Char Float where regGrammar = floatingG -- Sized integers read as `Integer`s, wrapping out of range, as `read` does. instance CtxGrammar Char Int instance Grammar Char Int where grammar = ruleTyped (regGrammar @Char) -instance RegGrammar Char Int where regGrammar = wrappedG +instance RegGrammar Char Int where regGrammar = integralG instance CtxGrammar Char Int8 instance Grammar Char Int8 where grammar = ruleTyped (regGrammar @Char) -instance RegGrammar Char Int8 where regGrammar = wrappedG +instance RegGrammar Char Int8 where regGrammar = integralG instance CtxGrammar Char Int16 instance Grammar Char Int16 where grammar = ruleTyped (regGrammar @Char) -instance RegGrammar Char Int16 where regGrammar = wrappedG +instance RegGrammar Char Int16 where regGrammar = integralG instance CtxGrammar Char Int32 instance Grammar Char Int32 where grammar = ruleTyped (regGrammar @Char) -instance RegGrammar Char Int32 where regGrammar = wrappedG +instance RegGrammar Char Int32 where regGrammar = integralG instance CtxGrammar Char Int64 instance Grammar Char Int64 where grammar = ruleTyped (regGrammar @Char) -instance RegGrammar Char Int64 where regGrammar = wrappedG +instance RegGrammar Char Int64 where regGrammar = integralG instance CtxGrammar Char Word instance Grammar Char Word where grammar = ruleTyped (regGrammar @Char) -instance RegGrammar Char Word where regGrammar = wrappedG +instance RegGrammar Char Word where regGrammar = integralG instance CtxGrammar Char Word8 instance Grammar Char Word8 where grammar = ruleTyped (regGrammar @Char) -instance RegGrammar Char Word8 where regGrammar = wrappedG +instance RegGrammar Char Word8 where regGrammar = integralG instance CtxGrammar Char Word16 instance Grammar Char Word16 where grammar = ruleTyped (regGrammar @Char) -instance RegGrammar Char Word16 where regGrammar = wrappedG +instance RegGrammar Char Word16 where regGrammar = integralG instance CtxGrammar Char Word32 instance Grammar Char Word32 where grammar = ruleTyped (regGrammar @Char) -instance RegGrammar Char Word32 where regGrammar = wrappedG +instance RegGrammar Char Word32 where regGrammar = integralG instance CtxGrammar Char Word64 instance Grammar Char Word64 where grammar = ruleTyped (regGrammar @Char) -instance RegGrammar Char Word64 where regGrammar = wrappedG +instance RegGrammar Char Word64 where regGrammar = integralG -- A prism which never matches, so that its alternative parses, but never prints. unprinted :: Prism' a a @@ -166,8 +166,8 @@ naturalG = (iso toInteger fromInteger >~ magnitudeG) integerG :: RegGrammatical Char p => p Integer Integer integerG = signed >~ negativeG >*< magnitudeG -wrappedG :: (Integral a, RegGrammatical Char p) => p a a -wrappedG = iso toInteger fromInteger >~ integerG +integralG :: (Integral a, RegGrammatical Char p) => p a a +integralG = iso toInteger fromInteger >~ integerG -- A floating point number's lexeme, without its sign. data FloatLexeme From 70ea53e3e70f8059ca98eb5c7dbf8e128a030037 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sat, 14 Nov 2026 01:35:31 -0800 Subject: [PATCH 31/51] Base types' grammars equivalent to Read & Show, property tested Whitespace & parentheses, as read accepts them, & character codes bounded by maxBound; readShowEquivalence tests each instance against show & readMaybe, on variants, decorations & mutations of its values' strings. Co-Authored-By: Claude Opus 5.5 --- distributors-grammar/CHANGELOG.md | 20 +- .../src/Control/Lens/Grammar/BackusNaur.hs | 8 +- .../src/Control/Lens/Grammar/Class.hs | 134 ++++++++----- distributors-grammar/test/Properties/Base.hs | 176 +++++++++++++----- 4 files changed, 237 insertions(+), 101 deletions(-) diff --git a/distributors-grammar/CHANGELOG.md b/distributors-grammar/CHANGELOG.md index 6c3df1a3..b983e943 100644 --- a/distributors-grammar/CHANGELOG.md +++ b/distributors-grammar/CHANGELOG.md @@ -26,15 +26,17 @@ 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, @\\-@. -- Grammars of base types, each a rule named by its type by `ruleTyped`, - with parity with their `Read` & `Show` instances' lexemes, printing as - `show` does & parsing as `read` does, but for the whitespace & - parentheses which `read` accepts around any lexeme: `Char` literals, with - `showLitChar`'s escapes, & `read`'s named, numeric & control escapes; - `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`. They're regular & LL(1). - `String`, a list of characters, has no instance. +- Grammars of base types, equivalent to their `Read` & `Show` instances, + printing as `show` does & parsing as `read` does, property tested against + `show` & `readMaybe`: their lexemes, amid whitespace & within any + parentheses, context-free, each a rule named by its type by + `ruleRecTyped`. `Char` literals, 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`. They're LL(1), by `try`, as `read`'s + lexer is left-biased. `String`, a list of characters, has no instance. +- `ruleRecTyped`, a `ruleRec` named by its `Typeable` type, as `ruleTyped`. - `Predicate`s are `Tokenized` & `TokenAlgebra`s, as predicates are; & `ReadPrec` runs grammars as `ReadP` does, `Tokenized`, a `TokenAlgebra`, `TerminalSymbol`, `Ruled`, `BackusNaurForm` & `Tried`. diff --git a/distributors-grammar/src/Control/Lens/Grammar/BackusNaur.hs b/distributors-grammar/src/Control/Lens/Grammar/BackusNaur.hs index ab8f883c..c40eed46 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/BackusNaur.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/BackusNaur.hs @@ -15,7 +15,7 @@ See Naur & Backus, et al. module Control.Lens.Grammar.BackusNaur ( -- * BackusNaurForm BackusNaurForm (..) - , Ruled (..), failP, ruleTyped + , Ruled (..), failP, ruleTyped, ruleRecTyped , Tried (..) -- * Grammatical , RegGrammatical @@ -107,6 +107,12 @@ 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 `ruleRec` for a Haskell type, named by its `Typeable` type, as `ruleTyped`. +ruleRecTyped + :: forall a p. (Typeable a, BackusNaurForm (p a a)) => (p a a -> p a a) -> p a a +ruleRecTyped = ruleRec (qualifiedName (SomeTypeRep (typeRep @a))) +{-# INLINE ruleRecTyped #-} + -- | A type, `show`n with its type constructors qualified by their modules. qualifiedName :: SomeTypeRep -> String qualifiedName (SomeTypeRep rep) = case (bracketed tyCon, args) of diff --git a/distributors-grammar/src/Control/Lens/Grammar/Class.hs b/distributors-grammar/src/Control/Lens/Grammar/Class.hs index e694465c..30e9f99c 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/Class.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/Class.hs @@ -37,6 +37,7 @@ import Data.Monoid.Disjunctive (orP, (>|<), (>&<)) import Data.Profunctor.Distributor import Data.Profunctor.Monoidal import Data.Word (Word8, Word16, Word32, Word64) +import Data.Typeable (Typeable) import Numeric.Natural (Natural) -- $setup @@ -63,61 +64,46 @@ class CtxGrammar token a where -- Base types -- -{- The base types' grammars are their `Read` & `Show` instances' lexemes, -printing as `show` does, & parsing as `read` does, but for whitespace & -parentheses, which `read` accepts around any lexeme of any type. -} +{- The base types' grammars are equivalent to their `Read` & `Show` +instances, printing as `show` does, & parsing as `read` does, their +lexemes amid whitespace & within parentheses, context-free. -} instance CtxGrammar Char Char -instance Grammar Char Char where grammar = ruleTyped (regGrammar @Char) -instance RegGrammar Char Char where regGrammar = charG +instance Grammar Char Char where grammar = readable charG instance CtxGrammar Char Natural -instance Grammar Char Natural where grammar = ruleTyped (regGrammar @Char) -instance RegGrammar Char Natural where regGrammar = naturalG +instance Grammar Char Natural where grammar = readable naturalG instance CtxGrammar Char Integer -instance Grammar Char Integer where grammar = ruleTyped (regGrammar @Char) -instance RegGrammar Char Integer where regGrammar = integerG +instance Grammar Char Integer where grammar = readable integerG instance CtxGrammar Char Double -instance Grammar Char Double where grammar = ruleTyped (regGrammar @Char) -instance RegGrammar Char Double where regGrammar = floatingG +instance Grammar Char Double where grammar = readable floatingG instance CtxGrammar Char Float -instance Grammar Char Float where grammar = ruleTyped (regGrammar @Char) -instance RegGrammar Char Float where regGrammar = floatingG +instance Grammar Char Float where grammar = readable floatingG -- Sized integers read as `Integer`s, wrapping out of range, as `read` does. instance CtxGrammar Char Int -instance Grammar Char Int where grammar = ruleTyped (regGrammar @Char) -instance RegGrammar Char Int where regGrammar = integralG +instance Grammar Char Int where grammar = readable integralG instance CtxGrammar Char Int8 -instance Grammar Char Int8 where grammar = ruleTyped (regGrammar @Char) -instance RegGrammar Char Int8 where regGrammar = integralG +instance Grammar Char Int8 where grammar = readable integralG instance CtxGrammar Char Int16 -instance Grammar Char Int16 where grammar = ruleTyped (regGrammar @Char) -instance RegGrammar Char Int16 where regGrammar = integralG +instance Grammar Char Int16 where grammar = readable integralG instance CtxGrammar Char Int32 -instance Grammar Char Int32 where grammar = ruleTyped (regGrammar @Char) -instance RegGrammar Char Int32 where regGrammar = integralG +instance Grammar Char Int32 where grammar = readable integralG instance CtxGrammar Char Int64 -instance Grammar Char Int64 where grammar = ruleTyped (regGrammar @Char) -instance RegGrammar Char Int64 where regGrammar = integralG +instance Grammar Char Int64 where grammar = readable integralG instance CtxGrammar Char Word -instance Grammar Char Word where grammar = ruleTyped (regGrammar @Char) -instance RegGrammar Char Word where regGrammar = integralG +instance Grammar Char Word where grammar = readable integralG instance CtxGrammar Char Word8 -instance Grammar Char Word8 where grammar = ruleTyped (regGrammar @Char) -instance RegGrammar Char Word8 where regGrammar = integralG +instance Grammar Char Word8 where grammar = readable integralG instance CtxGrammar Char Word16 -instance Grammar Char Word16 where grammar = ruleTyped (regGrammar @Char) -instance RegGrammar Char Word16 where regGrammar = integralG +instance Grammar Char Word16 where grammar = readable integralG instance CtxGrammar Char Word32 -instance Grammar Char Word32 where grammar = ruleTyped (regGrammar @Char) -instance RegGrammar Char Word32 where regGrammar = integralG +instance Grammar Char Word32 where grammar = readable integralG instance CtxGrammar Char Word64 -instance Grammar Char Word64 where grammar = ruleTyped (regGrammar @Char) -instance RegGrammar Char Word64 where regGrammar = integralG +instance Grammar Char Word64 where grammar = readable integralG -- A prism which never matches, so that its alternative parses, but never prints. unprinted :: Prism' a a @@ -130,7 +116,19 @@ eitherOf printed parsed = terminal printed >|< (unprinted >? terminal parsed) -- A minus, a lexeme of its own, as whether a number is negative. negativeG :: RegGrammatical Char p => p Bool Bool negativeG = iso (\b -> if b then Just () else Nothing) isJust - >~ optionalP (terminal "-") + >~ optionalP (terminal "-" >* spacesG) + +-- Whitespace, by `Data.Char.isSpace`, which `read` skips before each +-- lexeme & after all, & which never prints. +spacesG :: RegGrammatical Char p => p () () +spacesG = skippedMany >?* tokenClass (oneOf "\t\n\v\f\r" >|< asIn Space) + +-- A lexeme's grammar, as `read` reads it, by `parens`: after whitespace, & +-- within any parentheses, each after whitespace, & before whitespace once, +-- at the end; printing as `show` does, bare. +readable :: forall a p. (Typeable a, Grammatical Char p) => p a a -> p a a +readable lexeme = ruleRecTyped (\self -> spacesG >* + (lexeme >|< terminal "(" >* self *< spacesG *< terminal ")")) *< spacesG -- Signed, by an improper iso, where @-0@ parses too. signed :: (Num a, Ord a) => Iso' a (Bool, a) @@ -155,7 +153,7 @@ basedG = orP -- those which aren't negative. naturalG :: RegGrammatical Char p => p Natural Natural naturalG = (iso toInteger fromInteger >~ magnitudeG) - >|< (unprinted . only 0 >? terminal "-" >* zerosG) + >|< (unprinted . only 0 >? terminal "-" >* spacesG >* zerosG) where zerosG = terminal "0" >* orP [ skippedMany >?* terminal "0" @@ -265,18 +263,18 @@ charG = terminal "'" >* orP ( [('\'', "'"), ('\a', "a"), ('\b', "b"), ('\f', "f"), ('\n', "n")] <> [('\r', "r"), ('\t', "t"), ('\v', "v"), ('\\', "\\"), ('"', "\"")] <> zip ['\NUL' ..] asciiNames <> [(' ', "SP"), ('\DEL', "DEL")] ) - , prism' fromCode (\c -> if c > '\DEL' then Just (fromEnum c) else Nothing) - >? numeral 10 - , unprinted . codeOf >? eitherOf "o" "O" >* numeral 8 - , unprinted . codeOf >? eitherOf "x" "X" >* numeral 16 + , prism' toEnum (\c -> if c > '\DEL' then Just (fromEnum c) else Nothing) + >? boundedNumeral 10 maxCode + , unprinted . codeOf >? eitherOf "o" "O" >* boundedNumeral 8 maxCode + , unprinted . codeOf >? eitherOf "x" "X" >* boundedNumeral 16 maxCode , unprinted . iso (\c -> toEnum (fromEnum c + 64)) (\c -> toEnum (fromEnum c - 64)) >? terminal "^" >* tokenClass (oneOf ['@' .. '_']) ] ] *< terminal "'" where - codeOf = prism' fromCode (Just . fromEnum) - -- codes beyond `maxBound`, which `read` fails, are its, an improper prism - fromCode code = toEnum (min (fromEnum (maxBound :: Char)) code) + codeOf = prism' toEnum (Just . fromEnum) + -- codes up to `maxBound`, as `read` reads them + maxCode = fromEnum (maxBound :: Char) asciiNames = [ "NUL", "SOH", "STX", "ETX", "EOT", "ENQ", "ACK", "BEL" , "BS", "HT", "LF", "VT", "FF", "CR", "SO", "SI" @@ -322,3 +320,55 @@ numeral base = iso digitsOf (foldl' (\n d -> n * base + d) 0) >~ someP (digit ba digitsOf n | n < base = [n] | otherwise = let (q, r) = n `quotRem` base in digitsOf q <> [r] + +{- 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. -} +boundedNumeral :: forall n p. (Integral n, RegGrammatical Char p) => n -> n -> p n n +boundedNumeral base bound + = (unprinted >? 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 eitherOf [c] [toUpper c] else terminal [c] diff --git a/distributors-grammar/test/Properties/Base.hs b/distributors-grammar/test/Properties/Base.hs index 561f7ea6..7abada9a 100644 --- a/distributors-grammar/test/Properties/Base.hs +++ b/distributors-grammar/test/Properties/Base.hs @@ -1,12 +1,31 @@ -module Properties.Base (baseProperties) where +module Properties.Base (baseProperties, readShowEquivalence) where import Control.Lens.Grammar -import Data.Int (Int8, Int64) -import Data.Word (Word8, Word64) +import Data.Char (intToDigit, isAscii, isControl, ord, toUpper) +import Data.Int (Int8, Int16, Int32, Int64) +import Data.Maybe (maybeToList) +import Data.Word (Word8, Word16, Word32, Word64) +import Numeric (showIntAtBase) import Numeric.Natural (Natural) import Test.Hspec -import Test.Hspec.QuickCheck (prop) +import Test.Hspec.QuickCheck (modifyMaxSuccess, prop) import Test.QuickCheck +import Text.Read (readMaybe) + +{- | Equivalence with a type's `Read` & `Show` instances: printing is `show`, +& parsing is `readMaybe`, 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. (CtxGrammar Char a, Read a, Show a) + => String -> Gen a -> (a -> Gen String) -> Spec +readShowEquivalence name values variants = describe name $ do + prop "prints as show does" $ forAll values $ \a -> + printed a === Just (show a) + modifyMaxSuccess (const 1000) $ prop "parses as read does" $ + forAll (values >>= variants >>= decorated >>= mutated) $ \str -> + map show (parsed @a str) === map show (maybeToList (readMaybe @a str)) -- | Parse all of a string, if it parses. parsed :: forall a. CtxGrammar Char a => String -> [a] @@ -16,55 +35,114 @@ parsed str = [a | (a, "") <- parseG @a str] printed :: CtxGrammar Char a => a -> Maybe String printed a = ($ "") <$> printG a --- | Printing is `show`, & parsing its print is the value, by `show`, --- so that @NaN@ is itself. -showParity :: forall a. (CtxGrammar Char a, Show a) => a -> Property -showParity a = - printed a === Just (show a) .&&. map show (parsed @a (show a)) === [show a] +-- | 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" <> showIntAtBase 8 intToDigit (ord c) "") + , pure ("\\x" <> showIntAtBase 16 intToDigit (ord c) "") + , pure ("\\X" <> map toUpper (showIntAtBase 16 intToDigit (ord c) "")) ] + <> [pure ['\\', '^', toEnum (ord c + 64)] | ord c < 32] + pure ("'" <> escape <> "'") --- | Parsing is `read`, for strings which `read` parses. -readParity :: forall a. (CtxGrammar Char a, Read a, Show a) => String -> Expectation -readParity str = map show (parsed @a str) `shouldBe` [show (read str :: a)] +characters :: Gen Char +characters = frequency + [ (3, arbitraryASCIIChar) + , (2, elements "\\'\"\SO\SOH\DEL\NUL ") + , (1, arbitrary `suchThat` (\c -> isControl c || not (isAscii c))) + , (1, arbitraryUnicodeChar) ] --- | Parsing fails, as `read` does. -readFails :: forall a. (CtxGrammar Char a, Show a) => String -> Expectation -readFails str = map show (parsed @a str) `shouldBe` [] +-- | 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 = do - describe "prints as show does, & parses its print" $ do - prop "Char" $ showParity @Char - prop "Natural" $ \(NonNegative (n :: Integer)) -> showParity (fromInteger n :: Natural) - prop "Integer" $ showParity @Integer - prop "Int" $ showParity @Int - prop "Int8" $ showParity @Int8 - prop "Int64" $ showParity @Int64 - prop "Word8" $ showParity @Word8 - prop "Word64" $ showParity @Word64 - prop "Double" $ showParity @Double - prop "Float" $ showParity @Float - it "Double's & Float's specials" $ - conjoin (map (showParity @Double) [0 / 0, 1 / 0, -(1 / 0), -0.0, 0, 0.1, 1.0e7, 9999999, 5.0e-324]) - .&&. conjoin (map (showParity @Float) [0 / 0, 1 / 0, -0.0, 1.0e-2, 1.0e7]) - it "Char's escapes" $ - conjoin $ map (showParity @Char) (['\0' .. '\DEL'] <> ['\128', '\1234', '\1114111']) - describe "parses as read does" $ do - it "Natural" $ mapM_ (readParity @Natural) ["007", "0x1F", "0X1f", "0o17", "0O17", "0b101", "-0", "-0x00"] - it "Integer" $ mapM_ (readParity @Integer) ["-0", "-12", "0x1F", "-0o17", "0b0"] - it "sized integers, wrapping" $ do - mapM_ (readParity @Word8) ["255", "256", "-1", "0x1FF"] - mapM_ (readParity @Int8) ["127", "128", "-129"] - it "Double" $ mapM_ (readParity @Double) - [ "1E+5", "1.50", "2e-1", "0x10", "-Infinity", "Infinity", "NaN", "-NaN" - , "1e400", "1e-400", "0.000e99999999", "007.5", "1e-0" ] - it "Char" $ mapM_ (readParity @Char) - [ "'a'", "'\\n'", "'\\SOH'", "'\\SO'", "'\\1234'", "'\\x41'", "'\\X41'" - , "'\\o101'", "'\\^A'", "'\\^@'", "'\\DEL'", "'\"'", "'\\\"'", "'\\''" - , "'\\SP'", "'\\BEL'", "'\\a'", "'\n'" ] - describe "fails as read does" $ do - it "Natural" $ mapM_ (readFails @Natural) ["-1", "-0x1"] - it "Integer" $ mapM_ (readFails @Integer) ["1.5", "1e3", "0x", "--1", "+1"] - it "Char" $ mapM_ (readFails @Char) ["'''", "'\\&'", "'ab'", "''", "'\\q'"] +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 describe "statically LL(1), by ll1Conflicts" $ do it "Char" $ ll1Conflicts (regbnfG @Char Char) `shouldBe` [] it "Natural" $ ll1Conflicts (regbnfG @Char Natural) `shouldBe` [] From 7037fcec04b537df6da7358183a3908ff970fd31 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sat, 14 Nov 2026 05:54:53 -0800 Subject: [PATCH 32/51] Base types' grammars, lexemes again: parentheses & whitespace are precedence's Co-Authored-By: Claude Opus 5.5 --- distributors-grammar/CHANGELOG.md | 22 +++---- .../src/Control/Lens/Grammar/BackusNaur.hs | 8 +-- .../src/Control/Lens/Grammar/Class.hs | 60 +++++++++++-------- distributors-grammar/test/Properties/Base.hs | 31 ++++------ 4 files changed, 57 insertions(+), 64 deletions(-) diff --git a/distributors-grammar/CHANGELOG.md b/distributors-grammar/CHANGELOG.md index b983e943..6daab98a 100644 --- a/distributors-grammar/CHANGELOG.md +++ b/distributors-grammar/CHANGELOG.md @@ -26,17 +26,17 @@ 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, @\\-@. -- Grammars of base types, equivalent to their `Read` & `Show` instances, - printing as `show` does & parsing as `read` does, property tested against - `show` & `readMaybe`: their lexemes, amid whitespace & within any - parentheses, context-free, each a rule named by its type by - `ruleRecTyped`. `Char` literals, 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`. They're LL(1), by `try`, as `read`'s - lexer is left-biased. `String`, a list of characters, has no instance. -- `ruleRecTyped`, a `ruleRec` named by its `Typeable` type, as `ruleTyped`. +- Grammars of base types, equivalent to their `Read` & `Show` instances' + lexemes, printing as `show` does & parsing as `read` does, property tested + against `show` & `readMaybe`, but for whitespace around them & + parentheses, which `read` accepts around any value, a matter of + precedence; each a rule named by its type by `ruleTyped`. `Char` literals, + 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`. + They're regular & LL(1), by `try`, as `read`'s lexer is left-biased. + `String`, a list of characters, has no instance. - `Predicate`s are `Tokenized` & `TokenAlgebra`s, as predicates are; & `ReadPrec` runs grammars as `ReadP` does, `Tokenized`, a `TokenAlgebra`, `TerminalSymbol`, `Ruled`, `BackusNaurForm` & `Tried`. diff --git a/distributors-grammar/src/Control/Lens/Grammar/BackusNaur.hs b/distributors-grammar/src/Control/Lens/Grammar/BackusNaur.hs index c40eed46..ab8f883c 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/BackusNaur.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/BackusNaur.hs @@ -15,7 +15,7 @@ See Naur & Backus, et al. module Control.Lens.Grammar.BackusNaur ( -- * BackusNaurForm BackusNaurForm (..) - , Ruled (..), failP, ruleTyped, ruleRecTyped + , Ruled (..), failP, ruleTyped , Tried (..) -- * Grammatical , RegGrammatical @@ -107,12 +107,6 @@ 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 `ruleRec` for a Haskell type, named by its `Typeable` type, as `ruleTyped`. -ruleRecTyped - :: forall a p. (Typeable a, BackusNaurForm (p a a)) => (p a a -> p a a) -> p a a -ruleRecTyped = ruleRec (qualifiedName (SomeTypeRep (typeRep @a))) -{-# INLINE ruleRecTyped #-} - -- | A type, `show`n with its type constructors qualified by their modules. qualifiedName :: SomeTypeRep -> String qualifiedName (SomeTypeRep rep) = case (bracketed tyCon, args) of diff --git a/distributors-grammar/src/Control/Lens/Grammar/Class.hs b/distributors-grammar/src/Control/Lens/Grammar/Class.hs index 30e9f99c..f9924ac9 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/Class.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/Class.hs @@ -37,7 +37,6 @@ import Data.Monoid.Disjunctive (orP, (>|<), (>&<)) import Data.Profunctor.Distributor import Data.Profunctor.Monoidal import Data.Word (Word8, Word16, Word32, Word64) -import Data.Typeable (Typeable) import Numeric.Natural (Natural) -- $setup @@ -64,46 +63,62 @@ class CtxGrammar token a where -- Base types -- -{- The base types' grammars are equivalent to their `Read` & `Show` -instances, printing as `show` does, & parsing as `read` does, their -lexemes amid whitespace & within parentheses, context-free. -} +{- The base types' grammars are their `Read` & `Show` instances' lexemes, +printing as `show` does, & parsing as `read` does, but for whitespace +around them & parentheses, which `read` accepts around any value, of +any type, a matter of precedence. -} instance CtxGrammar Char Char -instance Grammar Char Char where grammar = readable charG +instance Grammar Char Char where grammar = ruleTyped (regGrammar @Char) +instance RegGrammar Char Char where regGrammar = charG instance CtxGrammar Char Natural -instance Grammar Char Natural where grammar = readable naturalG +instance Grammar Char Natural where grammar = ruleTyped (regGrammar @Char) +instance RegGrammar Char Natural where regGrammar = naturalG instance CtxGrammar Char Integer -instance Grammar Char Integer where grammar = readable integerG +instance Grammar Char Integer where grammar = ruleTyped (regGrammar @Char) +instance RegGrammar Char Integer where regGrammar = integerG instance CtxGrammar Char Double -instance Grammar Char Double where grammar = readable floatingG +instance Grammar Char Double where grammar = ruleTyped (regGrammar @Char) +instance RegGrammar Char Double where regGrammar = floatingG instance CtxGrammar Char Float -instance Grammar Char Float where grammar = readable floatingG +instance Grammar Char Float where grammar = ruleTyped (regGrammar @Char) +instance RegGrammar Char Float where regGrammar = floatingG -- Sized integers read as `Integer`s, wrapping out of range, as `read` does. instance CtxGrammar Char Int -instance Grammar Char Int where grammar = readable integralG +instance Grammar Char Int where grammar = ruleTyped (regGrammar @Char) +instance RegGrammar Char Int where regGrammar = integralG instance CtxGrammar Char Int8 -instance Grammar Char Int8 where grammar = readable integralG +instance Grammar Char Int8 where grammar = ruleTyped (regGrammar @Char) +instance RegGrammar Char Int8 where regGrammar = integralG instance CtxGrammar Char Int16 -instance Grammar Char Int16 where grammar = readable integralG +instance Grammar Char Int16 where grammar = ruleTyped (regGrammar @Char) +instance RegGrammar Char Int16 where regGrammar = integralG instance CtxGrammar Char Int32 -instance Grammar Char Int32 where grammar = readable integralG +instance Grammar Char Int32 where grammar = ruleTyped (regGrammar @Char) +instance RegGrammar Char Int32 where regGrammar = integralG instance CtxGrammar Char Int64 -instance Grammar Char Int64 where grammar = readable integralG +instance Grammar Char Int64 where grammar = ruleTyped (regGrammar @Char) +instance RegGrammar Char Int64 where regGrammar = integralG instance CtxGrammar Char Word -instance Grammar Char Word where grammar = readable integralG +instance Grammar Char Word where grammar = ruleTyped (regGrammar @Char) +instance RegGrammar Char Word where regGrammar = integralG instance CtxGrammar Char Word8 -instance Grammar Char Word8 where grammar = readable integralG +instance Grammar Char Word8 where grammar = ruleTyped (regGrammar @Char) +instance RegGrammar Char Word8 where regGrammar = integralG instance CtxGrammar Char Word16 -instance Grammar Char Word16 where grammar = readable integralG +instance Grammar Char Word16 where grammar = ruleTyped (regGrammar @Char) +instance RegGrammar Char Word16 where regGrammar = integralG instance CtxGrammar Char Word32 -instance Grammar Char Word32 where grammar = readable integralG +instance Grammar Char Word32 where grammar = ruleTyped (regGrammar @Char) +instance RegGrammar Char Word32 where regGrammar = integralG instance CtxGrammar Char Word64 -instance Grammar Char Word64 where grammar = readable integralG +instance Grammar Char Word64 where grammar = ruleTyped (regGrammar @Char) +instance RegGrammar Char Word64 where regGrammar = integralG -- A prism which never matches, so that its alternative parses, but never prints. unprinted :: Prism' a a @@ -123,13 +138,6 @@ negativeG = iso (\b -> if b then Just () else Nothing) isJust spacesG :: RegGrammatical Char p => p () () spacesG = skippedMany >?* tokenClass (oneOf "\t\n\v\f\r" >|< asIn Space) --- A lexeme's grammar, as `read` reads it, by `parens`: after whitespace, & --- within any parentheses, each after whitespace, & before whitespace once, --- at the end; printing as `show` does, bare. -readable :: forall a p. (Typeable a, Grammatical Char p) => p a a -> p a a -readable lexeme = ruleRecTyped (\self -> spacesG >* - (lexeme >|< terminal "(" >* self *< spacesG *< terminal ")")) *< spacesG - -- Signed, by an improper iso, where @-0@ parses too. signed :: (Num a, Ord a) => Iso' a (Bool, a) signed = iso diff --git a/distributors-grammar/test/Properties/Base.hs b/distributors-grammar/test/Properties/Base.hs index 7abada9a..e6d71ba3 100644 --- a/distributors-grammar/test/Properties/Base.hs +++ b/distributors-grammar/test/Properties/Base.hs @@ -1,7 +1,7 @@ module Properties.Base (baseProperties, readShowEquivalence) where import Control.Lens.Grammar -import Data.Char (intToDigit, isAscii, isControl, ord, toUpper) +import Data.Char (intToDigit, isAscii, isControl, isSpace, ord, toUpper) import Data.Int (Int8, Int16, Int32, Int64) import Data.Maybe (maybeToList) import Data.Word (Word8, Word16, Word32, Word64) @@ -12,10 +12,12 @@ import Test.Hspec.QuickCheck (modifyMaxSuccess, prop) import Test.QuickCheck import Text.Read (readMaybe) -{- | Equivalence with a type's `Read` & `Show` instances: printing is `show`, -& parsing is `readMaybe`, 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. +{- | Equivalence with a type's `Read` & `Show` instances' lexemes: printing +is `show`, & parsing is `readMaybe`, for strings of its values, by its +lexical variants, & mutated, so that strings which `read` rejects are +tried too, but for those with whitespace or parentheses around them, +which `read` accepts around any value, a matter of precedence. Each new +instance runs it. -} readShowEquivalence :: forall a. (CtxGrammar Char a, Read a, Show a) @@ -24,8 +26,11 @@ readShowEquivalence name values variants = describe name $ do prop "prints as show does" $ forAll values $ \a -> printed a === Just (show a) modifyMaxSuccess (const 1000) $ prop "parses as read does" $ - forAll (values >>= variants >>= decorated >>= mutated) $ \str -> + forAll (values >>= variants >>= mutated) $ \str -> lexical str ==> map show (parsed @a str) === map show (maybeToList (readMaybe @a str)) + where + lexical str = not (any outer (take 1 str <> take 1 (reverse str))) + outer c = isSpace c || c `elem` "()" -- | Parse all of a string, if it parses. parsed :: forall a. CtxGrammar Char a => String -> [a] @@ -42,20 +47,6 @@ spaces = frequency , (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)] From f67103e2049a6c3b8128096e3b3c225df52d4095 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sat, 14 Nov 2026 06:03:45 -0800 Subject: [PATCH 33/51] Control.Lens.Grammar.Prec: PrecGrammar, equivalent to stock Read & Show Haskell types have PrecGrammar instances, not Grammar instances, run by PrecGrammatical interpreters, with ReadPrec's prec, step & reset as precP, stepP & resetP, precedenceP & parensP; Precedence interprets them over any Grammatical one, for readsPrecG & showsPrecG. Base types' instances are property tested against showsPrec & readsPrec at each precedence. Co-Authored-By: Claude Opus 5.5 --- distributors-grammar/CHANGELOG.md | 25 +- .../distributors-grammar.cabal | 1 + .../src/Control/Lens/Grammar.hs | 1 + .../src/Control/Lens/Grammar/Class.hs | 306 +------------ .../src/Control/Lens/Grammar/Prec.hs | 408 ++++++++++++++++++ distributors-grammar/test/Properties/Base.hs | 68 +-- 6 files changed, 462 insertions(+), 347 deletions(-) create mode 100644 distributors-grammar/src/Control/Lens/Grammar/Prec.hs diff --git a/distributors-grammar/CHANGELOG.md b/distributors-grammar/CHANGELOG.md index 6daab98a..2681a42b 100644 --- a/distributors-grammar/CHANGELOG.md +++ b/distributors-grammar/CHANGELOG.md @@ -26,17 +26,20 @@ 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, @\\-@. -- Grammars of base types, equivalent to their `Read` & `Show` instances' - lexemes, printing as `show` does & parsing as `read` does, property tested - against `show` & `readMaybe`, but for whitespace around them & - parentheses, which `read` accepts around any value, a matter of - precedence; each a rule named by its type by `ruleTyped`. `Char` literals, - 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`. - They're regular & LL(1), by `try`, as `read`'s lexer is left-biased. - `String`, a list of characters, has no instance. +- `Control.Lens.Grammar.Prec`: Haskell types' grammars, by precedence, + equivalent to their stock `Read` & `Show` instances. `PrecGrammar` types, + run by `PrecGrammatical` interpreters, with `precP`, `stepP`, `resetP` & + `precedenceP`, as `ReadPrec`'s `prec`, `step` & `reset`, & `parensP`, as + `GHC.Read.parens` & `showParen`; `Precedence`, an interpreter over any + `Grammatical` one, run by `readsPrecG` & `showsPrecG`. Instances for + `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; `String`, a list of characters, has neither. - `Predicate`s are `Tokenized` & `TokenAlgebra`s, as predicates are; & `ReadPrec` runs grammars as `ReadP` does, `Tokenized`, a `TokenAlgebra`, `TerminalSymbol`, `Ruled`, `BackusNaurForm` & `Tried`. diff --git a/distributors-grammar/distributors-grammar.cabal b/distributors-grammar/distributors-grammar.cabal index 012bc59d..04b08077 100644 --- a/distributors-grammar/distributors-grammar.cabal +++ b/distributors-grammar/distributors-grammar.cabal @@ -33,6 +33,7 @@ library Control.Lens.Grammar.BackusNaur Control.Lens.Grammar.Class Control.Lens.Grammar.Machine + Control.Lens.Grammar.Prec Control.Lens.Grammar.RegEx Control.Lens.Grammar.Symbol Control.Lens.Grammar.Token diff --git a/distributors-grammar/src/Control/Lens/Grammar.hs b/distributors-grammar/src/Control/Lens/Grammar.hs index c9fc8409..ca12149b 100644 --- a/distributors-grammar/src/Control/Lens/Grammar.hs +++ b/distributors-grammar/src/Control/Lens/Grammar.hs @@ -75,6 +75,7 @@ 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.RegEx as X import Control.Lens.Grammar.Symbol as X import Control.Lens.Grammar.Token as X diff --git a/distributors-grammar/src/Control/Lens/Grammar/Class.hs b/distributors-grammar/src/Control/Lens/Grammar/Class.hs index f9924ac9..046125e8 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/Class.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/Class.hs @@ -1,6 +1,6 @@ {- | Module : Control.Lens.Grammar.Class -Description : grammar classes & base types' grammars +Description : grammar classes & numerals Copyright : (C) 2026 - Eitan Chatav License : BSD-style (see the file LICENSE) Maintainer : Eitan Chatav @@ -8,7 +8,9 @@ Stability : provisional Portability : non-portable The classes of types' grammars, over their tokens, regular, context-free -& context-sensitive, & the grammars of base types. +& 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 @@ -23,21 +25,9 @@ module Control.Lens.Grammar.Class import Control.Lens import Control.Lens.PartialIso import Control.Lens.Grammar.BackusNaur -import Control.Lens.Grammar.Symbol import Control.Lens.Grammar.Token import Data.Char (isDigit, isLetter, ord, toLower, toUpper) -import Data.List (nub) -import Data.Ratio ((%)) -import Numeric (floatToDigits) -import Control.Lens.Diopter (skippedMany) -import Control.Lens.Prismoid ((>?*)) -import Data.Int (Int8, Int16, Int32, Int64) -import Data.Maybe (isJust) -import Data.Monoid.Disjunctive (orP, (>|<), (>&<)) import Data.Profunctor.Distributor -import Data.Profunctor.Monoidal -import Data.Word (Word8, Word16, Word32, Word64) -import Numeric.Natural (Natural) -- $setup -- >>> import Control.Lens.Grammar @@ -61,242 +51,6 @@ class CtxGrammar token a where default ctxGrammar :: (Grammar token a, CtxGrammatical token p) => p a a ctxGrammar = grammar @token --- Base types -- - -{- The base types' grammars are their `Read` & `Show` instances' lexemes, -printing as `show` does, & parsing as `read` does, but for whitespace -around them & parentheses, which `read` accepts around any value, of -any type, a matter of precedence. -} - -instance CtxGrammar Char Char -instance Grammar Char Char where grammar = ruleTyped (regGrammar @Char) -instance RegGrammar Char Char where regGrammar = charG - -instance CtxGrammar Char Natural -instance Grammar Char Natural where grammar = ruleTyped (regGrammar @Char) -instance RegGrammar Char Natural where regGrammar = naturalG - -instance CtxGrammar Char Integer -instance Grammar Char Integer where grammar = ruleTyped (regGrammar @Char) -instance RegGrammar Char Integer where regGrammar = integerG - -instance CtxGrammar Char Double -instance Grammar Char Double where grammar = ruleTyped (regGrammar @Char) -instance RegGrammar Char Double where regGrammar = floatingG - -instance CtxGrammar Char Float -instance Grammar Char Float where grammar = ruleTyped (regGrammar @Char) -instance RegGrammar Char Float where regGrammar = floatingG - --- Sized integers read as `Integer`s, wrapping out of range, as `read` does. -instance CtxGrammar Char Int -instance Grammar Char Int where grammar = ruleTyped (regGrammar @Char) -instance RegGrammar Char Int where regGrammar = integralG -instance CtxGrammar Char Int8 -instance Grammar Char Int8 where grammar = ruleTyped (regGrammar @Char) -instance RegGrammar Char Int8 where regGrammar = integralG -instance CtxGrammar Char Int16 -instance Grammar Char Int16 where grammar = ruleTyped (regGrammar @Char) -instance RegGrammar Char Int16 where regGrammar = integralG -instance CtxGrammar Char Int32 -instance Grammar Char Int32 where grammar = ruleTyped (regGrammar @Char) -instance RegGrammar Char Int32 where regGrammar = integralG -instance CtxGrammar Char Int64 -instance Grammar Char Int64 where grammar = ruleTyped (regGrammar @Char) -instance RegGrammar Char Int64 where regGrammar = integralG -instance CtxGrammar Char Word -instance Grammar Char Word where grammar = ruleTyped (regGrammar @Char) -instance RegGrammar Char Word where regGrammar = integralG -instance CtxGrammar Char Word8 -instance Grammar Char Word8 where grammar = ruleTyped (regGrammar @Char) -instance RegGrammar Char Word8 where regGrammar = integralG -instance CtxGrammar Char Word16 -instance Grammar Char Word16 where grammar = ruleTyped (regGrammar @Char) -instance RegGrammar Char Word16 where regGrammar = integralG -instance CtxGrammar Char Word32 -instance Grammar Char Word32 where grammar = ruleTyped (regGrammar @Char) -instance RegGrammar Char Word32 where regGrammar = integralG -instance CtxGrammar Char Word64 -instance Grammar Char Word64 where grammar = ruleTyped (regGrammar @Char) -instance RegGrammar Char Word64 where regGrammar = integralG - --- A prism which never matches, so that its alternative parses, but never prints. -unprinted :: Prism' a a -unprinted = prism' id (const Nothing) - --- One of two terminals, printing the first, & parsing either. -eitherOf :: RegGrammatical Char p => String -> String -> p () () -eitherOf printed parsed = terminal printed >|< (unprinted >? terminal parsed) - --- A minus, a lexeme of its own, as whether a number is negative. -negativeG :: RegGrammatical Char p => p Bool Bool -negativeG = iso (\b -> if b then Just () else Nothing) isJust - >~ optionalP (terminal "-" >* spacesG) - --- Whitespace, by `Data.Char.isSpace`, which `read` skips before each --- lexeme & after all, & which never prints. -spacesG :: RegGrammatical Char p => p () () -spacesG = skippedMany >?* tokenClass (oneOf "\t\n\v\f\r" >|< asIn Space) - --- Signed, by an improper iso, where @-0@ parses too. -signed :: (Num a, Ord a) => Iso' a (Bool, a) -signed = 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. -magnitudeG :: RegGrammatical Char p => p Integer Integer -magnitudeG = (unprinted >? try (terminal "0" >* basedG)) >|< numeral 10 - -basedG :: RegGrammatical Char p => p Integer Integer -basedG = orP - [ eitherOf "b" "B" >* numeral 2 - , eitherOf "o" "O" >* numeral 8 - , eitherOf "x" "X" >* numeral 16 - ] - --- Natural numbers, & negative zero, as `read` reads integers & keeps --- those which aren't negative. -naturalG :: RegGrammatical Char p => p Natural Natural -naturalG = (iso toInteger fromInteger >~ magnitudeG) - >|< (unprinted . only 0 >? terminal "-" >* spacesG >* zerosG) - where - zerosG = terminal "0" >* orP - [ skippedMany >?* terminal "0" - , orP (map terminal ["b", "B", "o", "O", "x", "X"]) - >* terminal "0" >* (skippedMany >?* terminal "0") - ] - -integerG :: RegGrammatical Char p => p Integer Integer -integerG = signed >~ negativeG >*< magnitudeG - -integralG :: (Integral a, RegGrammatical Char p) => p a a -integralG = iso toInteger fromInteger >~ integerG - --- 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. -} -floatingG :: (RealFloat a, RegGrammatical Char p) => p a a -floatingG = iso toLexeme fromLexeme >~ negativeG >*< orP - [ only NotANumber >? terminal "NaN" - , only Infinite >? terminal "Infinity" - , unprinted . _Based >? try (terminal "0" >* basedG) - , _Decimal >? someP (digit 10) - >*< optionalP (terminal "." >* someP (digit 10)) - >*< optionalP (eitherOf "e" "E" >* (signed >~ exponentSignG >*< numeral 10)) - ] - where - exponentSignG = orP - [ only True >? terminal "-" - , only False . unprinted >? terminal "+" - , only False >? oneP - ] - -toLexeme :: RealFloat a => a -> (Bool, FloatLexeme) -toLexeme 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 - -fromLexeme :: RealFloat a => (Bool, FloatLexeme) -> a -fromLexeme (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, printing as `show` does, -by `showLitChar`, & parsing as `read` does: unescaped, but for @\\@ & @'@; -by a named escape; or by its decimal, octal or hexadecimal code, or as a -control, @\\^@@ to @\\^_@. -} -charG :: RegGrammatical Char p => p Char Char -charG = terminal "'" >* orP - [ tokenClass (oneOf [' ' .. '~'] >&< notOneOf "\\'") - , unprinted >? tokenClass (notOneOf ("\\'" <> [' ' .. '~'])) - , terminal "\\" >* orP - [ escapesG - ( [('\'', "'"), ('\a', "a"), ('\b', "b"), ('\f', "f"), ('\n', "n")] - <> [('\r', "r"), ('\t', "t"), ('\v', "v"), ('\\', "\\"), ('"', "\"")] - <> zip ['\NUL' ..] asciiNames <> [(' ', "SP"), ('\DEL', "DEL")] ) - , prism' toEnum (\c -> if c > '\DEL' then Just (fromEnum c) else Nothing) - >? boundedNumeral 10 maxCode - , unprinted . codeOf >? eitherOf "o" "O" >* boundedNumeral 8 maxCode - , unprinted . codeOf >? eitherOf "x" "X" >* boundedNumeral 16 maxCode - , unprinted . iso (\c -> toEnum (fromEnum c + 64)) (\c -> toEnum (fromEnum c - 64)) - >? terminal "^" >* tokenClass (oneOf ['@' .. '_']) - ] - ] *< terminal "'" - where - codeOf = prism' toEnum (Just . fromEnum) - -- codes up to `maxBound`, as `read` reads them - maxCode = fromEnum (maxBound :: Char) - 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" ] - --- Escapes by fixed strings, as a trie, which is LL(1), maximally munched, --- like @\\SO@ & @\\SOH@, each character printing by its first string. -escapesG :: RegGrammatical Char p => [(Char, String)] -> p Char Char -escapesG escapes = orP $ - [only c >? oneP | (c, "") <- take 1 [e | e@(_, "") <- escapes]] - <> [ terminal [first] >* escapesG [(c, rest) | (c, x : rest) <- escapes, x == first] - | first <- nub [x | (_, x : _) <- escapes] ] - {- | A digit in a base, from 2 to 36, by its value: @0-9@, then letters, printing in lowercase, & parsing either case. @@ -328,55 +82,3 @@ numeral base = iso digitsOf (foldl' (\n d -> n * base + d) 0) >~ someP (digit ba digitsOf n | n < base = [n] | otherwise = let (q, r) = n `quotRem` base in digitsOf q <> [r] - -{- 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. -} -boundedNumeral :: forall n p. (Integral n, RegGrammatical Char p) => n -> n -> p n n -boundedNumeral base bound - = (unprinted >? 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 eitherOf [c] [toUpper c] else terminal [c] 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..d5f8b58c --- /dev/null +++ b/distributors-grammar/src/Control/Lens/Grammar/Prec.hs @@ -0,0 +1,408 @@ +{- | +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 (..) + , parensP + -- * Precedence + , Precedence (..) + , readsPrecG + , showsPrecG + ) where + +import Control.Applicative +import Control.Lens +import Control.Lens.Diopter (skippedMany) +import Control.Lens.Grammar.BackusNaur +import Control.Lens.Grammar.Class +import Control.Lens.Grammar.Symbol +import Control.Lens.Grammar.Token +import Control.Lens.PartialIso +import Control.Lens.Prismoid ((>?*)) +import Data.Char (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 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 + +{- | `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, 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. -} + stepP :: p a b -> p a b + {- | In the context 0, within brackets, as + `Text.ParserCombinators.ReadPrec.reset` does. -} + resetP :: p a b -> p a b + {- | By the context's precedence. -} + precedenceP :: (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. -} +parensP :: PrecGrammatical p => p a b -> p a b +parensP p = optional' + where + optional' = spacesG >* (p >|< mandatory) + mandatory = terminal "(" >* resetP optional' *< spacesG *< terminal ")" + +{- | 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)) + timesP lo hi (Precedence x) = Precedence (timesP 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 IsString (p a b) => IsString (Precedence p a b) where + fromString = Precedence . const . fromString +instance (Grammatical Char p, forall x y. (x ~ (), y ~ ()) => IsString (p x y)) + => PrecGrammatical (Precedence p) where + precP n (Precedence x) = Precedence (\d -> if d <= n then x n else falseP) + stepP (Precedence x) = Precedence (x . (+ 1)) + resetP (Precedence x) = Precedence (const (x 0)) + precedenceP k = Precedence (\d -> runPrecedence (k d) d) + +{- | Read at a precedence, as `readsPrec` does. -} +readsPrecG :: forall a. PrecGrammar a => Int -> ReadS a +readsPrecG d = parseP (runPrecedence precGrammar 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 (runPrecedence precGrammar 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 = parensP charG +instance PrecGrammar Natural where precGrammar = parensP naturalG +instance PrecGrammar Integer where + precGrammar = parensP (precedenceP (\d -> signed >~ negativeAt d >*< magnitudeG)) +instance PrecGrammar Double where precGrammar = parensP (precedenceP floatingAt) +instance PrecGrammar Float where precGrammar = parensP (precedenceP floatingAt) +instance PrecGrammar Int where precGrammar = integralG +instance PrecGrammar Int8 where precGrammar = integralG +instance PrecGrammar Int16 where precGrammar = integralG +instance PrecGrammar Int32 where precGrammar = integralG +instance PrecGrammar Int64 where precGrammar = integralG +instance PrecGrammar Word where precGrammar = integralG +instance PrecGrammar Word8 where precGrammar = integralG +instance PrecGrammar Word16 where precGrammar = integralG +instance PrecGrammar Word32 where precGrammar = integralG +instance PrecGrammar Word64 where precGrammar = integralG + +-- Sized integers read as `Integer`s, wrapping out of range, as `read` does. +integralG :: (Integral a, PrecGrammatical p) => p a a +integralG = iso toInteger fromInteger >~ precGrammar @Integer + +-- A minus, printing bare up to precedence 6, & parsing bare at any. +negativeAt :: RegGrammatical Char p => Int -> p Bool Bool +negativeAt d + | d <= 6 = negativeG + | otherwise = orP + [ only False >? oneP + , only True . unprinted >? terminal "-" >* spacesG ] + +-- A prism which never matches, so that its alternative parses, but never prints. +unprinted :: Prism' a a +unprinted = prism' id (const Nothing) + +-- One of two terminals, printing the first, & parsing either. +eitherOf :: RegGrammatical Char p => String -> String -> p () () +eitherOf printed parsed = terminal printed >|< (unprinted >? terminal parsed) + +-- A minus, a lexeme of its own, as whether a number is negative. +negativeG :: RegGrammatical Char p => p Bool Bool +negativeG = iso (\b -> if b then Just () else Nothing) isJust + >~ optionalP (terminal "-" >* spacesG) + +-- Whitespace, by `Data.Char.isSpace`, which `read` skips before each +-- lexeme & after all, & which never prints. +spacesG :: RegGrammatical Char p => p () () +spacesG = skippedMany >?* tokenClass (oneOf "\t\n\v\f\r" >|< asIn Space) + +-- Signed, by an improper iso, where @-0@ parses too. +signed :: (Num a, Ord a) => Iso' a (Bool, a) +signed = 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. +magnitudeG :: RegGrammatical Char p => p Integer Integer +magnitudeG = (unprinted >? try (terminal "0" >* basedG)) >|< numeral 10 + +basedG :: RegGrammatical Char p => p Integer Integer +basedG = orP + [ eitherOf "b" "B" >* numeral 2 + , eitherOf "o" "O" >* numeral 8 + , eitherOf "x" "X" >* numeral 16 + ] + +-- Natural numbers, & negative zero, as `read` reads integers & keeps +-- those which aren't negative. +naturalG :: RegGrammatical Char p => p Natural Natural +naturalG = (iso toInteger fromInteger >~ magnitudeG) + >|< (unprinted . only 0 >? terminal "-" >* spacesG >* zerosG) + where + zerosG = terminal "0" >* orP + [ skippedMany >?* terminal "0" + , orP (map terminal ["b", "B", "o", "O", "x", "X"]) + >* terminal "0" >* (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. -} +floatingAt :: (RealFloat a, RegGrammatical Char p) => Int -> p a a +floatingAt d = iso toLexeme fromLexeme >~ negativeAt d >*< orP + [ only NotANumber >? terminal "NaN" + , only Infinite >? terminal "Infinity" + , unprinted . _Based >? try (terminal "0" >* basedG) + , _Decimal >? someP (digit 10) + >*< optionalP (terminal "." >* someP (digit 10)) + >*< optionalP (eitherOf "e" "E" >* (signed >~ exponentSignG >*< numeral 10)) + ] + where + exponentSignG = orP + [ only True >? terminal "-" + , only False . unprinted >? terminal "+" + , only False >? oneP + ] + +toLexeme :: RealFloat a => a -> (Bool, FloatLexeme) +toLexeme 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 + +fromLexeme :: RealFloat a => (Bool, FloatLexeme) -> a +fromLexeme (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, printing as `show` does, +by `showLitChar`, & parsing as `read` does: unescaped, but for @\\@ & @'@; +by a named escape; or by its decimal, octal or hexadecimal code, or as a +control, @\\^@@ to @\\^_@. -} +charG :: RegGrammatical Char p => p Char Char +charG = terminal "'" >* orP + [ tokenClass (oneOf [' ' .. '~'] >&< notOneOf "\\'") + , unprinted >? tokenClass (notOneOf ("\\'" <> [' ' .. '~'])) + , terminal "\\" >* orP + [ escapesG + ( [('\'', "'"), ('\a', "a"), ('\b', "b"), ('\f', "f"), ('\n', "n")] + <> [('\r', "r"), ('\t', "t"), ('\v', "v"), ('\\', "\\"), ('"', "\"")] + <> zip ['\NUL' ..] asciiNames <> [(' ', "SP"), ('\DEL', "DEL")] ) + , prism' toEnum (\c -> if c > '\DEL' then Just (fromEnum c) else Nothing) + >? boundedNumeral 10 maxCode + , unprinted . codeOf >? eitherOf "o" "O" >* boundedNumeral 8 maxCode + , unprinted . codeOf >? eitherOf "x" "X" >* boundedNumeral 16 maxCode + , unprinted . iso (\c -> toEnum (fromEnum c + 64)) (\c -> toEnum (fromEnum c - 64)) + >? terminal "^" >* tokenClass (oneOf ['@' .. '_']) + ] + ] *< terminal "'" + where + codeOf = prism' toEnum (Just . fromEnum) + -- codes up to `maxBound`, as `read` reads them + maxCode = fromEnum (maxBound :: Char) + 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" ] + +-- Escapes by fixed strings, as a trie, which is LL(1), maximally munched, +-- like @\\SO@ & @\\SOH@, each character printing by its first string. +escapesG :: RegGrammatical Char p => [(Char, String)] -> p Char Char +escapesG escapes = orP $ + [only c >? oneP | (c, "") <- take 1 [e | e@(_, "") <- escapes]] + <> [ terminal [first] >* escapesG [(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. -} +boundedNumeral :: forall n p. (Integral n, RegGrammatical Char p) => n -> n -> p n n +boundedNumeral base bound + = (unprinted >? 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 eitherOf [c] [toUpper c] else terminal [c] diff --git a/distributors-grammar/test/Properties/Base.hs b/distributors-grammar/test/Properties/Base.hs index e6d71ba3..915d1dc4 100644 --- a/distributors-grammar/test/Properties/Base.hs +++ b/distributors-grammar/test/Properties/Base.hs @@ -3,42 +3,33 @@ 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.Maybe (maybeToList) +import Data.Foldable (for_) +import Data.List (sort) import Data.Word (Word8, Word16, Word32, Word64) -import Numeric (showIntAtBase) +import Numeric (showHex, showIntAtBase, showOct) import Numeric.Natural (Natural) import Test.Hspec import Test.Hspec.QuickCheck (modifyMaxSuccess, prop) import Test.QuickCheck -import Text.Read (readMaybe) -{- | Equivalence with a type's `Read` & `Show` instances' lexemes: printing -is `show`, & parsing is `readMaybe`, for strings of its values, by its -lexical variants, & mutated, so that strings which `read` rejects are -tried too, but for those with whitespace or parentheses around them, -which `read` accepts around any value, a matter of precedence. Each new -instance runs it. +{- | 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. (CtxGrammar Char a, Read a, Show a) + :: forall a. (PrecGrammar a, Read a, Show a) => String -> Gen a -> (a -> Gen String) -> Spec -readShowEquivalence name values variants = describe name $ do - prop "prints as show does" $ forAll values $ \a -> - printed a === Just (show a) - modifyMaxSuccess (const 1000) $ prop "parses as read does" $ - forAll (values >>= variants >>= mutated) $ \str -> lexical str ==> - map show (parsed @a str) === map show (maybeToList (readMaybe @a str)) +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 - lexical str = not (any outer (take 1 str <> take 1 (reverse str))) - outer c = isSpace c || c `elem` "()" - --- | Parse all of a string, if it parses. -parsed :: forall a. CtxGrammar Char a => String -> [a] -parsed str = [a | (a, "") <- parseG @a str] - --- | Print a value, if it prints. -printed :: CtxGrammar Char a => a -> Maybe String -printed a = ($ "") <$> printG a + complete parses = sort [show a | (a, rest) <- parses, all isSpace rest] -- | Whitespace, `isSpace` & not, often none. spaces :: Gen String @@ -47,6 +38,20 @@ spaces = frequency , (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)] @@ -97,9 +102,9 @@ character c = do [ pure (drop 1 (init (show c))) ] <> [pure [c] | c `notElem` "\\'"] <> [ pure ("\\" <> show (ord c)) - , pure ("\\o" <> showIntAtBase 8 intToDigit (ord c) "") - , pure ("\\x" <> showIntAtBase 16 intToDigit (ord c) "") - , pure ("\\X" <> map toUpper (showIntAtBase 16 intToDigit (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 <> "'") @@ -134,8 +139,3 @@ baseProperties = describe "equivalent to Read & Show" $ do readShowEquivalence "Word64" (arbitrary :: Gen Word64) integral readShowEquivalence "Double" (floats :: Gen Double) floating readShowEquivalence "Float" (floats :: Gen Float) floating - describe "statically LL(1), by ll1Conflicts" $ do - it "Char" $ ll1Conflicts (regbnfG @Char Char) `shouldBe` [] - it "Natural" $ ll1Conflicts (regbnfG @Char Natural) `shouldBe` [] - it "Integer" $ ll1Conflicts (regbnfG @Char Integer) `shouldBe` [] - it "Double" $ ll1Conflicts (regbnfG @Char Double) `shouldBe` [] From 4e17d280ef303c944c20891363f17057b1ae247a Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sat, 14 Nov 2026 06:44:55 -0800 Subject: [PATCH 34/51] PrecGrammar lists & strings: precListGrammar, listG, precG; parensG Strings, as Read & Show's string literals, with empty escapes & gaps, & numeric escapes & \SOH maximally munched; whitespace skipped at one place before each lexeme, as read's greedy skipSpaces does. Co-Authored-By: Claude Opus 5.5 --- distributors-grammar/CHANGELOG.md | 12 +- .../src/Control/Lens/Grammar/Prec.hs | 172 ++++++++++++++---- distributors-grammar/test/Examples/SExpr.hs | 4 +- distributors-grammar/test/Properties/Base.hs | 30 ++- 4 files changed, 170 insertions(+), 48 deletions(-) diff --git a/distributors-grammar/CHANGELOG.md b/distributors-grammar/CHANGELOG.md index 2681a42b..fbcacdce 100644 --- a/distributors-grammar/CHANGELOG.md +++ b/distributors-grammar/CHANGELOG.md @@ -29,17 +29,19 @@ - `Control.Lens.Grammar.Prec`: Haskell types' grammars, by precedence, equivalent to their stock `Read` & `Show` instances. `PrecGrammar` types, run by `PrecGrammatical` interpreters, with `precP`, `stepP`, `resetP` & - `precedenceP`, as `ReadPrec`'s `prec`, `step` & `reset`, & `parensP`, as - `GHC.Read.parens` & `showParen`; `Precedence`, an interpreter over any - `Grammatical` one, run by `readsPrecG` & `showsPrecG`. Instances for + `precedenceP`, as `ReadPrec`'s `prec`, `step` & `reset`, `parensG`, as + `GHC.Read.parens` & `showParen`, & `listG`, 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; `String`, a list of characters, has neither. + `readsPrec`, at each precedence. Haskell types have no `Grammar` instances. - `Predicate`s are `Tokenized` & `TokenAlgebra`s, as predicates are; & `ReadPrec` runs grammars as `ReadP` does, `Tokenized`, a `TokenAlgebra`, `TerminalSymbol`, `Ruled`, `BackusNaurForm` & `Tried`. diff --git a/distributors-grammar/src/Control/Lens/Grammar/Prec.hs b/distributors-grammar/src/Control/Lens/Grammar/Prec.hs index d5f8b58c..2e59b966 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/Prec.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/Prec.hs @@ -17,9 +17,11 @@ module Control.Lens.Grammar.Prec ( -- * PrecGrammar PrecGrammar (..) , PrecGrammatical (..) - , parensP + , parensG + , listG -- * Precedence , Precedence (..) + , precG , readsPrecG , showsPrecG ) where @@ -52,6 +54,10 @@ import Numeric.Natural (Natural) & `Show` instances, `readsPrec` & `showsPrec`. -} class PrecGrammar a where precGrammar :: PrecGrammatical p => p a a + {- | Lists of the type, as `readListPrec` & `showList`, in brackets, by + `listG`, by default, & strings, for `Char`. -} + precListGrammar :: PrecGrammatical p => p [a] [a] + precListGrammar = listG precGrammar {- | `Grammatical` interpreters of precedence, as `Text.ParserCombinators.ReadPrec` has, where a grammar runs in a @@ -72,11 +78,26 @@ class (Grammatical Char p, forall x y. (x ~ (), y ~ ()) => IsString (p x y)) {- | Within any parentheses, after whitespace, as `GHC.Read.parens` reads, & within parentheses where it doesn't print bare, as `showParen` shows. -} -parensP :: PrecGrammatical p => p a b -> p a b -parensP p = optional' - where - optional' = spacesG >* (p >|< mandatory) - mandatory = terminal "(" >* resetP optional' *< spacesG *< terminal ")" +parensG :: PrecGrammatical p => p a b -> p a b +parensG p = spacesG >* parenthesized p + +{- Bare, or within parentheses, without leading whitespace, so that no two +places skip the same whitespace, which `read` skips once, greedily. -} +parenthesized :: PrecGrammatical p => p a b -> p a b +parenthesized p = p >|< terminal "(" >* resetP (parensG p) *< spacesG *< 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. -} +listG :: PrecGrammatical p => p a a -> p [a] [a] +listG = parensG . bracketsG + +-- Items in brackets, separated by commas, after whitespace, at precedence 0. +bracketsG :: PrecGrammatical p => p a a -> p [a] [a] +bracketsG x = terminal "[" >* orP + [ _Empty >? oneP + , _Cons >? resetP x >*< manyP (spacesG >* terminal "," >* resetP x) + ] *< spacesG *< terminal "]" {- | A grammar in a precedence context, a `PrecGrammatical` interpreter of any `Grammatical` one, each of whose structures it lifts pointwise. -} @@ -131,22 +152,27 @@ instance Tried (p a b) => Tried (Precedence p a b) where 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 IsString (p a b) => IsString (Precedence p a b) where - fromString = Precedence . const . fromString -instance (Grammatical Char p, forall x y. (x ~ (), y ~ ()) => IsString (p x y)) - => PrecGrammatical (Precedence p) where +instance (a ~ (), b ~ (), TerminalSymbol Char (p () ())) + => IsString (Precedence p a b) where + fromString = Precedence . const . terminal +instance Grammatical Char p => PrecGrammatical (Precedence p) where precP n (Precedence x) = Precedence (\d -> if d <= n then x n else falseP) stepP (Precedence x) = Precedence (x . (+ 1)) resetP (Precedence x) = Precedence (const (x 0)) precedenceP 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) => 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 (runPrecedence precGrammar d :: Parsor String [] a 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 (runPrecedence precGrammar d :: Printor String Maybe a a) +showsPrecG d = printP (precG d :: Printor String Maybe a a) -- Base types -- @@ -155,12 +181,17 @@ 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 = parensP charG -instance PrecGrammar Natural where precGrammar = parensP naturalG +instance PrecGrammar Char where + precGrammar = parensG charG + -- strings, or brackets, as `read` reads, & strings, as `show` shows + precListGrammar = parensG (stringG >|< parenthesized (bracketsG precGrammar)) +instance PrecGrammar a => PrecGrammar [a] where + precGrammar = precListGrammar +instance PrecGrammar Natural where precGrammar = parensG naturalG instance PrecGrammar Integer where - precGrammar = parensP (precedenceP (\d -> signed >~ negativeAt d >*< magnitudeG)) -instance PrecGrammar Double where precGrammar = parensP (precedenceP floatingAt) -instance PrecGrammar Float where precGrammar = parensP (precedenceP floatingAt) + precGrammar = parensG (precedenceP (\d -> signed >~ negativeAt d >*< magnitudeG)) +instance PrecGrammar Double where precGrammar = parensG (precedenceP floatingAt) +instance PrecGrammar Float where precGrammar = parensG (precedenceP floatingAt) instance PrecGrammar Int where precGrammar = integralG instance PrecGrammar Int8 where precGrammar = integralG instance PrecGrammar Int16 where precGrammar = integralG @@ -316,37 +347,98 @@ fromLexeme (negative, lexeme) = (if negative then negate else id) value (_, []) -> Nothing (zeros, _) -> Just (negate (length zeros)) -{- A character's literal, between single quotes, printing as `show` does, -by `showLitChar`, & parsing as `read` does: unescaped, but for @\\@ & @'@; -by a named escape; or by its decimal, octal or hexadecimal code, or as a -control, @\\^@@ to @\\^_@. -} +-- A character's literal, between single quotes. charG :: RegGrammatical Char p => p Char Char -charG = terminal "'" >* orP - [ tokenClass (oneOf [' ' .. '~'] >&< notOneOf "\\'") - , unprinted >? tokenClass (notOneOf ("\\'" <> [' ' .. '~'])) - , terminal "\\" >* orP - [ escapesG - ( [('\'', "'"), ('\a', "a"), ('\b', "b"), ('\f', "f"), ('\n', "n")] - <> [('\r', "r"), ('\t', "t"), ('\v', "v"), ('\\', "\\"), ('"', "\"")] - <> zip ['\NUL' ..] asciiNames <> [(' ', "SP"), ('\DEL', "DEL")] ) - , prism' toEnum (\c -> if c > '\DEL' then Just (fromEnum c) else Nothing) - >? boundedNumeral 10 maxCode - , unprinted . codeOf >? eitherOf "o" "O" >* boundedNumeral 8 maxCode - , unprinted . codeOf >? eitherOf "x" "X" >* boundedNumeral 16 maxCode - , unprinted . iso (\c -> toEnum (fromEnum c + 64)) (\c -> toEnum (fromEnum c - 64)) - >? terminal "^" >* tokenClass (oneOf ['@' .. '_']) - ] - ] *< terminal "'" +charG = terminal "'" >* litCharG '\'' *< 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 @\\^_@. -} +litCharG :: RegGrammatical Char p => Char -> p Char Char +litCharG quote = rawG [quote] >|< terminal "\\" >* orP + [fixedEscG True, decimalEscG, octalEscG, hexEscG, controlEscG] + +-- Unescaped, but for @\\@ & some others, printing only printable ASCII. +rawG :: RegGrammatical Char p => String -> p Char Char +rawG excluded = tokenClass (oneOf [' ' .. '~'] >&< notOneOf ('\\' : excluded)) + >|< unprinted >? tokenClass (notOneOf ('\\' : excluded <> [' ' .. '~'])) + +-- Named escapes, with @SO@ or not. +fixedEscG :: RegGrammatical Char p => Bool -> p Char Char +fixedEscG withSO = escapesG $ + [('\'', "'"), ('\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 - codeOf = prism' toEnum (Just . fromEnum) - -- codes up to `maxBound`, as `read` reads them - maxCode = fromEnum (maxBound :: Char) 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. +decimalEscG, octalEscG, hexEscG, controlEscG :: RegGrammatical Char p => p Char Char +decimalEscG = prism' toEnum (\c -> if c > '\DEL' then Just (fromEnum c) else Nothing) + >? boundedNumeral 10 (fromEnum (maxBound :: Char)) +octalEscG = unprinted . prism' toEnum (Just . fromEnum) + >? eitherOf "o" "O" >* boundedNumeral 8 (fromEnum (maxBound :: Char)) +hexEscG = unprinted . prism' toEnum (Just . fromEnum) + >? eitherOf "x" "X" >* boundedNumeral 16 (fromEnum (maxBound :: Char)) +controlEscG = unprinted . 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. -} +stringG :: forall p. RegGrammatical Char p => p String String +stringG = 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 >? rawG ('"' : continuing)) free + , itemThen (_StrChar >? terminal "\\" >* orP [fixedEscG False, controlEscG]) free + , itemThen (_StrChar . only '\SO' >? terminal "\\SO") afterSO + , itemThen (_StrChar >? terminal "\\" >* decimalEscG) afterDecimal + , itemThen (_StrChar >? terminal "\\" >* octalEscG) afterOctal + , itemThen (_StrChar >? terminal "\\" >* hexEscG) 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 "\\&" >|< unprinted >? terminal "\\" + >* dimap (const ' ') (const ()) (tokenClass (oneOf "\t\n\v\f\r" >|< asIn Space)) + >* spacesG *< 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' && isDec c') || (c == '\SO' && c' == 'H') + isDec c' = '0' <= c' && c' <= '9' + -- Escapes by fixed strings, as a trie, which is LL(1), maximally munched, -- like @\\SO@ & @\\SOH@, each character printing by its first string. escapesG :: RegGrammatical Char p => [(Char, String)] -> p Char Char diff --git a/distributors-grammar/test/Examples/SExpr.hs b/distributors-grammar/test/Examples/SExpr.hs index e0d4a4e3..f6262454 100644 --- a/distributors-grammar/test/Examples/SExpr.hs +++ b/distributors-grammar/test/Examples/SExpr.hs @@ -20,7 +20,7 @@ makePrisms ''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 +28,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 diff --git a/distributors-grammar/test/Properties/Base.hs b/distributors-grammar/test/Properties/Base.hs index 915d1dc4..0f461adb 100644 --- a/distributors-grammar/test/Properties/Base.hs +++ b/distributors-grammar/test/Properties/Base.hs @@ -4,7 +4,8 @@ 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 Data.List (sort) +import Control.Monad ((>=>)) +import Data.List (intercalate, sort) import Data.Word (Word8, Word16, Word32, Word64) import Numeric (showHex, showIntAtBase, showOct) import Numeric.Natural (Natural) @@ -108,6 +109,30 @@ character c = do <> [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) + characters :: Gen Char characters = frequency [ (3, arbitraryASCIIChar) @@ -139,3 +164,6 @@ baseProperties = describe "equivalent to Read & Show" $ do 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)) From 6d47225c61d46ed0cdbd73a3ef09bd2c18a10d4c Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sat, 14 Nov 2026 06:48:30 -0800 Subject: [PATCH 35/51] Prec names: precList, precStep, precReset, precWith, precParens Co-Authored-By: Claude Opus 5.5 --- distributors-grammar/CHANGELOG.md | 6 +-- .../src/Control/Lens/Grammar/Prec.hs | 44 +++++++++---------- 2 files changed, 25 insertions(+), 25 deletions(-) diff --git a/distributors-grammar/CHANGELOG.md b/distributors-grammar/CHANGELOG.md index fbcacdce..3a1e613f 100644 --- a/distributors-grammar/CHANGELOG.md +++ b/distributors-grammar/CHANGELOG.md @@ -28,9 +28,9 @@ 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`, `stepP`, `resetP` & - `precedenceP`, as `ReadPrec`'s `prec`, `step` & `reset`, `parensG`, as - `GHC.Read.parens` & `showParen`, & `listG`, as `GHC.Read.list` & + 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 diff --git a/distributors-grammar/src/Control/Lens/Grammar/Prec.hs b/distributors-grammar/src/Control/Lens/Grammar/Prec.hs index 2e59b966..eea15f92 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/Prec.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/Prec.hs @@ -17,8 +17,8 @@ module Control.Lens.Grammar.Prec ( -- * PrecGrammar PrecGrammar (..) , PrecGrammatical (..) - , parensG - , listG + , precParens + , precList -- * Precedence , Precedence (..) , precG @@ -55,9 +55,9 @@ import Numeric.Natural (Natural) class PrecGrammar a where precGrammar :: PrecGrammatical p => p a a {- | Lists of the type, as `readListPrec` & `showList`, in brackets, by - `listG`, by default, & strings, for `Char`. -} + `precList`, by default, & strings, for `Char`. -} precListGrammar :: PrecGrammatical p => p [a] [a] - precListGrammar = listG precGrammar + precListGrammar = precList precGrammar {- | `Grammatical` interpreters of precedence, as `Text.ParserCombinators.ReadPrec` has, where a grammar runs in a @@ -69,34 +69,34 @@ class (Grammatical Char p, forall x y. (x ~ (), y ~ ()) => IsString (p x y)) precP :: Int -> p a b -> p a b {- | In a context one higher, for arguments, as `Text.ParserCombinators.ReadPrec.step` does. -} - stepP :: p a b -> p a b + precStep :: p a b -> p a b {- | In the context 0, within brackets, as `Text.ParserCombinators.ReadPrec.reset` does. -} - resetP :: p a b -> p a b + precReset :: p a b -> p a b {- | By the context's precedence. -} - precedenceP :: (Int -> p a b) -> p a b + 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. -} -parensG :: PrecGrammatical p => p a b -> p a b -parensG p = spacesG >* parenthesized p +precParens :: PrecGrammatical p => p a b -> p a b +precParens p = spacesG >* parenthesized p {- Bare, or within parentheses, without leading whitespace, so that no two places skip the same whitespace, which `read` skips once, greedily. -} parenthesized :: PrecGrammatical p => p a b -> p a b -parenthesized p = p >|< terminal "(" >* resetP (parensG p) *< spacesG *< terminal ")" +parenthesized p = p >|< terminal "(" >* precReset (precParens p) *< spacesG *< 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. -} -listG :: PrecGrammatical p => p a a -> p [a] [a] -listG = parensG . bracketsG +precList :: PrecGrammatical p => p a a -> p [a] [a] +precList = precParens . bracketsG -- Items in brackets, separated by commas, after whitespace, at precedence 0. bracketsG :: PrecGrammatical p => p a a -> p [a] [a] bracketsG x = terminal "[" >* orP [ _Empty >? oneP - , _Cons >? resetP x >*< manyP (spacesG >* terminal "," >* resetP x) + , _Cons >? precReset x >*< manyP (spacesG >* terminal "," >* precReset x) ] *< spacesG *< terminal "]" {- | A grammar in a precedence context, a `PrecGrammatical` interpreter of @@ -157,9 +157,9 @@ instance (a ~ (), b ~ (), TerminalSymbol Char (p () ())) fromString = Precedence . const . terminal instance Grammatical Char p => PrecGrammatical (Precedence p) where precP n (Precedence x) = Precedence (\d -> if d <= n then x n else falseP) - stepP (Precedence x) = Precedence (x . (+ 1)) - resetP (Precedence x) = Precedence (const (x 0)) - precedenceP k = Precedence (\d -> runPrecedence (k d) d) + 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. -} @@ -182,16 +182,16 @@ negative numbers, which `showsPrec` parenthesizes above 6, & `read` accepts bare at any precedence. -} instance PrecGrammar Char where - precGrammar = parensG charG + precGrammar = precParens charG -- strings, or brackets, as `read` reads, & strings, as `show` shows - precListGrammar = parensG (stringG >|< parenthesized (bracketsG precGrammar)) + precListGrammar = precParens (stringG >|< parenthesized (bracketsG precGrammar)) instance PrecGrammar a => PrecGrammar [a] where precGrammar = precListGrammar -instance PrecGrammar Natural where precGrammar = parensG naturalG +instance PrecGrammar Natural where precGrammar = precParens naturalG instance PrecGrammar Integer where - precGrammar = parensG (precedenceP (\d -> signed >~ negativeAt d >*< magnitudeG)) -instance PrecGrammar Double where precGrammar = parensG (precedenceP floatingAt) -instance PrecGrammar Float where precGrammar = parensG (precedenceP floatingAt) + precGrammar = precParens (precWith (\d -> signed >~ negativeAt d >*< magnitudeG)) +instance PrecGrammar Double where precGrammar = precParens (precWith floatingAt) +instance PrecGrammar Float where precGrammar = precParens (precWith floatingAt) instance PrecGrammar Int where precGrammar = integralG instance PrecGrammar Int8 where precGrammar = integralG instance PrecGrammar Int16 where precGrammar = integralG From bac6f9a3e1356b411cb90864e836774cfc3725ee Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sat, 14 Nov 2026 07:04:03 -0800 Subject: [PATCH 36/51] PrecGrammar by Generics, as derived Read & Show; Lookahead; tuples & () Constructors nullary, prefix, record & infix, by fixity; lexemes munched maximally & whitespace skipped greedily by notAhead, as read's lexer does. Property tested against showsPrec & readsPrec at each precedence, for Bool, Ordering, (), Maybe, Either, tuples & a type of each shape. Co-Authored-By: Claude Opus 5.5 --- distributors-grammar/CHANGELOG.md | 9 + .../src/Control/Lens/Grammar/Prec.hs | 266 +++++++++++++++--- distributors-grammar/test/Properties/Base.hs | 49 ++++ 3 files changed, 292 insertions(+), 32 deletions(-) diff --git a/distributors-grammar/CHANGELOG.md b/distributors-grammar/CHANGELOG.md index 3a1e613f..57198e0f 100644 --- a/distributors-grammar/CHANGELOG.md +++ b/distributors-grammar/CHANGELOG.md @@ -42,6 +42,15 @@ 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. `Lookahead`, negative lookahead + by `notAhead`, which `PrecGrammatical` requires, 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`. diff --git a/distributors-grammar/src/Control/Lens/Grammar/Prec.hs b/distributors-grammar/src/Control/Lens/Grammar/Prec.hs index eea15f92..ffe88381 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/Prec.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/Prec.hs @@ -19,6 +19,8 @@ module Control.Lens.Grammar.Prec , PrecGrammatical (..) , precParens , precList + -- * Lookahead + , Lookahead (..) -- * Precedence , Precedence (..) , precG @@ -47,6 +49,9 @@ 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) @@ -54,6 +59,9 @@ import Numeric.Natural (Natural) & `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] @@ -62,7 +70,9 @@ class PrecGrammar a where {- | `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, forall x y. (x ~ (), y ~ ()) => IsString (p x y)) +class + ( Grammatical Char p, Lookahead 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. -} @@ -99,6 +109,20 @@ bracketsG x = terminal "[" >* orP , _Cons >? precReset x >*< manyP (spacesG >* terminal "," >* precReset x) ] *< spacesG *< terminal "]" +{- | Negative lookahead, as `read`'s lexer munches lexemes maximally: what +`notAhead` a grammar parses mustn't follow, which consumes nothing, & +prints nothing. -} +class Lookahead p where + notAhead :: p () () -> p () () +instance (Foldable f, Alternative f) => Lookahead (Parsor s f) where + notAhead (Parsor q) = Parsor $ \mode s -> case mode of + Nothing | not (null (q Nothing s)) -> empty + _ -> pure ((), s) +instance Applicative f => Lookahead (Printor s f) where + notAhead _ = Printor (\_ -> pure ((), id)) +instance Lookahead p => Lookahead (Precedence p) where + notAhead (Precedence q) = Precedence (notAhead . q) + {- | 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} @@ -155,7 +179,7 @@ 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 => PrecGrammatical (Precedence p) where +instance (Grammatical Char p, Lookahead 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)) @@ -163,7 +187,7 @@ instance Grammatical Char p => PrecGrammatical (Precedence p) where {- | A type's `PrecGrammar` at a precedence, at any `Grammatical` interpreter which parses or prints. -} -precG :: forall a p. (PrecGrammar a, Grammatical Char p) => Int -> p a a +precG :: forall a p. (PrecGrammar a, Grammatical Char p, Lookahead p) => Int -> p a a precG = runPrecedence precGrammar {- | Read at a precedence, as `readsPrec` does. -} @@ -187,6 +211,120 @@ instance PrecGrammar Char where precListGrammar = precParens (stringG >|< parenthesized (bracketsG 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 "(" >* spacesG *< terminal ")") +instance (PrecGrammar a, PrecGrammar b) => PrecGrammar (a, b) where + precGrammar = tupled (itemG >*< commaG >* itemG) +instance (PrecGrammar a, PrecGrammar b, PrecGrammar c) => PrecGrammar (a, b, c) where + precGrammar = tupled $ iso (\(a, b, c) -> (a, (b, c))) (\(a, (b, c)) -> (a, b, c)) + >~ itemG >*< commaG >* itemG >*< commaG >* itemG +instance (PrecGrammar a, PrecGrammar b, PrecGrammar c, PrecGrammar d) + => PrecGrammar (a, b, c, d) where + precGrammar = tupled $ iso + (\(a, b, c, d) -> (a, (b, (c, d)))) (\(a, (b, (c, d))) -> (a, b, c, d)) + >~ itemG >*< commaG >* itemG >*< commaG >* itemG >*< commaG >* itemG +instance (PrecGrammar a, PrecGrammar b, PrecGrammar c, PrecGrammar d, PrecGrammar e) + => PrecGrammar (a, b, c, d, e) where + precGrammar = tupled $ iso + (\(a, b, c, d, e) -> (a, (b, (c, (d, e))))) + (\(a, (b, (c, (d, e)))) -> (a, b, c, d, e)) + >~ itemG >*< commaG >* itemG >*< commaG >* itemG >*< commaG >* itemG + >*< commaG >* itemG + +-- A tuple, within parentheses, its items at precedence 0, as `read`'s +-- @wrap_tup@ reads & `show` shows. +tupled :: PrecGrammatical p => p a a -> p a a +tupled items' = precParens (terminal "(" >* items' *< spacesG *< terminal ")") + +itemG :: (PrecGrammar a, PrecGrammatical p) => p a a +itemG = precReset precGrammar + +commaG :: PrecGrammatical p => p () () +commaG = spacesG >* 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 (operatorG name))) + Prefix + | conIsRecord con -> precWith $ \d -> + let body = nameG name >* spacedG >* terminal "{" >* spacesG + >* gPrecFields RecordFields *< spacesG *< terminal "}" + in if d <= 10 then body else if d == 11 then unprinted >? body else falseP + | gArity (Proxy @f) == 0 -> nameG name >* gPrecFields PrefixFields + | otherwise -> precP 10 (nameG 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 >*< spacesG >* terminal "," >* spacedG >* 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 -> nameG field >* spacedG >* symbolG "=" >* spaceG >* precReset precGrammar + BareField -> precStep precGrammar + _ -> spaceG >* precStep precGrammar + where + field = selName (undefined :: M1 S s (K1 R a) ()) + gArity _ = 1 + +-- A name, an identifier, or a symbol within parentheses. +nameG :: PrecGrammatical p => String -> p () () +nameG name + | symbolic name = + terminal "(" >* spacesG >* symbolG name *< spacesG *< terminal ")" + | otherwise = identG name + +-- An infix operator, a symbol, or an identifier within backquotes. +operatorG :: PrecGrammatical p => String -> p () () +operatorG name + | symbolic name = spacedG >* symbolG name >* spaceG + | otherwise = spacedG >* terminal "`" >* spacesG >* identG name + *< spacesG *< terminal "`" >* spaceG + +symbolic :: String -> Bool +symbolic = \case + c : _ -> c == ':' || tokenClass symbolClass c + [] -> False instance PrecGrammar Natural where precGrammar = precParens naturalG instance PrecGrammar Integer where precGrammar = precParens (precWith (\d -> signed >~ negativeAt d >*< magnitudeG)) @@ -208,7 +346,7 @@ integralG :: (Integral a, PrecGrammatical p) => p a a integralG = iso toInteger fromInteger >~ precGrammar @Integer -- A minus, printing bare up to precedence 6, & parsing bare at any. -negativeAt :: RegGrammatical Char p => Int -> p Bool Bool +negativeAt :: (RegGrammatical Char p, Lookahead p) => Int -> p Bool Bool negativeAt d | d <= 6 = negativeG | otherwise = orP @@ -220,18 +358,60 @@ unprinted :: Prism' a a unprinted = prism' id (const Nothing) -- One of two terminals, printing the first, & parsing either. -eitherOf :: RegGrammatical Char p => String -> String -> p () () +eitherOf :: (RegGrammatical Char p, Lookahead p) => String -> String -> p () () eitherOf printed parsed = terminal printed >|< (unprinted >? terminal parsed) -- A minus, a lexeme of its own, as whether a number is negative. -negativeG :: RegGrammatical Char p => p Bool Bool +negativeG :: (RegGrammatical Char p, Lookahead p) => p Bool Bool negativeG = iso (\b -> if b then Just () else Nothing) isJust >~ optionalP (terminal "-" >* spacesG) -- Whitespace, by `Data.Char.isSpace`, which `read` skips before each -- lexeme & after all, & which never prints. -spacesG :: RegGrammatical Char p => p () () -spacesG = skippedMany >?* tokenClass (oneOf "\t\n\v\f\r" >|< asIn Space) +spacesG :: (RegGrammatical Char p, Lookahead p) => p () () +spacesG = (skippedMany >?* tokenClass spaceClass) *< notAhead (tokenG spaceClass) + +-- Whitespace, by `Data.Char.isSpace`. +spaceClass :: TokenClass Char +spaceClass = oneOf "\t\n\v\f\r" >|< asIn Space + +-- A token of a class, as unit, for lookahead. +tokenG :: (RegGrammatical Char p, Lookahead p) => TokenClass Char -> p () () +tokenG cls = dimap (const ' ') (const ()) (tokenClass cls) + +-- The digits of a base, in either case. +digitClass :: Int -> TokenClass Char +digitClass base = oneOf (concat + [ [c, toUpper c] | c <- take base (['0' .. '9'] <> ['a' .. 'z']) ]) + +-- Identifiers' & symbols' characters, which `read`'s lexer munches. +idfClass, symbolClass :: TokenClass Char +idfClass = anyP asIn + [ UppercaseLetter, LowercaseLetter, TitlecaseLetter, ModifierLetter + , OtherLetter, DecimalNumber, LetterNumber, OtherNumber ] + >|< oneOf "_'" +symbolClass = notOneOf ",;()[]{}`" >&< orP + [ anyP asIn [MathSymbol, CurrencySymbol, ModifierSymbol, OtherSymbol, DashPunctuation] + , asIn OtherPunctuation >&< notOneOf "'\"" + , asIn ConnectorPunctuation >&< notOneOf "_" ] + +-- An identifier, & a symbol, munched maximally. +identG, symbolG :: (RegGrammatical Char p, Lookahead p) => String -> p () () +identG name = terminal name *< notAhead (tokenG idfClass) +symbolG name = terminal name *< notAhead (tokenG symbolClass) + +-- 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. +spaceG :: (RegGrammatical Char p, Lookahead p) => p () () +spaceG = orP + [ terminal " " + , unprinted >? tokenG (spaceClass >&< notOneOf " ") + , unprinted >? notAhead (tokenG spaceClass) ] + +-- A space, printing one, & parsing any whitespace. +spacedG :: (RegGrammatical Char p, Lookahead p) => p () () +spacedG = spaceG >* spacesG -- Signed, by an improper iso, where @-0@ parses too. signed :: (Num a, Ord a) => Iso' a (Bool, a) @@ -242,27 +422,42 @@ signed = iso -- 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. -magnitudeG :: RegGrammatical Char p => p Integer Integer -magnitudeG = (unprinted >? try (terminal "0" >* basedG)) >|< numeral 10 +magnitudeG :: (RegGrammatical Char p, Lookahead p) => p Integer Integer +magnitudeG = (unprinted >? try (terminal "0" >* basedG)) + >|< numeral 10 *< notAhead (tokenG (digitClass 10)) *< decimalEndG + +-- Where a decimal integer ends: not before a fraction, nor an exponent. +decimalEndG :: (RegGrammatical Char p, Lookahead p) => p () () +decimalEndG = notAhead (terminal "." >* tokenG (digitClass 10)) + *< notAhead (orP (map terminal ["e", "E"]) + >* orP [terminal "-", terminal "+", oneP] >* tokenG (digitClass 10)) -basedG :: RegGrammatical Char p => p Integer Integer +basedG :: forall p. (RegGrammatical Char p, Lookahead p) => p Integer Integer basedG = orP - [ eitherOf "b" "B" >* numeral 2 - , eitherOf "o" "O" >* numeral 8 - , eitherOf "x" "X" >* numeral 16 + [ eitherOf "b" "B" >* munched 2 + , eitherOf "o" "O" >* munched 8 + , eitherOf "x" "X" >* munched 16 ] + where + munched :: Int -> p Integer Integer + munched base = numeral (toInteger base) *< notAhead (tokenG (digitClass base)) -- Natural numbers, & negative zero, as `read` reads integers & keeps -- those which aren't negative. -naturalG :: RegGrammatical Char p => p Natural Natural +naturalG :: (RegGrammatical Char p, Lookahead p) => p Natural Natural naturalG = (iso toInteger fromInteger >~ magnitudeG) >|< (unprinted . only 0 >? terminal "-" >* spacesG >* zerosG) where zerosG = terminal "0" >* orP - [ skippedMany >?* terminal "0" - , orP (map terminal ["b", "B", "o", "O", "x", "X"]) - >* terminal "0" >* (skippedMany >?* terminal "0") + [ zeros *< notAhead (tokenG (digitClass 10)) *< decimalEndG + , orP (map terminal ["b", "B"]) >* terminal "0" >* zeros + *< notAhead (tokenG (digitClass 2)) + , orP (map terminal ["o", "O"]) >* terminal "0" >* zeros + *< notAhead (tokenG (digitClass 8)) + , orP (map terminal ["x", "X"]) >* terminal "0" >* zeros + *< notAhead (tokenG (digitClass 16)) ] + zeros = skippedMany >?* terminal "0" -- A floating point number's lexeme, without its sign. data FloatLexeme @@ -287,16 +482,23 @@ _Based = prism' Based $ \case {- 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. -} -floatingAt :: (RealFloat a, RegGrammatical Char p) => Int -> p a a +floatingAt :: (RealFloat a, RegGrammatical Char p, Lookahead p) => Int -> p a a floatingAt d = iso toLexeme fromLexeme >~ negativeAt d >*< orP - [ only NotANumber >? terminal "NaN" - , only Infinite >? terminal "Infinity" + [ only NotANumber >? identG "NaN" + , only Infinite >? identG "Infinity" , unprinted . _Based >? try (terminal "0" >* basedG) - , _Decimal >? someP (digit 10) - >*< optionalP (terminal "." >* someP (digit 10)) - >*< optionalP (eitherOf "e" "E" >* (signed >~ exponentSignG >*< numeral 10)) + , _Decimal >? digitsG + >*< orP + [ _Just >? terminal "." >* digitsG + , _Nothing >? notAhead (terminal "." >* tokenG (digitClass 10)) ] + >*< orP + [ _Just >? eitherOf "e" "E" >* (signed >~ exponentSignG >*< numeral 10 + *< notAhead (tokenG (digitClass 10))) + , _Nothing >? notAhead (orP (map terminal ["e", "E"]) + >* orP [terminal "-", terminal "+", oneP] >* tokenG (digitClass 10)) ] ] where + digitsG = someP (digit 10) *< notAhead (tokenG (digitClass 10)) exponentSignG = orP [ only True >? terminal "-" , only False . unprinted >? terminal "+" @@ -348,24 +550,24 @@ fromLexeme (negative, lexeme) = (if negative then negate else id) value (zeros, _) -> Just (negate (length zeros)) -- A character's literal, between single quotes. -charG :: RegGrammatical Char p => p Char Char +charG :: (RegGrammatical Char p, Lookahead p) => p Char Char charG = terminal "'" >* litCharG '\'' *< 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 @\\^_@. -} -litCharG :: RegGrammatical Char p => Char -> p Char Char +litCharG :: (RegGrammatical Char p, Lookahead p) => Char -> p Char Char litCharG quote = rawG [quote] >|< terminal "\\" >* orP [fixedEscG True, decimalEscG, octalEscG, hexEscG, controlEscG] -- Unescaped, but for @\\@ & some others, printing only printable ASCII. -rawG :: RegGrammatical Char p => String -> p Char Char +rawG :: (RegGrammatical Char p, Lookahead p) => String -> p Char Char rawG excluded = tokenClass (oneOf [' ' .. '~'] >&< notOneOf ('\\' : excluded)) >|< unprinted >? tokenClass (notOneOf ('\\' : excluded <> [' ' .. '~'])) -- Named escapes, with @SO@ or not. -fixedEscG :: RegGrammatical Char p => Bool -> p Char Char +fixedEscG :: (RegGrammatical Char p, Lookahead p) => Bool -> p Char Char fixedEscG withSO = escapesG $ [('\'', "'"), ('\a', "a"), ('\b', "b"), ('\f', "f"), ('\n', "n")] <> [('\r', "r"), ('\t', "t"), ('\v', "v"), ('\\', "\\"), ('"', "\"")] @@ -379,7 +581,7 @@ fixedEscG withSO = escapesG $ , "CAN", "EM", "SUB", "ESC", "FS", "GS", "RS", "US" ] -- Codes up to `maxBound`, decimal, printing above @\\DEL@, octal & hexadecimal. -decimalEscG, octalEscG, hexEscG, controlEscG :: RegGrammatical Char p => p Char Char +decimalEscG, octalEscG, hexEscG, controlEscG :: (RegGrammatical Char p, Lookahead p) => p Char Char decimalEscG = prism' toEnum (\c -> if c > '\DEL' then Just (fromEnum c) else Nothing) >? boundedNumeral 10 (fromEnum (maxBound :: Char)) octalEscG = unprinted . prism' toEnum (Just . fromEnum) @@ -404,7 +606,7 @@ 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. -} -stringG :: forall p. RegGrammatical Char p => p String String +stringG :: forall p. (RegGrammatical Char p, Lookahead p) => p String String stringG = iso items (\xs -> [c | StrChar c <- xs]) >~ terminal "\"" >* free *< terminal "\"" where @@ -441,7 +643,7 @@ stringG = iso items (\xs -> [c | StrChar c <- xs]) -- Escapes by fixed strings, as a trie, which is LL(1), maximally munched, -- like @\\SO@ & @\\SOH@, each character printing by its first string. -escapesG :: RegGrammatical Char p => [(Char, String)] -> p Char Char +escapesG :: (RegGrammatical Char p, Lookahead p) => [(Char, String)] -> p Char Char escapesG escapes = orP $ [only c >? oneP | (c, "") <- take 1 [e | e@(_, "") <- escapes]] <> [ terminal [first] >* escapesG [(c, rest) | (c, x : rest) <- escapes, x == first] @@ -450,7 +652,7 @@ escapesG escapes = orP $ {- 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. -} -boundedNumeral :: forall n p. (Integral n, RegGrammatical Char p) => n -> n -> p n n +boundedNumeral :: forall n p. (Integral n, RegGrammatical Char p, Lookahead p) => n -> n -> p n n boundedNumeral base bound = (unprinted >? try (terminal "0" >* zerosG >* positiveG)) >|< (only 0 >? terminal "0" >* zerosG) diff --git a/distributors-grammar/test/Properties/Base.hs b/distributors-grammar/test/Properties/Base.hs index 0f461adb..3a22d552 100644 --- a/distributors-grammar/test/Properties/Base.hs +++ b/distributors-grammar/test/Properties/Base.hs @@ -7,6 +7,7 @@ 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 @@ -133,6 +134,42 @@ string s = oneof [pure (show s), literal, listing character s] , 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) @@ -167,3 +204,15 @@ baseProperties = describe "equivalent to Read & Show" $ do 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 From 9d6fef5f448c2ff6c7ed608d5885ab7750a13214 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sat, 14 Nov 2026 07:09:04 -0800 Subject: [PATCH 37/51] notFollowedByToken, a Lookahead method; used for lexemes' maximal munch Co-Authored-By: Claude Opus 5.5 --- distributors-grammar/CHANGELOG.md | 3 +- .../src/Control/Lens/Grammar/Prec.hs | 51 +++++++++++-------- 2 files changed, 32 insertions(+), 22 deletions(-) diff --git a/distributors-grammar/CHANGELOG.md b/distributors-grammar/CHANGELOG.md index 57198e0f..fbfdca40 100644 --- a/distributors-grammar/CHANGELOG.md +++ b/distributors-grammar/CHANGELOG.md @@ -48,7 +48,8 @@ fields, infix constructors, symbolic & backquoted, at their fixities, & symbolic constructors in prefix. Instances for `Bool`, `Ordering`, `Maybe` & `Either`, by it, & for `()` & tuples. `Lookahead`, negative lookahead - by `notAhead`, which `PrecGrammatical` requires, so that identifiers, + by `notAhead`, & not followed by a token of a class, by + `notFollowedByToken`, which `PrecGrammatical` requires, 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; & diff --git a/distributors-grammar/src/Control/Lens/Grammar/Prec.hs b/distributors-grammar/src/Control/Lens/Grammar/Prec.hs index ffe88381..00ba3735 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/Prec.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/Prec.hs @@ -114,14 +114,22 @@ bracketsG x = terminal "[" >* orP prints nothing. -} class Lookahead p where notAhead :: p () () -> p () () -instance (Foldable f, Alternative f) => Lookahead (Parsor s f) where - notAhead (Parsor q) = Parsor $ \mode s -> case mode of - Nothing | not (null (q Nothing s)) -> empty - _ -> pure ((), s) + {- | Not followed by a token of a class. -} + notFollowedByToken :: TokenClass Char -> p () () +instance (Foldable f, Alternative f, Cons s s Char Char) + => Lookahead (Parsor s f) where + notAhead (Parsor q) = Parsor $ \mode s -> case mode of + Nothing | not (null (q Nothing s)) -> empty + _ -> pure ((), s) + notFollowedByToken cls = Parsor $ \mode s -> case (mode, uncons s) of + (Nothing, Just (c, _)) | tokenClass cls c -> empty + _ -> pure ((), s) instance Applicative f => Lookahead (Printor s f) where notAhead _ = Printor (\_ -> pure ((), id)) + notFollowedByToken _ = Printor (\_ -> pure ((), id)) instance Lookahead p => Lookahead (Precedence p) where notAhead (Precedence q) = Precedence (notAhead . q) + notFollowedByToken cls = Precedence (const (notFollowedByToken cls)) {- | A grammar in a precedence context, a `PrecGrammatical` interpreter of any `Grammatical` one, each of whose structures it lifts pointwise. -} @@ -358,7 +366,7 @@ unprinted :: Prism' a a unprinted = prism' id (const Nothing) -- One of two terminals, printing the first, & parsing either. -eitherOf :: (RegGrammatical Char p, Lookahead p) => String -> String -> p () () +eitherOf :: RegGrammatical Char p => String -> String -> p () () eitherOf printed parsed = terminal printed >|< (unprinted >? terminal parsed) -- A minus, a lexeme of its own, as whether a number is negative. @@ -369,14 +377,14 @@ negativeG = iso (\b -> if b then Just () else Nothing) isJust -- Whitespace, by `Data.Char.isSpace`, which `read` skips before each -- lexeme & after all, & which never prints. spacesG :: (RegGrammatical Char p, Lookahead p) => p () () -spacesG = (skippedMany >?* tokenClass spaceClass) *< notAhead (tokenG spaceClass) +spacesG = (skippedMany >?* tokenClass spaceClass) *< notFollowedByToken spaceClass -- Whitespace, by `Data.Char.isSpace`. spaceClass :: TokenClass Char spaceClass = oneOf "\t\n\v\f\r" >|< asIn Space -- A token of a class, as unit, for lookahead. -tokenG :: (RegGrammatical Char p, Lookahead p) => TokenClass Char -> p () () +tokenG :: RegGrammatical Char p => TokenClass Char -> p () () tokenG cls = dimap (const ' ') (const ()) (tokenClass cls) -- The digits of a base, in either case. @@ -397,8 +405,8 @@ symbolClass = notOneOf ",;()[]{}`" >&< orP -- An identifier, & a symbol, munched maximally. identG, symbolG :: (RegGrammatical Char p, Lookahead p) => String -> p () () -identG name = terminal name *< notAhead (tokenG idfClass) -symbolG name = terminal name *< notAhead (tokenG symbolClass) +identG name = terminal name *< notFollowedByToken idfClass +symbolG name = terminal name *< notFollowedByToken symbolClass -- A space, where `show` separates lexemes, printing one, & parsing one -- whitespace character, or none where none follows, the rest of it @@ -407,7 +415,7 @@ spaceG :: (RegGrammatical Char p, Lookahead p) => p () () spaceG = orP [ terminal " " , unprinted >? tokenG (spaceClass >&< notOneOf " ") - , unprinted >? notAhead (tokenG spaceClass) ] + , unprinted >? notFollowedByToken spaceClass ] -- A space, printing one, & parsing any whitespace. spacedG :: (RegGrammatical Char p, Lookahead p) => p () () @@ -424,7 +432,7 @@ signed = iso -- case, parsed & tried first, as `read`'s lexer does. magnitudeG :: (RegGrammatical Char p, Lookahead p) => p Integer Integer magnitudeG = (unprinted >? try (terminal "0" >* basedG)) - >|< numeral 10 *< notAhead (tokenG (digitClass 10)) *< decimalEndG + >|< numeral 10 *< notFollowedByToken (digitClass 10) *< decimalEndG -- Where a decimal integer ends: not before a fraction, nor an exponent. decimalEndG :: (RegGrammatical Char p, Lookahead p) => p () () @@ -440,7 +448,7 @@ basedG = orP ] where munched :: Int -> p Integer Integer - munched base = numeral (toInteger base) *< notAhead (tokenG (digitClass base)) + munched base = numeral (toInteger base) *< notFollowedByToken (digitClass base) -- Natural numbers, & negative zero, as `read` reads integers & keeps -- those which aren't negative. @@ -449,13 +457,13 @@ naturalG = (iso toInteger fromInteger >~ magnitudeG) >|< (unprinted . only 0 >? terminal "-" >* spacesG >* zerosG) where zerosG = terminal "0" >* orP - [ zeros *< notAhead (tokenG (digitClass 10)) *< decimalEndG + [ zeros *< notFollowedByToken (digitClass 10) *< decimalEndG , orP (map terminal ["b", "B"]) >* terminal "0" >* zeros - *< notAhead (tokenG (digitClass 2)) + *< notFollowedByToken (digitClass 2) , orP (map terminal ["o", "O"]) >* terminal "0" >* zeros - *< notAhead (tokenG (digitClass 8)) + *< notFollowedByToken (digitClass 8) , orP (map terminal ["x", "X"]) >* terminal "0" >* zeros - *< notAhead (tokenG (digitClass 16)) + *< notFollowedByToken (digitClass 16) ] zeros = skippedMany >?* terminal "0" @@ -493,12 +501,12 @@ floatingAt d = iso toLexeme fromLexeme >~ negativeAt d >*< orP , _Nothing >? notAhead (terminal "." >* tokenG (digitClass 10)) ] >*< orP [ _Just >? eitherOf "e" "E" >* (signed >~ exponentSignG >*< numeral 10 - *< notAhead (tokenG (digitClass 10))) + *< notFollowedByToken (digitClass 10)) , _Nothing >? notAhead (orP (map terminal ["e", "E"]) >* orP [terminal "-", terminal "+", oneP] >* tokenG (digitClass 10)) ] ] where - digitsG = someP (digit 10) *< notAhead (tokenG (digitClass 10)) + digitsG = someP (digit 10) *< notFollowedByToken (digitClass 10) exponentSignG = orP [ only True >? terminal "-" , only False . unprinted >? terminal "+" @@ -562,7 +570,7 @@ litCharG quote = rawG [quote] >|< terminal "\\" >* orP [fixedEscG True, decimalEscG, octalEscG, hexEscG, controlEscG] -- Unescaped, but for @\\@ & some others, printing only printable ASCII. -rawG :: (RegGrammatical Char p, Lookahead p) => String -> p Char Char +rawG :: RegGrammatical Char p => String -> p Char Char rawG excluded = tokenClass (oneOf [' ' .. '~'] >&< notOneOf ('\\' : excluded)) >|< unprinted >? tokenClass (notOneOf ('\\' : excluded <> [' ' .. '~'])) @@ -581,13 +589,14 @@ fixedEscG withSO = escapesG $ , "CAN", "EM", "SUB", "ESC", "FS", "GS", "RS", "US" ] -- Codes up to `maxBound`, decimal, printing above @\\DEL@, octal & hexadecimal. -decimalEscG, octalEscG, hexEscG, controlEscG :: (RegGrammatical Char p, Lookahead p) => p Char Char +decimalEscG, octalEscG, hexEscG :: RegGrammatical Char p => p Char Char decimalEscG = prism' toEnum (\c -> if c > '\DEL' then Just (fromEnum c) else Nothing) >? boundedNumeral 10 (fromEnum (maxBound :: Char)) octalEscG = unprinted . prism' toEnum (Just . fromEnum) >? eitherOf "o" "O" >* boundedNumeral 8 (fromEnum (maxBound :: Char)) hexEscG = unprinted . prism' toEnum (Just . fromEnum) >? eitherOf "x" "X" >* boundedNumeral 16 (fromEnum (maxBound :: Char)) +controlEscG :: RegGrammatical Char p => p Char Char controlEscG = unprinted . iso (\c -> toEnum (fromEnum c + 64)) (\c -> toEnum (fromEnum c - 64)) >? terminal "^" >* tokenClass (oneOf ['@' .. '_']) @@ -652,7 +661,7 @@ escapesG escapes = orP $ {- 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. -} -boundedNumeral :: forall n p. (Integral n, RegGrammatical Char p, Lookahead p) => n -> n -> p n n +boundedNumeral :: forall n p. (Integral n, RegGrammatical Char p) => n -> n -> p n n boundedNumeral base bound = (unprinted >? try (terminal "0" >* zerosG >* positiveG)) >|< (only 0 >? terminal "0" >* zerosG) From 096cc828cb9229b325c79288199b14fb1a5f3c79 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sat, 14 Nov 2026 07:10:41 -0800 Subject: [PATCH 38/51] Lookahead: a single notFollowedBy, of a string of token classes Co-Authored-By: Claude Opus 5.5 --- distributors-grammar/CHANGELOG.md | 7 +- .../src/Control/Lens/Grammar/Prec.hs | 72 ++++++++++--------- 2 files changed, 41 insertions(+), 38 deletions(-) diff --git a/distributors-grammar/CHANGELOG.md b/distributors-grammar/CHANGELOG.md index fbfdca40..b03dd624 100644 --- a/distributors-grammar/CHANGELOG.md +++ b/distributors-grammar/CHANGELOG.md @@ -48,10 +48,9 @@ fields, infix constructors, symbolic & backquoted, at their fixities, & symbolic constructors in prefix. Instances for `Bool`, `Ordering`, `Maybe` & `Either`, by it, & for `()` & tuples. `Lookahead`, negative lookahead - by `notAhead`, & not followed by a token of a class, by - `notFollowedByToken`, which `PrecGrammatical` requires, so that identifiers, - symbols & numbers are munched maximally, & whitespace skipped greedily, - as `read`'s lexer does. + by `notFollowedBy` a string of token classes, which `PrecGrammatical` + requires, 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`. diff --git a/distributors-grammar/src/Control/Lens/Grammar/Prec.hs b/distributors-grammar/src/Control/Lens/Grammar/Prec.hs index 00ba3735..dc56fef3 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/Prec.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/Prec.hs @@ -109,27 +109,25 @@ bracketsG x = terminal "[" >* orP , _Cons >? precReset x >*< manyP (spacesG >* terminal "," >* precReset x) ] *< spacesG *< terminal "]" -{- | Negative lookahead, as `read`'s lexer munches lexemes maximally: what -`notAhead` a grammar parses mustn't follow, which consumes nothing, & -prints nothing. -} +{- | Negative lookahead, as `read`'s lexer munches lexemes maximally. -} class Lookahead p where - notAhead :: p () () -> p () () - {- | Not followed by a token of a class. -} - notFollowedByToken :: TokenClass Char -> p () () -instance (Foldable f, Alternative f, Cons s s Char Char) + {- | Not followed by a string of tokens, one of each class in turn, + consuming nothing, & printing nothing. -} + notFollowedBy :: [TokenClass Char] -> p () () +instance (Applicative f, Alternative f, Cons s s Char Char) => Lookahead (Parsor s f) where - notAhead (Parsor q) = Parsor $ \mode s -> case mode of - Nothing | not (null (q Nothing s)) -> empty - _ -> pure ((), s) - notFollowedByToken cls = Parsor $ \mode s -> case (mode, uncons s) of - (Nothing, Just (c, _)) | tokenClass cls c -> empty + notFollowedBy classes = Parsor $ \mode s -> case mode of + Nothing | follows classes s -> empty _ -> pure ((), s) + where + follows [] _ = True + follows (cls : rest) str = case uncons str of + Just (c, str') -> tokenClass cls c && follows rest str' + Nothing -> False instance Applicative f => Lookahead (Printor s f) where - notAhead _ = Printor (\_ -> pure ((), id)) - notFollowedByToken _ = Printor (\_ -> pure ((), id)) + notFollowedBy _ = Printor (\_ -> pure ((), id)) instance Lookahead p => Lookahead (Precedence p) where - notAhead (Precedence q) = Precedence (notAhead . q) - notFollowedByToken cls = Precedence (const (notFollowedByToken cls)) + notFollowedBy = Precedence . const . notFollowedBy {- | A grammar in a precedence context, a `PrecGrammatical` interpreter of any `Grammatical` one, each of whose structures it lifts pointwise. -} @@ -377,7 +375,7 @@ negativeG = iso (\b -> if b then Just () else Nothing) isJust -- Whitespace, by `Data.Char.isSpace`, which `read` skips before each -- lexeme & after all, & which never prints. spacesG :: (RegGrammatical Char p, Lookahead p) => p () () -spacesG = (skippedMany >?* tokenClass spaceClass) *< notFollowedByToken spaceClass +spacesG = (skippedMany >?* tokenClass spaceClass) *< notFollowedBy [spaceClass] -- Whitespace, by `Data.Char.isSpace`. spaceClass :: TokenClass Char @@ -405,8 +403,8 @@ symbolClass = notOneOf ",;()[]{}`" >&< orP -- An identifier, & a symbol, munched maximally. identG, symbolG :: (RegGrammatical Char p, Lookahead p) => String -> p () () -identG name = terminal name *< notFollowedByToken idfClass -symbolG name = terminal name *< notFollowedByToken symbolClass +identG name = terminal name *< notFollowedBy [idfClass] +symbolG name = terminal name *< notFollowedBy [symbolClass] -- A space, where `show` separates lexemes, printing one, & parsing one -- whitespace character, or none where none follows, the rest of it @@ -415,7 +413,7 @@ spaceG :: (RegGrammatical Char p, Lookahead p) => p () () spaceG = orP [ terminal " " , unprinted >? tokenG (spaceClass >&< notOneOf " ") - , unprinted >? notFollowedByToken spaceClass ] + , unprinted >? notFollowedBy [spaceClass] ] -- A space, printing one, & parsing any whitespace. spacedG :: (RegGrammatical Char p, Lookahead p) => p () () @@ -432,13 +430,20 @@ signed = iso -- case, parsed & tried first, as `read`'s lexer does. magnitudeG :: (RegGrammatical Char p, Lookahead p) => p Integer Integer magnitudeG = (unprinted >? try (terminal "0" >* basedG)) - >|< numeral 10 *< notFollowedByToken (digitClass 10) *< decimalEndG + >|< numeral 10 *< decimalEndG -- Where a decimal integer ends: not before a fraction, nor an exponent. decimalEndG :: (RegGrammatical Char p, Lookahead p) => p () () -decimalEndG = notAhead (terminal "." >* tokenG (digitClass 10)) - *< notAhead (orP (map terminal ["e", "E"]) - >* orP [terminal "-", terminal "+", oneP] >* tokenG (digitClass 10)) +decimalEndG = notFollowedBy [digitClass 10] *< notFractionG *< notExponentG + +-- Not before a fraction. +notFractionG :: Lookahead p => p () () +notFractionG = notFollowedBy [oneOf ".", digitClass 10] + +-- Not before an exponent. +notExponentG :: (Monoidal p, Lookahead p) => p () () +notExponentG = notFollowedBy [oneOf "eE", digitClass 10] + *< notFollowedBy [oneOf "eE", oneOf "+-", digitClass 10] basedG :: forall p. (RegGrammatical Char p, Lookahead p) => p Integer Integer basedG = orP @@ -448,7 +453,7 @@ basedG = orP ] where munched :: Int -> p Integer Integer - munched base = numeral (toInteger base) *< notFollowedByToken (digitClass base) + munched base = numeral (toInteger base) *< notFollowedBy [(digitClass base)] -- Natural numbers, & negative zero, as `read` reads integers & keeps -- those which aren't negative. @@ -457,13 +462,13 @@ naturalG = (iso toInteger fromInteger >~ magnitudeG) >|< (unprinted . only 0 >? terminal "-" >* spacesG >* zerosG) where zerosG = terminal "0" >* orP - [ zeros *< notFollowedByToken (digitClass 10) *< decimalEndG + [ zeros *< decimalEndG , orP (map terminal ["b", "B"]) >* terminal "0" >* zeros - *< notFollowedByToken (digitClass 2) + *< notFollowedBy [(digitClass 2)] , orP (map terminal ["o", "O"]) >* terminal "0" >* zeros - *< notFollowedByToken (digitClass 8) + *< notFollowedBy [(digitClass 8)] , orP (map terminal ["x", "X"]) >* terminal "0" >* zeros - *< notFollowedByToken (digitClass 16) + *< notFollowedBy [(digitClass 16)] ] zeros = skippedMany >?* terminal "0" @@ -498,15 +503,14 @@ floatingAt d = iso toLexeme fromLexeme >~ negativeAt d >*< orP , _Decimal >? digitsG >*< orP [ _Just >? terminal "." >* digitsG - , _Nothing >? notAhead (terminal "." >* tokenG (digitClass 10)) ] + , _Nothing >? notFractionG ] >*< orP [ _Just >? eitherOf "e" "E" >* (signed >~ exponentSignG >*< numeral 10 - *< notFollowedByToken (digitClass 10)) - , _Nothing >? notAhead (orP (map terminal ["e", "E"]) - >* orP [terminal "-", terminal "+", oneP] >* tokenG (digitClass 10)) ] + *< notFollowedBy [(digitClass 10)]) + , _Nothing >? notExponentG ] ] where - digitsG = someP (digit 10) *< notFollowedByToken (digitClass 10) + digitsG = someP (digit 10) *< notFollowedBy [(digitClass 10)] exponentSignG = orP [ only True >? terminal "-" , only False . unprinted >? terminal "+" From a0fc4247e5cd3172eadfdf77f8f13680a3a7c7b1 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sat, 14 Nov 2026 07:20:13 -0800 Subject: [PATCH 39/51] Lookahead: notFollowedBy a RegEx; eof Co-Authored-By: Claude Opus 5.5 --- distributors-grammar/CHANGELOG.md | 2 +- .../src/Control/Lens/Grammar/Prec.hs | 86 +++++++++++++------ 2 files changed, 59 insertions(+), 29 deletions(-) diff --git a/distributors-grammar/CHANGELOG.md b/distributors-grammar/CHANGELOG.md index b03dd624..a2341c12 100644 --- a/distributors-grammar/CHANGELOG.md +++ b/distributors-grammar/CHANGELOG.md @@ -48,7 +48,7 @@ fields, infix constructors, symbolic & backquoted, at their fixities, & symbolic constructors in prefix. Instances for `Bool`, `Ordering`, `Maybe` & `Either`, by it, & for `()` & tuples. `Lookahead`, negative lookahead - by `notFollowedBy` a string of token classes, which `PrecGrammatical` + by `notFollowedBy` a `RegEx`, & `eof`, which `PrecGrammatical` requires, 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; & diff --git a/distributors-grammar/src/Control/Lens/Grammar/Prec.hs b/distributors-grammar/src/Control/Lens/Grammar/Prec.hs index dc56fef3..16dd8aff 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/Prec.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/Prec.hs @@ -21,6 +21,7 @@ module Control.Lens.Grammar.Prec , precList -- * Lookahead , Lookahead (..) + , eof -- * Precedence , Precedence (..) , precG @@ -29,10 +30,12 @@ module Control.Lens.Grammar.Prec ) 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 @@ -111,24 +114,48 @@ bracketsG x = terminal "[" >* orP {- | Negative lookahead, as `read`'s lexer munches lexemes maximally. -} class Lookahead p where - {- | Not followed by a string of tokens, one of each class in turn, - consuming nothing, & printing nothing. -} - notFollowedBy :: [TokenClass Char] -> p () () -instance (Applicative f, Alternative f, Cons s s Char Char) - => Lookahead (Parsor s f) where - notFollowedBy classes = Parsor $ \mode s -> case mode of - Nothing | follows classes s -> empty - _ -> pure ((), s) - where - follows [] _ = True - follows (cls : rest) str = case uncons str of - Just (c, str') -> tokenClass cls c && follows rest str' - Nothing -> False + {- | 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) => Lookahead (Parsor s f) where + notFollowedBy rex = Parsor $ \mode s -> case mode of + Nothing | not (null (prefixes rex (0, s))) -> empty + _ -> pure ((), s) instance Applicative f => Lookahead (Printor s f) where notFollowedBy _ = Printor (\_ -> pure ((), id)) instance Lookahead p => Lookahead (Precedence p) where notFollowedBy = Precedence . const . notFollowedBy +{- | At the end of input, not followed by any token. -} +eof :: Lookahead p => p () () +eof = notFollowedBy anyToken + +{- The rests of a string after each of its prefixes a pattern matches, +counting tokens, so that repetitions of empty matches end. -} +prefixes :: Cons s s Char Char => RegEx Char -> (Int, s) -> [(Int, s)] +prefixes = \case + SeqEmpty -> pure + Sequence x y zs -> foldr (\rex k -> prefixes rex >=> k) pure (x : y : zs) + NonTerminal _ -> const [] + KleeneStar x -> star x + KleeneOpt x -> \pos -> pos : prefixes x pos + KleenePlus x -> prefixes x >=> star x + KleeneTimes lo hi x -> foldr (>=>) pure (replicate lo (prefixes x)) + >=> maybe (star x) (upTo x . subtract lo) 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)) + where + one cls (n, str) = case uncons str of + Just (c, str') | tokenClass cls c -> [(n + 1, str')] + _ -> [] + star x pos = pos : + [pos'' | pos' <- prefixes x pos, fst pos' > fst pos, pos'' <- star x pos'] + upTo x m pos + | m <= 0 = [pos] + | otherwise = pos : (prefixes x pos >>= upTo x (m - 1)) + {- | 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} @@ -375,7 +402,8 @@ negativeG = iso (\b -> if b then Just () else Nothing) isJust -- Whitespace, by `Data.Char.isSpace`, which `read` skips before each -- lexeme & after all, & which never prints. spacesG :: (RegGrammatical Char p, Lookahead p) => p () () -spacesG = (skippedMany >?* tokenClass spaceClass) *< notFollowedBy [spaceClass] +spacesG = (skippedMany >?* tokenClass spaceClass) + *< notFollowedBy (tokenClass spaceClass) -- Whitespace, by `Data.Char.isSpace`. spaceClass :: TokenClass Char @@ -403,8 +431,8 @@ symbolClass = notOneOf ",;()[]{}`" >&< orP -- An identifier, & a symbol, munched maximally. identG, symbolG :: (RegGrammatical Char p, Lookahead p) => String -> p () () -identG name = terminal name *< notFollowedBy [idfClass] -symbolG name = terminal name *< notFollowedBy [symbolClass] +identG name = terminal name *< notFollowedBy (tokenClass idfClass) +symbolG name = terminal name *< notFollowedBy (tokenClass symbolClass) -- A space, where `show` separates lexemes, printing one, & parsing one -- whitespace character, or none where none follows, the rest of it @@ -413,7 +441,7 @@ spaceG :: (RegGrammatical Char p, Lookahead p) => p () () spaceG = orP [ terminal " " , unprinted >? tokenG (spaceClass >&< notOneOf " ") - , unprinted >? notFollowedBy [spaceClass] ] + , unprinted >? notFollowedBy (tokenClass spaceClass) ] -- A space, printing one, & parsing any whitespace. spacedG :: (RegGrammatical Char p, Lookahead p) => p () () @@ -434,16 +462,17 @@ magnitudeG = (unprinted >? try (terminal "0" >* basedG)) -- Where a decimal integer ends: not before a fraction, nor an exponent. decimalEndG :: (RegGrammatical Char p, Lookahead p) => p () () -decimalEndG = notFollowedBy [digitClass 10] *< notFractionG *< notExponentG +decimalEndG = notFollowedBy (tokenClass (digitClass 10)) + *< notFractionG *< notExponentG -- Not before a fraction. notFractionG :: Lookahead p => p () () -notFractionG = notFollowedBy [oneOf ".", digitClass 10] +notFractionG = notFollowedBy (terminal "." <> tokenClass (digitClass 10)) -- Not before an exponent. -notExponentG :: (Monoidal p, Lookahead p) => p () () -notExponentG = notFollowedBy [oneOf "eE", digitClass 10] - *< notFollowedBy [oneOf "eE", oneOf "+-", digitClass 10] +notExponentG :: Lookahead p => p () () +notExponentG = notFollowedBy + (oneOf "eE" <> optK (oneOf "+-") <> tokenClass (digitClass 10)) basedG :: forall p. (RegGrammatical Char p, Lookahead p) => p Integer Integer basedG = orP @@ -453,7 +482,8 @@ basedG = orP ] where munched :: Int -> p Integer Integer - munched base = numeral (toInteger base) *< notFollowedBy [(digitClass base)] + munched base = numeral (toInteger base) + *< notFollowedBy (tokenClass (digitClass base)) -- Natural numbers, & negative zero, as `read` reads integers & keeps -- those which aren't negative. @@ -464,11 +494,11 @@ naturalG = (iso toInteger fromInteger >~ magnitudeG) zerosG = terminal "0" >* orP [ zeros *< decimalEndG , orP (map terminal ["b", "B"]) >* terminal "0" >* zeros - *< notFollowedBy [(digitClass 2)] + *< notFollowedBy (tokenClass (digitClass 2)) , orP (map terminal ["o", "O"]) >* terminal "0" >* zeros - *< notFollowedBy [(digitClass 8)] + *< notFollowedBy (tokenClass (digitClass 8)) , orP (map terminal ["x", "X"]) >* terminal "0" >* zeros - *< notFollowedBy [(digitClass 16)] + *< notFollowedBy (tokenClass (digitClass 16)) ] zeros = skippedMany >?* terminal "0" @@ -506,11 +536,11 @@ floatingAt d = iso toLexeme fromLexeme >~ negativeAt d >*< orP , _Nothing >? notFractionG ] >*< orP [ _Just >? eitherOf "e" "E" >* (signed >~ exponentSignG >*< numeral 10 - *< notFollowedBy [(digitClass 10)]) + *< notFollowedBy (tokenClass (digitClass 10))) , _Nothing >? notExponentG ] ] where - digitsG = someP (digit 10) *< notFollowedBy [(digitClass 10)] + digitsG = someP (digit 10) *< notFollowedBy (tokenClass (digitClass 10)) exponentSignG = orP [ only True >? terminal "-" , only False . unprinted >? terminal "+" From fa37ad25fa0855162abae7e1f4989e0875a1af78 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sat, 14 Nov 2026 07:25:40 -0800 Subject: [PATCH 40/51] Prec: precMunch, precMunch1, precSkipSpaces, precEof; prec* names throughout Co-Authored-By: Claude Opus 5.5 --- distributors-grammar/CHANGELOG.md | 7 +- .../src/Control/Lens/Grammar/Prec.hs | 405 +++++++++--------- 2 files changed, 215 insertions(+), 197 deletions(-) diff --git a/distributors-grammar/CHANGELOG.md b/distributors-grammar/CHANGELOG.md index a2341c12..0f60f09f 100644 --- a/distributors-grammar/CHANGELOG.md +++ b/distributors-grammar/CHANGELOG.md @@ -48,9 +48,10 @@ fields, infix constructors, symbolic & backquoted, at their fixities, & symbolic constructors in prefix. Instances for `Bool`, `Ordering`, `Maybe` & `Either`, by it, & for `()` & tuples. `Lookahead`, negative lookahead - by `notFollowedBy` a `RegEx`, & `eof`, which `PrecGrammatical` - requires, so that identifiers, symbols & numbers are munched - maximally, & whitespace skipped greedily, as `read`'s lexer does. + by `precNotFollowedBy` a `RegEx`, which `PrecGrammatical` requires, & + `precEof`, `precMunch`, `precMunch1` & `precSkipSpaces`, 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`. diff --git a/distributors-grammar/src/Control/Lens/Grammar/Prec.hs b/distributors-grammar/src/Control/Lens/Grammar/Prec.hs index 16dd8aff..52535547 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/Prec.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/Prec.hs @@ -21,7 +21,10 @@ module Control.Lens.Grammar.Prec , precList -- * Lookahead , Lookahead (..) - , eof + , precEof + , precMunch + , precMunch1 + , precSkipSpaces -- * Precedence , Precedence (..) , precG @@ -92,58 +95,78 @@ class {- | 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 = spacesG >* parenthesized p +precParens p = precSkipSpaces >* precParenthesized p {- Bare, or within parentheses, without leading whitespace, so that no two places skip the same whitespace, which `read` skips once, greedily. -} -parenthesized :: PrecGrammatical p => p a b -> p a b -parenthesized p = p >|< terminal "(" >* precReset (precParens p) *< spacesG *< terminal ")" +precParenthesized :: PrecGrammatical p => p a b -> p a b +precParenthesized p = p >|< terminal "(" >* precReset (precParens p) *< precSkipSpaces *< 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 . bracketsG +precList = precParens . precBrackets -- Items in brackets, separated by commas, after whitespace, at precedence 0. -bracketsG :: PrecGrammatical p => p a a -> p [a] [a] -bracketsG x = terminal "[" >* orP +precBrackets :: PrecGrammatical p => p a a -> p [a] [a] +precBrackets x = terminal "[" >* orP [ _Empty >? oneP - , _Cons >? precReset x >*< manyP (spacesG >* terminal "," >* precReset x) - ] *< spacesG *< terminal "]" + , _Cons >? precReset x >*< manyP (precSkipSpaces >* terminal "," >* precReset x) + ] *< precSkipSpaces *< terminal "]" {- | Negative lookahead, as `read`'s lexer munches lexemes maximally. -} class Lookahead p where {- | Not followed by a string a pattern matches, consuming nothing, & printing nothing; nonterminals match nothing. -} - notFollowedBy :: RegEx Char -> p () () + precNotFollowedBy :: RegEx Char -> p () () instance (Alternative f, Cons s s Char Char) => Lookahead (Parsor s f) where - notFollowedBy rex = Parsor $ \mode s -> case mode of - Nothing | not (null (prefixes rex (0, s))) -> empty + precNotFollowedBy rex = Parsor $ \mode s -> case mode of + Nothing | not (null (precPrefixes rex (0, s))) -> empty _ -> pure ((), s) instance Applicative f => Lookahead (Printor s f) where - notFollowedBy _ = Printor (\_ -> pure ((), id)) + precNotFollowedBy _ = Printor (\_ -> pure ((), id)) instance Lookahead p => Lookahead (Precedence p) where - notFollowedBy = Precedence . const . notFollowedBy + precNotFollowedBy = Precedence . const . precNotFollowedBy {- | At the end of input, not followed by any token. -} -eof :: Lookahead p => p () () -eof = notFollowedBy anyToken +precEof :: Lookahead p => p () () +precEof = precNotFollowedBy anyToken + +{- | Tokens of a class, as many as follow, as +`Text.ParserCombinators.ReadP.munch` parses, & printing them. -} +precMunch + :: (RegGrammatical Char p, Lookahead p) + => TokenClass Char -> p String String +precMunch cls = manyP (tokenClass cls) *< precNotFollowedBy (tokenClass cls) + +{- | Tokens of a class, one or more, as many as follow, as +`Text.ParserCombinators.ReadP.munch1` parses, & printing them. -} +precMunch1 + :: (RegGrammatical Char p, Lookahead p) + => TokenClass Char -> p String String +precMunch1 cls = someP (tokenClass cls) *< precNotFollowedBy (tokenClass cls) + +{- | Whitespace, by `Data.Char.isSpace`, as many as follow, as +`Text.ParserCombinators.ReadP.skipSpaces` parses, & printing none. -} +precSkipSpaces :: (RegGrammatical Char p, Lookahead p) => p () () +precSkipSpaces = dimap (const "") (const ()) (precMunch precSpaceClass) {- The rests of a string after each of its prefixes a pattern matches, counting tokens, so that repetitions of empty matches end. -} -prefixes :: Cons s s Char Char => RegEx Char -> (Int, s) -> [(Int, s)] -prefixes = \case +precPrefixes :: Cons s s Char Char => RegEx Char -> (Int, s) -> [(Int, s)] +precPrefixes = \case SeqEmpty -> pure - Sequence x y zs -> foldr (\rex k -> prefixes rex >=> k) pure (x : y : zs) + Sequence x y zs -> foldr (\rex k -> precPrefixes rex >=> k) pure (x : y : zs) NonTerminal _ -> const [] KleeneStar x -> star x - KleeneOpt x -> \pos -> pos : prefixes x pos - KleenePlus x -> prefixes x >=> star x - KleeneTimes lo hi x -> foldr (>=>) pure (replicate lo (prefixes x)) + KleeneOpt x -> \pos -> pos : precPrefixes x pos + KleenePlus x -> precPrefixes x >=> star x + KleeneTimes lo hi x -> foldr (>=>) pure (replicate lo (precPrefixes x)) >=> maybe (star x) (upTo x . subtract lo) hi - Backtracking x -> prefixes x - RegExam (Alternate x y zs) -> \pos -> concatMap (`prefixes` pos) (x : y : zs) + Backtracking x -> precPrefixes x + RegExam (Alternate x y zs) -> + \pos -> concatMap (`precPrefixes` pos) (x : y : zs) RegExam (OneOf toks) -> one (TokenClass (OneOf toks)) RegExam (NotOneOf toks test) -> one (TokenClass (NotOneOf toks test)) where @@ -151,10 +174,10 @@ prefixes = \case Just (c, str') | tokenClass cls c -> [(n + 1, str')] _ -> [] star x pos = pos : - [pos'' | pos' <- prefixes x pos, fst pos' > fst pos, pos'' <- star x pos'] + [pos'' | pos' <- precPrefixes x pos, fst pos' > fst pos, pos'' <- star x pos'] upTo x m pos | m <= 0 = [pos] - | otherwise = pos : (prefixes x pos >>= upTo x (m - 1)) + | otherwise = pos : (precPrefixes x pos >>= upTo x (m - 1)) {- | A grammar in a precedence context, a `PrecGrammatical` interpreter of any `Grammatical` one, each of whose structures it lifts pointwise. -} @@ -239,9 +262,9 @@ negative numbers, which `showsPrec` parenthesizes above 6, & `read` accepts bare at any precedence. -} instance PrecGrammar Char where - precGrammar = precParens charG + precGrammar = precParens precChar -- strings, or brackets, as `read` reads, & strings, as `show` shows - precListGrammar = precParens (stringG >|< parenthesized (bracketsG precGrammar)) + precListGrammar = precParens (precString >|< precParenthesized (precBrackets precGrammar)) instance PrecGrammar a => PrecGrammar [a] where precGrammar = precListGrammar instance PrecGrammar Bool @@ -249,35 +272,35 @@ instance PrecGrammar Ordering instance PrecGrammar a => PrecGrammar (Maybe a) instance (PrecGrammar a, PrecGrammar b) => PrecGrammar (Either a b) instance PrecGrammar () where - precGrammar = precParens (terminal "(" >* spacesG *< terminal ")") + precGrammar = precParens (terminal "(" >* precSkipSpaces *< terminal ")") instance (PrecGrammar a, PrecGrammar b) => PrecGrammar (a, b) where - precGrammar = tupled (itemG >*< commaG >* itemG) + precGrammar = precTupled (precItem >*< precComma >* precItem) instance (PrecGrammar a, PrecGrammar b, PrecGrammar c) => PrecGrammar (a, b, c) where - precGrammar = tupled $ iso (\(a, b, c) -> (a, (b, c))) (\(a, (b, c)) -> (a, b, c)) - >~ itemG >*< commaG >* itemG >*< commaG >* itemG + 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 = tupled $ iso + precGrammar = precTupled $ iso (\(a, b, c, d) -> (a, (b, (c, d)))) (\(a, (b, (c, d))) -> (a, b, c, d)) - >~ itemG >*< commaG >* itemG >*< commaG >* itemG >*< commaG >* itemG + >~ 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 = tupled $ iso + precGrammar = precTupled $ iso (\(a, b, c, d, e) -> (a, (b, (c, (d, e))))) (\(a, (b, (c, (d, e)))) -> (a, b, c, d, e)) - >~ itemG >*< commaG >* itemG >*< commaG >* itemG >*< commaG >* itemG - >*< commaG >* itemG + >~ 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. -tupled :: PrecGrammatical p => p a a -> p a a -tupled items' = precParens (terminal "(" >* items' *< spacesG *< terminal ")") +precTupled :: PrecGrammatical p => p a a -> p a a +precTupled items' = precParens (terminal "(" >* items' *< precSkipSpaces *< terminal ")") -itemG :: (PrecGrammar a, PrecGrammatical p) => p a a -itemG = precReset precGrammar +precItem :: (PrecGrammar a, PrecGrammatical p) => p a a +precItem = precReset precGrammar -commaG :: PrecGrammatical p => p () () -commaG = spacesG >* terminal "," +precComma :: PrecGrammatical p => p () () +precComma = precSkipSpaces >* terminal "," -- Generics -- @@ -296,14 +319,14 @@ 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 (operatorG name))) + Infix _ n -> precP n (gPrecFields (InfixFields (precOperator name))) Prefix | conIsRecord con -> precWith $ \d -> - let body = nameG name >* spacedG >* terminal "{" >* spacesG - >* gPrecFields RecordFields *< spacesG *< terminal "}" - in if d <= 10 then body else if d == 11 then unprinted >? body else falseP - | gArity (Proxy @f) == 0 -> nameG name >* gPrecFields PrefixFields - | otherwise -> precP 10 (nameG name >* gPrecFields PrefixFields) + let body = precName name >* precSpaced >* terminal "{" >* precSkipSpaces + >* gPrecFields RecordFields *< precSkipSpaces *< 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 @@ -327,178 +350,172 @@ instance GPrecFields U1 where instance (GPrecFields f, GPrecFields g) => GPrecFields (f :*: g) where gPrecFields style = iso (\(x :*: y) -> (x, y)) (uncurry (:*:)) >~ case style of RecordFields -> - gPrecFields RecordFields >*< spacesG >* terminal "," >* spacedG >* gPrecFields RecordFields + gPrecFields RecordFields >*< precSkipSpaces >* 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 -> nameG field >* spacedG >* symbolG "=" >* spaceG >* precReset precGrammar + RecordFields -> precName field >* precSpaced >* precSymbol "=" >* precSpace >* precReset precGrammar BareField -> precStep precGrammar - _ -> spaceG >* 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. -nameG :: PrecGrammatical p => String -> p () () -nameG name - | symbolic name = - terminal "(" >* spacesG >* symbolG name *< spacesG *< terminal ")" - | otherwise = identG name +precName :: PrecGrammatical p => String -> p () () +precName name + | precSymbolic name = + terminal "(" >* precSkipSpaces >* precSymbol name *< precSkipSpaces *< terminal ")" + | otherwise = precIdent name -- An infix operator, a symbol, or an identifier within backquotes. -operatorG :: PrecGrammatical p => String -> p () () -operatorG name - | symbolic name = spacedG >* symbolG name >* spaceG - | otherwise = spacedG >* terminal "`" >* spacesG >* identG name - *< spacesG *< terminal "`" >* spaceG - -symbolic :: String -> Bool -symbolic = \case - c : _ -> c == ':' || tokenClass symbolClass c +precOperator :: PrecGrammatical p => String -> p () () +precOperator name + | precSymbolic name = precSpaced >* precSymbol name >* precSpace + | otherwise = precSpaced >* terminal "`" >* precSkipSpaces >* precIdent name + *< precSkipSpaces *< terminal "`" >* precSpace + +precSymbolic :: String -> Bool +precSymbolic = \case + c : _ -> c == ':' || tokenClass precSymbolClass c [] -> False -instance PrecGrammar Natural where precGrammar = precParens naturalG +instance PrecGrammar Natural where precGrammar = precParens precNatural instance PrecGrammar Integer where - precGrammar = precParens (precWith (\d -> signed >~ negativeAt d >*< magnitudeG)) -instance PrecGrammar Double where precGrammar = precParens (precWith floatingAt) -instance PrecGrammar Float where precGrammar = precParens (precWith floatingAt) -instance PrecGrammar Int where precGrammar = integralG -instance PrecGrammar Int8 where precGrammar = integralG -instance PrecGrammar Int16 where precGrammar = integralG -instance PrecGrammar Int32 where precGrammar = integralG -instance PrecGrammar Int64 where precGrammar = integralG -instance PrecGrammar Word where precGrammar = integralG -instance PrecGrammar Word8 where precGrammar = integralG -instance PrecGrammar Word16 where precGrammar = integralG -instance PrecGrammar Word32 where precGrammar = integralG -instance PrecGrammar Word64 where precGrammar = integralG + 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. -integralG :: (Integral a, PrecGrammatical p) => p a a -integralG = iso toInteger fromInteger >~ precGrammar @Integer +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. -negativeAt :: (RegGrammatical Char p, Lookahead p) => Int -> p Bool Bool -negativeAt d - | d <= 6 = negativeG +precNegativeAt :: (RegGrammatical Char p, Lookahead p) => Int -> p Bool Bool +precNegativeAt d + | d <= 6 = precNegative | otherwise = orP [ only False >? oneP - , only True . unprinted >? terminal "-" >* spacesG ] + , only True . precUnprinted >? terminal "-" >* precSkipSpaces ] -- A prism which never matches, so that its alternative parses, but never prints. -unprinted :: Prism' a a -unprinted = prism' id (const Nothing) +precUnprinted :: Prism' a a +precUnprinted = prism' id (const Nothing) -- One of two terminals, printing the first, & parsing either. -eitherOf :: RegGrammatical Char p => String -> String -> p () () -eitherOf printed parsed = terminal printed >|< (unprinted >? terminal parsed) +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. -negativeG :: (RegGrammatical Char p, Lookahead p) => p Bool Bool -negativeG = iso (\b -> if b then Just () else Nothing) isJust - >~ optionalP (terminal "-" >* spacesG) - --- Whitespace, by `Data.Char.isSpace`, which `read` skips before each --- lexeme & after all, & which never prints. -spacesG :: (RegGrammatical Char p, Lookahead p) => p () () -spacesG = (skippedMany >?* tokenClass spaceClass) - *< notFollowedBy (tokenClass spaceClass) +precNegative :: (RegGrammatical Char p, Lookahead p) => p Bool Bool +precNegative = iso (\b -> if b then Just () else Nothing) isJust + >~ optionalP (terminal "-" >* precSkipSpaces) -- Whitespace, by `Data.Char.isSpace`. -spaceClass :: TokenClass Char -spaceClass = oneOf "\t\n\v\f\r" >|< asIn Space +precSpaceClass :: TokenClass Char +precSpaceClass = oneOf "\t\n\v\f\r" >|< asIn Space -- A token of a class, as unit, for lookahead. -tokenG :: RegGrammatical Char p => TokenClass Char -> p () () -tokenG cls = dimap (const ' ') (const ()) (tokenClass cls) +precToken :: RegGrammatical Char p => TokenClass Char -> p () () +precToken cls = dimap (const ' ') (const ()) (tokenClass cls) -- The digits of a base, in either case. -digitClass :: Int -> TokenClass Char -digitClass base = oneOf (concat +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. -idfClass, symbolClass :: TokenClass Char -idfClass = anyP asIn +precIdfClass, precSymbolClass :: TokenClass Char +precIdfClass = anyP asIn [ UppercaseLetter, LowercaseLetter, TitlecaseLetter, ModifierLetter , OtherLetter, DecimalNumber, LetterNumber, OtherNumber ] >|< oneOf "_'" -symbolClass = notOneOf ",;()[]{}`" >&< orP +precSymbolClass = notOneOf ",;()[]{}`" >&< orP [ anyP asIn [MathSymbol, CurrencySymbol, ModifierSymbol, OtherSymbol, DashPunctuation] , asIn OtherPunctuation >&< notOneOf "'\"" , asIn ConnectorPunctuation >&< notOneOf "_" ] -- An identifier, & a symbol, munched maximally. -identG, symbolG :: (RegGrammatical Char p, Lookahead p) => String -> p () () -identG name = terminal name *< notFollowedBy (tokenClass idfClass) -symbolG name = terminal name *< notFollowedBy (tokenClass symbolClass) +precIdent, precSymbol :: (RegGrammatical Char p, Lookahead p) => String -> p () () +precIdent name = terminal name *< precNotFollowedBy (tokenClass precIdfClass) +precSymbol name = terminal name *< precNotFollowedBy (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. -spaceG :: (RegGrammatical Char p, Lookahead p) => p () () -spaceG = orP +precSpace :: (RegGrammatical Char p, Lookahead p) => p () () +precSpace = orP [ terminal " " - , unprinted >? tokenG (spaceClass >&< notOneOf " ") - , unprinted >? notFollowedBy (tokenClass spaceClass) ] + , precUnprinted >? precToken (precSpaceClass >&< notOneOf " ") + , precUnprinted >? precNotFollowedBy (tokenClass precSpaceClass) ] -- A space, printing one, & parsing any whitespace. -spacedG :: (RegGrammatical Char p, Lookahead p) => p () () -spacedG = spaceG >* spacesG +precSpaced :: (RegGrammatical Char p, Lookahead p) => p () () +precSpaced = precSpace >* precSkipSpaces -- Signed, by an improper iso, where @-0@ parses too. -signed :: (Num a, Ord a) => Iso' a (Bool, a) -signed = iso +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. -magnitudeG :: (RegGrammatical Char p, Lookahead p) => p Integer Integer -magnitudeG = (unprinted >? try (terminal "0" >* basedG)) - >|< numeral 10 *< decimalEndG +precMagnitude :: (RegGrammatical Char p, Lookahead 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. -decimalEndG :: (RegGrammatical Char p, Lookahead p) => p () () -decimalEndG = notFollowedBy (tokenClass (digitClass 10)) - *< notFractionG *< notExponentG +precDecimalEnd :: (RegGrammatical Char p, Lookahead p) => p () () +precDecimalEnd = precNotFollowedBy (tokenClass (precDigitClass 10)) + *< precNotFraction *< precNotExponent -- Not before a fraction. -notFractionG :: Lookahead p => p () () -notFractionG = notFollowedBy (terminal "." <> tokenClass (digitClass 10)) +precNotFraction :: Lookahead p => p () () +precNotFraction = precNotFollowedBy (terminal "." <> tokenClass (precDigitClass 10)) -- Not before an exponent. -notExponentG :: Lookahead p => p () () -notExponentG = notFollowedBy - (oneOf "eE" <> optK (oneOf "+-") <> tokenClass (digitClass 10)) - -basedG :: forall p. (RegGrammatical Char p, Lookahead p) => p Integer Integer -basedG = orP - [ eitherOf "b" "B" >* munched 2 - , eitherOf "o" "O" >* munched 8 - , eitherOf "x" "X" >* munched 16 +precNotExponent :: Lookahead p => p () () +precNotExponent = precNotFollowedBy + (oneOf "eE" <> optK (oneOf "+-") <> tokenClass (precDigitClass 10)) + +precBased :: forall p. (RegGrammatical Char p, Lookahead p) => p Integer Integer +precBased = orP + [ precEitherOf "b" "B" >* munched 2 + , precEitherOf "o" "O" >* munched 8 + , precEitherOf "x" "X" >* munched 16 ] where munched :: Int -> p Integer Integer munched base = numeral (toInteger base) - *< notFollowedBy (tokenClass (digitClass base)) + *< precNotFollowedBy (tokenClass (precDigitClass base)) -- Natural numbers, & negative zero, as `read` reads integers & keeps -- those which aren't negative. -naturalG :: (RegGrammatical Char p, Lookahead p) => p Natural Natural -naturalG = (iso toInteger fromInteger >~ magnitudeG) - >|< (unprinted . only 0 >? terminal "-" >* spacesG >* zerosG) +precNatural :: (RegGrammatical Char p, Lookahead p) => p Natural Natural +precNatural = (iso toInteger fromInteger >~ precMagnitude) + >|< (precUnprinted . only 0 >? terminal "-" >* precSkipSpaces >* zerosG) where zerosG = terminal "0" >* orP - [ zeros *< decimalEndG + [ zeros *< precDecimalEnd , orP (map terminal ["b", "B"]) >* terminal "0" >* zeros - *< notFollowedBy (tokenClass (digitClass 2)) + *< precNotFollowedBy (tokenClass (precDigitClass 2)) , orP (map terminal ["o", "O"]) >* terminal "0" >* zeros - *< notFollowedBy (tokenClass (digitClass 8)) + *< precNotFollowedBy (tokenClass (precDigitClass 8)) , orP (map terminal ["x", "X"]) >* terminal "0" >* zeros - *< notFollowedBy (tokenClass (digitClass 16)) + *< precNotFollowedBy (tokenClass (precDigitClass 16)) ] zeros = skippedMany >?* terminal "0" @@ -525,30 +542,30 @@ _Based = prism' Based $ \case {- 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. -} -floatingAt :: (RealFloat a, RegGrammatical Char p, Lookahead p) => Int -> p a a -floatingAt d = iso toLexeme fromLexeme >~ negativeAt d >*< orP - [ only NotANumber >? identG "NaN" - , only Infinite >? identG "Infinity" - , unprinted . _Based >? try (terminal "0" >* basedG) +precFloating :: (RealFloat a, RegGrammatical Char p, Lookahead 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 >? notFractionG ] + , _Nothing >? precNotFraction ] >*< orP - [ _Just >? eitherOf "e" "E" >* (signed >~ exponentSignG >*< numeral 10 - *< notFollowedBy (tokenClass (digitClass 10))) - , _Nothing >? notExponentG ] + [ _Just >? precEitherOf "e" "E" >* (precSigned >~ exponentSignG >*< numeral 10 + *< precNotFollowedBy (tokenClass (precDigitClass 10))) + , _Nothing >? precNotExponent ] ] where - digitsG = someP (digit 10) *< notFollowedBy (tokenClass (digitClass 10)) + digitsG = someP (digit 10) *< precNotFollowedBy (tokenClass (precDigitClass 10)) exponentSignG = orP [ only True >? terminal "-" - , only False . unprinted >? terminal "+" + , only False . precUnprinted >? terminal "+" , only False >? oneP ] -toLexeme :: RealFloat a => a -> (Bool, FloatLexeme) -toLexeme x +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))) @@ -562,8 +579,8 @@ toLexeme x in Decimal (orZero whole) (Just (orZero fraction)) Nothing orZero ds = if null ds then [0] else ds -fromLexeme :: RealFloat a => (Bool, FloatLexeme) -> a -fromLexeme (negative, lexeme) = (if negative then negate else id) value +precFromLexeme :: RealFloat a => (Bool, FloatLexeme) -> a +precFromLexeme (negative, lexeme) = (if negative then negate else id) value where value = case lexeme of NotANumber -> 0 / 0 @@ -592,25 +609,25 @@ fromLexeme (negative, lexeme) = (if negative then negate else id) value (zeros, _) -> Just (negate (length zeros)) -- A character's literal, between single quotes. -charG :: (RegGrammatical Char p, Lookahead p) => p Char Char -charG = terminal "'" >* litCharG '\'' *< terminal "'" +precChar :: (RegGrammatical Char p, Lookahead 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 @\\^_@. -} -litCharG :: (RegGrammatical Char p, Lookahead p) => Char -> p Char Char -litCharG quote = rawG [quote] >|< terminal "\\" >* orP - [fixedEscG True, decimalEscG, octalEscG, hexEscG, controlEscG] +precLitChar :: (RegGrammatical Char p, Lookahead 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. -rawG :: RegGrammatical Char p => String -> p Char Char -rawG excluded = tokenClass (oneOf [' ' .. '~'] >&< notOneOf ('\\' : excluded)) - >|< unprinted >? tokenClass (notOneOf ('\\' : excluded <> [' ' .. '~'])) +precRaw :: RegGrammatical Char p => String -> p Char Char +precRaw excluded = tokenClass (oneOf [' ' .. '~'] >&< notOneOf ('\\' : excluded)) + >|< precUnprinted >? tokenClass (notOneOf ('\\' : excluded <> [' ' .. '~'])) -- Named escapes, with @SO@ or not. -fixedEscG :: (RegGrammatical Char p, Lookahead p) => Bool -> p Char Char -fixedEscG withSO = escapesG $ +precFixedEsc :: (RegGrammatical Char p, Lookahead 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'] @@ -623,15 +640,15 @@ fixedEscG withSO = escapesG $ , "CAN", "EM", "SUB", "ESC", "FS", "GS", "RS", "US" ] -- Codes up to `maxBound`, decimal, printing above @\\DEL@, octal & hexadecimal. -decimalEscG, octalEscG, hexEscG :: RegGrammatical Char p => p Char Char -decimalEscG = prism' toEnum (\c -> if c > '\DEL' then Just (fromEnum c) else Nothing) - >? boundedNumeral 10 (fromEnum (maxBound :: Char)) -octalEscG = unprinted . prism' toEnum (Just . fromEnum) - >? eitherOf "o" "O" >* boundedNumeral 8 (fromEnum (maxBound :: Char)) -hexEscG = unprinted . prism' toEnum (Just . fromEnum) - >? eitherOf "x" "X" >* boundedNumeral 16 (fromEnum (maxBound :: Char)) -controlEscG :: RegGrammatical Char p => p Char Char -controlEscG = unprinted . iso (\c -> toEnum (fromEnum c + 64)) (\c -> toEnum (fromEnum c - 64)) +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. @@ -649,8 +666,8 @@ 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. -} -stringG :: forall p. (RegGrammatical Char p, Lookahead p) => p String String -stringG = iso items (\xs -> [c | StrChar c <- xs]) +precString :: forall p. (RegGrammatical Char p, Lookahead 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 @@ -664,19 +681,19 @@ stringG = iso items (\xs -> [c | StrChar c <- xs]) itemsG continuing = orP [ _Empty >? oneP , itemThen emptyG free - , itemThen (_StrChar >? rawG ('"' : continuing)) free - , itemThen (_StrChar >? terminal "\\" >* orP [fixedEscG False, controlEscG]) free + , itemThen (_StrChar >? precRaw ('"' : continuing)) free + , itemThen (_StrChar >? terminal "\\" >* orP [precFixedEsc False, precControlEsc]) free , itemThen (_StrChar . only '\SO' >? terminal "\\SO") afterSO - , itemThen (_StrChar >? terminal "\\" >* decimalEscG) afterDecimal - , itemThen (_StrChar >? terminal "\\" >* octalEscG) afterOctal - , itemThen (_StrChar >? terminal "\\" >* hexEscG) afterHex + , 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 "\\&" >|< unprinted >? terminal "\\" + emptyG = only StrEmpty >? (terminal "\\&" >|< precUnprinted >? terminal "\\" >* dimap (const ' ') (const ()) (tokenClass (oneOf "\t\n\v\f\r" >|< asIn Space)) - >* spacesG *< terminal "\\") + >* precSkipSpaces *< terminal "\\") items = \case c : cs@(c' : _) | protected c c' -> StrChar c : StrEmpty : items cs c : cs -> StrChar c : items cs @@ -686,18 +703,18 @@ stringG = iso items (\xs -> [c | StrChar c <- xs]) -- Escapes by fixed strings, as a trie, which is LL(1), maximally munched, -- like @\\SO@ & @\\SOH@, each character printing by its first string. -escapesG :: (RegGrammatical Char p, Lookahead p) => [(Char, String)] -> p Char Char -escapesG escapes = orP $ +precEscapes :: (RegGrammatical Char p, Lookahead p) => [(Char, String)] -> p Char Char +precEscapes escapes = orP $ [only c >? oneP | (c, "") <- take 1 [e | e@(_, "") <- escapes]] - <> [ terminal [first] >* escapesG [(c, rest) | (c, x : rest) <- escapes, x == first] + <> [ 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. -} -boundedNumeral :: forall n p. (Integral n, RegGrammatical Char p) => n -> n -> p n n -boundedNumeral base bound - = (unprinted >? try (terminal "0" >* zerosG >* positiveG)) +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 @@ -742,4 +759,4 @@ boundedNumeral base bound digitIs :: n -> p () () digitIs d = let c = (['0' .. '9'] <> ['a' .. 'z']) !! fromIntegral d - in if isLetter c then eitherOf [c] [toUpper c] else terminal [c] + in if isLetter c then precEitherOf [c] [toUpper c] else terminal [c] From b095111b4ed2ea49bac4950c619c580299c5cc9a Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sat, 14 Nov 2026 07:26:58 -0800 Subject: [PATCH 41/51] Lookahead names after ReadP: notFollowedBy, eof, munch, munch1, skipSpaces Co-Authored-By: Claude Opus 5.5 --- distributors-grammar/CHANGELOG.md | 4 +- .../src/Control/Lens/Grammar/Prec.hs | 92 +++++++++---------- 2 files changed, 48 insertions(+), 48 deletions(-) diff --git a/distributors-grammar/CHANGELOG.md b/distributors-grammar/CHANGELOG.md index 0f60f09f..e9930333 100644 --- a/distributors-grammar/CHANGELOG.md +++ b/distributors-grammar/CHANGELOG.md @@ -48,8 +48,8 @@ fields, infix constructors, symbolic & backquoted, at their fixities, & symbolic constructors in prefix. Instances for `Bool`, `Ordering`, `Maybe` & `Either`, by it, & for `()` & tuples. `Lookahead`, negative lookahead - by `precNotFollowedBy` a `RegEx`, which `PrecGrammatical` requires, & - `precEof`, `precMunch`, `precMunch1` & `precSkipSpaces`, as `ReadP`'s, + 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; & diff --git a/distributors-grammar/src/Control/Lens/Grammar/Prec.hs b/distributors-grammar/src/Control/Lens/Grammar/Prec.hs index 52535547..bb5ee3f0 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/Prec.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/Prec.hs @@ -21,10 +21,10 @@ module Control.Lens.Grammar.Prec , precList -- * Lookahead , Lookahead (..) - , precEof - , precMunch - , precMunch1 - , precSkipSpaces + , eof + , munch + , munch1 + , skipSpaces -- * Precedence , Precedence (..) , precG @@ -95,12 +95,12 @@ class {- | 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 = precSkipSpaces >* precParenthesized p +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) *< precSkipSpaces *< terminal ")" +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 & @@ -112,45 +112,45 @@ precList = precParens . precBrackets precBrackets :: PrecGrammatical p => p a a -> p [a] [a] precBrackets x = terminal "[" >* orP [ _Empty >? oneP - , _Cons >? precReset x >*< manyP (precSkipSpaces >* terminal "," >* precReset x) - ] *< precSkipSpaces *< terminal "]" + , _Cons >? precReset x >*< manyP (skipSpaces >* terminal "," >* precReset x) + ] *< skipSpaces *< terminal "]" {- | Negative lookahead, as `read`'s lexer munches lexemes maximally. -} class Lookahead p where {- | Not followed by a string a pattern matches, consuming nothing, & printing nothing; nonterminals match nothing. -} - precNotFollowedBy :: RegEx Char -> p () () + notFollowedBy :: RegEx Char -> p () () instance (Alternative f, Cons s s Char Char) => Lookahead (Parsor s f) where - precNotFollowedBy rex = Parsor $ \mode s -> case mode of + notFollowedBy rex = Parsor $ \mode s -> case mode of Nothing | not (null (precPrefixes rex (0, s))) -> empty _ -> pure ((), s) instance Applicative f => Lookahead (Printor s f) where - precNotFollowedBy _ = Printor (\_ -> pure ((), id)) + notFollowedBy _ = Printor (\_ -> pure ((), id)) instance Lookahead p => Lookahead (Precedence p) where - precNotFollowedBy = Precedence . const . precNotFollowedBy + notFollowedBy = Precedence . const . notFollowedBy {- | At the end of input, not followed by any token. -} -precEof :: Lookahead p => p () () -precEof = precNotFollowedBy anyToken +eof :: Lookahead p => p () () +eof = notFollowedBy anyToken {- | Tokens of a class, as many as follow, as `Text.ParserCombinators.ReadP.munch` parses, & printing them. -} -precMunch +munch :: (RegGrammatical Char p, Lookahead p) => TokenClass Char -> p String String -precMunch cls = manyP (tokenClass cls) *< precNotFollowedBy (tokenClass cls) +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. -} -precMunch1 +munch1 :: (RegGrammatical Char p, Lookahead p) => TokenClass Char -> p String String -precMunch1 cls = someP (tokenClass cls) *< precNotFollowedBy (tokenClass cls) +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. -} -precSkipSpaces :: (RegGrammatical Char p, Lookahead p) => p () () -precSkipSpaces = dimap (const "") (const ()) (precMunch precSpaceClass) +skipSpaces :: (RegGrammatical Char p, Lookahead p) => p () () +skipSpaces = dimap (const "") (const ()) (munch precSpaceClass) {- The rests of a string after each of its prefixes a pattern matches, counting tokens, so that repetitions of empty matches end. -} @@ -272,7 +272,7 @@ instance PrecGrammar Ordering instance PrecGrammar a => PrecGrammar (Maybe a) instance (PrecGrammar a, PrecGrammar b) => PrecGrammar (Either a b) instance PrecGrammar () where - precGrammar = precParens (terminal "(" >* precSkipSpaces *< terminal ")") + 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 @@ -294,13 +294,13 @@ instance (PrecGrammar a, PrecGrammar b, PrecGrammar c, PrecGrammar d, PrecGramma -- 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' *< precSkipSpaces *< terminal ")") +precTupled items' = precParens (terminal "(" >* items' *< skipSpaces *< terminal ")") precItem :: (PrecGrammar a, PrecGrammatical p) => p a a precItem = precReset precGrammar precComma :: PrecGrammatical p => p () () -precComma = precSkipSpaces >* terminal "," +precComma = skipSpaces >* terminal "," -- Generics -- @@ -322,8 +322,8 @@ instance (Constructor c, GPrecFields f) => GPrecSum (M1 C c f) where Infix _ n -> precP n (gPrecFields (InfixFields (precOperator name))) Prefix | conIsRecord con -> precWith $ \d -> - let body = precName name >* precSpaced >* terminal "{" >* precSkipSpaces - >* gPrecFields RecordFields *< precSkipSpaces *< terminal "}" + 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) @@ -350,7 +350,7 @@ instance GPrecFields U1 where instance (GPrecFields f, GPrecFields g) => GPrecFields (f :*: g) where gPrecFields style = iso (\(x :*: y) -> (x, y)) (uncurry (:*:)) >~ case style of RecordFields -> - gPrecFields RecordFields >*< precSkipSpaces >* terminal "," >* precSpaced >* gPrecFields 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) @@ -367,15 +367,15 @@ instance (Selector s, PrecGrammar a) => GPrecFields (M1 S s (K1 R a)) where precName :: PrecGrammatical p => String -> p () () precName name | precSymbolic name = - terminal "(" >* precSkipSpaces >* precSymbol name *< precSkipSpaces *< terminal ")" + 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 "`" >* precSkipSpaces >* precIdent name - *< precSkipSpaces *< terminal "`" >* precSpace + | otherwise = precSpaced >* terminal "`" >* skipSpaces >* precIdent name + *< skipSpaces *< terminal "`" >* precSpace precSymbolic :: String -> Bool precSymbolic = \case @@ -407,7 +407,7 @@ precNegativeAt d | d <= 6 = precNegative | otherwise = orP [ only False >? oneP - , only True . precUnprinted >? terminal "-" >* precSkipSpaces ] + , only True . precUnprinted >? terminal "-" >* skipSpaces ] -- A prism which never matches, so that its alternative parses, but never prints. precUnprinted :: Prism' a a @@ -420,7 +420,7 @@ precEitherOf printed parsed = terminal printed >|< (precUnprinted >? terminal pa -- A minus, a lexeme of its own, as whether a number is negative. precNegative :: (RegGrammatical Char p, Lookahead p) => p Bool Bool precNegative = iso (\b -> if b then Just () else Nothing) isJust - >~ optionalP (terminal "-" >* precSkipSpaces) + >~ optionalP (terminal "-" >* skipSpaces) -- Whitespace, by `Data.Char.isSpace`. precSpaceClass :: TokenClass Char @@ -448,8 +448,8 @@ precSymbolClass = notOneOf ",;()[]{}`" >&< orP -- An identifier, & a symbol, munched maximally. precIdent, precSymbol :: (RegGrammatical Char p, Lookahead p) => String -> p () () -precIdent name = terminal name *< precNotFollowedBy (tokenClass precIdfClass) -precSymbol name = terminal name *< precNotFollowedBy (tokenClass precSymbolClass) +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 @@ -458,11 +458,11 @@ precSpace :: (RegGrammatical Char p, Lookahead p) => p () () precSpace = orP [ terminal " " , precUnprinted >? precToken (precSpaceClass >&< notOneOf " ") - , precUnprinted >? precNotFollowedBy (tokenClass precSpaceClass) ] + , precUnprinted >? notFollowedBy (tokenClass precSpaceClass) ] -- A space, printing one, & parsing any whitespace. precSpaced :: (RegGrammatical Char p, Lookahead p) => p () () -precSpaced = precSpace >* precSkipSpaces +precSpaced = precSpace >* skipSpaces -- Signed, by an improper iso, where @-0@ parses too. precSigned :: (Num a, Ord a) => Iso' a (Bool, a) @@ -479,16 +479,16 @@ precMagnitude = (precUnprinted >? try (terminal "0" >* precBased)) -- Where a decimal integer ends: not before a fraction, nor an exponent. precDecimalEnd :: (RegGrammatical Char p, Lookahead p) => p () () -precDecimalEnd = precNotFollowedBy (tokenClass (precDigitClass 10)) +precDecimalEnd = notFollowedBy (tokenClass (precDigitClass 10)) *< precNotFraction *< precNotExponent -- Not before a fraction. precNotFraction :: Lookahead p => p () () -precNotFraction = precNotFollowedBy (terminal "." <> tokenClass (precDigitClass 10)) +precNotFraction = notFollowedBy (terminal "." <> tokenClass (precDigitClass 10)) -- Not before an exponent. precNotExponent :: Lookahead p => p () () -precNotExponent = precNotFollowedBy +precNotExponent = notFollowedBy (oneOf "eE" <> optK (oneOf "+-") <> tokenClass (precDigitClass 10)) precBased :: forall p. (RegGrammatical Char p, Lookahead p) => p Integer Integer @@ -500,22 +500,22 @@ precBased = orP where munched :: Int -> p Integer Integer munched base = numeral (toInteger base) - *< precNotFollowedBy (tokenClass (precDigitClass base)) + *< notFollowedBy (tokenClass (precDigitClass base)) -- Natural numbers, & negative zero, as `read` reads integers & keeps -- those which aren't negative. precNatural :: (RegGrammatical Char p, Lookahead p) => p Natural Natural precNatural = (iso toInteger fromInteger >~ precMagnitude) - >|< (precUnprinted . only 0 >? terminal "-" >* precSkipSpaces >* zerosG) + >|< (precUnprinted . only 0 >? terminal "-" >* skipSpaces >* zerosG) where zerosG = terminal "0" >* orP [ zeros *< precDecimalEnd , orP (map terminal ["b", "B"]) >* terminal "0" >* zeros - *< precNotFollowedBy (tokenClass (precDigitClass 2)) + *< notFollowedBy (tokenClass (precDigitClass 2)) , orP (map terminal ["o", "O"]) >* terminal "0" >* zeros - *< precNotFollowedBy (tokenClass (precDigitClass 8)) + *< notFollowedBy (tokenClass (precDigitClass 8)) , orP (map terminal ["x", "X"]) >* terminal "0" >* zeros - *< precNotFollowedBy (tokenClass (precDigitClass 16)) + *< notFollowedBy (tokenClass (precDigitClass 16)) ] zeros = skippedMany >?* terminal "0" @@ -553,11 +553,11 @@ precFloating d = iso precToLexeme precFromLexeme >~ precNegativeAt d >*< orP , _Nothing >? precNotFraction ] >*< orP [ _Just >? precEitherOf "e" "E" >* (precSigned >~ exponentSignG >*< numeral 10 - *< precNotFollowedBy (tokenClass (precDigitClass 10))) + *< notFollowedBy (tokenClass (precDigitClass 10))) , _Nothing >? precNotExponent ] ] where - digitsG = someP (digit 10) *< precNotFollowedBy (tokenClass (precDigitClass 10)) + digitsG = someP (digit 10) *< notFollowedBy (tokenClass (precDigitClass 10)) exponentSignG = orP [ only True >? terminal "-" , only False . precUnprinted >? terminal "+" @@ -693,7 +693,7 @@ precString = iso items (\xs -> [c | StrChar c <- xs]) emptyG :: p StrItem StrItem emptyG = only StrEmpty >? (terminal "\\&" >|< precUnprinted >? terminal "\\" >* dimap (const ' ') (const ()) (tokenClass (oneOf "\t\n\v\f\r" >|< asIn Space)) - >* precSkipSpaces *< terminal "\\") + >* skipSpaces *< terminal "\\") items = \case c : cs@(c' : _) | protected c c' -> StrChar c : StrEmpty : items cs c : cs -> StrChar c : items cs From e8a761e7dde5635095b89080bb0f76da58fddb82 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sat, 14 Nov 2026 07:31:08 -0800 Subject: [PATCH 42/51] Lookahead: prefix matching local to Parsor's notFollowedBy Co-Authored-By: Claude Opus 5.5 --- .../src/Control/Lens/Grammar/Prec.hs | 54 +++++++++---------- 1 file changed, 26 insertions(+), 28 deletions(-) diff --git a/distributors-grammar/src/Control/Lens/Grammar/Prec.hs b/distributors-grammar/src/Control/Lens/Grammar/Prec.hs index bb5ee3f0..a6def96a 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/Prec.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/Prec.hs @@ -122,8 +122,33 @@ class Lookahead p where notFollowedBy :: RegEx Char -> p () () instance (Alternative f, Cons s s Char Char) => Lookahead (Parsor s f) where notFollowedBy rex = Parsor $ \mode s -> case mode of - Nothing | not (null (precPrefixes rex (0, s))) -> empty + 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 => Lookahead (Printor s f) where notFollowedBy _ = Printor (\_ -> pure ((), id)) instance Lookahead p => Lookahead (Precedence p) where @@ -152,33 +177,6 @@ munch1 cls = someP (tokenClass cls) *< notFollowedBy (tokenClass cls) skipSpaces :: (RegGrammatical Char p, Lookahead p) => p () () skipSpaces = dimap (const "") (const ()) (munch precSpaceClass) -{- The rests of a string after each of its prefixes a pattern matches, -counting tokens, so that repetitions of empty matches end. -} -precPrefixes :: Cons s s Char Char => RegEx Char -> (Int, s) -> [(Int, s)] -precPrefixes = \case - SeqEmpty -> pure - Sequence x y zs -> foldr (\rex k -> precPrefixes rex >=> k) pure (x : y : zs) - NonTerminal _ -> const [] - KleeneStar x -> star x - KleeneOpt x -> \pos -> pos : precPrefixes x pos - KleenePlus x -> precPrefixes x >=> star x - KleeneTimes lo hi x -> foldr (>=>) pure (replicate lo (precPrefixes x)) - >=> maybe (star x) (upTo x . subtract lo) hi - Backtracking x -> precPrefixes x - RegExam (Alternate x y zs) -> - \pos -> concatMap (`precPrefixes` pos) (x : y : zs) - RegExam (OneOf toks) -> one (TokenClass (OneOf toks)) - RegExam (NotOneOf toks test) -> one (TokenClass (NotOneOf toks test)) - where - one cls (n, str) = case uncons str of - Just (c, str') | tokenClass cls c -> [(n + 1, str')] - _ -> [] - star x pos = pos : - [pos'' | pos' <- precPrefixes x pos, fst pos' > fst pos, pos'' <- star x pos'] - upTo x m pos - | m <= 0 = [pos] - | otherwise = pos : (precPrefixes x pos >>= upTo x (m - 1)) - {- | 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} From 2d103456d758e9d412e0a54d57986f9541f93fa3 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sat, 14 Nov 2026 07:42:44 -0800 Subject: [PATCH 43/51] Update Prec.hs --- distributors-grammar/src/Control/Lens/Grammar/Prec.hs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/distributors-grammar/src/Control/Lens/Grammar/Prec.hs b/distributors-grammar/src/Control/Lens/Grammar/Prec.hs index a6def96a..2efcc124 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/Prec.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/Prec.hs @@ -43,7 +43,7 @@ import Control.Lens.Grammar.Symbol import Control.Lens.Grammar.Token import Control.Lens.PartialIso import Control.Lens.Prismoid ((>?*)) -import Data.Char (isLetter, toUpper) +import Data.Char (isDigit, isLetter, toUpper) import Data.Int (Int8, Int16, Int32, Int64) import Data.List (nub) import Data.Maybe (isJust) @@ -696,8 +696,7 @@ precString = iso items (\xs -> [c | StrChar c <- xs]) c : cs@(c' : _) | protected c c' -> StrChar c : StrEmpty : items cs c : cs -> StrChar c : items cs [] -> [] - protected c c' = (c > '\DEL' && isDec c') || (c == '\SO' && c' == 'H') - isDec c' = '0' <= c' && c' <= '9' + 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. From ce3276790df9063db94d432f4a79dd78a57301ea Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sat, 14 Nov 2026 12:47:37 -0800 Subject: [PATCH 44/51] asdf --- distributors-grammar/CHANGELOG.md | 2 +- .../src/Control/Lens/Grammar/Prec.hs | 60 ++++++------ .../src/Control/Lens/Grammar/SKETCHneeew.hs | 92 +++++++++++++++++++ 3 files changed, 123 insertions(+), 31 deletions(-) create mode 100644 distributors-grammar/src/Control/Lens/Grammar/SKETCHneeew.hs diff --git a/distributors-grammar/CHANGELOG.md b/distributors-grammar/CHANGELOG.md index e9930333..f249b212 100644 --- a/distributors-grammar/CHANGELOG.md +++ b/distributors-grammar/CHANGELOG.md @@ -47,7 +47,7 @@ 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. `Lookahead`, negative lookahead + & `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, & diff --git a/distributors-grammar/src/Control/Lens/Grammar/Prec.hs b/distributors-grammar/src/Control/Lens/Grammar/Prec.hs index 2efcc124..5d5fe956 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/Prec.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/Prec.hs @@ -19,8 +19,8 @@ module Control.Lens.Grammar.Prec , PrecGrammatical (..) , precParens , precList - -- * Lookahead - , Lookahead (..) + -- * NotFollowedBy + , NotFollowedBy (..) , eof , munch , munch1 @@ -77,7 +77,7 @@ class PrecGrammar a where `Text.ParserCombinators.ReadPrec` has, where a grammar runs in a precedence context, from 0 to 11, as `showsPrec`'s is. -} class - ( Grammatical Char p, Lookahead p + ( 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 @@ -116,11 +116,11 @@ precBrackets x = terminal "[" >* orP ] *< skipSpaces *< terminal "]" {- | Negative lookahead, as `read`'s lexer munches lexemes maximally. -} -class Lookahead p where +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) => Lookahead (Parsor s f) where +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) @@ -149,32 +149,32 @@ instance (Alternative f, Cons s s Char Char) => Lookahead (Parsor s f) where upTo m x pos | m <= 0 = [pos] | otherwise = pos : (prefixes x pos >>= upTo (m - 1) x) -instance Applicative f => Lookahead (Printor s f) where +instance Applicative f => NotFollowedBy (Printor s f) where notFollowedBy _ = Printor (\_ -> pure ((), id)) -instance Lookahead p => Lookahead (Precedence p) where +instance NotFollowedBy p => NotFollowedBy (Precedence p) where notFollowedBy = Precedence . const . notFollowedBy {- | At the end of input, not followed by any token. -} -eof :: Lookahead p => p () () +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, Lookahead p) + :: (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, Lookahead p) + :: (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, Lookahead p) => p () () +skipSpaces :: (RegGrammatical Char p, NotFollowedBy p) => p () () skipSpaces = dimap (const "") (const ()) (munch precSpaceClass) {- | A grammar in a precedence context, a `PrecGrammatical` interpreter of @@ -233,7 +233,7 @@ 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, Lookahead p) => PrecGrammatical (Precedence p) where +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)) @@ -241,7 +241,7 @@ instance (Grammatical Char p, Lookahead p) => PrecGrammatical (Precedence p) whe {- | A type's `PrecGrammar` at a precedence, at any `Grammatical` interpreter which parses or prints. -} -precG :: forall a p. (PrecGrammar a, Grammatical Char p, Lookahead p) => Int -> p a a +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. -} @@ -400,7 +400,7 @@ 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, Lookahead p) => Int -> p Bool Bool +precNegativeAt :: (RegGrammatical Char p, NotFollowedBy p) => Int -> p Bool Bool precNegativeAt d | d <= 6 = precNegative | otherwise = orP @@ -416,7 +416,7 @@ 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, Lookahead p) => p Bool Bool +precNegative :: (RegGrammatical Char p, NotFollowedBy p) => p Bool Bool precNegative = iso (\b -> if b then Just () else Nothing) isJust >~ optionalP (terminal "-" >* skipSpaces) @@ -445,21 +445,21 @@ precSymbolClass = notOneOf ",;()[]{}`" >&< orP , asIn ConnectorPunctuation >&< notOneOf "_" ] -- An identifier, & a symbol, munched maximally. -precIdent, precSymbol :: (RegGrammatical Char p, Lookahead p) => String -> p () () +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, Lookahead p) => p () () +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, Lookahead p) => p () () +precSpaced :: (RegGrammatical Char p, NotFollowedBy p) => p () () precSpaced = precSpace >* skipSpaces -- Signed, by an improper iso, where @-0@ parses too. @@ -471,25 +471,25 @@ precSigned = iso -- 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. -precMagnitude :: (RegGrammatical Char p, Lookahead p) => p Integer Integer +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, Lookahead p) => p () () +precDecimalEnd :: (RegGrammatical Char p, NotFollowedBy p) => p () () precDecimalEnd = notFollowedBy (tokenClass (precDigitClass 10)) *< precNotFraction *< precNotExponent -- Not before a fraction. -precNotFraction :: Lookahead p => p () () +precNotFraction :: NotFollowedBy p => p () () precNotFraction = notFollowedBy (terminal "." <> tokenClass (precDigitClass 10)) -- Not before an exponent. -precNotExponent :: Lookahead p => p () () +precNotExponent :: NotFollowedBy p => p () () precNotExponent = notFollowedBy (oneOf "eE" <> optK (oneOf "+-") <> tokenClass (precDigitClass 10)) -precBased :: forall p. (RegGrammatical Char p, Lookahead p) => p Integer Integer +precBased :: forall p. (RegGrammatical Char p, NotFollowedBy p) => p Integer Integer precBased = orP [ precEitherOf "b" "B" >* munched 2 , precEitherOf "o" "O" >* munched 8 @@ -502,7 +502,7 @@ precBased = orP -- Natural numbers, & negative zero, as `read` reads integers & keeps -- those which aren't negative. -precNatural :: (RegGrammatical Char p, Lookahead p) => p Natural Natural +precNatural :: (RegGrammatical Char p, NotFollowedBy p) => p Natural Natural precNatural = (iso toInteger fromInteger >~ precMagnitude) >|< (precUnprinted . only 0 >? terminal "-" >* skipSpaces >* zerosG) where @@ -540,7 +540,7 @@ _Based = prism' Based $ \case {- 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, Lookahead p) => Int -> p a a +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" @@ -607,14 +607,14 @@ precFromLexeme (negative, lexeme) = (if negative then negate else id) value (zeros, _) -> Just (negate (length zeros)) -- A character's literal, between single quotes. -precChar :: (RegGrammatical Char p, Lookahead p) => p Char Char +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, Lookahead p) => Char -> p Char Char +precLitChar :: (RegGrammatical Char p, NotFollowedBy p) => Char -> p Char Char precLitChar quote = precRaw [quote] >|< terminal "\\" >* orP [precFixedEsc True, precDecimalEsc, precOctalEsc, precHexEsc, precControlEsc] @@ -624,7 +624,7 @@ precRaw excluded = tokenClass (oneOf [' ' .. '~'] >&< notOneOf ('\\' : excluded) >|< precUnprinted >? tokenClass (notOneOf ('\\' : excluded <> [' ' .. '~'])) -- Named escapes, with @SO@ or not. -precFixedEsc :: (RegGrammatical Char p, Lookahead p) => Bool -> p Char Char +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"), ('\\', "\\"), ('"', "\"")] @@ -664,7 +664,7 @@ 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, Lookahead p) => p String String +precString :: forall p. (RegGrammatical Char p, NotFollowedBy p) => p String String precString = iso items (\xs -> [c | StrChar c <- xs]) >~ terminal "\"" >* free *< terminal "\"" where @@ -700,7 +700,7 @@ precString = iso items (\xs -> [c | StrChar c <- xs]) -- 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, Lookahead p) => [(Char, String)] -> p Char Char +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] diff --git a/distributors-grammar/src/Control/Lens/Grammar/SKETCHneeew.hs b/distributors-grammar/src/Control/Lens/Grammar/SKETCHneeew.hs new file mode 100644 index 00000000..54a22e3b --- /dev/null +++ b/distributors-grammar/src/Control/Lens/Grammar/SKETCHneeew.hs @@ -0,0 +1,92 @@ +module Token + ( Categorize (..) + , Tokenized (..) + , TokenAlgebra (..) + , TokenClass (..) + , TokenExam (..) + ) where + +class + ( Ord token + , Enum (Categorize token) + , Bounded (Categorize token) + ) => Categorized token where + type Categorize token :: Type + categorize :: token -> Categorize token + +class Categorized token => Tokenized token p | p -> token where + anyToken :: p + token :: token -> p + oneOf :: Foldable f => f token -> p + notOneOf :: Foldable f => f token -> p + asIn :: Categorize token -> p + notAsIn :: Categorize token -> p + +class Tokenized token p => TokenAlgebra token p where + tokenClass :: TokenClass token -> p + +newtype TokenClass token = TokenClass (TokenExam token (TokenClass token)) + +data TokenExam token alg + = OneOf (Set token) + | NotOneOf (Set token) (CategoryTest token) + | Alternate [alg] + +data CategoryTest token + = AndAsIn (Categorize token) + | AndNotAsIn (Set (Categorize token)) + +module RegEx + ( RegEx (..) + , fromRegEx + , KleeneStarAlgebra (..) + , NotFollowed (..) + , Tried (..) + ) where + +data RegEx token + = Sequence [RegEx token] + | KleeneStar (RegEx token) + | KleeneOpt (RegEx token) + | KleenePlus (RegEx token) + | KleeneQuant Int (Maybe Int) (RegEx token) + | RegExam (TokenExam token (RegEx token)) + | NotFollowedBy (RegEx token) + | Try (RegEx token) + +fromRegEx + :: (KleeneStarAlgebra k, TokenAlgebra token k, NotFollowed token k, Tried k) + -> RegEx token -> k + +class NotFollowed token p where + notFollowedBy :: RegEx token -> p + +class Tried p where + try :: p -> p + +module BackusNaur + ( Ruled (..) + , BackusNaurForm (..) + , Bnf (..) + ) where + +class Ruled name p where + rule :: name -> p -> p + +class Ruled name p => BackusNaurForm name p where + ruleRec :: name -> (p -> p) -> p + +data Bnf name rule = Bnf + { startBnf :: Either name rule + , rulesBnf :: Set (name, Either name rule) + } deriving stock (Eq, Ord, Show, Read) + +module Prec + ( Preceded (..) + ) where + +class TerminalSymbol token p => Preceded p where + prec :: Int -> p -> p + precStep :: p -> p + precReset :: p -> p + precWith :: (Int -> p) -> p From eacd12eae0d69c5aea38350b90f593608cedd1a1 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Thu, 19 Nov 2026 13:04:02 -0800 Subject: [PATCH 45/51] ,jhg --- .../src/Control/Lens/Grammar/Prec.hs | 3 +- .../src/Control/Lens/Grammar/SKETCHneeew.hs | 92 ------------------- 2 files changed, 2 insertions(+), 93 deletions(-) delete mode 100644 distributors-grammar/src/Control/Lens/Grammar/SKETCHneeew.hs diff --git a/distributors-grammar/src/Control/Lens/Grammar/Prec.hs b/distributors-grammar/src/Control/Lens/Grammar/Prec.hs index 5d5fe956..ca1cbffa 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/Prec.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/Prec.hs @@ -233,7 +233,8 @@ 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 +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)) diff --git a/distributors-grammar/src/Control/Lens/Grammar/SKETCHneeew.hs b/distributors-grammar/src/Control/Lens/Grammar/SKETCHneeew.hs deleted file mode 100644 index 54a22e3b..00000000 --- a/distributors-grammar/src/Control/Lens/Grammar/SKETCHneeew.hs +++ /dev/null @@ -1,92 +0,0 @@ -module Token - ( Categorize (..) - , Tokenized (..) - , TokenAlgebra (..) - , TokenClass (..) - , TokenExam (..) - ) where - -class - ( Ord token - , Enum (Categorize token) - , Bounded (Categorize token) - ) => Categorized token where - type Categorize token :: Type - categorize :: token -> Categorize token - -class Categorized token => Tokenized token p | p -> token where - anyToken :: p - token :: token -> p - oneOf :: Foldable f => f token -> p - notOneOf :: Foldable f => f token -> p - asIn :: Categorize token -> p - notAsIn :: Categorize token -> p - -class Tokenized token p => TokenAlgebra token p where - tokenClass :: TokenClass token -> p - -newtype TokenClass token = TokenClass (TokenExam token (TokenClass token)) - -data TokenExam token alg - = OneOf (Set token) - | NotOneOf (Set token) (CategoryTest token) - | Alternate [alg] - -data CategoryTest token - = AndAsIn (Categorize token) - | AndNotAsIn (Set (Categorize token)) - -module RegEx - ( RegEx (..) - , fromRegEx - , KleeneStarAlgebra (..) - , NotFollowed (..) - , Tried (..) - ) where - -data RegEx token - = Sequence [RegEx token] - | KleeneStar (RegEx token) - | KleeneOpt (RegEx token) - | KleenePlus (RegEx token) - | KleeneQuant Int (Maybe Int) (RegEx token) - | RegExam (TokenExam token (RegEx token)) - | NotFollowedBy (RegEx token) - | Try (RegEx token) - -fromRegEx - :: (KleeneStarAlgebra k, TokenAlgebra token k, NotFollowed token k, Tried k) - -> RegEx token -> k - -class NotFollowed token p where - notFollowedBy :: RegEx token -> p - -class Tried p where - try :: p -> p - -module BackusNaur - ( Ruled (..) - , BackusNaurForm (..) - , Bnf (..) - ) where - -class Ruled name p where - rule :: name -> p -> p - -class Ruled name p => BackusNaurForm name p where - ruleRec :: name -> (p -> p) -> p - -data Bnf name rule = Bnf - { startBnf :: Either name rule - , rulesBnf :: Set (name, Either name rule) - } deriving stock (Eq, Ord, Show, Read) - -module Prec - ( Preceded (..) - ) where - -class TerminalSymbol token p => Preceded p where - prec :: Int -> p -> p - precStep :: p -> p - precReset :: p -> p - precWith :: (Int -> p) -> p From 83e16235d2071b4b50196872b91f71eb79281179 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Thu, 19 Nov 2026 13:18:17 -0800 Subject: [PATCH 46/51] Prec: read binary literals only on base >= 4.21, as read does base-4.20 (GHC 9.10) Read doesn't lex 0b/0B literals, so the grammar disagreed with readsPrec there, failing CI's cabal 9.10.3 and nix jobs. Co-Authored-By: Claude Opus 5.5 --- .../src/Control/Lens/Grammar/Prec.hs | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/distributors-grammar/src/Control/Lens/Grammar/Prec.hs b/distributors-grammar/src/Control/Lens/Grammar/Prec.hs index ca1cbffa..1cbb496a 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/Prec.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/Prec.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE CPP #-} {- | Module : Control.Lens.Grammar.Prec Description : grammars of Haskell types, as Read & Show @@ -471,7 +472,9 @@ precSigned = iso -- 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. +-- 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 @@ -492,8 +495,11 @@ precNotExponent = notFollowedBy precBased :: forall p. (RegGrammatical Char p, NotFollowedBy p) => p Integer Integer precBased = orP - [ precEitherOf "b" "B" >* munched 2 - , precEitherOf "o" "O" >* munched 8 + [ +#if MIN_VERSION_base(4,21,0) + precEitherOf "b" "B" >* munched 2, +#endif + precEitherOf "o" "O" >* munched 8 , precEitherOf "x" "X" >* munched 16 ] where @@ -509,8 +515,10 @@ precNatural = (iso toInteger fromInteger >~ precMagnitude) 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 From 3fd4f5319f1a996325cacefca0e166cca7505c06 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Fri, 20 Nov 2026 13:17:14 -0800 Subject: [PATCH 47/51] Merge json-algebra: quantK, quantP, ctxList & ctxTree Takes json-algebra's distributors-core, which is this branch's plus the renames timesK ~> quantK, timesP ~> quantP, stepping ~> ctxList & steppingTree ~> ctxTree, & renames their uses in distributors-grammar. Co-Authored-By: Claude Opus 5.5 --- distributors-grammar/CHANGELOG.md | 2 +- .../src/Control/Lens/Grammar/Analysis.hs | 2 +- .../src/Control/Lens/Grammar/Prec.hs | 2 +- .../src/Control/Lens/Grammar/RegEx.hs | 12 ++++++------ distributors-grammar/src/Data/Profunctor/Grammar.hs | 2 +- distributors-grammar/test/Main.hs | 10 +++++----- 6 files changed, 15 insertions(+), 15 deletions(-) diff --git a/distributors-grammar/CHANGELOG.md b/distributors-grammar/CHANGELOG.md index f249b212..bacdccb6 100644 --- a/distributors-grammar/CHANGELOG.md +++ b/distributors-grammar/CHANGELOG.md @@ -17,7 +17,7 @@ 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 `timesK`, +- `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. diff --git a/distributors-grammar/src/Control/Lens/Grammar/Analysis.hs b/distributors-grammar/src/Control/Lens/Grammar/Analysis.hs index acf6d674..de8e704e 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/Analysis.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/Analysis.hs @@ -70,7 +70,7 @@ foldRegEx tok nonterm = go KleeneStar x -> starK (go x) KleeneOpt x -> optK (go x) KleenePlus x -> plusK (go x) - KleeneTimes lo hi x -> timesK lo hi (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)) diff --git a/distributors-grammar/src/Control/Lens/Grammar/Prec.hs b/distributors-grammar/src/Control/Lens/Grammar/Prec.hs index 1cbb496a..6ed24e63 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/Prec.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/Prec.hs @@ -214,7 +214,7 @@ 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)) - timesP lo hi (Precedence x) = Precedence (timesP lo hi . x) + 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 diff --git a/distributors-grammar/src/Control/Lens/Grammar/RegEx.hs b/distributors-grammar/src/Control/Lens/Grammar/RegEx.hs index e95f0e58..ce6b2f30 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/RegEx.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/RegEx.hs @@ -70,7 +70,7 @@ data RegEx token | KleeneOpt (RegEx token) | KleenePlus (RegEx token) {- | Between some numbers of times, inclusive, @x{lo,hi}@ or @x{lo,}@, - normalized by `timesK`: either unbounded, at least twice, or bounded, + 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. -} @@ -126,7 +126,7 @@ instance Categorized token => KleeneStarAlgebra (RegEx token) where plusK (RegExam exam) | isFailExam exam = falseP plusK SeqEmpty = mempty plusK rex = KleenePlus rex - timesK lo0 hi rex = case (max 0 lo0, hi) of + 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 -> @@ -160,7 +160,7 @@ instance (Categorized token, HasTrie token) , kleeneStarTrie = trie (f . starK) , kleeneOptTrie = trie (f . optK) , kleenePlusTrie = trie (f . plusK) - , kleeneTimesTrie = trie (f . \((lo, hi), x) -> timesK lo hi x) + , kleeneTimesTrie = trie (f . \((lo, hi), x) -> quantK lo hi x) , backtrackingTrie = trie (f . try) , oneOfTrie = trie (f . oneOf) , notOneOfTrie = trie (f . testNotOneOf) @@ -370,7 +370,7 @@ diffB prefix (Bnf start rules) = Backtracking y -> diff1B x y KleenePlus y -> diff1B x y <> starK y KleeneTimes lo hi y -> - diff1B x y <> timesK (lo - 1) (subtract 1 <$> 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)) -> @@ -616,8 +616,8 @@ regexGrammar = ruleRec "regex" altG , atomG rex ] - -- improper, normalizing counts by `timesK` - _Times = prism' (\(x, (lo, hi)) -> timesK lo hi x) $ \case + -- improper, normalizing counts by `quantK` + _Times = prism' (\(x, (lo, hi)) -> quantK lo hi x) $ \case KleeneTimes lo hi x -> Just (x, (lo, hi)) _ -> Nothing diff --git a/distributors-grammar/src/Data/Profunctor/Grammar.hs b/distributors-grammar/src/Data/Profunctor/Grammar.hs index 2ea554e4..c7dcb26a 100644 --- a/distributors-grammar/src/Data/Profunctor/Grammar.hs +++ b/distributors-grammar/src/Data/Profunctor/Grammar.hs @@ -236,7 +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) - timesP lo hi (Grammor rex) = Grammor (timesK lo hi rex) + 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 diff --git a/distributors-grammar/test/Main.hs b/distributors-grammar/test/Main.hs index 2d1d3164..af7152fc 100644 --- a/distributors-grammar/test/Main.hs +++ b/distributors-grammar/test/Main.hs @@ -99,7 +99,7 @@ regexQuantifierTests = do rendered (exactly 0) `shouldBe` "" rendered (inRange 3 (Just 2)) `shouldBe` "[]" it "parses counts, normalizing them" $ do - (fromString "a{2,3}" :: RegEx Char) `shouldBe` timesK 2 (Just 3) (token 'a') + (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}" @@ -111,17 +111,17 @@ regexQuantifierTests = do 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 = timesK lo hi (token 'a') :: RegEx Char + 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 "timesK n (Just n) x matches as n times x" $ \(x :: RegEx Char) -> + 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 =~ timesK n (Just n) x) === (w =~ mconcat (replicate n x)) + (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 = timesK lo hi x in fromString (toList rex) === rex + let rex = quantK lo hi x in fromString (toList rex) === rex readPrecTests :: Spec readPrecTests = do From 9e415262888b2dd071c6c9253bbf47cc940d6e2f Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Fri, 20 Nov 2026 15:24:08 -0800 Subject: [PATCH 48/51] Control.Lens.Grammar.Pretty: Wadler-Leijen layout for grammars Lined (hardlineP) & LaidOut (flatAltP, nestP, groupP, alignP), with lineP, lineP' & softlineP; PrettyGrammar & PrettyGrammatical; Prettor, a printer into a Monoid, printing a prettyprinter Doc by prettyG & layoutG; Parsor parses every layout, any indentation, & RegEx, Bnf & Grammor describe them. Grammor is IsString. Tested at SExpr. Co-Authored-By: Claude Opus 5.5 --- distributors-grammar/CHANGELOG.md | 8 + .../distributors-grammar.cabal | 6 + distributors-grammar/package.yaml | 1 + .../src/Control/Lens/Grammar.hs | 1 + .../src/Control/Lens/Grammar/Pretty.hs | 264 ++++++++++++++++++ .../src/Data/Profunctor/Grammar.hs | 2 + distributors-grammar/test/Examples/SExpr.hs | 17 ++ distributors-grammar/test/Main.hs | 2 + .../test/Properties/Pretty.hs | 34 +++ 9 files changed, 335 insertions(+) create mode 100644 distributors-grammar/src/Control/Lens/Grammar/Pretty.hs create mode 100644 distributors-grammar/test/Properties/Pretty.hs diff --git a/distributors-grammar/CHANGELOG.md b/distributors-grammar/CHANGELOG.md index bacdccb6..1e985033 100644 --- a/distributors-grammar/CHANGELOG.md +++ b/distributors-grammar/CHANGELOG.md @@ -2,6 +2,14 @@ ## 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 `PrettyGrammatical` interpreters, 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. diff --git a/distributors-grammar/distributors-grammar.cabal b/distributors-grammar/distributors-grammar.cabal index 04b08077..183453f5 100644 --- a/distributors-grammar/distributors-grammar.cabal +++ b/distributors-grammar/distributors-grammar.cabal @@ -34,6 +34,7 @@ library 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 @@ -95,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 @@ -160,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 @@ -182,6 +185,7 @@ test-suite test Examples.SExpr Properties.Base Properties.Kleene + Properties.Pretty Properties.Varifocal Paths_distributors_grammar autogen-modules: @@ -241,6 +245,7 @@ test-suite test , 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 @@ -310,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 ad1143a4..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 diff --git a/distributors-grammar/src/Control/Lens/Grammar.hs b/distributors-grammar/src/Control/Lens/Grammar.hs index ca12149b..71dc265f 100644 --- a/distributors-grammar/src/Control/Lens/Grammar.hs +++ b/distributors-grammar/src/Control/Lens/Grammar.hs @@ -76,6 +76,7 @@ import Control.Lens.Grammar.BackusNaur as X hiding 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 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..c386e8a5 --- /dev/null +++ b/distributors-grammar/src/Control/Lens/Grammar/Pretty.hs @@ -0,0 +1,264 @@ +{- | +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 (..) + , PrettyGrammatical + , 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 (Constraint, 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 :: PrettyGrammatical p => p a a + +{- | The `Grammatical` interpreters of layout, `Lined` & `LaidOut`. -} +type PrettyGrammatical p = + ( Grammatical Char p + , forall x y. (x ~ (), y ~ ()) => Lined (p x y) + , forall x y. LaidOut (p x y) + , forall x y. (x ~ (), y ~ ()) => IsString (p x y) + ) :: Constraint + +{- | 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/Data/Profunctor/Grammar.hs b/distributors-grammar/src/Data/Profunctor/Grammar.hs index c7dcb26a..3945a1d9 100644 --- a/distributors-grammar/src/Data/Profunctor/Grammar.hs +++ b/distributors-grammar/src/Data/Profunctor/Grammar.hs @@ -249,6 +249,8 @@ 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 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 diff --git a/distributors-grammar/test/Examples/SExpr.hs b/distributors-grammar/test/Examples/SExpr.hs index f6262454..afe82292 100644 --- a/distributors-grammar/test/Examples/SExpr.hs +++ b/distributors-grammar/test/Examples/SExpr.hs @@ -1,6 +1,7 @@ module Examples.SExpr ( SExpr (..) , sexprGrammar + , sexprPrettyGrammar , sexprExamples ) where @@ -58,4 +59,20 @@ sexprExamples = ] 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 :: PrettyGrammatical p => 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/Main.hs b/distributors-grammar/test/Main.hs index af7152fc..2f34e797 100644 --- a/distributors-grammar/test/Main.hs +++ b/distributors-grammar/test/Main.hs @@ -28,6 +28,7 @@ import Examples.SemVer import Examples.SExpr import Properties.Base import Properties.Kleene +import Properties.Pretty import Properties.Varifocal main :: IO () @@ -55,6 +56,7 @@ main = hspec $ do describe "base types" baseProperties describe "RegEx ranges & try" regexRangeTryTests describe "RegEx quantifiers" regexQuantifierTests + describe "PrettyGrammar, at SExpr" prettyProperties regexRangeTryTests :: Spec regexRangeTryTests = do 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 From bc8c60d9954e1a53d50b7d4ffb21d08074fa5732 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Fri, 20 Nov 2026 15:30:35 -0800 Subject: [PATCH 49/51] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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: From c8378047b6333e0f138974826840a50df1e61456 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Fri, 20 Nov 2026 15:54:18 -0800 Subject: [PATCH 50/51] Update Pretty.hs --- .../src/Control/Lens/Grammar/Pretty.hs | 18 +++++++----------- 1 file changed, 7 insertions(+), 11 deletions(-) diff --git a/distributors-grammar/src/Control/Lens/Grammar/Pretty.hs b/distributors-grammar/src/Control/Lens/Grammar/Pretty.hs index c386e8a5..5c8addb3 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/Pretty.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/Pretty.hs @@ -18,7 +18,6 @@ they print, with any indentation. module Control.Lens.Grammar.Pretty ( -- * PrettyGrammar PrettyGrammar (..) - , PrettyGrammatical , prettyG , layoutG , LayoutStyle (..) @@ -47,7 +46,7 @@ import Data.Profunctor.Monoidal import Data.Profunctor.Monoidal.Cocartesian import Data.String (IsString (..)) import Data.Void (absurd) -import GHC.Exts (Constraint, IsList, Item) +import GHC.Exts (IsList, Item) import Prettyprinter ( Doc, LayoutOptions, align, flatAlt, group, hardline, layoutCompact , layoutPretty, layoutSmart, nest ) @@ -56,15 +55,12 @@ import Witherable (Filterable) {- | A type's grammar, laid out by `Lined` & `LaidOut` combinators. -} class PrettyGrammar a where - prettyGrammar :: PrettyGrammatical p => p a a - -{- | The `Grammatical` interpreters of layout, `Lined` & `LaidOut`. -} -type PrettyGrammatical p = - ( Grammatical Char p - , forall x y. (x ~ (), y ~ ()) => Lined (p x y) - , forall x y. LaidOut (p x y) - , forall x y. (x ~ (), y ~ ()) => IsString (p x y) - ) :: Constraint + 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) From 8e9b36e291937c9ae085c7df8f4c65bc9f2a1d54 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Fri, 20 Nov 2026 15:59:43 -0800 Subject: [PATCH 51/51] SExpr's pretty grammar spells out its constraints, PrettyGrammatical removed Co-Authored-By: Claude Opus 5.5 --- distributors-grammar/CHANGELOG.md | 3 ++- distributors-grammar/test/Examples/SExpr.hs | 8 +++++++- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/distributors-grammar/CHANGELOG.md b/distributors-grammar/CHANGELOG.md index 1e985033..961a1222 100644 --- a/distributors-grammar/CHANGELOG.md +++ b/distributors-grammar/CHANGELOG.md @@ -5,7 +5,8 @@ - `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 `PrettyGrammatical` interpreters, print, by + `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`, diff --git a/distributors-grammar/test/Examples/SExpr.hs b/distributors-grammar/test/Examples/SExpr.hs index afe82292..5a0a6656 100644 --- a/distributors-grammar/test/Examples/SExpr.hs +++ b/distributors-grammar/test/Examples/SExpr.hs @@ -7,6 +7,7 @@ module Examples.SExpr import Control.Lens hiding (List) import Control.Lens.Grammar hiding (List) +import Data.String (IsString) -- | Abstract syntax tree for S-expressions data SExpr @@ -63,7 +64,12 @@ 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 :: PrettyGrammatical p => p SExpr SExpr +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"