Skip to content

JSON grammars, disjunctive monoids & cocartesian choice - #30

Open
echatav wants to merge 137 commits into
mainfrom
json-algebra
Open

echatav wants to merge 137 commits into
mainfrom
json-algebra

Conversation

@echatav

@echatav echatav commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Control.Lens.Grammar.Json: bidirectional JSON grammars, compatible with aeson, which parse, decode, print & encode JSON and generate TypeScript types, from one grammar.

  • Classes of grammars for strings (JsonStr), values (JsonVal), array elements (JsonTup) & object properties (JsonObj), and a Json class of types with grammars, including map key grammars.
  • Object combinators: required (!:) & optional (?:) properties, defaults (!=), the rest of an object (jsonDict), strict objects (jsonObjectStrict) & alternative object shapes.
  • Runners: jsonParse & jsonPrint to & from aeson Values, jsonDecode & jsonEncode to & from bytes, with errors (JsonError) located by path & labeled by rules; jsonTypes for TypeScript.
  • jsonGeneric derives grammars by aeson's Options, agreeing with aeson's generic instances, and ViaJson derives aeson's instances.
  • TypeScript: rules name type aliases; tuples, unions, index signatures, mapped types of enumerated keys & ${number} keys.
  • Performance within 2x of aeson across a benchmark suite (bench/Main.hs), checking agreement with aeson first.

Data.Monoid.Disjunctive: DisjunctiveMonoid (falseP, >|<), BooleanAlgebra & KleeneStarAlgebra, replacing the Boole & Kleene modules; Kleene's regular expressions move to Control.Lens.Grammar.RegEx.

Data.Profunctor.Monoidal.Cocartesian: CocartesianMonoidal (zeroP, >+<) is split from Distributor, and CocartesianChoice ties it to Choice & DisjunctiveMonoid, by alternate, without requiring (Cartesian) Monoidal.

Data.Profunctor.Monoidal: idP & arrP for Monoidal & Strong profunctors, and Monoidally, to derive Traversing & Arrow instances.

Control.Lens.Grammar.Json: bidirectional JSON grammars, compatible
with aeson, which parse, decode, print & encode JSON and generate
TypeScript types, from one grammar.

* Classes of grammars for strings (JsonStr), values (JsonVal),
  array elements (JsonTup) & object properties (JsonObj), and a Json
  class of types with grammars, including map key grammars.
* Object combinators: required (!:) & optional (?:) properties,
  defaults (!=), the rest of an object (jsonDict),
  strict objects (jsonObjectStrict) & alternative object shapes.
* Runners: jsonParse & jsonPrint to & from aeson Values,
  jsonDecode & jsonEncode to & from bytes, with errors (JsonError)
  located by path & labeled by rules; jsonTypes for TypeScript.
* jsonGeneric derives grammars by aeson's Options, agreeing with
  aeson's generic instances, and ViaJson derives aeson's instances.
* TypeScript: rules name type aliases; tuples, unions, index
  signatures, mapped types of enumerated keys & `${number}` keys.
* Performance within 2x of aeson across a benchmark suite
  (bench/Main.hs), checking agreement with aeson first.

Data.Monoid.Disjunctive: DisjunctiveMonoid (falseP, >|<),
BooleanAlgebra & KleeneStarAlgebra, replacing the Boole & Kleene
modules; Kleene's regular expressions move to Control.Lens.Grammar.RegEx.

Data.Profunctor.Distributor: CocartesianMonoidal (zeroP, >+<) is split
from Distributor, and CocartesianChoice ties it to Choice & a
DisjunctiveMonoid, by alternate, without requiring Monoidal.

Data.Profunctor.Monoidal: idP & arrP for Monoidal & Strong
profunctors, and Monoidally, to derive Traversing & Arrow instances.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@echatav

echatav commented Nov 5, 2026

Copy link
Copy Markdown
Contributor Author

@theNerd247

@echatav

echatav commented Nov 5, 2026

Copy link
Copy Markdown
Contributor Author

@sjoerdvisscher

echatav and others added 27 commits November 5, 2026 09:30
CocartesianMonoidal, dialt & CocartesianChoice move to their own module,
the cocartesian counterpart of Data.Profunctor.Monoidal, leaving
Distributor & Alternator, which combine the two, in
Data.Profunctor.Distributor. Each class is documented by its own laws.

The CocartesianChoice instances of Yoneda, Coyoneda & WrappedPafb
require only CocartesianChoice, rather than Alternator.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
distributors-core holds the distributors package, unchanged but for
Control.Lens.Grammar.Json & its tests and benchmarks, which move to the
new distributors-json package, along with their dependencies.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- cabal.project builds both packages; GHC 9.10 & 9.12 build & pass.
- flake.nix builds & checks both packages with nixpkgs' cached GHC.
- CI lints (HLint, & .cabal files generated from package.yaml), builds &
  tests with stack (with doctests), cabal (GHC 9.10 & 9.12) & nix, caches
  each, & builds the documentation, deploying it to GitHub Pages from main.
- .hlint.yaml ignores the hints in today's code, so new hints fail CI.
- Tests no longer need QuickCheck 2.17's GeneralCategory & Down instances.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- jsonType types a type's JSON as a Bnf of JsonTypes, by its rules,
  & jsonTsDeclarations declares the rules of types in TypeScript,
  replacing jsonTypes.
- Control.Lens.Grammar.TypeScript models TypeScript's type declarations
  after its compiler: tsTokenGrammar, a RegGrammar Char TsToken of its
  scanner's tokens & trivia, & tsGrammar, a Grammar TsToken of its syntax,
  so that tsPrint & tsParse print & parse declarations.
- Mapped types exclude named keys by an as clause, rather than Exclude,
  so that declarations refer to no global types.
- Document the JSON package by doctested examples, & add a root README.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
jsonTsPut prints by Parsector, reporting the offset & expectation where
it can't print, & the tests round-trip by Parsector & Parsor.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A prism's constructor is total, so withOperators builds every operator it
parses: no error for an infix pattern which doesn't build, & no prefix or
postfix operator silently dropped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
tsTokensGrammar scans tokens without their trivia, as tsc's scanner skips
them, & prints them with their trivia, so that tsGrammar, left-factored &
guarding its printing alternatives by prisms, is LL(1): parsecG parses &
unparsecG prints both layers, locating failures.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Its type is unchanged. tokenClass interprets its class & makes its
failures once, rather than for each token; liftA2 sequences without a
continuation; left' & right' choose without alternate; dimap, lmap &
rmap map states directly; #. & .# coerce. Parsing Textual grammars is
~30-40% faster.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
terminal checks its tokens in one loop, and manyP runs its elements in
one loop, both parsing & printing, rather than through isos, sums &
sequencing for each token & element, with the same failures & hints
as before. Parsing Textual grammars is now 1.1-3.8x read.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
TokenAlgebra & TerminalSymbol instances call uncons & snoc for each
token through dictionaries; specialising them to String streams makes
parsing Textual grammars ~5-15% faster. Specialising the other
instances, inlining & -O2 made no measurable difference, since grammars
are built by dictionary passing & run as already compiled closures.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
tokenClass, token, oneOf & the rest test their tokens directly, rather
than through satisfy; terminal prints its tokens together; manyP &
optionalP traverse their elements; dimap, lmap & rmap map directly.
Instances which print tokens are specialised to String & Maybe, and
TerminalSymbol & IsString need only an Applicative. Printing Textual
grammars is 2-4x faster.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
jsonEnumWith, a JsonStr method, takes a table of strings & values, & each
value's index in it, so that printers index rendered literals rather than
walking a sum. Generic enumerations, whose constructors are all nullary,
index by dataToTag#, which a type family over Rep requires only of them,
since newtypes have no DataToTag. Encoding enumerations goes from 1.97x
aeson to 1.37x, & printing them to Values from 0.84x to 0.41x.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…iteral

TypeNode is TsType, TypeElement is TsProperty, PropertyName is
TsPropertyName, Literal is TsLiteral, & TypeLiteral is ObjectType.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Enumerable functors are Homogeneous countable sums of single copies,
sequenced by CocartesianMonoidal profunctors. Comonocles are the optic
dual to Monocles by sums, with enumerated, enumBounded & Comonocular.
WrappedPafb f p is CocartesianMonoidal for any Functor f.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
echatav and others added 29 commits November 13, 2026 00:48
Prismoids apply directly at an Alternator, so the target's own methods
act, & separators, repetition & delimiters compose from small parts.

- >?* applies a polymorphic Prismoid at an Alternator, without a
  concrete form, keeping the target's someP & optionP (e.g. Grammor's
  plusK exactly). mapPrismoid is removed: clonePrismoid pat >?*.
- sepBy :: p () () -> Prismoid s t a b -> p a b -> p s t separates
  consecutive foci by an internal upper triangular matrix of actions,
  preferring foci greedily; delimiters compose by >* & *<. It replaces
  SepBy, noSep, sepWith, beginWith & endWith, & the SepBy combinators.
- manyTillP, an Alternator method, p* q trying q first; Grammor defines
  it as starK p <> q, so sepBy is finite at static Alternators.
- Optics renamed or new: manied -> several, somed -> atLeast 1,
  chained1/chained -> chain1/chain; exactly, atLeast, atMost & inRange,
  unified on one worker (finite lower bound, optional upper bound).
- skipManyP & skipOptionalP, & their Diopters skippedMany &
  skippedOptional: actions a parser accepts & a printer omits.
- SepBy's module merges into Control.Lens.Prismoid, which, with
  Control.Lens.Diopter, Control.Lens.Grammar re-exports.
- Fixed: a deterministic parser's separated many parsed nothing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
sepWith :: (Alternator p, TerminalSymbol c (p () ()))
        => [c] -> Prismoid s t a b -> p a b -> p s t
sepWith = sepBy . terminal

Every grammar separator is a terminal, so grammars read
sepWith "," (atLeast 1) json; 0.6's several1 (sepWith ",") p is
sepWith "," (atLeast 1) p.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A list of items as an IsList, like lens's List pattern, as an optic:
act on an IsList as on lists by listed ~< p, or into its items by
from listed. It replaces iso toList fromList in the grammars.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
JsonErrorSort's JsonLiteral is error info, a literal mismatch, not a
literal value; the JsonType of a string literal takes its name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Prismoid applicators: >?*, sepBy & counted Prismoids
type Varifocal s t a b = forall p m.
  (MonadicTrans p, Alternator (p m), MonadPlus m, Filterable m)
    => p m a (m b) -> p m s (m t)

A Varifocal's shape may depend on the foci it builds, as no Bifocal's
can. Its Applicative is the monad m of its profunctor, absorbed by
joinP, so Bifocal ⊂ Varifocal & lens optics compose by (.).

- MonadicTrans, in Data.Profunctor.Monadic: profunctors transforming a
  monad, with liftP & joinP, laws (tested) & a MINIMAL pragma; Printor
  & Parsor are instances. Parsector deliberately isn't: its failure
  backtracks by its state, which a monad's mzero can't reach.
- >?=< applies a Varifocal by joinP.
- Varifocus, the free concrete form: a free MonadicTrans Alternator on
  a focus, with constructors named for their methods (FocusP ...
  ManyTillP), keeping targets' own manyP & co; AVarifocal, varifocus,
  runVarifocus & cloneVarifocal, round-tripping as tested.
- terminatedBy & delimited: sentinel-terminated & matching-delimited
  sequences, not context-free; a heredoc grammar example & doc.
- Data.Profunctor.Monadic splits: Monadic & MonadicTrans to import
  unqualified, & Data.Profunctor.Monadic.Do, the qualified do-notation.
- Control.Lens.Grammar re-exports Control.Lens.Varifocal &
  Data.Profunctor.Monadic.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
varifocus :: MonadPlus m => AVarifocal s t a b -> Varifocus a b m s t
embeds the captured list monad's choices into m, so runVarifocus
interprets LiftP by liftP directly, needing only Monad m.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
contextually :: Varifocal s t a b -> p m a b -> p m s t, a Varifocal's
applicator, conflicting with no names in the library, lens,
profunctors or aeson.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…icTrans

contextually :: (Monadic p, Alternator p) => AVarifocal s t a b -> p a b -> p s t
runs a Varifocal's concrete form, interpreting its list monad's choices
& failures by the Alternator's own, so it applies in CtxGrammars,
TypeScript's included, & backtracks as Parsector does. The MonadicTrans
applicator & runner are renamed contextuallyT & runVarifocusT.

The heredoc example is a CtxGrammar, running by parseG, printG,
parsecG & unparsecG, as tested & documented.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
stepping :: st -> (st -> a -> Either Bool st) -> Varifocal' [a] a
decides by each focus built to continue (Right st), stop (Left True)
or reject (Left False). terminatedBy & delimited are its instances,
with new balanced, nested open/close pairs, & countPrefixed, a count
then that many, as tested, cloned too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Varifocals of the same foci, side by side on a pair, one or the other
on a sum, or the second chosen by what the first built, as only
Varifocals can, like a netstring, tested over random payloads.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- oneOptic, zeroOptic & falseOptic: the units of the crosses, alts &
  ors, each in its least optic, the rest by inclusion.
- crossPrismoid/Bifocal/Diopter/Grate, altPrismoid/Bifocal/Diopter,
  orPrismoid/Bifocal/Varifocal.
- crossComonocle ~> alongsideComonocle: it pairs differing foci, as
  lens's alongside, with unit id, unlike the crosses.
- Remove imprism & the orphan Applicative (Market a b s): a Monocle
  without foci made an improper Prism breaking even
  preview l (review l b) = Just b.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Varifocals: context-sensitive optics over MonadicTrans profunctors,
contextually & contextuallyT, stepping & its instances, heredocs;
Monadic/Monadic.Do split; optic units & cross/alt/or combinators.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- inRange (exactly, atLeast, atMost) sequences its foci at the target
  itself, then its Applicative once, rather than at WrappedPafb per
  focus: 25-34% faster printing & Parsector parsing of counted
  repetitions, 15-21% for sepBy exactly.
- withOperators decomposes left-associated chains by accumulating
  their steps, linearly rather than quadratically: expression printing
  10-13% faster.
- Distributor's default manyP ties its knot, building its action once.

Measured by distributors-grammar's bench:core (uncommitted).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- crossPartialIso ~> alongsidePartialIso & altPartialIso ~>
  withoutPartialIso, after lens's alongside & without, since they pair
  & sum differing foci; emptyPartialIso ~> falsePartialIso, as
  falseOptic.
- distributors-grammar's bench:core benchmarks distributors' combinators
  & the test examples, scaled, at parsing, printing & Parsector.
- Changelog: orPartialIso, the renames & the performance changes.
- Eitan's edits to Varifocal, Monadic, Homogeneous, Grammar & tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- tokenClass's default tests a class's sets of tokens by Set.member &
  Set.notMember, & predicates' oneOf & notOneOf collect their tokens
  into a Set once, rather than testing by Foldable's elem, linearly:
  the JSON example parses ~665x faster (4.36 s -> 6.5 ms on 4.6 KB),
  its characters being a class of over a million tokens.
- unparseG & unparsecG document that they snoc, so print to a Seq,
  not a String, which prints quadratically (16000 tokens: 4 s vs 6 ms).
- bench:core's manyTillP workload checks emptiness before printing its
  terminator, as an LL(1) printer requires; manyTillP round-trips.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Parsor's manyP & optionalP parse & print their elements in turn,
rather than by Distributor's defaults, through isomorphisms & sums,
as Printor's do, parsing more before fewer, as the defaults do.
bench:core: manyP & someP parse 0.58x, sepBy 0.77x, heredoc 0.48x,
sexpr 0.67x, expr 0.72x; printing & Parsector unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Control.Lens.Internal.Distributor.NestedPrismTH is renamed
Control.Lens.Prism.Nested, & gains the Generic versions of what
makeNestedPrisms generates, focusing fields as right-nested pairs:

  genericNestedPrism :: forall s -> forall (con :: Symbol) -> ...
    => Prism' s (ConFocus con (Rep s))
  genericNestedIso :: forall s -> ... => Iso' s (IsoFocus (Rep s))

by required type arguments, e.g. genericNestedPrism Shape "Rect" &
genericNestedIso (type Point), with type errors for a missing
constructor & for an Iso of a sum. No new dependency: a closed family
finds the constructor by name & a class right-nests its product,
which generic-lens-core's tupled _GCtor couldn't. Tested against
makeNestedPrisms's prisms & iso; re-exported by Control.Lens.PartialIso.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
bif >?<* p = catMaybes (bif (rmap Just p)) applies a Bifocal directly
at a partial Alternator, as >?* does a Prismoid: the target's own
methods act as they are (an opted default prints nothing at Printor,
as its optionP does, where through a Spectacle it printed the default),
& it's faster than through a Spectacle (atLeast 1 at Parsor/Printor:
parse 212 vs 234-292 us, print 43 vs 59 us). It agrees with >?* on
Prismoids & >?< on PartialIsos, tested at Parsor & Printor.
ABifocal applies by cloneBifocal, now by withSpectacle. Grammar
re-exports Control.Lens.Bifocal, as CtxGrammars are Filtrators.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Brings distributors-core to its state on json-algebra-grammar (83e1623),
leaving distributors-grammar & distributors-json as on json-algebra:

- timesK & timesP: repetition between bounds, x{lo,hi} & x{lo,};
  inRange, exactly, atLeast & atMost by timesP
- DisjunctiveMonoid for every Alternative of the dependencies, & for
  Set, IntSet, Map & IntMap by union
- Bits types as BooleanAlgebras; Predicate & Ap Kleene algebras;
  ReadPrec Filterable
- Varifocal: stepping over any Cons stream, steppingTree & arityWith,
  many & some by manyP & someP, alternatives by anyP

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Renames timesK ~> quantK, timesP ~> quantP, stepping ~> ctxList &
steppingTree ~> ctxTree. Documents quantK & quantP as Kleene
quantifiers, with quantP 0 (Just 1) by optionalP.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
distributors-core changes from json-algebra-grammar

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant