diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4a049442..9aec33cd 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,37 +1,129 @@ name: CI on: - pull_request: + push: branches: - main + pull_request: + workflow_dispatch: + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +permissions: + contents: read jobs: - build-and-test: + lint: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Set up HLint + uses: haskell-actions/hlint-setup@v2 + + - name: Run HLint + uses: haskell-actions/hlint-run@v2 + with: + path: '["distributors-core/", "distributors-grammar/", "distributors-json/"]' + fail-on: suggestion + + - name: Check generated .cabal files match package.yaml + run: | + curl -sSL https://github.com/sol/hpack/releases/download/0.39.1/hpack_linux.gz \ + | gunzip > hpack + chmod +x hpack + for package in distributors-core distributors-grammar distributors-json; do + (cd "$package" && ../hpack --force) + done + git diff --exit-code -I 'by hpack version' -- '*.cabal' + + stack: runs-on: ubuntu-latest steps: - - name: Checkout repository - uses: actions/checkout@v4 + - uses: actions/checkout@v4 - - name: Setup Haskell Stack + - name: Set up Stack uses: haskell-actions/setup@v2 with: enable-stack: true + stack-no-global: true - - name: Cache Stack dependencies + - name: Cache Stack uses: actions/cache@v4 with: - path: ~/.stack - key: stack-${{ runner.os }}-${{ hashFiles('stack.yaml', 'package.yaml') }} + path: | + ~/.stack + .stack-work + distributors-core/.stack-work + distributors-grammar/.stack-work + distributors-json/.stack-work + key: stack-${{ runner.os }}-${{ hashFiles('stack.yaml', '**/package.yaml') }}-${{ hashFiles('**/*.hs') }} restore-keys: | + stack-${{ runner.os }}-${{ hashFiles('stack.yaml', '**/package.yaml') }}- stack-${{ runner.os }}- - - name: Install dependencies - run: stack build --only-dependencies + - name: Build dependencies + run: stack build --test --bench --only-dependencies - - name: Build project - run: stack build + - name: Build + run: stack build --test --bench --no-run-tests --no-run-benchmarks - - name: Run tests - env: - DISTRIBUTORS_RUN_DOCTESTS: "1" + - name: Test run: stack test + + cabal: + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + ghc: ["9.10.3", "9.12.4"] + steps: + - uses: actions/checkout@v4 + + - name: Set up GHC & Cabal + id: setup + uses: haskell-actions/setup@v2 + with: + ghc-version: ${{ matrix.ghc }} + cabal-update: true + + - name: Plan the build + run: | + cabal configure --enable-tests --enable-benchmarks + cabal build all --dry-run + + - name: Cache the Cabal store + uses: actions/cache@v4 + with: + path: ${{ steps.setup.outputs.cabal-store }} + key: cabal-${{ runner.os }}-${{ matrix.ghc }}-${{ hashFiles('dist-newstyle/cache/plan.json') }} + restore-keys: cabal-${{ runner.os }}-${{ matrix.ghc }}- + + - name: Build dependencies + run: cabal build all --only-dependencies + + - name: Build + run: cabal build all + + - name: Test + run: cabal test all --test-show-details=direct + + - name: Check packages + run: | + for package in distributors-core distributors-grammar distributors-json; do + (cd "$package" && cabal check) + done + + nix: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - uses: DeterminateSystems/nix-installer-action@v16 + + - uses: DeterminateSystems/magic-nix-cache-action@v8 + + - name: Build & check the flake + run: nix flake check -L diff --git a/.gitignore b/.gitignore index 972ef579..f866aee4 100644 --- a/.gitignore +++ b/.gitignore @@ -16,6 +16,7 @@ cabal.sandbox.config *.hp *.eventlog .stack-work/ +.stack-*/ cabal.project.local .DS_Store stack.yaml.lock @@ -24,3 +25,4 @@ tags .*.swp .qodo SCRATCH* +.ghc.environment.* diff --git a/.hlint.yaml b/.hlint.yaml new file mode 100644 index 00000000..c30aa497 --- /dev/null +++ b/.hlint.yaml @@ -0,0 +1,99 @@ +# HLint configuration file +# https://github.com/ndmitchell/hlint +########################## + +# This file contains a template configuration file, which is typically +# placed as .hlint.yaml in the root of your project + + +# Warnings currently triggered by your code +- ignore: {name: "Avoid lambda"} # 17 hints +- ignore: {name: "Avoid lambda using `infix`"} # 1 hint +- ignore: {name: "Eta reduce"} # 21 hints +- ignore: {name: "Functor law"} # 1 hint +- ignore: {name: "Monoid law, left identity"} # 1 hint +- ignore: {name: "Monoid law, right identity"} # 1 hint +- ignore: {name: "Redundant bracket"} # 3 hints +- ignore: {name: "Redundant toList"} # 1 hint +- ignore: {name: "Use $>"} # 2 hints +- ignore: {name: "Use :"} # 1 hint +- ignore: {name: "Use =<<"} # 1 hint +- ignore: {name: "Use catMaybes"} # 1 hint +- ignore: {name: "Use const"} # 11 hints +- ignore: {name: "Use fewer imports"} # 14 hints +- ignore: {name: "Use fmap"} # 1 hint +- ignore: {name: "Use mapMaybe"} # 2 hints +- ignore: {name: "Use newtype instead of data"} # 1 hint +- ignore: {name: "Use traverse"} # 1 hint +- ignore: {name: "Use tuple-section"} # 3 hints +- ignore: {name: "Use void"} # 1 hint + + +# Specify additional command line arguments +# +# - arguments: [--color, --cpp-simple, -XQuasiQuotes] + + +# Control which extensions/flags/modules/functions can be used +# +# - extensions: +# - default: false # all extension are banned by default +# - name: [PatternGuards, ViewPatterns] # only these listed extensions can be used +# - {name: CPP, within: CrossPlatform} # CPP can only be used in a given module +# +# - flags: +# - {name: -w, within: []} # -w is allowed nowhere +# +# - modules: +# - {name: [Data.Set, Data.HashSet], as: Set} # if you import Data.Set qualified, it must be as 'Set' +# - {name: Control.Arrow, within: []} # Certain modules are banned entirely +# +# - functions: +# - {name: unsafePerformIO, within: []} # unsafePerformIO can only appear in no modules + + +# Add custom hints for this project +# +# Will suggest replacing "wibbleMany [myvar]" with "wibbleOne myvar" +# - error: {lhs: "wibbleMany [x]", rhs: wibbleOne x} + +# The hints are named by the string they display in warning messages. +# For example, if you see a warning starting like +# +# Main.hs:116:51: Warning: Redundant == +# +# You can refer to that hint with `{name: Redundant ==}` (see below). + +# Turn on hints that are off by default +# +# Ban "module X(module X) where", to require a real export list +# - warn: {name: Use explicit module export list} +# +# Replace a $ b $ c with a . b $ c +# - group: {name: dollar, enabled: true} +# +# Generalise map to fmap, ++ to <> +# - group: {name: generalise, enabled: true} +# +# Warn on use of partial functions +# - group: {name: partial, enabled: true} + + +# Ignore some builtin hints +# - ignore: {name: Use let} +# - ignore: {name: Use const, within: SpecialModule} # Only within certain modules + + +# Define some custom infix operators +# - fixity: infixr 3 ~^#^~ + + +# To generate a suitable file for HLint do: +# $ hlint --default > .hlint.yaml + +# Some modules name variables `pattern`. +- arguments: [-XNoPatternSynonyms] + +# Printor matches its pairs strictly, for speed. +- ignore: {name: "Use first", within: Data.Profunctor.Grammar} +- ignore: {name: "Use snd", within: Data.Profunctor.Grammar} diff --git a/CHANGELOG.md b/CHANGELOG.md deleted file mode 100644 index 83402d2c..00000000 --- a/CHANGELOG.md +++ /dev/null @@ -1,130 +0,0 @@ -# Changelog for `distributors` - -## 0.6.0.0 - 2026-04-24 - -### New Module - -- Added `Control.Lens.Grammar.Machine` as the transducer/matching runtime layer. - -### New Types - -- Added `Transducer` and `TransducerStep` as the finite-state representation for - compiled grammar machines. - -### New APIs (Machine Runtime) - -- Added `transducer` to compile `Bnf (RegEx token)` into `Transducer`. -- Added `parseForest` to reconstruct parse forests with rule labels and token spans/slices, - returning the remaining unparsed suffix. -- Added `expectNext` to compute scanner-frontier expected token classes after a prefix. -- Added `languageSample` to lazily enumerate sampled language words from shortest length upward. -- Added `unreachableRules` to report dead nonterminals unreachable from the start expression. - -### Internal Machinery - -- Implemented Thompson-style transducer construction over `RegEx`-extended BNF. -- Implemented Earley-style chart runtime (`initialChart`, `closeChartAt`, `scanClassOptions`, - `prefixGen`) with predict/complete closure and scanner grouping. -- Added completion-time caller indexing/cache optimizations and precomputed rule nullability/first-state - indexing to speed machine execution. - -### Grammar Integration - -- `Control.Lens.Grammar` now exposes machine-backed generators: - `transducerG` and the parse-forest examples/docs built on the Machine runtime. - -## 0.5.0.0 - 2026-04-16 - -### Changes - -- `MonadTry` now implies `BackusNaurForm` (so `rule` tracing/failure semantics are available) - and `Filtrator` (via `MonadPlus`, with `filtrate = mfiltrate`). -- Simplified the default implementation of `terminal`. -- Added `applicativeG` and `monadG` generators via `Joker` orphan and non-orphan instances. -- Made nomenclature consistent with use of "fail" and "failure", not "error". - -### Internal - -- Moved orphan instances and Template Haskell internals to `Control.Lens.Grammar.Internal`. - -### Documentation - -- Expanded `BackusNaurForm` documentation with separate motivation from: - category-theoretic structure and failure-tracing semantics (both called “trace” - in different senses, and combined by BNF-style rules). -- Added a `monadG` Megaparsec example. -- Fixed typo in the `makeNestedPrisms` example. - -## 0.4.0.0 - 2026-04-10 - -### New Modules - -- `Control.Monad.Fail.Try` - `MonadTry` class with `try` & `fail` for backtracking parsers -- `Data.Profunctor.Grammar.Parsector` - Invertible LL(1) parser with Parsec-style failure reporting: - `ParsecState`, `ParsecFailure`, `parsecP`, `unparsecP`; implements hints, LL(1) commitment - via `parsecLooked`, and `try` for explicit backtracking -- `Data.Profunctor.Separator` - Separator/delimiter combinators: `sepWith`, `noSep`, - `beginWith`, `endWith`, `several`, `several1`, `intercalateP`, `chain`, `chain1` -- `Data.Traversable.Homogeneous` - `Homogeneous` class for static containers with uniform elements; - `ditraverse` for distributive traversals - -### New Combinators - -- `Control.Lens.Grammar.Kleene`: `tokenClass` embedding into `RegEx`; `KleeneAlgebra` laws - as QuickCheck properties; `RegExam` helpers `failExam`, `passExam`, `isFailExam` -- `Control.Lens.Grammar.Boole`: `trueB`, `falseB` added to `BooleanAlgebra`; - `andB`, `orB`, `allB`, `anyB` fold combinators -- `Data.Profunctor.Monadic`: `MonadicTry` constraint alias; `P.return` combinator; - improved documentation for qualified do-notation pattern bonding -- `Data.Profunctor.Distributor`: `manyP` / `optionalP` now place the empty case on - the right of `>+<` for correct LL(1) behaviour (`p >*< manyP p >+< oneP`) - -### Changes - -- `<|>` in `Parsector` now commits when the left branch consumes input (LL(1)); - use `try` to opt into backtracking -- `TokenTest` renamed to `TokenClass` throughout -- `chain`, `chain1`, `intercalateP` moved from `Data.Profunctor.Distributor` - to the new `Data.Profunctor.Separator` -- `BackusNaurForm`: `rule` documentation clarified; added reference to Breitner's - *Showcasing Applicative* - -### Testing - -- `test/Properties/Kleene` - QuickCheck properties for `KleeneStarAlgebra`, - `TokenAlgebra`, `BooleanAlgebra TokenClass` -- `test/Examples/Chain` - Chain grammar example -- `test/Main`: `testCtxGrammarExample` extended with `parsecG` / `unparsecG` round-trip checks - -## 0.3.0.0 - 2026-02-05 - -### New Modules - -- `Control.Lens.Grammar` - Grammar hierarchy based on Chomsky's formal grammar classification -- `Control.Lens.Grammar.BackusNaur` - Context-free grammar combinators (BNF) -- `Control.Lens.Grammar.Boole` - Boolean algebra for grammars -- `Control.Lens.Grammar.Kleene` - Regular expression combinators -- `Control.Lens.Grammar.Symbol` - Symbol-level grammar primitives -- `Control.Lens.Grammar.Token` - Token-level grammar primitives -- `Data.Profunctor.Filtrator` - Filterable profunctors -- `Data.Profunctor.Grammar` - Grammar profunctor abstraction -- `Data.Profunctor.Monadic` - Monadic profunctor combinators with QualifiedDo support -- `Data.Profunctor.Monoidal` - Monoidal profunctor combinators - -### Removed Modules - -- `Text.Grammar.Distributor` - Functionality split into the new modules above - -### Testing - -- Added `doctest` for documentation testing -- New test examples: Arithmetic, Json, Lambda, LenVec, RegString, SemVer, SExpr - -## 0.2.0.0 - 2025-07-08 - -Added some combinators for `RegEx`es. Updated documentation. - -## 0.1.0.0 - -First version with profunctorial interpretation of invertible syntax. - diff --git a/README.md b/README.md index 18cfd50a..a80c5892 100644 --- a/README.md +++ b/README.md @@ -1,44 +1,38 @@ -# Distributors -## Unifying Parsers, Printers & Grammars +# distributors -[![GithubWorkflowCI](https://github.com/morphismtech/distributors/actions/workflows/ci.yml/badge.svg)](https://github.com/morphismtech/distributors/actions/workflows/ci.yml) +Unifying parsers, printers & grammars, in three packages: -[Github](https://github.com/morphismtech/distributors) +- [`distributors-core`](distributors-core): the `distributors` package, + of profunctor algebra & optics for invertible syntax. +- [`distributors-grammar`](distributors-grammar): the + `distributors-grammar` package, of grammars, which parse, print & + generate together. +- [`distributors-json`](distributors-json): the `distributors-json` + package, of JSON grammars, compatible with `aeson` & typed in TypeScript. -[Hackage](https://hackage.haskell.org/package/distributors) +## Building -[YouTube](https://www.youtube.com/watch?v=tZErj7XYpVI) +With Stack: -This library provides mathematically inspired abstractions for coders to write parsers that can also be inverted to printers. +```sh +stack build --test --bench +DISTRIBUTORS_RUN_DOCTESTS=1 stack test +``` -## introduction -The term "distributor" is a synonym for "[profunctor](https://ncatlab.org/nlab/show/profunctor)". Jean Bénabou who invented the term and originally used “profunctor,” then preferred “[distributor](http://www.entretemps.asso.fr/maths/Distributors.pdf)”, which is supposed to carry the intuition that a distributor generalizes a functor in a similar way to how a distribution generalizes a function. +With Cabal: -[Bénabou](http://cahierstgdc.com/wp-content/uploads/2022/07/F.-BORCEUX-LXIII-3.pdf) in his time introduced the notions of enriched categories, bicategories as well as distributors and invented the term monad. He was lost to us on 11, February 2022 and this library is dedicated to his memory. +```sh +cabal build all +cabal test all +``` -Since "profunctor" became the standard nomenclature, we reappropriate "distributor" to describe a profunctor on a [distributive category](https://ncatlab.org/nlab/show/distributive+category). +With Nix: -This library provides a study of distributor theory and optics, -and their application to invertible grammar theory. +```sh +nix build .#distributors-json +nix flake check +nix develop # a shell with GHC, Cabal, HLint & hpack +``` -## previous work - -The results concerning invertible parsers are a profunctorial interpretation of [Invertible Syntax Descriptions](https://www.mathematik.uni-marburg.de/~rendel/rendel10invertible.pdf) by Tillman Rendel & Klaus Ostermann. - -While `Distributor`s in the library are lax distributive endoprofunctors, a mathematical treatment of strong (i.e. with invertible structure morphisms) distributors is given by Travis Squires in [Profunctors and Distributive Categories](https://central.bac-lac.gc.ca/.item?id=MR31635). - -The idea for unifying Backus-Naur grammars with parsers comes from Joachim Breitner in a post [Showcasing Applicative](https://www.joachim-breitner.de/blog/710-Showcasing_Applicative). - -The idea for using monadic profunctors for reversible context-sensitive grammars -comes from Li-Yao Xia, in some posts and a paper but particularly -this post on [Monadic profunctors for bidirectional programming](https://blog.poisson.chat/posts/2017-01-01-monadic-profunctors.html). - -The person deserving the most credit for bringing the power of optics to programming, with his [lens library](https://github.com/ekmett/lens/), is Ed Kmett, to whom I am very grateful for teaching me a lot. - -None of the ideas in this library are particularly original and a lot of related ideas have been explored, in Tom Ellis' [product-profunctors](https://github.com/tomjaguarpaw/product-profunctors) as well as Sjoerd Visscher's [one-liner](https://github.com/sjoerdvisscher/one-liner) and more. Such explorations are _not_ limited to Haskell. Brandon Williams and Stephen Celis' excellent [swift-parsing](https://github.com/pointfreeco/swift-parsing) was also influenced by invertible parser theory. - -Some optics in this library are [grates, a new kind of optic](https://r6research.livejournal.com/28050.html), discovered by Russel O'Connor and James Deikun; monocles which are studied by Alexandre Garcia de Oliveira, Mauro Jaskelioff, and Ana Cristina Vieira de Melo in [On Structuring Functional Programs with Monoidal Profunctors](https://arxiv.org/abs/2207.00852); and withers, discovered by Chris Penner in [Composable filters using Witherable optics](https://chrispenner.ca/posts/witherable-optics). - -## contributing - -Contributors are welcome. The [Issues](https://github.com/morphismtech/distributors/issues) page is a good place to communicate. +Each package's `.cabal` file is generated from its `package.yaml`, +by `hpack`, which Stack runs. diff --git a/cabal.project b/cabal.project new file mode 100644 index 00000000..3e190f1e --- /dev/null +++ b/cabal.project @@ -0,0 +1,10 @@ +packages: + distributors-core + distributors-grammar + distributors-json + +tests: True +benchmarks: True + +-- doctest-parallel finds the built packages by their GHC environment file. +write-ghc-environment-files: always diff --git a/distributors-core/CHANGELOG.md b/distributors-core/CHANGELOG.md new file mode 100644 index 00000000..f09aebf4 --- /dev/null +++ b/distributors-core/CHANGELOG.md @@ -0,0 +1,369 @@ +# Changelog for `distributors` + +## Unreleased + +### New APIs + +- Kleene quantifiers: `quantK`, a `KleeneStarAlgebra` method, & `quantP`, + 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 `quantP`. +- 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. +- `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`. +- `ctxList` & 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. +- `ctxTree`, 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 `ctxList` 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`. +- `Comonocle`s, in `Control.Lens.Comonocle`, dual to `Monocle`s by sums: + `comonocle`, `_Enumerable`, `_BoundedEnum`, & concrete + `Comonocular`s, with `runComonocular`. +- `WrappedPafb f p` is `CocartesianMonoidal` for any `Functor f`. +- `AComonocle`, `withComonocle`, `cloneComonocle`, `mapComonocle`, + `altComonocle`, `alongsideComonocle`, `indexComonocle` & + `zipWithComonocle`; & `crossMonocle`. +- `Ditraversal`s, a secondary concrete representation of `Monocle`s, + by `Traversable` & `Distributive` homogeneous products, + with `ditraversal` & `withDitraversal`. +- Enum-like optics & functions of `Enumerable`s: the prism + `fromEnumerable`, the partial isos `succEnumerable` & `predEnumerable`, + `enumerateFrom`, `enumerateFromThen`, `enumerateFromTo` & + `enumerateFromThenTo`; & of `Comonocle`s: the prism `fromComonocle`, + the partial isos `succComonocle` & `predComonocle`, `enumerateComonocle`, + `enumerateFromThenComonocle`, `enumerateFromToComonocle` & + `enumerateFromThenToComonocle`. +- `Homogeneous` & `Enumerable` instances for `Down`, `Min`, `Max`, + `First`, `Last`, `Alt f`, `Ap f` & `IdentityT f`. +- `Homogeneous` & `Enumerable` instances for `(,) e`, a copy for each tag + of a `Bounded` `Enum`, summed in a balanceBy tree. +- A `Homogeneous` instance for `NonEmpty`. +- Dual combinators: `copiesComonocle`, the `Prism`s of a `Comonocle`'s + copies, exactly one of which matches, & `fociMonocle`, the `Lens`es of + a `Monocle`'s foci, every one of which focuses. +- `Prismoid`s move to their own module, `Control.Lens.Prismoid`, from + `Control.Lens.Bifocal`, with `opted`, `lefted`, `righted`, `chain1` & + `chain`; & new `exactly`, `atLeast`, `atMost` & `inRange`. +- `sepBy sep pat p`, running any `Prismoid` with a separator between + consecutive foci, by the `Alternator`'s own `manyP`, `someP`, + `optionalP` & `optionP`, preferring foci, greedily; so + `sepBy sep several`, `sepBy sep (atLeast 1)`, `sepBy sep (chain1 assoc pat)` + & `sepBy sep (exactly n)` sequence lists, binary constructor + patterns & repetitions, separated. Delimiters compose around it. +- `Varifocal`s, in `Control.Lens.Varifocal`, context-sensitive optics + whose shape may depend on the foci they build: `Bifocal` ⊂ `Varifocal`, + their `Applicative` the monad of a `MonadicTrans` profunctor, absorbed + by `joinP`; with `Varifocal'`; the applicators `contextually`, in any + `Monadic` `Alternator`, like a `CtxGrammar`, by its free concrete form + `Varifocus`, & `contextuallyT`, on a `MonadicTrans` profunctor; + `AVarifocal`, `varifocus`, `runVarifocus`, `runVarifocusT` & + `cloneVarifocal`; `crossVarifocal`, `altVarifocal`, `orVarifocal` + & `bindVarifocal`, + the last choosing a second by what the first built, like a netstring; & `ctxList`, a deterministic machine over foci, + deciding by each built whether to continue, stop or reject, with its + instances `terminateBy`, `delimitBy`, `balanceBy` & `countWith`: + sentinel-terminated, matching-delimitBy, nested & count-prefixed + sequences, which no `Bifocal` can express. +- Combinators of optics with the same foci: `crossPrismoid`, + `crossBifocal`, `crossDiopter` & `crossGrate`, on pairs; `altPrismoid`, + `altBifocal` & `altDiopter`, on `Either`s; & `orPrismoid` & `orBifocal`, + disjoining two on the same source by `>|<`, with the units + `oneOptic`, `zeroOptic` & `falseOptic`, of the crosses, alts & ors, + by inclusion, of every optic which has them. +- `MonadicTrans`, in `Data.Profunctor.Monadic`, profunctors transforming a + monad, lifting its effects by `liftP` & absorbing them by `joinP`. +- `skipManyP` & `skipOptionalP`, zero or more, & zero or one, skipped: + sequencing actions forwards & none backwards, like whitespace or a + trailing separator, which a parser accepts & a printer omits; & their + `Diopter`s, `skippedMany` & `skippedOptional`. +- `inRange lo hi`, a `Prismoid` of between some numbers of times, at least + @lo@ & at most @hi@, if @Just@, like a regular expression's @{lo,hi}@ or + @{lo,}@; & its intervals `exactly`, `atLeast` & `atMost`. +- `listed`, in `Control.Lens.PartialIso`, a list of items as an `IsList`, + `iso fromList toList`: act on an `IsList` as on lists by `listed ~< p`. +- `manyTillP`, an `Alternator` method, zero or more, then the rest, + @p* q@, trying the rest first, like parsec's @manyTill@, which a static + `Alternator` defines without recursing, as @starK p <> q@. +- `>?*`, the action of a `Prismoid` on `Alternator`s, applying it directly, + without a concrete form, so the `Alternator`'s own methods act. +- `Prismatoid`, the concrete form of `Prismoid`s, a partial `Dioptrice`, + with `APrismoid`, `prismoid`, `withPrismoid`, `clonePrismoid` & + `runPrismatoid`. +- Secondary concrete representations: `Prismocular`s of `Prismoid`s, + probing by `Alternative`s, with `runPrismocular`, `prismocular` & + `withPrismocular`; `Spectacle`s of `Bifocal`s, by `Homogeneous` + shapes with partial merges, with `runSpectacle`, `spectacle` & + `withSpectacle`; & `Diffraction`s of `Grate`s, by `Distributive` + shapes, with `diffraction` & `withDiffraction`. +- `lengthPrepend`, in `Data.Profunctor.Monadic`, a count, then that many + repetitions, which depend on the count built. +- `satisfied` is a homomorphism of predicates' `BooleanAlgebra`s, to the + `DisjunctiveMonoid` of partial functions, choosing by first success in + either direction, by which `withOperators` tries its unary operators. +- `genericNestedPrism` & `genericNestedIso`, in `Control.Lens.Prism.Nested` + & re-exported by `Control.Lens.PartialIso`, the `Prism`s & `Iso`s that + `makeNestedPrisms` generates, focusing fields as right-nested pairs, + by `GHC.Generics` rather than Template Haskell, taking the type, & + for a `Prism` the constructor's name as a `Symbol`, as required type + arguments, like @genericNestedPrism Shape "Rect"@; a type sharing its + constructor's name is @(type Point)@, by @ExplicitNamespaces@. +- `orPartialIso`, the union of two patterns, trying the first, then the + second, in either direction, with its unit `falsePartialIso`. + +### Performance + +- `exactly`, `atLeast`, `atMost` & `inRange` sequence their foci at the + target itself, & its `Applicative` once: 25-34% faster printing & + Parsector parsing of counted repetitions. +- `withOperators` prints left-associated chains in linear time, not + quadratic. +- `Distributor`'s default `manyP` ties its knot, building its action once. + +### Bug Fixes + +- `Grating` is `Profunctor` & `Closed`, so every `Grate`, & so every + `Monocle`, is `AGrate`, for `withGrate`, `cotraverseOf` & co. + +### Breaking Changes + +- `mapBifocal` is replaced by `>?<*`, `Bifocal`'s applicator, which + applies a `Bifocal` directly at a partial `Alternator`, keeping its own + methods, like `optionP`, as `>?*` does a `Prismoid`'s, & ~25% faster + than through a `Spectacle`. Apply `ABifocal` by `cloneBifocal`. +- `Control.Lens.Internal.Distributor.NestedPrismTH` is renamed + `Control.Lens.Prism.Nested`. +- `crossPartialIso` ~> `alongsidePartialIso` & `altPartialIso` ~> + `withoutPartialIso`, after lens's `alongside` & `without`, since they + pair & sum differing foci, unlike the crosses & alts of the same foci. +- `withoutPartialIso` & `alongsidePartialIso` keep a `Prism`'s passing a mismatch + through, a pair only where both components pass through. +- `>?<` passes a mismatch through by `Choice`, as `>?` does, so a + `Prism` acts by `>?<` as by `>?`. +- `PartialExchange` is removed. `APartialIso` is by `PartialMarket`s, + so `clonePartialIso` is the identity, keeping a `Prism`'s passing a + mismatch through; `withPartialIso pattern partialIso` rebuilds a + `PartialIso` from its partial functions, failing on a mismatch instead. +- `Bifocal`s need `(Alternator p, Applicative f, Filterable f)`, dropping + `Filtrator p` & `Alternative f`, which `Filterable f` provides, as it + does `PartialIso`'s `Cochoice`. +- `ABifocal` is by `Spectacle`s, matching shapes once, rather than by + `Binocular`s, whose probes rematch from the source, quadratically, & + unroll repetition, so `cloneBifocal` & `mapBifocal` of repeating + `Bifocal`s like `atLeast 1` diverged at static `Profunctor`s. +- The `base` lower bound is 4.20 (GHC 9.10). +- `Prismoid`s need `(Alternator p, Applicative f)`, rather than an + `Alternative f`, failing by their `Alternator` alone, so that they have + a concrete form, `Prismatoid`. +- `Witheroid` & `witherPrism` are removed: a `Witheroid`'s `Alternative f` + could fail backwards, without a concrete form, & `witherPrism` is + `clonePartialIso`, with `catMaybes (pure Nothing)` for `empty`, as + `withered`'s documentation shows. + +- `imprism` & the orphan `Applicative (Market a b s)` are removed: a + `Monocle` without foci made an improper `Prism` breaking even + @preview l (review l b) = Just b@. + +- `Filtroid`, `unlefted` & `unrighted` are removed: by `Filtrator`'s laws, + its `Cochoice` derives from `Profunctor` & `Filterable`, so an optic for + `Filtrator`s may only map its source & filter its target, as a + `filterPrism` does. Use `filterPrism _Left` & `filterPrism _Right`. +- `coPrism` is renamed `filterPrism`, a filter pattern of a `Prism`, + since the coprism, the action of a reversed `Prism`, is `?<`. + +- `PartialIso` drops its `Cochoice` constraint, failing by `Filterable` + alone, so `preview`, `^?`, `has` & `toListOf` terminate on a + `PartialIso` which fails to match, rather than looping in `Cochoice (->)`. + `partialIso` is the action `dimapMaybe` on @p a (f b)@. + Its action `>?<` on `Choice` & `Cochoice` profunctors is unchanged. +- `Filtrator`'s laws are that `filtrate` is a retraction of `alternate`, + rather than an inverse of `>+<`, which fails for left-biased & + predictive parsers, & for profunctors which cross summands. +- `Filtrator (Star f)` is removed, since `Star`'s `Cochoice` retries + the other summand where `filtrate` drops it, breaking + `unright = snd . filtrate`. +- `KleeneStarAlgebra (Ap f k)` is removed, since a left-biased `f`, + like `Maybe`, breaks `optK x = mempty >|< x = x >|< mempty`. +- `Enumerable`, its functions & `Indexing`, renamed `Enumerator`, move from + `Data.Traversable.Homogeneous` to `Data.Traversable.Homogeneous.Enumerable`. +- `Comonocle`s & their combinators move from `Control.Lens.Monocle` to + their own module, `Control.Lens.Comonocle`. +- `Data.Profunctor.Separator` merges into `Control.Lens.Prismoid`: + `Operator`, `Assoc` & `withOperators`. +- `manied`, `chained1` & `chained` are renamed `several`, `chain1` & + `chain`, & `somed` is `atLeast 1`, replacing the `SepBy` combinators + `several`, `chain1` & `chain`, which `sepBy` of them replaces: + `several sep p` is `sepBy sep several p`, of lists, & + `listed ~< sepBy sep several p` of other `IsList`s; + `several1 sep p` is `sepBy sep (atLeast 1) p`; + `chain1 assoc pat sep p` is `sepBy sep (chain1 assoc pat) p`; & + `intercalateP n sep p` is `sepBy sep (exactly n) p`. +- `SepBy` & `noSep` are removed, & `sepBy` is now the action of a + `Prismoid` with a separator, rather than a `SepBy` smart constructor: + delimiters compose around it, `beg >* sepBy sep pat p *< end`; with + no separator, `sepBy oneP pat = (pat >?*)`. +- The grammars move to their own package, `distributors-grammar`: + `Control.Lens.Grammar` & its `BackusNaur`, `Machine`, `RegEx`, `Symbol` + & `Token` modules, `Control.Monad.Fail.Try`, `Data.Profunctor.Grammar` + & `Data.Profunctor.Grammar.Parsector`. So `distributors` no longer + depends on `QuickCheck`, `random`, `MemoTrie`, `monad-loops` or `mtl`. +- `Control.Lens.Grammar.Internal.NestedPrismTH` & `.Orphanage` are renamed + `Control.Lens.Internal.Distributor.NestedPrismTH` & `.Orphanage`. +- `Operator`'s `Infix`, `Prefix` & `Postfix` take `APrism`s, rather than + `APartialIso`s, so that `withOperators` builds every operator it parses, + rather than failing by `error`, or dropping prefix & postfix operators. +- `Data.Profunctor.Monadic` splits: its qualified do-notation, `>>=`, + `>>`, `return` & `fail`, moves to `Data.Profunctor.Monadic.Do`, to import + qualified, leaving `Monadic` to import unqualified, with no names + conflicting with the `Prelude`. +- `MonadicTry` moves from `Data.Profunctor.Monadic` to + `Control.Monad.Fail.Try`, which `Data.Profunctor.Monadic` no longer + imports, & `Data.Profunctor.Monadic` no longer re-exports `try`. +- `sepWith` moves to `Control.Lens.Grammar.Symbol` & takes a `Prismoid`, + `sepWith str = sepBy (terminal str)`, so `several1 (sepWith ",") p` is + `sepWith "," (atLeast 1) p`; `beginWith` & `endWith` are removed, as + delimiters compose around it by `>*` & `*<`. + +## 0.6.0.0 - 2026-04-24 + +### New Module + +- Added `Control.Lens.Grammar.Machine` as the transducer/matching runtime layer. + +### New Types + +- Added `Transducer` and `TransducerStep` as the finite-state representation for + compiled grammar machines. + +### New APIs (Machine Runtime) + +- Added `transducer` to compile `Bnf (RegEx token)` into `Transducer`. +- Added `parseForest` to reconstruct parse forests with rule labels and token spans/slices, + returning the remaining unparsed suffix. +- Added `expectNext` to compute scanner-frontier expected token classes after a prefix. +- Added `languageSample` to lazily enumerate sampled language words from shortest length upward. +- Added `unreachableRules` to report dead nonterminals unreachable from the start expression. + +### Internal Machinery + +- Implemented Thompson-style transducer construction over `RegEx`-extended BNF. +- Implemented Earley-style chart runtime (`initialChart`, `closeChartAt`, `scanClassOptions`, + `prefixGen`) with predict/complete closure and scanner grouping. +- Added completion-time caller indexing/cache optimizations and precomputed rule nullability/first-state + indexing to speed machine execution. + +### Grammar Integration + +- `Control.Lens.Grammar` now exposes machine-backed generators: + `transducerG` and the parse-forest examples/docs built on the Machine runtime. + +## 0.5.0.0 - 2026-04-16 + +### Changes + +- `MonadTry` now implies `BackusNaurForm` (so `rule` tracing/failure semantics are available) + and `Filtrator` (via `MonadPlus`, with `filtrate = mfiltrate`). +- Simplified the default implementation of `terminal`. +- Added `applicativeG` and `monadG` generators via `Joker` orphan and non-orphan instances. +- Made nomenclature consistent with use of "fail" and "failure", not "error". + +### Internal + +- Moved orphan instances and Template Haskell internals to `Control.Lens.Grammar.Internal`. + +### Documentation + +- Expanded `BackusNaurForm` documentation with separate motivation from: + category-theoretic structure and failure-tracing semantics (both called “trace” + in different senses, and combined by BNF-style rules). +- Added a `monadG` Megaparsec example. +- Fixed typo in the `makeNestedPrisms` example. + +## 0.4.0.0 - 2026-04-10 + +### New Modules + +- `Control.Monad.Fail.Try` - `MonadTry` class with `try` & `fail` for backtracking parsers +- `Data.Profunctor.Grammar.Parsector` - Invertible LL(1) parser with Parsec-style failure reporting: + `ParsecState`, `ParsecFailure`, `parsecP`, `unparsecP`; implements hints, LL(1) commitment + via `parsecLooked`, and `try` for explicit backtracking +- `Data.Profunctor.Separator` - Separator/delimiter combinators: `sepWith`, `noSep`, + `beginWith`, `endWith`, `several`, `several1`, `intercalateP`, `chain`, `chain1` +- `Data.Traversable.Homogeneous` - `Homogeneous` class for static containers with uniform elements; + `ditraverse` for distributive traversals + +### New Combinators + +- `Control.Lens.Grammar.Kleene`: `tokenClass` embedding into `RegEx`; `KleeneAlgebra` laws + as QuickCheck properties; `RegExam` helpers `failExam`, `passExam`, `isFailExam` +- `Control.Lens.Grammar.Boole`: `trueB`, `falseB` added to `BooleanAlgebra`; + `andB`, `orB`, `allB`, `anyB` fold combinators +- `Data.Profunctor.Monadic`: `MonadicTry` constraint alias; `P.return` combinator; + improved documentation for qualified do-notation pattern bonding +- `Data.Profunctor.Distributor`: `manyP` / `optionalP` now place the empty case on + the right of `>+<` for correct LL(1) behaviour (`p >*< manyP p >+< oneP`) + +### Changes + +- `<|>` in `Parsector` now commits when the left branch consumes input (LL(1)); + use `try` to opt into backtracking +- `TokenTest` renamed to `TokenClass` throughout +- `chain`, `chain1`, `intercalateP` moved from `Data.Profunctor.Distributor` + to the new `Data.Profunctor.Separator` +- `BackusNaurForm`: `rule` documentation clarified; added reference to Breitner's + *Showcasing Applicative* + +### Testing + +- `test/Properties/Kleene` - QuickCheck properties for `KleeneStarAlgebra`, + `TokenAlgebra`, `BooleanAlgebra TokenClass` +- `test/Examples/Chain` - Chain grammar example +- `test/Main`: `testCtxGrammarExample` extended with `parsecG` / `unparsecG` round-trip checks + +## 0.3.0.0 - 2026-02-05 + +### New Modules + +- `Control.Lens.Grammar` - Grammar hierarchy based on Chomsky's formal grammar classification +- `Control.Lens.Grammar.BackusNaur` - Context-free grammar combinators (BNF) +- `Control.Lens.Grammar.Boole` - Boolean algebra for grammars +- `Control.Lens.Grammar.Kleene` - Regular expression combinators +- `Control.Lens.Grammar.Symbol` - Symbol-level grammar primitives +- `Control.Lens.Grammar.Token` - Token-level grammar primitives +- `Data.Profunctor.Filtrator` - Filterable profunctors +- `Data.Profunctor.Grammar` - Grammar profunctor abstraction +- `Data.Profunctor.Monadic` - Monadic profunctor combinators with QualifiedDo support +- `Data.Profunctor.Monoidal` - Monoidal profunctor combinators + +### Removed Modules + +- `Text.Grammar.Distributor` - Functionality split into the new modules above + +### Testing + +- Added `doctest` for documentation testing +- New test examples: Arithmetic, Json, Lambda, LenVec, RegString, SemVer, SExpr + +## 0.2.0.0 - 2025-07-08 + +Added some combinators for `RegEx`es. Updated documentation. + +## 0.1.0.0 + +First version with profunctorial interpretation of invertible syntax. + diff --git a/LICENSE b/distributors-core/LICENSE similarity index 100% rename from LICENSE rename to distributors-core/LICENSE diff --git a/distributors-core/README.md b/distributors-core/README.md new file mode 100644 index 00000000..9e3c9b7d --- /dev/null +++ b/distributors-core/README.md @@ -0,0 +1,88 @@ +# Distributors +## Unifying Parsers, Printers & Grammars + +[![GithubWorkflowCI](https://github.com/morphismtech/distributors/actions/workflows/ci.yml/badge.svg)](https://github.com/morphismtech/distributors/actions/workflows/ci.yml) + +[Github](https://github.com/morphismtech/distributors) + +[Hackage](https://hackage.haskell.org/package/distributors) + +[YouTube](https://www.youtube.com/watch?v=tZErj7XYpVI) + +This library provides mathematically inspired abstractions for coders to write parsers that can also be inverted to printers. + +## introduction +The term "distributor" is a synonym for "[profunctor](https://ncatlab.org/nlab/show/profunctor)". Jean Bénabou who invented the term and originally used “profunctor,” then preferred “[distributor](http://www.entretemps.asso.fr/maths/Distributors.pdf)”, which is supposed to carry the intuition that a distributor generalizes a functor in a similar way to how a distribution generalizes a function. + +[Bénabou](http://cahierstgdc.com/wp-content/uploads/2022/07/F.-BORCEUX-LXIII-3.pdf) in his time introduced the notions of enriched categories, bicategories as well as distributors and invented the term monad. He was lost to us on 11, February 2022 and this library is dedicated to his memory. + +Since "profunctor" became the standard nomenclature, we reappropriate "distributor" to describe a profunctor on a [distributive category](https://ncatlab.org/nlab/show/distributive+category). + +This library provides a study of distributor theory and optics, +and their application to invertible grammar theory. + +## previous work + +The results concerning invertible parsers are a profunctorial interpretation of [Invertible Syntax Descriptions](https://www.mathematik.uni-marburg.de/~rendel/rendel10invertible.pdf) by Tillman Rendel & Klaus Ostermann. + +While `Distributor`s in the library are lax distributive endoprofunctors, a mathematical treatment of strong (i.e. with invertible structure morphisms) distributors is given by Travis Squires in [Profunctors and Distributive Categories](https://central.bac-lac.gc.ca/.item?id=MR31635). + +The idea for unifying Backus-Naur grammars with parsers comes from Joachim Breitner in a post [Showcasing Applicative](https://www.joachim-breitner.de/blog/710-Showcasing_Applicative). + +The idea for using monadic profunctors for reversible context-sensitive grammars +comes from Li-Yao Xia, in some posts and a paper but particularly +this post on [Monadic profunctors for bidirectional programming](https://blog.poisson.chat/posts/2017-01-01-monadic-profunctors.html). + +The person deserving the most credit for bringing the power of optics to programming, with his [lens library](https://github.com/ekmett/lens/), is Ed Kmett, to whom I am very grateful for teaching me a lot. + +None of the ideas in this library are particularly original and a lot of related ideas have been explored, in Tom Ellis' [product-profunctors](https://github.com/tomjaguarpaw/product-profunctors) as well as Sjoerd Visscher's [one-liner](https://github.com/sjoerdvisscher/one-liner) and more. Such explorations are _not_ limited to Haskell. Brandon Williams and Stephen Celis' excellent [swift-parsing](https://github.com/pointfreeco/swift-parsing) was also influenced by invertible parser theory. + +Some optics in this library are [grates, a new kind of optic](https://r6research.livejournal.com/28050.html), discovered by Russel O'Connor and James Deikun; monocles which are studied by Alexandre Garcia de Oliveira, Mauro Jaskelioff, and Ana Cristina Vieira de Melo in [On Structuring Functional Programs with Monoidal Profunctors](https://arxiv.org/abs/2207.00852); and withers, discovered by Chris Penner in [Composable filters using Witherable optics](https://chrispenner.ca/posts/witherable-optics). + +## contributing + +Contributors are welcome. The [Issues](https://github.com/morphismtech/distributors/issues) page is a good place to communicate. + +## diagram + +[Fold] [Setter] [Wither] [Review] [Bifocal] + ^ ^ ^ ^ ^ ^ ^ ^ + | | | | | | | | + | | +-------+ | | | | | + | | | +--------|-------+ | | | + +-|---------------+ | | | | | | + | | | | | | | | +[Fold1] [Traversal] | | | | + ^ ^ ^ ^ ^ | | | | + | | | | | | | | | + | | | | | | +---|----------|--+ + | | | | | | | | | + | +------+ +---+ | | | | | | + | | | | | | | | | +[Getter] [Traversal1] | | | [Prismoid] | | + ^ ^ | | | ^ ^ | | + | | | | | | | | | + | | | +-----------|-------------+ | | | | + | | | | | | | | | + | +-----+ | +---------|-------------|-|--+ | | + | | | | | | | | | + [Lens] [Diopter] [Grate] | | | [PartialIso] + ^ ^ ^ ^ | | | ^ + | | | | | | | | + | | | | | | | | + | | +-+ | | |+-------+ | + +-+ +-----------+ | ++ | ||+---------------+ + | | | | | ||| + [Comonocle] [Monocle] [Prism] + ^ ^ ^ + | | | + | | | + +---------------------+| | + ||+-----------------+ + [Iso] + ^ + | + | + | + | + [Equality] diff --git a/Setup.hs b/distributors-core/Setup.hs similarity index 100% rename from Setup.hs rename to distributors-core/Setup.hs diff --git a/distributors.cabal b/distributors-core/distributors.cabal similarity index 63% rename from distributors.cabal rename to distributors-core/distributors.cabal index 5d68dd41..1a519709 100644 --- a/distributors.cabal +++ b/distributors-core/distributors.cabal @@ -5,9 +5,9 @@ cabal-version: 2.2 -- see: https://github.com/sol/hpack name: distributors -version: 0.6.0.0 -synopsis: Unifying Parsers, Printers & Grammars -description: Distributors provides mathematically inspired abstractions for coders to write parsers that can also be inverted to printers. +version: 0.7.0.0 +synopsis: Profunctor algebra & optics for invertible syntax +description: Distributors provides mathematically inspired abstractions for coders to write parsers that can also be inverted to printers. Its grammars are in @distributors-grammar@. category: Profunctors, Optics, Parsing homepage: https://github.com/morphismtech/distributors#readme bug-reports: https://github.com/morphismtech/distributors/issues @@ -29,29 +29,25 @@ source-repository head library exposed-modules: Control.Lens.Bifocal + Control.Lens.Comonocle Control.Lens.Diopter - Control.Lens.Grammar - Control.Lens.Grammar.BackusNaur - Control.Lens.Grammar.Boole - Control.Lens.Grammar.Internal.NestedPrismTH - Control.Lens.Grammar.Internal.Orphanage - Control.Lens.Grammar.Kleene - Control.Lens.Grammar.Machine - Control.Lens.Grammar.Symbol - Control.Lens.Grammar.Token Control.Lens.Grate + Control.Lens.Internal.Distributor.Orphanage Control.Lens.Monocle Control.Lens.PartialIso + Control.Lens.Prism.Nested + Control.Lens.Prismoid + Control.Lens.Varifocal Control.Lens.Wither - Control.Monad.Fail.Try + Data.Monoid.Disjunctive Data.Profunctor.Distributor Data.Profunctor.Filtrator - Data.Profunctor.Grammar - Data.Profunctor.Grammar.Parsector Data.Profunctor.Monadic + Data.Profunctor.Monadic.Do Data.Profunctor.Monoidal - Data.Profunctor.Separator + Data.Profunctor.Monoidal.Cocartesian Data.Traversable.Homogeneous + Data.Traversable.Homogeneous.Enumerable other-modules: Paths_distributors autogen-modules: @@ -98,23 +94,85 @@ library UndecidableSuperClasses ghc-options: -Wall -Wcompat -Widentities -Wincomplete-record-updates -Wincomplete-uni-patterns -Wmissing-export-lists -Wmissing-home-modules -Wpartial-fields -Wredundant-constraints build-depends: - MemoTrie >=0.6 && <1 - , QuickCheck >=2.14 && <3 - , adjunctions >=4.4 && <5 - , base >=4.15 && <5 + adjunctions >=4.4 && <5 + , base >=4.20 && <5 , bifunctors >=5.5 && <6 - , bytestring >=0.11 && <1 , 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 + , template-haskell >=2.17 && <3 + , th-abstraction >=0.4 && <1 + , transformers >=0.5 && <1 + , vector >=0.12 && <1 + , witherable >=0.4 && <1 + default-language: Haskell2010 + +test-suite doctests + type: exitcode-stdio-1.0 + main-is: Doctests.hs + other-modules: + Paths_distributors + autogen-modules: + Paths_distributors + hs-source-dirs: + doctest + default-extensions: + AllowAmbiguousTypes + Arrows + ConstraintKinds + DataKinds + DefaultSignatures + DeriveFoldable + DeriveFunctor + DeriveTraversable + DeriveGeneric + DerivingStrategies + DerivingVia + EmptyCase + FlexibleContexts + FlexibleInstances + FunctionalDependencies + GADTs + GeneralizedNewtypeDeriving + ImportQualifiedPost + ImpredicativeTypes + InstanceSigs + LambdaCase + MagicHash + MonoLocalBinds + QualifiedDo + QuantifiedConstraints + RankNTypes + RecursiveDo + ScopedTypeVariables + StandaloneDeriving + StandaloneKindSignatures + TemplateHaskell + TupleSections + TypeApplications + TypeFamilies + TypeOperators + UndecidableInstances + UndecidableSuperClasses + ghc-options: -Wall -Wcompat -Widentities -Wincomplete-record-updates -Wincomplete-uni-patterns -Wmissing-export-lists -Wmissing-home-modules -Wpartial-fields -Wredundant-constraints -threaded + build-depends: + adjunctions >=4.4 && <5 + , base >=4.20 && <5 + , bifunctors >=5.5 && <6 + , containers >=0.6 && <1 + , contravariant >=1.5 && <2 + , distributive >=0.6 && <1 + , distributors + , doctest-parallel >=0.3 && <1 + , free >=5.1 && <6 , lens >=5.0 && <6 - , monad-loops >=0.4.3 && <1 - , mtl >=2.2 && <3 , profunctors >=5.6 && <6 - , random >=1.2 && <2 , tagged >=0.8 && <1 , template-haskell >=2.17 && <3 - , text ==2.* , th-abstraction >=0.4 && <1 , transformers >=0.5 && <1 , vector >=0.12 && <1 @@ -125,16 +183,11 @@ test-suite test type: exitcode-stdio-1.0 main-is: Main.hs other-modules: - Examples.Arithmetic - Examples.Chain - Examples.Expression - Examples.Json - Examples.Lambda - Examples.LenVec - Examples.RegString - Examples.SemVer - Examples.SExpr - Properties.Kleene + Properties.Disjunctive + Properties.Homogeneous + Properties.Nested + Properties.Parsing + Properties.PartialIso Paths_distributors autogen-modules: Paths_distributors @@ -180,27 +233,20 @@ test-suite test UndecidableSuperClasses ghc-options: -Wall -Wcompat -Widentities -Wincomplete-record-updates -Wincomplete-uni-patterns -Wmissing-export-lists -Wmissing-home-modules -Wpartial-fields -Wredundant-constraints build-depends: - MemoTrie >=0.6 && <1 - , QuickCheck >=2.14 && <3 + QuickCheck >=2.14 && <3 , adjunctions >=4.4 && <5 - , base >=4.15 && <5 + , base >=4.20 && <5 , bifunctors >=5.5 && <6 - , bytestring >=0.11 && <1 , containers >=0.6 && <1 , contravariant >=1.5 && <2 , distributive >=0.6 && <1 , distributors - , doctest >=0.18 && <1 + , free >=5.1 && <6 , hspec >=2.7 && <3 , lens >=5.0 && <6 - , megaparsec >=9.0 && <10 - , monad-loops >=0.4.3 && <1 - , mtl >=2.2 && <3 , profunctors >=5.6 && <6 - , random >=1.2 && <2 , tagged >=0.8 && <1 , template-haskell >=2.17 && <3 - , text ==2.* , th-abstraction >=0.4 && <1 , transformers >=0.5 && <1 , vector >=0.12 && <1 diff --git a/distributors-core/doctest/Doctests.hs b/distributors-core/doctest/Doctests.hs new file mode 100644 index 00000000..5e763d99 --- /dev/null +++ b/distributors-core/doctest/Doctests.hs @@ -0,0 +1,7 @@ +module Main (main) where + +import System.Environment (getArgs) +import Test.DocTest (mainFromCabal) + +main :: IO () +main = mainFromCabal "distributors" =<< getArgs diff --git a/package.yaml b/distributors-core/package.yaml similarity index 84% rename from package.yaml rename to distributors-core/package.yaml index 4319745c..713bcf89 100644 --- a/package.yaml +++ b/distributors-core/package.yaml @@ -1,5 +1,5 @@ name: distributors -version: 0.6.0.0 +version: 0.7.0.0 github: "morphismtech/distributors" license: BSD-3-Clause author: "Eitan Chatav" @@ -12,30 +12,25 @@ extra-doc-files: - CHANGELOG.md category: Profunctors, Optics, Parsing -synopsis: Unifying Parsers, Printers & Grammars +synopsis: Profunctor algebra & optics for invertible syntax description: Distributors provides mathematically inspired abstractions for coders to write parsers that can also be inverted to printers. + Its grammars are in @distributors-grammar@. dependencies: -- base >= 4.15 && < 5 +- base >= 4.20 && < 5 - adjunctions >= 4.4 && < 5 - bifunctors >= 5.5 && < 6 -- bytestring >= 0.11 && < 1 - containers >= 0.6 && < 1 - contravariant >= 1.5 && < 2 - distributive >= 0.6 && < 1 +- free >= 5.1 && < 6 - lens >= 5.0 && < 6 -- MemoTrie >= 0.6 && < 1 -- QuickCheck >= 2.14 && < 3 -- monad-loops >=0.4.3 && < 1 -- mtl >= 2.2 && < 3 -- random >= 1.2 && < 2 - transformers >= 0.5 && < 1 - profunctors >= 5.6 && < 6 - tagged >= 0.8 && < 1 - template-haskell >= 2.17 && < 3 -- text >= 2 && < 3 - th-abstraction >= 0.4 && < 1 - vector >= 0.12 && < 1 - witherable >= 0.4 && < 1 @@ -94,12 +89,17 @@ default-extensions: - UndecidableSuperClasses tests: + doctests: + main: Doctests.hs + source-dirs: doctest + ghc-options: -threaded + dependencies: + - distributors + - doctest-parallel >= 0.3 && < 1 test: main: Main.hs source-dirs: test dependencies: - distributors - - doctest >= 0.18 && < 1 - hspec >= 2.7 && < 3 - - megaparsec >= 9.0 && < 10 - QuickCheck >= 2.14 && < 3 diff --git a/distributors-core/src/Control/Lens/Bifocal.hs b/distributors-core/src/Control/Lens/Bifocal.hs new file mode 100644 index 00000000..0f79026b --- /dev/null +++ b/distributors-core/src/Control/Lens/Bifocal.hs @@ -0,0 +1,284 @@ +{- | +Module : Control.Lens.Bifocal +Description : bifocals +Copyright : (C) 2026 - Eitan Chatav +License : BSD-style (see the file LICENSE) +Maintainer : Eitan Chatav +Stability : provisional +Portability : non-portable +-} + +module Control.Lens.Bifocal + ( -- * Bifocal + Bifocal + , ABifocal + , Spectacle (..), runSpectacle, spectacle, withSpectacle + , Binocular (..), runBinocular + -- * Applicator + , (>?<*) + -- * Combinators + , bifocal + , withBifocal + , cloneBifocal + , crossBifocal + , altBifocal + , orBifocal + ) where + +import Control.Applicative +import Control.Lens +import Control.Lens.Internal.Profunctor +import Control.Lens.PartialIso +import Control.Monad ((>=>)) +import Data.Monoid.Disjunctive (DisjunctiveMonoid (..)) +import Data.Profunctor +import Data.Profunctor.Distributor +import Data.Profunctor.Monoidal ((>*<)) +import Data.Profunctor.Monoidal.Cocartesian +import Data.Profunctor.Filtrator +import Data.Traversable.Homogeneous +import Data.Void +import GHC.Generics (Par1 (..), U1 (..), V1, (:*:) (..), (:+:) (..), (:.:) (..)) +import Witherable + +-- $setup +-- >>> import Control.Lens (_Just, _Left, _Right) +-- >>> import Control.Lens.PartialIso (clonePartialIso, satisfied) +-- >>> import Control.Lens.Prismoid (atLeast) +-- >>> import Data.Bifunctor.Joker (Joker (..)) +-- >>> import Data.Char (isDigit, digitToInt) +-- >>> import Text.ParserCombinators.ReadP (readP_to_S, satisfy) + +{- | `Bifocal`s are bidirectional parser optics. +`Control.Lens.Prismoid.Prismoid` ∪ `Control.Lens.PartialIso.PartialIso` ⊂ `Bifocal`, + +so every `Control.Lens.Iso.Iso`, `Control.Lens.Prism.Prism`, +`Control.Lens.PartialIso.filterPrism`, `Control.Lens.Monocle.Monocle`, +`Control.Lens.Comonocle.Comonocle` & `Control.Lens.Diopter.Diopter` +is a `Bifocal` too. + +`Bifocal`s are isomorphic to t'Spectacle's, by `Homogeneous` shapes, +& to t'Binocular's, by partial probes. +-} +type Bifocal s t a b = forall p f. + (Alternator p, Applicative f, Filterable f) + => p a (f b) -> p s (f t) + +{- | `ABifocal` is monomorphically a `Bifocal`. + +> prop> Bifocal s t a b ⊂ ABifocal s t a b +-} +type ABifocal s t a b = + Spectacle a b a (Maybe b) -> Spectacle a b s (Maybe t) + +{- | Build a `Bifocal` from a concrete t'Binocular'. -} +bifocal :: Binocular a b s t -> Bifocal s t a b +bifocal bif = unwrapPafb . runBinocular bif . WrapPafb + +{- | Action of a `Bifocal` on partial `Alternator`s, +applying it directly at the `Alternator`, without converting it +to a concrete form, so the `Alternator`'s own methods, +like `someP` & `optionP`, act as they are, failing to build by +the `Alternator`'s `Filtrator`. +Clone `ABifocal` to apply it, by @`cloneBifocal` bif >?<* p@. + +> prop> prsm >?<* p = prsm Control.Lens.Prismoid.>?* p +> prop> pat >?<* p = pat Control.Lens.PartialIso.>?< p + +>>> let digits = runJoker (atLeast 1 >?<* Joker (satisfy isDigit)) +>>> [ds | (ds, "") <- readP_to_S digits "123"] +["123"] +>>> let evenDigit = runJoker (satisfied even >?<* Joker (digitToInt <$> satisfy isDigit)) +>>> [(d, rest) | (d, rest) <- readP_to_S evenDigit "41"] +[(4,"1")] +-} +(>?<*) + :: (Alternator p, Filtrator p) + => Bifocal s t a b -> p a b -> p s t +bif >?<* p = catMaybes (bif (rmap Just p)) +infixl 4 >?<* + +{- | Clone `ABifocal` so that you can reuse the same +monomorphically typed `Bifocal` for different purposes. +-} +cloneBifocal :: ABifocal s t a b -> Bifocal s t a b +cloneBifocal bif = withSpectacle bif $ \match build -> + spectacle (Spectacle match build) + +{- | Construct a `Bifocal` on pairs from components, with the same foci. + +>>> withSpectacle (crossBifocal _Just _Just) $ \match build -> (match (Just 1, Just 2) >>= build . fmap negate, match (Just 1, Nothing) >>= build) +(Just (Just (-1),Just (-2)),Nothing) +-} +crossBifocal + :: ABifocal s t a b + -> ABifocal u v a b + -> Bifocal (s,u) (t,v) a b +crossBifocal x y p = + rmap (uncurry (liftA2 (,))) (cloneBifocal x p >*< cloneBifocal y p) + +{- | Construct a `Bifocal` on `Either`s from components, with the same foci. + +>>> withSpectacle (altBifocal _Just _Just) $ \match build -> (match (Left (Just 'x')) >>= build . fmap succ, match (Right Nothing) >>= build) +(Just (Left (Just 'y')),Nothing) +-} +altBifocal + :: ABifocal s t a b + -> ABifocal u v a b + -> Bifocal (Either s u) (Either t v) a b +altBifocal x y p = rmap (either (fmap Left) (fmap Right)) + (cloneBifocal x p >+< cloneBifocal y p) + +{- | Disjoin two `Bifocal`s on the same source, by `>|<`. + +> prop> orBifocal x falseOptic = cloneBifocal x +> prop> orBifocal falseOptic y = cloneBifocal y + +>>> withSpectacle (orBifocal _Left _Right) $ \match build -> (match (Left 'x') >>= build . fmap succ, match (Right 'x') >>= build . fmap succ) +(Just (Left 'y'),Just (Right 'y')) +-} +orBifocal + :: ABifocal s t a b + -> ABifocal s t a b + -> Bifocal s t a b +orBifocal x y p = cloneBifocal x p >|< cloneBifocal y p + +{- | Run `ABifocal` over an `Alternative` & `Filterable`, +by partial probes. -} +withBifocal + :: (Alternative f, Filterable f) + => ABifocal s t a b -> ((s -> Maybe a) -> f b) -> f t +withBifocal bif = unBinocular (cloneBifocal bif >?<* Binocular ($ Just)) + +{- | t'Binocular' is a secondary concrete representation of `Bifocal`s, +by partial probes, each of which matches from the source anew. -} +newtype Binocular a b s t = Binocular + { unBinocular + :: forall f. (Alternative f, Filterable f) + => ((s -> Maybe a) -> f b) -> f t + } +instance Profunctor (Binocular a b) where + dimap f g (Binocular k) = Binocular $ fmap g . k . (. (. f)) +instance Functor (Binocular a b s) where fmap = rmap +instance Applicative (Binocular a b s) where + pure t = Binocular (pure (pure t)) + Binocular x <*> Binocular y = Binocular (liftA2 (<*>) x y) +instance Alternative (Binocular a b s) where + empty = Binocular (pure empty) + Binocular x <|> Binocular y = Binocular (liftA2 (<|>) x y) + many = lmap repeat . manyP + some = lmap repeat . someP +instance DisjunctiveMonoid (Binocular a b s t) +instance Filterable (Binocular a b s) where + mapMaybe f (Binocular k) = Binocular (mapMaybe f . k) + catMaybes (Binocular k) = Binocular (catMaybes . k) +instance Choice (Binocular a b) where + left' (Binocular k) + = Binocular $ fmap Left + . k . (. (\f -> either f (const Nothing))) + right' (Binocular k) + = Binocular $ fmap Right + . k . (. (\f -> either (const Nothing) f)) +instance Cochoice (Binocular a b) where + unleft (Binocular k) + = Binocular $ catMaybes + . fmap (either Just (const Nothing)) + . k . (. (. Left)) + unright (Binocular k) + = Binocular $ catMaybes + . fmap (either (const Nothing) Just) + . k . (. (. Right)) +instance CocartesianMonoidal (Binocular a b) +instance Distributor (Binocular a b) +instance CocartesianChoice (Binocular a b) +instance Alternator (Binocular a b) +instance Filtrator (Binocular a b) + +{- | Run a t'Binocular' on a partial `Distributor`. -} +runBinocular + :: (Alternator p, Filtrator p) + => Binocular a b s t + -> p a b -> p s t +runBinocular (Binocular k) p = k $ \f -> dimapMaybe f Just p + +{- | t'Spectacle' provides an efficient +concrete representation of `Bifocal`s, by `Homogeneous` shapes, matching partially forwards +& building partially backwards, a +t'Control.Lens.Prismoid.Prismatoid' which may also fail to build. +-} +data Spectacle a b s t where + Spectacle + :: Homogeneous h + => (s -> Maybe (h a)) + -> (h b -> Maybe t) + -> Spectacle a b s t +instance Profunctor (Spectacle a b) where + dimap f' g' (Spectacle f g) = Spectacle (f . f') (fmap g' . g) +instance Functor (Spectacle a b s) where fmap = rmap +instance Applicative (Spectacle a b s) where + pure t = Spectacle (const (Just U1)) (const (Just t)) + liftA2 h (Spectacle f0 g0) (Spectacle f1 g1) = Spectacle + (\s -> liftA2 (:*:) (f0 s) (f1 s)) + (\(x :*: y) -> liftA2 h (g0 x) (g1 y)) + (<*>) = liftA2 id +instance Alternative (Spectacle a b s) where + empty = Spectacle (const Nothing) (\(v :: V1 b) -> case v of {}) + Spectacle f0 g0 <|> Spectacle f1 g1 = Spectacle + (\s -> (L1 <$> f0 s) <|> (R1 <$> f1 s)) + (\case {L1 x -> g0 x; R1 y -> g1 y}) +instance DisjunctiveMonoid (Spectacle a b s t) +instance Filterable (Spectacle a b s) where + mapMaybe h (Spectacle f g) = Spectacle f (g >=> h) +instance CocartesianMonoidal (Spectacle a b) where + zeroP = Spectacle absurd (\(v :: V1 b) -> case v of {}) + Spectacle f0 g0 >+< Spectacle f1 g1 = Spectacle + (either (fmap L1 . f0) (fmap R1 . f1)) + (\case {L1 x -> Left <$> g0 x; R1 y -> Right <$> g1 y}) +instance Choice (Spectacle a b) where + left' = alternate . Left + right' = alternate . Right +instance Cochoice (Spectacle a b) where + unleft (Spectacle f g) = + Spectacle (f . Left) (g >=> either Just (const Nothing)) + unright (Spectacle f g) = + Spectacle (f . Right) (g >=> either (const Nothing) Just) +instance CocartesianChoice (Spectacle a b) where + alternate = \case + Left (Spectacle f g) -> + Spectacle (either f (const Nothing)) (fmap Left . g) + Right (Spectacle f g) -> + Spectacle (either (const Nothing) f) (fmap Right . g) +instance Distributor (Spectacle a b) where + optionalP (Spectacle f g) = + Spectacle (fmap Comp1 . traverse f) (traverse g . unComp1) + manyP (Spectacle f g) = + Spectacle (fmap Comp1 . traverse f) (traverse g . unComp1) +instance Alternator (Spectacle a b) +instance Filtrator (Spectacle a b) + +{- | Run a t'Spectacle' on a partial `Distributor`, +failing by `falseP` where it doesn't match, +& by `mapMaybe` where it doesn't build. -} +runSpectacle + :: (Alternator p, Filtrator p) + => Spectacle a b s t -> p a b -> p s t +runSpectacle (Spectacle f g) p = + dialt (maybe (Left ()) Right . f) id id falseP (mapMaybe g (homogeneously p)) + +{- | Build a `Bifocal` from a t'Spectacle'. -} +spectacle :: Spectacle a b s t -> Bifocal s t a b +spectacle sp = unwrapPafb . runSpectacle sp . WrapPafb + +{- | Convert `ABifocal` to the pair of functions that characterize it, +matching into & building from a `Homogeneous` shape. + +>>> withSpectacle (clonePartialIso _Just) $ \match build -> (match Nothing >>= build, match (Just 'x') >>= build . fmap succ) +(Nothing,Just (Just 'y')) +-} +withSpectacle + :: ABifocal s t a b + -> (forall h. Homogeneous h => (s -> Maybe (h a)) -> (h b -> Maybe t) -> r) + -> r +withSpectacle bif k = + case catMaybes (bif (Just <$> Spectacle (Just . Par1) (Just . unPar1))) of + Spectacle f g -> k f g diff --git a/distributors-core/src/Control/Lens/Comonocle.hs b/distributors-core/src/Control/Lens/Comonocle.hs new file mode 100644 index 00000000..d19050e1 --- /dev/null +++ b/distributors-core/src/Control/Lens/Comonocle.hs @@ -0,0 +1,359 @@ +{- | +Module : Control.Lens.Comonocle +Description : comonocles +Copyright : (C) 2026 - Eitan Chatav +License : BSD-style (see the file LICENSE) +Maintainer : Eitan Chatav +Stability : provisional +Portability : non-portable +-} + +module Control.Lens.Comonocle + ( -- * Comonocle + Comonocle + , AComonocle + , Comonocular (..), runComonocular + -- * Combinators + , comonocle + , withComonocle + , cloneComonocle + , mapComonocle + , altComonocle + , zeroOptic + , alongsideComonocle + , indexComonocle + , countComonocle + , copiesComonocle + , fromComonocle + , succComonocle + , predComonocle + , enumerateComonocle + , enumerateFromThenComonocle + , enumerateFromToComonocle + , enumerateFromThenToComonocle + , zipComonocle + , zipWithComonocle + , _Enumerable + , _BoundedEnum + ) where + +import Control.Applicative (Alternative) +import Control.Lens hiding (Traversing) +import Control.Lens.PartialIso +import Control.Lens.Internal.Profunctor +import Data.Functor.Compose +import Data.Profunctor.Monoidal +import Data.Profunctor.Monoidal.Cocartesian +import Data.Traversable.Homogeneous +import Data.Traversable.Homogeneous.Enumerable +import Data.Void (Void, absurd) +import GHC.Generics (Par1 (..), V1, (:+:) (..), (:*:) (..)) +import Numeric.Natural (Natural) + +-- $setup +-- >>> import Control.Lens +-- >>> import Data.Functor.Identity + +{- | `Comonocle`s are an optic dual to `Control.Lens.Monocle.Monocle`s, by sums, +which focus on the one copy that an `Enumerable` sum holds. + +`Control.Lens.Iso.Iso` ⊂ `Comonocle` ⊂ +`Control.Lens.Lens.Lens` ∩ `Control.Lens.Diopter.Diopter`, + +a `Comonocle` being a `Control.Lens.Lens.Lens` +whose residue is which copy is held. + +>>> view _Enumerable (Identity 'a') +'a' + +`Comonocle`s are isomorphic to t'Comonocular's, +whose shapes are `Enumerable`. +-} +type Comonocle s t a b = forall p f. + (CocartesianMonoidal p, Functor f) + => p a (f b) -> p s (f t) + +{- | `AComonocle` is monomorphically a `Comonocle`. + +> prop> Comonocle s t a b ⊂ AComonocle s t a b +-} +type AComonocle s t a b = + Comonocular a b a (Identity b) -> Comonocular a b s (Identity t) + +{- | Build a `Comonocle` from a concrete t'Comonocular'. -} +comonocle :: Comonocular a b s t -> Comonocle s t a b +comonocle mon = unwrapPafb . runComonocular mon . WrapPafb + +{- | Convert `AComonocle` to the pair of functions that characterize it. -} +withComonocle + :: AComonocle s t a b + -> (forall f. Enumerable f => (s -> f a) -> (f b -> t) -> r) + -> r +withComonocle mon k = + case rmap runIdentity (mon (rmap Identity (Comonocular Par1 unPar1))) of + Comonocular split merge -> k split merge + +{- | Clone `AComonocle` so that you can reuse the same +monomorphically typed `Comonocle` for different purposes. +-} +cloneComonocle :: AComonocle s t a b -> Comonocle s t a b +cloneComonocle mon = withComonocle mon $ \split merge -> + comonocle (Comonocular split merge) + +{- | Action of `AComonocle` on `CocartesianMonoidal` `Profunctor`s. -} +mapComonocle + :: CocartesianMonoidal p => AComonocle s t a b -> p a b -> p s t +mapComonocle mon = withComonocle mon $ \split merge -> + dimap split merge . enumerably + +{- | The `Comonocle` without copies, the unit of the alts, +like `altComonocle`, up to the unitor @Either s Void ≅ s@, +as `zeroP` is of `>+<`, & by inclusion an optic of every +kind which alts. +-} +zeroOptic :: Comonocle Void Void a b +zeroOptic _ = rmap absurd zeroP + +{- | Construct a `Comonocle` on `Either`s from components, with the same foci, +since sums of copies add, \(m a + n a = (m+n) a\), +as `Control.Lens.Lens.choosing` does `Control.Lens.Lens.Lens`es. + +>>> set (altComonocle id _Enumerable) 'x' (Right (Identity 'y')) +Right (Identity 'x') +-} +altComonocle + :: AComonocle s t a b + -> AComonocle u v a b + -> Comonocle (Either s u) (Either t v) a b +altComonocle x y p = rmap (either (fmap Left) (fmap Right)) + (cloneComonocle x p >+< cloneComonocle y p) + +{- | Construct a `Comonocle` on pairs from components, +since products of sums of copies distribute, +\(m a \times n c = (m n) (a \times c)\). + +>>> over (alongsideComonocle _Enumerable id) (\(a, c) -> (a + c, show c)) (Identity 1, 2) +(Identity 3,"2") +-} +alongsideComonocle + :: AComonocle s t a b + -> AComonocle u v c d + -> Comonocle (s,u) (t,v) (a,c) (b,d) +alongsideComonocle x y = + withComonocle x $ \e f -> + withComonocle y $ \g h -> + comonocle $ Comonocular + (\(s,u) -> Compose (fmap (\a -> fmap (a,) (g u)) (e s))) + (\(Compose i) -> f >*< h $ + let + (_, j) = review fromEnumerable i + k = fmap (review fromEnumerable) i + in + (fmap (fst . snd) k, fmap snd j) + ) + +{- | The `Control.Lens.Indexed.IndexedLens` of `AComonocle`, +indexed by which copy is held, numbered from 0, left to right. +Numbering diverges past a summand of infinitely many copies. + +>>> iview (indexComonocle (altComonocle id id)) (Right 'a' :: Either Char Char) +(1,'a') +-} +indexComonocle :: AComonocle s t a b -> IndexedLens Natural s t a b +indexComonocle mon = withComonocle mon $ \split merge -> ilens + (review fromEnumerable . split) + (\s b -> merge (b <$ split s)) + +{- | The copy of `AComonocle` at an index, holding a focus, if there is one, +like `toEnum`, & inverse to `indexComonocle`. + +>>> preview (fromComonocle _BoundedEnum) (2, ()) :: Maybe Ordering +Just GT +>>> preview (fromComonocle _BoundedEnum) (3, ()) :: Maybe Ordering +Nothing +-} +fromComonocle :: AComonocle s s a a -> Prism' (Natural, a) s +fromComonocle mon = withComonocle mon $ \split merge -> prism' + (review fromEnumerable . split) + (fmap merge . preview fromEnumerable) + +{- | Zip two sources of `AComonocle`, when they hold the same copy, +dual to `Control.Lens.Grate.cotraverseOf`, which zips every `Control.Lens.Monocle.Monocle`. + +>>> zipWithComonocle (altComonocle id id) (+) (Left 1) (Left 2 :: Either Int Int) +Just (Left 3) +>>> zipWithComonocle (altComonocle id id) (+) (Left 1) (Right 2 :: Either Int Int) +Nothing +-} +zipWithComonocle + :: AComonocle s t a b -> (a -> a -> b) -> s -> s -> Maybe t +zipWithComonocle mon f s0 s1 = + zipComonocle mon (\(Par1 a0 :*: Par1 a1) -> Just (f a0 a1)) (Par1 s0 :*: Par1 s1) + +{- | Zip sources of `AComonocle` in the positions of a `Traversable`, +when they all hold the same copy, or else `Control.Applicative.empty`. + +>>> zipComonocle (altComonocle id id) (Just . sum) [Left 1, Left 2, Left 3 :: Either Int Int] +Just (Left 6) +>>> zipComonocle (altComonocle id id) (Just . sum) [Left 1, Right 2 :: Either Int Int] +Nothing +-} +zipComonocle + :: (Traversable f, Alternative g) + => AComonocle s t a b -> (f a -> g b) -> f s -> g t +zipComonocle mon f = runZipporah (mapComonocle mon (Zipporah f)) + +{- | How many copies `AComonocle` has, like the size of a `Bounded` `Enum`. +It diverges for infinitely many copies, & takes time linear in their number. + +>>> countComonocle (_BoundedEnum @Ordering) +3 +-} +countComonocle :: AComonocle s t a b -> Natural +countComonocle mon = withComonocle mon $ \split _ -> copies split + where + copies :: forall f x y. Enumerable f => (x -> f y) -> Natural + copies _ = case enumerably (pure () :: Enumerator () ()) :: Enumerator (f ()) (f ()) of + Enumerator count _ _ -> count + +{- | The `Control.Lens.Prism.Prism`s of the copies of `AComonocle`, +numbered from 0, left to right, exactly one of which matches a source. + +Dual to `Control.Lens.Monocle.fociMonocle`: a sum of copies has +a `Control.Lens.Prism.Prism` for each copy, exactly one of which matches, +as a product of foci has a `Control.Lens.Lens.Lens` for each focus, +every one of which focuses. + +>>> [preview (runPrism copy) EQ | copy <- copiesComonocle _BoundedEnum] +[Nothing,Just (),Nothing] +>>> [review (runPrism copy) () | copy <- copiesComonocle _BoundedEnum] :: [Ordering] +[LT,EQ,GT] +-} +copiesComonocle :: forall s a. AComonocle s s a a -> [ReifiedPrism' s a] +copiesComonocle mon = withComonocle mon copiesOf + where + copiesOf + :: forall f. Enumerable f + => (s -> f a) -> (f a -> s) -> [ReifiedPrism' s a] + copiesOf split merge = + case enumerably (pure () :: Enumerator () ()) :: Enumerator (f ()) (f ()) of + Enumerator _ _ select -> + let + go i = case select i of + Nothing -> [] + Just copy -> copyAt i copy : go (i + 1) + in + go 0 + where + copyAt i copy = Prism $ prism (\a -> merge (a <$ copy)) $ \s -> + case review fromEnumerable (split s) of + (j, a) | j == i -> Right a + _ -> Left s + +{- | The next copy of `AComonocle`, holding the same focus, +if there is one, like `succ`, & conversely, the previous copy, like `pred`. + +>>> preview (succComonocle _BoundedEnum) EQ +Just GT +>>> preview (succComonocle _BoundedEnum) GT +Nothing +-} +succComonocle :: AComonocle s s a a -> PartialIso' s s +succComonocle mon = + withComonocle mon $ \split merge -> + withPartialIso succEnumerable $ \hither thither -> + partialIso + (fmap merge . hither . split) + (fmap merge . thither . split) + +{- | The previous copy of `AComonocle`, holding the same focus, +if there is one, like `pred`, & conversely, the next copy, like `succ`. + +>>> preview (predComonocle _BoundedEnum) EQ +Just LT +>>> preview (predComonocle _BoundedEnum) LT +Nothing +-} +predComonocle :: AComonocle s s a a -> PartialIso' s s +predComonocle mon = coPartialIso (succComonocle mon) + +{- | The copies of `AComonocle` from one onward, holding the same focus, +like `enumFrom`. + +>>> enumerateComonocle _BoundedEnum False +[False,True] +>>> enumerateComonocle (altComonocle id id) (Left 'x' :: Either Char Char) +[Left 'x',Right 'x'] +-} +enumerateComonocle :: AComonocle s s a a -> s -> [s] +enumerateComonocle mon s = + withComonocle mon $ \split merge -> merge <$> enumerateFrom (split s) + +{- | The copies of `AComonocle` from one onward, holding its focus, +stepping by the copy of another, like `enumFromThen`. + +>>> enumerateFromThenComonocle _BoundedEnum GT EQ +[GT,EQ,LT] +-} +enumerateFromThenComonocle :: AComonocle s s a a -> s -> s -> [s] +enumerateFromThenComonocle mon s s' = withComonocle mon $ \split merge -> + merge <$> enumerateFromThen (split s) (split s') + +{- | The copies of `AComonocle` from one to the copy of another, +holding its focus, like `enumFromTo`. + +>>> enumerateFromToComonocle _BoundedEnum LT EQ +[LT,EQ] +-} +enumerateFromToComonocle :: AComonocle s s a a -> s -> s -> [s] +enumerateFromToComonocle mon s s'' = withComonocle mon $ \split merge -> + merge <$> enumerateFromTo (split s) (split s'') + +{- | The copies of `AComonocle` from one to the copy of another, +holding its focus, stepping by the copy of a third, like `enumFromThenTo`. + +>>> enumerateFromThenToComonocle _BoundedEnum LT GT LT +[LT] +-} +enumerateFromThenToComonocle :: AComonocle s s a a -> s -> s -> s -> [s] +enumerateFromThenToComonocle mon s s' s'' = withComonocle mon $ \split merge -> + merge <$> enumerateFromThenTo (split s) (split s') (split s'') + +{- | The `Comonocle` of an `Enumerable` sum's copy. + +>>> over _Enumerable (+ 1) (Identity 1) +Identity 2 +-} +_Enumerable :: Enumerable f => Comonocle (f a) (f b) a b +_Enumerable = unwrapPafb . enumerably . WrapPafb + +{- | The `Comonocle` of a `Bounded` `Enum`, as copies of @()@, +numbered by `fromEnum` from `minBound`. + +>>> iview (indexComonocle _BoundedEnum) True +(1,()) +-} +_BoundedEnum :: (Bounded a, Enum a) => Comonocle a a () () +_BoundedEnum = iso (\x -> (x,())) (\(x,()) -> x) . _Enumerable + +{- | t'Comonocular' provides a concrete representation of `Comonocle`s, +by an `Enumerable` sum of copies. +-} +data Comonocular a b s t where + Comonocular + :: Enumerable f + => (s -> f a) + -> (f b -> t) + -> Comonocular a b s t +instance Profunctor (Comonocular a b) where + dimap f g (Comonocular split merge) = Comonocular (split . f) (g . merge) +instance CocartesianMonoidal (Comonocular a b) where + zeroP = Comonocular (absurd :: Void -> V1 a) (\case) + Comonocular split0 merge0 >+< Comonocular split1 merge1 = Comonocular + (either (L1 . split0) (R1 . split1)) + (\case L1 x -> Left (merge0 x); R1 y -> Right (merge1 y)) + +{- | Run a t'Comonocular' on a `CocartesianMonoidal` `Profunctor`. -} +runComonocular + :: CocartesianMonoidal p => Comonocular a b s t -> p a b -> p s t +runComonocular (Comonocular split merge) = dimap split merge . enumerably diff --git a/distributors-core/src/Control/Lens/Diopter.hs b/distributors-core/src/Control/Lens/Diopter.hs new file mode 100644 index 00000000..121ed9f4 --- /dev/null +++ b/distributors-core/src/Control/Lens/Diopter.hs @@ -0,0 +1,231 @@ +{- | +Module : Control.Lens.Diopter +Description : diopters +Copyright : (C) 2026 - Eitan Chatav +License : BSD-style (see the file LICENSE) +Maintainer : Eitan Chatav +Stability : provisional +Portability : non-portable +-} + +module Control.Lens.Diopter + ( -- * Diopter + Diopter + , ADiopter + , Dioptrice (..), runDioptrice + -- * Combinators + , diopter + , withDiopter + , cloneDiopter + , crossDiopter + , altDiopter + , mapDiopter + , optioned + , several + , skippedMany + , skippedOptional + , homogenized + , zipDiopter + , zipWithDiopter + , transposeDiopter + ) where + +import Control.Applicative (Alternative) +import Control.Lens +import Control.Lens.Internal.Profunctor +import Data.Profunctor.Distributor +import Data.Profunctor.Monoidal ((>*<)) +import Data.Profunctor.Monoidal.Cocartesian +import Data.Traversable.Homogeneous +import Data.Void +import GHC.Generics + +-- $setup +-- >>> import Control.Lens (over) +-- >>> import Control.Lens.Prismoid ((>?*)) +-- >>> import Data.Bifunctor.Joker (Joker (..)) +-- >>> import Data.Profunctor.Monoidal ((*<)) +-- >>> import Text.ParserCombinators.ReadP (char, readP_to_S) + +{- | `Diopter`s are an optic that generalizes +`Control.Lens.Monocle.Monocle`s, of products, +& `Control.Lens.Comonocle.Comonocle`s, of sums, +to countable sums of countable products. +`Control.Lens.Monocle.Monocle` ∪ `Control.Lens.Comonocle.Comonocle` +⊂ `Diopter` ⊂ +`Control.Lens.Traversal.Traversal` ∩ `Control.Lens.Prismoid.Prismoid`. + +`Diopter`s are isomorphic to t'Dioptrice's, whose shapes are `Homogeneous`, +so these inclusions mirror those of the optics' shapes, + +(`Traversable` ∩ `Data.Distributive.Distributive`) +∪ `Data.Traversable.Homogeneous.Enumerable.Enumerable` +⊂ `Homogeneous`. +-} +type Diopter s t a b = forall p f. + (Distributor p, Applicative f) + => p a (f b) -> p s (f t) + +{- | `ADiopter` is monomorphically a `Diopter`. + +> prop> Diopter s t a b ⊂ ADiopter s t a b +-} +type ADiopter s t a b = + Dioptrice a b a (Identity b) -> Dioptrice a b s (Identity t) + +{- | Build a `Diopter`. -} +diopter :: Homogeneous h => (s -> h a) -> (h b -> t) -> Diopter s t a b +diopter f g = unwrapPafb . runDioptrice (Dioptrice f g) . WrapPafb + +{- | Convert `ADiopter` to the pair of functions that characterize it. -} +withDiopter + :: ADiopter s t a b + -> (forall h. Homogeneous h => (s -> h a) -> (h b -> t) -> r) + -> r +withDiopter dio k = case runIdentity <$> dio (Identity <$> Dioptrice Par1 unPar1) of + Dioptrice f g -> k f g + +{- | Action of `ADiopter` on `Distributor`s. -} +mapDiopter :: Distributor p => ADiopter s t a b -> p a b -> p s t +mapDiopter dio = withDiopter dio $ \f g -> dimap f g . homogeneously + +{- | Clone `ADiopter` so that you can reuse the same +monomorphically typed `Diopter` for different purposes. +-} +cloneDiopter :: ADiopter s t a b -> Diopter s t a b +cloneDiopter dio = withDiopter dio diopter + +{- | Construct a `Diopter` on pairs from components, with the same foci, +as `Control.Lens.Monocle.crossMonocle` does `Control.Lens.Monocle.Monocle`s. + +>>> over (crossDiopter several optioned) negate ([1, 2], Just 3) +([-1,-2],Just (-3)) +-} +crossDiopter + :: ADiopter s t a b + -> ADiopter u v a b + -> Diopter (s,u) (t,v) a b +crossDiopter x y p = + rmap (uncurry (liftA2 (,))) (cloneDiopter x p >*< cloneDiopter y p) + +{- | Construct a `Diopter` on `Either`s from components, with the same foci, +as `Control.Lens.Comonocle.altComonocle` does `Control.Lens.Comonocle.Comonocle`s. + +>>> over (altDiopter several optioned) negate (Left [1, 2]) +Left [-1,-2] +-} +altDiopter + :: ADiopter s t a b + -> ADiopter u v a b + -> Diopter (Either s u) (Either t v) a b +altDiopter x y p = rmap (either (fmap Left) (fmap Right)) + (cloneDiopter x p >+< cloneDiopter y p) + +{- | One or none. -} +optioned :: Diopter (Maybe a) (Maybe b) a b +optioned = unwrapPafb . optionalP . WrapPafb + +{- | Zero or more. -} +several :: Diopter [a] [b] a b +several = unwrapPafb . manyP . WrapPafb + +{- | Zero or more, skipped, like `skipManyP`: sequencing any number +of foci forwards, & none backwards. + +>>> [r | (r, "") <- readP_to_S (runJoker ((skippedMany >?* Joker (char ' ')) *< Joker (char 'x'))) " x"] +[()] +-} +skippedMany :: Diopter () () a b +skippedMany = unwrapPafb . skipManyP . WrapPafb + +{- | Zero or one, skipped, like `skipOptionalP`: sequencing one focus +or none forwards, & none backwards. + +>>> [r | (r, "") <- readP_to_S (runJoker (Joker (char 'x') *< (skippedOptional >?* Joker (char ',')))) "x,"] +"x" +-} +skippedOptional :: Diopter () () a b +skippedOptional = unwrapPafb . skipOptionalP . WrapPafb + +{- | Build a `Diopter` from a `Homogeneous` +countable sum of countable products. + +> prop> traverse = homogenized +> prop> homogenized = ditraversed +-} +homogenized :: Homogeneous t => Diopter (t a) (t b) a b +homogenized = unwrapPafb . homogeneously . WrapPafb + +{- | Zip sources of `ADiopter` in the positions of a `Traversable`, +when they have the same shape, or else `Control.Applicative.empty`. + +>>> zipDiopter several (Just . sum) [[1, 2], [3, 4], [5, 6 :: Int]] +Just [9,12] +>>> zipDiopter several (Just . sum) [[1, 2], [3 :: Int]] +Nothing +-} +zipDiopter + :: (Traversable f, Alternative g) + => ADiopter s t a b -> (f a -> g b) -> f s -> g t +zipDiopter dio f = withDiopter dio $ \split merge -> + fmap merge . zipHomogeneous f . fmap split + +{- | Zip two sources of `ADiopter`, when they have the same shape. + +>>> zipWithDiopter optioned (+) (Just 1) (Just 2 :: Maybe Int) +Just (Just 3) +>>> zipWithDiopter optioned (+) (Just 1) (Nothing :: Maybe Int) +Nothing +-} +zipWithDiopter :: ADiopter s t a b -> (a -> a -> b) -> s -> s -> Maybe t +zipWithDiopter dio f s0 s1 = + zipDiopter dio (\(Par1 a0 :*: Par1 a1) -> Just (f a0 a1)) (Par1 s0 :*: Par1 s1) + +{- | Transpose sources of `ADiopter` in the positions of a `Traversable`, +when they have the same shape. + +>>> transposeDiopter several [[1, 2, 3], [4, 5, 6 :: Int]] +Just [[1,4],[2,5],[3,6]] +-} +transposeDiopter :: Traversable f => ADiopter s t a (f a) -> f s -> Maybe t +transposeDiopter dio = zipDiopter dio Just + +{- | A t'Dioptrice' provides efficient access +to some pair of functions that make up a `Diopter`. +-} +data Dioptrice a b s t where + Dioptrice + :: Homogeneous h + => (s -> h a) + -> (h b -> t) + -> Dioptrice a b s t +instance Profunctor (Dioptrice a b) where + dimap f g (Dioptrice sa bt) = Dioptrice (sa . f) (g . bt) +instance Functor (Dioptrice a b s) where fmap = rmap +instance Applicative (Dioptrice a b s) where + pure t = Dioptrice (const U1) (const t) + Dioptrice fx gx <*> Dioptrice fy gy = Dioptrice + (\s -> fx s :*: fy s) + (\(h :*: g) -> gx h (gy g)) +instance CocartesianMonoidal (Dioptrice a b) where + zeroP = Dioptrice absurd ridiculous + where + ridiculous :: V1 b -> x + ridiculous = (\case) + Dioptrice fx gx >+< Dioptrice fy gy = Dioptrice + (either (L1 . fx) (R1 . fy)) + (\case {L1 h -> Left (gx h); R1 j -> Right (gy j)}) +instance Distributor (Dioptrice a b) where + optionalP (Dioptrice f g) = Dioptrice + (Comp1 . fmap f) + (fmap g . unComp1) + manyP (Dioptrice f g) = Dioptrice + (Comp1 . fmap f) + (fmap g . unComp1) + +{- | Run a t'Dioptrice' on a `Distributor`. -} +runDioptrice + :: Distributor p + => Dioptrice a b s t + -> p a b -> p s t +runDioptrice (Dioptrice f g) = dimap f g . homogeneously diff --git a/src/Control/Lens/Grate.hs b/distributors-core/src/Control/Lens/Grate.hs similarity index 57% rename from src/Control/Lens/Grate.hs rename to distributors-core/src/Control/Lens/Grate.hs index 520065b8..3f3c31c1 100644 --- a/src/Control/Lens/Grate.hs +++ b/distributors-core/src/Control/Lens/Grate.hs @@ -15,10 +15,13 @@ module Control.Lens.Grate ( -- * Grate Grate , AGrate + , Grating (..) + , Diffraction (..), diffraction, withDiffraction -- * Combinators , grate , withGrate , cloneGrate + , crossGrate , mapGrate , cotraversed , represented @@ -26,8 +29,6 @@ module Control.Lens.Grate , distributeOf , collectOf , distributing - -- * Grating - , Grating (..) ) where import Data.Distributive @@ -37,18 +38,26 @@ import Data.Functor.Rep import Data.Profunctor import Data.Profunctor.Monoidal +-- $setup +-- >>> import Control.Lens (over) +-- >>> import Data.Complex + {- | `Grate`s are an optic that are dual to `Control.Lens.Traversal.Traversal`s, as `Distributive` is `Traversable`. -Every `Control.Lens.Monocle.Monocle` is a `Grate`. +`Control.Lens.Iso.Iso` ⊂ `Control.Lens.Monocle.Monocle` ⊂ `Grate`. -`Grate`s are isomorphic to `Grating`s. +`Grate`s are isomorphic to t'Grating's, & to t'Diffraction's, +whose shapes are `Distributive`. -} type Grate s t a b = forall p f. (Closed p, Monoidal p, Distributive f, Applicative f) => p a (f b) -> p s (f t) -{- | `AGrate` is monomorphically a `Grate`. -} +{- | `AGrate` is monomorphically a `Grate`. + +> prop> Grate s t a b ⊂ AGrate s t a b +-} type AGrate s t a b = Grating a b a (Identity b) -> Grating a b s (Identity t) @@ -74,6 +83,19 @@ monomorphically typed `Grate` for different purposes. cloneGrate :: AGrate s t a b -> Grate s t a b cloneGrate = grate . withGrate +{- | Construct a `Grate` on pairs from components, with the same foci, +as `Control.Lens.Monocle.crossMonocle` does `Control.Lens.Monocle.Monocle`s. + +>>> over (crossGrate cotraversed cotraversed) negate (1 :+ 2, 3 :+ 4) +((-1) :+ (-2),(-3) :+ (-4)) +-} +crossGrate + :: AGrate s t a b + -> AGrate u v a b + -> Grate (s,u) (t,v) a b +crossGrate x y p = + rmap (uncurry (liftA2 (,))) (cloneGrate x p >*< cloneGrate y p) + {- | Run `AGrate`. -} withGrate :: AGrate s t a b -> ((s -> a) -> b) -> t withGrate grt = runGrating $ runIdentity <$> grt (Identity <$> Grating ($ id)) @@ -99,10 +121,14 @@ distributeOf grt = cotraverseOf grt id collectOf :: Functor f => AGrate s t b (f b) -> (a -> s) -> f a -> t collectOf grt f = distributeOf grt . fmap f -{- | `Grating` provides an efficient +{- | t'Grating' provides an efficient concrete representation of `Grate`s. -} newtype Grating a b s t = Grating {runGrating :: ((s -> a) -> b) -> t} +instance Profunctor (Grating a b) where + dimap f g (Grating k) = Grating (g . k . (. (. f))) +instance Closed (Grating a b) where + closed (Grating k) = Grating $ \f x -> k $ \g -> f (g . ($ x)) instance Functor (Grating a b s) where fmap = fmapRep instance Applicative (Grating a b s) where pure = pureRep @@ -114,3 +140,40 @@ instance Representable (Grating a b s) where type Rep (Grating a b s) = (s -> a) -> b index (Grating k) f = k f tabulate = Grating + +{- | t'Diffraction' is a secondary concrete representation of `Grate`s, +by `Distributive` shapes, into which a source splits its foci, +& from which a target merges them, as +t'Control.Lens.Monocle.Ditraversal's are of +`Control.Lens.Monocle.Monocle`s, by `Traversable` & `Distributive` shapes. + +>>> over (diffraction (Diffraction (uncurry (:+)) (\(x :+ y) -> (x, y)))) negate (1, 2) +(-1,-2) +-} +data Diffraction a b s t where + Diffraction + :: Distributive f + => (s -> f a) -> (f b -> t) -> Diffraction a b s t +instance Profunctor (Diffraction a b) where + dimap f g (Diffraction split merge) = Diffraction (split . f) (g . merge) +instance Functor (Diffraction a b s) where fmap = rmap + +{- | Build a `Grate` from a t'Diffraction', +getting each focus of its shape by `distribute`. +-} +diffraction :: Diffraction a b s t -> Grate s t a b +diffraction (Diffraction split merge) = + grate $ \get -> merge (fmap get (distribute split)) + +{- | Convert `AGrate` to the pair of functions that characterize it, +splitting into & merging from a `Distributive` shape, +the functions of getters, as a t'Grating' is. + +>>> withDiffraction cotraversed $ \split merge -> merge (fmap (+ 1) (split (1 :+ 2))) :: Complex Int +2 :+ 3 +-} +withDiffraction + :: AGrate s t a b + -> (forall f. Distributive f => (s -> f a) -> (f b -> t) -> r) + -> r +withDiffraction grt k = k (\s get -> get s) (withGrate grt) diff --git a/src/Control/Lens/Grammar/Internal/Orphanage.hs b/distributors-core/src/Control/Lens/Internal/Distributor/Orphanage.hs similarity index 91% rename from src/Control/Lens/Grammar/Internal/Orphanage.hs rename to distributors-core/src/Control/Lens/Internal/Distributor/Orphanage.hs index bccd3001..d160e6c3 100644 --- a/src/Control/Lens/Grammar/Internal/Orphanage.hs +++ b/distributors-core/src/Control/Lens/Internal/Distributor/Orphanage.hs @@ -1,7 +1,7 @@ {-# OPTIONS_GHC -Wno-orphans #-} {- | -Module : Control.Lens.Grammar.Internal.Orphanage +Module : Control.Lens.Internal.Distributor.Orphanage Description : orphanage Copyright : (C) 2026 - Eitan Chatav License : BSD-style (see the file LICENSE) @@ -12,13 +12,12 @@ Portability : non-portable An orphanage for instances without a home. -} -module Control.Lens.Grammar.Internal.Orphanage () where +module Control.Lens.Internal.Distributor.Orphanage () where import Control.Applicative hiding (WrappedArrow) import Control.Applicative qualified as Ap (WrappedArrow) import Control.Arrow import Control.Lens -import Control.Lens.Internal.Prism import Control.Lens.Internal.Profunctor import Control.Monad import Data.Bifunctor.Clown @@ -34,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 -- @@ -77,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) @@ -127,14 +129,3 @@ instance (Profunctor p, Alternative (p a)) empty = proreturn empty ab <|> cd = proreturn (proextract ab <|> proextract cd) many = proreturn . many . proextract -instance Applicative (Market a b s) where - pure t = Market (pure t) (pure (Left t)) - Market f0 g0 <*> Market f1 g1 = Market - (\b -> f0 b (f1 b)) - (\s -> - case g0 s of - Left bt -> case g1 s of - Left b -> Left (bt b) - Right a -> Right a - Right a -> Right a - ) diff --git a/distributors-core/src/Control/Lens/Monocle.hs b/distributors-core/src/Control/Lens/Monocle.hs new file mode 100644 index 00000000..4c20b5de --- /dev/null +++ b/distributors-core/src/Control/Lens/Monocle.hs @@ -0,0 +1,259 @@ +{- | +Module : Control.Lens.Monocle +Description : monocles +Copyright : (C) 2026 - Eitan Chatav +License : BSD-style (see the file LICENSE) +Maintainer : Eitan Chatav +Stability : provisional +Portability : non-portable + +See Oliveira, Jaskelioff & de Melo, +[On Structuring Functional Programs with Monoidal Profunctors](https://arxiv.org/abs/2207.00852) +-} + +module Control.Lens.Monocle + ( -- * Monocle + Monocle + , AMonocle + , Monocular (..), runMonocular + , Ditraversal (..), ditraversal, withDitraversal + -- * Combinators + , monocle + , withMonocle + , cloneMonocle + , mapMonocle + , crossMonocle + , oneOptic + , ditraversed + , forevered + , zipMonocle + , zipWithMonocle + , replicateMonocle + , tabulateMonocle + , fociMonocle + ) where + +import Control.Lens hiding (Traversing) +import Control.Lens.Internal.Profunctor +import Control.Monad.Trans.State.Lazy (evalState, state) +import Data.Distributive +import Data.Profunctor.Monoidal +import GHC.Generics (Par1 (..), U1 (..), (:*:) (..)) +import Numeric.Natural (Natural) + +-- $setup +-- >>> import Control.Lens +-- >>> import Data.Complex +-- >>> import Data.Foldable (toList) +-- >>> import Data.Functor.Identity + +{- | `Monocle`s are an optic which is both +a `Control.Lens.Traversal.Traversal` & a `Control.Lens.Grate.Grate`, +focusing on a number of foci fixed by the optic, not its source. +`Control.Lens.Iso.Iso` ⊂ `Monocle` ⊂ +`Control.Lens.Traversal.Traversal` ∩ `Control.Lens.Grate.Grate`. + +`Monocle`s are isomorphic to t'Monocular's, & those of finitely many foci +to t'Ditraversal's, whose shapes are `Traversable` ∩ `Distributive`, +the shapes of `Control.Lens.Traversal.Traversal`s +∩ the shapes of `Control.Lens.Grate.Grate`s. +-} +type Monocle s t a b = forall p f. + (Monoidal p, Applicative f) + => p a (f b) -> p s (f t) + +{- | `AMonocle` is monomorphically a `Monocle`. + +> prop> Monocle s t a b ⊂ AMonocle s t a b +-} +type AMonocle s t a b = + Monocular a b a (Identity b) -> Monocular a b s (Identity t) + +{- | Build a `Monocle` from a concrete t'Monocular'. -} +monocle :: Monocular a b s t -> Monocle s t a b +monocle mon = unwrapPafb . runMonocular mon . WrapPafb + +{- | Action of `AMonocle` on `Monoidal` `Profunctor`s. -} +mapMonocle :: Monoidal p => AMonocle s t a b -> p a b -> p s t +mapMonocle mon p = withMonocle mon $ \f -> lmap f p + +{- | Clone `AMonocle` so that you can reuse the same +monomorphically typed `Monocle` for different purposes. +-} +cloneMonocle :: AMonocle s t a b -> Monocle s t a b +cloneMonocle mon = unwrapPafb . mapMonocle mon . WrapPafb + +{- | The `Monocle` without foci, the unit of the crosses, +like `crossMonocle`, up to the unitor @(s,()) ≅ s@, +as `oneP` is of `>*<`, & by inclusion an optic of every +kind which crosses. + +>>> toListOf oneOptic () :: [Int] +[] +-} +oneOptic :: Monocle () () a b +oneOptic _ = pure (pure ()) + +{- | Construct a `Monocle` on pairs from components, with the same foci, +since products of powers add, \(a^m \times a^n = a^{m+n}\), +as `Control.Lens.Traversal.beside` does `Control.Lens.Traversal.Traversal`s. + +>>> over (crossMonocle id ditraversed) negate (1, 2 :+ 3) +(-1,(-2) :+ (-3)) +-} +crossMonocle + :: AMonocle s t a b + -> AMonocle u v a b + -> Monocle (s,u) (t,v) a b +crossMonocle x y p = + rmap (uncurry (liftA2 (,))) (cloneMonocle x p >*< cloneMonocle y p) + +{- | Build a `Monocle` from a `Traversable` & `Distributive`, +homogeneous, countable product. + +> prop> traverse = ditraversed +> prop> cotraversed = ditraversed +-} +ditraversed :: (Traversable g, Distributive g) => Monocle (g a) (g b) a b +ditraversed = unwrapPafb . ditraverse . WrapPafb + +{- | Repeat action indefinitely. -} +forevered :: Monocle s t () b +forevered = unwrapPafb . foreverP . WrapPafb + +{- | Zip with `AMonocle`, by running it on the `Monoidal` `Profunctor` +of functions @f a -> g b@, generalizing both +`Control.Lens.Traversal.traverseOf`, at t'Identity' @f@, +& `Control.Lens.Grate.cotraverseOf`, at t'Identity' @g@. + +>>> zipMonocle ditraversed (\xs -> [sum xs, product xs]) [1 :+ 2, 3 :+ 4 :: Complex Int] +[4 :+ 6,4 :+ 8,3 :+ 6,3 :+ 8] +-} +zipMonocle + :: (Functor f, Applicative g) + => AMonocle s t a b -> (f a -> g b) -> f s -> g t +zipMonocle mon f ss = withMonocle mon $ \get -> f (get <$> ss) + +{- | Zip two sources with `AMonocle`; all of whose foci match. + +>>> zipWithMonocle ditraversed (+) (1 :+ 2) (3 :+ 4 :: Complex Int) +4 :+ 6 +-} +zipWithMonocle :: AMonocle s t a b -> (a -> a -> b) -> s -> s -> t +zipWithMonocle mon f s0 s1 = + runIdentity (withMonocle mon (\get -> Identity (f (get s0) (get s1)))) + +{- | Sequence an action at every focus of `AMonocle`, +needing no source, by running it on the `Monoidal` `Profunctor` +@Joker g@, like `Control.Monad.replicateM`. + +>>> replicateMonocle ditraversed "ab" :: [Complex Char] +['a' :+ 'a','a' :+ 'b','b' :+ 'a','b' :+ 'b'] +-} +replicateMonocle :: Applicative g => AMonocle s t a b -> g b -> g t +replicateMonocle mon gb = withMonocle mon (const gb) + +{- | Build from the index of each focus of `AMonocle`, numbered left to right, +like `Data.Functor.Rep.tabulate`. + +>>> tabulateMonocle ditraversed fromIntegral :: Complex Int +0 :+ 1 +-} +tabulateMonocle :: AMonocle s t a b -> (Natural -> b) -> t +tabulateMonocle mon f = + evalState (replicateMonocle mon (state (\n -> (f n, n + 1)))) 0 + +{- | The `Control.Lens.Lens.Lens`es of the foci of `AMonocle`, +numbered from 0, left to right, every one of which focuses on a source. + +Dual to `Control.Lens.Comonocle.copiesComonocle`: a product of foci has +a `Control.Lens.Lens.Lens` for each focus, every one of which focuses, +as a sum of copies has a `Control.Lens.Prism.Prism` for each copy, +exactly one of which matches. + +>>> [view (runLens focus) (1 :+ 2) | focus <- fociMonocle ditraversed] :: [Int] +[1,2] +>>> [set (runLens focus) 0 (1 :+ 2) | focus <- fociMonocle ditraversed] :: [Complex Int] +[0 :+ 2,1 :+ 0] +-} +fociMonocle :: AMonocle s s a a -> [ReifiedLens' s a] +fociMonocle mon = zipWith focusAt [0 :: Natural ..] getters + where + getters = getConst (withMonocle mon (\get -> Const [get])) + focusAt i get = Lens $ lens get $ \s a -> evalState + (withMonocle mon (\get' -> state (\n -> (if n == i then a else get' s, n + 1)))) + 0 + +{- | Run `AMonocle` over an `Applicative`. -} +withMonocle :: Applicative f => AMonocle s t a b -> ((s -> a) -> f b) -> f t +withMonocle mon = unMonocular (runIdentity <$> mon (Identity <$> Monocular ($ id))) + +{- | t'Monocular' provides an efficient +concrete representation of `Monocle`s. -} +newtype Monocular a b s t = Monocular + {unMonocular :: forall f. Applicative f => ((s -> a) -> f b) -> f t} +instance Profunctor (Monocular a b) where + dimap f g (Monocular k) = + Monocular (fmap g . k . (. (. f))) +instance Functor (Monocular a b s) where fmap = rmap +instance Applicative (Monocular a b s) where + pure t = Monocular (pure (pure t)) + Monocular x <*> Monocular y = Monocular (liftA2 (<*>) x y) + +{- | Run a t'Monocular' on a `Monoidal` `Profunctor`. -} +runMonocular :: Monoidal p => Monocular a b s t -> p a b -> p s t +runMonocular (Monocular k) p = k $ \f -> lmap f p + +{- | t'Ditraversal' is a secondary concrete representation of `Monocle`s, +by homogeneous products: a `Traversable` & `Distributive` shape, +into which a source splits its foci, & from which a target merges them. + +`Monocle`s with finitely many foci are isomorphic to t'Ditraversal's, +by `ditraversal` & `withDitraversal`. +-} +data Ditraversal a b s t where + Ditraversal + :: (Distributive f, Traversable f) + => (s -> f a) -> (f b -> t) -> Ditraversal a b s t +instance Profunctor (Ditraversal a b) where + dimap f g (Ditraversal split merge) = Ditraversal (split . f) (g . merge) +instance Functor (Ditraversal a b s) where fmap = rmap +{- | Shapes multiply by t':*:', with unit t'U1', +since products of powers add, \(a^m \times a^n = a^{m+n}\). +-} +instance Applicative (Ditraversal a b s) where + pure t = Ditraversal (const U1) (const t) + liftA2 h (Ditraversal split0 merge0) (Ditraversal split1 merge1) = + Ditraversal + (\s -> split0 s :*: split1 s) + (\(b0 :*: b1) -> h (merge0 b0) (merge1 b1)) + (<*>) = liftA2 id + +{- | Build a `Monocle` from a t'Ditraversal'. + +>>> over (ditraversal (Ditraversal (uncurry (:+)) (\(x :+ y) -> (x, y)))) negate (1, 2) +(-1,-2) +-} +ditraversal :: Ditraversal a b s t -> Monocle s t a b +ditraversal (Ditraversal split merge) = + dimap split (fmap merge) . ditraversed + +{- | Convert `AMonocle` to the pair of functions that characterize it, +splitting into & merging from a homogeneous product of its foci. +It diverges for infinitely many foci, like those of `forevered`. + +>>> withDitraversal (crossMonocle id ditraversed) $ \split _ -> toList (split (1, 2 :+ 3)) +[1,2,3] +>>> withDitraversal ditraversed (\split merge -> merge (negate <$> split (1 :+ 2))) :: Complex Int +(-1) :+ (-2) +-} +withDitraversal + :: AMonocle s t a b + -> (forall f. (Distributive f, Traversable f) + => (s -> f a) -> (f b -> t) -> r) + -> r +withDitraversal mon k = + case runMonocular monocular (Ditraversal Par1 unPar1) of + Ditraversal split merge -> k split merge + where + monocular = runIdentity <$> mon (Identity <$> Monocular ($ id)) diff --git a/distributors-core/src/Control/Lens/PartialIso.hs b/distributors-core/src/Control/Lens/PartialIso.hs new file mode 100644 index 00000000..78e1f96a --- /dev/null +++ b/distributors-core/src/Control/Lens/PartialIso.hs @@ -0,0 +1,725 @@ +{- | +Module : Control.Lens.PartialIso +Description : partial isomorphisms +Copyright : (C) 2026 - Eitan Chatav +License : BSD-style (see the file LICENSE) +Maintainer : Eitan Chatav +Stability : provisional +Portability : non-portable + +See Rendel & Ostermann, +[Invertible syntax descriptions](https://www.informatik.uni-marburg.de/~rendel/unparse/) +-} + +module Control.Lens.PartialIso + ( -- * PartialIso + PartialIso + , PartialIso' + , APartialIso + , PartialMarket (..), partialMarket, withPartialMarket + -- * Combinators + , partialIso + , partialInvoluted + , withPartialIso + , clonePartialIso + , coPartialIso + , alongsidePartialIso + , withoutPartialIso + , orPartialIso + , falsePartialIso + -- * Applicators + , dimapMaybe + , (>?) + , (?<) + , (>?<) + , (>~) + , (~<) + , (!=) + -- * Patterns + , filterPrism + , satisfied + , nulled + , notNulled + , eotMaybe + , eotList + , listed + -- * Iterators + , iterating + , difoldl1 + , difoldr1 + , difoldl + , difoldr + -- * Nested prisms + , makeNestedPrisms + , genericNestedPrism + , genericNestedIso + -- * Re-exports + , module Control.Lens.Iso + , module Control.Lens.Prism + ) where + +import Control.Lens +import Control.Lens.Internal.Distributor.Orphanage () +import Control.Lens.Prism.Nested +import Control.Lens.Internal.Profunctor +import Control.Lens.Iso +import Control.Lens.Prism +import Control.Applicative +import Control.Monad +import Data.Monoid.Disjunctive +import Data.Profunctor +import Witherable +import GHC.IsList (IsList (..)) + +-- $setup +-- >>> import Control.Lens +-- >>> import Data.Monoid.Disjunctive ((>|<)) +-- >>> import Data.Sequence (Seq) +-- >>> import GHC.IsList (fromList) + +{- | The `dimapMaybe` function endows +`Choice` & `Cochoice` "partial profunctors" +with an action `>?<` of `PartialIso`s. +-} +dimapMaybe + :: (Choice p, Cochoice p) + => (s -> Maybe a) -> (b -> Maybe t) + -> p a b -> p s t +dimapMaybe f g = + let + m2e h = maybe (Left ()) Right . h + fg = dimap (>>= m2e f) (>>= m2e g) + in + unright . fg . right' + +{- | `PartialIso` is a first class inexhaustive pattern, +similar to how `Control.Lens.Prism.Prism` is a first class exhaustive pattern, +by combining `Control.Lens.Prism.Prism`s, constructor patterns, +with `filterPrism`s, filter patterns. + +`Control.Lens.Iso.Iso` ∪ `Control.Lens.Prism.Prism` ∪ `filterPrism` +⊂ `PartialIso` ⊂ `Control.Lens.Bifocal.Bifocal`. + +Applied to a value, a pattern does one of three things. +It __matches__, focusing on part of the value, to work on & rebuild. +Or it doesn't match, & either __passes the value through__, untouched, +as a `Control.Lens.Prism.Prism` does, so there is nothing to work on, +but nothing goes wrong; or it __fails__, rejecting the value, +as a filter does. A `PartialIso` may do any of the three. + +>>> traverseOf _Just (Just . succ) (Just 1) +Just (Just 2) +>>> traverseOf _Just (Just . succ) Nothing +Just Nothing +>>> traverseOf (satisfied even) (Just . succ) 3 +Nothing + +Here `_Just` matches @Just 1@, & passes @Nothing@ through, +while @`satisfied` `even`@ fails on @3@. +Passing through & failing can only be told apart where a result +can succeed with nothing done, like `traverseOf`'s; a parser can't, +since a value that doesn't match isn't parsed, so it fails. + +`PartialIso`s are the compositions of `Control.Lens.Prism.Prism`s, +which pass a mismatch through, & `filterPrism`s, which fail, +forwards where they reject what a `Control.Lens.Prism.Prism` passes through. +Each is a `filterPrism` after a `Control.Lens.Prism.Prism`, + +> prop> partialMarket build match = filterPrism _Just . prism build (maybe (Left Nothing) match) + +& isomorphic to a t'PartialMarket', so `clonePartialIso` is the identity. + +> prop> clonePartialIso pattern = pattern + +Its partial functions, by `withPartialIso`, forget passing through, +which @`withPartialIso` pattern `partialIso`@ rebuilds from, failing instead. + +A `PartialIso` chooses whether its pattern matches by `Choice`, +& fails in either direction by `Filterable`, +emptying with @`catMaybes` (`pure` `Nothing`)@ & filtering with `mapMaybe`. +So it needs no `Cochoice` of its own, unlike its action `>?<` +on a `Choice` & `Cochoice` partial profunctor, +which has no `Filterable` to fail by. + +>>> :{ +let halve :: PartialIso' Int Int + halve = partialIso + (\n -> if even n then Just (n `div` 2) else Nothing) + (Just . (* 2)) +:} + +Forwards, a `PartialIso` folds at most one focus, +so `preview`, `^?`, `has` & `toListOf` match by it. + +>>> preview halve 6 +Just 3 +>>> 7 ^? halve +Nothing +>>> has halve 7 +False +>>> toListOf halve 6 +[3] + +Backwards, a `PartialIso` folds forwards by `coPartialIso`. + +>>> preview (coPartialIso halve) 3 +Just 6 + +`withPartialIso` converts a `PartialIso` to both directions. + +>>> withPartialIso halve $ \match build -> (match 6, build 3) +(Just 3,Just 6) + +Since it may fail to build, as well as to match, a `PartialIso` +modifies by `traverseOf` with a `Filterable` `Applicative` like `Maybe`, +in place of `over` & `set`. + +>>> traverseOf halve (Just . succ) 6 +Just 8 +>>> traverseOf halve (Just . succ) 7 +Nothing + +A `Control.Lens.Prism.Prism` is exhaustive though, +passing a mismatched source through, as does its clone, +where its partial functions, rebuilt by `partialIso`, fail. + +>>> traverseOf _Just (Just . succ) Nothing +Just Nothing +>>> traverseOf (clonePartialIso _Just) (Just . succ) Nothing +Just Nothing +>>> traverseOf (withPartialIso _Just partialIso) (Just . succ) Nothing +Nothing + +Neither `review`, `over` nor `set` applies to a `PartialIso`, +since t'Data.Functor.Identity.Identity' can't fail, so isn't `Filterable`; +& `view` applies only to a `Monoid`al focus, as for a +`Control.Lens.Fold.Fold`, by t'Data.Functor.Const.Const'. + +`PartialIso`s compose by `.`, with each other, +& with `Control.Lens.Iso.Iso`s, `Control.Lens.Prism.Prism`s & `filterPrism`s. + +>>> preview (halve . halve) 12 +Just 3 +>>> preview (_Just . halve) (Just 4) +Just 2 +>>> preview (halve . filterPrism _Just) 6 +Just (Just 3) +-} +type PartialIso s t a b = forall p f. + (Choice p, Applicative f, Filterable f) + => p a (f b) -> p s (f t) + +{- | +A simple `PartialIso'` @s a@ is an identification of +a subset of @s@ with a subset of @a@. + +A proper `PartialIso'`, with partial functions @match@ & @build@, +by `withPartialIso`, inverts what it matches & what it builds. + +> prop> match s = Just a ==> build a = Just s +> prop> build a = Just s ==> match s = Just a + +However, sometimes an improper `PartialIso'` will be useful, +matching what it builds, but not necessarily rebuilding what it matches. + +> prop> build a = Just s ==> match s = Just a + +For an improper `PartialIso'`, @norm = build <=< match@ is an idempotent + +> prop> norm = norm <=< norm + +and can be regarded as a normalization within +some equivalence class of terms. +-} +type PartialIso' s a = PartialIso s s a a + +{- | `APartialIso` is monomorphically a `PartialIso`. + +> prop> PartialIso s t a b ⊂ APartialIso s t a b +-} +type APartialIso s t a b = + PartialMarket a b a (Maybe b) -> PartialMarket a b s (Maybe t) + +{- | A t'PartialMarket' is the concrete form of a `PartialIso`, +isomorphic to it, a `Control.Lens.Internal.Prism.Market` which may fail +in either direction: building backwards, partially; +& matching forwards, either its focus, +or, where its pattern doesn't match, `Nothing`, failing, +or `Just` a target, passing through, as a `Control.Lens.Prism.Prism` does. + +> prop> withPartialMarket (partialMarket build match) k = k build match +> prop> withPartialMarket pattern partialMarket = pattern + +Its functions are those of a `Control.Lens.Prism.Prism` with a @Maybe t@ +target, a `PartialIso` failing in its target, rather than in its `Filterable`, +& the conversions are inverse. + +> prop> withPrism (withPartialMarket pattern prism :: Prism s (Maybe t) a b) partialMarket = (clonePartialIso pattern :: PartialIso s t a b) +> prop> withPartialMarket (withPrism prsm partialMarket :: PartialIso s t a b) prism = (clonePrism prsm :: Prism s (Maybe t) a b) + +So lens's `over` & `set` apply to a `PartialIso` as such a `Control.Lens.Prism.Prism`. + +>>> over (withPartialMarket (satisfied even) prism :: Prism Int (Maybe Int) Int Int) (* 2) 4 +Just 8 +>>> over (withPartialMarket (satisfied even) prism :: Prism Int (Maybe Int) Int Int) (* 2) 3 +Nothing +>>> over (withPartialMarket _Just prism :: Prism (Maybe Int) (Maybe (Maybe Int)) Int Int) succ Nothing +Just Nothing + +Only a `Choice` which isn't +`Data.Profunctor.Monoidal.Cocartesian.CocartesianChoice` +can tell passing through from failing, +like @(->)@, by `Control.Lens.Traversal.traverseOf`. + +>>> withPartialMarket _Left $ \_ match -> (match (Left 'x'), match (Right 'y') :: Either (Maybe (Either Char Char)) Char) +(Right 'x',Left (Just (Right 'y'))) +-} +data PartialMarket a b s t = + PartialMarket (b -> Maybe t) (s -> Either (Maybe t) a) +instance Functor (PartialMarket a b s) where fmap = rmap +instance Filterable (PartialMarket a b s) where + mapMaybe h (PartialMarket build match) = + PartialMarket (h <=< build) (either (Left . (h =<<)) Right . match) +instance Profunctor (PartialMarket a b) where + dimap f g (PartialMarket build match) = + PartialMarket (fmap g . build) (either (Left . fmap g) Right . match . f) +instance Choice (PartialMarket a b) where + left' (PartialMarket build match) = PartialMarket + (fmap Left . build) + (either (either (Left . fmap Left) Right . match) (Left . Just . Right)) + right' (PartialMarket build match) = PartialMarket + (fmap Right . build) + (either (Left . Just . Left) (either (Left . fmap Right) Right . match)) +instance Cochoice (PartialMarket a b) where + unleft = lmap Left . mapMaybe (either Just (const Nothing)) + unright = lmap Right . mapMaybe (either (const Nothing) Just) +{- | t'PartialMarket's choose by first success, in either direction, +& forwards, on a mismatch of both, pass through the first target passed through, +& `falseP` fails in both directions. +-} +instance DisjunctiveMonoid (PartialMarket a b s t) where + falseP = PartialMarket (const Nothing) (const (Left Nothing)) + PartialMarket build0 match0 >|< PartialMarket build1 match1 = PartialMarket + (\b -> build0 b <|> build1 b) + (\s -> case match0 s of + Right a -> Right a + Left t0 -> case match1 s of + Right a -> Right a + Left t1 -> Left (t0 <|> t1)) + +{- | Build a `PartialIso` from the functions of a t'PartialMarket', +building backwards, partially, & matching forwards, like `prism`, +either its focus, or on a mismatch, `Just` a target to pass through, +or `Nothing` to fail. + +`partialIso` builds a `PartialIso` from partial functions, +whose mismatches always fail; it is `partialMarket` +without passing through, + +> prop> partialIso match build = partialMarket build (maybe (Left Nothing) Right . match) + +so every `PartialIso` is a `partialMarket`, but not every one a `partialIso`, +like a `Control.Lens.Prism.Prism`, which passes a mismatch through. +They differ only at a `Choice` which can tell passing through from failing, +like @(->)@, by `traverseOf`. + +>>> traverseOf (partialMarket (Just . Just) (maybe (Left (Just Nothing)) Right)) (Just . succ) (Nothing :: Maybe Int) +Just Nothing +>>> traverseOf (partialIso id (Just . Just)) (Just . succ) (Nothing :: Maybe Int) +Nothing +-} +partialMarket + :: (b -> Maybe t) -> (s -> Either (Maybe t) a) + -> PartialIso s t a b +partialMarket build match = + dimap + (either (Left . maybe (catMaybes (pure Nothing)) pure) Right . match) + (either id (mapMaybe build)) + . right' + +{- | Convert `APartialIso` to the pair of functions that characterize it, +of its t'PartialMarket', building backwards, +& matching forwards, passing through or failing, like `withPrism`. -} +withPartialMarket + :: APartialIso s t a b + -> ((b -> Maybe t) -> (s -> Either (Maybe t) a) -> r) + -> r +withPartialMarket pattern k = + case catMaybes (pattern (PartialMarket (Just . Just) Right)) of + PartialMarket build match -> k build match + +{- | Build a `PartialIso` from its partial functions, +matching forwards & building backwards, +as the action `dimapMaybe` on @p a (f b)@, +like `filterPrism` is the action `?<`. +-} +partialIso :: (s -> Maybe a) -> (b -> Maybe t) -> PartialIso s t a b +partialIso f g = unwrapPafb . dimapMaybe f g . WrapPafb + +{- | Given a partial function that is its own inverse, +this gives you a `PartialIso'` using it in both directions. -} +partialInvoluted :: (a -> Maybe a) -> PartialIso' a a +partialInvoluted f = partialIso f f + +{- | Convert `APartialIso` to its partial functions, +matching forwards & building backwards, like `withIso`. +They forget passing through, failing on a mismatch which a +`Control.Lens.Prism.Prism` passes through, so they characterize +only a `PartialIso` which never passes through, one built by `partialIso`; +its t'PartialMarket', by `withPartialMarket`, characterizes any. + +> prop> withPartialIso (partialIso match build) k = k match build +-} +withPartialIso + :: APartialIso s t a b + -> ((s -> Maybe a) -> (b -> Maybe t) -> r) + -> r +withPartialIso pattern k = withPartialMarket pattern $ \build match -> + k (either (const Nothing) Just . match) build + +{- | Clone `APartialIso` so that you can reuse the same +monomorphically typed partial isomorphism for different purposes. +It keeps a `Control.Lens.Prism.Prism`'s passing a mismatch through, +unlike rebuilding it from its partial functions, +by @`withPartialIso` pattern `partialIso`@, which fails on a mismatch instead. +They agree at every `Data.Profunctor.Monoidal.Cocartesian.CocartesianChoice`, +like a parser's, which can't tell passing through from failing, +& differ at a `Choice` which can, like @(->)@, by `traverseOf`. + +> prop> clonePartialIso pattern = pattern + +>>> traverseOf (clonePartialIso _Just) (Just . succ) Nothing +Just Nothing +>>> traverseOf (withPartialIso _Just partialIso) (Just . succ) Nothing +Nothing +-} +clonePartialIso + :: APartialIso s t a b + -> PartialIso s t a b +clonePartialIso pattern = + withPartialMarket pattern partialMarket + +{- | Clone and invert `APartialIso`, by its partial functions. +Only matching forwards can pass a value through, building backwards can't, +so the inverse of a `PartialIso` which passes through fails instead. +`coPartialIso` is its own inverse on `PartialIso`s which never pass through, +those rebuilt from their partial functions, +& inverts any other as that rebuilding. + +> prop> coPartialIso pattern = coPartialIso (withPartialIso pattern partialIso) +> prop> coPartialIso (coPartialIso pattern) = withPartialIso pattern partialIso +-} +coPartialIso + :: APartialIso b a t s + -> PartialIso s t a b +coPartialIso pattern = + withPartialIso pattern $ \f g -> partialIso g f + +{- | Construct a `PartialIso` on pairs from components, +pairing their foci, as `Control.Lens.Lens.alongside` does, +passing a pair through where both components pass through, +& otherwise failing on a mismatch, since a pair passed through +needs a target from each component. + +>>> traverseOf (alongsidePartialIso _Just _Just) (\(x, y) -> Just (x + y, x * y)) (Just 2, Just 3 :: Maybe Int) +Just (Just 5,Just 6) +>>> traverseOf (alongsidePartialIso _Just _Just) (Just . id) (Nothing, Nothing :: Maybe Int) +Just (Nothing,Nothing) +>>> traverseOf (alongsidePartialIso _Just _Just) (Just . id) (Just 2, Nothing :: Maybe Int) +Nothing +-} +alongsidePartialIso + :: APartialIso s t a b + -> APartialIso u v c d + -> PartialIso (s,u) (t,v) (a,c) (b,d) +alongsidePartialIso x y = + withPartialMarket x $ \build0 match0 -> + withPartialMarket y $ \build1 match1 -> + partialMarket + (\(b,d) -> (,) <$> build0 b <*> build1 d) + (\(s,u) -> case (match0 s, match1 u) of + (Right a, Right c) -> Right (a,c) + (Left t, Left v) -> Left ((,) <$> t <*> v) + _ -> Left Nothing) + +{- | Construct a `PartialIso` on `Either`s from components, +summing their foci, as `Control.Lens.Prism.without` does, +passing a mismatch through from either. + +>>> traverseOf (withoutPartialIso _Just _Just) (Just . either (Left . succ) (Right . pred)) (Left (Just 1) :: Either (Maybe Int) (Maybe Int)) +Just (Left (Just 2)) +>>> traverseOf (withoutPartialIso _Just _Just) (Just . either (Left . succ) (Right . pred)) (Left Nothing :: Either (Maybe Int) (Maybe Int)) +Just (Left Nothing) +-} +withoutPartialIso + :: APartialIso s t a b + -> APartialIso u v c d + -> PartialIso + (Either s u) (Either t v) + (Either a c) (Either b d) +withoutPartialIso x y = + withPartialMarket x $ \build0 match0 -> + withPartialMarket y $ \build1 match1 -> + partialMarket + (either (fmap Left . build0) (fmap Right . build1)) + (either + (either (Left . fmap Left) (Right . Left) . match0) + (either (Left . fmap Right) (Right . Right) . match1)) + +{- | The union of two patterns, trying the first, then the second, +in either direction, & on a mismatch of both, +passing through the first target passed through, +by the `DisjunctiveMonoid` of their t'PartialMarket's. + +>>> [traverseOf (orPartialIso (satisfied even) (satisfied odd)) Just n | n <- [2, 3 :: Int]] +[Just 2,Just 3] + +__N.B.__ `>|<` on `APartialIso`s typechecks, pointwise, but is wrong: +it chooses within @PartialMarket a b s (Maybe t)@, whose @`Just` `Nothing`@ +is a failure, which it takes for a success. + +>>> [traverseOf (clonePartialIso (satisfied even >|< satisfied odd)) Just n | n <- [2, 3 :: Int]] +[Just 2,Nothing] +-} +orPartialIso + :: APartialIso s t a b + -> APartialIso s t a b + -> PartialIso s t a b +orPartialIso x y = + withPartialMarket x $ \build0 match0 -> + withPartialMarket y $ \build1 match1 -> + case PartialMarket build0 match0 >|< PartialMarket build1 match1 of + PartialMarket build match -> partialMarket build match + +{- | The pattern which never matches & never builds, +failing in both directions, the identity of `orPartialIso`. + +> prop> orPartialIso falsePartialIso pattern = clonePartialIso pattern +> prop> orPartialIso pattern falsePartialIso = clonePartialIso pattern +> prop> satisfied (const False) = falsePartialIso + +>>> preview falsePartialIso 'x' :: Maybe Char +Nothing +-} +falsePartialIso :: PartialIso s t a b +falsePartialIso = partialMarket (const Nothing) (const (Left Nothing)) + +{- | Action of `APrism` on `Choice` `Profunctor`s. -} +(>?) + :: Choice p + => APrism s t a b + -> p a b + -> p s t +(>?) pat = withPrism pat $ \f g -> dimap g (either id f) . right' +infixl 4 >? + +{- | The coprism, the action of a reversed `APrism` +on `Cochoice` `Profunctor`s, feeding the residual of a mismatch +back by `unright`, as in +[profunctor-optics](https://hackage.haskell.org/package/profunctor-optics), +where @coprism f g = re (prism f g)@. +`filterPrism` acts by it on @p a (f b)@, +whose `Cochoice` by a `Filterable` @f@ filters the residual out. +-} +(?<) + :: Cochoice p + => APrism b a t s + -> p a b + -> p s t +(?<) pat = withPrism pat $ \f g -> unright . dimap (either id f) g +infixl 4 ?< + +{- | Action of `APartialIso` on `Choice` & `Cochoice` partial profunctors, +passing a mismatch through by `Choice`, as `>?` does, +& failing by `Cochoice`, as `dimapMaybe` does, +so it acts on a `Control.Lens.Prism.Prism` as `>?` does, +& on partial functions as `dimapMaybe` does. + +> prop> prsm >?< p = prsm >? p +> prop> partialIso match build >?< p = dimapMaybe match build p + +A `Control.Lens.Prism.Prism` with a @Maybe t@ target acts, +by its `PartialIso`, as it does, filtering its target, +on a `Data.Profunctor.Filtrator.Filtrator`. + +> prop> withPrism prsm partialMarket >?< p = catMaybes (prsm >? p) +-} +(>?<) + :: (Choice p, Cochoice p) + => APartialIso s t a b + -> p a b + -> p s t +(>?<) pat = withPartialMarket pat $ \build match -> + unright . dimap + (either (const (Left Nothing)) match) + (either (maybe (Left ()) Right) (maybe (Left ()) Right . build)) + . right' +infixl 4 >?< + +{- | Action of `AnIso` on `Profunctor`s. -} +(>~) :: Profunctor p => AnIso s t a b -> p a b -> p s t +(>~) pattern = withIso pattern dimap +infixl 2 >~ + +{- | Inverse action of `AnIso` on `Profunctor`s. -} +(~<) :: Profunctor p => AnIso b a t s -> p a b -> p s t +(~<) pattern = withIso pattern (flip dimap) +infixl 2 ~< + +{- | An optional value, +missing exactly when it's the default, +like `Data.Aeson.!=`, +by the `non` isomorphism. + +> prop> optP != def = non def ~< optP +-} +(!=) + :: (Eq a, Profunctor q) + => q (Maybe a) (Maybe a) -- ^ optional + -> a -- ^ default + -> q a a +prop != def = non def ~< prop +infix 6 != + +{- | A filter pattern of `APrism`, as the coprism `?<` acts on @p a (f b)@, +total forwards & partial backwards, failing by `Filterable` alone. +As a `Control.Lens.Prism.Prism` is a constructor pattern, +like @Right x@ in a @case@ expression, passing any other case through, +a `filterPrism` is a filter pattern, +like @Right x <- xs@ in a comprehension or a @do@ block, +filtering any other case out, by discarding the residual of a mismatch. +It runs as its `Control.Lens.Prism.Prism` does, reversed, +building forwards by `view`, as the prism `review`s, +& matching backwards by `preview` of its `coPartialIso`, +as the prism `preview`s. + +>>> view (filterPrism _Just) 'x' +Just 'x' +>>> preview (coPartialIso (filterPrism _Just)) (Just 'x') +Just 'x' +>>> preview (coPartialIso (filterPrism _Just)) (Nothing :: Maybe Char) +Nothing + +An optic for `Data.Profunctor.Filtrator.Filtrator`s may only map its source +& filter its target, as a `filterPrism` does, since by its laws, +a `Data.Profunctor.Filtrator.Filtrator`'s `Cochoice` derives from +its `Profunctor` & `Filterable` structure, +@unleft = lmap Left . mapMaybe (either Just (const Nothing))@. +-} +filterPrism + :: (Profunctor p, Filterable f) + => APrism b a t s -> p a (f b) -> p s (f t) +filterPrism p = unwrapPafb . (?<) p . WrapPafb + +{- | `satisfied` is the prototypical proper partial isomorphism, +identifying a subset which satisfies a predicate. + +It is a homomorphism of `Data.Monoid.Disjunctive.BooleanAlgebra`s +of predicates, from `>|<` to `>|<` of its partial functions, +which choose by first success, in either direction, +& from `>&<` to composition. + +> prop> withPartialIso (satisfied (p >|< q)) (,) = withPartialIso (satisfied p) (,) >|< withPartialIso (satisfied q) (,) +> prop> withPartialIso (satisfied falseP) (,) = falseP +> prop> satisfied (p >&< q) = satisfied p . satisfied q +> prop> satisfied trueP = id +-} +satisfied :: (a -> Bool) -> PartialIso' a a +satisfied f = partialInvoluted satiate where + satiate a = if f a then Just a else Nothing + +{- | `nulled` matches an `Empty` pattern, like `_Empty`. -} +nulled :: (AsEmpty s, AsEmpty t) => PartialIso s t () () +nulled = partialIso empA empB where + empA s = if isn't _Empty s then Nothing else Just () + empB _ = Just Empty + +{- | `notNulled` matches a non-`Empty` pattern. -} +notNulled :: (AsEmpty s, AsEmpty t) => PartialIso s t s t +notNulled = partialIso nonEmp nonEmp where + nonEmp s = if isn't _Empty s then Just s else Nothing + +{- | The either-of-tuples representation of `Maybe`, +in the order of its constructors. +-} +eotMaybe :: Iso (Maybe a) (Maybe b) (Either () a) (Either () b) +eotMaybe = iso + (maybe (Left ()) Right) + (either (const Nothing) Just) + +{- | The either-of-tuples representation of list-like streams, +empty or else a cons, as lists' constructors are ordered. +-} +eotList + :: (Cons s s a a, AsEmpty t, Cons t t b b) + => Iso s t (Either () (a,s)) (Either () (b,t)) +eotList = iso + (maybe (Left ()) Right . uncons) + (either (const Empty) (review _Cons)) + +{- | A list of items as an `IsList`, like lens's @List@ pattern. +Act on an `IsList` as on lists by @listed ~< p@; +optically, into its items by @from listed@. + +>>> review listed (fromList "abc" :: Seq Char) +"abc" +-} +listed :: (IsList s, IsList t) => Iso [Item s] [Item t] s t +listed = iso fromList toList + +{- | Iterate the application of a partial isomorphism, +useful for constructing fold/unfold isomorphisms. -} +iterating :: APartialIso a b a b -> Iso a b a b +iterating pattern = withPartialIso pattern $ \f g -> + iso (iter f) (iter g) where + iter h state = maybe state (iter h) (h state) + +{- | Left fold & unfold `APartialIso` to an `Control.Lens.Iso.Iso`. -} +difoldl1 + :: Cons s t a b + => APartialIso d c (d,b) (c,a) + -> Iso (d,t) (c,s) (d,t) (c,s) +difoldl1 pattern = + let + associate = iso + (\(c,(a,s)) -> ((c,a),s)) + (\((d,b),t) -> (d,(b,t))) + step + = alongsidePartialIso id _Cons + . associate + . alongsidePartialIso (coPartialIso pattern) id + in from (iterating step) + +{- | Right fold & unfold `APartialIso` to an `Control.Lens.Iso.Iso`. -} +difoldr1 + :: Snoc s t a b + => APartialIso d c (b,d) (a,c) + -> Iso (t,d) (s,c) (t,d) (s,c) +difoldr1 pattern = + let + reorder = iso + (\((s,a),c) -> (s,(a,c))) + (\(t,(b,d)) -> ((t,b),d)) + step + = alongsidePartialIso _Snoc id + . reorder + . alongsidePartialIso id (coPartialIso pattern) + in from (iterating step) + +{- | Left fold & unfold `APartialIso` to a `Control.Lens.Prism.Prism`. -} +difoldl + :: (AsEmpty t, Cons s t a b) + => APartialIso d c (d,b) (c,a) + -> Prism d c (d,t) (c,s) +difoldl pattern + = dimap (,Empty) (fmap fst) + . difoldl1 pattern + +{- | Right fold & unfold `APartialIso` to a `Control.Lens.Prism.Prism`. -} +difoldr + :: (AsEmpty t, Snoc s t a b) + => APartialIso d c (b,d) (a,c) + -> Prism d c (t,d) (s,c) +difoldr pattern + = dimap (Empty,) (fmap snd) + . difoldr1 pattern diff --git a/src/Control/Lens/Grammar/Internal/NestedPrismTH.hs b/distributors-core/src/Control/Lens/Prism/Nested.hs similarity index 63% rename from src/Control/Lens/Grammar/Internal/NestedPrismTH.hs rename to distributors-core/src/Control/Lens/Prism/Nested.hs index 773da1b8..ce2e6fe6 100644 --- a/src/Control/Lens/Grammar/Internal/NestedPrismTH.hs +++ b/distributors-core/src/Control/Lens/Prism/Nested.hs @@ -1,5 +1,6 @@ +{-# LANGUAGE RequiredTypeArguments #-} {- | -Module : Control.Lens.Grammar.Internal.NestedPrismTH +Module : Control.Lens.Prism.Nested Description : nested pair prisms Copyright : (C) 2026 - Eitan Chatav License : BSD-style (see the file LICENSE) @@ -7,24 +8,40 @@ Maintainer : Eitan Chatav Stability : provisional Portability : non-portable -Code is duplicated from `Control.Lens.Internal.PrismTH`, +`Control.Lens.Prism.Prism`s & `Control.Lens.Iso.Iso`s +of constructors' fields as right-nested pairs, for pattern bonding, +generated by Template Haskell, with `makeNestedPrisms`, +or by `Generic`s, with `genericNestedPrism` & `genericNestedIso`. + +`makeNestedPrisms`'s code is duplicated from `Control.Lens.Internal.PrismTH`, with small tweaks to support nested pairs. -} -module Control.Lens.Grammar.Internal.NestedPrismTH +module Control.Lens.Prism.Nested ( -- * Nested prisms makeNestedPrisms + , genericNestedPrism + , genericNestedIso ) where import Control.Applicative import Control.Lens.Getter +import Control.Lens.Iso (Iso', iso) +import Control.Lens.Prism (Prism', prism') import Control.Lens.Internal.TH import Control.Lens.Lens import Control.Monad import Data.Char (isUpper) import qualified Data.List as List import Data.Set.Lens +import Data.Kind qualified as Kind import Data.Traversable +import Data.Type.Bool (If, type (||)) +import GHC.Generics + ( Generic (Rep), M1 (..), K1 (..), U1 (..) + , (:*:) (..), (:+:) (..), C, D, S, Meta (MetaCons) ) +import GHC.Generics qualified as Generics (from, to) +import GHC.TypeLits (ErrorMessage (..), Symbol, TypeError) import Language.Haskell.TH import qualified Language.Haskell.TH.Datatype as D import Language.Haskell.TH.Lens @@ -46,7 +63,7 @@ import Prelude -- by use of the applicator `Control.Lens.PartialIso.>?` -- to `Data.Profunctor.Monoidal.Monoidal` idiom notation -- with `Data.Profunctor.Monoidal.>*<`, --- or to `Data.Profunctor.Monadic.Monadic` qualified do-notation. +-- or to "Data.Profunctor.Monadic.Do" qualified do-notation. -- -- /e.g./ -- @@ -340,3 +357,154 @@ toNestedPairP :: [PatQ] -> PatQ toNestedPairP [] = tupP [] toNestedPairP [x] = x toNestedPairP (x:xs) = tupP [x, toNestedPairP xs] + +{- | A `Control.Lens.Prism.Prism` of the constructor of a `Generic` type +named by a `Symbol`, focusing its fields as right-nested pairs, +as `makeNestedPrisms` would generate, without Template Haskell: +@()@ for none, the field for one, +& @(a, (b, ...))@ for more. +Where the type & a constructor share a name, +the type is named by @type@, with @ExplicitNamespaces@, +as in `genericNestedIso`. + +>>> :set -XDeriveGeneric -XRequiredTypeArguments +>>> import Control.Lens (preview, review) +>>> import GHC.Generics (Generic) +>>> data FooBar = Foo Int | Bar Int Char Bool | Baz deriving (Show, Generic) +>>> preview (genericNestedPrism FooBar "Bar") (Bar 1 'x' True) +Just (1,('x',True)) +>>> preview (genericNestedPrism FooBar "Bar") (Foo 1) +Nothing +>>> review (genericNestedPrism FooBar "Baz") () +Baz +-} +genericNestedPrism + :: forall s -> forall (con :: Symbol) -> + (Generic s, GNestedCon con (Rep s)) + => Prism' s (ConFocus con (Rep s)) +genericNestedPrism s con = + prism' (Generics.to . gbuildCon @con) (gmatchCon @con . Generics.from @s) + +{- | A `Control.Lens.Iso.Iso` of the sole constructor of a `Generic` type, +focusing its fields as right-nested pairs, +as `makeNestedPrisms` would generate, without Template Haskell. +Where the type & its constructor share a name, as is usual, +the type is named by @type@, with @ExplicitNamespaces@. + +>>> :set -XDeriveGeneric -XRequiredTypeArguments -XExplicitNamespaces +>>> import Control.Lens (view, review) +>>> import GHC.Generics (Generic) +>>> data Point = Point Int Int Int deriving (Show, Generic) +>>> view (genericNestedIso (type Point)) (Point 1 2 3) +(1,(2,3)) +>>> review (genericNestedIso (type Point)) (4, (5, 6)) +Point 4 5 6 +-} +genericNestedIso + :: forall s -> (Generic s, GNestedIso (Rep s)) + => Iso' s (IsoFocus (Rep s)) +genericNestedIso s = + iso (gtoNested . Generics.from @s) (Generics.to . gfromNested) + +-- Whether a generic representation has a constructor of a name. +type HasCon :: Symbol -> (Kind.Type -> Kind.Type) -> Bool +type family HasCon con f where + HasCon con (M1 D m f) = HasCon con f + HasCon con (M1 C ('MetaCons con fixity fields) f) = 'True + HasCon con (l :+: r) = HasCon con l || HasCon con r + HasCon con f = 'False + +-- The right-nested pairs of a product's fields, followed by the rest. +type Rest :: Maybe Kind.Type -> Kind.Type +type family Rest r where + Rest 'Nothing = () + Rest ('Just t) = t + +type Nest :: (Kind.Type -> Kind.Type) -> Maybe Kind.Type -> Kind.Type +type family Nest f r where + Nest U1 r = Rest r + Nest (M1 S m (K1 i a)) 'Nothing = a + Nest (M1 S m (K1 i a)) ('Just t) = (a, t) + Nest (f :*: g) r = Nest f ('Just (Nest g r)) + +class GNest f (r :: Maybe Kind.Type) where + gnest :: f x -> Rest r -> Nest f r + gunnest :: Nest f r -> (f x, Rest r) +instance GNest U1 r where + gnest U1 rest = rest + gunnest rest = (U1, rest) +instance GNest (M1 S m (K1 i a)) 'Nothing where + gnest (M1 (K1 a)) () = a + gunnest a = (M1 (K1 a), ()) +instance GNest (M1 S m (K1 i a)) ('Just t) where + gnest (M1 (K1 a)) t = (a, t) + gunnest (a, t) = (M1 (K1 a), t) +instance (GNest g r, GNest f ('Just (Nest g r))) => GNest (f :*: g) r where + gnest (f :*: g) rest = gnest @f @('Just (Nest g r)) f (gnest @g @r g rest) + gunnest nested = + let + (f, rest') = gunnest @f @('Just (Nest g r)) nested + (g, rest) = gunnest @g @r rest' + in + (f :*: g, rest) + +-- The focus of a constructor of a name. +type ConFocus :: Symbol -> (Kind.Type -> Kind.Type) -> Kind.Type +type family ConFocus con f where + ConFocus con (M1 D m f) = ConFocus con f + ConFocus con (M1 C ('MetaCons con fixity fields) f) = Nest f 'Nothing + ConFocus con (l :+: r) = If (HasCon con l) (ConFocus con l) (ConFocus con r) + +class GNestedCon (con :: Symbol) f where + gmatchCon :: f x -> Maybe (ConFocus con f) + gbuildCon :: ConFocus con f -> f x +instance GNestedCon con f => GNestedCon con (M1 D m f) where + gmatchCon (M1 x) = gmatchCon @con x + gbuildCon = M1 . gbuildCon @con +instance GNest f 'Nothing + => GNestedCon con (M1 C ('MetaCons con fixity fields) f) where + gmatchCon (M1 x) = Just (gnest @f @'Nothing x ()) + gbuildCon = M1 . fst . gunnest @f @'Nothing +-- reached only where no constructor has the name +instance {-# OVERLAPPABLE #-} TypeError + ('Text "genericNestedPrism: no constructor named " ':<>: 'ShowType con) + => GNestedCon con (M1 C meta f) where + gmatchCon = error "unreachable" + gbuildCon = error "unreachable" +instance GNestedSum con (HasCon con l) l r => GNestedCon con (l :+: r) where + gmatchCon = gmatchSum @con @(HasCon con l) + gbuildCon = gbuildSum @con @(HasCon con l) + +class GNestedSum (con :: Symbol) (inLeft :: Bool) l r where + gmatchSum :: (l :+: r) x -> Maybe (ConFocus con (l :+: r)) + gbuildSum :: ConFocus con (l :+: r) -> (l :+: r) x +instance (GNestedCon con l, ConFocus con (l :+: r) ~ ConFocus con l) + => GNestedSum con 'True l r where + gmatchSum = \case + L1 x -> gmatchCon @con x + R1 _ -> Nothing + gbuildSum = L1 . gbuildCon @con +instance (GNestedCon con r, ConFocus con (l :+: r) ~ ConFocus con r) + => GNestedSum con 'False l r where + gmatchSum = \case + L1 _ -> Nothing + R1 x -> gmatchCon @con x + gbuildSum = R1 . gbuildCon @con + +-- The focus of a sole constructor. +type IsoFocus :: (Kind.Type -> Kind.Type) -> Kind.Type +type family IsoFocus f where + IsoFocus (M1 D m (M1 C c f)) = Nest f 'Nothing + +class GNestedIso f where + gtoNested :: f x -> IsoFocus f + gfromNested :: IsoFocus f -> f x +instance GNest f 'Nothing => GNestedIso (M1 D m (M1 C c f)) where + gtoNested (M1 (M1 x)) = gnest @f @'Nothing x () + gfromNested = M1 . M1 . fst . gunnest @f @'Nothing +instance TypeError + ('Text "genericNestedIso needs a type of one constructor") + => GNestedIso (M1 D m (l :+: r)) where + gtoNested = error "unreachable" + gfromNested = error "unreachable" + diff --git a/distributors-core/src/Control/Lens/Prismoid.hs b/distributors-core/src/Control/Lens/Prismoid.hs new file mode 100644 index 00000000..3389dae4 --- /dev/null +++ b/distributors-core/src/Control/Lens/Prismoid.hs @@ -0,0 +1,643 @@ +{- | +Module : Control.Lens.Prismoid +Description : prismoids +Copyright : (C) 2026 - Eitan Chatav +License : BSD-style (see the file LICENSE) +Maintainer : Eitan Chatav +Stability : provisional +Portability : non-portable +-} + +module Control.Lens.Prismoid + ( -- * Prismoid + Prismoid + , APrismoid + , Prismatoid (..), runPrismatoid + , Prismocular (..), runPrismocular, prismocular, withPrismocular + -- * Applicators + , (>?*) + , sepBy + , withOperators + -- * Combinators + , prismoid + , withPrismoid + , clonePrismoid + , crossPrismoid + , altPrismoid + , orPrismoid + , falseOptic + , opted + , lefted + , righted + , chain1 + , chain + , exactly + , atLeast + , atMost + , inRange + -- * Operator Expressions + , Operator (..) + , Assoc (..) + ) where + +import Control.Applicative +import Control.Monad (void) +import Data.Maybe (fromMaybe) +import Control.Lens +import Control.Lens.Internal.Profunctor +import Control.Lens.PartialIso +import Data.Monoid.Disjunctive (DisjunctiveMonoid (..), orP) +import Data.Profunctor.Distributor +import Data.Profunctor.Monoidal +import Data.Profunctor.Monoidal.Cocartesian +import Data.Profunctor.Unsafe ((#.)) +import Data.Traversable.Homogeneous +import Data.Void +import GHC.Generics (Par1 (..), U1 (..), V1, (:*:) (..), (:+:) (..), (:.:) (..)) + +-- $setup +-- >>> import Control.Applicative (empty) +-- >>> import Control.Lens (Prism', prism') +-- >>> import Data.Bifunctor.Joker +-- >>> import Data.Char (digitToInt, isDigit) +-- >>> import Control.Lens.Monocle (ditraversed) +-- >>> import Data.Functor.Identity (Identity (..)) +-- >>> import Data.Functor.Product (Product (..)) +-- >>> import Text.ParserCombinators.ReadP (ReadP, char, readP_to_S, satisfy) + +{- | `Prismoid`s generalize `Control.Lens.Prism.Prism`s +& `Control.Lens.Diopter.Diopter`s, combining them, +matching partially forwards, into a `Homogeneous` shape, +& building totally backwards. + +`Control.Lens.Prism.Prism` ∪ `Control.Lens.Diopter.Diopter` +⊂ `Prismoid` ⊂ `Control.Lens.Bifocal.Bifocal`. + +A `Prismoid` fails by its `Alternator`, never by its `Applicative` @f@, +so a `Control.Lens.Prism.Prism`, as a `Prismoid`, fails on a mismatch, +rather than passing it through, by the laws of +`Data.Profunctor.Monoidal.Cocartesian.CocartesianChoice`, +as rebuilding it from its partial functions, +by `Control.Lens.PartialIso.withPartialIso` & `Control.Lens.PartialIso.partialIso`, +makes it do in any `Choice`. +A `Control.Lens.Bifocal.Bifocal` adds failing backwards, by a `Witherable.Filterable` @f@. + +`Prismoid`s are isomorphic to t'Prismatoid's, +by `Homogeneous` shapes, & to t'Prismocular's, by partial probes. +-} +type Prismoid s t a b = forall p f. + (Alternator p, Applicative f) + => p a (f b) -> p s (f t) + +{- | `APrismoid` is monomorphically a `Prismoid`. + +> prop> Prismoid s t a b ⊂ APrismoid s t a b +-} +type APrismoid s t a b = + Prismatoid a b a (Identity b) -> Prismatoid a b s (Identity t) + +{- | Build a `Prismoid` from its partial match forwards, into a +`Homogeneous` shape, & its total build backwards. + +>>> withPrismoid (prismoid (\xs -> if null xs then Nothing else Just xs) id) $ \f _ -> (length <$> f "", length <$> f "ab") +(Nothing,Just 2) +-} +prismoid + :: Homogeneous h + => (s -> Maybe (h a)) -> (h b -> t) -> Prismoid s t a b +prismoid f g = unwrapPafb . runPrismatoid (Prismatoid f g) . WrapPafb + +{- | Action of a `Prismoid` on `Alternator`s, +applying it directly at the `Alternator`, without converting it +to a concrete form, so the `Alternator`'s own methods, +like `someP` & `optionP`, act as they are. + +> prop> prsm >?* p = prsm >? p +> prop> atLeast 1 >?* p = someP p +> prop> opted def >?* p = optionP def p + +So a `Prismoid` acts on an `Alternative`, by t'Joker', +as a homomorphism, @atLeast 1@ to `some`, @several@ to `many`, +& @opted@ to `optional`; & on a `Data.Monoid.Disjunctive.KleeneStarAlgebra`, +by @Data.Profunctor.Grammar.Grammor@, @atLeast 1@ to `plusK`, +@several@ to `starK` & @opted@ to `optK`. + +>>> let digits = runJoker (atLeast 1 >?* Joker (satisfy isDigit)) :: ReadP String +>>> [ds | (ds, "") <- readP_to_S digits "123"] +["123"] +-} +(>?*) :: Alternator p => Prismoid s t a b -> p a b -> p s t +pat >?* p = runIdentity #. pat (Identity #. p) +infixl 4 >?* + +{- | Clone `APrismoid` so that you can reuse the same +monomorphically typed `Prismoid` for different purposes. +-} +clonePrismoid :: APrismoid s t a b -> Prismoid s t a b +clonePrismoid pat = withPrismoid pat prismoid + +{- | Construct a `Prismoid` on pairs from components, with the same foci, +sequencing the first's foci, then the second's. + +>>> let p = runJoker (crossPrismoid (exactly 1) (atLeast 1) >?* Joker (satisfy isDigit)) +>>> [r | (r, "") <- readP_to_S p "123"] +[("1","23")] +-} +crossPrismoid + :: APrismoid s t a b + -> APrismoid u v a b + -> Prismoid (s,u) (t,v) a b +crossPrismoid x y p = + rmap (uncurry (liftA2 (,))) (clonePrismoid x p >*< clonePrismoid y p) + +{- | Construct a `Prismoid` on `Either`s from components, with the same foci. + +>>> let p = runJoker (altPrismoid (exactly 2) (exactly 1) >?* Joker (satisfy isDigit)) +>>> [r | (r, "") <- readP_to_S p "12"] +[Left "12"] +-} +altPrismoid + :: APrismoid s t a b + -> APrismoid u v a b + -> Prismoid (Either s u) (Either t v) a b +altPrismoid x y p = rmap (either (fmap Left) (fmap Right)) + (clonePrismoid x p >+< clonePrismoid y p) + +{- | Disjoin two `Prismoid`s on the same source, by `>|<`. + +> prop> orPrismoid x falseOptic = clonePrismoid x +> prop> orPrismoid falseOptic y = clonePrismoid y + +>>> let p = runJoker (orPrismoid (exactly 2) (exactly 1) >?* Joker (satisfy isDigit)) +>>> [r | (r, "") <- readP_to_S p "1"] +["1"] +-} +orPrismoid + :: APrismoid s t a b + -> APrismoid s t a b + -> Prismoid s t a b +orPrismoid x y p = clonePrismoid x p >|< clonePrismoid y p + +{- | The `Prismoid` which never matches, nor builds, the unit of the ors, +like `orPrismoid`, as `falseP` is of `>|<`, & by inclusion an optic +of every kind which ors. + +>>> [r | (r, "") <- readP_to_S (runJoker (falseOptic >?* Joker (char 'a'))) "a"] :: [String] +[] +-} +falseOptic :: Prismoid s t a b +falseOptic _ = falseP + +{- | Convert `APrismoid` to the pair of functions that characterize it. + +>>> withPrismoid (atLeast 1) $ \f _ -> (fmap length (f ""), fmap length (f "ab")) +(Nothing,Just 2) +-} +withPrismoid + :: APrismoid s t a b + -> (forall h. Homogeneous h => (s -> Maybe (h a)) -> (h b -> t) -> r) + -> r +withPrismoid pat k = + case runIdentity <$> pat (Identity <$> Prismatoid (Just . Par1) unPar1) of + Prismatoid f g -> k f g + +{- | Exactly some number of times, or separated by `sepBy`. + +> prop> exactly n = inRange n (Just n) +> prop> exactly n >?* p = replicateP n p, for @n >= 0@ +-} +exactly :: Int -> Prismoid [a] [b] a b +exactly n = inRange n (Just n) + +{- | At least some number of times, or separated by `sepBy`, +ending with the `Alternator`'s own `someP`, or, for at least none, +its own `manyP`. + +> prop> atLeast n = inRange n Nothing +> prop> atLeast 0 = several +> prop> atLeast 1 >?* p = someP p + +>>> let digits n = runJoker (atLeast n >?* Joker (satisfy isDigit)) :: ReadP String +>>> [ds | (ds, "") <- readP_to_S (digits 2) "123"] +["123"] +>>> [ds | (ds, "") <- readP_to_S (digits 2) "1"] +[] +-} +atLeast :: Int -> Prismoid [a] [b] a b +atLeast n = inRange n Nothing + +{- | At most some number of times, trying more first, +or separated by `sepBy`. + +> prop> atMost n = inRange 0 (Just n) + +>>> let digits n = runJoker (atMost n >?* Joker (satisfy isDigit)) :: ReadP String +>>> [ds | (ds, "") <- readP_to_S (digits 2) "12"] +["12"] +>>> [ds | (ds, "") <- readP_to_S (digits 2) "123"] +[] +-} +atMost :: Int -> Prismoid [a] [b] a b +atMost n = inRange 0 (Just n) + +{- | 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,}@, or separated by `sepBy`. +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@, 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"] +["123"] +>>> [ds | n <- [1 .. 4], (ds, "") <- readP_to_S (digits 2 (Just 3)) (take n "1234")] +["12","123"] +-} +inRange :: Int -> Maybe Int -> Prismoid [a] [b] a b +inRange lo hi = rmap sequenceA . quantP lo hi + +{- | One or zero with default. -} +opted :: APrism a b () () -> Prismoid a b a b +opted def = unwrapPafb . optionP def . WrapPafb + +{- | `lefted` is like `_Left`, except +with heterogeneous `Right` parameters. -} +lefted :: Prismoid (Either a c) (Either b d) a b +lefted = unwrapPafb . alternate . Left . WrapPafb + + +{- | `righted` is like `_Right`, except +with heterogeneous `Left` parameters. -} +righted :: Prismoid (Either c a) (Either d b) a b +righted = unwrapPafb . alternate . Right . WrapPafb + +{- | +Associate a binary constructor pattern to sequence one or more times, +`Left` or `Right` associated, folding & unfolding it by +`Control.Lens.PartialIso.difoldl` or `Control.Lens.PartialIso.difoldr`, +or separated by `sepBy`. +-} +chain1 + :: (forall x. x -> Either x x) -- ^ `Left` or `Right` associate + -> APartialIso a b (a,a) (b,b) -- ^ binary constructor pattern + -> Prismoid a b a b +chain1 assoc binPat = unwrapPafb . chainP . WrapPafb + where + chainP p = case assoc () of + Left _ -> difoldl binPat >? p >*< manyP p + Right _ -> difoldr binPat >? manyP p >*< p + +{- | +Associate a binary constructor pattern to sequence one or more times, +or use a nilary constructor pattern to sequence zero times, +like `chain1` & `opted`, +or separated by `sepBy`. +-} +chain + :: (forall x. x -> Either x x) -- ^ `Left` or `Right` associate + -> APartialIso a b (a,a) (b,b) -- ^ binary constructor pattern + -> APrism a b () () -- ^ nilary constructor pattern + -> Prismoid a b a b +chain assoc binPat nilPat = opted nilPat . chain1 assoc binPat + +{- | A t'Prismatoid' provides efficient access +to the pair of functions that make up a `Prismoid`, +like a t'Control.Lens.Diopter.Dioptrice' which may fail to match. +-} +data Prismatoid a b s t where + Prismatoid + :: Homogeneous h + => (s -> Maybe (h a)) + -> (h b -> t) + -> Prismatoid a b s t +instance Profunctor (Prismatoid a b) where + dimap f' g' (Prismatoid f g) = Prismatoid (f . f') (g' . g) +instance Functor (Prismatoid a b s) where fmap = rmap +instance Applicative (Prismatoid a b s) where + pure t = Prismatoid (const (Just U1)) (const t) + liftA2 h (Prismatoid f0 g0) (Prismatoid f1 g1) = Prismatoid + (\s -> liftA2 (:*:) (f0 s) (f1 s)) + (\(x :*: y) -> h (g0 x) (g1 y)) + (<*>) = liftA2 id +instance Alternative (Prismatoid a b s) where + empty = Prismatoid (const Nothing) (\(v :: V1 b) -> case v of {}) + Prismatoid f0 g0 <|> Prismatoid f1 g1 = Prismatoid + (\s -> (L1 <$> f0 s) <|> (R1 <$> f1 s)) + (\case {L1 x -> g0 x; R1 y -> g1 y}) +instance DisjunctiveMonoid (Prismatoid a b s t) +instance CocartesianMonoidal (Prismatoid a b) where + zeroP = Prismatoid absurd (\(v :: V1 b) -> case v of {}) + Prismatoid f0 g0 >+< Prismatoid f1 g1 = Prismatoid + (either (fmap L1 . f0) (fmap R1 . f1)) + (\case {L1 x -> Left (g0 x); R1 y -> Right (g1 y)}) +instance Choice (Prismatoid a b) where + left' = alternate . Left + right' = alternate . Right +instance CocartesianChoice (Prismatoid a b) where + alternate = \case + Left (Prismatoid f g) -> Prismatoid (either f (const Nothing)) (Left . g) + Right (Prismatoid f g) -> Prismatoid (either (const Nothing) f) (Right . g) +instance Distributor (Prismatoid a b) where + optionalP (Prismatoid f g) = + Prismatoid (fmap Comp1 . traverse f) (fmap g . unComp1) + manyP (Prismatoid f g) = + Prismatoid (fmap Comp1 . traverse f) (fmap g . unComp1) +instance Alternator (Prismatoid a b) + +{- | Run a t'Prismatoid' on an `Alternator`, +failing by `falseP` where it doesn't match. -} +runPrismatoid :: Alternator p => Prismatoid a b s t -> p a b -> p s t +runPrismatoid (Prismatoid f g) p = + dialt (maybe (Left ()) Right . f) id g falseP (homogeneously p) + +{- | t'Prismocular' is a secondary concrete representation of `Prismoid`s, +by partial probes of a source, run in an `Alternative`, +as a t'Control.Lens.Bifocal.Binocular' is of +`Control.Lens.Bifocal.Bifocal`s, without filtering. +-} +newtype Prismocular a b s t = Prismocular + { unPrismocular + :: forall f. Alternative f => ((s -> Maybe a) -> f b) -> f t + } +instance Profunctor (Prismocular a b) where + dimap f g (Prismocular k) = Prismocular $ fmap g . k . (. (. f)) +instance Functor (Prismocular a b s) where fmap = rmap +instance Applicative (Prismocular a b s) where + pure t = Prismocular (pure (pure t)) + Prismocular x <*> Prismocular y = Prismocular (liftA2 (<*>) x y) +instance Alternative (Prismocular a b s) where + empty = Prismocular (pure empty) + Prismocular x <|> Prismocular y = Prismocular (liftA2 (<|>) x y) + many = lmap repeat . manyP + some = lmap repeat . someP +instance DisjunctiveMonoid (Prismocular a b s t) +instance Choice (Prismocular a b) where + left' = alternate . Left + right' = alternate . Right +instance CocartesianMonoidal (Prismocular a b) +instance CocartesianChoice (Prismocular a b) where + alternate = \case + Left (Prismocular k) -> Prismocular $ + fmap Left . k . (. (\f -> either f (const Nothing))) + Right (Prismocular k) -> Prismocular $ + fmap Right . k . (. (\f -> either (const Nothing) f)) +instance Distributor (Prismocular a b) +instance Alternator (Prismocular a b) + +{- | Run a t'Prismocular' on an `Alternator`, +failing by `falseP` where a probe doesn't match. -} +runPrismocular :: Alternator p => Prismocular a b s t -> p a b -> p s t +runPrismocular (Prismocular k) p = + k $ \probe -> dialt (maybe (Left ()) Right . probe) id id falseP p + +{- | Build a `Prismoid` from a t'Prismocular'. -} +prismocular :: Prismocular a b s t -> Prismoid s t a b +prismocular pm = unwrapPafb . runPrismocular pm . WrapPafb + +{- | Run `APrismoid` by partial probes in an `Alternative`. + +>>> withPrismocular (atLeast 1) (\probe -> maybe empty pure (probe "")) :: Maybe String +Nothing +>>> withPrismocular (atLeast 1) (\probe -> maybe empty pure (probe "ab")) :: Maybe String +Just "ab" +-} +withPrismocular + :: Alternative g + => APrismoid s t a b -> ((s -> Maybe a) -> g b) -> g t +withPrismocular pat = unPrismocular (clonePrismoid pat >?* Prismocular ($ Just)) + +{- | Action of a `Prismoid` on `Alternator`s, like `>?*`, +with a separator between consecutive foci, data-free, +so a shape of @n@ foci gets @n - 1@ separators, +like `Data.List.intersperse`. Delimiters compose around it, +@beg >* sepBy sep pat p *< end@. +It applies the `Prismoid` directly, as `>?*` does, so the `Alternator`'s +own `manyP`, `someP`, `optionalP` & `optionP` sequence the foci, +by an upper triangular matrix of actions. +It prefers sequencing foci to sequencing none, +so a deterministic `Alternator` sequences them greedily. + +> prop> sepBy oneP pat p = pat >?* p +> prop> sepBy sep (atLeast 1) p = p >:< manyP (sep >* p) +> prop> sepBy sep several p = p >:< manyP (sep >* p) <|> asEmpty + +Separating `Control.Lens.Diopter.several`, `atLeast`, `atMost`, `inRange`, +`chain1`, `chain` or `exactly`, it sequences +lists, binary constructor patterns, or a number of repetitions; +& separating a `Control.Lens.Monocle.Monocle`, like +`Control.Lens.Monocle.ditraversed`, the positions of a fixed product. +Other `IsList`s act as lists by @`Control.Lens.PartialIso.listed` ~<@. + +>>> let comma = Joker (() <$ char ',') +>>> let digit = Joker (satisfy isDigit) +>>> let digits = runJoker (sepBy comma (atLeast 1) digit) :: ReadP String +>>> [ds | (ds, "") <- readP_to_S digits "1,2,3"] +["123"] +>>> let pair = runJoker (sepBy comma ditraversed digit) :: ReadP (Product Identity Identity Char) +>>> [ds | (ds, "") <- readP_to_S pair "1,2"] +[Pair (Identity '1') (Identity '2')] +-} +sepBy + :: Alternator p + => p () () -> Prismoid s t a b -> p a b -> p s t +sepBy sep pat p = + case pat >?* UpperTriangular Nothing p (sep >* p) of + UpperTriangular noFoci firstFoci _ -> maybe firstFoci (firstFoci <|>) noFoci + +{- | An upper triangular matrix of actions, @[n f; 0 l]@, +of transitions between two states, an `Alternator` by +matrix product `liftA2`, entrywise alternation `<|>`, & the star +@manyP [n f; 0 l] = [n*, n* f l*; 0, l*]@. + +Its first entry is `Nothing` where it's zero statically, +so that the star of a matrix @[0 f; 0 l]@ is @f l*@. +Where it's an action, the star's @n* f l*@ is @`manyTillP` n (f l*)@, +which a static `Alternator`, like a `Control.Lens.Grammar.Grammor`, +defines without recursing. + +`sepBy` separates foci by it, its states before any focus & after one: +before any focus, an action sequences no focus, @n@, or some, its first +unseparated, @f@; after one, it separates every focus, @l@. +Where both are possible, it prefers a focus to none, greedily. +-} +data UpperTriangular p a b = UpperTriangular (Maybe (p a b)) (p a b) (p a b) +instance Profunctor p => Profunctor (UpperTriangular p) where + dimap f g ~(UpperTriangular n x y) = + UpperTriangular (dimap f g <$> n) (dimap f g x) (dimap f g y) +instance Alternator p => Functor (UpperTriangular p a) where fmap = rmap +instance Alternator p => Applicative (UpperTriangular p a) where + pure b = UpperTriangular (Just (pure b)) empty (pure b) + liftA2 h ~(UpperTriangular xn xf xl) ~(UpperTriangular yn yf yl) = UpperTriangular + (liftA2 (liftA2 h) xn yn) + (maybe id (\n -> (<|> liftA2 h n yf)) xn (liftA2 h xf yl)) + (liftA2 h xl yl) +instance Alternator p => Alternative (UpperTriangular p a) where + empty = UpperTriangular Nothing empty empty + ~(UpperTriangular xn xf xl) <|> ~(UpperTriangular yn yf yl) = + UpperTriangular (liftA2 (<|>) xn yn <|> xn <|> yn) (xf <|> yf) (xl <|> yl) +instance Alternator p => DisjunctiveMonoid (UpperTriangular p a b) +instance Alternator p => Choice (UpperTriangular p) where + left' = alternate . Left + right' = alternate . Right +instance Alternator p => CocartesianMonoidal (UpperTriangular p) where + zeroP = UpperTriangular Nothing zeroP zeroP + ~(UpperTriangular xn xf xl) >+< ~(UpperTriangular yn yf yl) = UpperTriangular + ((fromMaybe empty xn >+< fromMaybe empty yn) <$ (void xn <|> void yn)) + (xf >+< yf) + (xl >+< yl) +instance Alternator p => CocartesianChoice (UpperTriangular p) where + alternate = \case + Left ~(UpperTriangular n x y) -> UpperTriangular + (alternate . Left <$> n) (alternate (Left x)) (alternate (Left y)) + Right ~(UpperTriangular n x y) -> UpperTriangular + (alternate . Right <$> n) (alternate (Right x)) (alternate (Right y)) +{- | Repetitions sequence by the `Alternator`'s own methods: with no foci, +or, after a focus, separating every focus. Before the first focus, +repetitions without foci may precede it. -} +instance Alternator p => Distributor (UpperTriangular p) where + manyP ~(UpperTriangular n x y) = + UpperTriangular (Just (manyP (fromMaybe empty n))) f (manyP y) + where + f = maybe id manyTillP n (x >:< manyP y) + optionalP ~(UpperTriangular n x y) = UpperTriangular + (Just (optionalP (fromMaybe empty n))) (_Just >? x) (optionalP y) +instance Alternator p => Alternator (UpperTriangular p) where + someP i@(~(UpperTriangular n _ y)) = case manyP i of + ~(UpperTriangular _ f _) -> UpperTriangular (someP <$> n) f (someP y) + optionP def ~(UpperTriangular n x y) = UpperTriangular + (Just (optionP def (fromMaybe empty n))) x (optionP def y) + manyTillP ~(UpperTriangular n x y) ~(UpperTriangular n' x' y') = + UpperTriangular (maybe id manyTillP n <$> n') f l + where + l = manyTillP y y' + f = maybe id manyTillP n (x' <|> x >:< l) + +{- | An operator at some level of an operator table, for use with +`withOperators`. `Infix` takes an `Assoc` to distinguish binary operators; +`Prefix` & `Postfix` are for unary operators. -} +data Operator p a b where + Infix + :: Assoc -- ^ `NonAssoc`, `LeftAssoc`, `RightAssoc` + -> APrism a b (a,a) (b,b) -- ^ binary constructor pattern + -> p () () -- ^ operator symbol + -> Operator p a b + Prefix + :: APrism a b a b -- ^ unary constructor pattern + -> p () () -- ^ operator symbol + -> Operator p a b + Postfix + :: APrism a b a b -- ^ unary constructor pattern + -> p () () -- ^ operator symbol + -> Operator p a b + +{- | The associativity of an `Infix` binary operator. -} +data Assoc = NonAssoc | LeftAssoc | RightAssoc + deriving stock (Eq, Ord, Show, Read) + +{- | Build an expression `Alternator` from a table of `Operator`s and +an atomic term `Alternator`, analogous to @buildExpressionParser@ from +[parsec](https://hackage.haskell.org/package/parsec). + +The operator table is a list of list of operators, ordered from highest to lowest precedence. +Each level is a list of `Operator`s which share precedence. +Within a level, `Infix` takes an `Assoc` to set left, right or non-associativity for binary operators, +while `Prefix` & `Postfix` are for unary operators. + +Its operator symbols are actions of the `Alternator` @p@, data-free, +so, unlike a `Prismoid`, it isn't polymorphic in @p@. + +>>> :{ +data Sum = Digit Int | Plus Sum Sum deriving Show +_Plus :: Prism' Sum (Sum, Sum) +_Plus = prism' (uncurry Plus) (\case Plus x y -> Just (x, y); _ -> Nothing) +:} + +>>> let plus = Infix LeftAssoc _Plus (Joker (() <$ char '+')) +>>> let digit = Joker (Digit . digitToInt <$> satisfy isDigit) +>>> [e | (e, "") <- readP_to_S (runJoker (withOperators [[plus]] digit)) "1+2+3"] +[Plus (Plus (Digit 1) (Digit 2)) (Digit 3)] + +For a larger example, see the expression grammar in "Control.Lens.Grammar", +of natural numbers with postfix, right-associative & left-associative operators. +-} +withOperators + :: Alternator p + => [[Operator p a b]] -- ^ operator table + -> p a b -- ^ atomic term + -> p a b -- ^ expression +withOperators table p = foldl makeLevel p table + where + makeLevel term ops = + let + (infixes, pres, posts) = foldr splitOp ([],[],[]) ops + termP = withPostP posts (withPreP pres term) + in + infixP infixes termP + + splitOp oper (infixes, pres, posts) = case oper of + Infix associativity pat sym -> ((associativity,pat,sym):infixes, pres, posts) + Prefix pat sym -> (infixes, (pat,sym):pres, posts) + Postfix pat sym -> (infixes, pres, (pat,sym):posts) + + tagSepP syms = orP [only i >? sym | (i, sym) <- zip [0 :: Int ..] syms] + + withPreP ops inner = + difoldr (taggedP (,) id (fst <$> ops)) + >? manyP (tagSepP (snd <$> ops)) >*< inner + + withPostP ops inner = + difoldl (taggedP (flip (,)) (\(y,i) -> (i,y)) (fst <$> ops)) + >? inner >*< manyP (tagSepP (snd <$> ops)) + + -- unary operators' patterns, tagged by their positions, + -- & tried in turn, as one partial isomorphism + taggedP + :: (Int -> x -> c) -- ^ tag a match + -> (d -> (Int, y)) -- ^ untag a build + -> [APrism x y x y] -> PartialIso x y c d + taggedP tag untag pats = + let (fwd, bwd) = orP (zipWith exchange [0 ..] pats) in partialIso fwd bwd + where + exchange i pat = let (match, build) = patternFns pat in + (fmap (tag i) . match, \d -> case untag d of + (j, y) | j == i -> Just (build y) + _ -> Nothing) + + -- An operand, then @(operator, operand)@ steps, folded by each + -- operator's associativity, like parsec's @buildExpressionParser@: + -- https://hackage.haskell.org/package/parsec/docs/src/Text.Parsec.Expr.html + infixP infixes term = + prism (uncurry go) (Right . fwd) >? term >*< manyP (tagSepP syms >*< term) + where + syms = [sym | (_,_,sym) <- infixes] + fns = [(associativity,f,g) | (associativity,pat,_) <- infixes, let (f,g) = patternFns pat] + + assocOf i = let (associativity,_,_) = fns !! i in associativity + applyTag i (l,r) = let (_,_,g) = fns !! i in g (l,r) + + -- fold a shared seed together with a left-to-right list of tagged + -- steps, dispatching on each step's `Assoc`iativity in turn + go l [] = l + go l ((i,r):more) = case assocOf i of + RightAssoc -> applyTag i (l, go r more) + _ -> go (applyTag i (l,r)) more + + -- the exact inverse of `go`: decompose a value into a seed and the + -- list of tagged steps that `go` would fold back into that value + fwd x = decompose x [] + where + -- decompose y steps = (seed, the steps of y ++ steps) + decompose y steps = case tryTags y of + Nothing -> (y, steps) + Just (i,l,r) -> case assocOf i of + RightAssoc -> + let (r0, rest) = decompose r steps in (l, (i,r0) : rest) + _ -> decompose l ((i,r) : steps) + tryTags y = orP + [ (\(l,r) -> (i,l,r)) <$> f y + | (i,(_,f,_)) <- zip [0 :: Int ..] fns ] + + -- an operator's constructor pattern, matching partially & building totally + patternFns pat = withPrism pat $ \construct match -> + (either (const Nothing) Just . match, construct) diff --git a/distributors-core/src/Control/Lens/Varifocal.hs b/distributors-core/src/Control/Lens/Varifocal.hs new file mode 100644 index 00000000..2dabf629 --- /dev/null +++ b/distributors-core/src/Control/Lens/Varifocal.hs @@ -0,0 +1,405 @@ +-- `Varifocal` requires a `Filterable` monad, so that every +-- `Control.Lens.Bifocal.Bifocal` is a `Varifocal`, which `ctxList` & +-- its combinators, generic in their streams, needn't use. +{-# OPTIONS_GHC -Wno-redundant-constraints #-} +{- | +Module : Control.Lens.Varifocal +Description : varifocals +Copyright : (C) 2026 - Eitan Chatav +License : BSD-style (see the file LICENSE) +Maintainer : Eitan Chatav +Stability : provisional +Portability : non-portable +-} + +module Control.Lens.Varifocal + ( -- * Varifocal + Varifocal + , Varifocal' + , AVarifocal + , Varifocus (..) + , varifocus + , runVarifocus + , runVarifocusT + , cloneVarifocal + , crossVarifocal + , altVarifocal + , orVarifocal + , bindVarifocal + -- * Applicator + , contextually + , contextuallyT + -- * Combinators + , ctxList + , ctxTree + , terminateBy + , delimitBy + , balanceBy + , countWith + , arityWith + ) where + +import Control.Applicative (Alternative (..)) +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 (..), anyP) +import Data.Profunctor (Cochoice (..)) +import Data.Profunctor.Distributor +import Data.Profunctor.Filtrator (Filtrator (..), mfiltrate) +import Data.Profunctor.Monadic (Monadic, MonadicTrans (..)) +import qualified Data.Profunctor.Monadic.Do as P +import Data.Profunctor.Monoidal (asEmpty, (>*<)) +import Data.Profunctor.Monoidal.Cocartesian +import Witherable (Filterable (..)) + +{- | `Varifocal`s are context-sensitive bidirectional parser optics, +whose shape may depend on the foci they build, +as varifocal lenses refocus by what they're looking at. +Their `Applicative` is the monad @m@ of a `MonadicTrans` profunctor, +whose effects it absorbs by `joinP`, so failure & choice backwards +have a home, rather than needing flattening. + +`Control.Lens.Bifocal.Bifocal` ⊂ `Varifocal`, + +instantiating a `Control.Lens.Bifocal.Bifocal`'s @p@ & @f@ +as @p m@ & @m@, so every `Control.Lens.Prism.Prism`, +`Control.Lens.Prismoid.Prismoid` & `Control.Lens.Bifocal.Bifocal` +is a `Varifocal` too, composing with them by @(.)@. + +Unlike them, a `Varifocal` needs a `MonadicTrans` profunctor, +like a @Data.Profunctor.Grammar.Printor@ or @Parsor@, +so static ones, like a @Data.Profunctor.Grammar.Grammor@, can't run it. +Nor can a @Data.Profunctor.Grammar.Parsector.Parsector@, by design: +its failure backtracks by its state, which a `Varifocal`'s failure, +by its monad's `mzero`, can't reach, & its backtracking can't undo +a monad's effects. +-} +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 simple `Varifocal`. -} +type Varifocal' s a = Varifocal s s a a + +{- | `AVarifocal` is monomorphically a `Varifocal`, +at the free t'Varifocus', whose monad is the list monad, +which embeds into every `MonadPlus`. + +> prop> Varifocal s t a b ⊂ AVarifocal s t a b +-} +type AVarifocal s t a b = + Varifocus a b [] a [b] -> Varifocus a b [] s [t] + +{- | A t'Varifocus' is the concrete form of a `Varifocal`, +a free `MonadicTrans` `Alternator` on one `FocusP`: its syntax, +with a constructor for each method which can't be derived, +& for each one which a target may override, like `manyP`, +so that running it, by `runVarifocus`, keeps the target's own. +Its `Filterable`, `Cochoice` & `Filtrator` derive from its +`Monad` & `Alternative`, by `mfiltrate`. +-} +data Varifocus a b m s t where + FocusP :: Varifocus a b m a b + LiftP :: m t -> Varifocus a b m s t + BindP + :: Varifocus a b m s x + -> (x -> Varifocus a b m s t) + -> Varifocus a b m s t + LmapP :: (s -> s') -> Varifocus a b m s' t -> Varifocus a b m s t + AltsP :: [Varifocus a b m s t] -> Varifocus a b m s t + AlternateP + :: Either (Varifocus a b m s t) (Varifocus a b m s' t') + -> Varifocus a b m (Either s s') (Either t t') + ManyP :: Varifocus a b m s t -> Varifocus a b m [s] [t] + OptionalP :: Varifocus a b m s t -> Varifocus a b m (Maybe s) (Maybe t) + SomeP :: Varifocus a b m s t -> Varifocus a b m [s] [t] + OptionP :: APrism s t () () -> Varifocus a b m s t -> Varifocus a b m s t + ManyTillP + :: Varifocus a b m s t + -> Varifocus a b m [s] [t] + -> Varifocus a b m [s] [t] +instance Monad m => Profunctor (Varifocus a b m) where + dimap f g = lmap f . rmap g + lmap = LmapP + rmap g x = BindP x (LiftP . pure . g) +instance Monad m => Functor (Varifocus a b m s) where fmap = rmap +instance Monad m => Applicative (Varifocus a b m s) where + pure = LiftP . pure + (<*>) = ap +instance Monad m => Monad (Varifocus a b m s) where + (>>=) = BindP +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 + right' = AlternateP . Right +instance Monad m => CocartesianMonoidal (Varifocus a b m) +instance Monad m => CocartesianChoice (Varifocus a b m) where + alternate = AlternateP +instance Monad m => Distributor (Varifocus a b m) where + manyP = ManyP + optionalP = OptionalP +instance Monad m => Alternator (Varifocus a b m) where + someP = SomeP + optionP = OptionP + manyTillP = ManyTillP +instance Monad m => Filterable (Varifocus a b m s) where + mapMaybe f x = x >>= maybe empty pure . f +instance Monad m => Cochoice (Varifocus a b m) where + unleft = fst . filtrate + unright = snd . filtrate +instance Monad m => Filtrator (Varifocus a b m) where + filtrate = mfiltrate +instance MonadicTrans (Varifocus a b) where + liftP = LiftP + +{- | The t'Varifocus' of `AVarifocal`, at any `MonadPlus`, +into which its list monad's choices embed. +-} +varifocus :: MonadPlus m => AVarifocal s t a b -> Varifocus a b m s t +varifocus vari = go (joinP (vari (rmap pure FocusP))) + where + go :: MonadPlus m => Varifocus a b [] s' t' -> Varifocus a b m s' t' + go = \case + FocusP -> FocusP + LiftP xs -> LiftP (foldr (mplus . pure) mzero xs) + BindP x k -> BindP (go x) (go . k) + LmapP f x -> LmapP f (go x) + AltsP xs -> AltsP (map go xs) + AlternateP e -> AlternateP (either (Left . go) (Right . go) e) + ManyP x -> ManyP (go x) + OptionalP x -> OptionalP (go x) + SomeP x -> SomeP (go x) + OptionP d x -> OptionP d (go x) + ManyTillP x y -> ManyTillP (go x) (go y) + +{- | Run a t'Varifocus' of the list monad on a `Monadic` `Alternator`, +interpreting each constructor by its method, +& its lists of choices by the `Alternator`'s own. +-} +runVarifocus + :: forall p a b s t. (Monadic p, Alternator p) + => Varifocus a b [] s t -> p a b -> p s t +runVarifocus v p = go v + where + go :: Varifocus a b [] s' t' -> p s' t' + go = \case + FocusP -> p + LiftP xs -> anyP pure xs + BindP x k -> go x >>= go . k + LmapP f x -> lmap f (go x) + AltsP xs -> anyP go xs + AlternateP e -> alternate (either (Left . go) (Right . go) e) + ManyP x -> manyP (go x) + OptionalP x -> optionalP (go x) + SomeP x -> someP (go x) + OptionP d x -> optionP d (go x) + ManyTillP x y -> manyTillP (go x) (go y) + +{- | Run a t'Varifocus' on a `MonadicTrans` `Alternator`, +interpreting each constructor by its method. +-} +runVarifocusT + :: forall p m a b s t. (MonadicTrans p, Alternator (p m), Monad m) + => Varifocus a b m s t -> p m a b -> p m s t +runVarifocusT v p = go v + where + go :: Varifocus a b m s' t' -> p m s' t' + go = \case + FocusP -> p + LiftP mt -> liftP mt + BindP x k -> go x >>= go . k + LmapP f x -> lmap f (go x) + AltsP xs -> anyP go xs + AlternateP e -> alternate (either (Left . go) (Right . go) e) + ManyP x -> manyP (go x) + OptionalP x -> optionalP (go x) + SomeP x -> someP (go x) + OptionP d x -> optionP d (go x) + ManyTillP x y -> manyTillP (go x) (go y) + +{- | Clone `AVarifocal` so that you can reuse the same +monomorphically typed `Varifocal` for different purposes. +-} +cloneVarifocal :: AVarifocal s t a b -> Varifocal s t a b +cloneVarifocal vari q = rmap pure (runVarifocusT (varifocus vari) (joinP q)) + +{- | Two `AVarifocal`s of the same foci, side by side, on a pair. -} +crossVarifocal + :: AVarifocal s t a b + -> AVarifocal u v a b + -> Varifocal (s,u) (t,v) a b +crossVarifocal x y q = rmap (uncurry (liftA2 (,))) + (cloneVarifocal x q >*< cloneVarifocal y q) + +{- | Two `AVarifocal`s of the same foci, one or the other, on a sum. -} +altVarifocal + :: AVarifocal s t a b + -> AVarifocal u v a b + -> Varifocal (Either s u) (Either t v) a b +altVarifocal x y q = rmap (either (fmap Left) (fmap Right)) + (cloneVarifocal x q >+< cloneVarifocal y q) + +{- | Two `AVarifocal`s of the same source, disjoined by `>|<`. + +> prop> orVarifocal x falseOptic = cloneVarifocal x +> prop> orVarifocal falseOptic y = cloneVarifocal y +-} +orVarifocal + :: AVarifocal s t a b + -> AVarifocal s t a b + -> Varifocal s t a b +orVarifocal x y q = cloneVarifocal x q >|< cloneVarifocal y q + +{- | An `AVarifocal`, then another, chosen by what the first built, +on a pair, as only `Varifocal`s can, +like a netstring's length, then that many foci. + +> prop> bindVarifocal x (const y) = crossVarifocal x y +-} +bindVarifocal + :: AVarifocal s t a b + -> (t -> AVarifocal u v a b) + -> Varifocal (s,u) (t,v) a b +bindVarifocal x k q = rmap pure + (joinP (cloneVarifocal x q) P.>>= \t -> joinP (cloneVarifocal (k t) q)) + +{- | Action of `AVarifocal` on `Monadic` `Alternator`s, +like a @Control.Lens.Grammar.CtxGrammar@'s, by its t'Varifocus', +whose choices & failures are the `Alternator`'s own, +so that it backtracks as the `Alternator` does. + +> prop> contextually vari = runVarifocus (varifocus vari) +-} +contextually + :: (Monadic p, Alternator p) + => AVarifocal s t a b -> p a b -> p s t +contextually vari = runVarifocus (varifocus vari) + +{- | Action of a `Varifocal` on `MonadicTrans` `Alternator`s, +absorbing its monad by `joinP`, applying it directly. + +> prop> contextuallyT vari p = joinP (vari (rmap pure p)) +-} +contextuallyT + :: (MonadicTrans p, Alternator (p m), MonadPlus m, Filterable m) + => Varifocal s t a b -> p m a b -> p m s t +contextuallyT vari p = joinP (vari (rmap pure p)) + +{- | Foci stepped through by a deterministic machine, from a state, +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 stream, like a list, matches when its last focus, +& no earlier one, stops it. +-} +ctxList + :: (Cons s s a a, AsEmpty s) + => st -> (st -> a -> Either Bool st) -> Varifocal' s a +ctxList st0 step q = rmap pure (go st0) + where + go st = _Cons >? P.do + b <- joinP q + case step st b of + Right st' -> go st' + 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. + +`ctxList` is `ctxTree` 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)@; +`ctxList` steps through a stream directly, rather than through +a `Cofree`, & needn't check a shape, as a stream's is its focus's. +-} +ctxTree + :: (Traversable g, Eq (g ())) + => st -> (st -> a -> Maybe (g st)) -> Varifocal' (Cofree g a) a +ctxTree 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. + +> prop> terminateBy end = ctxList () (\() -> bool (Right ()) (Left True) . end) +-} +terminateBy :: (Cons s s a a, AsEmpty s) => (a -> Bool) -> Varifocal' s a +terminateBy end = ctxList () (\() -> bool (Right ()) (Left True) . end) + +{- | Foci opened by the first, & closed by the first after it +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 stream which doesn't close by its first match doesn't match. +-} +delimitBy :: (Cons s s a a, AsEmpty s) => (a -> a -> Bool) -> Varifocal' s a +delimitBy same = ctxList Nothing $ \st b -> case st of + Nothing -> Right (Just b) + Just open -> bool (Right st) (Left True) (same open b) + +{- | Foci opened by one which @open@s, & closed by the one which @close@s, +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 stream which doesn't open first, or close only last, doesn't match. +-} +balanceBy + :: (Cons s s a a, AsEmpty s) + => (a -> Bool) -> (a -> Bool) -> Varifocal' s a +balanceBy open close = ctxList (0 :: Int) step + where + step depth b + | open b = Right (depth + 1) + | close b && depth == 1 = Left True + | close b && depth > 1 = Right (depth - 1) + | depth > 0 = Right depth + | otherwise = Left False + +{- | A focus counting how many foci follow it, then those, +like a length-prefixed record of bytes in a binary format. +A stream which doesn't have as many as its first focus counts +doesn't match. +-} +countWith :: (Cons s s a a, AsEmpty s) => (a -> Int) -> Varifocal' s a +countWith count = ctxList 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 `ctxTree`, as `countWith` counts a stream's. +A node counting fewer than none doesn't match. +-} +arityWith :: (a -> Int) -> Varifocal' (Cofree [] a) a +arityWith arity = ctxTree () $ \() b -> + if arity b < 0 then Nothing else Just (replicate (arity b) ()) diff --git a/src/Control/Lens/Wither.hs b/distributors-core/src/Control/Lens/Wither.hs similarity index 59% rename from src/Control/Lens/Wither.hs rename to distributors-core/src/Control/Lens/Wither.hs index 7b5d7c59..88cd6370 100644 --- a/src/Control/Lens/Wither.hs +++ b/distributors-core/src/Control/Lens/Wither.hs @@ -15,16 +15,12 @@ module Control.Lens.Wither ( -- * Wither Wither , AWither + , Altar (..) -- * Combinators , cloneWither , withered , filtraversed , filterOf - -- * Witheroid - , Witheroid - , witherPrism - -- * Altar - , Altar (..) ) where import Control.Applicative @@ -35,27 +31,24 @@ import Data.Profunctor.Sieve import Prelude hiding (filter) import Witherable -{- | `Wither`s extends `Control.Lens.Traversal.Traversal`s by filtering. +-- $setup +-- >>> import Control.Applicative (Alternative (..)) +-- >>> import Control.Lens +-- >>> import Control.Lens.PartialIso (partialIso, withPartialIso) -Every one of the following is a `Wither`. +{- | `Wither`s extend `Control.Lens.Traversal.Traversal`s by filtering. +`Control.Lens.Traversal.Traversal` ⊂ `Wither`, -* `Control.Lens.Iso.Iso` -* `Control.Lens.Lens.Lens` -* `Control.Lens.Prism.Prism` -* `Control.Lens.Traversal.Traversal` -* `Witheroid` +so every `Control.Lens.Iso.Iso`, `Control.Lens.Lens.Lens` +& `Control.Lens.Prism.Prism` is a `Wither` too. -} type Wither s t a b = forall f. Alternative f => (a -> f b) -> s -> f t -{- | `AWither` is monomorphically a `Wither`. -} -type AWither s t a b = (a -> Altar a b b) -> s -> Altar a b t +{- | `AWither` is monomorphically a `Wither`. -{- | `Witheroid`s generalize `Wither`s. -Every `Control.Lens.Prism.Prism` is a `Witheroid`. +> prop> Wither s t a b ⊂ AWither s t a b -} -type Witheroid s t a b = forall p f. - (Choice p, Alternative f) - => p a (f b) -> p s (f t) +type AWither s t a b = (a -> Altar a b b) -> s -> Altar a b t {- | Clone `AWither` so that you can reuse the same monomorphically typed `Wither` for different purposes. @@ -63,12 +56,37 @@ monomorphically typed `Wither` for different purposes. cloneWither :: AWither s t a b -> Wither s t a b cloneWither w f = (\g z -> runAltar z g) f . w sell -{- | Construct a `Wither` for a `Witherable`. -} +{- | Construct a `Wither` for a `Witherable`, +dropping each element whose action fails, by `optional`. + +A `Control.Lens.Prism.Prism` passes a mismatch through, +so it filters nothing in a `Wither`. Penner's @witherPrism@ +makes it fail instead, by `empty`, so that `withered` drops it. + +>>> :{ +witherPrism + :: (Choice p, Alternative f) + => APrism s t a b -> p a (f b) -> p s (f t) +witherPrism prsm = withPrism prsm $ \embed match -> + dimap match (either (const empty) (fmap embed)) . right' +:} + +>>> (withered . witherPrism _Just) (\x -> Just (x + 1)) [Just 1, Nothing, Just 2] +Just [Just 2,Just 3] + +With @catMaybes (pure Nothing)@ in place of `empty`, for a `Filterable` @f@, +@witherPrism@ is @withPartialIso prsm partialIso@, +rebuilding a `Control.Lens.PartialIso.PartialIso` +from the partial functions of a `Control.Lens.Prism.Prism`. + +>>> (withered . withPartialIso _Just partialIso) (\x -> Just (x + 1)) [Just 1, Nothing, Just 2] +Just [Just 2,Just 3] +-} withered :: Witherable t => Wither (t a) (t b) a b withered f = wither (optional . f) {- | -prop> withered = filtraversed +> prop> withered = filtraversed -} filtraversed :: (Filterable t, Traversable t) => Wither (t a) (t b) a b filtraversed f = fmap catMaybes . traverse (optional . f) @@ -80,16 +98,6 @@ filterOf w p s = w guardingp s where | p a = pure a | otherwise = empty -{- | -`Control.Lens.Prism.Prism`s already capture the idea of success and failure, -but they simply skip the traversal if the prism doesn't match. -Lift prisms into withers such that they'll fail in a way that wither can catch. --} -witherPrism :: APrism s t a b -> Witheroid s t a b -witherPrism prsm = - withPrism prsm $ \embed match -> - dimap match (either (const empty) (fmap embed)) . right' - {- | This is used to characterize `Wither`s. -} newtype Altar a b t = Altar { runAltar :: forall f. Alternative f => (a -> f b) -> f t } diff --git a/distributors-core/src/Data/Monoid/Disjunctive.hs b/distributors-core/src/Data/Monoid/Disjunctive.hs new file mode 100644 index 00000000..b7f76ed1 --- /dev/null +++ b/distributors-core/src/Data/Monoid/Disjunctive.hs @@ -0,0 +1,618 @@ +{-# LANGUAGE DeriveAnyClass #-} +{- | +Module : Data.Monoid.Disjunctive +Description : disjunctive monoids, Boolean & Kleene star algebras +Copyright : (C) 2026 - Eitan Chatav +License : BSD-style (see the file LICENSE) +Maintainer : Eitan Chatav +Stability : provisional +Portability : non-portable + +See Boole, [The Mathematical Analysis of Logic] +(https://www.gutenberg.org/files/36884/36884-pdf.pdf), +and Kleene, [Representation of Events in Nerve Nets and Finite Automata] +(https://www.rand.org/pubs/research_memoranda/RM704.html). +-} + +module Data.Monoid.Disjunctive + ( -- * DisjunctiveMonoid + DisjunctiveMonoid (..) + , orP, anyP + -- * BooleanAlgebra + , BooleanAlgebra (..) + , andP, allP + -- * KleeneStarAlgebra + , KleeneStarAlgebra (..) + ) where + +import Control.Applicative +import Control.Arrow +import Control.Lens.Internal.Profunctor +import Control.Monad +import Data.Bifunctor.Joker +import Data.Bifunctor.Product qualified as Bifunctor +import Data.Functor.Compose +import Data.Functor.Contravariant +import Data.Functor.Identity +import Data.Functor.Product qualified as Functor +import Data.Monoid +import Data.Profunctor hiding (WrappedArrow (..)) +import Data.Profunctor qualified as Pro (WrappedArrow (..)) +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.Bits (Bits (..)) +import Data.Maybe (isJust) +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) +import Witherable (WrappedFoldable) + +{- | A `DisjunctiveMonoid` is simply a monoid, +the only difference from `Monoid` being its semantics +are disjunctive logical "or" constructs. + +It has a disjunction `>|<` with identity `falseP`, +like `Alternative`'s `<|>` & `empty`. + +> prop> falseP >|< x = x = x >|< falseP +> prop> (x >|< y) >|< z = x >|< (y >|< z) +-} +class DisjunctiveMonoid a where + + -- | identity of disjunction + falseP :: a + default falseP :: (a ~ f x, Alternative f) => a + falseP = empty + + -- | disjunction + (>|<) :: a -> a -> a + default (>|<) :: (a ~ f x, Alternative f) => a -> a -> a + (>|<) = (<|>) + infixl 3 >|< + +-- | cumulative disjunction +orP :: (Foldable f, DisjunctiveMonoid a) => f a -> a +orP = foldl' (>|<) falseP + +-- | existential +anyP :: (Foldable f, DisjunctiveMonoid b) => (a -> b) -> f a -> b +anyP f = foldl' (\b a -> b >|< f a) falseP + +{- | A `BooleanAlgebra`, like `Bool`, supporting classical logical operations, +with disjunction `>|<` & false `falseP`. +-} +class DisjunctiveMonoid b => BooleanAlgebra b where + + -- | conjunction + (>&<) :: b -> b -> b + default (>&<) + :: (b ~ f bool, BooleanAlgebra bool, Applicative f) => b -> b -> b + (>&<) = liftA2 (>&<) + + -- | negation + notP :: b -> b + default notP + :: (b ~ f bool, BooleanAlgebra bool, Functor f) => b -> b + notP = fmap notP + + -- | true + trueP :: b + default trueP + :: (b ~ f bool, BooleanAlgebra bool, Applicative f) => b + trueP = pure trueP + +-- | cumulative conjunction +andP :: (Foldable f, BooleanAlgebra b) => f b -> b +andP = foldl' (>&<) trueP + +-- | universal +allP :: (Foldable f, BooleanAlgebra b) => (a -> b) -> f a -> b +allP f = foldl' (\b a -> b >&< f a) trueP + +{- | A `KleeneStarAlgebra` is a semiring +with a generally non-commutative multiplication, +the `Monoid` concatenation operator `<>` with identity `mempty`; +and an idempotent `DisjunctiveMonoid` addition, the alternation operator `>|<` +with identity `falseP`. + +> prop> x >|< x = x +> prop> falseP >|< x = x = x >|< falseP +> prop> falseP <> x = falseP = x <> falseP +> prop> mempty <> x = x = x <> mempty + +It also has three unary Kleene quantifier operators; + +* `optK`, zero or one, + +> prop> optK x = mempty >|< x = x >|< mempty + +* `plusK`, one or more, + +> prop> plusK x = x <> starK x = starK x <> x + +* and the eponymous `starK`, zero or more. + +> prop> starK x = optK (plusK x) + +-} +class (Monoid k, DisjunctiveMonoid k) => KleeneStarAlgebra k where + starK, plusK, optK :: k -> k + starK x = optK (plusK x) + plusK x = x <> starK x + optK x = mempty >|< x + + {- | A Kleene quantifier, 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,}@. 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> quantK 0 Nothing = starK + > prop> quantK 1 Nothing = plusK + > prop> quantK 0 (Just 1) = optK + > prop> quantK n (Just n) x = mconcat (replicate n x), for @n >= 0@ + > prop> quantK (n + 1) hi x = x <> quantK n (subtract 1 <$> hi) x, for @n >= 0@ + > prop> quantK (-1) hi = quantK 0 hi + > prop> quantK 0 (Just (-1)) x = falseP + -} + quantK :: Int -> Maybe Int -> k -> k + quantK lo hi x + | lo < 0 = quantK 0 hi x + | maybe False (lo >) hi = falseP + | lo > 1 || (lo == 1 && isJust hi) = + x <> quantK (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 <> quantK 0 (Just (m - 1)) x) + +--instances +instance DisjunctiveMonoid Bool where + falseP = False + (>|<) = (||) +instance BooleanAlgebra Bool where + trueP = True + notP = not + (>&<) = (&&) +instance DisjunctiveMonoid Any where + falseP = Any False + Any x >|< Any y = Any (x || y) +instance BooleanAlgebra Any where + trueP = Any True + notP (Any x) = Any (not x) + Any x >&< Any y = Any (x && y) +deriving via Generically () instance DisjunctiveMonoid () +deriving via Generically () instance BooleanAlgebra () +deriving via Generically () instance KleeneStarAlgebra () +deriving via Generically (a, b) + instance (DisjunctiveMonoid a, DisjunctiveMonoid b) + => DisjunctiveMonoid (a, b) +deriving via Generically (a, b) + instance (BooleanAlgebra a, BooleanAlgebra b) => BooleanAlgebra (a, b) +deriving via Generically (a, b) + instance (KleeneStarAlgebra a, KleeneStarAlgebra b) + => KleeneStarAlgebra (a, b) +deriving via Generically (a, b, c) + instance (DisjunctiveMonoid a, DisjunctiveMonoid b, DisjunctiveMonoid c) + => DisjunctiveMonoid (a, b, c) +deriving via Generically (a, b, c) + instance (BooleanAlgebra a, BooleanAlgebra b, BooleanAlgebra c) + => BooleanAlgebra (a, b, c) +deriving via Generically (a, b, c) + instance (KleeneStarAlgebra a, KleeneStarAlgebra b, KleeneStarAlgebra c) + => KleeneStarAlgebra (a, b, c) +deriving via Generically (a, b, c, d) + instance + ( DisjunctiveMonoid a, DisjunctiveMonoid b, DisjunctiveMonoid c + , DisjunctiveMonoid d ) + => DisjunctiveMonoid (a, b, c, d) +deriving via Generically (a, b, c, d) + instance + ( BooleanAlgebra a, BooleanAlgebra b, BooleanAlgebra c + , BooleanAlgebra d ) + => BooleanAlgebra (a, b, c, d) +deriving via Generically (a, b, c, d) + instance + ( KleeneStarAlgebra a, KleeneStarAlgebra b, KleeneStarAlgebra c + , KleeneStarAlgebra d ) + => KleeneStarAlgebra (a, b, c, d) +deriving via Generically (a, b, c, d, e) + instance + ( DisjunctiveMonoid a, DisjunctiveMonoid b, DisjunctiveMonoid c + , DisjunctiveMonoid d, DisjunctiveMonoid e ) + => DisjunctiveMonoid (a, b, c, d, e) +deriving via Generically (a, b, c, d, e) + instance + ( BooleanAlgebra a, BooleanAlgebra b, BooleanAlgebra c + , BooleanAlgebra d, BooleanAlgebra e ) + => BooleanAlgebra (a, b, c, d, e) +deriving via Generically (a, b, c, d, e) + instance + ( KleeneStarAlgebra a, KleeneStarAlgebra b, KleeneStarAlgebra c + , KleeneStarAlgebra d, KleeneStarAlgebra e ) + => KleeneStarAlgebra (a, b, c, d, e) +instance DisjunctiveMonoid b => DisjunctiveMonoid (x -> b) where + falseP = const falseP + f >|< g = \x -> f x >|< g x +instance BooleanAlgebra b => BooleanAlgebra (x -> b) +instance KleeneStarAlgebra k => KleeneStarAlgebra (x -> k) where + starK = (starK .) + plusK = (plusK .) + optK = (optK .) +instance DisjunctiveMonoid (Predicate a) where + falseP = Predicate falseP + Predicate p >|< Predicate q = Predicate (p >|< q) +instance BooleanAlgebra (Predicate a) where + trueP = Predicate trueP + notP (Predicate p) = Predicate (notP p) + Predicate p >&< Predicate q = Predicate (p >&< q) +deriving via Generically (Identity a) + instance DisjunctiveMonoid a => DisjunctiveMonoid (Identity a) +deriving via Generically (Identity a) + instance BooleanAlgebra a => BooleanAlgebra (Identity a) +deriving via Generically (Identity a) + instance KleeneStarAlgebra a => KleeneStarAlgebra (Identity a) +deriving via Generically (Const a b) + instance DisjunctiveMonoid a => DisjunctiveMonoid (Const a b) +deriving via Generically (Const a b) + instance BooleanAlgebra a => BooleanAlgebra (Const a b) +deriving via Generically (Const a b) + instance KleeneStarAlgebra a => KleeneStarAlgebra (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 + (>|<) = (<>) +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) +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) +instance DisjunctiveMonoid (f a) => DisjunctiveMonoid (Ap f a) where + falseP = Ap falseP + Ap x >|< Ap y = Ap (x >|< y) +instance DisjunctiveMonoid (f (g a)) => DisjunctiveMonoid (Compose f g a) where + falseP = Compose falseP + Compose x >|< Compose y = Compose (x >|< y) +instance (DisjunctiveMonoid (f a), DisjunctiveMonoid (g a)) + => DisjunctiveMonoid (Functor.Product f g a) where + falseP = Functor.Pair falseP falseP + Functor.Pair x0 y0 >|< Functor.Pair x1 y1 = + Functor.Pair (x0 >|< x1) (y0 >|< y1) +instance (DisjunctiveMonoid (f p), DisjunctiveMonoid (g p)) + => DisjunctiveMonoid ((f :*: g) p) where + falseP = falseP :*: falseP + (x0 :*: y0) >|< (x1 :*: y1) = (x0 >|< x1) :*: (y0 >|< y1) +instance DisjunctiveMonoid (f (g p)) => DisjunctiveMonoid ((f :.: g) p) where + falseP = Comp1 falseP + Comp1 x >|< Comp1 y = Comp1 (x >|< y) +instance DisjunctiveMonoid (f p) => DisjunctiveMonoid (M1 i c f p) where + falseP = M1 falseP + M1 x >|< M1 y = M1 (x >|< y) +instance DisjunctiveMonoid (f p) => DisjunctiveMonoid (Rec1 f p) where + falseP = Rec1 falseP + Rec1 x >|< Rec1 y = Rec1 (x >|< y) +instance DisjunctiveMonoid c => DisjunctiveMonoid (K1 i c p) where + falseP = K1 falseP + K1 x >|< K1 y = K1 (x >|< y) +instance DisjunctiveMonoid p => DisjunctiveMonoid (Par1 p) where + falseP = Par1 falseP + Par1 x >|< Par1 y = Par1 (x >|< y) +instance BooleanAlgebra (U1 p) where + trueP = U1 + notP _ = U1 + _ >&< _ = U1 +instance (BooleanAlgebra (f p), BooleanAlgebra (g p)) + => BooleanAlgebra ((f :*: g) p) where + trueP = trueP :*: trueP + notP (x :*: y) = notP x :*: notP y + (x0 :*: y0) >&< (x1 :*: y1) = (x0 >&< x1) :*: (y0 >&< y1) +instance BooleanAlgebra (f (g p)) => BooleanAlgebra ((f :.: g) p) where + trueP = Comp1 trueP + notP (Comp1 x) = Comp1 (notP x) + Comp1 x >&< Comp1 y = Comp1 (x >&< y) +instance BooleanAlgebra (f p) => BooleanAlgebra (M1 i c f p) where + trueP = M1 trueP + notP (M1 x) = M1 (notP x) + M1 x >&< M1 y = M1 (x >&< y) +instance BooleanAlgebra (f p) => BooleanAlgebra (Rec1 f p) where + trueP = Rec1 trueP + notP (Rec1 x) = Rec1 (notP x) + Rec1 x >&< Rec1 y = Rec1 (x >&< y) +instance BooleanAlgebra c => BooleanAlgebra (K1 i c p) where + trueP = K1 trueP + notP (K1 x) = K1 (notP x) + K1 x >&< K1 y = K1 (x >&< y) +instance BooleanAlgebra p => BooleanAlgebra (Par1 p) where + trueP = Par1 trueP + notP (Par1 x) = Par1 (notP x) + Par1 x >&< Par1 y = Par1 (x >&< y) +instance KleeneStarAlgebra (U1 p) where + starK _ = U1 +instance (KleeneStarAlgebra (f p), KleeneStarAlgebra (g p)) + => KleeneStarAlgebra ((f :*: g) p) where + starK (x :*: y) = starK x :*: starK y + plusK (x :*: y) = plusK x :*: plusK y + optK (x :*: y) = optK x :*: optK y +instance KleeneStarAlgebra (f (g p)) => KleeneStarAlgebra ((f :.: g) p) where + starK (Comp1 x) = Comp1 (starK x) + plusK (Comp1 x) = Comp1 (plusK x) + optK (Comp1 x) = Comp1 (optK x) +instance KleeneStarAlgebra (f p) => KleeneStarAlgebra (M1 i c f p) where + starK (M1 x) = M1 (starK x) + plusK (M1 x) = M1 (plusK x) + optK (M1 x) = M1 (optK x) +instance KleeneStarAlgebra (f p) => KleeneStarAlgebra (Rec1 f p) where + starK (Rec1 x) = Rec1 (starK x) + plusK (Rec1 x) = Rec1 (plusK x) + optK (Rec1 x) = Rec1 (optK x) +instance KleeneStarAlgebra c => KleeneStarAlgebra (K1 i c p) where + starK (K1 x) = K1 (starK x) + plusK (K1 x) = K1 (plusK x) + optK (K1 x) = K1 (optK x) +instance KleeneStarAlgebra p => KleeneStarAlgebra (Par1 p) where + starK (Par1 x) = Par1 (starK x) + plusK (Par1 x) = Par1 (plusK x) + optK (Par1 x) = Par1 (optK x) +instance (Generic a, DisjunctiveMonoid (Rep a ())) + => DisjunctiveMonoid (Generically a) where + falseP = Generically (to (falseP :: Rep a ())) + Generically x >|< Generically y = + Generically (to (from x >|< from y :: Rep a ())) +instance (Generic a, BooleanAlgebra (Rep a ())) + => BooleanAlgebra (Generically a) where + trueP = Generically (to (trueP :: Rep a ())) + notP (Generically x) = Generically (to (notP (from x :: Rep a ()))) + Generically x >&< Generically y = + Generically (to (from x >&< from y :: Rep a ())) +instance (Generic a, Monoid (Rep a ()), KleeneStarAlgebra (Rep a ())) + => KleeneStarAlgebra (Generically a) where + starK (Generically x) = Generically (to (starK (from x :: Rep a ()))) + plusK (Generically x) = Generically (to (plusK (from x :: Rep a ()))) + optK (Generically x) = Generically (to (optK (from x :: Rep a ()))) +instance (Generic1 f, DisjunctiveMonoid (Rep1 f a)) + => DisjunctiveMonoid (Generically1 f a) where + falseP = Generically1 (to1 (falseP :: Rep1 f a)) + Generically1 x >|< Generically1 y = + Generically1 (to1 (from1 x >|< from1 y :: Rep1 f a)) +instance DisjunctiveMonoid (m b) => DisjunctiveMonoid (Kleisli m a b) where + falseP = Kleisli falseP + Kleisli f >|< Kleisli g = Kleisli (f >|< g) +instance DisjunctiveMonoid (f b) => DisjunctiveMonoid (Star f a b) where + falseP = Star falseP + Star f >|< Star g = Star (f >|< g) +instance DisjunctiveMonoid r => DisjunctiveMonoid (Forget r a b) where + falseP = Forget falseP + Forget f >|< Forget g = Forget (f >|< g) +instance ArrowPlus p => DisjunctiveMonoid (Pro.WrappedArrow p a b) where + falseP = Pro.WrapArrow zeroArrow + Pro.WrapArrow x >|< Pro.WrapArrow y = Pro.WrapArrow (x <+> y) +instance (Applicative f, DisjunctiveMonoid (p a b)) + => DisjunctiveMonoid (Cayley f p a b) where + falseP = Cayley (pure falseP) + Cayley x >|< Cayley y = Cayley (liftA2 (>|<) x y) +instance (DisjunctiveMonoid (p a b), DisjunctiveMonoid (q a b)) + => DisjunctiveMonoid (Bifunctor.Product p q a b) where + falseP = Bifunctor.Pair falseP falseP + Bifunctor.Pair x0 y0 >|< Bifunctor.Pair x1 y1 = + Bifunctor.Pair (x0 >|< x1) (y0 >|< y1) +instance Alternative f => DisjunctiveMonoid (Joker f a b) where + falseP = Joker empty + Joker x >|< Joker y = Joker (x <|> y) +instance DisjunctiveMonoid (p a (f b)) + => DisjunctiveMonoid (WrappedPafb f p a b) where + falseP = WrapPafb falseP + WrapPafb x >|< WrapPafb y = WrapPafb (x >|< y) +instance (Profunctor p, DisjunctiveMonoid (p a b)) + => DisjunctiveMonoid (Yoneda p a b) where + falseP = proreturn falseP + x >|< y = proreturn (proextract x >|< proextract y) +instance (Profunctor p, DisjunctiveMonoid (p a b)) + => DisjunctiveMonoid (Coyoneda p a b) where + falseP = proreturn falseP + x >|< y = proreturn (proextract x >|< proextract y) diff --git a/distributors-core/src/Data/Profunctor/Distributor.hs b/distributors-core/src/Data/Profunctor/Distributor.hs new file mode 100644 index 00000000..b1cd9a6d --- /dev/null +++ b/distributors-core/src/Data/Profunctor/Distributor.hs @@ -0,0 +1,244 @@ +{-| +Module : Data.Profunctor.Distributor +Description : distributors +Copyright : (C) 2026 - Eitan Chatav +License : BSD-style (see the file LICENSE) +Maintainer : Eitan Chatav +Stability : provisional +Portability : non-portable +-} + +module Data.Profunctor.Distributor + ( -- * Distributor + Distributor (..) + , skipManyP + , skipOptionalP + -- * Alternator + , Alternator (..) + ) where + +import Control.Applicative hiding (WrappedArrow) +import Control.Applicative qualified as Ap (WrappedArrow) +import Control.Arrow +import Control.Lens hiding (chosen) +import Control.Lens.Internal.Profunctor +import Control.Lens.PartialIso +import Data.Bifunctor.Clown +import Data.Bifunctor.Joker +import Data.Bifunctor.Product +import Data.Functor.Adjunction +import Data.Functor.Contravariant.Divisible +import Data.Monoid.Disjunctive +import Data.Profunctor hiding (WrappedArrow) +import Data.Profunctor qualified as Pro (WrappedArrow) +import Data.Profunctor.Cayley +import Data.Profunctor.Composition +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 (..)) +-- >>> import Data.Profunctor.Monoidal ((*<)) +-- >>> import Text.ParserCombinators.ReadP (char, readP_to_S) + +-- Distributor -- + +{- | A `Distributor`, or lax distributive profunctor, +respects [distributive category] +(https://ncatlab.org/nlab/show/distributive+category) +structure, that is nilary and binary products and coproducts, +@()@, @(,)@, `Data.Void.Void` and `Either`, being both +`Monoidal` and `CocartesianMonoidal`. + +`Distributor` additionally has methods `manyP` & `optionalP`, +distributing an action over @[]@ and `Maybe` datatypes, +which generalize to `Data.Traversable.Homogeneous.homogeneously` +distributing an action over +`Data.Traversable.Homogeneous.Homogeneous` +sum-of-products datatypes. +-} +class (Monoidal p, CocartesianMonoidal p) => Distributor p where + + {- | One or none. -} + optionalP :: p a b -> p (Maybe a) (Maybe b) + optionalP p = eotMaybe . swapped >~ p >+< oneP + + {- | Zero or more. -} + manyP :: p a b -> p [a] [b] + manyP p = let ps = eotList . swapped >~ p >*< ps >+< oneP in ps + +instance Distributor (->) +instance Monoid s => Distributor (Forget s) +instance Decidable f => Distributor (Clown f) +instance Alternative f => Distributor (Joker f) where + optionalP (Joker x) = Joker (optional x) + manyP (Joker x) = Joker (many x) +instance (Distributor p, Applicative f) + => Distributor (WrappedPafb f p) where + manyP (WrapPafb x) = WrapPafb (rmap sequenceA (manyP x)) + optionalP (WrapPafb x) = WrapPafb (rmap sequenceA (optionalP x)) +instance Applicative f => Distributor (Star f) where + optionalP (Star f) = Star (traverse f) + manyP (Star f) = Star (traverse f) +deriving via (Star m) instance Monad m => Distributor (Kleisli m) +instance Adjunction f u => Distributor (Costar f) +instance (Applicative f, Distributor p) + => Distributor (Cayley f p) where + optionalP (Cayley x) = Cayley (optionalP <$> x) + manyP (Cayley x) = Cayley (manyP <$> x) +instance (ArrowZero p, ArrowChoice p) + => Distributor (Pro.WrappedArrow p) +deriving via (Pro.WrappedArrow p) + instance (ArrowZero p, ArrowChoice p) + => Distributor (Ap.WrappedArrow p) +instance (Distributor p, Distributor q) + => Distributor (Procompose p q) where + optionalP (Procompose f g) = + Procompose (optionalP f) (optionalP g) + manyP (Procompose f g) = + Procompose (manyP f) (manyP g) +instance (Distributor p, Distributor q) + => Distributor (Product p q) where + optionalP (Pair f g) = + Pair (optionalP f) (optionalP g) + manyP (Pair f g) = + Pair (manyP f) (manyP g) +instance Distributor p => Distributor (Yoneda p) where + optionalP = proreturn . optionalP . proextract + manyP = proreturn . manyP . proextract +instance Distributor p => Distributor (Coyoneda p) where + optionalP = proreturn . optionalP . proextract + manyP = proreturn . manyP . proextract + +{- | Zero or more, skipped: sequencing any number of actions forwards, +& none backwards, like whitespace that a parser accepts +& a printer omits. + +> prop> skipManyP p = dimap (const []) (const ()) (manyP p) + +>>> [r | (r, "") <- readP_to_S (runJoker (skipManyP (Joker (char ' ')) *< Joker (char 'x'))) " x"] +[()] +-} +skipManyP :: Distributor p => p a b -> p () () +skipManyP p = dimap (const []) (const ()) (manyP p) + +{- | Zero or one, skipped: sequencing one action or none forwards, +& none backwards, like a trailing separator that a parser accepts +& a printer omits. + +>>> [r | (r, "") <- readP_to_S (runJoker (Joker (char 'x') *< skipOptionalP (Joker (char ',')))) "x,"] +"x" +-} +skipOptionalP :: Distributor p => p a b -> p () () +skipOptionalP p = dimap (const Nothing) (const ()) (optionalP p) + +-- Alternator -- + +{- | The `Alternator` class co-extends `CocartesianChoice` and `Distributor`, +as well as `Alternative`, adding methods `someP` & `optionP`, +with these laws relating them. + +> prop> manyP p = optionP _Empty (someP p) +> prop> optionalP p = optionP _Nothing (_Just >? p) +> prop> someP p = p >:< manyP p + +These mirror the laws of a `KleeneStarAlgebra`, @starK x = optK (plusK x)@ +& @plusK x = x <> starK x@, unfolding `someP` on the left. +Its unfolding on the right, @someP p = snocP (manyP p) p@, +mirroring @plusK x = starK x <> x@, isn't a law though, +since a greedy or predictive parser's `manyP` consumes every @p@, +leaving none for the last; only a backtracking one finds it. + +Its `Alternative` structure agrees with its `Alternator` structure, +`many` & `some` repeating an input for `manyP` & `someP`. + +> prop> empty = falseP +> prop> (<|>) = (>|<) +> prop> many = lmap repeat . manyP +> prop> some = lmap repeat . someP + +Not all `Distributor`s are `Alternator`s, in particular @(->)@ is +a `Distributor` but cannot be `Alternative`, +because there is no general polymorphic function @empty :: a -> b@, +so @(->)@ isn't an `Alternator`. + +-} +class (Distributor p, CocartesianChoice p, forall x. Alternative (p x)) + => Alternator p where + + {- | One or more. -} + someP :: p a b -> p [a] [b] + someP x = x >:< manyP x + + {- | One or zero-with-default. -} + optionP :: APrism a b () () {- ^ default -} -> p a b -> p a b + optionP def p = p >|< pureP def + + {- | Zero or more, then the rest, @p* q@, trying the rest first, + like @manyTill@ of [parsec](https://hackage.haskell.org/package/parsec), + the least solution of its unfolding. + + > prop> manyTillP p q = q >|< p >:< manyTillP p q + > prop> manyTillP falseP q = q + + It mirrors a `KleeneStarAlgebra`'s @starK x <> y@, so that + a static `Alternator`, which sequences no input, may define it + without recursing, as an input-consuming one, like a parser + or printer, can't, since only consuming finds where @q@ begins. + It recognizes what @manyP p@ does with @q = `asEmpty`@, + but trying fewer @p@s first, rather than more. + -} + manyTillP :: p a b -> p [a] [b] -> p [a] [b] + manyTillP p q = let r = q >|< p >:< r in r + + {- | A Kleene quantifier, 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@, + nor where @hi@ is negative, its counts being those @n >= 0@ within + its bounds. + + It mirrors a `KleeneStarAlgebra`'s `quantK`, so that a static + `Alternator` may keep its counts, rather than unfolding them. + + > prop> quantP 0 Nothing = manyP + > prop> quantP 1 Nothing = someP + > prop> quantP n (Just n) = replicateP n, for @n >= 0@ + -} + quantP :: Int -> Maybe Int -> p a b -> p [a] [b] + quantP lo hi p + | lo < 0 = quantP 0 hi p + | maybe False (lo >) hi = empty + | lo > 1 || (lo == 1 && isJust hi) = + p >:< quantP (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 >*< quantP 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) + quantP lo hi (WrapPafb x) = WrapPafb (rmap sequenceA (quantP 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)) + quantP lo hi = proreturn . quantP 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)) + quantP lo hi = proreturn . quantP lo hi . proextract +instance Alternative f => Alternator (Joker f) where + someP (Joker x) = Joker (some x) + optionP def (Joker x) = + Joker (x <|> withPrism def (\f _ -> pure (f ()))) diff --git a/src/Data/Profunctor/Filtrator.hs b/distributors-core/src/Data/Profunctor/Filtrator.hs similarity index 64% rename from src/Data/Profunctor/Filtrator.hs rename to distributors-core/src/Data/Profunctor/Filtrator.hs index 4adc28df..bbdf27ff 100644 --- a/src/Data/Profunctor/Filtrator.hs +++ b/distributors-core/src/Data/Profunctor/Filtrator.hs @@ -14,12 +14,12 @@ module Data.Profunctor.Filtrator , mfiltrate ) where -import Control.Applicative import Control.Arrow import Control.Lens.PartialIso import Control.Lens.Internal.Profunctor import Control.Monad import Data.Bifunctor.Joker +import Data.Monoid.Disjunctive (falseP) import Data.Profunctor import Data.Profunctor.Distributor import Data.Profunctor.Monad @@ -29,24 +29,43 @@ import Witherable {- | The `Filtrator` class extends `Cochoice`, as well as `Filterable`, adding the `filtrate` method, -which is an oplax monoidal structure morphism dual to -`>+<`. +which projects a profunctor of sums onto its summands. -prop> filtrate . uncurry (>+<) = id -prop> uncurry (>+<) . filtrate = id +For a `Data.Profunctor.Monoidal.Cocartesian.CocartesianChoice`, +`filtrate` is a retraction of `Data.Profunctor.Monoidal.Cocartesian.alternate`, +projecting a summand back out of its injection, + +> prop> fst (filtrate (alternate (Left p))) = p +> prop> snd (filtrate (alternate (Right p))) = p + +that is, since `unleft` is @fst . filtrate@ & `left'` is @alternate . Left@, + +> prop> unleft . left' = id +> prop> unright . right' = id + +`filtrate` isn't a retraction of +`Data.Profunctor.Monoidal.Cocartesian.>+<` in general, though, +since it tries its summands in turn, & the second summand +of a left-biased or predictive one, +like the @Parsor s Maybe@ or @Parsector@ parsers of @distributors-grammar@, +is lost where the first applies. Nor is `Data.Profunctor.Monoidal.Cocartesian.>+<` +a retraction of `filtrate`, since a profunctor of sums may cross summands, +as @rmap (either Right Left)@ does. -} class (Cochoice p, forall x. Filterable (p x)) => Filtrator p where {- | - prop> unleft = fst . filtrate = lmap Left . mapMaybe (either Just (const Nothing)) - prop> unright = snd . filtrate = lmap Right . mapMaybe (either (const Nothing) Just) + > prop> unleft = fst . filtrate + > prop> unleft = lmap Left . mapMaybe (either Just (const Nothing)) + > prop> unright = snd . filtrate + > prop> unright = lmap Right . mapMaybe (either (const Nothing) Just) `filtrate` is a distant relative to `Data.Either.partitionEithers`. `filtrate` can be given a default value for `Monadic` `Alternator`s via `mfiltrate`. - prop> filtrate = mfiltrate + > prop> filtrate = mfiltrate `filtrate` has a default for `Choice` & `Cochoice` partial profunctors. -} @@ -65,15 +84,16 @@ class (Cochoice p, forall x. Filterable (p x)) -- | A `Monadic` `Alternator` has -- an equivalent to `filtrate`, given by `mfiltrate`. -- --- prop> filtrate = mfiltrate +-- > prop> filtrate = mfiltrate +-- mfiltrate :: (Monadic p, Alternator p) => p (Either a c) (Either b d) -- ^ partition `Either` -> (p a b, p c d) mfiltrate = - (lmap Left >=> either pure (const empty)) + (lmap Left >=> either pure (const falseP)) &&& - (lmap Right >=> either (const empty) pure) + (lmap Right >=> either (const falseP) pure) instance (Profunctor p, forall x. Functor (p x), Filterable f) => Filtrator (WrappedPafb f p) where @@ -91,16 +111,7 @@ instance Filtrator p => Filtrator (Yoneda p) where in (proreturn q, proreturn r) instance Filtrator (Forget r) where filtrate (Forget f) = (Forget (f . Left), Forget (f . Right)) -instance (Filterable f, Traversable f) => Filtrator (Star f) where - filtrate (Star f) = - ( Star (mapMaybe (either Just (const Nothing)) . f . Left) - , Star (mapMaybe (either (const Nothing) Just) . f . Right) - ) -instance Filtrator (PartialExchange a b) where - filtrate (PartialExchange f g) = - ( PartialExchange (f . Left) (either Just (pure Nothing) <=< g) - , PartialExchange (f . Right) (either (pure Nothing) Just <=< g) - ) +instance Filtrator (PartialMarket a b) instance Filterable f => Filtrator (Joker f) where filtrate (Joker x) = ( Joker (mapMaybe (either Just (const Nothing)) x) diff --git a/distributors-core/src/Data/Profunctor/Monadic.hs b/distributors-core/src/Data/Profunctor/Monadic.hs new file mode 100644 index 00000000..676c15cf --- /dev/null +++ b/distributors-core/src/Data/Profunctor/Monadic.hs @@ -0,0 +1,46 @@ +{-| +Module : Data.Profunctor.Monadic +Description : monadic profunctors +Copyright : (C) 2026 - Eitan Chatav +License : BSD-style (see the file LICENSE) +Maintainer : Eitan Chatav +Stability : provisional +Portability : non-portable + +See Li-yao Xia, [Monadic profunctors for bidirectional programming] +(https://blog.poisson.chat/posts/2017-01-01-monadic-profunctors.html) + +For qualified do-notation, with pattern bonding, +import "Data.Profunctor.Monadic.Do" qualified; +this module has no names which conflict with the "Prelude". +-} + +module Data.Profunctor.Monadic + ( -- * Monadic + Monadic + -- * MonadicTrans + , MonadicTrans (..) + ) where + +import Control.Monad (join) +import Data.Profunctor (Profunctor) + +{- | A `Profunctor` which is also a `Monad`. -} +type Monadic p = (Profunctor p, forall x. Monad (p x)) + +{- | A `MonadicTrans` profunctor transforms a monad @m@, +like a `Control.Monad.Trans.Class.MonadTrans`, so that its actions +may run effects of @m@ forwards, by `liftP`, +& absorb them backwards, by `joinP`. + +`liftP` is a monad morphism. +-} +class + ( forall m x. Monad m => Monad (p m x) + , forall m. Monad m => Profunctor (p m) + ) => MonadicTrans p where + liftP :: Monad m => m b -> p m a b + liftP = joinP . return + joinP :: Monad m => p m a (m b) -> p m a b + joinP = join . fmap liftP + {-# MINIMAL liftP | joinP #-} diff --git a/src/Data/Profunctor/Monadic.hs b/distributors-core/src/Data/Profunctor/Monadic/Do.hs similarity index 54% rename from src/Data/Profunctor/Monadic.hs rename to distributors-core/src/Data/Profunctor/Monadic/Do.hs index 69e8b191..ec51eb2d 100644 --- a/src/Data/Profunctor/Monadic.hs +++ b/distributors-core/src/Data/Profunctor/Monadic/Do.hs @@ -1,50 +1,40 @@ {-| -Module : Data.Profunctor.Monadic -Description : monadic profunctors +Module : Data.Profunctor.Monadic.Do +Description : qualified do-notation for monadic profunctors Copyright : (C) 2026 - Eitan Chatav License : BSD-style (see the file LICENSE) Maintainer : Eitan Chatav Stability : provisional Portability : non-portable -See Li-yao Xia, [Monadic profunctors for bidirectional programming] -(https://blog.poisson.chat/posts/2017-01-01-monadic-profunctors.html) - -This module can provide qualified do-notation for `Monadic` profunctors. +Qualified do-notation for `Monadic` profunctors, +with pattern bonding, to import qualified. >>> :set -XQualifiedDo ->>> import qualified Data.Profunctor.Monadic as P +>>> import qualified Data.Profunctor.Monadic.Do as P See "Control.Lens.Grammar#t:CtxGrammar" for an example of how to use qualified do-notation with pattern bonding. -} -module Data.Profunctor.Monadic - ( -- * Monadic - Monadic - , (>>=) +module Data.Profunctor.Monadic.Do + ( (>>=) , (>>) , return - -- * MonadicTry - , MonadicTry - , try + -- | The "Prelude"'s, for patterns which may fail. , fail ) where import Control.Lens -import Control.Monad hiding ((>>=), (>>), return) -import Control.Monad.Fail.Try +import Data.Profunctor.Monadic (Monadic) import Data.Profunctor.Monoidal import Prelude hiding ((>>=), (>>), return) -{- | A `Profunctor` which is also a `Monad`. -} -type Monadic p = (Profunctor p, forall x. Monad (p x)) - {- | The pair bonding operator @P.@`>>=` is a context-sensitive version of `>*<`. -prop> x >*< y = x P.>>= (\_ -> y) +> prop> x >*< y = x P.>>= (\_ -> y) -} (>>=) :: Monadic p => p a b -> (b -> p c d) -> p (a,c) (b,d) infixl 1 >>= @@ -61,10 +51,7 @@ x >> y = do _ <- lmap (const ()) x; y {- | @P.@`return` is a `Monadic`-restricted version of `pureP`. -prop> pureP = P.return +> prop> pureP = P.return -} return :: (Monadic p, Choice p) => APrism a b () () -> p a b return = pureP - -{- | A `Profunctor` which is also a `MonadTry`. -} -type MonadicTry p = (Profunctor p, forall x. MonadTry (p x)) diff --git a/src/Data/Profunctor/Monoidal.hs b/distributors-core/src/Data/Profunctor/Monoidal.hs similarity index 63% rename from src/Data/Profunctor/Monoidal.hs rename to distributors-core/src/Data/Profunctor/Monoidal.hs index a1e83e36..8c6ed532 100644 --- a/src/Data/Profunctor/Monoidal.hs +++ b/distributors-core/src/Data/Profunctor/Monoidal.hs @@ -17,18 +17,33 @@ module Data.Profunctor.Monoidal , dimap2, foreverP, ditraverse -- * Monoidal & Choice , pureP, asEmpty, (>:<), snocP, replicateP, onlyOne + -- * Monoidal & Strong + , idP, arrP + -- * Monoidal, Strong & Costrong + , fixP -- * Monoidal, Choice & Strong , meander, traverseP, foldP + -- * Deriving via Monoidally + , Monoidally (..) ) where +import Control.Applicative +import Control.Arrow qualified as Arrow +import Control.Category qualified as Category import Control.Lens import Control.Lens.Internal.Context import Control.Lens.PartialIso import Data.Distributive +import Data.Monoid.Disjunctive import Data.Profunctor +import Data.Profunctor.Traversing qualified as Traversing import Data.Foldable (traverse_) import GHC.IsList +-- $setup +-- >>> import Control.Lens (Traversal) +-- >>> import Data.Profunctor + -- Monoidal -- {- | A lax `Monoidal` product `Profunctor` has unit `oneP` @@ -41,10 +56,10 @@ Laws: >>> let runit = dimap (\(a,()) -> a) (\a -> (a,())) >>> let assoc = dimap (\(a,(b,c)) -> ((a,b),c)) (\((a,b),c) -> (a,(b,c))) -prop> oneP >*< p = lunit p -prop> p >*< oneP = runit p -prop> p >*< q >*< r = assoc ((p >*< q) >*< r) -prop> dimap (f >*< g) (h >*< i) (p >*< q) = dimap f h p >*< dimap g i q +> prop> oneP >*< p = lunit p +> prop> p >*< oneP = runit p +> prop> p >*< q >*< r = assoc ((p >*< q) >*< r) +> prop> dimap (f >*< g) (h >*< i) (p >*< q) = dimap f h p >*< dimap g i q -} type Monoidal p = (Profunctor p, forall x. Applicative (p x)) @@ -52,34 +67,38 @@ type Monoidal p = (Profunctor p, forall x. Applicative (p x)) {- | `oneP` is the unit of a `Monoidal` `Profunctor`. -} oneP :: Monoidal p => p () () oneP = pure () +{-# INLINE oneP #-} {- | `>*<` is the product of a `Monoidal` `Profunctor`. -} (>*<) :: Monoidal p => p a b -> p c d -> p (a,c) (b,d) (>*<) = dimap2 fst snd (,) +{-# INLINE (>*<) #-} infixr 5 >*< {- | `>*` sequences actions, discarding the value of the first argument; -analagous to `*>`, extending it to `Monoidal`. +analogous to `*>`, extending it to `Monoidal`. -prop> oneP >* p = p +> prop> oneP >* p = p -} (>*) :: Monoidal p => p () c -> p a b -> p a b x >* y = lmap (const ()) x *> y +{-# INLINE (>*) #-} infixl 6 >* {- | `*<` sequences actions, discarding the value of the second argument; -analagous to `<*`, extending it to `Monoidal`. +analogous to `<*`, extending it to `Monoidal`. -prop> p *< oneP = p +> prop> p *< oneP = p -} (*<) :: Monoidal p => p a b -> p () c -> p a b x *< y = x <* lmap (const ()) y +{-# INLINE (*<) #-} infixl 6 *< {- | `dimap2` is a curried, functionalized form of `>*<`, -analagous to `liftA2`. -} +analogous to `liftA2`. -} dimap2 :: Monoidal p => (s -> a) -- ^ first projection, e.g. `fst` @@ -87,9 +106,10 @@ dimap2 -> (b -> d -> t) -- ^ pairing function, e.g. @(,)@ -> p a b -> p c d -> p s t dimap2 f g h p q = liftA2 h (lmap f p) (lmap g q) +{-# INLINE dimap2 #-} {- | `foreverP` repeats an action a countable infinity of times; -analagous to `Control.Monad.forever`, extending it to `Monoidal`. -} +analogous to `Control.Monad.forever`, extending it to `Monoidal`. -} foreverP :: Monoidal p => p () c -> p a b foreverP a = let a' = a >* a' in a' @@ -142,7 +162,7 @@ onlyOne => p (Item s) (Item s) -> p s s onlyOne p = iso toList (fromListN 1) >? p >:< asEmpty -{- | `replicateP` is analagous to `Control.Monad.replicateM`, +{- | `replicateP` is analogous to `Control.Monad.replicateM`, for `Monoidal` & `Choice` `Profunctor`s. When the number of repetitions is less than or equal to 0, it returns `asEmpty`. -} @@ -163,8 +183,9 @@ but for its invertibility property. traversalP :: (forall p. (Monoidal p, Choice p, Strong p) => p a b -> p s t) -> Traversal s t a b traversalP f = runStar . f . Star :} -prop> traversalP . meander = id -prop> meander . traversalP = id + +> prop> traversalP . meander = id +> prop> meander . traversalP = id See Pickering, Gibbons & Wu, [Profunctor Optics - Modular Data Accessors](https://arxiv.org/abs/1703.10857) @@ -192,7 +213,7 @@ traverseP = meander traverse However, a `Profunctor` which is also `Contravariant` in its last argument is /constant/ over or /phantom/ in its last argument. -prop> foldMap f = getConst . runStar (foldP (Star (Const . f))) +> prop> foldMap f = getConst . runStar (foldP (Star (Const . f))) -} foldP :: (Foldable f, Monoidal p, Choice p, Strong p, forall x. (Contravariant (p x))) @@ -236,3 +257,83 @@ instance Applicative (FunList a b) where MoreFun a h -> \l -> MoreFun a (flip <$> h <*> fromFun l) instance Sellable (->) FunList where sell b = MoreFun b (pure id) + +{- | The unit map of a `Monoidal` & `Strong` `Profunctor`, +the strength of `oneP`, which is natural, +& whose product is the strength. +It needn't be an identity; @idP = Forget (const mempty)@. + +> prop> lmap f idP = rmap f idP +> prop> first' p = p >*< idP +> prop> second' p = idP >*< p +-} +idP :: (Monoidal p, Strong p) => p a a +idP = dimap (\a -> ((),a)) (\((),a) -> a) (first' oneP) + +{- | Lift a function into a `Monoidal` & `Strong` `Profunctor`, +like `Control.Arrow.arr`. + +> prop> arrP f = rmap f idP = lmap f idP +-} +arrP :: (Monoidal p, Strong p) => (a -> b) -> p a b +arrP f = fmap f idP + +{- | The fixed point of a function, like `Data.Function.fix`, +by `Costrong`'s `unfirst`, like `Control.Arrow.loop`. +-} +fixP :: (Monoidal p, Strong p, Costrong p) => p (a -> a) a +fixP = let dup x = (x,x) in unfirst (arrP (uncurry (dup .))) + +{- | t'Monoidally' derives instances of a `Monoidal` `Profunctor`, +via `meander` for `Data.Profunctor.Traversing.Traversing`, +& via `arrP` & `>*<` for `Control.Arrow.Arrow`, +given `Control.Category.Category`. + +> newtype P a b = P ... +> deriving (Traversing, Arrow) via Monoidally P +-} +newtype Monoidally p a b = Monoidally {runMonoidally :: p a b} +deriving newtype instance Functor (p a) => Functor (Monoidally p a) +deriving newtype instance Applicative (p a) + => Applicative (Monoidally p a) +deriving newtype instance Alternative (p a) + => Alternative (Monoidally p a) +deriving newtype instance DisjunctiveMonoid (p a b) + => DisjunctiveMonoid (Monoidally p a b) +deriving newtype instance Profunctor p => Profunctor (Monoidally p) +deriving newtype instance Strong p => Strong (Monoidally p) +deriving newtype instance Costrong p => Costrong (Monoidally p) +deriving newtype instance Choice p => Choice (Monoidally p) +deriving newtype instance Cochoice p => Cochoice (Monoidally p) +deriving newtype instance Category.Category p + => Category.Category (Monoidally p) +instance (Monoidal p, Choice p, Strong p) + => Traversing.Traversing (Monoidally p) where + wander f (Monoidally p) = Monoidally (meander f p) + traverse' = traverseP +instance (Category.Category p, Monoidal p, Strong p) + => Arrow.Arrow (Monoidally p) where + arr = arrP + first = first' + second = second' + (***) = (>*<) + (&&&) = liftA2 (,) +instance (Category.Category p, Monoidal p, Strong p, Choice p) + => Arrow.ArrowChoice (Monoidally p) where + left = left' + right = right' +instance + ( Category.Category p, Monoidal p, Strong p + , forall x y. DisjunctiveMonoid (p x y) + ) + => Arrow.ArrowZero (Monoidally p) where + zeroArrow = falseP +instance + ( Category.Category p, Monoidal p, Strong p + , forall x y. DisjunctiveMonoid (p x y) + ) + => Arrow.ArrowPlus (Monoidally p) where + (<+>) = (>|<) +instance (Category.Category p, Monoidal p, Strong p, Costrong p) + => Arrow.ArrowLoop (Monoidally p) where + loop = unfirst diff --git a/distributors-core/src/Data/Profunctor/Monoidal/Cocartesian.hs b/distributors-core/src/Data/Profunctor/Monoidal/Cocartesian.hs new file mode 100644 index 00000000..606e7185 --- /dev/null +++ b/distributors-core/src/Data/Profunctor/Monoidal/Cocartesian.hs @@ -0,0 +1,225 @@ +{-| +Module : Data.Profunctor.Monoidal.Cocartesian +Description : cocartesian monoidal profunctors +Copyright : (C) 2026 - Eitan Chatav +License : BSD-style (see the file LICENSE) +Maintainer : Eitan Chatav +Stability : provisional +Portability : non-portable +-} + +module Data.Profunctor.Monoidal.Cocartesian + ( -- * CocartesianMonoidal + CocartesianMonoidal (..) + , dialt + -- * CocartesianChoice + , CocartesianChoice (..) + ) where + + +import Control.Applicative hiding (WrappedArrow) +import Control.Applicative qualified as Ap (WrappedArrow) +import Control.Arrow +import Control.Lens hiding (chosen) +import Control.Lens.Internal.Profunctor +import Control.Lens.PartialIso +import Data.Bifunctor.Clown +import Data.Bifunctor.Joker +import Data.Bifunctor.Product +import Data.Functor.Adjunction +import Data.Functor.Contravariant.Divisible +import Data.Monoid.Disjunctive +import Data.Profunctor hiding (WrappedArrow) +import Data.Profunctor qualified as Pro (WrappedArrow) +import Data.Profunctor.Cayley +import Data.Profunctor.Composition +import Data.Profunctor.Monad +import Data.Profunctor.Yoneda +import Data.Void + +-- $setup +-- >>> import Data.Profunctor (dimap) +-- >>> import Data.Void (absurd) + +-- CocartesianMonoidal -- + +{- | A lax `CocartesianMonoidal` sum `Profunctor` has zero `zeroP` +and sum `>+<` lax monoidal structure morphisms, +respecting the cocartesian monoidal structure of `Void` & `Either`, +as `Data.Profunctor.Monoidal.Monoidal` respects that of @()@ & @(,)@. + +Laws: + +>>> let lunit = dimap (either absurd id) Right +>>> let runit = dimap (either id absurd) Left +>>> :{ +let assoc = dimap + (either (Left . Left) (either (Left . Right) Right)) + (either (either Left (Right . Left)) (Right . Right)) +:} + +> prop> zeroP >+< p = lunit p +> prop> p >+< zeroP = runit p +> prop> p >+< q >+< r = assoc ((p >+< q) >+< r) +> prop> dimap (f >+< g) (h >+< i) (p >+< q) = dimap f h p >+< dimap g i q +-} +class Profunctor p => CocartesianMonoidal p where + + {- | The zero structure morphism of a `CocartesianMonoidal`. + + `zeroP` has a default for `CocartesianChoice`s. + + > prop> zeroP = falseP + -} + zeroP :: p Void Void + default zeroP :: CocartesianChoice p => p Void Void + zeroP = falseP + + {- | The sum structure morphism of a `CocartesianMonoidal`. + + `>+<` has a default for `CocartesianChoice`s. + + > prop> x >+< y = alternate (Left x) >|< alternate (Right y) + -} + (>+<) :: p a b -> p c d -> p (Either a c) (Either b d) + default (>+<) + :: CocartesianChoice p + => p a b -> p c d -> p (Either a c) (Either b d) + x >+< y = alternate (Left x) >|< alternate (Right y) + infixr 3 >+< + +instance CocartesianMonoidal (->) where + zeroP = id + (>+<) = (+++) +instance CocartesianMonoidal (Forget s) where + zeroP = Forget absurd + Forget kL >+< Forget kR = Forget (either kL kR) +instance Decidable f => CocartesianMonoidal (Clown f) where + zeroP = Clown lost + Clown x >+< Clown y = Clown (chosen x y) +instance Alternative f => CocartesianMonoidal (Joker f) where + zeroP = Joker empty + Joker x >+< Joker y = Joker (Left <$> x <|> Right <$> y) +instance (CocartesianMonoidal p, Functor f) + => CocartesianMonoidal (WrappedPafb f p) where + zeroP = WrapPafb (rmap absurd zeroP) + WrapPafb x >+< WrapPafb y = WrapPafb $ + dialt id (fmap Left) (fmap Right) x y +instance Functor f => CocartesianMonoidal (Star f) where + zeroP = Star absurd + Star f >+< Star g = + Star (either (fmap Left . f) (fmap Right . g)) +deriving via (Star m) instance Monad m => CocartesianMonoidal (Kleisli m) +instance Adjunction f u => CocartesianMonoidal (Costar f) where + zeroP = Costar unabsurdL + Costar f >+< Costar g = Costar (bimap f g . cozipL) +instance (Applicative f, CocartesianMonoidal p) + => CocartesianMonoidal (Cayley f p) where + zeroP = Cayley (pure zeroP) + Cayley x >+< Cayley y = Cayley ((>+<) <$> x <*> y) +instance (ArrowZero p, ArrowChoice p) + => CocartesianMonoidal (Pro.WrappedArrow p) where + zeroP = zeroArrow + (>+<) = (+++) +deriving via (Pro.WrappedArrow p) + instance (ArrowZero p, ArrowChoice p) + => CocartesianMonoidal (Ap.WrappedArrow p) +instance (CocartesianMonoidal p, CocartesianMonoidal q) + => CocartesianMonoidal (Procompose p q) where + zeroP = Procompose zeroP zeroP + Procompose xL yL >+< Procompose xR yR = + Procompose (xL >+< xR) (yL >+< yR) +instance (CocartesianMonoidal p, CocartesianMonoidal q) + => CocartesianMonoidal (Product p q) where + zeroP = Pair zeroP zeroP + Pair x0 y0 >+< Pair x1 y1 = Pair (x0 >+< x1) (y0 >+< y1) +instance CocartesianMonoidal p => CocartesianMonoidal (Yoneda p) where + zeroP = proreturn zeroP + ab >+< cd = proreturn (proextract ab >+< proextract cd) +instance CocartesianMonoidal p => CocartesianMonoidal (Coyoneda p) where + zeroP = proreturn zeroP + ab >+< cd = proreturn (proextract ab >+< proextract cd) + +{- | `dialt` is a functionalized form of `>+<`. -} +dialt + :: CocartesianMonoidal p + => (s -> Either a c) + -> (b -> t) + -> (d -> t) + -> p a b -> p c d -> p s t +dialt f g h p q = dimap f (either g h) (p >+< q) + +-- CocartesianChoice -- + +{- | `CocartesianChoice` co-extends `Choice` and `CocartesianMonoidal`, +with `DisjunctiveMonoid` failure `falseP` and choice `>|<`, +like `Alternative` but without requiring +`Data.Profunctor.Monoidal.Monoidal` structure, +and the `alternate` method, which is a lax monoidal structure morphism +on sums, with these laws relating them. + +> prop> left' = alternate . Left +> prop> right' = alternate . Right +> prop> zeroP = falseP +> prop> x >+< y = alternate (Left x) >|< alternate (Right y) + +Since @alternate (Left x)@ is parametric in the other summand, +it can't pass that summand through, so by these laws, +`left'` & `right'` of a `CocartesianChoice` never pass the other +summand through, unlike those of @(->)@, which isn't one; +they fail on it, or ignore their input, as those of t'Joker' do. +So a `Control.Lens.Prism.Prism` applied by `Control.Lens.PartialIso.>?` +doesn't pass a mismatch through, either. + +For the case of `Functor`s, the analog of `alternate` can be defined +without any other constraint, but the case of `Profunctor`s turns +out to be slightly more complex, necessitating `CocartesianChoice`. + +>>> :{ +alternateF :: Functor f => Either (f a) (f b) -> f (Either a b) +alternateF = either (fmap Left) (fmap Right) +:} +-} +class (CocartesianMonoidal p, Choice p, forall x y. DisjunctiveMonoid (p x y)) + => CocartesianChoice p where + + {- | The structure morphism for a `CocartesianChoice`, + `alternate` has a default for `Choice` & `Cochoice` partial distributors. + -} + alternate + :: Either (p a b) (p c d) + -> p (Either a c) (Either b d) + default alternate + :: Cochoice p + => Either (p a b) (p c d) + -> p (Either a c) (Either b d) + alternate = + dimapMaybe (either Just (pure Nothing)) (Just . Left) + ||| + dimapMaybe (either (pure Nothing) Just) (Just . Right) + +instance (CocartesianChoice p, Applicative f) + => CocartesianChoice (WrappedPafb f p) where + alternate = + let + f = WrapPafb + . rmap (either (fmap Left) pure) + . alternate + . Left + . unwrapPafb + g = WrapPafb + . rmap (either pure (fmap Right)) + . alternate + . Right + . unwrapPafb + in + either f g +instance CocartesianChoice p => CocartesianChoice (Coyoneda p) where + alternate (Left p) = proreturn (alternate (Left (proextract p))) + alternate (Right p) = proreturn (alternate (Right (proextract p))) +instance CocartesianChoice p => CocartesianChoice (Yoneda p) where + alternate (Left p) = proreturn (alternate (Left (proextract p))) + alternate (Right p) = proreturn (alternate (Right (proextract p))) +instance Alternative f => CocartesianChoice (Joker f) where + alternate (Left (Joker x)) = Joker (Left <$> x) + alternate (Right (Joker y)) = Joker (Right <$> y) diff --git a/distributors-core/src/Data/Traversable/Homogeneous.hs b/distributors-core/src/Data/Traversable/Homogeneous.hs new file mode 100644 index 00000000..e16567eb --- /dev/null +++ b/distributors-core/src/Data/Traversable/Homogeneous.hs @@ -0,0 +1,352 @@ +{-| +Module : Data.Traversable.Homogeneous +Description : homogeneous +Copyright : (C) 2026 - Eitan Chatav +License : BSD-style (see the file LICENSE) +Maintainer : Eitan Chatav +Stability : provisional +Portability : non-portable +-} + +module Data.Traversable.Homogeneous + ( -- * Homogeneous + Homogeneous (..) + , zipHomogeneous + , zipWithHomogeneous + , zipWithHomogeneous3 + , zipWithHomogeneousM + , transposeHomogeneous + -- * Zipporah + , Zipporah (..) + ) where + +import Control.Applicative +import Control.Lens hiding (chosen) +import Control.Lens.PartialIso +import Control.Monad.Trans.Identity (IdentityT (..)) +import Data.Complex +import Data.Functor.Compose +import Data.List.NonEmpty (NonEmpty (..)) +import qualified Data.Functor.Product as Functor +import qualified Data.Functor.Sum as Functor +import qualified Data.Monoid as Monoid +import Data.Ord (Down (..)) +import qualified Data.Semigroup as Semigroup +import Data.Monoid.Disjunctive +import Data.Profunctor (Cochoice (..), Star (..)) +import Data.Profunctor.Monoidal +import Data.Proxy +import Data.Sequence (Seq) +import Data.Tagged +import Data.Tree (Tree (..)) +import Data.Vector (Vector) +import Data.Void +import GHC.Generics +import Witherable (Filterable (..)) + +import Data.Profunctor.Distributor +import Data.Profunctor.Monadic (Monadic) +import Data.Profunctor.Monoidal.Cocartesian + +-- $setup +-- >>> import Data.List.NonEmpty (NonEmpty (..)) + +{- | A class of `Homogeneous` +countable sums of countable products. + +They shape `Control.Lens.Diopter.Diopter`s, +& two subclasses of them shape two kinds of `Control.Lens.Diopter.Diopter`: +countable products, which are `Traversable` ∩ `Data.Distributive.Distributive`, +shape `Control.Lens.Monocle.Monocle`s, +& countable sums of single copies, which are +`Data.Traversable.Homogeneous.Enumerable.Enumerable`, +shape `Control.Lens.Comonocle.Comonocle`s, + +(`Traversable` ∩ `Data.Distributive.Distributive`) +∪ `Data.Traversable.Homogeneous.Enumerable.Enumerable` +⊂ `Homogeneous`, + +as `Control.Lens.Monocle.Monocle` ∪ `Control.Lens.Comonocle.Comonocle` +⊂ `Control.Lens.Diopter.Diopter`. +-} +class Traversable t => Homogeneous t where + {- | Sequences actions `homogeneously`. + + > prop> homogeneously @Maybe = optionalP + > prop> homogeneously @[] = manyP + + Any `Traversable` & `Data.Distributive.Distributive` countable product + can be given a default implementation for the `homogeneously` method + with `ditraverse`. + + > prop> homogeneously = ditraverse + + And any user-defined homogeneous algebraic datatype has + a default instance for `Homogeneous`, by deriving `Generic1`. + -} + homogeneously :: Distributor p => p a b -> p (t a) (t b) + default homogeneously + :: (Generic1 t, Homogeneous (Rep1 t), Distributor p) + => p a b -> p (t a) (t b) + homogeneously = dimap from1 to1 . homogeneously +instance Homogeneous Par1 where + homogeneously = dimap unPar1 Par1 +instance Homogeneous Identity where + homogeneously = dimap runIdentity Identity +instance Homogeneous Monoid.Dual where + homogeneously = dimap Monoid.getDual Monoid.Dual +instance Homogeneous Monoid.Product where + homogeneously = dimap Monoid.getProduct Monoid.Product +instance Homogeneous Monoid.Sum where + homogeneously = dimap Monoid.getSum Monoid.Sum +instance Homogeneous (Tagged s) where + homogeneously = dimap unTagged Tagged +instance Homogeneous Down where + homogeneously = dimap getDown Down +instance Homogeneous Semigroup.Min where + homogeneously = dimap Semigroup.getMin Semigroup.Min +instance Homogeneous Semigroup.Max where + homogeneously = dimap Semigroup.getMax Semigroup.Max +instance Homogeneous Semigroup.First where + homogeneously = dimap Semigroup.getFirst Semigroup.First +instance Homogeneous Semigroup.Last where + homogeneously = dimap Semigroup.getLast Semigroup.Last +instance Homogeneous f => Homogeneous (Monoid.Alt f) where + homogeneously = dimap Monoid.getAlt Monoid.Alt . homogeneously +instance Homogeneous f => Homogeneous (Monoid.Ap f) where + homogeneously = dimap Monoid.getAp Monoid.Ap . homogeneously +instance Homogeneous f => Homogeneous (IdentityT f) where + homogeneously = dimap runIdentityT IdentityT . homogeneously +instance Homogeneous U1 where + homogeneously _ = pure U1 +instance Homogeneous (K1 i ()) where + homogeneously _ = pure (K1 ()) +instance Homogeneous (Const ()) where + homogeneously _ = pure (Const ()) +instance Homogeneous Proxy where + homogeneously _ = pure Proxy +instance (Homogeneous s, Homogeneous t) + => Homogeneous (s :.: t) where + homogeneously + = dimap unComp1 Comp1 + . homogeneously . homogeneously +instance (Homogeneous s, Homogeneous t) + => Homogeneous (Compose s t) where + homogeneously + = dimap getCompose Compose + . homogeneously . homogeneously +instance (Homogeneous s, Homogeneous t) + => Homogeneous (s :*: t) where + homogeneously p = dimap2 + (\(s :*: _) -> s) + (\(_ :*: t) -> t) + (:*:) + (homogeneously p) + (homogeneously p) +instance (Homogeneous s, Homogeneous t) + => Homogeneous (Functor.Product s t) where + homogeneously p = dimap2 + (\(Functor.Pair s _) -> s) + (\(Functor.Pair _ t) -> t) + Functor.Pair + (homogeneously p) + (homogeneously p) +instance Homogeneous V1 where + homogeneously _ = dimap (\case) (\case) zeroP +instance Homogeneous (K1 i Void) where + homogeneously _ = dimap unK1 K1 zeroP +instance Homogeneous (Const Void) where + homogeneously _ = dimap getConst Const zeroP +instance (Homogeneous s, Homogeneous t) + => Homogeneous (s :+: t) where + homogeneously p = dialt + (\case {L1 s -> Left s; R1 t -> Right t}) + L1 + R1 + (homogeneously p) + (homogeneously p) +instance (Homogeneous s, Homogeneous t) + => Homogeneous (Functor.Sum s t) where + homogeneously p = dialt + (\case {Functor.InL s -> Left s; Functor.InR t -> Right t}) + Functor.InL + Functor.InR + (homogeneously p) + (homogeneously p) +instance Homogeneous t + => Homogeneous (M1 i c t) where + homogeneously = dimap unM1 M1 . homogeneously +instance Homogeneous f => Homogeneous (Rec1 f) where + homogeneously = dimap unRec1 Rec1 . homogeneously +instance Homogeneous Maybe where + homogeneously = optionalP +instance Homogeneous [] where + homogeneously = manyP +{- | One or more, by deriving `Generic1`, like `someP`. + +>>> zipWithHomogeneous (+) (1 :| [2]) (3 :| [4 :: Int]) +Just (4 :| [6]) +-} +instance Homogeneous NonEmpty +instance Homogeneous Vector where + homogeneously p = eotList . swapped >~ p >*< homogeneously p >+< oneP +instance Homogeneous Seq where + homogeneously p = eotList . swapped >~ p >*< homogeneously p >+< oneP +instance Homogeneous Complex where + homogeneously p = dimap2 realPart imagPart (:+) p p +instance Homogeneous Tree where + homogeneously p = dimap2 rootLabel subForest Node p (manyP (homogeneously p)) + +{- | A copy tagged by a finite enumeration is a copy for each tag, +summed in a balanceBy tree, built lazily. + +>>> zipWithHomogeneous (+) (True, 1) (True, 2 :: Int) +Just (True,3) +>>> zipWithHomogeneous (+) (True, 1) (False, 2 :: Int) +Nothing +-} +instance (Enum e, Bounded e) => Homogeneous ((,) e) where + homogeneously p = go (tag (minBound :: e)) (tag (maxBound :: e)) + where + tag = toInteger . fromEnum + go lo hi + | lo >= hi = dimap snd (toEnum (fromInteger lo),) p + | otherwise = dialt + (\ea -> if tag (fst ea) <= mid then Left ea else Right ea) + id id (go lo mid) (go (mid + 1) hi) + where + mid = (lo + hi) `div` 2 + +{- | Zip `Homogeneous` structures in the positions of a `Traversable`, +by a function of their elements at each position, when they have the +same shape, or else `empty`. + +>>> zipHomogeneous (Just . sum) [[1, 2], [3, 4], [5, 6 :: Int]] +Just [9,12] +>>> zipHomogeneous (Just . sum) [[1, 2], [3 :: Int]] +Nothing +>>> zipHomogeneous id [[1, 2], [3, 4 :: Int]] +[[1,2],[1,4],[3,2],[3,4]] +-} +zipHomogeneous + :: (Homogeneous t, Traversable f, Alternative g) + => (f a -> g b) -> f (t a) -> g (t b) +zipHomogeneous f = runZipporah (homogeneously (Zipporah f)) + +{- | Zip two `Homogeneous` structures, when they have the same shape. + +>>> zipWithHomogeneous (+) [1, 2] [3, 4 :: Int] +Just [4,6] +>>> zipWithHomogeneous (+) [1] [3, 4 :: Int] +Nothing +-} +zipWithHomogeneous + :: Homogeneous t => (a -> a -> b) -> t a -> t a -> Maybe (t b) +zipWithHomogeneous f x y = + zipHomogeneous (\(Par1 a :*: Par1 b) -> Just (f a b)) (Par1 x :*: Par1 y) + +{- | Zip three `Homogeneous` structures, when they have the same shape. + +>>> zipWithHomogeneous3 (\a b c -> a + b + c) [1, 2] [3, 4] [5, 6 :: Int] +Just [9,12] +>>> zipWithHomogeneous3 (\a b c -> a + b + c) [1, 2] [3, 4] [5 :: Int] +Nothing +-} +zipWithHomogeneous3 + :: Homogeneous t + => (a -> a -> a -> b) -> t a -> t a -> t a -> Maybe (t b) +zipWithHomogeneous3 f x y z = zipHomogeneous + (\(Par1 a :*: Par1 b :*: Par1 c) -> Just (f a b c)) + (Par1 x :*: Par1 y :*: Par1 z) + +{- | Zip two `Homogeneous` structures by an action, when they have the same +shape. The actions of the positions which match run, even when the shapes +differ elsewhere. + +>>> zipWithHomogeneousM (\a b -> ([a + b], a * b)) [1, 2] [3, 4 :: Int] +([4,6],Just [3,8]) +>>> zipWithHomogeneousM (\a b -> ([a + b], a * b)) [1, 2] [3 :: Int] +([4],Nothing) +-} +zipWithHomogeneousM + :: (Homogeneous t, Applicative m) + => (a -> a -> m b) -> t a -> t a -> m (Maybe (t b)) +zipWithHomogeneousM f x y = runStar + (runZipporah (homogeneously (Zipporah (Star + (\(Par1 a :*: Par1 b) -> Just <$> f a b))))) + (Par1 x :*: Par1 y) + +{- | Transpose `Homogeneous` structures in the positions of a `Traversable`, +when they have the same shape. Without any structures, a sum's first copy +repeats, so that a list is infinite. + +>>> transposeHomogeneous [[1, 2, 3], [4, 5, 6 :: Int]] +Just [[1,4],[2,5],[3,6]] +>>> transposeHomogeneous [[1, 2], [3 :: Int]] +Nothing +-} +transposeHomogeneous + :: (Homogeneous t, Traversable f) => f (t a) -> Maybe (t (f a)) +transposeHomogeneous = zipHomogeneous Just + + +{- | t'Zipporah' is a profunctor @p@ between functors, like `Data.Bifunctor.Biff`, +but lifting @p@'s instances through @g@, & splitting sums by @f@, +which fail in @g@ unless every position of @f@ holds the same copy. +-} +newtype Zipporah p f g a b = Zipporah {runZipporah :: p (f a) (g b)} +instance (Profunctor p, Functor f, Functor g) + => Profunctor (Zipporah p f g) where + dimap h k (Zipporah x) = Zipporah (dimap (fmap h) (fmap k) x) +instance (Profunctor p, Functor g) => Functor (Zipporah p f g a) where + fmap k (Zipporah x) = Zipporah (rmap (fmap k) x) +instance (Monoidal p, Applicative g) => Applicative (Zipporah p f g a) where + pure b = Zipporah (pure (pure b)) + Zipporah x <*> Zipporah y = Zipporah (liftA2 (<*>) x y) +instance (Monoidal p, Alternative g) => Alternative (Zipporah p f g a) where + empty = Zipporah (pure empty) + Zipporah x <|> Zipporah y = Zipporah (liftA2 (<|>) x y) +instance Monadic p => Monad (Zipporah p f Maybe a) where + Zipporah x >>= k = Zipporah (x >>= maybe (pure Nothing) (runZipporah . k)) +instance (Profunctor p, Filterable g) => Filterable (Zipporah p f g a) where + mapMaybe h (Zipporah x) = Zipporah (rmap (mapMaybe h) x) +instance (Monoidal p, Alternative g) => DisjunctiveMonoid (Zipporah p f g a b) where + falseP = empty + (>|<) = (<|>) +instance (Choice p, Traversable f, Alternative g) => Choice (Zipporah p f g) where + left' (Zipporah x) = Zipporah (leftCopies x) + right' (Zipporah x) = Zipporah (rightCopies x) +instance (Profunctor p, Functor f, Filterable g) => Cochoice (Zipporah p f g) where + unleft (Zipporah x) = + Zipporah (dimap (fmap Left) (mapMaybe (either Just (const Nothing))) x) + unright (Zipporah x) = + Zipporah (dimap (fmap Right) (mapMaybe (either (const Nothing) Just)) x) +instance (Choice p, Monoidal p, Traversable f, Alternative g) + => CocartesianMonoidal (Zipporah p f g) where + zeroP = empty + Zipporah x >+< Zipporah y = Zipporah (liftA2 (<|>) (leftCopies x) (rightCopies y)) +instance (Choice p, Monoidal p, Traversable f, Alternative g) + => CocartesianChoice (Zipporah p f g) where + alternate = Zipporah . either leftCopies rightCopies . bimap runZipporah runZipporah +instance (Choice p, Monoidal p, Traversable f, Alternative g) + => Distributor (Zipporah p f g) +instance (Choice p, Monoidal p, Traversable f, Alternative g) + => Alternator (Zipporah p f g) + +-- Sources which all hold the left copy of a sum, or else fail. +leftCopies + :: (Choice p, Traversable f, Alternative g) + => p (f a) (g b) -> p (f (Either a c)) (g (Either b d)) +leftCopies = dimap + (\ss -> maybe (Right ()) Left (traverse (either Just (const Nothing)) ss)) + (either (fmap Left) (const empty)) + . left' + +-- Sources which all hold the right copy of a sum, or else fail. +rightCopies + :: (Choice p, Traversable f, Alternative g) + => p (f c) (g d) -> p (f (Either a c)) (g (Either b d)) +rightCopies = dimap + (\ss -> maybe (Right ()) Left (traverse (either (const Nothing) Just) ss)) + (either (fmap Right) (const empty)) + . left' diff --git a/distributors-core/src/Data/Traversable/Homogeneous/Enumerable.hs b/distributors-core/src/Data/Traversable/Homogeneous/Enumerable.hs new file mode 100644 index 00000000..4f4ac981 --- /dev/null +++ b/distributors-core/src/Data/Traversable/Homogeneous/Enumerable.hs @@ -0,0 +1,290 @@ +{-| +Module : Data.Traversable.Homogeneous.Enumerable +Description : enumerable +Copyright : (C) 2026 - Eitan Chatav +License : BSD-style (see the file LICENSE) +Maintainer : Eitan Chatav +Stability : provisional +Portability : non-portable +-} + +module Data.Traversable.Homogeneous.Enumerable + ( -- * Enumerable + Enumerable (..) + , fromEnumerable + , succEnumerable + , predEnumerable + , enumerateFrom + , enumerateFromThen + , enumerateFromTo + , enumerateFromThenTo + -- * Enumerator + , Enumerator (..) + ) where + +import Control.Applicative +import Control.Lens hiding (chosen) +import Control.Lens.PartialIso +import Control.Monad ((>=>)) +import Control.Monad.Trans.Identity (IdentityT (..)) +import Data.Functor.Compose +import qualified Data.Functor.Sum as Functor +import qualified Data.Monoid as Monoid +import Data.Ord (Down (..)) +import qualified Data.Semigroup as Semigroup +import Data.Profunctor (Cochoice (..), Forget (..)) +import Data.Tagged +import Data.Void +import GHC.Generics +import Numeric.Natural (Natural) + +import Data.Profunctor.Monoidal.Cocartesian +import Data.Traversable.Homogeneous + +-- $setup +-- >>> import Control.Lens (preview, review) + +{- | A class of `Enumerable` countable sums of single copies, +which are `Homogeneous`, & sequenced by sums alone. + +> prop> enumerably @Identity = dimap runIdentity Identity + +Every `Enumerable` is sequenced `enumerably` as it's sequenced +`homogeneously`, by a `Data.Profunctor.Distributor.Distributor`. + +> prop> enumerably = homogeneously + +And any user-defined enumerable algebraic datatype has +a default instance for `Enumerable`, by deriving `Generic1`. +-} +class Homogeneous f => Enumerable f where + {- | Sequences an action on the copy which a sum holds. -} + enumerably :: CocartesianMonoidal p => p a b -> p (f a) (f b) + default enumerably + :: (Generic1 f, Enumerable (Rep1 f), CocartesianMonoidal p) + => p a b -> p (f a) (f b) + enumerably = dimap from1 to1 . enumerably +instance Enumerable Par1 where + enumerably = dimap unPar1 Par1 +instance Enumerable Identity where + enumerably = dimap runIdentity Identity +instance Enumerable Monoid.Dual where + enumerably = dimap Monoid.getDual Monoid.Dual +instance Enumerable Monoid.Product where + enumerably = dimap Monoid.getProduct Monoid.Product +instance Enumerable Monoid.Sum where + enumerably = dimap Monoid.getSum Monoid.Sum +instance Enumerable (Tagged s) where + enumerably = dimap unTagged Tagged +instance Enumerable Down where + enumerably = dimap getDown Down +instance Enumerable Semigroup.Min where + enumerably = dimap Semigroup.getMin Semigroup.Min +instance Enumerable Semigroup.Max where + enumerably = dimap Semigroup.getMax Semigroup.Max +instance Enumerable Semigroup.First where + enumerably = dimap Semigroup.getFirst Semigroup.First +instance Enumerable Semigroup.Last where + enumerably = dimap Semigroup.getLast Semigroup.Last +instance Enumerable f => Enumerable (Monoid.Alt f) where + enumerably = dimap Monoid.getAlt Monoid.Alt . enumerably +instance Enumerable f => Enumerable (Monoid.Ap f) where + enumerably = dimap Monoid.getAp Monoid.Ap . enumerably +instance Enumerable f => Enumerable (IdentityT f) where + enumerably = dimap runIdentityT IdentityT . enumerably +instance (Enumerable s, Enumerable t) + => Enumerable (s :.: t) where + enumerably = dimap unComp1 Comp1 . enumerably . enumerably +instance (Enumerable s, Enumerable t) + => Enumerable (Compose s t) where + enumerably = dimap getCompose Compose . enumerably . enumerably +instance Enumerable V1 where + enumerably _ = dimap (\case) (\case) zeroP +instance Enumerable (K1 i Void) where + enumerably _ = dimap unK1 K1 zeroP +instance Enumerable (Const Void) where + enumerably _ = dimap getConst Const zeroP +instance (Enumerable s, Enumerable t) + => Enumerable (s :+: t) where + enumerably p = dialt + (\case {L1 s -> Left s; R1 t -> Right t}) + L1 + R1 + (enumerably p) + (enumerably p) +instance (Enumerable s, Enumerable t) + => Enumerable (Functor.Sum s t) where + enumerably p = dialt + (\case {Functor.InL s -> Left s; Functor.InR t -> Right t}) + Functor.InL + Functor.InR + (enumerably p) + (enumerably p) +instance Enumerable t => Enumerable (M1 i c t) where + enumerably = dimap unM1 M1 . enumerably +instance Enumerable f => Enumerable (Rec1 f) where + enumerably = dimap unRec1 Rec1 . enumerably +{- | A copy tagged by a finite enumeration is a copy for each tag, +numbered by its tag's `fromEnum`, from `minBound`, +& summed in a balanceBy tree, built lazily. + +>>> map (review fromEnumerable) [(False, 'a'), (True, 'b')] +[(0,'a'),(1,'b')] +>>> map (review fromEnumerable) [(LT, 'a'), (EQ, 'b'), (GT, 'c')] +[(0,'a'),(1,'b'),(2,'c')] + +Reaching a copy takes time logarithmic in the number of tags, +but counting them, as `fromEnumerable` does, takes time linear in it, +so it never ends for @Int@, & tags whose `fromEnum` fails, like large +@Word@s, aren't enumerable. +-} +instance (Enum e, Bounded e) => Enumerable ((,) e) where + enumerably p = go (tag (minBound :: e)) (tag (maxBound :: e)) + where + tag = toInteger . fromEnum + go lo hi + | lo >= hi = dimap snd (toEnum (fromInteger lo),) p + | otherwise = dialt + (\ea -> if tag (fst ea) <= mid then Left ea else Right ea) + id id (go lo mid) (go (mid + 1) hi) + where + mid = (lo + hi) `div` 2 + +{- | Which copy an `Enumerable` sum holds, numbered from 0, left to right, +like `fromEnum`. + +>>> review fromEnumerable (GT, 'x') +(2,'x') + +Also, the copy of an `Enumerable` sum at an index, if there is one, +like `toEnum`. + +>>> [preview fromEnumerable (i,'x') | i <- [0..3]] :: [Maybe (Ordering, Char)] +[Just (LT,'x'),Just (EQ,'x'),Just (GT,'x'),Nothing] + +-} +fromEnumerable :: Enumerable f => Prism' (Natural, a) (f a) +fromEnumerable = prism' (liftA2 (,) from' extract') to' + where + extract' = runForget (enumerably (Forget id)) + from' = case enumerably (pure ()) of + Enumerator _ which _ -> which + to' (n,a) = case enumerably (pure a) of + Enumerator _ _ select -> select n + +{- | The next copy of an `Enumerable` sum, if there is one, like `succ`, +& conversely, the previous copy, like `pred`. + +>>> preview succEnumerable (EQ, 'x') +Just (GT,'x') +>>> preview succEnumerable (GT, 'x') +Nothing +-} +succEnumerable :: Enumerable f => PartialIso' (f a) (f a) +succEnumerable = partialIso succ' pred' + where + succ' :: Enumerable f => f a -> Maybe (f a) + succ' x = case enumerably (pure (review fromEnumerable x)) of + Enumerator _ which select -> fmap (fmap snd) (select (which x + 1)) + pred' :: Enumerable f => f a -> Maybe (f a) + pred' x = case enumerably (pure (snd (review fromEnumerable x))) of + Enumerator _ which select -> case which x of + 0 -> Nothing + n -> select (n - 1) + +{- | The previous copy of an `Enumerable` sum, if there is one, like `pred`, +& conversely, the next copy, like `succ`. + +>>> preview predEnumerable (EQ, 'x') +Just (LT,'x') +>>> preview predEnumerable (LT, 'x') +Nothing +-} +predEnumerable :: Enumerable f => PartialIso' (f a) (f a) +predEnumerable = coPartialIso succEnumerable + +{- | The copies of an `Enumerable` sum from one onward, like `enumFrom`. + +>>> enumerateFrom (EQ, 'x') +[(EQ,'x'),(GT,'x')] +-} +enumerateFrom :: Enumerable f => f a -> [f a] +enumerateFrom x = case enumerably (pure (review fromEnumerable x)) of + Enumerator _ which select -> + let go n = maybe [] (: go (n + 1)) (select n) in fmap (fmap snd) (go (which x)) + +{- | The copies of an `Enumerable` sum from one onward, holding its focus, +stepping by the copy of another, like `enumFromThen`. + +>>> enumerateFromThen (LT, 'x') (EQ, ()) +[(LT,'x'),(EQ,'x'),(GT,'x')] +>>> enumerateFromThen (GT, 'x') (EQ, ()) +[(GT,'x'),(EQ,'x'),(LT,'x')] +-} +enumerateFromThen :: Enumerable f => f a -> f b -> [f a] +enumerateFromThen x y = copiesAt x [fromEnumerable' x, fromEnumerable' y ..] + +{- | The copies of an `Enumerable` sum from one to the copy of another, +holding its focus, like `enumFromTo`. + +>>> enumerateFromTo (LT, 'x') (EQ, ()) +[(LT,'x'),(EQ,'x')] +-} +enumerateFromTo :: Enumerable f => f a -> f b -> [f a] +enumerateFromTo x z = copiesAt x [fromEnumerable' x .. fromEnumerable' z] + +{- | The copies of an `Enumerable` sum from one to the copy of another, +holding its focus, stepping by the copy of a third, like `enumFromThenTo`. + +>>> enumerateFromThenTo (GT, 'x') (EQ, ()) (LT, ()) +[(GT,'x'),(EQ,'x'),(LT,'x')] +-} +enumerateFromThenTo :: Enumerable f => f a -> f b -> f c -> [f a] +enumerateFromThenTo x y z = + copiesAt x [fromEnumerable' x, fromEnumerable' y .. fromEnumerable' z] + +-- | The index of an `Enumerable` sum's copy, as an `Integer`. +fromEnumerable' :: Enumerable f => f a -> Integer +fromEnumerable' = toInteger . fst . review fromEnumerable + +{- | The copies at some indices, holding a sum's focus, +until an index has none. +-} +copiesAt :: Enumerable f => f a -> [Integer] -> [f a] +copiesAt x ixes = case enumerably (pure (snd (review fromEnumerable x))) of + Enumerator _ _ select -> + let + go = \case + i : is | i >= 0, Just copy <- select (fromInteger i) -> copy : go is + _ -> [] + in go ixes + +{- | t'Enumerator' numbers the copies of a sum of products, from 0, +left to right, & products row by row, both ways: +how many copies there are, which copy a source is, & the copy at an index. +-} +data Enumerator s t = Enumerator Natural (s -> Natural) (Natural -> Maybe t) +instance Profunctor Enumerator where + dimap f g (Enumerator count which select) = + Enumerator count (which . f) (fmap g . select) +instance Functor (Enumerator s) where + fmap = rmap +instance Applicative (Enumerator s) where + pure t = Enumerator 1 (const 0) (\i -> if i == 0 then Just t else Nothing) + Enumerator count0 which0 select0 <*> Enumerator count1 which1 select1 = Enumerator + (count0 * count1) + (\s -> which0 s * count1 + which1 s) + (\i -> if count1 == 0 then Nothing + else select0 (i `div` count1) <*> select1 (i `mod` count1)) +instance CocartesianMonoidal Enumerator where + zeroP = Enumerator 0 absurd (const Nothing) + Enumerator count0 which0 select0 >+< Enumerator count1 which1 select1 = Enumerator + (count0 + count1) + (either which0 ((count0 +) . which1)) + (\i -> if i < count0 then Left <$> select0 i + else Right <$> select1 (i - count0)) +instance Cochoice Enumerator where + unleft (Enumerator count which select) = Enumerator count + (which . Left) (select >=> either Just (const Nothing)) + unright (Enumerator count which select) = Enumerator count + (which . Right) (select >=> either (const Nothing) Just) diff --git a/distributors-core/test/Main.hs b/distributors-core/test/Main.hs new file mode 100644 index 00000000..838ca7a8 --- /dev/null +++ b/distributors-core/test/Main.hs @@ -0,0 +1,32 @@ +module Main (main) where + +import Data.IORef +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 +import Properties.Parsing + +main :: IO () +main = hspec $ do + describe "Disjunctive" disjunctiveProperties + describe "Homogeneous" homogeneousProperties + describe "PartialIso" partialIsoProperties + describe "Nested" nestedProperties + describe "Parsing" parsingProperties + describe "meander" meanderProperties + +meanderProperties :: Spec +meanderProperties = + it "preserves left-to-right traversal effects" $ do + let input = ["h", "e", "l", "l", "o"] + seenRef <- newIORef [] + let visit item = modifyIORef' seenRef (item :) >> pure () + units <- runStar (meander traverse (Star visit)) input + seen <- reverse <$> readIORef seenRef + seen `shouldBe` input + units `shouldBe` replicate (length input) () 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-core/test/Properties/Homogeneous.hs b/distributors-core/test/Properties/Homogeneous.hs new file mode 100644 index 00000000..880adb00 --- /dev/null +++ b/distributors-core/test/Properties/Homogeneous.hs @@ -0,0 +1,488 @@ +-- The laws are stated as written, which HLint would simplify. +{- HLINT ignore "Use <$>" -} +{- HLINT ignore "Alternative law, left identity" -} +{- HLINT ignore "Alternative law, right identity" -} +{- HLINT ignore "Monad law, left identity" -} +{- HLINT ignore "Monad law, right identity" -} +{- HLINT ignore "Use >=>" -} +module Properties.Homogeneous (homogeneousProperties) where + +import Control.Applicative +import Control.Arrow ((+++)) +import Control.Lens (ReifiedLens (..), ReifiedPrism (..), _Just, iview, over, preview, review, set, toListOf, traverseOf, view) +import Control.Lens.Diopter +import Control.Lens.Prismoid (APrismoid, Prismocular (..), clonePrismoid, lefted, prismocular, atLeast, withPrismocular, withPrismoid, (>?*)) +import Control.Lens.Bifocal (ABifocal, Spectacle (..), cloneBifocal, spectacle, withBifocal, withSpectacle) +import Control.Lens.PartialIso (clonePartialIso, satisfied) +import Control.Lens.Comonocle +import Control.Lens.Grate (Diffraction (..), diffraction, cotraversed, cotraverseOf, withDiffraction) +import Control.Lens.Monocle +import Control.Lens.PartialIso (withPartialIso) +import Control.Monad ((<=<)) +import Data.Functor.Compose (Compose (..)) +import Data.Complex (Complex (..)) +import Data.Foldable (toList) +import Data.Functor.Identity (Identity (..)) +import Data.List (transpose) +import Data.Int (Int8) +import Data.Maybe (fromMaybe) +import Data.Monoid.Disjunctive +import Data.Profunctor +import Data.Profunctor.Monadic (Monadic) +import Data.Profunctor.Monoidal (Monoidal) +import Data.Profunctor.Monoidal.Cocartesian +import Data.Proxy (Proxy (..)) +import Data.Traversable.Homogeneous +import Data.Traversable.Homogeneous.Enumerable +import Data.Void +import GHC.Generics (Par1 (..), (:*:) (..)) +import Numeric.Natural (Natural) +import Test.Hspec +import Test.Hspec.QuickCheck (prop) +import Test.QuickCheck +import Witherable (Filterable (..)) + +-- | Types of finitely many values, to observe profunctors on all inputs. +class Eq s => Finite s where + universe :: [s] +instance Finite () where + universe = [()] +instance Finite Bool where + universe = [False, True] +instance Finite Void where + universe = [] +instance (Finite a, Finite b) => Finite (Either a b) where + universe = map Left universe <> map Right universe + +-- | An `Enumerator`'s count, indices of all sources, & selections, a little past. +enumerator :: Finite s => Enumerator s t -> (Natural, [Natural], [Maybe t]) +enumerator (Enumerator count which select) = + (count, map which universe, map select [0 .. count + 1]) + +natural :: Gen Natural +natural = fromInteger . getNonNegative <$> arbitrary + +genEnumerator :: forall s t. Finite s => Gen t -> Gen (Enumerator s t) +genEnumerator gen = do + count <- (`mod` 5) <$> natural + which <- vectorOf (length (universe :: [s])) natural + selected <- vectorOf (fromIntegral count) gen + pure $ Enumerator count + (\s -> fromMaybe 0 (lookup s (zip universe which))) + (\i -> lookup i (zip [0 ..] selected)) + +lunit :: Profunctor p => p a b -> p (Either Void a) (Either Void b) +lunit = dimap (either absurd id) Right + +runit :: Profunctor p => p a b -> p (Either a Void) (Either b Void) +runit = dimap (either id absurd) Left + +assocE :: Either (Either a b) c -> Either a (Either b c) +assocE = either (either Left (Right . Left)) (Right . Right) + +unassocE :: Either a (Either b c) -> Either (Either a b) c +unassocE = either (Left . Left) (either (Left . Right) Right) + +swapE :: Either a b -> Either b a +swapE = either Right Left + +-- | All the sources of a shape, of a finite type. +sources :: (Traversable f, Finite s) => f () -> [f s] +sources shape = traverse (const universe) shape + +-- | A function of sources, by a table of its results. +tabulated :: (Foldable f, Eq s) => [f s] -> [r] -> r -> f s -> r +tabulated inputs results def ss = + fromMaybe def (lookup (toList ss) (zip (map toList inputs) results)) + +-- | Observing & generating `Zipporah`s of a profunctor & a functor. +data Zipper p g h = Zipper + { observeZipper + :: forall f s t. (Traversable f, Finite s) + => f () -> Zipporah p f g s t -> [h t] + , generateZipper + :: forall f s t. (Traversable f, Finite s) + => f () -> Gen t -> Gen (Zipporah p f g s t) + } + +-- | `Zipporah`s of functions, to an `Alternative`. +functionZipper :: Alternative g => (forall t. Gen t -> Gen (g t)) -> Zipper (->) g g +functionZipper genG = Zipper + { observeZipper = \shape (Zipporah z) -> map z (sources shape) + , generateZipper = \shape gen -> do + let inputs = sources shape + results <- vectorOf (length inputs) (genG gen) + pure (Zipporah (tabulated inputs results empty)) + } + +-- | `Zipporah`s of `Star`s of a writer, to `Maybe`. +writerZipper :: Zipper (Star ((,) [Int])) Maybe (Compose ((,) [Int]) Maybe) +writerZipper = Zipper + { observeZipper = \shape (Zipporah (Star z)) -> map (Compose . z) (sources shape) + , generateZipper = \shape gen -> do + let inputs = sources shape + results <- vectorOf (length inputs) + ((,) <$> resize 2 arbitrary <*> liftArbitrary gen) + pure (Zipporah (Star (tabulated inputs results ([], Nothing)))) + } + +-- | The laws of `Zipporah`, up to `Alternator`, of the sources of a shape. +zippingLaws + :: forall p g h f. + ( Choice p, Monoidal p, Alternative g, Filterable g, Traversable f + , forall t. Eq t => Eq (h t), forall t. Show t => Show (h t) ) + => Zipper p g h -> String -> f () -> Spec +zippingLaws zipper name shape = describe name $ do + let + obs :: Finite s => Zipporah p f g s t -> [h t] + obs = observeZipper zipper shape + gen :: Finite s => Gen t -> Gen (Zipporah p f g s t) + gen = generateZipper zipper shape + z = gen arbitrary :: Gen (Zipporah p f g Bool Int) + zf = gen (applyFun <$> arbitrary) :: Gen (Zipporah p f g Bool (Int -> Int)) + ze = gen arbitrary :: Gen (Zipporah p f g (Either Bool ()) (Either Int ())) + prop "dimap id id = id" $ forAllBlind z $ \p -> + obs (dimap id id p) === obs p + prop "dimap (f . g) (h . i) = dimap g h . dimap f i" $ forAllBlind z $ + \p (Fun _ f) (Fun _ g) (Fun _ h) (Fun _ i) -> + obs (dimap (f . g) (h . i) p :: Zipporah p f g Bool Int) + === obs (dimap g (h :: Int -> Int) (dimap (f :: Bool -> Bool) i p)) + prop "pure id <*> v = v" $ forAllBlind z $ \v -> + obs (pure id <*> v) === obs v + prop "pure (.) <*> u <*> v <*> w = u <*> (v <*> w)" $ + forAllBlind zf $ \u -> forAllBlind zf $ \v -> forAllBlind z $ \w -> + obs (pure (.) <*> u <*> v <*> w) === obs (u <*> (v <*> w)) + prop "pure f <*> pure x = pure (f x)" $ \(Fun _ f) (x :: Int) -> + obs (pure f <*> pure x :: Zipporah p f g Bool Int) + === obs (pure (f x) :: Zipporah p f g Bool Int) + prop "u <*> pure y = pure ($ y) <*> u" $ forAllBlind zf $ \u (y :: Int) -> + obs (u <*> pure y) === obs (pure ($ y) <*> u) + prop "empty <|> x = x = x <|> empty" $ forAllBlind z $ \x -> + obs (empty <|> x) === obs x .&&. obs (x <|> empty) === obs x + prop "(x <|> y) <|> w = x <|> (y <|> w)" $ + forAllBlind z $ \x -> forAllBlind z $ \y -> forAllBlind z $ \w -> + obs ((x <|> y) <|> w) === obs (x <|> (y <|> w)) + prop "mapMaybe Just = id" $ forAllBlind z $ \p -> + obs (mapMaybe Just p) === obs p + prop "mapMaybe f . mapMaybe g = mapMaybe (f <=< g)" $ forAllBlind z $ + \p (Fun _ f) (Fun _ g) -> + obs (mapMaybe (f :: Int -> Maybe Int) (mapMaybe (g :: Int -> Maybe Int) p)) + === obs (mapMaybe (f <=< g) p) + prop "zeroP >+< p = lunit p" $ forAllBlind z $ \p -> + obs (zeroP >+< p) === obs (lunit p) + prop "p >+< zeroP = runit p" $ forAllBlind z $ \p -> + obs (p >+< zeroP) === obs (runit p) + prop "p >+< q >+< r = assoc ((p >+< q) >+< r)" $ + forAllBlind z $ \p -> forAllBlind z $ \q -> forAllBlind z $ \r -> + obs (p >+< q >+< r) === obs (dimap unassocE assocE ((p >+< q) >+< r)) + prop "dimap (f +++ g) (h +++ i) (p >+< q) = dimap f h p >+< dimap g i q" $ + forAllBlind z $ \p -> forAllBlind z $ \q (Fun _ f) (Fun _ g) (Fun _ h) (Fun _ i) -> + obs (dimap (f +++ g) (h +++ i) (p >+< q) + :: Zipporah p f g (Either Bool Bool) (Either Int Int)) + === obs (dimap f (h :: Int -> Int) p >+< dimap g (i :: Int -> Int) q) + prop "rmap Left = lmap Left . left'" $ forAllBlind z $ \p -> + obs (rmap Left p :: Zipporah p f g Bool (Either Int ())) + === obs (lmap Left (left' p)) + prop "left' = dimap swapE swapE . right'" $ forAllBlind z $ \p -> + obs (left' p :: Zipporah p f g (Either Bool ()) (Either Int ())) + === obs (dimap swapE swapE (right' p)) + prop "left' . left' = dimap assocE unassocE . left'" $ forAllBlind z $ \p -> + obs (left' (left' p) + :: Zipporah p f g (Either (Either Bool ()) ()) (Either (Either Int ()) ())) + === obs (dimap assocE unassocE (left' p)) + prop "unleft = unright . dimap swapE swapE" $ forAllBlind ze $ \p -> + obs (unleft p) === obs (unright (dimap swapE swapE p)) + prop "rmap (either id absurd) = unleft . lmap (either id absurd)" $ + forAllBlind (gen (Left <$> arbitrary) + :: Gen (Zipporah p f g Bool (Either Int Void))) $ \p -> + obs (rmap (either id absurd) p) + === obs (unleft (lmap (either id absurd) p) :: Zipporah p f g Bool Int) + prop "left' = alternate . Left" $ forAllBlind z $ \p -> + obs (left' p :: Zipporah p f g (Either Bool ()) (Either Int ())) + === obs (alternate (Left p) + :: Zipporah p f g (Either Bool ()) (Either Int ())) + prop "right' = alternate . Right" $ forAllBlind z $ \p -> + obs (right' p :: Zipporah p f g (Either () Bool) (Either () Int)) + === obs (alternate (Right p) + :: Zipporah p f g (Either () Bool) (Either () Int)) + prop "x >+< y = alternate (Left x) >|< alternate (Right y)" $ + forAllBlind z $ \x -> forAllBlind z $ \y -> + obs (x >+< y) === obs (alternate (Left x) >|< alternate (Right y)) + +-- | The `Monad` laws of `Zipporah`, to `Maybe`, of the sources of a shape. +zippingMonadLaws + :: forall p h f. + ( Monadic p, Traversable f + , forall t. Eq t => Eq (h t), forall t. Show t => Show (h t) ) + => Zipper p Maybe h -> String -> f () -> Spec +zippingMonadLaws zipper name shape = describe name $ do + let + obs :: Finite s => Zipporah p f Maybe s t -> [h t] + obs = observeZipper zipper shape + zb = generateZipper zipper shape arbitrary :: Gen (Zipporah p f Maybe Bool Bool) + kleisli = (\(k0, k1) b -> if b then k0 else k1) <$> ((,) <$> zb <*> zb) + prop "pure a >>= k = k a" $ forAllBlind kleisli $ \k a -> + obs (pure a >>= k) === obs (k a) + prop "m >>= pure = m" $ forAllBlind zb $ \m -> + obs (m >>= pure) === obs m + prop "(m >>= k) >>= h = m >>= (\\x -> k x >>= h)" $ + forAllBlind zb $ \m -> forAllBlind kleisli $ \k -> forAllBlind kleisli $ \h -> + obs ((m >>= k) >>= h) === obs (m >>= (\x -> k x >>= h)) + +-- | The laws of `Zipporah`s, of no, two & three sources. +zipporahLaws :: Spec +zipporahLaws = do + let + shapes :: (forall f. Traversable f => String -> f () -> Spec) -> Spec + shapes laws = do + laws "of no sources" Proxy + laws "of two sources" (Par1 () :*: Par1 ()) + laws "of three sources" (Par1 () :*: Par1 () :*: Par1 ()) + maybes = functionZipper liftArbitrary + lists = functionZipper (\gen -> choose (0, 2) >>= (`vectorOf` gen)) + describe "Zipporah (->) f Maybe" $ do + shapes (zippingLaws maybes) + shapes (zippingMonadLaws maybes) + describe "Zipporah (->) f []" $ shapes (zippingLaws lists) + describe "Zipporah (Star ((,) [Int])) f Maybe" $ do + shapes (zippingLaws writerZipper) + shapes (zippingMonadLaws writerZipper) + +homogeneousProperties :: Spec +homogeneousProperties = do + describe "Enumerator" $ do + let ix = genEnumerator arbitrary :: Gen (Enumerator Bool Int) + ixf = genEnumerator (applyFun <$> arbitrary) + :: Gen (Enumerator Bool (Int -> Int)) + prop "pure id <*> v = v" $ forAllBlind ix $ \v -> + enumerator (pure id <*> v) === enumerator v + prop "pure (.) <*> u <*> v <*> w = u <*> (v <*> w)" $ + forAllBlind ixf $ \u -> forAllBlind ixf $ \v -> forAllBlind ix $ \w -> + enumerator (pure (.) <*> u <*> v <*> w) === enumerator (u <*> (v <*> w)) + prop "u <*> pure y = pure ($ y) <*> u" $ forAllBlind ixf $ \u (y :: Int) -> + enumerator (u <*> pure y) === enumerator (pure ($ y) <*> u) + prop "zeroP >+< p = lunit p" $ forAllBlind ix $ \p -> + enumerator (zeroP >+< p) === enumerator (lunit p) + prop "p >+< zeroP = runit p" $ forAllBlind ix $ \p -> + enumerator (p >+< zeroP) === enumerator (runit p) + prop "p >+< q >+< r = assoc ((p >+< q) >+< r)" $ + forAllBlind ix $ \p -> forAllBlind ix $ \q -> forAllBlind ix $ \r -> + enumerator (p >+< q >+< r) + === enumerator (dimap unassocE assocE ((p >+< q) >+< r)) + prop "unleft = unright . dimap swapE swapE" $ + forAllBlind (genEnumerator arbitrary + :: Gen (Enumerator (Either Bool ()) (Either Int ()))) $ \p -> + enumerator (unleft p) === enumerator (unright (dimap swapE swapE p)) + prop "rmap (either id absurd) = unleft . lmap (either id absurd)" $ + forAllBlind (genEnumerator (Left <$> arbitrary) + :: Gen (Enumerator Bool (Either Int Void))) $ \p -> + enumerator (rmap (either id absurd) p) + === enumerator (unleft (lmap (either id absurd) p) :: Enumerator Bool Int) + zipporahLaws + describe "Comonocle & Diopter combinators" $ do + prop "countComonocle _BoundedEnum is the number of values" $ + countComonocle (_BoundedEnum @Int8) === 256 .&&. countComonocle (_BoundedEnum @Bool) === 2 + prop "fromComonocle _BoundedEnum inverts indexComonocle" $ \(e :: Int8) -> + preview (fromComonocle _BoundedEnum) + (fst (iview (indexComonocle _BoundedEnum) e), ()) === Just e + prop "succComonocle _BoundedEnum is succ, but at maxBound" $ \(e :: Int8) -> + withPartialIso (succComonocle _BoundedEnum) const e + === if e == maxBound then Nothing else Just (succ e) + prop "predComonocle _BoundedEnum is pred, but at minBound" $ \(e :: Int8) -> + withPartialIso (predComonocle _BoundedEnum) const e + === if e == minBound then Nothing else Just (pred e) + prop "enumerateComonocle _BoundedEnum is enumFrom" $ \(e :: Ordering) -> + enumerateComonocle _BoundedEnum e === [e ..] + prop "enumerateFromThenComonocle _BoundedEnum is enumFromThen" $ + \(e :: Int8) e' -> take 600 (enumerateFromThenComonocle _BoundedEnum e e') + === take 600 [e, e' ..] + prop "enumerateFromToComonocle _BoundedEnum is enumFromTo" $ + \(e :: Int8) e' -> enumerateFromToComonocle _BoundedEnum e e' === [e .. e'] + prop "enumerateFromThenToComonocle _BoundedEnum is enumFromThenTo" $ + \(e :: Int8) e' e'' -> + take 600 (enumerateFromThenToComonocle _BoundedEnum e e' e'') + === take 600 [e, e' .. e''] + prop "zipMonocle at Identity sources is traverseOf" $ \(c :: Complex Int) -> + let f x = if even x then Just x else Nothing + in zipMonocle ditraversed (f . runIdentity) (Identity c) + === traverseOf ditraversed f c + prop "zipMonocle at Identity effects is cotraverseOf" $ + \(cs :: [Complex Int]) -> + runIdentity (zipMonocle ditraversed (Identity . sum) cs) + === cotraverseOf ditraversed sum cs + prop "zipWithMonocle ditraversed zips componentwise" $ + \(x :+ y :: Complex Int) (x' :+ y') -> + zipWithMonocle ditraversed (-) (x :+ y) (x' :+ y') === (x - x') :+ (y - y') + prop "replicateMonocle ditraversed is replicateM 2" $ \(xs :: [Int]) -> + map (toListOf ditraversed) (replicateMonocle ditraversed xs :: [Complex Int]) + === sequenceA [xs, xs] + prop "withDitraversal splits into the foci, in order" $ + \(s :: (Int, Complex Int)) -> + withDitraversal (crossMonocle id ditraversed) + (\split _ -> toList (split s)) + === toListOf (crossMonocle id ditraversed) s + prop "ditraversal inverts withDitraversal" $ + \(s :: (Int, Complex Int)) (Fun _ f :: Fun Int Int) -> + withDitraversal (crossMonocle id ditraversed) + (\split merge -> over (ditraversal (Ditraversal split merge)) f s) + === over (crossMonocle id ditraversed) f s + prop "withDitraversal inverts ditraversal" $ + \(x :: Int) y (Fun _ f :: Fun Int Int) -> + let d = Ditraversal (uncurry (:+)) (\(u :+ v) -> (u, v)) + in withDitraversal (ditraversal d) + (\split merge -> (toList (split (x, y)), merge (f <$> split (x, y)))) + === ([x, y], (f x, f y)) + it "tabulateMonocle numbers foci left to right" $ + toListOf ditraversed (tabulateMonocle ditraversed id :: Complex Natural) + `shouldBe` [0, 1] + prop "copiesComonocle has a copy for each, exactly one matching" $ + \(e :: Int8) -> + length (copiesComonocle (_BoundedEnum @Int8)) === 256 + .&&. length + [ () | Prism copy <- copiesComonocle _BoundedEnum + , Just () <- [preview copy e] ] === 1 + prop "copiesComonocle are lawful prisms" $ \(s :: Either Int Int) a -> + conjoin + [ preview copy (review copy a) === Just a + .&&. maybe (property True) (\a' -> review copy a' === s) + (preview copy s) + | Prism copy <- copiesComonocle (altComonocle id id) ] + prop "fociMonocle has a focus for each, viewing toListOf" $ + \(s :: (Int, Complex Int)) -> + [view foc s | Lens foc <- fociMonocle (crossMonocle id ditraversed)] + === toListOf (crossMonocle id ditraversed) s + prop "fociMonocle are lawful lenses" $ \(s :: (Int, Complex Int)) a b -> + conjoin + [ view foc (set foc a s) === a + .&&. set foc (view foc s) s === s + .&&. set foc b (set foc a s) === set foc b s + | Lens foc <- fociMonocle (crossMonocle id ditraversed) ] + prop "clonePrismoid keeps both directions" $ + \(xs :: [Int]) (e :: Either Int Char) (m :: Maybe Int) (Fun _ k :: Fun Int Int) -> + let + roundTrip :: APrismoid s s Int Int -> s -> Maybe s + roundTrip o s = withPrismoid o $ \match build -> build . fmap k <$> match s + in + roundTrip (clonePrismoid (atLeast 1)) xs === roundTrip (atLeast 1) xs + .&&. roundTrip (clonePrismoid lefted) e === roundTrip lefted e + .&&. roundTrip (clonePrismoid _Just) m === roundTrip _Just m + .&&. roundTrip (clonePrismoid several) xs === roundTrip several xs + prop "a Prism, as a Prismoid, fails on a mismatch" $ \(m :: Maybe Int) -> + withPrismoid (_Just :: APrismoid (Maybe Int) (Maybe Int) Int Int) + (\match _ -> toList <$> match m) + === fmap pure m + prop "withDiffraction is over a Grate" $ + \(z :: Complex Int) (Fun _ f :: Fun Int Int) -> + withDiffraction cotraversed (\split merge -> merge (fmap f (split z))) + === over cotraversed f z + prop "diffraction inverts withDiffraction" $ + \(z :: Complex Int) (Fun _ f :: Fun Int Int) -> + withDiffraction cotraversed + (\split merge -> over (diffraction (Diffraction split merge)) f z) + === over cotraversed f z + prop "withPrismocular agrees with withPrismoid" $ + \(xs :: [Int]) (e :: Either Int Char) (m :: Maybe Int) (Fun _ f :: Fun Int Int) -> + let + probing :: APrismoid s s Int Int -> s -> Maybe s + probing o s = withPrismocular o (\probe -> f <$> probe s) + shaping :: APrismoid s s Int Int -> s -> Maybe s + shaping o s = withPrismoid o $ \match build -> build . fmap f <$> match s + in + probing (atLeast 1) xs === shaping (atLeast 1) xs + .&&. probing lefted e === shaping lefted e + .&&. probing _Just m === shaping _Just m + .&&. probing several xs === shaping several xs + prop "prismocular inverts withPrismocular, without repetition" $ + \(e :: Either Int Char) (Fun _ f :: Fun Int Int) -> + let l = lefted :: APrismoid (Either Int Char) (Either Int Char) Int Int + in withPrismoid (prismocular (clonePrismoid l >?* Prismocular ($ Just))) + (\match build -> build . fmap f <$> match e) + === withPrismoid l (\match build -> build . fmap f <$> match e) + prop "withSpectacle agrees with withBifocal" $ + \(xs :: [Int]) (e :: Either Int Char) (m :: Maybe Int) (Fun _ f :: Fun Int Int) -> + let + probing :: ABifocal s s Int Int -> s -> Maybe s + probing o s = withBifocal o (\probe -> maybe Nothing (Just . f) (probe s)) + shaping :: ABifocal s s Int Int -> s -> Maybe s + shaping o s = withSpectacle o $ \match build -> match s >>= build . fmap f + in + probing lefted e === shaping lefted e + .&&. probing (clonePartialIso _Just) m === shaping (clonePartialIso _Just) m + .&&. probing (satisfied even) (length xs) === shaping (satisfied even) (length xs) + .&&. probing (atLeast 1) xs === shaping (atLeast 1) xs + .&&. probing several xs === shaping several xs + prop "cloneBifocal (atLeast 1) matches one or more" $ \(xs :: [Int]) -> + withSpectacle (cloneBifocal (atLeast 1)) (\match _ -> toList <$> match xs) + === if null xs then Nothing else Just xs + prop "spectacle inverts withSpectacle" $ + \(m :: Maybe Int) (Fun _ f :: Fun Int Int) -> + withSpectacle (clonePartialIso _Just) + (\match build -> withSpectacle (spectacle (Spectacle match build)) + (\match' build' -> match' m >>= build' . fmap f)) + === withSpectacle (clonePartialIso _Just) (\match build -> match m >>= build . fmap f) + prop "atLeast 1 matches one or more" $ \(xs :: [Int]) -> + withPrismoid (atLeast 1) (\match _ -> toList <$> match xs) + === if null xs then Nothing else Just xs + prop "zipDiopter homogenized is zipHomogeneous" $ \(xss :: [[Int]]) -> + zipDiopter homogenized (Just . sum) ([1, 2] : xss) + === zipHomogeneous (Just . sum) ([1, 2 :: Int] : xss) + prop "zipWithDiopter several is zipWithHomogeneous" $ \(xs :: [Int]) ys -> + zipWithDiopter several (+) xs ys === zipWithHomogeneous (+) xs ys + describe "Enumerable & Homogeneous" $ do + let tagged = map (fst :: (Int8, Char) -> Int8) + prop "enumerateFromThen is enumFromThen" $ \(e :: Int8) e' c -> + take 600 (tagged (enumerateFromThen (e, c) (e', ()))) + === take 600 [e, e' ..] + prop "enumerateFromTo is enumFromTo" $ \(e :: Int8) e' c -> + tagged (enumerateFromTo (e, c) (e', ())) === [e .. e'] + prop "enumerateFromThenTo is enumFromThenTo" $ \(e :: Int8) e' e'' c -> + take 600 (tagged (enumerateFromThenTo (e, c) (e', ()) (e'', ()))) + === take 600 [e, e' .. e''] + prop "enumerate holds the first focus" $ \(e :: Int8) e' (c :: Char) -> + all ((== c) . snd) + (take 600 (enumerateFromThenTo (e, c) (e', ()) (maxBound, ()))) + it "numbers copies left to right" $ + map (fst . review fromEnumerable) [(LT, ()), (EQ, ()), (GT, ())] + `shouldBe` [0, 1, 2] + prop "fromEnumerable is a prism, inverting its review" $ \(c :: Char) -> + map (\i -> preview fromEnumerable (i, c)) [0 .. 3] + === map Just [(LT, c), (EQ, c), (GT, c)] <> [Nothing :: Maybe (Ordering, Char)] + .&&. fmap (review fromEnumerable) + (preview fromEnumerable (2, c) :: Maybe (Ordering, Char)) + === Just (2, c) + prop "fromEnumerable is fromEnum, from minBound" $ \(e :: Int8) (c :: Char) -> + review fromEnumerable (e, c) + === (fromIntegral (fromEnum e - fromEnum (minBound :: Int8)), c) + prop "succEnumerable is succ, but at maxBound" $ \(e :: Ordering) (c :: Char) -> + withPartialIso succEnumerable const (e, c) + === if e == maxBound then Nothing else Just (succ e, c) + prop "predEnumerable is pred, but at minBound" $ \(e :: Int8) (c :: Char) -> + withPartialIso predEnumerable const (e, c) + === if e == minBound then Nothing else Just (pred e, c) + prop "enumerateFrom is enumFrom" $ \(e :: Ordering) (c :: Char) -> + enumerateFrom (e, c) === [(e', c) | e' <- [e ..]] + prop "zipWithHomogeneous zips lists of the same length" $ + \(Fun _ f) (xs :: [Int]) (ys :: [Int]) -> + zipWithHomogeneous (curry f) xs ys === if length xs == length ys + then Just (zipWith (curry f) xs ys :: [Int]) + else Nothing + prop "zipWithHomogeneous3 is zipWith3, of the same lengths" $ + \(Fun _ f) (xs :: [Int]) (ys :: [Int]) (zs :: [Int]) -> + zipWithHomogeneous3 (\x y z -> f (x, y, z) :: Int) xs ys zs + === if length xs == length ys && length ys == length zs + then Just (zipWith3 (\x y z -> f (x, y, z)) xs ys zs) + else Nothing + it "zips no sources of a sum as its first copy" $ + zipHomogeneous (\Proxy -> Just 'a') (Proxy :: Proxy (Maybe Char)) + `shouldBe` Just (Just 'a') + prop "transposeHomogeneous is transpose, of the same lengths" $ + \(xs :: [Int]) (xss :: [[Int]]) -> + transposeHomogeneous (xs : xss) + === if all ((== length xs) . length) xss + then Just (transpose (xs : xss)) + else Nothing + prop "zipWithHomogeneousM acts on the positions which match" $ + \(xs :: [Int]) (ys :: [Int]) -> + zipWithHomogeneousM (\x y -> ([x], x + y)) xs ys + === ( take (min (length xs) (length ys)) xs + , if length xs == length ys then Just (zipWith (+) xs ys) else Nothing ) diff --git a/distributors-core/test/Properties/Nested.hs b/distributors-core/test/Properties/Nested.hs new file mode 100644 index 00000000..0a85e182 --- /dev/null +++ b/distributors-core/test/Properties/Nested.hs @@ -0,0 +1,57 @@ +{-# LANGUAGE ExplicitNamespaces, RequiredTypeArguments #-} +module Properties.Nested (nestedProperties) where + +import Control.Lens (preview, review, view) +import Control.Lens.Prism.Nested +import GHC.Generics (Generic) +import Test.Hspec +import Test.Hspec.QuickCheck (prop) +import Test.QuickCheck + +data Shape + = Dot + | Circle Int + | Rect Int Bool + | Box Int Bool Char + | Quad Int Bool Char Int + deriving stock (Eq, Show, Generic) +makeNestedPrisms ''Shape + +data Pt = Pt Int Bool Char + deriving stock (Eq, Show, Generic) +makeNestedPrisms ''Pt + +instance Arbitrary Shape where + arbitrary = oneof + [ pure Dot + , Circle <$> arbitrary + , Rect <$> arbitrary <*> arbitrary + , Box <$> arbitrary <*> arbitrary <*> arbitrary + , Quad <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary + ] + +instance Arbitrary Pt where + arbitrary = Pt <$> arbitrary <*> arbitrary <*> arbitrary + +nestedProperties :: Spec +nestedProperties = do + describe "genericNestedPrism, as makeNestedPrisms's prisms" $ do + prop "previews as they do" $ \(s :: Shape) -> + preview (genericNestedPrism Shape "Dot") s === preview _Dot s + .&&. preview (genericNestedPrism Shape "Circle") s === preview _Circle s + .&&. preview (genericNestedPrism Shape "Rect") s === preview _Rect s + .&&. preview (genericNestedPrism Shape "Box") s === preview _Box s + .&&. preview (genericNestedPrism Shape "Quad") s === preview _Quad s + prop "reviews as they do" $ \n b c m -> + review (genericNestedPrism Shape "Dot") () === review _Dot () + .&&. review (genericNestedPrism Shape "Circle") n === review _Circle n + .&&. review (genericNestedPrism Shape "Rect") (n, b) === review _Rect (n, b) + .&&. review (genericNestedPrism Shape "Box") (n, (b, c)) + === review _Box (n, (b, c)) + .&&. review (genericNestedPrism Shape "Quad") (n, (b, (c, m))) + === review _Quad (n, (b, (c, m))) + describe "genericNestedIso, as makeNestedPrisms's iso" $ do + prop "views as it does" $ \(p :: Pt) -> + view (genericNestedIso (type Pt)) p === view _Pt p + prop "reviews as it does" $ \(n :: Int) b c -> + review (genericNestedIso (type Pt)) (n, (b, c)) === review _Pt (n, (b, c)) diff --git a/distributors-core/test/Properties/Parsing.hs b/distributors-core/test/Properties/Parsing.hs new file mode 100644 index 00000000..0fe8ab21 --- /dev/null +++ b/distributors-core/test/Properties/Parsing.hs @@ -0,0 +1,132 @@ +module Properties.Parsing (parsingProperties) where + +import Control.Lens.Diopter (several, skippedOptional) +import Control.Lens.Monocle (ditraversed) +import Control.Lens.Prismoid +import Control.Monad.Trans.State (StateT (..)) +import Data.Bifunctor.Joker (Joker (..)) +import Data.Char (isDigit) +import Data.Functor.Identity (Identity (..)) +import Data.Functor.Product (Product (..)) +import Data.List (intercalate) +import Control.Lens (Prism', prism') +import Data.Profunctor (rmap) +import Data.Profunctor.Distributor (Alternator (..)) +import Data.Profunctor.Monoidal ((>*), (*<), replicateP) +import Test.Hspec +import Test.Hspec.QuickCheck (prop) +import Test.QuickCheck +import Text.ParserCombinators.ReadP (ReadP, char, readP_to_S, satisfy) + +parsingProperties :: Spec +parsingProperties = do + describe "sepBy" $ do + prop "sepBy sep several parses exactly the separated digits" $ + \(Digits ds) -> parses (rmap Identity (inBrackets (sepBy comma several plainDigit))) (bracketed ds) + === [ds] + prop "sepBy sep (atLeast 1) parses exactly some separated digits" $ + \(Digits ds) -> parses (rmap Identity (inBrackets (sepBy comma (atLeast 1) plainDigit))) (bracketed ds) + === [ds | not (null ds)] + prop "sepBy sep (exactly n) parses exactly n separated digits" $ + \(Digits ds) (Small k) -> let n = length ds in + parses (rmap Identity (inBrackets (sepBy comma (exactly n) plainDigit) :: Joker ReadP String String)) (bracketed ds) + === [ds] + .&&. parses (rmap Identity (inBrackets (sepBy comma (exactly (n + 1 + abs k)) plainDigit) :: Joker ReadP String String)) (bracketed ds) + === [] + prop "sepBy sep (chain1 assoc pat) associates, left or right" $ + \(Digits ds) -> let str = bracketed ds; leaves = map Leaf ds in + parses (rmap Identity (inBrackets (sepBy comma (chain1 Left _Node) plainLeaf))) str + === [foldl1 Node leaves | not (null ds)] + .&&. parses (rmap Identity (inBrackets (sepBy comma (chain1 Right _Node) plainLeaf))) str + === [foldr1 Node leaves | not (null ds)] + prop "sepBy sequences greedily, deterministically" $ + \(Digits ds) -> let str = intercalate "," (map pure ds) in + greedy (sepBy greedyComma several greedyDigit) str + === Just (ds, "") + .&&. greedy (sepBy greedyComma (atLeast 1) greedyDigit) str + === (if null ds then Nothing else Just (ds, "")) + prop "manyTillP p q parses some p, then q" $ + \(Digits ds) -> + parses (rmap Identity (manyTillP plainDigit (Joker ("!" <$ char '!')))) (ds ++ "!") + === [ds ++ "!"] + prop "manyTillP tries the rest first, deterministically" $ + \(Digits ds) -> + greedy (manyTillP greedyDigit (Joker (pure []))) ds === Just ("", ds) + it "sepBy sep ditraversed separates a fixed product's foci" $ do + let pair = sepBy comma ditraversed plainDigit + :: Joker ReadP (Product Identity Identity Char) (Product Identity Identity Char) + full str = [x | (x, "") <- readP_to_S (runJoker pair) str] + full "1,2" `shouldBe` [Pair (Identity '1') (Identity '2')] + full "12" `shouldBe` [] + prop "atLeast n parses exactly the digit strings of at least n" $ + \(Digits ds) (Small k) -> let n = abs k `mod` 6 in + parses (rmap Identity (atLeast n >?* plainDigit)) ds + === [ds | length ds >= n] + prop "atMost n parses exactly the digit strings of at most n" $ + \(Digits ds) (Small k) -> let n = abs k `mod` 6 in + parses (rmap Identity (atMost n >?* plainDigit)) ds + === [ds | length ds <= n] + prop "exactly n >?* p = replicateP n p" $ + \(Digits ds) (Small k) -> let n = abs k `mod` 6 in + parses (rmap Identity (exactly n >?* plainDigit)) ds + === parses (rmap Identity (replicateP n plainDigit :: Joker ReadP String String)) ds + prop "inRange lo hi parses exactly the digit strings of lo to hi" $ + \(Digits ds) (Small a) (Small b) -> let lo = abs a `mod` 6; hi = abs b `mod` 6 in + parses (rmap Identity (inRange lo (Just hi) >?* plainDigit)) ds + === [ds | lo <= length ds, length ds <= hi] + prop "sepBy sep (atLeast n) & (atMost n) bound separated digits" $ + \(Digits ds) (Small k) -> let n = abs k `mod` 6; str = bracketed ds in + parses (rmap Identity (inBrackets (sepBy comma (atLeast n) plainDigit))) str + === [ds | length ds >= n] + .&&. parses (rmap Identity (inBrackets (sepBy comma (atMost n) plainDigit))) str + === [ds | length ds <= n] + prop "skippedOptional skips a trailing separator, or none" $ + \(Digits ds) -> let + trailing = rmap Identity ((several >?* plainDigit) *< (skippedOptional >?* comma)) + in parses trailing ds === [ds] .&&. parses trailing (ds ++ ",") === [ds] + prop "sepBy is ambiguous only where its Prismoid is" $ + \(Digits ds0) -> let ds = take 8 ds0 in + length (parses (rmap Identity (sepBy comma (atLeast 1 . atLeast 1) plainDigit)) (intercalate "," (map pure ds))) + === length (parses ((atLeast 1 . atLeast 1) digit) ds) + +newtype Digits = Digits String deriving Show +instance Arbitrary Digits where + arbitrary = Digits <$> listOf (elements ['0' .. '9']) + +bracketed :: String -> String +bracketed ds = "[" ++ intercalate "," (map pure ds) ++ "]" + +inBrackets :: Joker ReadP a b -> Joker ReadP a b +inBrackets p = Joker (() <$ char '[') >* p *< Joker (() <$ char ']') + +comma :: Joker ReadP () () +comma = Joker (() <$ char ',') + +digit :: Joker ReadP Char (Identity Char) +digit = rmap Identity plainDigit + +plainDigit :: Joker ReadP Char Char +plainDigit = Joker (satisfy isDigit) + +data Tree = Leaf Char | Node Tree Tree deriving (Eq, Show) + +_Node :: Prism' Tree (Tree, Tree) +_Node = prism' (uncurry Node) (\case Node x y -> Just (x, y); _ -> Nothing) + +plainLeaf :: Joker ReadP Tree Tree +plainLeaf = Joker (Leaf <$> satisfy isDigit) + +-- | A deterministic parser, committing to its first success. +type Greedy = Joker (StateT String Maybe) + +greedyDigit :: Greedy Char Char +greedyDigit = Joker (StateT (\case c : cs | isDigit c -> Just (c, cs); _ -> Nothing)) + +greedyComma :: Greedy () () +greedyComma = Joker (StateT (\case ',' : cs -> Just ((), cs); _ -> Nothing)) + +greedy :: Greedy s t -> String -> Maybe (t, String) +greedy = runStateT . runJoker + +parses :: Joker ReadP s (Identity t) -> String -> [t] +parses p str = [x | (Identity x, "") <- readP_to_S (runJoker p) str] diff --git a/distributors-core/test/Properties/PartialIso.hs b/distributors-core/test/Properties/PartialIso.hs new file mode 100644 index 00000000..3860f1e4 --- /dev/null +++ b/distributors-core/test/Properties/PartialIso.hs @@ -0,0 +1,213 @@ +module Properties.PartialIso (partialIsoProperties) where + +import Control.Lens (over, preview, review, traverseOf, view) +import Control.Lens.PartialIso +import Data.Profunctor (Cochoice (..), Forget (..)) +import Data.Profunctor.Filtrator (Filtrator (..)) +import Data.Monoid.Disjunctive +import Test.Hspec +import Witherable (catMaybes) +import Test.Hspec.QuickCheck (prop) +import Test.QuickCheck + +partialIsoProperties :: Spec +partialIsoProperties = do + checkPartialIso "partialIso" halve + checkTraverse "partialIso" halve + checkPartialIso "partialIso, composed" (halve . halve) + checkTraverse "partialIso, composed" (halve . halve) + checkPartialIso "satisfied" (satisfied (even :: Int -> Bool)) + checkTraverse "satisfied" (satisfied (even :: Int -> Bool)) + checkPartialIso "nulled" (nulled :: PartialIso' [Int] ()) + checkTraverse "nulled" (nulled :: PartialIso' [Int] ()) + checkPartialIso "notNulled" (notNulled :: PartialIso' [Int] [Int]) + checkTraverse "notNulled" (notNulled :: PartialIso' [Int] [Int]) + checkPartialIso "filterPrism" (filterPrism _Just :: PartialIso' Int (Maybe Int)) + checkTraverse "filterPrism" (filterPrism _Just :: PartialIso' Int (Maybe Int)) + describe "filterPrism" $ do + prop "reverses a Prism, forwards by view as it reviews" $ \(x :: Int) -> + view (filterPrism _Just) x === review _Just x + prop "reverses a Prism, backwards by preview as it previews" $ + \(m :: Maybe Int) -> + preview (coPartialIso (filterPrism _Just)) m === preview _Just m + checkPartialIso "a Prism" (_Just :: PartialIso' (Maybe Int) Int) + describe "a Prism" $ + prop "traverseOf passes a mismatch through, as its clone does, unlike its partial functions" $ + \(Fun _ f :: Fun Int (Maybe Int)) -> within second $ + traverseOf _Just f Nothing === Just Nothing + .&&. traverseOf (clonePartialIso _Just) f Nothing === Just Nothing + .&&. traverseOf (withPartialIso _Just partialIso) f Nothing === Nothing + describe "PartialMarket, isomorphic to PartialIso" $ do + prop "partialMarket . withPartialMarket keeps a Prism's passing through" $ + \(Fun _ f :: Fun Int (Maybe Int)) (m :: Maybe Int) -> within second $ + traverseOf (remarket _Just) f m + === traverseOf _Just f m + prop "partialMarket . withPartialMarket keeps a PartialIso" $ + \(Fun _ f :: Fun Int (Maybe Int)) (n :: Int) -> within second $ + traverseOf (remarket halve) f n + === traverseOf halve f n + prop "withPartialMarket . partialMarket is the identity" $ + \(n :: Int) (b :: Int) -> within second $ + let build x = if x > 0 then Just (x * 2) else Nothing + match x + | even x = Right (x `div` 2) + | x > 0 = Left (Just x) + | otherwise = Left Nothing + in withPartialMarket (partialMarket build match) (\build' match' -> (build' b, match' n)) + === (build b, match n) + prop "is a filterPrism after a Prism" $ + \(Fun _ f :: Fun Int (Maybe Int)) (n :: Int) -> within second $ + let build x = if x > 0 then Just (x * 2) else Nothing + match x + | even x = Right (x `div` 2) + | x > 0 = Left (Just x) + | otherwise = Left Nothing + in traverseOf (partialMarket build match) f n + === traverseOf (filterPrism _Just . prism build (maybe (Left Nothing) match)) f n + prop "forgetting passing through gives its partial functions" $ + \(m :: Maybe Int) (b :: Int) -> within second $ + withPartialMarket _Just (\build match -> (either (const Nothing) Just (match m), build b)) + === withPartialIso _Just (\match' build' -> (match' m, build' b)) + describe "combinators keep passing through" $ do + prop "withoutPartialIso of Prisms is their sum" $ + \(Fun _ f :: Fun Int (Maybe Int)) (e :: Either (Maybe Int) (Maybe Int)) -> within second $ + traverseOf (withoutPartialIso _Just _Just) (either (fmap Left . f) (fmap Right . f)) e + === either (fmap Left . traverseOf _Just f) (fmap Right . traverseOf _Just f) e + prop "alongsidePartialIso of Prisms passes through where both do" $ + \(Fun _ f :: Fun (Int, Int) (Maybe (Int, Int))) (m :: Maybe Int) (n :: Maybe Int) -> within second $ + traverseOf (alongsidePartialIso _Just _Just) f (m, n) + === case (m, n) of + (Just x, Just y) -> f (x, y) >>= \(x', y') -> Just (Just x', Just y') + (Nothing, Nothing) -> Just (Nothing, Nothing) + _ -> Nothing + prop "orPartialIso is the union of patterns" $ + \(n :: Int) -> within second $ + traverseOf (orPartialIso (satisfied even) (satisfied odd)) Just n === Just n + prop "falsePartialIso is orPartialIso's identity" $ + \(Fun _ f :: Fun Int (Maybe Int)) (m :: Maybe Int) -> within second $ + traverseOf (orPartialIso falsePartialIso _Just) f m === traverseOf _Just f m + .&&. traverseOf (orPartialIso _Just falsePartialIso) f m === traverseOf _Just f m + prop "coPartialIso twice rebuilds from partial functions" $ + \(Fun _ f :: Fun Int (Maybe Int)) (m :: Maybe Int) -> within second $ + traverseOf (coPartialIso (coPartialIso _Just)) f m + === traverseOf (withPartialIso _Just partialIso) f m + describe "a PartialIso is a Prism with a Maybe target" $ do + prop "withPrism . withPartialMarket keeps a PartialIso" $ + \(Fun _ f :: Fun Int (Maybe Int)) (n :: Int) (m :: Maybe Int) -> within second $ + let viaPrism :: APartialIso s t Int Int -> PartialIso s t Int Int + viaPrism pattern = withPrism (withPartialMarket pattern prism) partialMarket + in traverseOf (viaPrism halve) f n === traverseOf halve f n + .&&. traverseOf (viaPrism _Just) f m === traverseOf _Just f m + prop "withPartialMarket . withPrism keeps a Prism" $ + \(Fun _ f :: Fun Int Int) (n :: Int) -> within second $ + let prsm :: Prism Int (Maybe Int) Int Int + prsm = withPartialMarket halve prism + in over (withPartialMarket (withPrism prsm partialMarket) prism) f n === over prsm f n + describe ">?< passes through as >? does" $ do + prop "prsm >?< p = prsm >? p, at (->)" $ + \(Fun _ f :: Fun Int Int) (m :: Maybe Int) (e :: Either Int Char) -> within second $ + (_Just >?< f) m === (_Just >? f) m + .&&. (_Left >?< f) e === (_Left >? f) e + prop "withPrism prsm partialMarket >?< p = catMaybes (prsm >? p), at PartialMarket" $ + \(m0 :: Market') (b :: Int) (n :: Int) (m :: Maybe Int) -> within second $ + let halves :: Prism Int (Maybe Int) Int Int + halves = withPartialMarket halve prism + justs :: Prism (Maybe Int) (Maybe (Maybe Int)) Int Int + justs = withPartialMarket _Just prism + in observe (withPrism halves partialMarket >?< market m0) b n + === observe (catMaybes (halves >? market m0)) b n + .&&. observe (withPrism justs partialMarket >?< market m0) b m + === observe (catMaybes (justs >? market m0)) b m + prop "partialIso match build >?< p = dimapMaybe match build p, at Forget" $ + \(n :: Int) -> within second $ + let match, build :: Int -> Maybe Int + match k = if even k then Just (k `div` 2) else Nothing + build k = Just (k * 2) + in runForget (partialIso match build >?< Forget (: [])) n + === runForget (dimapMaybe match build (Forget (: []))) n + describe "PartialMarket's instances are lawful" $ do + prop "unleft . left' = id" $ + \(Fun _ build :: Fun Int (Maybe Int)) (Fun _ match :: Fun Int (Either (Maybe Int) Int)) x y -> + observe (unleft (left' (PartialMarket build match :: PartialMarket Int Int Int Int))) x y + === observe (PartialMarket build match) x y + prop "unright . right' = id" $ + \(Fun _ build :: Fun Int (Maybe Int)) (Fun _ match :: Fun Int (Either (Maybe Int) Int)) x y -> + observe (unright (right' (PartialMarket build match :: PartialMarket Int Int Int Int))) x y + === observe (PartialMarket build match) x y + prop "fst . filtrate = unleft, snd . filtrate = unright" $ + \(Fun _ build :: Fun Int (Maybe (Either Int Int))) (Fun _ match :: Fun (Either Int Int) (Either (Maybe (Either Int Int)) Int)) x y -> + let sums = PartialMarket build match :: PartialMarket Int Int (Either Int Int) (Either Int Int) + in observe (fst (filtrate sums)) x y === observe (unleft sums) x y + .&&. observe (snd (filtrate sums)) x y === observe (unright sums) x y + prop ">|< is associative" $ + \(m0 :: Market') m1 m2 x y -> + observe (market m0 >|< (market m1 >|< market m2)) x y + === observe ((market m0 >|< market m1) >|< market m2) x y + prop "falseP is its identity" $ + \(m0 :: Market') x y -> + observe (falseP >|< market m0) x y === observe (market m0) x y + .&&. observe (market m0 >|< falseP) x y === observe (market m0) x y + describe "satisfied, a homomorphism of predicates" $ do + prop "from >|< to >|< of partial functions" $ + \(Fun _ p :: Fun Int Bool) (Fun _ q) x y -> + exchanged (satisfied (p >|< q)) x y + === exchanging + ( withPartialIso (satisfied p) (,) + >|< withPartialIso (satisfied q) (,) ) x y + prop "from falseP to falseP" $ \x y -> + exchanged (satisfied (falseP :: Int -> Bool)) x y + === exchanging falseP x y + prop "from >&< to composition" $ + \(Fun _ p :: Fun Int Bool) (Fun _ q) x y -> + exchanged (satisfied (p >&< q)) x y + === exchanged (satisfied p . satisfied q) x y + where + remarket :: APartialIso s t a b -> PartialIso s t a b + remarket pattern = withPartialMarket pattern partialMarket + exchanged :: APartialIso s t a b -> s -> b -> (Maybe a, Maybe t) + exchanged pattern = exchanging (withPartialIso pattern (,)) + exchanging :: (s -> Maybe a, b -> Maybe t) -> s -> b -> (Maybe a, Maybe t) + exchanging (match, build) s b = (match s, build b) + +type Market' = (Fun Int (Maybe Int), Fun Int (Either (Maybe Int) Int)) + +market :: Market' -> PartialMarket Int Int Int Int +market (Fun _ build, Fun _ match) = PartialMarket build match + +observe :: PartialMarket a b s t -> b -> s -> (Maybe t, Either (Maybe t) a) +observe (PartialMarket build match) b s = (build b, match s) + +halve :: PartialIso' Int Int +halve = partialIso + (\n -> if even n then Just (n `div` 2) else Nothing) + (Just . (* 2)) + +{- | The combinators which run a `PartialIso` +agree with the partial functions which characterize it, +& terminate, failing or not. +-} +checkPartialIso + :: (Arbitrary s, Show s, Eq s, Arbitrary a, Show a, Eq a) + => String -> PartialIso' s a -> Spec +checkPartialIso name pattern = describe name $ do + prop "preview matches forwards" $ \s -> within second $ + preview pattern s === withPartialIso pattern const s + prop "preview of coPartialIso builds backwards" $ \a -> within second $ + preview (coPartialIso pattern) a === withPartialIso pattern (const id) a + prop "clonePartialIso keeps both directions" $ \s a -> within second $ + withPartialIso (clonePartialIso pattern) (\match build -> (match s, build a)) + === withPartialIso pattern (\match build -> (match s, build a)) + +{- | A `PartialIso` which fails by `Filterable`, like those `partialIso` +builds, traverses by matching, then building, failing if either does. +-} +checkTraverse + :: (Arbitrary s, Show s, Eq s) + => String -> PartialIso' s a -> Spec +checkTraverse name pattern = describe name $ + prop "traverseOf with Just matches, then builds" $ \s -> within second $ + traverseOf pattern Just s + === withPartialIso pattern (\match build -> build =<< match s) + +second :: Int +second = 1000000 diff --git a/distributors-grammar/CHANGELOG.md b/distributors-grammar/CHANGELOG.md new file mode 100644 index 00000000..77257c43 --- /dev/null +++ b/distributors-grammar/CHANGELOG.md @@ -0,0 +1,42 @@ +# Changelog for `distributors-grammar` + +## Unreleased + +- 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 + are a class of over a million tokens, is hundreds of times faster. +- `Control.Lens.Grammar` re-exports `Control.Lens.Bifocal`, for `>?<*`, + which applies `Bifocal`s in `CtxGrammar`s, as they're `Filtrator`s. +- `Parsor`'s `manyP` & `optionalP` parse & print their elements in turn, + rather than by `Distributor`'s defaults, through isomorphisms & sums: + parsing repetitions is ~40% faster, & the test examples 10-50%. +- `unparseG` & `unparsecG` document that printing `snoc`s, so a `String` + prints quadratically, & a `Data.Sequence.Seq` linearly. +- Benchmarks, `bench:core`, of `distributors`' combinators & the test + examples, at parsing, printing & `Parsector`. +- The grammars of `distributors` 0.6, split into their own package: + `Control.Lens.Grammar` & its `BackusNaur`, `Machine`, `RegEx`, `Symbol` + & `Token` modules, `Control.Monad.Fail.Try`, `Data.Profunctor.Grammar` + & `Data.Profunctor.Grammar.Parsector`. +- `Control.Lens.Grammar` re-exports `Control.Lens.Prismoid` & + `Control.Lens.Diopter`, so grammars separate by `sepBy`, of + `several`, `atLeast`, `chain1` & `exactly`, & `Control.Lens.Grammar.Symbol` + exports `sepWith`, `sepBy` of a `terminal` separator, delimiters + composing around a separated grammar by `>*` & `*<`. +- `Printor s` & `Parsor s` are `MonadicTrans`, so `Varifocal`s run on + them, as the heredoc example grammar does; `Control.Lens.Grammar` + re-exports `Control.Lens.Varifocal` & + `Data.Profunctor.Monadic`. +- `Grammor` defines `manyTillP` as @starK p <> q@, without recursing, so + `sepBy` grammars, even of shapes without foci, have finite + regular expressions & `Bnf`s. +- `RegExam`, the type, is renamed `TokenExam`, & moves with `TokenClass`, + `TokenAlgebra` & `CategoryTest` to `Control.Lens.Grammar.Token`; + `RegEx`'s `RegExam` constructor keeps its name. `foldTokenClass` folds a + `TokenClass` by an algebra of its `TokenExam`s. +- `RegEx`'s `Sequence` & `TokenExam`'s `Alternate` take two or more items, + as two & a list, normalized, + so that `RegEx`'s `Monoid` & `DisjunctiveMonoid`, & `TokenClass`'s + `DisjunctiveMonoid`, are associative up to `==`, as tested; regular + expressions print with fewer parentheses. diff --git a/distributors-grammar/LICENSE b/distributors-grammar/LICENSE new file mode 100644 index 00000000..c969d4b7 --- /dev/null +++ b/distributors-grammar/LICENSE @@ -0,0 +1,30 @@ +Copyright Eitan Chatav (c) 2026 + +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + + * Neither the name of Eitan Chatav nor the names of other + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/distributors-grammar/README.md b/distributors-grammar/README.md new file mode 100644 index 00000000..82fda1a5 --- /dev/null +++ b/distributors-grammar/README.md @@ -0,0 +1,10 @@ +# distributors-grammar +## Unifying Parsers, Printers & Grammars + +[Github](https://github.com/morphismtech/distributors) + +Grammars by the profunctor algebra of +[distributors](https://hackage.haskell.org/package/distributors): +one grammar parses, prints, generates & describes its language, +as a regular expression or a Backus-Naur form. +Start at "Control.Lens.Grammar". diff --git a/distributors-grammar/Setup.hs b/distributors-grammar/Setup.hs new file mode 100644 index 00000000..9a994af6 --- /dev/null +++ b/distributors-grammar/Setup.hs @@ -0,0 +1,2 @@ +import Distribution.Simple +main = defaultMain diff --git a/distributors-grammar/bench/Main.hs b/distributors-grammar/bench/Main.hs new file mode 100644 index 00000000..dd3cc2f2 --- /dev/null +++ b/distributors-grammar/bench/Main.hs @@ -0,0 +1,186 @@ +{- | Benchmarks of @distributors@' core combinators, at the grammar +backends which run them: parsing by @Parsor@ & @Parsector@, printing +by @Printor@ & @Parsector@, & building static @Grammor@s. + +Every benchmark checks its result against an expected value, which +forces it fully; a backend which doesn't round-trip a workload in +setup is skipped, & reported. +-} +module Main (main) where + +import Control.Lens +import Control.Lens.Grammar +import Control.Lens.Comonocle (_BoundedEnum, indexComonocle) +import Control.Monad (unless) +import Data.List (intercalate) +import Test.Tasty.Bench + +import Examples.Arithmetic +import Examples.Expression +import Examples.Heredoc +import Examples.Json +import Examples.Lambda +import Examples.SemVer +import Examples.SExpr + +main :: IO () +main = do + groups <- sequence + [ backends "repeat" repeats + , backends "separate" separates + , backends "varifocal" varifocals + , backends "example" examples + , pure statics + , pure optics + ] + 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 + +-- | Benchmark each workload at each backend which round-trips it. +backends :: String -> [Workload] -> IO Benchmark +backends name workloads = bgroup name . concat <$> traverse workload workloads + where + workload (Workload wname g str a) = + fmap catMaybes . traverse keep $ cases wname g str a + keep (backend, ok, b) = do + unless ok $ putStrLn ("skipped: " <> name <> "/" <> backend) + pure (if ok then Just b else Nothing) + +cases + :: forall a. Eq a + => String -> CtxGrammar Char a -> String -> a + -> [(String, Bool, Benchmark)] +cases wname g str a = + [ ( wname <> "/parse" + , fmap fst (parser str) == Just a + , bench (wname <> "/parse") $ + whnf (\s -> fmap fst (parser s) == Just a) str ) + , ( wname <> "/print" + , fmap ($ "") (printer a) == Just str + , bench (wname <> "/print") $ + whnf (\x -> fmap (\pr -> length (pr "")) (printer x)) a ) + , ( wname <> "/parsec" + , parsecResult (parsector str) == Just a + , bench (wname <> "/parsec") $ + whnf (\s -> parsecResult (parsector s) == Just a) str ) + , ( wname <> "/unparsec" + , parsecStream (unparsector a "") == str + , bench (wname <> "/unparsec") $ + whnf (\x -> length (parsecStream (unparsector x ""))) a ) + ] + where + parser :: String -> Maybe (a, String) + parser = parseG g + printer :: a -> Maybe (String -> String) + printer = printG g + parsector :: String -> ParsecState String a + parsector = parsecG g + unparsector :: a -> String -> ParsecState String a + unparsector = unparsecG g + +digitG :: RegGrammar Char Char +digitG = asIn @Char DecimalNumber + +commaG :: RegGrammar Char () +commaG = terminal "," + +size :: Int +size = 1000 + +digits :: String +digits = take size (cycle ['0' .. '9']) + +commaDigits :: String +commaDigits = intercalate "," (map pure digits) + +-- | Repetition, by the classes' methods & by Prismoids. +repeats :: [Workload] +repeats = + [ Workload "manyP" (manyP digitG) digits digits + , Workload "someP" (someP digitG) digits digits + , Workload "several" (several >?* digitG) digits digits + , Workload "atLeast 1" (atLeast 1 >?* digitG) digits digits + , Workload "atLeast 500" (atLeast 500 >?* digitG) digits digits + , Workload "atMost" (atMost size >?* digitG) digits digits + , Workload "exactly" (exactly size >?* digitG) digits digits + , Workload "replicateP" (replicateP size digitG) digits digits + , Workload "clonePrismoid atLeast 1" (clonePrismoid (atLeast 1) >?* digitG) digits digits + , Workload "manyTillP" (manyTillP digitG (asEmpty *< terminal ".")) (digits <> ".") digits + , Workload "skipManyP" (skipManyP (terminal " ")) (replicate size ' ') () + ] + +-- | Separated repetition, by sepBy, & hand-rolled. +separates :: [Workload] +separates = + [ Workload "sepBy several" (sepBy commaG several digitG) commaDigits digits + , Workload "sepBy atLeast 1" (sepBy commaG (atLeast 1) digitG) commaDigits digits + , Workload "sepBy exactly" (sepBy commaG (exactly size) digitG) commaDigits digits + , Workload "hand-rolled" (digitG >:< manyP (commaG >* digitG) >|< asEmpty) commaDigits digits + ] + +-- | Varifocals, applied by contextually. +varifocals :: [Workload] +varifocals = + [ Workload "terminateBy" (contextually (terminateBy (== '.')) (anyToken @Char)) + (digits <> ".") (digits <> ".") + , Workload "balanceBy" (contextually (balanceBy (== '(') (== ')')) (anyToken @Char)) + nested nested + , Workload "heredoc" heredocG heredocStr heredoc + ] + where + nested = replicate 200 '(' <> replicate 200 ')' + heredoc = Heredoc "EOF" (replicate 200 "some line of the body") + heredocStr = "< concatMap (<> "\n") (replicate 200 "some line of the body") <> "EOF\n" + +-- | 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) + ] + where + parsed :: CtxGrammar Char a -> String -> a + parsed g s = case parseG g s of + Just (a, "") -> a + _ -> error ("bench input doesn't parse: " <> take 40 s) + terms n ops = concat + [ show (i `mod` 97) <> [ops !! (i `mod` length ops)] | i <- [1 .. n] ] <> "1" + arithStr = terms 300 "+*" + exprStr = terms 300 "+-*/^" + leftStr = terms 300 "+-*/" + jsonStr = "[" <> intercalate "," + (replicate 100 "{\"a\":[1,2,3],\"b\":\"text\",\"c\":true,\"d\":null}") <> "]" + sexprStr = "(" <> unwords (replicate 200 "(foo (bar baz) qux)") <> ")" + lambdaStr = foldr (\v body -> "\\" <> v <> "." <> body) "x" + [ "x" <> show i | i <- [1 .. 100 :: Int] ] + semverStr = "1.22.333-alpha.beta.1.2.3+build.7.sha.abcdef" + +-- | 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 + ] + +-- | Optics as lenses, at functions. +optics :: Benchmark +optics = bgroup "optic" + [ bench "over several" $ nf (over several succ) ints + , bench "map" $ nf (map succ) ints + , bench "over homogenized" $ nf (over homogenized succ) ints + , bench "over crossDiopter" $ nf (over (crossDiopter several several) succ) (ints, ints) + , bench "zipDiopter" $ nf (zipDiopter several (Just . sum)) [ints, ints, ints] + , bench "indexComonocle" $ nf (map (view (indexComonocle _BoundedEnum))) ords + , bench "withPrismoid" $ nf (\xs -> withPrismoid (atLeast 1) (\f g -> fmap g (f xs))) ints + ] + where + ints = [1 .. size] + ords = take size (cycle [LT, EQ, GT]) diff --git a/distributors-grammar/distributors-grammar.cabal b/distributors-grammar/distributors-grammar.cabal new file mode 100644 index 00000000..cae63344 --- /dev/null +++ b/distributors-grammar/distributors-grammar.cabal @@ -0,0 +1,311 @@ +cabal-version: 2.2 + +-- This file has been generated from package.yaml by hpack version 0.39.6. +-- +-- see: https://github.com/sol/hpack + +name: distributors-grammar +version: 0.1.0.0 +synopsis: Unifying Parsers, Printers & Grammars +description: Grammars, by the profunctor algebra of @distributors@, which parse, print, generate & describe their languages, as regular expressions & Backus-Naur forms. +category: Parsing, Profunctors, Optics +homepage: https://github.com/morphismtech/distributors#readme +bug-reports: https://github.com/morphismtech/distributors/issues +author: Eitan Chatav +maintainer: eitan.chatav@gmail.com +copyright: 2026 Eitan Chatav +license: BSD-3-Clause +license-file: LICENSE +build-type: Simple +extra-source-files: + README.md +extra-doc-files: + CHANGELOG.md + +source-repository head + type: git + location: https://github.com/morphismtech/distributors + +library + exposed-modules: + Control.Lens.Grammar + Control.Lens.Grammar.BackusNaur + Control.Lens.Grammar.Machine + 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: + Paths_distributors_grammar + autogen-modules: + Paths_distributors_grammar + hs-source-dirs: + src + default-extensions: + AllowAmbiguousTypes + Arrows + ConstraintKinds + DataKinds + DefaultSignatures + DeriveFoldable + DeriveFunctor + DeriveTraversable + DeriveGeneric + DerivingStrategies + DerivingVia + EmptyCase + FlexibleContexts + FlexibleInstances + FunctionalDependencies + GADTs + GeneralizedNewtypeDeriving + ImportQualifiedPost + ImpredicativeTypes + InstanceSigs + LambdaCase + MagicHash + MonoLocalBinds + QualifiedDo + QuantifiedConstraints + RankNTypes + RecursiveDo + ScopedTypeVariables + StandaloneDeriving + StandaloneKindSignatures + TemplateHaskell + TupleSections + TypeApplications + TypeFamilies + TypeOperators + UndecidableInstances + UndecidableSuperClasses + ghc-options: -Wall -Wcompat -Widentities -Wincomplete-record-updates -Wincomplete-uni-patterns -Wmissing-export-lists -Wmissing-home-modules -Wpartial-fields -Wredundant-constraints + build-depends: + MemoTrie >=0.6 && <1 + , QuickCheck >=2.14 && <3 + , base >=4.20 && <5 + , bifunctors >=5.5 && <6 + , containers >=0.6 && <1 + , distributors ==0.7.* + , lens >=5.0 && <6 + , monad-loops >=0.4.3 && <1 + , mtl >=2.2 && <3 + , profunctors >=5.6 && <6 + , random >=1.2 && <2 + , witherable >=0.4 && <1 + default-language: Haskell2010 + +test-suite doctests + type: exitcode-stdio-1.0 + main-is: Doctests.hs + other-modules: + Paths_distributors_grammar + autogen-modules: + Paths_distributors_grammar + hs-source-dirs: + doctest + default-extensions: + AllowAmbiguousTypes + Arrows + ConstraintKinds + DataKinds + DefaultSignatures + DeriveFoldable + DeriveFunctor + DeriveTraversable + DeriveGeneric + DerivingStrategies + DerivingVia + EmptyCase + FlexibleContexts + FlexibleInstances + FunctionalDependencies + GADTs + GeneralizedNewtypeDeriving + ImportQualifiedPost + ImpredicativeTypes + InstanceSigs + LambdaCase + MagicHash + MonoLocalBinds + QualifiedDo + QuantifiedConstraints + RankNTypes + RecursiveDo + ScopedTypeVariables + StandaloneDeriving + StandaloneKindSignatures + TemplateHaskell + TupleSections + TypeApplications + TypeFamilies + TypeOperators + UndecidableInstances + UndecidableSuperClasses + ghc-options: -Wall -Wcompat -Widentities -Wincomplete-record-updates -Wincomplete-uni-patterns -Wmissing-export-lists -Wmissing-home-modules -Wpartial-fields -Wredundant-constraints -threaded + build-depends: + MemoTrie >=0.6 && <1 + , QuickCheck >=2.14 && <3 + , base >=4.20 && <5 + , bifunctors >=5.5 && <6 + , containers >=0.6 && <1 + , distributors ==0.7.* + , distributors-grammar + , doctest-parallel >=0.3 && <1 + , lens >=5.0 && <6 + , monad-loops >=0.4.3 && <1 + , mtl >=2.2 && <3 + , profunctors >=5.6 && <6 + , random >=1.2 && <2 + , witherable >=0.4 && <1 + default-language: Haskell2010 + +test-suite test + type: exitcode-stdio-1.0 + main-is: Main.hs + other-modules: + Examples.Arithmetic + Examples.Chain + Examples.Expression + Examples.Heredoc + Examples.Json + Examples.Lambda + Examples.LenVec + Examples.RegString + Examples.SemVer + Examples.SExpr + Properties.Kleene + Properties.Varifocal + Paths_distributors_grammar + autogen-modules: + Paths_distributors_grammar + hs-source-dirs: + test + default-extensions: + AllowAmbiguousTypes + Arrows + ConstraintKinds + DataKinds + DefaultSignatures + DeriveFoldable + DeriveFunctor + DeriveTraversable + DeriveGeneric + DerivingStrategies + DerivingVia + EmptyCase + FlexibleContexts + FlexibleInstances + FunctionalDependencies + GADTs + GeneralizedNewtypeDeriving + ImportQualifiedPost + ImpredicativeTypes + InstanceSigs + LambdaCase + MagicHash + MonoLocalBinds + QualifiedDo + QuantifiedConstraints + RankNTypes + RecursiveDo + ScopedTypeVariables + StandaloneDeriving + StandaloneKindSignatures + TemplateHaskell + TupleSections + TypeApplications + TypeFamilies + TypeOperators + UndecidableInstances + UndecidableSuperClasses + ghc-options: -Wall -Wcompat -Widentities -Wincomplete-record-updates -Wincomplete-uni-patterns -Wmissing-export-lists -Wmissing-home-modules -Wpartial-fields -Wredundant-constraints + build-depends: + MemoTrie >=0.6 && <1 + , QuickCheck >=2.14 && <3 + , base >=4.20 && <5 + , bifunctors >=5.5 && <6 + , containers >=0.6 && <1 + , distributors + , distributors-grammar + , hspec >=2.7 && <3 + , lens >=5.0 && <6 + , megaparsec >=9.0 && <10 + , monad-loops >=0.4.3 && <1 + , mtl >=2.2 && <3 + , profunctors >=5.6 && <6 + , random >=1.2 && <2 + , witherable >=0.4 && <1 + default-language: Haskell2010 + +benchmark core + type: exitcode-stdio-1.0 + main-is: Main.hs + other-modules: + Examples.Arithmetic + Examples.Expression + Examples.Heredoc + Examples.Json + Examples.Lambda + Examples.SemVer + Examples.SExpr + hs-source-dirs: + bench + test + default-extensions: + AllowAmbiguousTypes + Arrows + ConstraintKinds + DataKinds + DefaultSignatures + DeriveFoldable + DeriveFunctor + DeriveTraversable + DeriveGeneric + DerivingStrategies + DerivingVia + EmptyCase + FlexibleContexts + FlexibleInstances + FunctionalDependencies + GADTs + GeneralizedNewtypeDeriving + ImportQualifiedPost + ImpredicativeTypes + InstanceSigs + LambdaCase + MagicHash + MonoLocalBinds + QualifiedDo + QuantifiedConstraints + RankNTypes + RecursiveDo + ScopedTypeVariables + StandaloneDeriving + StandaloneKindSignatures + TemplateHaskell + TupleSections + TypeApplications + TypeFamilies + TypeOperators + UndecidableInstances + UndecidableSuperClasses + ghc-options: -Wall -Wcompat -Widentities -Wincomplete-record-updates -Wincomplete-uni-patterns -Wmissing-export-lists -Wmissing-home-modules -Wpartial-fields -Wredundant-constraints -O2 -rtsopts + build-depends: + MemoTrie >=0.6 && <1 + , QuickCheck >=2.14 && <3 + , base >=4.20 && <5 + , bifunctors >=5.5 && <6 + , containers >=0.6 && <1 + , distributors + , distributors-grammar + , lens >=5.0 && <6 + , monad-loops >=0.4.3 && <1 + , mtl >=2.2 && <3 + , profunctors >=5.6 && <6 + , random >=1.2 && <2 + , tasty-bench >=0.3 && <1 + , witherable >=0.4 && <1 + default-language: Haskell2010 diff --git a/distributors-grammar/doctest/Doctests.hs b/distributors-grammar/doctest/Doctests.hs new file mode 100644 index 00000000..f8dfdff7 --- /dev/null +++ b/distributors-grammar/doctest/Doctests.hs @@ -0,0 +1,7 @@ +module Main (main) where + +import System.Environment (getArgs) +import Test.DocTest (mainFromCabal) + +main :: IO () +main = mainFromCabal "distributors-grammar" =<< getArgs diff --git a/distributors-grammar/package.yaml b/distributors-grammar/package.yaml new file mode 100644 index 00000000..c29da918 --- /dev/null +++ b/distributors-grammar/package.yaml @@ -0,0 +1,126 @@ +name: distributors-grammar +version: 0.1.0.0 +github: "morphismtech/distributors" +license: BSD-3-Clause +author: "Eitan Chatav" +maintainer: "eitan.chatav@gmail.com" +copyright: "2026 Eitan Chatav" + +extra-source-files: +- README.md +extra-doc-files: +- CHANGELOG.md + +category: Parsing, Profunctors, Optics +synopsis: Unifying Parsers, Printers & Grammars +description: + Grammars, by the profunctor algebra of @distributors@, + which parse, print, generate & describe their languages, + as regular expressions & Backus-Naur forms. + +dependencies: +- base >= 4.20 && < 5 +- bifunctors >= 5.5 && < 6 +- containers >= 0.6 && < 1 +- distributors >= 0.7 && < 0.8 +- lens >= 5.0 && < 6 +- MemoTrie >= 0.6 && < 1 +- monad-loops >= 0.4.3 && < 1 +- mtl >= 2.2 && < 3 +- profunctors >= 5.6 && < 6 +- QuickCheck >= 2.14 && < 3 +- random >= 1.2 && < 2 +- witherable >= 0.4 && < 1 + +ghc-options: +- -Wall +- -Wcompat +- -Widentities +- -Wincomplete-record-updates +- -Wincomplete-uni-patterns +- -Wmissing-export-lists +- -Wmissing-home-modules +- -Wpartial-fields +- -Wredundant-constraints + +library: + source-dirs: src + +default-extensions: +- AllowAmbiguousTypes +- Arrows +- ConstraintKinds +- DataKinds +- DefaultSignatures +- DeriveFoldable +- DeriveFunctor +- DeriveTraversable +- DeriveGeneric +- DerivingStrategies +- DerivingVia +- EmptyCase +- FlexibleContexts +- FlexibleInstances +- FunctionalDependencies +- GADTs +- GeneralizedNewtypeDeriving +- ImportQualifiedPost +- ImpredicativeTypes +- InstanceSigs +- LambdaCase +- MagicHash +- MonoLocalBinds +- QualifiedDo +- QuantifiedConstraints +- RankNTypes +- RecursiveDo +- ScopedTypeVariables +- StandaloneDeriving +- StandaloneKindSignatures +- TemplateHaskell +- TupleSections +- TypeApplications +- TypeFamilies +- TypeOperators +- UndecidableInstances +- UndecidableSuperClasses + +tests: + doctests: + main: Doctests.hs + source-dirs: doctest + ghc-options: -threaded + dependencies: + - distributors-grammar + - doctest-parallel >= 0.3 && < 1 + test: + main: Main.hs + source-dirs: test + dependencies: + - distributors + - distributors-grammar + - hspec >= 2.7 && < 3 + - megaparsec >= 9.0 && < 10 + - QuickCheck >= 2.14 && < 3 + +benchmarks: + core: + main: Main.hs + source-dirs: + - bench + - test + other-modules: + - Examples.Arithmetic + - Examples.Expression + - Examples.Heredoc + - Examples.Json + - Examples.Lambda + - Examples.SemVer + - Examples.SExpr + ghc-options: + - -O2 + - -rtsopts + dependencies: + - distributors + - distributors-grammar + - tasty-bench >= 0.3 && < 1 diff --git a/src/Control/Lens/Grammar.hs b/distributors-grammar/src/Control/Lens/Grammar.hs similarity index 75% rename from src/Control/Lens/Grammar.hs rename to distributors-grammar/src/Control/Lens/Grammar.hs index 7c3dcaf1..ae91a62b 100644 --- a/src/Control/Lens/Grammar.hs +++ b/distributors-grammar/src/Control/Lens/Grammar.hs @@ -44,21 +44,21 @@ import Control.Applicative import Control.Lens import Control.Lens.PartialIso import Control.Lens.Grammar.BackusNaur -import Control.Lens.Grammar.Boole -import Control.Lens.Grammar.Kleene import Control.Lens.Grammar.Machine +import Control.Lens.Grammar.RegEx import Control.Lens.Grammar.Token import Control.Lens.Grammar.Symbol import Data.Bifunctor.Joker import Data.Maybe hiding (mapMaybe) import Data.Monoid +import Data.Monoid.Disjunctive import Data.Profunctor.Distributor +import Data.Profunctor.Monoidal.Cocartesian import Data.Profunctor.Filtrator -import Data.Profunctor.Monadic +import Data.Profunctor.Monadic as X import Data.Profunctor.Monoidal import Data.Profunctor.Grammar import Data.Profunctor.Grammar.Parsector -import Data.Profunctor.Separator import Data.String import GHC.Exts import Prelude hiding (filter) @@ -69,20 +69,29 @@ import Witherable import Control.Lens.Cons as X import Control.Lens.Empty as X import Control.Lens.Grammar.BackusNaur as X -import Control.Lens.Grammar.Boole as X -import Control.Lens.Grammar.Kleene as X import Control.Lens.Grammar.Machine as X +import Control.Lens.Grammar.RegEx as X import Control.Lens.Grammar.Symbol as X import Control.Lens.Grammar.Token as X import Control.Lens.PartialIso as X +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 Data.Monoid.Disjunctive as X import Data.Profunctor.Distributor as X +import Data.Profunctor.Monoidal.Cocartesian as X import Data.Profunctor.Filtrator as X import Data.Profunctor.Grammar as X import Data.Profunctor.Grammar.Parsector as X import Data.Profunctor.Monoidal as X -import Data.Profunctor.Separator as X import Data.Traversable.Homogeneous as X +import Data.Traversable.Homogeneous.Enumerable as X + +-- $setup +-- >>> import Data.String (fromString) +-- >>> import GHC.Exts (toList) {- | A regular grammar may be constructed using @@ -111,7 +120,7 @@ You could generate it with the TemplateHaskell combinator, Unfortunately, we can't use TemplateHaskell to generate it in [GHCi] (https://wiki.haskell.org/GHC/GHCi), -which is used to test this documenation. +which is used to test this documentation. Here is equivalent Haskell code instead. Since @SemVer@ has only one constructor, @_SemVer@ can be an `Control.Lens.Iso.Iso`. @@ -138,18 +147,17 @@ semverGrammar = _SemVer >*< optionP _Empty (terminal "+" >* identifiersG) where numberG = iso show read >~ someP (asIn @Char DecimalNumber) - identifiersG = several1 (sepWith ".") (someP charG) + identifiersG = sepWith "." (atLeast 1) (someP charG) charG = asIn LowercaseLetter - <|> asIn UppercaseLetter - <|> asIn DecimalNumber - <|> token '-' + >|< asIn UppercaseLetter + >|< asIn DecimalNumber + >|< token '-' :} Instead of using the constructor @SemVer@ with the `Functor` applicator `<$>`, we use the optic @_SemVer@ we defined and the `Choice` applicator `>?`; although, we could have used the `Profunctor` applicator `>~` instead, -because @_SemVer@ is an `Control.Lens.Iso.Iso`. A few `Alternative` -combinators like `<|>` work both `Functor`ially and `Profunctor`ially. +because @_SemVer@ is an `Control.Lens.Iso.Iso`. +------------+---------------+ | Functorial | Profunctorial | @@ -166,11 +174,11 @@ combinators like `<|>` work both `Functor`ially and `Profunctor`ially. +------------+---------------+ | `<*>` | `>*<` | +------------+---------------+ -| `empty` | `empty` | +| `empty` | `falseP` | +------------+---------------+ -| `<|>` | `<|>` | +| `<|>` | `>|<` | +------------+---------------+ -| `choice` | `choice` | +| @choice@ | `orP` | +------------+---------------+ | `many` | `manyP` | +------------+---------------+ @@ -179,10 +187,11 @@ combinators like `<|>` work both `Functor`ially and `Profunctor`ially. | `optional` | `optionalP` | +------------+---------------+ -You can generate a `RegString` from a `RegGrammar` with `regstringG`. +You can generate a t'RegString' from a `RegGrammar` +with `Control.Lens.Grammar.regstringG`. >>> putStringLn (regstringG semverGrammar) -\p{Nd}+(.\p{Nd}+(.\p{Nd}+((-((\p{Ll}|\p{Lu}|\p{Nd}|-)+(.(\p{Ll}|\p{Lu}|\p{Nd}|-)+)*))?(\+((\p{Ll}|\p{Lu}|\p{Nd}|-)+(.(\p{Ll}|\p{Lu}|\p{Nd}|-)+)*))?))) +\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. @@ -214,7 +223,8 @@ coming from the `BackusNaurForm` interface * `rule` abstraction, * and general recursion. -`regexGrammar` and `regbnfGrammar` are examples of context-free +`Control.Lens.Grammar.regexGrammar` and +`Control.Lens.Grammar.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. @@ -250,11 +260,11 @@ arithGrammar :: Grammar Char Arith arithGrammar = ruleRec "arith" sumG where sumG arith = rule "sum" $ - chain1 Left _Add (sepWith "+") (prodG arith) + sepWith "+" (chain1 Left _Add) (prodG arith) prodG arith = rule "product" $ - chain1 Left _Mul (sepWith "*") (factorG arith) + sepWith "*" (chain1 Left _Mul) (factorG arith) factorG arith = rule "factor" $ - numberG <|> terminal "(" >* arith *< terminal ")" + numberG >|< terminal "(" >* arith *< terminal ")" numberG = rule "number" $ _Num . iso show read >? someP (asIn @Char DecimalNumber) :} @@ -275,6 +285,66 @@ Just "1+2*3" >>> do pr <- printG arithGrammar (Num 69); pure (pr "") :: Maybe String Just "69" +Operator tables with precedence, like @buildExpressionParser@'s, +are built by `withOperators`. For example, an expression grammar +over natural numbers with a postfix factorial @!@ (binding tightest, +and not required to actually compute a factorial), a right-associative +exponent @^@, a left-associative @*@, and left-associative @+@ & @-@ +binding loosest: + +>>> :{ +data Expr + = Nat Natural + | Fac Expr + | Exp Expr Expr + | Mul Expr Expr + | Add Expr Expr + | Sub Expr Expr + deriving stock (Eq, Ord, Show, Read) +_Nat :: Prism' Expr Natural +_Nat = prism' Nat (\case Nat n -> Just n; _ -> Nothing) +_Fac :: Prism' Expr Expr +_Fac = prism' Fac (\case Fac x -> Just x; _ -> Nothing) +_Exp, _Mul, _Add, _Sub :: Prism' Expr (Expr, Expr) +_Exp = prism' (uncurry Exp) (\case Exp x y -> Just (x,y); _ -> Nothing) +_Mul = prism' (uncurry Mul) (\case Mul x y -> Just (x,y); _ -> Nothing) +_Add = prism' (uncurry Add) (\case Add x y -> Just (x,y); _ -> Nothing) +_Sub = prism' (uncurry Sub) (\case Sub x y -> Just (x,y); _ -> Nothing) +exprGrammar :: Grammar Char Expr +exprGrammar = ruleRec "expr" $ \expr -> + let atom = rule "atom" $ nat >|< terminal "(" >* expr *< terminal ")" + nat = rule "nat" $ _Nat . iso show read >? someP (asIn @Char DecimalNumber) + in withOperators + [ [ Postfix _Fac (terminal "!") ] + , [ Infix RightAssoc _Exp (terminal "^") ] + , [ Infix LeftAssoc _Mul (terminal "*") ] + , [ Infix LeftAssoc _Add (terminal "+"), Infix LeftAssoc _Sub (terminal "-") ] + ] atom +:} + +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"] +[Exp (Nat 2) (Exp (Nat 3) (Nat 2))] +>>> [e | (e,"") <- parseG exprGrammar "3-2-1"] +[Sub (Sub (Nat 3) (Nat 2)) (Nat 1)] +>>> [e | (e,"") <- parseG exprGrammar "2*3+4"] +[Add (Mul (Nat 2) (Nat 3)) (Nat 4)] +>>> [e | (e,"") <- parseG exprGrammar "2*(3+4)"] +[Mul (Nat 2) (Add (Nat 3) (Nat 4))] +>>> [e | (e,"") <- parseG exprGrammar "3!"] +[Fac (Nat 3)] +>>> [e | (e,"") <- parseG exprGrammar "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 +Just "2^3^2" +>>> unparseG exprGrammar (Exp (Nat 2) (Fac (Nat 3))) "" :: Maybe String +Just "2^3!" + If all `rule`s are non-recursive, then a `Grammar` can be rewritten as a `RegGrammar`. Since Haskell permits general recursion, and `RegGrammar`s are @@ -290,7 +360,7 @@ type Grammar token a = forall p. ) => p a a {- | For context-sensitivity, -the `Monadic` interface is used by importing "Data.Profunctor.Monadic" +the `Monadic` interface is used by importing "Data.Profunctor.Monadic.Do" qualified and using a "bonding" notation which mixes "idiom" style with qualified do-notation. Let's use length-encoded vectors of numbers as an example. @@ -306,26 +376,26 @@ _LenVec = iso (\LenVec {..} -> (length, vector)) (\(length, vector) -> LenVec {. :} >>> :set -XQualifiedDo ->>> import qualified Data.Profunctor.Monadic as P +>>> import qualified Data.Profunctor.Monadic.Do as P >>> :{ lenvecGrammar :: CtxGrammar Char LenVec lenvecGrammar = _LenVec >? P.do let numberG = iso show read >~ someP (asIn @Char DecimalNumber) - vectorG n = intercalateP n (sepWith ",") numberG + vectorG n = sepWith "," (exactly n) numberG len <- numberG -- bonds to _LenVec terminal ";" -- doesn't bond vectorG (fromIntegral len) -- bonds to _LenVec :} The qualified do-notation changes the signature of -@P.@`Data.Profunctor.Monadic.>>=`, +@P.@`Data.Profunctor.Monadic.Do.>>=`, so that we must apply the constructor pattern @_LenVec@ to the do-block with the `>?` applicator. Any scoped bound action, @var <- action@, gets "bonded" to the constructor pattern. -Any unbound actions, except for the last action in the do-block, -does not get bonded to the pattern. +Unbound actions, except for the last action in the do-block, +don't get bonded to the pattern. The last action does get bonded to the pattern. Any unscoped bound action, @_ <- action@, also gets bonded to the pattern, @@ -333,7 +403,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 `RegBnf` from a `CtxGrammar` since the `rule`s +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. @@ -368,25 +438,57 @@ the context-sensitivity of `CtxGrammar` implies unrestricted filtration of grammars by computable predicates, which can recognize the larger class of recursively enumerable languages. +Context-sensitivity can also be optical. A `Varifocal` is an optic +whose shape depends on the foci it builds, as no `Bifocal` can, +applied in a `CtxGrammar` by `contextually`, +or on a `MonadicTrans` profunctor, by `contextuallyT`. +A [heredoc](https://en.wikipedia.org/wiki/Here_document)'s lines are its foci, +its tag, its body, & its tag again, `delimitBy` by the first line +equal to the opening tag, a language which isn't context-free. + +>>> :{ +data Heredoc = Heredoc String [String] deriving (Eq, Show) +heredocG :: CtxGrammar Char Heredoc +heredocG = lined >~ terminal "<<" >* contextually (delimitBy (==)) lineG + where + lineG = manyP (notOneOf "\n") *< terminal "\n" + lined = iso + (\(Heredoc tag body) -> tag : body ++ [tag]) + (\case + tag : rest -> Heredoc tag (if null rest then [] else init rest) + [] -> Heredoc "" []) +:} + +>>> [pr "" | pr <- printG heredocG (Heredoc "EOF" ["hi"])] :: [String] +["<>> [h | (h, "") <- parseG heredocG "<>> parsecResult (parsecG heredocG "<>> [pr "" | pr <- printG heredocG (Heredoc "EOF" ["EOF"])] :: [String] +[] + Finally, `CtxGrammar`s support failure reporting and backtracking. -This has no effect on `printG`, `parseG` or `unparseG`; -but it effects `parsecG` and `unparsecG`. +This has no effect on `Control.Lens.Grammar.printG`, +`Control.Lens.Grammar.parseG` or `Control.Lens.Grammar.unparseG`; +but it affects `Control.Lens.Grammar.parsecG` +and `Control.Lens.Grammar.unparsecG`. For context, an @LL@ grammar can be (un)parsed by an @LL@ parser. An @LL@ parser (un)parses from left to right, -and constucts leftmost derivations. +and constructs leftmost derivations. An @LL(k)@ parser can look @k@ tokens ahead. -`Parsor` is an @LL(∞)@ parser. -`Parsector` is an @LL(1)@ parser. +t'Parsor' is an @LL(∞)@ parser. +t'Parsector' is an @LL(1)@ parser. The backtracking `try` combinator -restores full lookahead to `Parsector`. -Since both `Parsor` & `Parsector` are @LL@ parsers they +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" +>>> parsecG (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" -ParsecState {parsecLooked = True, parsecOffset = 3, parsecStream = "b", parsecFailure = ParsecFailure {parsecExpect = TokenClass (Alternate (TokenClass (OneOf (fromList "a"))) (TokenClass (NotOneOf (fromList "") (AndAsIn DecimalNumber)))), parsecLabels = []}, parsecResult = Nothing} +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" "" ParsecState {parsecLooked = True, parsecOffset = 2, parsecStream = "ab", parsecFailure = ParsecFailure {parsecExpect = TokenClass (OneOf (fromList "c")), parsecLabels = []}, parsecResult = Nothing} @@ -408,7 +510,7 @@ type Lexical token p = , forall x y. (x ~ token, y ~ token) => TokenAlgebra token (p x y) ) :: Constraint -{- | `RegString`s are an embedded domain specific language +{- | t'RegString's are an embedded domain specific language of regular expression strings. Since they are strings, they have a string-like interface. @@ -419,17 +521,18 @@ ab|c >>> rex "ab|c" -`RegString`s can be generated from `RegGrammar`s with `regstringG`. +t'RegString's can be generated from `RegGrammar`s +with `Control.Lens.Grammar.regstringG`. ->>> regstringG (terminal "a" >* terminal "b" <|> terminal "c") +>>> regstringG (terminal "a" >* terminal "b" >|< terminal "c") "ab|c" -`RegString`s are actually stored as an algebraic datatype, `RegEx`. +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")))) +RegExam (Alternate (Sequence (RegExam (OneOf (fromList "a"))) (RegExam (OneOf (fromList "b"))) []) (RegExam (OneOf (fromList "c"))) []) -`RegString`s are similar to regular expression strings in many other +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`. @@ -440,16 +543,16 @@ True >>> "xyz" =~ rex False -Like `RegGrammar`s, `RegString`s can use all the `Lexical` combinators. +Like `RegGrammar`s, t'RegString's can use all the `Lexical` combinators. Unlike `RegGrammar`s, instead of using `Monoidal` and `Alternator` combinators, -`RegString`s use `Monoid` and `KleeneStarAlgebra` combinators. +t'RegString's use `Monoid` and `KleeneStarAlgebra` combinators. >>> terminal "a" <> terminal "b" >|< terminal "c" :: RegString "ab|c" >>> mempty :: RegString "" -Since `RegString`s are a `KleeneStarAlgebra`, +Since t'RegString's are a `KleeneStarAlgebra`, they support Kleene quantifiers. >>> starK rex @@ -459,7 +562,7 @@ they support Kleene quantifiers. >>> optK rex "(ab|c)?" -Like other regular expression languages, `RegString`s support +Like other regular expression languages, t'RegString's support character classes. >>> oneOf "abc" :: RegString @@ -470,7 +573,7 @@ character classes. The character classes are used for failure, matching no character or string, as well as the wildcard, matching any single character. ->>> zeroK :: RegString +>>> falseP :: RegString "[]" >>> anyToken :: RegString "[^]" @@ -486,21 +589,21 @@ Additional forms of character classes test for a character's `GeneralCategory`. and the `Tokenized` combinators are all negatable. However, we'd like to be able to take the intersection of character classes as well. -`RegString`s can combine characters' `tokenClass`es +t'RegString's can combine characters' `tokenClass`es using `BooleanAlgebra` combinators. ->>> tokenClass (notOneOf "abc" >&&< notOneOf "xyz") :: RegString +>>> tokenClass (notOneOf "abc" >&< notOneOf "xyz") :: RegString "[^abcxyz]" ->>> tokenClass (oneOf "abcxyz" >&&< notOneOf "xyz") :: RegString +>>> tokenClass (oneOf "abcxyz" >&< notOneOf "xyz") :: RegString "[abc]" ->>> tokenClass (notOneOf "#$%" >&&< notAsIn Control) :: RegString +>>> tokenClass (notOneOf "#$%" >&< notAsIn Control) :: RegString "[^#$%\\P{Cc}]" ->>> tokenClass (allB notAsIn [MathSymbol, Control]) :: RegString +>>> tokenClass (allP notAsIn [MathSymbol, Control]) :: RegString "\\P{Sm|Cc}" ->>> tokenClass (notB (oneOf "xyz")) :: RegString +>>> tokenClass (notP (oneOf "xyz")) :: RegString "[^xyz]" -Ill-formed `RegString`s normalize to failure. +Ill-formed t'RegString's normalize to failure. >>> fromString ")(" :: RegString "[]" @@ -508,23 +611,23 @@ Ill-formed `RegString`s normalize to failure. newtype RegString = RegString {runRegString :: RegEx Char} deriving newtype ( Eq, Ord - , Semigroup, Monoid, KleeneStarAlgebra + , Semigroup, Monoid, DisjunctiveMonoid, KleeneStarAlgebra , Tokenized Char, TokenAlgebra Char , TerminalSymbol Char, NonTerminalSymbol , Matching String ) -{- | `RegBnf`s are an embedded domain specific language +{- | t'RegBnf's are an embedded domain specific language of Backus-Naur forms extended by regular expression strings. -A `RegBnf` consists of a distinguished `RegString` "start" rule, -and a set of named `RegString` `rule`s. +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 `RegString`s they have a string-like interface. +Like t'RegString's they have a string-like interface. >>> let bnf = fromString "{start} = foo|bar" :: RegBnf >>> putStringLn bnf @@ -534,12 +637,13 @@ Like `RegString`s they have a string-like interface. >>> :type toList bnf toList bnf :: [Char] -`RegBnf`s can be generated from context-free `Grammar`s with `regbnfG`. +t'RegBnf's can be generated from context-free `Grammar`s +with `Control.Lens.Grammar.regbnfG`. >>> :type regbnfG regbnfGrammar regbnfG regbnfGrammar :: RegBnf -Like `RegString`s, `RegBnf`s can be constructed using +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. @@ -553,7 +657,7 @@ But they also support `BackusNaurForm` `rule`s and `ruleRec`s. newtype RegBnf = RegBnf {runRegBnf :: Bnf RegString} deriving newtype ( Eq, Ord - , Semigroup, Monoid, KleeneStarAlgebra + , Semigroup, Monoid, DisjunctiveMonoid, KleeneStarAlgebra , Tokenized Char, TokenAlgebra Char , TerminalSymbol Char, NonTerminalSymbol , BackusNaurForm @@ -563,15 +667,15 @@ instance Matching String RegBnf where makeNestedPrisms ''Bnf makeNestedPrisms ''RegEx -makeNestedPrisms ''RegExam +makeNestedPrisms ''TokenExam makeNestedPrisms ''CategoryTest makeNestedPrisms ''GeneralCategory makeNestedPrisms ''RegString makeNestedPrisms ''RegBnf -{- | `regexGrammar` is a context-free `Grammar` for `RegString`s. -It can't be a `RegGrammar`, since `RegString`s include parenthesization. -But [balanced parentheses](https://en.wikipedia.org/wiki/Dyck_language) +{- | `regexGrammar` is a context-free `Grammar` for t'RegString's. +It can't be a `RegGrammar`, since t'RegString's include parenthesization. +But [balanceBy parentheses](https://en.wikipedia.org/wiki/Dyck_language) are a context-free language. >>> putStringLn (regbnfG regexGrammar) @@ -583,8 +687,8 @@ are a context-free language. {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-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}*\} @@ -595,25 +699,35 @@ regexGrammar :: Grammar Char RegString regexGrammar = _RegString >~ ruleRec "regex" altG where altG rex = rule "alternate" $ - chain1 Left (_RegExam . _Alternate) (sepWith "|") (seqG rex) + iso alternativesOf (foldr1 (>|<) :: [RegEx Char] -> RegEx Char) + >~ sepWith "|" (atLeast 1) (seqG rex) seqG rex = rule "sequence" $ - chain Left _Sequence _SeqEmpty noSep (exprG rex) + 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" $ choice + exprG rex = rule "expression" $ orP [ _KleeneOpt >? atomG rex *< terminal "?" , _KleeneStar >? atomG rex *< terminal "*" , _KleenePlus >? atomG rex *< terminal "+" , atomG rex ] - atomG rex = rule "atom" $ choice + atomG rex = rule "atom" $ orP [ _NonTerminal >? terminal "\\q" >* nonterminalG , _RegExam >? classG , terminal "(" >* rex *< terminal ")" ] - categoryG = rule "category" $ choice + categoryG = rule "category" $ orP [ _LowercaseLetter >? terminal "Ll" , _UppercaseLetter >? terminal "Lu" , _TitlecaseLetter >? terminal "Lt" @@ -646,26 +760,25 @@ regexGrammar = _RegString >~ ruleRec "regex" altG , _NotAssigned >? terminal "Cn" ] - classG = rule "class" $ choice + classG = rule "class" $ orP [ _OneOf >? classOneOfG , _NotOneOf >? classNotOneOfG ] - classCatG = rule "class-category" $ choice + classCatG = rule "class-category" $ orP [ _AndAsIn >? terminal "\\p{" >* categoryG *< terminal "}" - , _AndNotAsIn >? several1 - (sepWith "|" & beginWith "\\P{" & endWith "}") - categoryG + , _AndNotAsIn . from listed >? + terminal "\\P{" >* sepWith "|" (atLeast 1) categoryG *< terminal "}" ] - classOneOfG = rule "class-one-of" $ choice + classOneOfG = rule "class-one-of" $ orP [ onlyOne charG - , terminal "[" >* several noSep charG *< terminal "]" + , terminal "[" >* (listed ~< manyP charG) *< terminal "]" ] - classNotOneOfG = rule "class-not-one-of" $ choice + classNotOneOfG = rule "class-not-one-of" $ orP [ asEmpty >*< classCatG - , terminal "[^" >* several noSep charG >*< + , terminal "[^" >* (listed ~< manyP charG) >*< optionP (_AndNotAsIn . _Empty) classCatG *< terminal "]" ] @@ -675,15 +788,15 @@ nonterminalG = rule "nonterminal" $ charG :: Grammar Char Char charG = rule "char" $ - tokenClass (notOneOf charsReserved >&&< notAsIn Control) - <|> terminal "\\" >* charEscapedG + tokenClass (notOneOf charsReserved >&< notAsIn Control) + >|< terminal "\\" >* charEscapedG where charEscapedG = rule "char-escaped" $ - oneOf charsReserved <|> charControlG + oneOf charsReserved >|< charControlG charsReserved = "()*+?[\\]^{|}" - charControlG = rule "char-control" $ choice + charControlG = rule "char-control" $ orP [ only '\NUL' >? terminal "NUL" , only '\SOH' >? terminal "SOH" , only '\STX' >? terminal "STX" @@ -752,7 +865,7 @@ charG = rule "char" $ ] {- | -`regbnfGrammar` is a context-free `Grammar` for `RegBnf`s. +`regbnfGrammar` is a context-free `Grammar` for t'RegBnf's. That means that it can generate a self-hosted definition. >>> putStringLn (regbnfG regbnfGrammar) @@ -764,29 +877,29 @@ That means that it can generate a self-hosted definition. {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-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})* +{regbnf} = \{start\} = \q{regex}(\LF\q{nonterminal} = \q{regex})* {regex} = \q{alternate} {sequence} = \q{expression}* -} regbnfGrammar :: Grammar Char RegBnf regbnfGrammar = rule "regbnf" $ _RegBnf . _Bnf >~ - terminal "{start} = " >* regexGrammar >*< several noSep - (terminal "\n" >* nonterminalG *< terminal " = " >*< regexGrammar) + terminal "{start} = " >* regexGrammar >*< (listed ~< manyP + (terminal "\n" >* nonterminalG *< terminal " = " >*< regexGrammar)) -{- | `regstringG` generates a `RegString` from a regular grammar. +{- | `regstringG` generates a t'RegString' from a regular grammar. 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 -{- | `regbnfG` generates a `RegBnf` from a context-free `Grammar`. +{- | `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`. @@ -794,7 +907,7 @@ It can apply to a `RegGrammar`. regbnfG :: Grammar Char a -> RegBnf regbnfG bnf = runGrammor bnf -{- | Compile a `Grammar` into a `Transducer`. +{- | Compile a `Grammar` into a t'Transducer'. >>> let regexMachine = transducerG @Char regexGrammar @@ -897,6 +1010,9 @@ the type system will allow `unparseG` to be applied to them. Running the printer on a syntax value and an input string `snoc`s tokens at the end of the string, from left to right, returning the output string. +Print to a string with a constant time `snoc`, like a +@Data.Sequence.Seq@, since a list's `snoc` is linear, +making printing to a `String` quadratic. -} unparseG :: (Cons string string token token, Snoc string string token token) @@ -934,6 +1050,9 @@ Running the printer on a syntax value and an input string `snoc`s tokens at the end of the string, from left to right, returning `parsecResult` as `Nothing` on failure or `Just` the input syntax value, with print success stored in `parsecStream`. +Print to a string with a constant time `snoc`, like a +@Data.Sequence.Seq@, since a list's `snoc` is linear, +making printing to a `String` quadratic. -} unparsecG :: (Cons string string token token, Snoc string string token token) @@ -1016,7 +1135,7 @@ monadG monadG joker = runJoker joker {- | `putStringLn` is a utility that generalizes `putStrLn` -to string-like interfaces such as `RegString` and `RegBnf`. +to string-like interfaces such as t'RegString' and t'RegBnf'. -} putStringLn :: (IsList string, Item string ~ Char) => string -> IO () putStringLn = putStrLn . toList @@ -1024,7 +1143,7 @@ putStringLn = putStrLn . toList instance IsList RegString where type Item RegString = Char fromList - = fromMaybe zeroK + = fromMaybe falseP . listToMaybe . mapMaybe prsF . readP_to_S (readG regexGrammar) @@ -1039,11 +1158,11 @@ instance IsString RegString where instance Show RegString where showsPrec precision = showsPrec precision . toList instance Read RegString where - readsPrec _ str = [(fromList str, "")] + readsPrec = readsGrammar regexGrammar instance IsList RegBnf where type Item RegBnf = Char fromList - = fromMaybe zeroK + = fromMaybe falseP . listToMaybe . mapMaybe prsF . readP_to_S (readG regbnfGrammar) @@ -1058,4 +1177,14 @@ instance IsString RegBnf where instance Show RegBnf where showsPrec precision = showsPrec precision . toList instance Read RegBnf where - readsPrec _ str = [(fromList str, "")] + readsPrec = readsGrammar regbnfGrammar + +{- | Read a string literal, as `String`'s `readsPrec` does, +& its text by a `Grammar`, so that @read . show = id@. +-} +readsGrammar :: Grammar Char a -> Int -> ReadS a +readsGrammar grammar precision str = + [ (a, rest) + | (text, rest) <- readsPrec @String precision str + , a <- take 1 [a | (a, "") <- readP_to_S (readG grammar) text] + ] diff --git a/src/Control/Lens/Grammar/BackusNaur.hs b/distributors-grammar/src/Control/Lens/Grammar/BackusNaur.hs similarity index 82% rename from src/Control/Lens/Grammar/BackusNaur.hs rename to distributors-grammar/src/Control/Lens/Grammar/BackusNaur.hs index 274d9d4b..8b4146bc 100644 --- a/src/Control/Lens/Grammar/BackusNaur.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/BackusNaur.hs @@ -14,7 +14,7 @@ See Naur & Backus, et al. module Control.Lens.Grammar.BackusNaur ( -- * BackusNaurForm - BackusNaurForm (..) + BackusNaurForm (..), failBnf , Bnf (..) , liftBnf0 , liftBnf1 @@ -23,13 +23,14 @@ module Control.Lens.Grammar.BackusNaur ) where import Control.Lens -import Control.Lens.Grammar.Kleene +import Control.Lens.Grammar.RegEx import Control.Lens.Grammar.Token import Control.Lens.Grammar.Symbol import Data.Bifunctor.Joker import Data.Coerce 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) @@ -38,7 +39,7 @@ import Text.ParserCombinators.ReadP (ReadP) `rule` abstraction and general recursion with `ruleRec`, related by this invariant. -prop> rule label bnf = ruleRec label (\_ -> bnf) +> prop> rule label bnf = ruleRec label (\_ -> bnf) The `BackusNaurForm` interface is reminiscent of two distinct notions of "trace". @@ -51,8 +52,8 @@ in the form of `Data.Profunctor.unfirst` @=@ `Control.Arrow.loop` or equivalently the fixpoint function `fix`, determining default methods for a `BackusNaurForm`. -prop> rule _ = id -prop> ruleRec _ = fix +> prop> rule _ = id +> prop> ruleRec _ = fix The `BackusNaurForm` interface permits overloading these methods, and tracing them with a label. @@ -75,12 +76,16 @@ class BackusNaurForm bnf where ruleRec :: String -> (bnf -> bnf) -> bnf ruleRec _ = fix -{- | A `Bnf` consists of a distinguished starting rule -and a set of named rules. When a `Bnf` supports `NonTerminalSymbol`s, +-- | A nonterminal symbol to indicate a failure. +failBnf :: (BackusNaurForm bnf, DisjunctiveMonoid bnf) => String -> bnf +failBnf msg = rule msg falseP + +{- | A t'Bnf' consists of a distinguished starting rule +and a set of named rules. When a t'Bnf' supports `NonTerminalSymbol`s, then it supports the `BackusNaurForm` interface by replacing recursive calls with `nonTerminal`s. -prop> ruleRec label f = rule label (f (nonTerminal label)) +> prop> ruleRec label f = rule label (f (nonTerminal label)) -} data Bnf rule = Bnf @@ -88,15 +93,15 @@ data Bnf rule = Bnf , rulesBnf :: Set (String, rule) } deriving stock (Eq, Ord, Show, Read) -{- | Lift a rule to a `Bnf`. -} +{- | Lift a rule to a t'Bnf'. -} liftBnf0 :: Ord a => a -> Bnf a liftBnf0 a = Bnf a mempty -{- | Lift a function of rules to `Bnf`s. -} +{- | 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 `Bnf`s. -} +{- | 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 @@ -106,9 +111,9 @@ liftBnf2 f (Bnf start0 rules0) (Bnf start1 rules1) = {- | The [Brzozowski derivative] (https://dl.acm.org/doi/pdf/10.1145/321239.321249) of a -`RegEx`tended `Bnf`, with memoization. +`RegEx`tended t'Bnf', with memoization. -prop> word =~ diffB prefix pattern = prefix <> word =~ pattern +> prop> word =~ diffB prefix pattern = prefix <> word =~ pattern Unfortunately, despite elegance & optimization, Brzozowski's pattern matching algorithm is worst case exponential in grammar size. @@ -123,25 +128,26 @@ diffB prefix (Bnf start rules) = where -- derivative wrt 1 token, memoized diff1B = memo2 $ \x -> \case - SeqEmpty -> zeroK - NonTerminal nameY -> anyK (diff1B x) (rulesNamed nameY rules) - Sequence y1 y2 -> + 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 zeroK + if x `elem` chars then mempty else falseP RegExam (NotOneOf chars (AndAsIn cat)) -> if elem x chars || categorize x /= cat - then zeroK else mempty + then falseP else mempty RegExam (NotOneOf chars (AndNotAsIn cats)) -> if elem x chars || elem (categorize x) cats - then zeroK else mempty - RegExam (Alternate y1 y2) -> diff1B x y1 >|< diff1B x y2 + 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) @@ -152,8 +158,8 @@ diffB prefix (Bnf start rules) = KleeneStar _ -> True KleeneOpt _ -> True KleenePlus y -> ν y - Sequence y1 y2 -> ν y1 && ν y2 - RegExam (Alternate y1 y2) -> ν y1 || ν y2 + Sequence y1 y2 ys -> all ν (y1 : y2 : ys) + RegExam (Alternate y1 y2 ys) -> any ν (y1 : y2 : ys) NonTerminal nameY -> any ν (rulesNamed nameY rules) _ -> False @@ -195,7 +201,9 @@ instance (Ord rule, KleeneStarAlgebra rule) starK = liftBnf1 starK plusK = liftBnf1 plusK optK = liftBnf1 optK - zeroK = liftBnf0 zeroK +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 diff --git a/src/Control/Lens/Grammar/Machine.hs b/distributors-grammar/src/Control/Lens/Grammar/Machine.hs similarity index 94% rename from src/Control/Lens/Grammar/Machine.hs rename to distributors-grammar/src/Control/Lens/Grammar/Machine.hs index 0fb7f508..d2f702bb 100644 --- a/src/Control/Lens/Grammar/Machine.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/Machine.hs @@ -24,8 +24,7 @@ module Control.Lens.Grammar.Machine import Control.Lens import Control.Lens.Extras import Control.Lens.Grammar.BackusNaur -import Control.Lens.Grammar.Boole -import Control.Lens.Grammar.Kleene +import Control.Lens.Grammar.RegEx import Control.Lens.Grammar.Token import Data.Foldable import qualified Data.IntMap.Strict as IntMap @@ -34,6 +33,7 @@ import qualified Data.IntSet as IntSet import Data.IntSet (IntSet) import qualified Data.Map.Strict as Map import Data.Map.Strict (Map) +import Data.Monoid.Disjunctive import qualified Data.Set as Set import Data.Set (Set) import Data.Tree (Tree (..)) @@ -57,13 +57,13 @@ instance Categorized token instance Matching s (APrism s t a b) where word =~ pattern = is pattern word -{-| A `Transducer` is a tuple +{-| A t'Transducer' is a tuple @ T = (Σ, Δ, Q, I ⊆ Q, F ∈ Q, transition ⊆ Q × (Σ ∪ ∆) × Q, output ⊆ Q × ∆) @ -* @Σ@ is a (possibly infinite) set of terminal token classes, represented by `TokenClass`es. +* @Σ@ is a (possibly infinite) set of terminal token classes, represented by t'TokenClass'es. * @Δ@ is a finite set of nonterminals, represented by the key set of `transducerRules`. * @Q@ is a set of states, which is represented by the key set of `transducerRelations`. * @I@ are initial states represented by `transducerStarts`. @@ -80,13 +80,13 @@ data Transducer token = Transducer -- ^ an index into `transducerRelations` for the starting rule } --- | A `TransducerStep` in a `Transducer`. +-- | A `TransducerStep` in a t'Transducer'. data TransducerStep token = TransitionTokenClass (TokenClass token) IntSet | TransitionNonTerminal String IntSet | EmitNonTerminal String -{- | Compile a `RegEx`tended `Bnf` into a `Transducer`, +{- | Compile a `RegEx`tended t'Bnf' into a t'Transducer', using a combination of Thompson's algorithm for regular expressions and Earley's algorithm for context-free grammars. See Jim & Mandelbaum, [Efficient Earley Parsing with Regular Right-hand Sides] @@ -120,11 +120,11 @@ transducer (Bnf start rules) = Transducer rexNullable nm = \case SeqEmpty -> True NonTerminal n -> Set.member n nm - Sequence x y -> rexNullable nm x && rexNullable nm y + Sequence x y zs -> all (rexNullable nm) (x : y : zs) KleeneStar _ -> True KleeneOpt _ -> True KleenePlus x -> rexNullable nm x - RegExam (Alternate x y) -> rexNullable nm x || rexNullable nm y + RegExam (Alternate x y zs) -> any (rexNullable nm) (x : y : zs) RegExam (OneOf _) -> False RegExam (NotOneOf _ _) -> False @@ -180,9 +180,12 @@ transducer (Bnf start rules) = Transducer , nextId + 1 , Set.member name nullSet ) - Sequence rex0 rex1 -> + Sequence rex0 rex1 rexes -> let - (firsts1, states1, nextId1, bypass1) = thompson rex1 nextId dests + rest = case rexes of + [] -> rex1 + rex2 : rexes' -> Sequence rex1 rex2 rexes' + (firsts1, states1, nextId1, bypass1) = thompson rest nextId dests (firsts0, states0, nextId0, bypass0) = thompson rex0 nextId1 (firsts1 <> bypassStates bypass1 dests) in @@ -220,9 +223,12 @@ transducer (Bnf start rules) = Transducer , nextId + 1 , False ) - RegExam (Alternate rex0 rex1) -> + RegExam (Alternate rex0 rex1 rexes) -> let - (firsts1, states1, nextId1, bypass1) = thompson rex1 nextId dests + rest = case rexes of + [] -> rex1 + rex2 : rexes' -> RegExam (Alternate rex1 rex2 rexes') + (firsts1, states1, nextId1, bypass1) = thompson rest nextId dests (firsts0, states0, nextId0, bypass0) = thompson rex0 nextId1 dests in ( firsts0 <> firsts1 @@ -364,15 +370,15 @@ prefixGen et word = go 0 (initialChart et) word _ -> acc {- | What token is expected next? -The scanner frontier, `expectNext` returns the `TokenClass` +The scanner frontier, `expectNext` returns the t'TokenClass' that can be scanned next after the given input prefix. -A `falseB` result means the current chart has no scanner transitions, +A `falseP` result means the current chart has no scanner transitions, i.e. the prefix is a dead end for recognition. -} expectNext :: Categorized token => Transducer token -> [token] {- ^ prefix -} -> TokenClass token -expectNext et word = anyB fst (scanClassOptions et n chart) +expectNext et word = anyP fst (scanClassOptions et n chart) where (n, chart) = prefixGen et word @@ -404,7 +410,7 @@ unreachableRules et = {- | `languageSample` lazily produces all words in a language from shortest to longest. -However since `TokenClass`es can resolve to infinite sets of tokens, +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`. -} diff --git a/distributors-grammar/src/Control/Lens/Grammar/RegEx.hs b/distributors-grammar/src/Control/Lens/Grammar/RegEx.hs new file mode 100644 index 00000000..1246cd55 --- /dev/null +++ b/distributors-grammar/src/Control/Lens/Grammar/RegEx.hs @@ -0,0 +1,254 @@ +{- | +Module : Control.Lens.Grammar.RegEx +Description : regular expressions +Copyright : (C) 2026 - Eitan Chatav +License : BSD-style (see the file LICENSE) +Maintainer : Eitan Chatav +Stability : provisional +Portability : non-portable + +Regular expressions form a Kleene star algebra. See Kleene, +[Representation of Events in Nerve Nets and Finite Automata] +(https://www.rand.org/pubs/research_memoranda/RM704.html) +-} + +module Control.Lens.Grammar.RegEx + ( -- * RegEx + RegEx (..) + ) where + +import Control.Lens.Grammar.Symbol +import Control.Lens.Grammar.Token +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 + +{- | The `RegEx`pression type forms the prototypical `KleeneStarAlgebra`. +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. +-} +data RegEx token + = SeqEmpty + -- | Two or more items, none of them sequences or empty. + | Sequence (RegEx token) (RegEx token) [RegEx token] + | NonTerminal String + | KleeneStar (RegEx token) + | KleeneOpt (RegEx token) + | KleenePlus (RegEx token) + | RegExam (TokenExam token (RegEx 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 + (Categorized token, Read token, Read (Categorize token)) + => Read (RegEx token) +deriving stock instance + (Categorized token, Show token, Show (Categorize token)) + => Show (RegEx token) +instance Categorized 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 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 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) + rex0 >|< rex1 = alternated (alternatives rex0 <> alternatives rex1) +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 exam) | isFailExam exam = mempty + starK SeqEmpty = mempty + starK rex = KleeneStar rex + plusK (RegExam exam) | isFailExam exam = falseP + plusK SeqEmpty = mempty + plusK rex = KleenePlus rex +instance (Categorized token, HasTrie token) + => HasTrie (RegEx token) where + data (RegEx token :->: b) = RegExTrie + { seqEmptyTrie :: b + , nonTerminalTrie :: String :->: b + , sequenceTrie :: [RegEx token] :->: b + , alternateTrie :: [RegEx token] :->: b + , kleeneStarTrie :: RegEx token :->: b + , kleeneOptTrie :: RegEx token :->: b + , kleenePlusTrie :: RegEx token :->: b + , oneOfTrie :: [token] :->: b + , notOneOfTrie :: ([token], Either Int [Int]) :->: b + } + trie f = RegExTrie + { seqEmptyTrie = f mempty + , nonTerminalTrie = trie (f . nonTerminal) + , sequenceTrie = trie (f . mconcat) + , alternateTrie = trie (f . foldr (>|<) falseP) + , kleeneStarTrie = trie (f . starK) + , kleeneOptTrie = trie (f . optK) + , kleenePlusTrie = trie (f . plusK) + , oneOfTrie = trie (f . oneOf) + , notOneOfTrie = trie (f . testNotOneOf) + } + untrie rex = \case + SeqEmpty -> seqEmptyTrie rex + NonTerminal name -> untrie (nonTerminalTrie rex) name + Sequence x y zs -> untrie (sequenceTrie rex) (x : y : zs) + KleeneStar x -> untrie (kleeneStarTrie rex) x + KleenePlus x -> untrie (kleenePlusTrie rex) x + KleeneOpt x -> untrie (kleeneOptTrie 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)) + 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) + , first' mconcat <$> enumerate (sequenceTrie rex) + , first' (foldr (>|<) falseP) <$> enumerate (alternateTrie rex) + , first' KleeneStar <$> enumerate (kleeneStarTrie rex) + , first' KleeneOpt <$> enumerate (kleeneOptTrie rex) + , first' KleenePlus <$> enumerate (kleenePlusTrie 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] +items = \case + SeqEmpty -> [] + Sequence rex0 rex1 rexes -> rex0 : rex1 : rexes + rex -> [rex] + +{- | Items, normalized: any which fails fails, & runs of a repeated item, +@b@, whose items are @B@, are rewritten until none apply, by + +* @B b*@ & @b* B@ to @b+@, +* @b* b*@ to @b*@, & @b+ b*@ & @b* b+@ to @b+@, +* @b+ B@ to @B b+@, & @b+ b+@ to @B b+@, + +so that sequences of sequences are associative. +-} +sequenced :: Categorized token => [RegEx token] -> RegEx token +sequenced rexes + | any isFail rexes = falseP + | otherwise = case rewrite rexes of + [] -> SeqEmpty + [rex] -> rex + rex0 : rex1 : rexes' -> Sequence rex0 rex1 rexes' + where + isFail = \case + RegExam exam -> isFailExam exam + _ -> False + rewrite xs = maybe xs rewrite (step xs) + step = \case + [] -> Nothing + xs@(x : rest) -> case once xs of + Just xs' -> Just xs' + Nothing -> (x :) <$> step rest + -- a rule applying at the start of the items + once = \case + KleeneStar b : KleeneStar b' : rest | b == b' -> + Just (KleeneStar b : rest) + KleenePlus b : KleeneStar b' : rest | b == b' -> + Just (KleenePlus b : rest) + KleeneStar b : KleenePlus b' : rest | b == b' -> + Just (KleenePlus b : rest) + KleenePlus b : KleenePlus b' : rest | b == b' -> + Just (items b <> (KleenePlus b : rest)) + KleeneStar b : rest | not (null (items b)) + , Just rest' <- after (items b) rest -> + Just (KleenePlus b : rest') + KleenePlus b : rest | not (null (items b)) + , Just rest' <- after (items b) rest -> + Just (items b <> (KleenePlus b : rest')) + xs | Just (b, rest) <- starred xs -> Just (KleenePlus b : rest) + _ -> Nothing + -- the rest of the items after a prefix of them + after prefix xs + | prefix == take (length prefix) xs = Just (drop (length prefix) xs) + | otherwise = Nothing + -- items which a repetition of them follows + starred xs = case [ (b, rest) + | n <- [1 .. length xs - 1] + , KleeneStar b : rest <- [drop n xs] + , items b == take n xs + ] of + found : _ -> Just found + [] -> Nothing + +-- | The alternatives of an alternation, with the empty word for an option. +alternatives :: RegEx token -> [RegEx token] +alternatives = \case + 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] + +{- | Alternatives, normalized: those of tokens are one t'TokenClass', +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 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') + where + unionTokens xs = case [cls | x <- xs, Just cls <- [tokenOf x]] of + [] -> xs + classes -> + placeFirst (alternatives (tokenClass (foldr1 (>|<) classes))) xs + placeFirst union = \case + x : rest | Just _ <- tokenOf x -> + union <> [y | y <- rest, Nothing <- [tokenOf y]] + x : rest -> x : placeFirst union rest + [] -> [] + tokenOf = \case + RegExam (OneOf tokens') -> Just (TokenClass (OneOf tokens')) + RegExam (NotOneOf tokens' test) -> + Just (TokenClass (NotOneOf tokens' test)) + _ -> Nothing + diff --git a/src/Control/Lens/Grammar/Symbol.hs b/distributors-grammar/src/Control/Lens/Grammar/Symbol.hs similarity index 75% rename from src/Control/Lens/Grammar/Symbol.hs rename to distributors-grammar/src/Control/Lens/Grammar/Symbol.hs index a36ec396..e19789d8 100644 --- a/src/Control/Lens/Grammar/Symbol.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/Symbol.hs @@ -12,13 +12,17 @@ module Control.Lens.Grammar.Symbol ( -- * Symbol TerminalSymbol (..) , NonTerminalSymbol (..) + -- * Separators + , sepWith ) where import Control.Lens import Control.Lens.PartialIso import Control.Lens.Grammar.Token +import Control.Lens.Prismoid (Prismoid, sepBy) import Data.Bifunctor.Joker import Data.Profunctor +import Data.Profunctor.Distributor (Alternator) import Data.Profunctor.Monoidal import Text.ParserCombinators.ReadP (ReadP, string) @@ -30,6 +34,16 @@ class TerminalSymbol token s | s -> token where => [token] -> s terminal str = only str ?< tokens str +{- | `sepBy` a `terminal` separator, so a grammar separates foci +of a `Prismoid` by symbols. + +> prop> sepWith str = sepBy (terminal str) +-} +sepWith + :: (Alternator p, TerminalSymbol c (p () ())) + => [c] -> Prismoid s t a b -> p a b -> p s t +sepWith = sepBy . terminal + -- | A `nonTerminal` symbol in a grammar. class NonTerminalSymbol s where nonTerminal :: String -> s diff --git a/distributors-grammar/src/Control/Lens/Grammar/Token.hs b/distributors-grammar/src/Control/Lens/Grammar/Token.hs new file mode 100644 index 00000000..95905283 --- /dev/null +++ b/distributors-grammar/src/Control/Lens/Grammar/Token.hs @@ -0,0 +1,429 @@ +{- | +Module : Control.Lens.Grammar.Token +Description : lexical tokens +Copyright : (C) 2026 - Eitan Chatav +License : BSD-style (see the file LICENSE) +Maintainer : Eitan Chatav +Stability : provisional +Portability : non-portable +-} + +module Control.Lens.Grammar.Token + ( -- * Tokenized + Tokenized (..) + , satisfy + , tokens + -- * Categorized + , Categorized (..) + , GeneralCategory (..) + -- * TokenAlgebra + , TokenAlgebra (..) + , TokenClass (..) + , foldTokenClass + , TokenExam (..) + , CategoryTest (..) + ) where + +import Control.Lens +import Control.Lens.PartialIso +import Control.Monad.Loops (iterateUntil) +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.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) +import Test.QuickCheck.Arbitrary +import Test.QuickCheck.Gen (Gen) +import qualified Test.QuickCheck.Gen as Gen +import Text.ParserCombinators.ReadP (ReadP) +import qualified Text.ParserCombinators.ReadP as ReadP + +{- | `Categorized` provides a type family `Categorize` +and a function to `categorize` tokens into disjoint categories. + +>>> :kind! Categorize Char +Categorize Char :: * += GeneralCategory + +>>> categorize 'a' +LowercaseLetter +-} +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. -} + anyToken :: p + + {- | A single specified `token`. -} + token :: token -> p + 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 + 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> anyToken = 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 + + {- | 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 >?< anyToken + +{- | A specified stream of `tokens`. -} +tokens + :: ( Foldable f, Tokenized a (p a a) + , Monoidal p, Choice p + , AsEmpty s, Cons s s a a + ) + => f a -> p s s +tokens = foldr ((>:<) . token) asEmpty + +-- instances +instance Categorized token => Tokenized token (token -> Bool) where + anyToken _ = 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 . (/=) +instance Tokenized token (f token) + => Tokenized token (Joker f token token) where + anyToken = Joker (anyToken @token) + token = Joker . token @token + oneOf = Joker . oneOf @token + notOneOf = Joker . notOneOf @token + asIn = Joker . asIn @token + notAsIn = Joker . notAsIn @token +instance Tokenized Char (ReadP Char) where + anyToken = ReadP.get + token = ReadP.char + oneOf = ReadP.satisfy . oneOf + notOneOf = ReadP.satisfy . notOneOf + asIn = ReadP.satisfy . asIn + notAsIn = ReadP.satisfy . notAsIn +instance (Categorized token, Arbitrary token) => Tokenized token (Gen token) where + anyToken = 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) +instance (RandomGen g, Monad m, Categorized token, Random token) + => Tokenized token (StateT g m token) where + 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) + +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. +-} +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 (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)) + +{- | 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 (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/src/Control/Monad/Fail/Try.hs b/distributors-grammar/src/Control/Monad/Fail/Try.hs similarity index 80% rename from src/Control/Monad/Fail/Try.hs rename to distributors-grammar/src/Control/Monad/Fail/Try.hs index 48fa94a3..e2bbb273 100644 --- a/src/Control/Monad/Fail/Try.hs +++ b/distributors-grammar/src/Control/Monad/Fail/Try.hs @@ -11,6 +11,7 @@ Portability : non-portable module Control.Monad.Fail.Try ( -- * MonadTry MonadTry (..) + , MonadicTry -- * MonadFail , MonadFail (..) -- * MonadPlus @@ -26,20 +27,21 @@ 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 +> 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 +> prop> fail label = rule label empty -} class @@ -49,12 +51,15 @@ class {- | A handler for failures. Used for backtracking state on failure in - `Data.Profunctor.Grammar.Parsector.Parsector`. + 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/src/Data/Profunctor/Grammar.hs b/distributors-grammar/src/Data/Profunctor/Grammar.hs similarity index 74% rename from src/Data/Profunctor/Grammar.hs rename to distributors-grammar/src/Data/Profunctor/Grammar.hs index ee88cc91..507a6cec 100644 --- a/src/Data/Profunctor/Grammar.hs +++ b/distributors-grammar/src/Data/Profunctor/Grammar.hs @@ -26,7 +26,6 @@ import Control.Category import Control.Lens import Control.Lens.Extras import Control.Lens.Grammar.BackusNaur -import Control.Lens.Grammar.Kleene import Control.Lens.Grammar.Machine import Control.Lens.Grammar.Symbol import Control.Lens.Grammar.Token @@ -34,15 +33,18 @@ import Control.Monad import Control.Monad.Fail.Try import Data.Coerce import Data.Monoid +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 --- | `Printor` is a simple printer `Profunctor`. +-- | 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 @@ -51,7 +53,7 @@ newtype Printor s f a b = Printor {runPrintor :: a -> f (b, s -> s)} printP :: Functor f => Printor s f a b -> a -> f (s -> s) printP (Printor f) = fmap snd . f --- | `Parsor` is a simple invertible parser `Profunctor`. +-- | t'Parsor' is a simple invertible parser `Profunctor`. newtype Parsor s f a b = Parsor {runParsor :: Maybe a -> s -> f (b,s)} -- | Run the parser on an input string, @@ -66,7 +68,7 @@ parseP (Parsor f) = f Nothing unparseP :: Functor f => Parsor s f a b -> a -> s -> f s unparseP (Parsor f) a = fmap snd . f (Just a) --- | `Grammor` is a constant `Profunctor`. +-- | t'Grammor' is a constant `Profunctor`. newtype Grammor k a b = Grammor {runGrammor :: k} -- Parsor instances @@ -87,6 +89,8 @@ instance Monad m => Monad (Parsor s m a) where Parsor p >>= f = Parsor $ \ma s -> do (a, s') <- p ma s runParsor (f a) ma s' +instance MonadicTrans (Parsor s) where + liftP mb = Parsor (\_ s -> (, s) <$> mb) instance (Alternative m, Monad m) => Alternative (Parsor s m a) where empty = Parsor (\_ _ -> empty) Parsor p <|> Parsor q = Parsor $ \ma s -> p ma s <|> q ma s @@ -106,11 +110,35 @@ instance Filterable f => Filtrator (Parsor s f) where (\case{(Right b,t) -> Just (b,t); _ -> Nothing}) (p (fmap Right ma) s) ) -instance (Alternative m, Monad m) => Distributor (Parsor s m) +instance (Alternative m, Monad m) => CocartesianMonoidal (Parsor s m) +{- | `manyP` & `optionalP` parse & print their elements in turn, +rather than through isomorphisms & sums, parsing more before fewer. +-} +instance (Alternative m, Monad m) => Distributor (Parsor s m) where + manyP (Parsor p) = Parsor $ \ma s -> case ma of + Nothing -> parsing s + Just as -> printing as s + where + parsing s = + (do + (b, s') <- p Nothing s + (bs, s'') <- parsing s' + pure (b : bs, s'')) + <|> pure ([], s) + printing [] s = pure ([], s) + printing (a : as) s = do + (b, s') <- p (Just a) s + (bs, s'') <- printing as s' + pure (b : bs, s'') + optionalP (Parsor p) = Parsor $ \ma s -> case ma of + Nothing -> fmap (first' Just) (p Nothing s) <|> pure (Nothing, s) + Just Nothing -> pure (Nothing, s) + Just (Just a) -> fmap (first' Just) (p (Just a) s) instance (Alternative m, Monad m) => Choice (Parsor s m) where left' = alternate . Left right' = alternate . Right -instance (Alternative m, Monad m) => Alternator (Parsor s m) where +instance (Alternative m, Monad m) => DisjunctiveMonoid (Parsor s m a b) +instance (Alternative m, Monad m) => CocartesianChoice (Parsor s m) where alternate = \case Left (Parsor p) -> Parsor $ \ma s -> case ma of Nothing -> fmap (first' Left) (p Nothing s) @@ -120,6 +148,7 @@ instance (Alternative m, Monad m) => Alternator (Parsor s m) where Nothing -> fmap (first' Right) (p Nothing s) Just (Right a) -> fmap (first' Right) (p (Just a) s) Just (Left _) -> empty +instance (Alternative m, Monad m) => Alternator (Parsor s m) where optionP def p = Parsor $ \ma s -> case ma of Nothing -> runParsor (p <|> pureP def) ma s Just _ -> runParsor (pureP def <|> p) ma s @@ -192,7 +221,9 @@ instance AsEmpty s => Matching s (Parsor s [] a b) where 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 . dimap f (fmap (first' g)) . runPrintor + 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 -> @@ -210,16 +241,30 @@ instance Monad f => Monad (Printor s f a) where (b,h) <- runPrintor (f a1) a return (b, g . h) instance (Alternative f, Monad f) => MonadPlus (Printor s f a) -instance Applicative f => Distributor (Printor s f) where +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) -instance Alternative f => Alternator (Printor s f) where +{- | `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) = @@ -268,19 +313,34 @@ 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) -instance - ( Categorized a, a ~ Item s, IsList s, Cons s s a a - , Filterable m, Alternative m, Monad m - ) => TerminalSymbol a (Printor s m () ()) where -instance - ( Char ~ Item s, IsList s, Cons s s Char Char - , Filterable m, Alternative m, Monad m - ) => IsString (Printor s m () ()) where + ) => 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 @@ -304,20 +364,24 @@ instance Choice (Grammor k) where instance Monoid k => Applicative (Grammor k a) where pure _ = Grammor mempty Grammor rex1 <*> Grammor rex2 = Grammor (rex1 <> rex2) +instance DisjunctiveMonoid k => DisjunctiveMonoid (Grammor k a b) where + falseP = Grammor falseP + Grammor rex1 >|< Grammor rex2 = Grammor (rex1 >|< rex2) instance KleeneStarAlgebra k => Alternative (Grammor k a) where - empty = Grammor zeroK - Grammor rex1 <|> Grammor rex2 = Grammor (rex1 >|< rex2) - many (Grammor rex) = Grammor (starK rex) - some (Grammor rex) = Grammor (plusK rex) + empty = falseP + (<|>) = (>|<) + many = lmap repeat . manyP + some = lmap repeat . someP +instance KleeneStarAlgebra k => CocartesianMonoidal (Grammor k) +instance KleeneStarAlgebra k => CocartesianChoice (Grammor k) where + alternate = either coerce coerce instance KleeneStarAlgebra k => Distributor (Grammor k) where - zeroP = Grammor zeroK - Grammor rex1 >+< Grammor rex2 = Grammor (rex1 >|< rex2) manyP (Grammor rex) = Grammor (starK rex) optionalP (Grammor rex) = Grammor (optK rex) instance KleeneStarAlgebra k => Alternator (Grammor k) where - alternate = either coerce coerce someP (Grammor rex) = Grammor (plusK rex) optionP _ (Grammor rex) = Grammor (optK rex) + manyTillP (Grammor rex) (Grammor rest) = Grammor (starK rex <> rest) instance Tokenized token k => Tokenized token (Grammor k a b) where anyToken = Grammor anyToken token = Grammor . token diff --git a/src/Data/Profunctor/Grammar/Parsector.hs b/distributors-grammar/src/Data/Profunctor/Grammar/Parsector.hs similarity index 63% rename from src/Data/Profunctor/Grammar/Parsector.hs rename to distributors-grammar/src/Data/Profunctor/Grammar/Parsector.hs index bf00e228..2f6cf602 100644 --- a/src/Data/Profunctor/Grammar/Parsector.hs +++ b/distributors-grammar/src/Data/Profunctor/Grammar/Parsector.hs @@ -27,30 +27,31 @@ import Control.Category import Data.Function (fix) import Control.Lens import Control.Lens.Grammar.BackusNaur -import Control.Lens.Grammar.Boole -import Control.Lens.Grammar.Kleene 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 ((#.), (.#)) import Data.Profunctor.Distributor +import Data.Profunctor.Monoidal.Cocartesian import Data.Profunctor.Filtrator import Data.Profunctor.Monoidal import Data.Tree import GHC.Exts import Prelude hiding (id, (.)) -{- | `Parsector` is an invertible @LL(1)@ parser which is intended +{- | t'Parsector' is an invertible @LL(1)@ parser which is intended to provide detailed failure information, based on [Parsec] (https://www.microsoft.com/en-us/research/wp-content/uploads/2016/02/parsec-paper-letter.pdf). -} newtype Parsector s a b = Parsector {runParsector :: forall x. (ParsecState s b -> x) -> ParsecState s a -> x} -{- | Run `Parsector` as a parser: consume tokens from @s@, -left to right, returning a `ParsecState` whose `parsecResult` +{- | Run t'Parsector' as a parser: consume tokens from @s@, +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) @@ -59,9 +60,9 @@ parsecP -> ParsecState s b parsecP p s = runParsector p id (ParsecState False 0 s mempty Nothing) -{- | Run `Parsector` as a printer: given a syntax value @a@ and +{- | Run t'Parsector' as a printer: given a syntax value @a@ and an input stream, append tokens to @s@ left to right, -returning a `ParsecState` whose `parsecResult` is +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 @@ -72,13 +73,13 @@ unparsecP -> ParsecState s b unparsecP p a s = runParsector p id (ParsecState False 0 s mempty (Just a)) -{- | `ParsecState` is both the input and output type of the -underlying function inside `Parsector`. +{- | t'ParsecState' is both the input and output type of the +underlying function inside t'Parsector'. @Parsector s a b@ is equivalent to @ParsecState s a -> ParsecState s b@ -So `ParsecState` has a dual interpretation as input and output. -} +So t'ParsecState' has a dual interpretation as input and output. -} data ParsecState s a = ParsecState { parsecLooked :: !Bool {- ^ `True` once the parser has consumed/produced at least one token @@ -91,7 +92,7 @@ data ParsecState s a = ParsecState -- ^ Number of tokens consumed from the start of the stream. , parsecStream :: s -- ^ stream , parsecFailure :: ParsecFailure s - {- ^ `ParsecFailure` channel. + {- ^ t'ParsecFailure' channel. * If `parsecResult` is `Nothing`, this is the hard failure. * If `parsecResult` is `Just`, this is deferred failure/hint info @@ -110,16 +111,16 @@ data ParsecState s a = ParsecState -} } -{- | `ParsecFailure` is the failure payload produced by `Parsector`, +{- | t'ParsecFailure' is the failure payload produced by t'Parsector', stored in `parsecFailure`. -`ParsecFailure` is a `Monoid` and `Parsector` merges failures/hints +t'ParsecFailure' is a `Monoid` and t'Parsector' merges failures/hints when control flow reaches the same offset without commitment. -} data ParsecFailure s = ParsecFailure { parsecExpect :: TokenClass (Item s) {- ^ Class of expected token `Item`s at the `parsecOffset`. `tokenClass`es and `Tokenized` combinators specify expectations. - Under `<>`, expectations are combined with disjunction `>||<`. + Under `<>`, expectations are combined with disjunction `>|<`. In case of a parse failure, contrast with the actual `parsecStream`, which is either unexpectedly empty or begins with an unexpected token. -} @@ -144,9 +145,9 @@ deriving stock instance 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) + ParsecFailure e1 l1 <> ParsecFailure e2 l2 = ParsecFailure (e1 >|< e2) (l1 ++ l2) instance Categorized (Item s) => Monoid (ParsecFailure s) where - mempty = ParsecFailure falseB [] + mempty = ParsecFailure falseP [] -- ParsecState instances deriving stock instance Functor (ParsecState s) @@ -186,33 +187,40 @@ instance ( Categorized token, Item s ~ token , Cons s s token token, Snoc s s token token ) => TokenAlgebra token (Parsector s token token) where - tokenClass test = Parsector $ \callback query -> + {-# 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 stream = parsecStream query mode = parsecResult query offset = parsecOffset query replyOk tok str = query { parsecLooked = True - , parsecFailure = mempty + , parsecFailure = noFailure , parsecStream = str , parsecOffset = offset + 1 , parsecResult = Just tok } replyErr = query - { parsecFailure = ParsecFailure test [] + { parsecFailure = failure , parsecResult = Nothing } in callback $ case mode of -- print mode Just tok - | tokenClass test tok -> replyOk tok (snoc stream tok) + | matches tok -> replyOk tok (snoc stream tok) | otherwise -> replyErr -- parse mode Nothing -> case uncons stream of Just (tok, rest) - | tokenClass test tok -> replyOk tok rest + | matches tok -> replyOk tok rest | otherwise -> replyErr - Nothing -> replyErr + Nothing -> replyErr) + where + matches :: token -> Bool + matches = tokenClass test + noFailure = mempty + failure = ParsecFailure test [] instance BackusNaurForm (Parsector s a b) where -- | Wraps inner `parsecLabels` in a new `Node name` on failure. -- Has no effect on success. @@ -229,13 +237,55 @@ instance BackusNaurForm (Parsector s a b) where instance ( Categorized token, Item s ~ token , Cons s s token token, Snoc s s token token - ) => TerminalSymbol token (Parsector s () ()) + ) => TerminalSymbol token (Parsector s () ()) where + {-# SPECIALISE instance TerminalSymbol Char (Parsector String () ()) #-} + {- | Like @only str ?< tokens str@, checking its tokens in one loop, + failing without consuming at the first token, and committed after. + -} + terminal str = Parsector $ \callback query -> callback $ + case str of + [] -> query {parsecResult = Just ()} + _ -> go str query + where + go [] state = state {parsecResult = Just ()} + go (tok : rest) state = + let + next str' = state + { parsecLooked = True + , parsecFailure = mempty + , parsecStream = str' + , parsecOffset = parsecOffset state + 1 + } + failure = state + { parsecFailure = ParsecFailure (token tok) [] + , parsecResult = Nothing + } + in + case parsecResult state of + Just () -> go rest (next (snoc (parsecStream state) tok)) + Nothing -> case uncons (parsecStream state) of + Just (tok', str') | tok' == tok -> go rest (next str') + _ -> failure +instance + ( Item s ~ Char + , Cons s s Char Char, Snoc s s Char Char + , x ~ (), y ~ () + ) => IsString (Parsector s x y) where + fromString = terminal instance Functor (Parsector s a) where fmap = rmap instance Categorized (Item s) => Applicative (Parsector s a) where pure b = Parsector $ \callback query -> callback query { parsecResult = Just b } - (<*>) = ap + (<*>) = liftA2 id + -- | Like `>>=`, without a continuation of the first result. + liftA2 f p q = Parsector $ \callback query -> + flip (runParsector p) query $ \reply -> + case parsecResult reply of + Nothing -> callback reply { parsecResult = Nothing } + Just b -> + flip (runParsector q) (bound query reply) $ \qReply -> + callback (rebound reply (f b <$> qReply)) instance Categorized (Item s) => Monad (Parsector s a) where return = pure @@ -244,21 +294,32 @@ instance Categorized (Item s) => Monad (Parsector s a) where case parsecResult reply of Nothing -> callback reply { parsecResult = Nothing } Just b -> - let - hintP = parsecFailure reply - fQuery = reply - { parsecLooked = False - , parsecFailure = mempty - , parsecResult = parsecResult query - } - in - flip (runParsector (f b)) fQuery $ \fReply -> callback $ - if parsecLooked fReply - then fReply - else fReply - { parsecLooked = parsecLooked reply - , parsecFailure = hintP <> parsecFailure fReply - } + flip (runParsector (f b)) (bound query reply) $ \fReply -> + callback (rebound reply fReply) + +-- | The query of the second of a sequence, after the first's reply. +bound + :: Categorized (Item s) + => ParsecState s a -> ParsecState s b -> ParsecState s a +bound query reply = reply + { parsecLooked = False + , parsecFailure = mempty + , parsecResult = parsecResult query + } + +{- | The reply of a sequence, from the first's & the second's replies, +which keeps the first's hints when the second hasn't consumed. +-} +rebound + :: Categorized (Item s) + => ParsecState s b -> ParsecState s c -> ParsecState s c +rebound reply next + | parsecLooked next = next + | otherwise = next + { parsecLooked = parsecLooked reply + , parsecFailure = parsecFailure reply <> parsecFailure next + } + instance Categorized (Item s) => Alternative (Parsector s a) where -- | Always fails without consuming input; expects nothing. empty = Parsector $ \callback query -> @@ -317,8 +378,13 @@ instance Categorized (Item s) => ArrowChoice (Parsector s) where left = left' right = right' instance Profunctor (Parsector s) where - dimap f g (Parsector p) = Parsector $ - dimap (lmap (fmap g)) (lmap (fmap f)) p + dimap f g (Parsector p) = Parsector $ \callback query -> + p (callback . fmap g) (fmap f query) + lmap f (Parsector p) = Parsector $ \callback query -> + p callback (fmap f query) + rmap g (Parsector p) = Parsector $ \callback -> p (callback . fmap g) + (#.) _ = coerce + p .# _ = coerce p instance Strong (Parsector s) where first' p = Parsector $ \callback reply0 -> flip (runParsector p) (fst <$> reply0) $ \reply1 -> @@ -334,11 +400,74 @@ instance Strong (Parsector s) where <$> (fst <$> parsecResult reply0) <*> parsecResult reply1 } +-- | Like `alternate`, without a sum of branches. instance Categorized (Item s) => Choice (Parsector s) where - left' = alternate . Left - right' = alternate . Right -instance Categorized (Item s) => Distributor (Parsector s) -instance Categorized (Item s) => Alternator (Parsector s) where + left' (Parsector p) = Parsector $ \callback query -> + case parsecResult query of + Just (Right _) -> + callback query { parsecFailure = mempty, parsecResult = Nothing } + result -> p (callback . fmap Left) + query { parsecResult = either Just (const Nothing) =<< result } + right' (Parsector p) = Parsector $ \callback query -> + case parsecResult query of + Just (Left _) -> + 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 + {- | 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. + -} + manyP (Parsector p) = Parsector $ \callback query -> + let + -- the first element is tried on the query itself + parsedFirst reply = case parsecResult reply of + Just b -> parsedRest [b] reply + Nothing + | parsecLooked reply -> callback reply {parsecResult = Nothing} + | otherwise -> callback query + { parsecResult = Just [] + , parsecFailure = parsecFailure reply <> parsecFailure query + } + -- the rest are tried after the reply to the last + parsedRest bs reply = p + (\next -> case parsecResult next of + Just b -> parsedRest (b : bs) next + Nothing -> ended False bs reply next) + (afresh reply) {parsecResult = Nothing} + printedFirst as reply = case parsecResult reply of + Just b -> printedRest [b] as reply + Nothing -> callback reply {parsecResult = Nothing} + printedRest bs as reply = case as of + [] -> callback reply {parsecResult = Just (reverse bs)} + a : as' -> p + (\next -> case parsecResult next of + Just b -> printedRest (b : bs) as' next + Nothing -> ended True bs reply next) + (afresh reply) {parsecResult = Just a} + {- an element failed after the last one's reply, ending a parsed list, + or failing a printed one, unless it was committed -} + ended printing bs reply next + | parsecLooked next = callback next {parsecResult = Nothing} + | printing = callback next + { parsecLooked = parsecLooked reply + , parsecFailure = parsecFailure reply <> parsecFailure next + , parsecResult = Nothing + } + | otherwise = callback reply + { parsecFailure = parsecFailure reply <> parsecFailure next + , parsecResult = Just (reverse bs) + } + afresh reply = reply {parsecLooked = False, parsecFailure = mempty} + in + case parsecResult query of + 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 alternate (Left p) = Parsector $ \callback query -> callback $ let replyOk = query @@ -369,6 +498,7 @@ instance Categorized (Item s) => Alternator (Parsector s) where _________________ -> flip (runParsector p) replyOk $ \reply -> reply { parsecResult = fmap Right (parsecResult reply) } +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 diff --git a/test/Examples/Arithmetic.hs b/distributors-grammar/test/Examples/Arithmetic.hs similarity index 81% rename from test/Examples/Arithmetic.hs rename to distributors-grammar/test/Examples/Arithmetic.hs index f7ee1bb6..27046118 100644 --- a/test/Examples/Arithmetic.hs +++ b/distributors-grammar/test/Examples/Arithmetic.hs @@ -4,7 +4,6 @@ module Examples.Arithmetic , arithExamples ) where -import Control.Applicative import Control.Lens import Control.Lens.Grammar import Numeric.Natural @@ -21,11 +20,11 @@ arithGrammar :: Grammar Char Arith arithGrammar = ruleRec "arith" sumG where sumG arith = rule "sum" $ - chain1 Left _Add (sepWith "+") (prodG arith) + sepWith "+" (chain1 Left _Add) (prodG arith) prodG arith = rule "product" $ - chain1 Left _Mul (sepWith "*") (factorG arith) + sepWith "*" (chain1 Left _Mul) (factorG arith) factorG arith = rule "factor" $ - number <|> terminal "(" >* arith *< terminal ")" + number >|< terminal "(" >* arith *< terminal ")" number = rule "number" $ _Num . iso show read >? someP (asIn @Char DecimalNumber) diff --git a/test/Examples/Chain.hs b/distributors-grammar/test/Examples/Chain.hs similarity index 79% rename from test/Examples/Chain.hs rename to distributors-grammar/test/Examples/Chain.hs index 1b54285a..8c397264 100644 --- a/test/Examples/Chain.hs +++ b/distributors-grammar/test/Examples/Chain.hs @@ -4,7 +4,6 @@ module Examples.Chain , chainExamples ) where -import Control.Applicative import Control.Lens import Control.Lens.Grammar @@ -20,11 +19,11 @@ chainGrammar :: Grammar Char Chain chainGrammar = ruleRec "chain" seqG where seqG chn = rule "seq" $ - chain Left _Seq _Emp noSep (atomG chn) + chain Left _Seq _Emp >?* atomG chn atomG chn = rule "atom" $ - _Char >? charG <|> terminal "(" >* chn *< terminal ")" + _Char >? charG >|< terminal "(" >* chn *< terminal ")" charG = notOneOf "()\\" - <|> terminal "\\" >* oneOf "()\\" + >|< terminal "\\" >* oneOf "()\\" chainExamples :: [(Chain, String)] chainExamples = diff --git a/test/Examples/Expression.hs b/distributors-grammar/test/Examples/Expression.hs similarity index 94% rename from test/Examples/Expression.hs rename to distributors-grammar/test/Examples/Expression.hs index ba237aa9..0f626c10 100644 --- a/test/Examples/Expression.hs +++ b/distributors-grammar/test/Examples/Expression.hs @@ -8,7 +8,6 @@ module Examples.Expression , leftExamples ) where -import Control.Applicative import Control.Lens import Control.Lens.Grammar import Numeric.Natural @@ -37,7 +36,7 @@ exprGrammar :: Grammar Char Expr exprGrammar = ruleRec "expr" $ \expr -> let atom = rule "atom" $ - nat <|> terminal "(" >* expr *< terminal ")" + nat >|< terminal "(" >* expr *< terminal ")" nat = rule "nat" $ _Nat . iso show read >? someP (asIn @Char DecimalNumber) in withOperators @@ -73,10 +72,10 @@ powGrammar :: Grammar Char Expr powGrammar = ruleRec "pow" $ \e -> let atom = rule "atom" $ - nat <|> terminal "(" >* e *< terminal ")" + nat >|< terminal "(" >* e *< terminal ")" nat = rule "nat" $ _Nat . iso show read >? someP (asIn @Char DecimalNumber) - in chain1 (\x -> Right x) _Exp (sepWith "^") atom + in sepWith "^" (chain1 Right _Exp) atom powExamples :: [(Expr, String)] powExamples = @@ -93,7 +92,7 @@ leftGrammar :: Grammar Char Expr leftGrammar = ruleRec "expr" $ \expr -> let atom = rule "atom" $ - nat <|> terminal "(" >* expr *< terminal ")" + nat >|< terminal "(" >* expr *< terminal ")" nat = rule "nat" $ _Nat . iso show read >? someP (asIn @Char DecimalNumber) in withOperators diff --git a/distributors-grammar/test/Examples/Heredoc.hs b/distributors-grammar/test/Examples/Heredoc.hs new file mode 100644 index 00000000..0fb9de08 --- /dev/null +++ b/distributors-grammar/test/Examples/Heredoc.hs @@ -0,0 +1,50 @@ +module Examples.Heredoc + ( Heredoc (..) + , heredocP + , heredocG + , heredocExamples + ) where + +import Control.Lens.Grammar + +-- | A heredoc, @< tag : body ++ [tag]) + (\case + tag : rest -> Heredoc tag (if null rest then [] else init rest) + [] -> Heredoc "" []) + +-- | Heredocs, by their lines, `delimitBy` by their tag, +-- a context-sensitive grammar, which needs a `Varifocal`. +heredocP + :: forall p m. + ( MonadicTrans p, Alternator (p m), MonadPlus m, Filterable m + , Tokenized Char (p m Char Char), TerminalSymbol Char (p m () ()) ) + => p m Heredoc Heredoc +heredocP = heredocLines >~ symbol "<<" >* contextuallyT (delimitBy (==)) lineP + where + symbol :: String -> p m () () + symbol = terminal + lineP = manyP (notOneOf "\n") *< symbol "\n" + +-- | Heredocs as a `CtxGrammar`, applying `delimitBy` `contextually`, +-- so it runs as any `CtxGrammar` does, by `Parsector` too. +heredocG :: CtxGrammar Char Heredoc +heredocG = heredocLines >~ terminal "<<" >* contextually (delimitBy (==)) lineG + where + lineG = manyP (notOneOf "\n") *< terminal "\n" + +heredocExamples :: [(Heredoc, String)] +heredocExamples = + [ (Heredoc "EOF" ["hello", "world"], "<* valueG json *< ws -- value = object | array | string | number | "true" | "false" | "null" - valueG json = rule "value" $ choice + valueG json = rule "value" $ orP [ _JNull >? terminal "null" , _JBool . only True >? terminal "true" , _JBool . only False >? terminal "false" @@ -49,7 +48,7 @@ jsonGrammar = rule "json" elementG ] -- object = '{' ws '}' | '{' members '}' - objectG json = rule "object" $ choice + objectG json = rule "object" $ orP [ only Map.empty >? terminal "{" >* ws >* terminal "}" , iso Map.toList Map.fromList >~ @@ -58,21 +57,21 @@ jsonGrammar = rule "json" elementG -- members = member | member ',' members membersG json = rule "members" $ - several1 (sepWith ",") (memberG json) + sepWith "," (atLeast 1) (memberG json) -- member = ws string ws ':' element memberG json = rule "member" $ ws >* stringG *< ws *< terminal ":" >*< json -- array = '[' ws ']' | '[' elements ']' - arrayG json = rule "array" $ choice + arrayG json = rule "array" $ orP [ only [] >? terminal "[" >* ws >* terminal "]" , terminal "[" >* elementsG json *< terminal "]" ] -- elements = element | element ',' elements elementsG json = rule "elements" $ - several1 (sepWith ",") json + sepWith "," (atLeast 1) json -- string = '"' characters '"' stringG = rule "string" $ @@ -80,11 +79,11 @@ jsonGrammar = rule "json" elementG -- character = '0020' . '10FFFF' - '"' - '\' | '\' escape characterG = rule "character" $ - tokenClass (oneOf ['\x0020' .. '\x10FFFF'] >&&< notOneOf ['\"','\\']) - <|> terminal "\\" >* escapeG + tokenClass (oneOf ['\x0020' .. '\x10FFFF'] >&< notOneOf ['\"','\\']) + >|< terminal "\\" >* escapeG -- escape = '"' | '\' | '/' | 'b' | 'f' | 'n' | 'r' | 't' - escapeG = rule "escape" $ choice + escapeG = rule "escape" $ orP [ only '"' >? terminal "\"" , only '\\' >? terminal "\\" , only '/' >? terminal "/" @@ -101,7 +100,7 @@ jsonGrammar = rule "json" elementG -- Simplified: zero or more whitespace characters ws = rule "ws" $ - iso (\() -> "") (\_ -> ()) >~ manyP (token @Char ' ') + skipManyP (token @Char ' ') -- | Example JSON values for testing jsonExamples :: [(Json, String)] diff --git a/test/Examples/Lambda.hs b/distributors-grammar/test/Examples/Lambda.hs similarity index 92% rename from test/Examples/Lambda.hs rename to distributors-grammar/test/Examples/Lambda.hs index 3c43425c..82d0c3c4 100644 --- a/test/Examples/Lambda.hs +++ b/distributors-grammar/test/Examples/Lambda.hs @@ -22,7 +22,7 @@ lambdaGrammar :: Grammar Char Lambda lambdaGrammar = ruleRec "lambda" termG where -- Top level term: lambda abstraction or application - termG term = rule "term" $ choice + termG term = rule "term" $ orP [ lamG term , appG term ] @@ -34,10 +34,10 @@ lambdaGrammar = ruleRec "lambda" termG -- Application: left-associative chain of atoms -- e.g., "f x y" parses as "(f x) y" appG term = rule "application" $ - chain1 Left _App (sepWith " ") (atomG term) + sepWith " " (chain1 Left _App) (atomG term) -- Atomic term: variable or parenthesized term - atomG term = rule "atom" $ choice + atomG term = rule "atom" $ orP [ _Var >? varNameG , terminal "(" >* term *< terminal ")" ] @@ -45,7 +45,7 @@ lambdaGrammar = ruleRec "lambda" termG -- Variable name: starts with lowercase letter, -- followed by alphanumeric or underscore varNameG = rule "varname" $ asIn LowercaseLetter >:< - manyP (choice (token '_' : map asIn [LowercaseLetter, UppercaseLetter, DecimalNumber])) + manyP (orP (token '_' : map asIn [LowercaseLetter, UppercaseLetter, DecimalNumber])) -- | Example lambda calculus terms for testing lambdaExamples :: [(Lambda, String)] diff --git a/test/Examples/LenVec.hs b/distributors-grammar/test/Examples/LenVec.hs similarity index 86% rename from test/Examples/LenVec.hs rename to distributors-grammar/test/Examples/LenVec.hs index 13483dc3..8ea2716c 100644 --- a/test/Examples/LenVec.hs +++ b/distributors-grammar/test/Examples/LenVec.hs @@ -5,7 +5,7 @@ module Examples.LenVec ) where import Control.Lens.Grammar -import qualified Data.Profunctor.Monadic as P +import qualified Data.Profunctor.Monadic.Do as P import Numeric.Natural data LenVec = LenVec {length :: Natural, vector :: [Natural]} @@ -17,7 +17,7 @@ lenvecGrammar :: CtxGrammar Char LenVec lenvecGrammar = _LenVec >? P.do let numberG = iso show read >~ someP (asIn @Char DecimalNumber) - vectorG n = intercalateP n (sepWith ",") numberG + vectorG n = sepWith "," (exactly n) numberG len <- numberG -- bonds to _LenVec terminal ";" -- doesn't bond vectorG (fromIntegral len) -- bonds to _LenVec diff --git a/distributors-grammar/test/Examples/RegString.hs b/distributors-grammar/test/Examples/RegString.hs new file mode 100644 index 00000000..1069a603 --- /dev/null +++ b/distributors-grammar/test/Examples/RegString.hs @@ -0,0 +1,60 @@ +module Examples.RegString + ( regexExamples + ) where + +import Control.Lens.Grammar + +regexExamples :: [(RegString, String)] +regexExamples = + [ (terminal "abc123etc.", "abc123etc.") + , (terminal "x" <> terminal "y", "xy") + , (falseP, "[]") + , (terminal "xy" >|< terminal "z", "xy|z") + , (token 'x' >|< token 'y', "[xy]") + , (optK (terminal "x"), "x?") + , (starK (terminal "x"), "x*") + , (plusK (terminal "x"), "x+") + , (anyToken, "[^]") + , (oneOf "abc", "[abc]") + , (notOneOf "abc", "[^abc]") + , (asIn UppercaseLetter, "\\p{Lu}") + , (notAsIn LowercaseLetter, "\\P{Ll}") + , (nonTerminal "rule-name", "\\q{rule-name}") + , (terminal "", "") + , (optK (terminal "abc"), "(abc)?") + , (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 (asIn UppercaseLetter >|< asIn LowercaseLetter), "\\p{Lu}|\\p{Ll}") + , (tokenClass (oneOf "abc" >|< asIn DecimalNumber), "[abc]|\\p{Nd}") + + -- Boolean AND (>&<) operations + , (tokenClass (oneOf "abcdef" >&< oneOf "def123"), "[def]") + , (tokenClass (notOneOf "abc" >&< notOneOf "xyz"), "[^abcxyz]") + , (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 (notAsIn Control >&< notAsIn Space), "\\P{Zs|Cc}") + , (tokenClass (oneOf "0123456789xyz" >&< asIn DecimalNumber), "[0123456789]") + + -- Boolean NOT (notP) operations + , (tokenClass (notP (oneOf "abc")), "[^abc]") + , (tokenClass (notP (notOneOf "abc")), "[abc]") + , (tokenClass (notP (oneOf "abc" >|< oneOf "xyz")), "[^abcxyz]") + , (tokenClass (notP (asIn UppercaseLetter)), "\\P{Lu}") + , (tokenClass (notP (notAsIn Control)), "\\p{Cc}") + , (tokenClass (notP (notOneOf "abc" >&< asIn LowercaseLetter)), "[abc]|\\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}]") + ] diff --git a/test/Examples/SExpr.hs b/distributors-grammar/test/Examples/SExpr.hs similarity index 93% rename from test/Examples/SExpr.hs rename to distributors-grammar/test/Examples/SExpr.hs index 5cef3e42..6fdc9bde 100644 --- a/test/Examples/SExpr.hs +++ b/distributors-grammar/test/Examples/SExpr.hs @@ -18,7 +18,7 @@ makePrisms ''SExpr -- | Grammar for S-expressions sexprGrammar :: Grammar Char SExpr -sexprGrammar = ruleRec "sexpr" $ \sexpr -> choice +sexprGrammar = ruleRec "sexpr" $ \sexpr -> orP [ _Atom >? atomG , _List >? listG sexpr ] @@ -29,7 +29,7 @@ sexprGrammar = ruleRec "sexpr" $ \sexpr -> choice -- List: parenthesized sequence of S-expressions -- Elements are separated by whitespace listG sexpr = rule "list" $ - terminal "(" >* several (sepWith " ") sexpr *< terminal ")" + terminal "(" >* sepWith " " several sexpr *< terminal ")" -- Characters allowed in atoms: letters, digits, and symbols atomChars = diff --git a/test/Examples/SemVer.hs b/distributors-grammar/test/Examples/SemVer.hs similarity index 88% rename from test/Examples/SemVer.hs rename to distributors-grammar/test/Examples/SemVer.hs index c8f2ba55..087f325b 100644 --- a/test/Examples/SemVer.hs +++ b/distributors-grammar/test/Examples/SemVer.hs @@ -5,10 +5,9 @@ module Examples.SemVer , semverExamples ) where -import Control.Applicative import Control.Lens import Control.Lens.Grammar -import qualified Data.Profunctor.Monadic as P +import qualified Data.Profunctor.Monadic.Do as P import Numeric.Natural -- | Semantic version structure following semver.org specification @@ -42,22 +41,22 @@ semverGrammar = _SemVer >*< optionP _Empty (terminal "+" >* identifiersG) where numberG = iso show read >~ someP (asIn @Char DecimalNumber) - identifiersG = several1 (sepWith ".") (someP charG) + identifiersG = sepWith "." (atLeast 1) (someP charG) charG = asIn LowercaseLetter - <|> asIn UppercaseLetter - <|> asIn DecimalNumber - <|> token '-' + >|< asIn UppercaseLetter + >|< asIn DecimalNumber + >|< token '-' -- Context-sensitive SemVer to test qualified-do semverCtxGrammar :: CtxGrammar Char SemVer semverCtxGrammar = _SemVer >? P.do let numberG = iso show read >~ someP (asIn @Char DecimalNumber) - identifiersG = several1 (sepWith ".") (someP charG) + identifiersG = sepWith "." (atLeast 1) (someP charG) charG = asIn LowercaseLetter - <|> asIn UppercaseLetter - <|> asIn DecimalNumber - <|> token '-' + >|< asIn UppercaseLetter + >|< asIn DecimalNumber + >|< token '-' _ <- numberG _ <- terminal "." >* numberG _ <- terminal "." >* numberG diff --git a/test/Main.hs b/distributors-grammar/test/Main.hs similarity index 62% rename from test/Main.hs rename to distributors-grammar/test/Main.hs index 7477aa8e..68902791 100644 --- a/test/Main.hs +++ b/distributors-grammar/test/Main.hs @@ -3,14 +3,9 @@ module Main (main) where import Data.Foldable hiding (toList) import Control.Lens.Grammar import Control.Monad (when) -import Data.IORef import Data.Function (fix) import Data.List (genericLength) -import Data.Maybe (isJust) -import Data.Profunctor.Types (Star (..)) import Data.Tree (Tree (..)) -import System.Environment (lookupEnv) -import Test.DocTest import Test.Hspec import Test.QuickCheck (generate) import qualified Text.Megaparsec as M @@ -25,30 +20,26 @@ import Examples.RegString import Examples.SemVer import Examples.SExpr import Properties.Kleene +import Properties.Varifocal main :: IO () -main = do - shouldRunDoctests <- isJust <$> lookupEnv "DISTRIBUTORS_RUN_DOCTESTS" - hspec $ do - when shouldRunDoctests $ - describe "doctest" $ - it "should run haddock examples" doctests - describe "regexGrammar" $ testCfg False regexExamples regexGrammar - describe "semverGrammar" $ testCfg True semverExamples semverGrammar - describe "semverCtxGrammar" $ testCsg True semverExamples semverCtxGrammar - describe "arithGrammar" $ testCfg True arithExamples arithGrammar - describe "jsonGrammar" $ testCfg False jsonExamples jsonGrammar - describe "sexprGrammar" $ testCfg True sexprExamples sexprGrammar - describe "lambdaGrammar" $ testCfg True lambdaExamples lambdaGrammar - describe "lenvecGrammar" $ testCsg True lenvecExamples lenvecGrammar - describe "chainGrammar" $ testCfg True chainExamples chainGrammar - describe "exprGrammar" $ testCfg True exprExamples exprGrammar - describe "powGrammar" $ testCfg False powExamples powGrammar - describe "leftGrammar" $ testCfg True leftExamples leftGrammar - describe "parseForest" parseForestTests - describe "Parsector try rollback" tryRollbackTests - describe "Kleene" kleeneProperties - describe "meander" meanderProperties +main = hspec $ do + describe "regexGrammar" $ testCfg False regexExamples regexGrammar + describe "semverGrammar" $ testCfg True semverExamples semverGrammar + describe "semverCtxGrammar" $ testCsg True semverExamples semverCtxGrammar + describe "arithGrammar" $ testCfg True arithExamples arithGrammar + describe "jsonGrammar" $ testCfg False jsonExamples jsonGrammar + describe "sexprGrammar" $ testCfg True sexprExamples sexprGrammar + describe "lambdaGrammar" $ testCfg True lambdaExamples lambdaGrammar + describe "lenvecGrammar" $ testCsg True lenvecExamples lenvecGrammar + describe "chainGrammar" $ testCfg True chainExamples chainGrammar + describe "exprGrammar" $ testCfg True exprExamples exprGrammar + describe "powGrammar" $ testCfg False powExamples powGrammar + describe "leftGrammar" $ testCfg True leftExamples leftGrammar + describe "parseForest" parseForestTests + describe "Parsector try rollback" tryRollbackTests + describe "Kleene" kleeneProperties + describe "Varifocal" varifocalProperties parseForestTests :: Spec parseForestTests = do @@ -87,80 +78,6 @@ tryRollbackTests = do parsecStream actual `shouldBe` "" parsecResult actual `shouldBe` (Nothing :: Maybe String) -doctests :: IO () -doctests = do - stackExe <- lookupEnv "STACK_EXE" - ghcEnvironment <- lookupEnv "GHC_ENVIRONMENT" - let - modulePaths = - [ "src/Control/Lens/Grammar.hs" - , "src/Data/Profunctor/Separator.hs" - ] - sourceDirs = - [ "-isrc" - , "-itest" - ] - packageEnvFlags = case ghcEnvironment of - Just "-" -> [] - Just path -> ["-package-env=" <> path] - Nothing -> [] - runnerFlags - | isJust stackExe = [] - | otherwise = sourceDirs <> packageEnvFlags - languageExtensions = - [ "-XAllowAmbiguousTypes" - , "-XArrows" - , "-XConstraintKinds" - , "-XDataKinds" - , "-XDefaultSignatures" - , "-XDeriveFoldable" - , "-XDeriveFunctor" - , "-XDeriveTraversable" - , "-XDeriveGeneric" - , "-XDerivingStrategies" - , "-XDerivingVia" - , "-XEmptyCase" - , "-XFlexibleContexts" - , "-XFlexibleInstances" - , "-XFunctionalDependencies" - , "-XGADTs" - , "-XGeneralizedNewtypeDeriving" - , "-XImportQualifiedPost" - , "-XImpredicativeTypes" - , "-XInstanceSigs" - , "-XLambdaCase" - , "-XMagicHash" - , "-XMonoLocalBinds" - , "-XQuantifiedConstraints" - , "-XRankNTypes" - , "-XRecursiveDo" - , "-XScopedTypeVariables" - , "-XStandaloneDeriving" - , "-XStandaloneKindSignatures" - , "-XTemplateHaskell" - , "-XTupleSections" - , "-XTypeApplications" - , "-XTypeFamilies" - , "-XTypeOperators" - , "-XUndecidableInstances" - , "-XUndecidableSuperClasses" - ] - for_ modulePaths $ \modulePath -> do - putStr "Testing module documentation in " - putStrLn modulePath - doctest (modulePath : runnerFlags <> languageExtensions) - -meanderProperties :: Spec -meanderProperties = - it "preserves left-to-right traversal effects" $ do - let input = ["h", "e", "l", "l", "o"] - seenRef <- newIORef [] - let visit item = modifyIORef' seenRef (item :) >> pure () - units <- runStar (meander traverse (Star visit)) input - seen <- reverse <$> readIORef seenRef - seen `shouldBe` input - units `shouldBe` replicate (length input) () - testCfg :: (Show a, Eq a) => Bool -> [(a, String)] -> Grammar Char a -> Spec testCfg isLL1 examples grammar = do describe "examples" $ for_ examples $ \(expectedSyntax, expectedString) -> do diff --git a/distributors-grammar/test/Properties/Kleene.hs b/distributors-grammar/test/Properties/Kleene.hs new file mode 100644 index 00000000..fddc561a --- /dev/null +++ b/distributors-grammar/test/Properties/Kleene.hs @@ -0,0 +1,222 @@ +{-# LANGUAGE CPP #-} +{-# OPTIONS_GHC -Wno-orphans #-} +module Properties.Kleene (kleeneProperties) where + +import Control.Lens.Grammar +import Data.Foldable (for_) +import Data.String (fromString) +import GHC.Exts (fromList, toList) +import Test.Hspec +import Test.Hspec.QuickCheck (modifyMaxSize, prop) +import Test.QuickCheck + +#if !MIN_VERSION_QuickCheck(2,17,0) +import Data.Char (GeneralCategory) + +-- | QuickCheck 2.17's instance, for earlier versions. +instance Arbitrary GeneralCategory where + arbitrary = arbitraryBoundedEnum + shrink = shrinkBoundedEnum +#endif + +instance Arbitrary (TokenClass Char) where + arbitrary = sized go + where + go 0 = frequency + [ (1, pure falseP) + , (1, pure trueP) + , (4, oneOf <$> (arbitrary :: Gen [Char])) + , (4, notOneOf <$> (arbitrary :: Gen [Char])) + , (3, asIn <$> arbitrary) + , (3, notAsIn <$> arbitrary) + ] + go n = frequency + [ (2, go 0) + , (2, (>|<) <$> go (n `div` 2) <*> go (n `div` 2)) + , (2, (>&<) <$> go (n `div` 2) <*> go (n `div` 2)) + , (1, notP <$> go (n - 1)) + ] + +instance Arbitrary (RegEx Char) where + arbitrary = sized go + where + go 0 = frequency + [ (1, pure (falseP :: RegEx Char)) + , (1, pure (mempty :: RegEx Char)) + , (6, tokenClass <$> (arbitrary :: Gen (TokenClass Char))) + ] + go n = frequency + [ (2, go 0) + , (2, (<>) <$> go (n `div` 2) <*> go (n `div` 2)) + , (2, (>|<) <$> go (n `div` 2) <*> go (n `div` 2)) + , (1, starK <$> go (n - 1)) + , (1, plusK <$> go (n - 1)) + , (1, optK <$> go (n - 1)) + ] + +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) + 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) + 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 + read (show bnf) `shouldBe` bnf + read (show [bnf]) `shouldBe` [bnf] + describe "KleeneStarAlgebra" $ do + prop "starK x = optK (plusK x)" $ \(x :: RegEx Char) -> + starK x == optK (plusK x) + prop "plusK x = x <> starK x" $ \(x :: RegEx Char) -> + plusK x == x <> starK x + prop "optK x = mempty >|< x" $ \(x :: RegEx Char) -> + optK x == (mempty >|< x) + prop "x >|< x = x" $ \(x :: RegEx Char) -> + (x >|< x) == x + prop "falseP >|< x = x" $ \(x :: RegEx Char) -> + (falseP >|< x) == x + prop "x >|< falseP = x" $ \(x :: RegEx Char) -> + (x >|< falseP) == x + prop "x >|< mempty = optK x" $ \(x :: RegEx Char) -> + (x >|< mempty) == optK x + prop "falseP <> x = falseP" $ \(x :: RegEx Char) -> + (falseP <> x) == falseP + prop "x <> falseP = falseP" $ \(x :: RegEx Char) -> + (x <> falseP) == falseP + prop "mempty <> x = x" $ \(x :: RegEx Char) -> + (mempty <> x) == x + prop "x <> mempty = x" $ \(x :: RegEx Char) -> + (x <> mempty) == x + prop "(x <> y) <> z = x <> (y <> z)" $ \(x :: RegEx Char) y z -> + (x <> y) <> z === x <> (y <> z) + prop "(x >|< y) >|< z = x >|< (y >|< z)" $ \(x :: RegEx Char) y z -> + ((x >|< y) >|< z) === (x >|< (y >|< z)) + prop "TokenClass: (x >|< y) >|< z = x >|< (y >|< z)" $ + \(x :: TokenClass Char) y z -> + ((x >|< y) >|< z) === (x >|< (y >|< z)) + describe "Prismoids act on KleeneStarAlgebras, by Grammor" $ do + let grammor = Grammor :: RegEx Char -> Grammor (RegEx Char) Char Char + prop "atLeast 1 >?* Grammor x = Grammor (plusK x)" $ \(x :: RegEx Char) -> + runGrammor (atLeast 1 >?* grammor x) == plusK x + prop "several >?* Grammor x = Grammor (starK x)" $ \(x :: RegEx Char) -> + runGrammor (several >?* grammor x) == starK x + prop "opted def >?* Grammor x = Grammor (optK x)" $ \(x :: RegEx Char) -> + runGrammor (opted (only 'a') >?* grammor x) == optK x + describe "manyTillP & sepBy at Grammor" $ do + prop "sepBy sep (several . several) is finite at Grammor" $ \(x :: RegEx Char) -> + let sep = Grammor (token ',') :: Grammor (RegEx Char) () () + r = runGrammor (sepBy sep (several . several) (Grammor x :: Grammor (RegEx Char) Char Char)) + in r == r + prop "skippedMany >?* x = starK x, by Grammor" $ \(x :: RegEx Char) -> + runGrammor (skippedMany >?* (Grammor x :: Grammor (RegEx Char) Char Char) :: Grammor (RegEx Char) () ()) + == starK x + prop "manyTillP x y = starK x <> y, by Grammor" $ \(x :: RegEx Char) y -> + runGrammor (manyTillP (Grammor x) (Grammor y) :: Grammor (RegEx Char) [()] [()]) + == starK x <> y + describe "Counted Prismoids & skippedOptional print & parse, by Printor & Parsor" $ + 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 + parsed :: Prismoid String String Char Char -> String -> Maybe (String, String) + 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 -> + printed (inRange lo (Just hi)) s === (if bounded lo hi s then Just s else Nothing) + .&&. (if bounded lo hi s then parsed (inRange lo (Just hi)) s === Just (s, "") else property True) + prop "atMost n prints & parses at most n tokens" $ + \(s :: String) -> forAll (choose (0, 4)) $ \n -> + printed (atMost n) s === (if length s <= n then Just s else Nothing) + .&&. parsed (atMost n) s === Just (splitAt n s) + prop "atLeast n prints & parses at least n tokens" $ + \(s :: String) -> forAll (choose (0, 4)) $ \n -> + printed (atLeast n) s === (if length s >= n then Just s else Nothing) + .&&. parsed (atLeast n) s === (if length s >= n then Just (s, "") else Nothing) + it "skippedOptional prints nothing, & parses one or none" $ do + let comma = token ',' :: Printor String Maybe Char Char + comma' = token ',' :: Parsor String Maybe Char Char + (($ "") <$> printP (skippedOptional >?* comma) ()) `shouldBe` Just "" + parseP (skippedOptional >?* comma') "," `shouldBe` Just ((), "") + parseP (skippedOptional >?* comma') "" `shouldBe` Just ((), "") + parseP (skippedOptional >?* comma') "x" `shouldBe` Just ((), "x") + describe "TokenAlgebra" $ do + it "falseP = tokenClass falseP" $ + (falseP :: RegEx Char) `shouldBe` tokenClass falseP + prop "tokenClass x >|< tokenClass y = tokenClass (x >|< y)" $ + \(x :: TokenClass Char) (y :: TokenClass Char) -> + ((tokenClass x :: RegEx Char) >|< tokenClass y) + == tokenClass (x >|< y) + describe "TokenAlgebra RegEx" $ do + 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) + prop "oneOf cs = tokenClass (oneOf cs)" $ + \(cs :: [Char]) -> + (oneOf cs :: RegEx Char) == tokenClass (oneOf cs) + prop "notOneOf cs = tokenClass (notOneOf cs)" $ + \(cs :: [Char]) -> + (notOneOf cs :: RegEx Char) == tokenClass (notOneOf cs) + prop "asIn cat = tokenClass (asIn cat)" $ + \(cat :: GeneralCategory) -> + (asIn cat :: RegEx Char) == tokenClass (asIn cat) + prop "notAsIn cat = tokenClass (notAsIn cat)" $ + \(cat :: GeneralCategory) -> + (notAsIn cat :: RegEx Char) == tokenClass (notAsIn cat) + it "matching agrees with lifted Bnf on examples" $ do + let + cases = + [ ("", mempty :: RegEx Char) + , ("a", token 'a') + , ("b", token 'a') + , ("ab", token 'a' <> token 'b') + , ("a", token 'a' >|< token 'b') + , ("bbb", starK (token 'b')) + , ("bbb", plusK (token 'b')) + , ("", optK (token 'b')) + , ("x", oneOf "xyz") + , ("x", notOneOf "abc") + , ("A", asIn UppercaseLetter) + , ("a", notAsIn UppercaseLetter) + , ("abbb", token 'a' <> starK (token 'b')) + , ("cat", terminal "cat" >|< terminal "dog") + ] + for_ cases $ \(word, rex) -> + (word =~ rex) `shouldBe` (word =~ liftBnf0 rex) + describe "BooleanAlgebra TokenClass" $ do + it "trueP = anyToken" $ + (trueP :: TokenClass Char) `shouldBe` anyToken + it "trueP = notOneOf []" $ + (trueP :: TokenClass Char) `shouldBe` notOneOf [] + it "falseP = oneOf []" $ + (falseP :: TokenClass Char) `shouldBe` oneOf [] + prop "notP . oneOf = notOneOf" $ + \(cs :: [Char]) -> + notP (oneOf cs :: TokenClass Char) == notOneOf cs + prop "notP . notOneOf = oneOf" $ + \(cs :: [Char]) -> + notP (notOneOf cs :: TokenClass Char) == oneOf cs + prop "notP . asIn = notAsIn" $ + \(cat :: GeneralCategory) -> + notP (asIn cat :: TokenClass Char) == notAsIn cat + prop "notP . notAsIn = asIn" $ + \(cat :: GeneralCategory) -> + notP (notAsIn cat :: TokenClass Char) == asIn cat + prop "x >|< x = x" $ \(x :: TokenClass Char) -> + (x >|< x) == x + prop "x >&< x = x" $ \(x :: TokenClass Char) -> + (x >&< x) == x + +-- | A `RegString` as its printed text parses, which `read` reads. +reparsed :: RegString -> RegString +reparsed = fromList . toList + + diff --git a/distributors-grammar/test/Properties/Varifocal.hs b/distributors-grammar/test/Properties/Varifocal.hs new file mode 100644 index 00000000..c4d7e535 --- /dev/null +++ b/distributors-grammar/test/Properties/Varifocal.hs @@ -0,0 +1,190 @@ +module Properties.Varifocal (varifocalProperties) where + +import Control.Lens.Grammar +import Data.Char (digitToInt, isDigit) +import Data.Foldable (for_) +import Data.Maybe (fromMaybe) +import Text.Read (readMaybe) +import Examples.Heredoc +import Test.Hspec +import Test.Hspec.QuickCheck (prop) +import Test.QuickCheck + +varifocalProperties :: Spec +varifocalProperties = do + let + printed :: Varifocal' String Char -> String -> Maybe String + printed v s = + ($ "") <$> printP (contextuallyT v (anyToken :: 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)) + ended :: Varifocal' String Char + ended = terminateBy (== '.') + plain = Prelude.filter (/= '.') <$> arbitrary + describe "MonadicTrans laws, at Printor & Parsor" $ do + let + printing :: Printor String Maybe Char b -> Char -> Maybe (b, String) + 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 + 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 + prop "liftP (m >>= k) = liftP m >>= liftP . k" $ + \(m :: Maybe Int) (Fun _ k :: Fun Int (Maybe Int)) (c :: Char) (str :: String) -> + printing (liftP (m >>= k)) c === printing (liftP m >>= liftP . k) c + .&&. parsing (liftP (m >>= k)) str === parsing (liftP m >>= liftP . k) str + prop "joinP (fmap pure p) = p" $ \(c :: Char) (str :: String) -> + printing (joinP (fmap pure prToken)) c === printing prToken c + .&&. parsing (joinP (fmap pure paToken)) str === parsing paToken str + describe "terminateBy" $ do + prop "prints & parses up to its first end" $ + forAll plain $ \s -> forAll plain $ \rest -> + printed ended (s ++ ".") === Just (s ++ ".") + .&&. parsed ended (s ++ "." ++ rest) === Just (s ++ ".", rest) + prop "doesn't print without an end" $ + forAll plain $ \s -> printed ended s === Nothing + prop "doesn't print an early end" $ + forAll plain $ \s -> forAll plain $ \t -> + printed ended (s ++ "." ++ t ++ ".") === Nothing + describe "balanceBy & countWith, by ctxList" $ do + let + nested :: Varifocal' String Char + nested = balanceBy (== '(') (== ')') + counted :: Varifocal' String Char + counted = countWith (\c -> if isDigit c then digitToInt c else 0) + it "balanceBy parses a nested block, leaving the rest" $ + parsed nested "(a(b)c)rest" `shouldBe` Just ("(a(b)c)", "rest") + it "balanceBy prints only a balanceBy block" $ do + printed nested "(a(b)c)" `shouldBe` Just "(a(b)c)" + map (printed nested) ["(a(b)", "(a)b", "a", ")", ""] `shouldBe` replicate 5 Nothing + prop "balanceBy round-trips nesting of any depth" $ + forAll (choose (1, 6)) $ \n -> let str = replicate n '(' ++ replicate n ')' in + printed nested str === Just str .&&. parsed nested (str ++ ")") === Just (str, ")") + it "countWith reads as many as its first focus counts" $ do + parsed counted "3abcd" `shouldBe` Just ("3abc", "d") + parsed counted "0x" `shouldBe` Just ("0", "x") + printed counted "2ab" `shouldBe` Just "2ab" + map (printed counted) ["3ab", "1ab"] `shouldBe` [Nothing, Nothing] + it "clones balanceBy, as it does" $ do + let cloned :: Varifocal' String Char + cloned = cloneVarifocal nested + strs = ["(a(b)c)", "(a(b)", "a", "((x))"] + map (printed cloned) strs `shouldBe` map (printed nested) strs + map (parsed cloned) strs `shouldBe` map (parsed nested) strs + describe "crossVarifocal, altVarifocal & bindVarifocal" $ do + let + printedG :: Varifocal' s Char -> s -> Maybe String + printedG v x = + ($ "") <$> printP (contextuallyT v (anyToken :: 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)) + crossed :: Varifocal' (String, String) Char + crossed = crossVarifocal (terminateBy (== '.')) (delimitBy (==)) + alted :: Varifocal' (Either String String) Char + alted = altVarifocal (terminateBy (== '.')) (balanceBy (== '(') (== ')')) + netstring :: Varifocal' (String, String) Char + netstring = bindVarifocal (terminateBy (== ':')) + (\header -> exactly (fromMaybe 0 (readMaybe (init header)))) + it "crosses side by side" $ do + printedG crossed ("ab.", "xyx") `shouldBe` Just "ab.xyx" + parsedG crossed "ab.xyxrest" `shouldBe` Just (("ab.", "xyx"), "rest") + it "alts one or the other" $ do + printedG alted (Left "ab.") `shouldBe` Just "ab." + printedG alted (Right "(a)") `shouldBe` Just "(a)" + parsedG alted "ab." `shouldBe` Just (Left "ab.", "") + parsedG alted "(a)" `shouldBe` Just (Right "(a)", "") + prop "binds a netstring's length to its payload" $ \(payload :: String) -> + let header = show (length payload) ++ ":" + in printedG netstring (header, payload) === Just (header ++ payload) + .&&. parsedG netstring (header ++ payload ++ "rest") + === Just ((header, payload), "rest") + it "won't print a netstring whose length isn't its payload's" $ + printedG netstring ("3:", "ab") `shouldBe` Nothing + it "ors one, else the other, with falseOptic as its unit" $ do + let ored, emptied :: Varifocal' String Char + ored = orVarifocal (terminateBy (== '.')) (balanceBy (== '(') (== ')')) + emptied = orVarifocal falseOptic (terminateBy (== '.')) + map (printed ored) ["ab.", "(a)", "ab"] `shouldBe` [Just "ab.", Just "(a)", Nothing] + map (parsed ored) ["ab.c", "(a)c"] `shouldBe` [Just ("ab.", "c"), Just ("(a)", "c")] + map (printed emptied) ["ab.", "ab"] `shouldBe` map (printed ended) ["ab.", "ab"] + printed falseOptic "ab." `shouldBe` Nothing + describe "cloneVarifocal, by its free Varifocus" $ do + prop "clones terminateBy, printing & parsing as it does" $ + forAll plain $ \s -> forAll plain $ \t -> + let cloned :: Varifocal' String Char + cloned = cloneVarifocal ended + strs = [s, s ++ ".", s ++ "." ++ t, s ++ "." ++ t ++ "."] + in map (printed cloned) strs === map (printed ended) strs + .&&. map (parsed cloned) strs === map (parsed ended) strs + prop "clones inRange, printing & parsing as it does" $ + \(s :: String) -> forAll (choose (0, 4)) $ \lo -> forAll (choose (0, 4)) $ \hi -> + let range :: Varifocal' String Char + range = inRange lo (Just hi) + in printed (cloneVarifocal range) s === printed range s + .&&. parsed (cloneVarifocal range) s === parsed range s + describe "heredocs, by delimitBy" $ do + let + printedH h = + ($ "") <$> printP (heredocP :: Printor String Maybe Heredoc Heredoc) h + parsedH = parseP (heredocP :: Parsor String Maybe Heredoc Heredoc) + line = Prelude.filter (/= '\n') <$> arbitrary + for_ heredocExamples $ \(h, str) -> + it ("prints & parses " <> show str) $ do + printedH h `shouldBe` Just str + parsedH str `shouldBe` Just (h, "") + it "doesn't print a body line equal to its tag" $ + printedH (Heredoc "EOF" ["EOF"]) `shouldBe` Nothing + it "closes at the first line equal to its tag" $ + parsedH "< forAll (listOf (line `suchThat` (/= tag))) $ \body -> + let h = Heredoc tag body + in (printedH h >>= fmap fst . parsedH) === Just h + describe "cloneVarifocal of a composite, a Prism then a Varifocal" $ do + let + composite :: Varifocal' (Either Int String) Char + 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 + parsedE :: Varifocal' (Either Int String) Char -> String -> Maybe (Either Int String, String) + 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 ++ ".")] + in map (printedE (cloneVarifocal composite)) es === map (printedE composite) es + .&&. parsedE (cloneVarifocal composite) (s ++ ".") === parsedE composite (s ++ ".") + 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 + it "doesn't print a body line equal to its tag" $ + [pr "" | pr <- printG heredocG (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 + === 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 >?<* (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') >?<* (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 >?* (anyToken :: Parsor String Maybe Char Char)) s + .&&. printed (atLeast 1) s + === (($ "") <$> printP (atLeast 1 >?* (anyToken :: Printor String Maybe Char Char)) s) diff --git a/distributors-json/CHANGELOG.md b/distributors-json/CHANGELOG.md new file mode 100644 index 00000000..12750ac0 --- /dev/null +++ b/distributors-json/CHANGELOG.md @@ -0,0 +1,28 @@ +# Changelog for distributors-json + +## 0.1.0.0 + +- Split out of `distributors` as its own package. +- `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`. +- `Control.Lens.Grammar.TypeScript` parses & prints TypeScript type + declarations, by `tsTokenGrammar` & `tsGrammar`, after the TypeScript + compiler's scanner & syntax. +- `tsTokensGrammar` scans tokens without their trivia, so that `tsGrammar` + parses by Parsector, locating failures. +- Mapped types exclude named keys by `as`, rather than the global `Exclude`. +- Single-key objects, like `Either`'s, & numeric keys parse as `aeson` does. +- `jsonObjectStrict` is a `JsonVal` method. +- `jsonPair` is a `JsonVal` method, of pairs & of generic constructors of + two positional fields, which printing renders as arrays of two elements + directly. +- `jsonTag`, an object of a single property, as `Either` & sums by + `ObjectWithSingleField` print, is a `JsonVal` method, which printing renders + directly; sums by `TwoElemArray` print by `jsonPair`. +- `ViaJson` derives all of `aeson`'s instances: `ToJSON` & `FromJSON` with + `omitField` & `omittedField`, by `jsonOmitField`, & `ToJSONKey` & + `FromJSONKey`, by `jsonKey` & `jsonKeyList`, or else as values in arrays + of pairs; & it's `Eq`, `Ord` & `Show`. +- `jsonEnumWith` takes a table of strings & values, & each value's index in it, + so that it prints by index; generic enumerations index by `dataToTag#`. diff --git a/distributors-json/LICENSE b/distributors-json/LICENSE new file mode 100644 index 00000000..c969d4b7 --- /dev/null +++ b/distributors-json/LICENSE @@ -0,0 +1,30 @@ +Copyright Eitan Chatav (c) 2026 + +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + + * Neither the name of Eitan Chatav nor the names of other + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/distributors-json/README.md b/distributors-json/README.md new file mode 100644 index 00000000..33e26162 --- /dev/null +++ b/distributors-json/README.md @@ -0,0 +1,22 @@ +# distributors-json + +A `Json` grammar of a type parses, prints & encodes its JSON, +compatibly with `aeson`, & types it in TypeScript, all at once. + +```haskell +data Person = Person {name :: Text, age :: Int, email :: Maybe Text} + deriving stock (Show, Generic) + deriving anyclass Json + deriving (ToJSON, FromJSON) via ViaJson Person +``` + +```haskell +>>> jsonDecode @Person "{\"name\":\"Ada\",\"age\":36}" +Right (Person {name = "Ada", age = 36, email = Nothing}) +>>> jsonTsPut (type '[Person]) stdout +export type Int = number; +export type Person = { name: string; age: Int; email?: null | string }; +``` + +See `Control.Lens.Grammar.Json` for a tour, & `Control.Lens.Grammar.TypeScript` +for the TypeScript grammar. diff --git a/distributors-json/bench/Documents.hs b/distributors-json/bench/Documents.hs new file mode 100644 index 00000000..0d90d60b --- /dev/null +++ b/distributors-json/bench/Documents.hs @@ -0,0 +1,296 @@ +{-# LANGUAGE DuplicateRecordFields #-} +{-# LANGUAGE DeriveAnyClass #-} +{-# LANGUAGE TemplateHaskell #-} + +{- | Real-world documents, from @aeson@'s benchmarks (see @data/README.md@), +typed by records whose `Json` & @aeson@ instances are derived generically, +by the same `Options`. +-} +module Documents + ( Search (..) + , Story (..) + , Metadata (..) + , Geo (..) + , Issue (..) + , GitHubUser (..) + , Label (..) + , Milestone (..) + , PullRequest (..) + , Polygon (..) + , Geometry (..) + , Person (..) + , Friend (..) + , twitter10 + , twitter100 + , jp100 + , githubIssues + , geoJson + , people + ) where + +import Control.DeepSeq (NFData) +import Control.Lens.Grammar.Json +import Data.Aeson +import Data.ByteString (ByteString) +import Data.FileEmbed (embedFile) +import Data.Int (Int64) +import Data.Text (Text) +import GHC.Generics (Generic) + +-- | Record fields named @id_@ & @type_@ are keyed @id@ & @type@. +keyed :: Options +keyed = defaultOptions + { fieldLabelModifier = \case + "id_" -> "id" + "type_" -> "type" + "default_" -> "default" + field -> field + } + +-- Twitter -- + +data Search = Search + { results :: [Story] + , max_id :: Int64 + , since_id :: Int64 + , refresh_url :: Text + , next_page :: Text + , results_per_page :: Int + , page :: Int + , completed_in :: Double + , since_id_str :: Text + , max_id_str :: Text + , query :: Text + } + deriving stock (Show, Generic) + deriving anyclass (NFData, Json, ToJSON, FromJSON) + +data Story = Story + { from_user_id_str :: Text + , profile_image_url :: Text + , created_at :: Text + , from_user :: Text + , id_str :: Text + , metadata :: Metadata + , to_user_id :: Maybe Int64 + , text :: Text + , id_ :: Int64 + , from_user_id :: Int64 + , geo :: Maybe Geo + , iso_language_code :: Text + , to_user_id_str :: Maybe Text + , source :: Text + , to_user :: Maybe Text + } + deriving stock (Show, Generic) + deriving anyclass NFData +instance Json Story where json = jsonGeneric keyed +instance ToJSON Story where + toJSON = genericToJSON keyed + toEncoding = genericToEncoding keyed +instance FromJSON Story where parseJSON = genericParseJSON keyed + +newtype Metadata = Metadata {result_type :: Text} + deriving stock (Show, Generic) + deriving anyclass (NFData, Json, ToJSON, FromJSON) + +-- | A point, keyed literally @type_@ by Twitter. +data Geo = Geo {type_ :: Text, coordinates :: (Double, Double)} + deriving stock (Show, Generic) + deriving anyclass (NFData, Json, ToJSON, FromJSON) + +-- GitHub -- + +data Issue = Issue + { url :: Text + , repository_url :: Text + , labels_url :: Text + , comments_url :: Text + , events_url :: Text + , html_url :: Text + , id_ :: Int64 + , node_id :: Text + , number :: Int + , title :: Text + , user :: GitHubUser + , labels :: [Label] + , state :: Text + , locked :: Bool + , assignee :: Maybe GitHubUser + , assignees :: [GitHubUser] + , milestone :: Maybe Milestone + , comments :: Int + , created_at :: Text + , updated_at :: Text + , closed_at :: Maybe Text + , author_association :: Text + , pull_request :: Maybe PullRequest + , body :: Maybe Text + } + deriving stock (Show, Generic) + deriving anyclass NFData + +data GitHubUser = GitHubUser + { login :: Text + , id_ :: Int64 + , node_id :: Text + , avatar_url :: Text + , gravatar_id :: Text + , url :: Text + , html_url :: Text + , followers_url :: Text + , following_url :: Text + , gists_url :: Text + , starred_url :: Text + , subscriptions_url :: Text + , organizations_url :: Text + , repos_url :: Text + , events_url :: Text + , received_events_url :: Text + , type_ :: Text + , site_admin :: Bool + } + deriving stock (Show, Generic) + deriving anyclass NFData + +data Label = Label + { id_ :: Int64 + , node_id :: Text + , url :: Text + , name :: Text + , color :: Text + , default_ :: Bool + , description :: Maybe Text + } + deriving stock (Show, Generic) + deriving anyclass NFData + +data Milestone = Milestone + { url :: Text + , html_url :: Text + , labels_url :: Text + , id_ :: Int64 + , node_id :: Text + , number :: Int + , title :: Text + , description :: Maybe Text + , creator :: GitHubUser + , open_issues :: Int + , closed_issues :: Int + , state :: Text + , created_at :: Text + , updated_at :: Text + , due_on :: Maybe Text + , closed_at :: Maybe Text + } + deriving stock (Show, Generic) + deriving anyclass NFData + +data PullRequest = PullRequest + { url :: Text + , html_url :: Text + , diff_url :: Text + , patch_url :: Text + } + deriving stock (Show, Generic) + deriving anyclass (NFData, Json, ToJSON, FromJSON) + +instance Json Issue where json = jsonGeneric keyed +instance ToJSON Issue where + toJSON = genericToJSON keyed + toEncoding = genericToEncoding keyed +instance FromJSON Issue where parseJSON = genericParseJSON keyed +instance Json GitHubUser where json = jsonGeneric keyed +instance ToJSON GitHubUser where + toJSON = genericToJSON keyed + toEncoding = genericToEncoding keyed +instance FromJSON GitHubUser where parseJSON = genericParseJSON keyed +instance Json Label where json = jsonGeneric keyed +instance ToJSON Label where + toJSON = genericToJSON keyed + toEncoding = genericToEncoding keyed +instance FromJSON Label where parseJSON = genericParseJSON keyed +instance Json Milestone where json = jsonGeneric keyed +instance ToJSON Milestone where + toJSON = genericToJSON keyed + toEncoding = genericToEncoding keyed +instance FromJSON Milestone where parseJSON = genericParseJSON keyed + +-- GeoJSON -- + +newtype Geometry = Geometry {geometry :: Polygon} + deriving stock (Show, Generic) + deriving anyclass (NFData, Json, ToJSON, FromJSON) + +data Polygon = Polygon {type_ :: Text, coordinates :: [[[Double]]]} + deriving stock (Show, Generic) + deriving anyclass NFData +instance Json Polygon where json = jsonGeneric keyed +instance ToJSON Polygon where + toJSON = genericToJSON keyed + toEncoding = genericToEncoding keyed +instance FromJSON Polygon where parseJSON = genericParseJSON keyed + +-- People -- + +data Person = Person + { _id :: Text + , index :: Int + , guid :: Text + , isActive :: Bool + , balance :: Text + , picture :: Text + , age :: Int + , eyeColor :: Text + , name :: Text + , gender :: Text + , company :: Text + , email :: Text + , phone :: Text + , address :: Text + , about :: Text + , registered :: Text + , latitude :: Double + , longitude :: Double + , tags :: [Text] + , friends :: [Friend] + , greeting :: Text + , favoriteFruit :: Text + } + deriving stock (Show, Generic) + deriving anyclass (NFData, Json, ToJSON, FromJSON) + +data Friend = Friend {id_ :: Int, name :: Text} + deriving stock (Show, Generic) + deriving anyclass NFData +instance Json Friend where json = jsonGeneric keyed +instance ToJSON Friend where + toJSON = genericToJSON keyed + toEncoding = genericToEncoding keyed +instance FromJSON Friend where parseJSON = genericParseJSON keyed + +-- Documents -- + +-- | A document, decoded by @aeson@ once, failing loudly if it can't be. +document :: FromJSON a => String -> ByteString -> a +document file = either (error . (("benchmark data " <> file <> ": ") <>)) id + . eitherDecodeStrict + +twitter10 :: Search +twitter10 = document "twitter10" $(embedFile "bench/data/twitter10.json") + +twitter100 :: Search +twitter100 = document "twitter100" $(embedFile "bench/data/twitter100.json") + +jp100 :: Search +jp100 = document "jp100" $(embedFile "bench/data/jp100.json") + +githubIssues :: [Issue] +githubIssues = + document "github-issues" $(embedFile "bench/data/github-issues.json") + +geoJson :: Geometry +geoJson = document "geometry" $(embedFile "bench/data/geometry.json") + +people :: [Person] +people = document "buffer-builder" $(embedFile "bench/data/buffer-builder.json") diff --git a/distributors-json/bench/Main.hs b/distributors-json/bench/Main.hs new file mode 100644 index 00000000..db0d5f49 --- /dev/null +++ b/distributors-json/bench/Main.hs @@ -0,0 +1,314 @@ +{-# LANGUAGE DeriveAnyClass #-} +{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE RequiredTypeArguments #-} +-- | Keep constant benchmarks, like `tsTypes`, from being shared. +{-# OPTIONS_GHC -fno-full-laziness #-} +-- | A sum of records, like `Variant`, has partial fields. +{-# OPTIONS_GHC -Wno-partial-fields #-} +module Main (main) where + +import Control.DeepSeq (NFData) +import Control.Lens.Grammar.Json +import Data.Kind (Type) +import Data.SOP (All) +import Control.Lens.Grammar (ParsecState (..), unparsecG) +import Control.Lens.Grammar.TypeScript +import Data.Foldable (toList) +import Data.Sequence qualified as Seq +import Data.Aeson + ( FromJSON (..), ToJSON (..), Value (..), decode, defaultOptions, encode + , genericToEncoding, object, (.=) + ) +import Data.Aeson.Encoding (encodingToLazyByteString) +import Data.Aeson.Types (parseEither) +import Data.ByteString.Lazy (ByteString) +import Data.HashMap.Strict (HashMap) +import Data.HashMap.Strict qualified as HashMap +import Data.Int (Int8) +import Data.Maybe (isNothing) +import Data.Map.Strict (Map) +import Data.Map.Strict qualified as Map +import Data.Text (Text) +import Data.Text qualified as Text +import Data.Time (UTCTime) +import Data.Time.Clock.POSIX (posixSecondsToUTCTime) +import Data.Word (Word64) +import GHC.Generics (Generic) +import Test.Tasty.Bench + +import Documents qualified as Doc + +data Person = Person + { name :: Text + , age :: Int + , email :: Maybe Text + , tags :: [Text] + , score :: Double + } deriving stock (Show, Generic) + deriving anyclass (NFData, Json, FromJSON) + +-- | @aeson@ encodes generic types directly, as it recommends. +instance ToJSON Person where toEncoding = genericToEncoding defaultOptions + +data Shape = Circle Double | Rectangle Double Double | Point + deriving stock (Show, Generic) + deriving anyclass (NFData, Json, FromJSON) +instance ToJSON Shape where toEncoding = genericToEncoding defaultOptions + +data Weekday = Monday | Tuesday | Wednesday | Thursday | Friday + deriving stock (Show, Generic, Enum, Bounded) + deriving anyclass (NFData, Json, FromJSON) +instance ToJSON Weekday where toEncoding = genericToEncoding defaultOptions + +data Rose = Rose Int [Rose] + deriving stock (Show, Generic) + deriving anyclass (NFData, Json, FromJSON) +instance ToJSON Rose where toEncoding = genericToEncoding defaultOptions + +-- | A wide record, of twenty fields. +data Wide = Wide + { w01 :: Int, w02 :: Text, w03 :: Bool, w04 :: Double, w05 :: Maybe Int + , w06 :: Int, w07 :: Text, w08 :: Bool, w09 :: Double, w10 :: Maybe Int + , w11 :: Int, w12 :: Text, w13 :: Bool, w14 :: Double, w15 :: Maybe Int + , w16 :: Int, w17 :: Text, w18 :: Bool, w19 :: Double, w20 :: Maybe Int + } deriving stock (Show, Generic) + deriving anyclass (NFData, Json, FromJSON) +instance ToJSON Wide where toEncoding = genericToEncoding defaultOptions + +-- | A sum of records, tagged objects of their fields. +data Variant + = Created {vid :: Int, vname :: Text} + | Updated {vid :: Int, vchanges :: [Text]} + | Deleted {vid :: Int} + deriving stock (Show, Generic) + deriving anyclass (NFData, Json, FromJSON) +instance ToJSON Variant where toEncoding = genericToEncoding defaultOptions + +-- | Records nested deeply. +data Deep = Deep {title :: Text, child :: Maybe Deep} + deriving stock (Show, Generic) + deriving anyclass (NFData, Json, FromJSON) +instance ToJSON Deep where toEncoding = genericToEncoding defaultOptions + +-- | Twelve nested pairs, each its own type alias. +type Twice12 = Twice (Twice (Twice (Twice (Twice (Twice (Twice (Twice + (Twice (Twice (Twice (Twice Double))))))))))) +data Twice a = Twice a a + deriving stock Generic + deriving anyclass Json + +people :: [Person] +people = + [ Person + { name = "person " <> Text.pack (show i) + , age = i `mod` 90 + , email = if even i then Just (Text.pack ("p" <> show i <> "@x.org")) + else Nothing + , tags = ["a", "bb", "ccc"] + , score = fromIntegral i / 7 + } + | i <- [1 .. 1000 :: Int] + ] + +shapes :: [Shape] +shapes = take 3000 (cycle [Circle 1.5, Rectangle 2 3, Point]) + +weekdays :: [Weekday] +weekdays = take 10000 (cycle [minBound .. maxBound]) + +ints :: [Int] +ints = [1 .. 10000] + +doubles :: [Double] +doubles = [fromIntegral i / 7 | i <- [1 .. 10000 :: Int]] + +integers :: [Integer] +integers = [2 ^ (100 :: Int) + i | i <- [1 .. 2000]] + +word64s :: [Word64] +word64s = [maxBound - i | i <- [1 .. 10000]] + +int8s :: [Int8] +int8s = take 10000 (cycle [minBound .. maxBound]) + +bools :: [Bool] +bools = take 10000 (cycle [True, False]) + +maybes :: [Maybe Int] +maybes = [if even i then Just i else Nothing | i <- [1 .. 10000]] + +tuples :: [(Int, Text, Bool)] +tuples = [(i, Text.pack (show i), even i) | i <- [1 .. 3000]] + +texts :: [Text] +texts = + [ Text.replicate 8 ("text \"" <> Text.pack (show i) <> "\" \\n ") + | i <- [1 .. 1000 :: Int] + ] + +strings :: [String] +strings = ["string " <> show i | i <- [1 .. 3000 :: Int]] + +textMap :: Map Text Int +textMap = Map.fromList [("key" <> Text.pack (show i), i) | i <- [1 .. 1000]] + +intMap :: Map Int Text +intMap = Map.fromList [(i, Text.pack (show i)) | i <- [1 .. 1000]] + +pairMap :: Map (Int, Int) Bool +pairMap = Map.fromList [((i, i * 2), even i) | i <- [1 .. 1000]] + +nested :: [[Int]] +nested = [[i .. i + 99] | i <- [1 .. 100]] + +rose :: Rose +rose = grow (6 :: Int) 1 + where + grow 0 i = Rose i [] + grow n i = Rose i [grow (n - 1) (i * 3 + j) | j <- [0 .. 2]] + +wides :: [Wide] +wides = + [ Wide i t (even i) d m i t (odd i) d m i t (even i) d m i t (odd i) d m + | i <- [1 .. 500 :: Int] + , let + t = "wide " <> Text.pack (show i) + d = fromIntegral i / 3 + m = if even i then Just i else Nothing + ] + +variants :: [Variant] +variants = take 3000 $ cycle + [Created 1 "created", Updated 2 ["a", "bb", "ccc"], Deleted 3] + +deeps :: [Deep] +deeps = [chain (50 :: Int) i | i <- [1 .. 100 :: Int]] + where + chain 0 _ = Deep "leaf" Nothing + chain n i = Deep (Text.pack (show (n, i))) (Just (chain (n - 1) i)) + +eithers :: [Either Int Text] +eithers = + [if even i then Left i else Right (Text.pack (show i)) | i <- [1 .. 5000]] + +longTexts :: [Text] +longTexts = + [ Text.replicate 500 ("line \"" <> Text.pack (show i) <> "\"\t\\ ") + | i <- [1 .. 10 :: Int] + ] + +hashMap :: HashMap Text Int +hashMap = + HashMap.fromList [("key" <> Text.pack (show i), i) | i <- [1 .. 1000]] + +times :: [UTCTime] +times = + [posixSecondsToUTCTime (fromIntegral i * 1234.5) | i <- [1 .. 1000 :: Int]] + +value :: Value +value = tree (6 :: Int) + where + tree 0 = Number 1 + tree n = object + [ "leaf" .= String "abc" + , "flag" .= Bool True + , "children" .= [tree (n - 1), tree (n - 1), Null] + ] + +{- | Compare @aeson@ & `Json` on a dataset, +checking first that they agree on it. +-} +dataset + :: (Json a, ToJSON a, FromJSON a, NFData a) => String -> a -> Benchmark +dataset label a = env agreed $ \ ~(bytes, val) -> + bgroup label + [ bgroup "encode" + [ bench "aeson toEncoding" (nf encode a) + , bench "Json jsonEncode" (nf (encodingToLazyByteString . jsonEncode) a) + ] + , bgroup "toValue" + [ bench "aeson toJSON" (nf toJSON a) + , bench "Json jsonPrint" (nf jsonPrint a) + ] + , bgroup "fromValue" + [ bench "aeson parseJSON" (nf (fromValueAeson a) val) + , bench "Json jsonParse" (nf (fromValueJson a) val) + ] + , bgroup "decode" + [ bench "aeson decode" (nf (decodeAeson a) bytes) + , bench "Json jsonDecode" (nf (decodeJson a) bytes) + ] + ] + where + agreed + | jsonPrint a /= toJSON a = disagree "jsonPrint" + | decode (encodingToLazyByteString (jsonEncode a)) /= Just (toJSON a) = + disagree "jsonEncode" + | isNothing (decodeJson a (encode a)) = disagree "jsonDecode" + | otherwise = pure (encode a, toJSON a) + disagree run = fail (label <> ": " <> run <> " disagrees with aeson") + +fromValueAeson :: FromJSON a => a -> Value -> Maybe a +fromValueAeson _ = either (const Nothing) Just . parseEither parseJSON + +fromValueJson :: Json a => a -> Value -> Maybe a +fromValueJson _ = either (const Nothing) Just . jsonParse + +decodeAeson :: FromJSON a => a -> ByteString -> Maybe a +decodeAeson _ = decode + +decodeJson :: Json a => a -> ByteString -> Maybe a +decodeJson _ = either (const Nothing) Just . jsonDecode + +main :: IO () +main = defaultMain + [ dataset "records" people + , dataset "sums" shapes + , dataset "enums" weekdays + , dataset "ints" ints + , dataset "doubles" doubles + , dataset "integers" integers + , dataset "word64s" word64s + , dataset "int8s" int8s + , dataset "bools" bools + , dataset "maybes" maybes + , dataset "tuples" tuples + , dataset "texts" texts + , dataset "strings" strings + , dataset "textMap" textMap + , dataset "intMap" intMap + , dataset "pairMap" pairMap + , dataset "nested" nested + , dataset "rose" rose + , dataset "times" times + , dataset "wide" wides + , dataset "variants" variants + , dataset "deep" deeps + , dataset "eithers" eithers + , dataset "longTexts" longTexts + , dataset "hashMap" hashMap + , dataset "value" value + , dataset "twitter10" Doc.twitter10 + , dataset "twitter100" Doc.twitter100 + , dataset "jp100" Doc.jp100 + , dataset "githubIssues" Doc.githubIssues + , dataset "geometry" Doc.geoJson + , dataset "people" Doc.people + , bgroup "typescript" + [ bench "records" (nf (\() -> tsTypes (type '[Person])) ()) + , bench "sums" (nf (\() -> tsTypes [Shape]) ()) + , bench "rose" (nf (\() -> tsTypes (type '[Rose])) ()) + , bench "value" (nf (\() -> tsTypes [Value]) ()) + , bench "twice12" (nf (\() -> tsTypes [Twice12]) ()) + ] + ] + +-- | The TypeScript declarations of types, as text. +tsTypes :: forall (as :: [Type]) -> All Json as => Text.Text +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)))) + (Seq.empty @Char) diff --git a/distributors-json/bench/data/README.md b/distributors-json/bench/data/README.md new file mode 100644 index 00000000..87c6b15f --- /dev/null +++ b/distributors-json/bench/data/README.md @@ -0,0 +1,14 @@ +# Benchmark data + +These JSON documents are copied from [aeson](https://github.com/haskell/aeson)'s +benchmarks (`benchmarks/json-data`, aeson 2.2.5.1), which are distributed under +aeson's BSD-3-Clause license: + +> Copyright (c) 2011, MailRank, Inc. 2014-2021 Aeson project contributors. +> All rights reserved. + +- `twitter10.json`, `twitter100.json`: Twitter search results, 10 & 100 stories. +- `jp100.json`: Twitter search results of Japanese text, 100 stories. +- `github-issues.json`: 30 issues of a GitHub repository, by GitHub's API. +- `geometry.json`: a GeoJSON polygon. +- `buffer-builder.json`: 96 generated records of people. diff --git a/distributors-json/bench/data/buffer-builder.json b/distributors-json/bench/data/buffer-builder.json new file mode 100644 index 00000000..046a5a0c --- /dev/null +++ b/distributors-json/bench/data/buffer-builder.json @@ -0,0 +1,4322 @@ +[ + { + "_id": "54727a90e43524efe8abfdac", + "index": 0, + "guid": "aaa926e8-8359-4afe-adb0-dca0401de765", + "isActive": true, + "balance": "$1,114.73", + "picture": "http://placehold.it/32x32", + "age": 20, + "eyeColor": "green", + "name": "Dillon Valenzuela", + "gender": "male", + "company": "GEOFORM", + "email": "dillonvalenzuela@geoform.com", + "phone": "+1 (817) 536-3796", + "address": "309 Desmond Court, Zarephath, Montana, 6156", + "about": "Dolore laboris excepteur sunt velit velit nostrud non esse qui laboris nostrud Lorem. Amet anim occaecat et ipsum. Ad proident nostrud elit adipisicing anim labore consectetur ut amet elit. Tempor aliqua in ea eiusmod elit Lorem cillum est laboris. Nisi Lorem amet amet Lorem. Nostrud sunt incididunt magna nostrud amet enim. Laboris ad et fugiat dolor ad proident aliquip nisi do ea eiusmod enim proident.\r\n", + "registered": "2014-08-17T07:29:03 +07:00", + "latitude": -17.423462, + "longitude": 121.069662, + "tags": [ + "sunt", + "ex", + "irure", + "cillum", + "velit", + "duis", + "sit" + ], + "friends": [ + { + "id": 0, + "name": "Joyce Jordan" + }, + { + "id": 1, + "name": "Ophelia Rosales" + }, + { + "id": 2, + "name": "Florine Stark" + } + ], + "greeting": "Hello, Dillon Valenzuela! You have 9 unread messages.", + "favoriteFruit": "apple" + }, + { + "_id": "54727a90f520a07ff2498a69", + "index": 1, + "guid": "8f78cc18-a7ef-498b-9adf-60f008a48c02", + "isActive": false, + "balance": "$1,324.52", + "picture": "http://placehold.it/32x32", + "age": 33, + "eyeColor": "blue", + "name": "Donovan Weiss", + "gender": "male", + "company": "TELPOD", + "email": "donovanweiss@telpod.com", + "phone": "+1 (962) 417-2408", + "address": "511 Grant Avenue, Westmoreland, Hawaii, 5092", + "about": "Laborum excepteur exercitation sint veniam dolor. Dolor aliqua esse do aliqua adipisicing. Ea magna minim veniam tempor ipsum. Incididunt anim reprehenderit occaecat proident eiusmod anim Lorem aliquip dolore incididunt. Consequat occaecat qui minim commodo est velit ex.\r\n", + "registered": "2014-09-30T23:49:41 +07:00", + "latitude": -18.034963, + "longitude": 70.821705, + "tags": [ + "cupidatat", + "excepteur", + "id", + "consectetur", + "ea", + "enim", + "et" + ], + "friends": [ + { + "id": 0, + "name": "Cummings Irwin" + }, + { + "id": 1, + "name": "Conley Lester" + }, + { + "id": 2, + "name": "Katy Holt" + } + ], + "greeting": "Hello, Donovan Weiss! You have 2 unread messages.", + "favoriteFruit": "apple" + }, + { + "_id": "54727a90fbb3f49ea6d40dde", + "index": 2, + "guid": "69a4c6d7-6189-4a90-ae00-7b64ab1d5a2d", + "isActive": false, + "balance": "$2,739.87", + "picture": "http://placehold.it/32x32", + "age": 33, + "eyeColor": "brown", + "name": "Renee Calderon", + "gender": "female", + "company": "TALKOLA", + "email": "reneecalderon@talkola.com", + "phone": "+1 (910) 523-3382", + "address": "323 Montauk Avenue, Greenwich, South Dakota, 8034", + "about": "Reprehenderit deserunt et do proident Lorem Lorem dolor labore ullamco eu nulla laborum voluptate. Consectetur sint magna enim commodo dolore ullamco in. Nulla id proident esse veniam proident esse velit exercitation do. Qui nulla magna anim Lorem dolor culpa id. Nostrud cupidatat officia culpa sit irure voluptate exercitation voluptate nostrud elit. Duis occaecat velit fugiat exercitation anim aute laborum irure.\r\n", + "registered": "2014-09-11T20:48:20 +07:00", + "latitude": 15.654081, + "longitude": 84.156609, + "tags": [ + "dolor", + "et", + "in", + "veniam", + "non", + "est", + "enim" + ], + "friends": [ + { + "id": 0, + "name": "Gilda Murray" + }, + { + "id": 1, + "name": "Marguerite West" + }, + { + "id": 2, + "name": "Chrystal Rojas" + } + ], + "greeting": "Hello, Renee Calderon! You have 1 unread messages.", + "favoriteFruit": "strawberry" + }, + { + "_id": "54727a90c5ea2a48502a0640", + "index": 3, + "guid": "689a64d7-16b0-41dc-947d-035b40a29ed4", + "isActive": false, + "balance": "$3,805.39", + "picture": "http://placehold.it/32x32", + "age": 32, + "eyeColor": "blue", + "name": "Aguirre Garrett", + "gender": "male", + "company": "ZOSIS", + "email": "aguirregarrett@zosis.com", + "phone": "+1 (811) 471-3145", + "address": "198 Baycliff Terrace, Clarence, District Of Columbia, 1528", + "about": "Deserunt minim aliquip magna ut fugiat quis. Quis consequat culpa reprehenderit minim do eiusmod adipisicing nostrud aute. Lorem nostrud laborum quis dolore tempor tempor magna aute eu pariatur dolor est. Reprehenderit ex consectetur adipisicing Lorem nostrud fugiat aute non quis anim laborum aute proident amet. Sunt consectetur eu ut eu mollit ipsum.\r\n", + "registered": "2014-02-14T04:27:27 +08:00", + "latitude": 25.922024, + "longitude": 107.428199, + "tags": [ + "esse", + "officia", + "commodo", + "esse", + "cupidatat", + "amet", + "ad" + ], + "friends": [ + { + "id": 0, + "name": "Penelope Humphrey" + }, + { + "id": 1, + "name": "Church Byers" + }, + { + "id": 2, + "name": "Hazel Stafford" + } + ], + "greeting": "Hello, Aguirre Garrett! You have 4 unread messages.", + "favoriteFruit": "apple" + }, + { + "_id": "54727a9096bcf2d2f4b4aeff", + "index": 4, + "guid": "77392422-81ad-48c8-9cfc-37d142a814d5", + "isActive": false, + "balance": "$1,956.06", + "picture": "http://placehold.it/32x32", + "age": 26, + "eyeColor": "brown", + "name": "Griffin Mclaughlin", + "gender": "male", + "company": "COMTOUR", + "email": "griffinmclaughlin@comtour.com", + "phone": "+1 (950) 494-2956", + "address": "549 Robert Street, Libertytown, North Carolina, 4377", + "about": "Exercitation culpa ad id deserunt sit ullamco anim anim ad aute officia ut tempor. Ullamco dolor pariatur enim exercitation commodo consectetur fugiat velit nulla mollit pariatur occaecat. Amet voluptate qui labore mollit ipsum consequat. Esse pariatur proident ad pariatur aliquip labore quis voluptate quis ut culpa tempor. Reprehenderit sint id officia deserunt quis laboris. Velit ipsum dolore anim consectetur.\r\n", + "registered": "2014-06-23T04:48:12 +07:00", + "latitude": 8.808284, + "longitude": 20.539814, + "tags": [ + "consequat", + "proident", + "eiusmod", + "dolore", + "in", + "laborum", + "non" + ], + "friends": [ + { + "id": 0, + "name": "Hinton Santiago" + }, + { + "id": 1, + "name": "Talley Dyer" + }, + { + "id": 2, + "name": "Karen Logan" + } + ], + "greeting": "Hello, Griffin Mclaughlin! You have 3 unread messages.", + "favoriteFruit": "apple" + }, + { + "_id": "54727a9010e5c5ac55919561", + "index": 5, + "guid": "7e6fca4d-0329-47ab-b3e7-f4d6a6ee4dd2", + "isActive": true, + "balance": "$3,767.46", + "picture": "http://placehold.it/32x32", + "age": 36, + "eyeColor": "brown", + "name": "Rachel Mcclure", + "gender": "female", + "company": "ESCENTA", + "email": "rachelmcclure@escenta.com", + "phone": "+1 (857) 518-3454", + "address": "901 Harwood Place, Rossmore, Tennessee, 3213", + "about": "Nisi enim deserunt ut ex mollit fugiat. Magna nostrud culpa irure nulla mollit nisi. Sit ea incididunt amet culpa veniam voluptate Lorem sunt dolore amet. Exercitation tempor eiusmod exercitation officia dolor. Ut ea sint veniam cupidatat et. Sunt nostrud ad ipsum non elit elit esse ut dolor. Et officia et minim ipsum amet sint eu ut nostrud adipisicing cillum ullamco.\r\n", + "registered": "2014-05-29T20:42:11 +07:00", + "latitude": 8.132878, + "longitude": -99.198755, + "tags": [ + "est", + "Lorem", + "ullamco", + "nisi", + "reprehenderit", + "nisi", + "cupidatat" + ], + "friends": [ + { + "id": 0, + "name": "Michael Martin" + }, + { + "id": 1, + "name": "Gayle Heath" + }, + { + "id": 2, + "name": "Slater Bender" + } + ], + "greeting": "Hello, Rachel Mcclure! You have 2 unread messages.", + "favoriteFruit": "apple" + }, + { + "_id": "54727a90a76a5ba627b180c9", + "index": 6, + "guid": "fbf59485-142c-4eb6-a98e-8952cbb19942", + "isActive": true, + "balance": "$2,139.12", + "picture": "http://placehold.it/32x32", + "age": 28, + "eyeColor": "blue", + "name": "Megan Morrow", + "gender": "female", + "company": "PETICULAR", + "email": "meganmorrow@peticular.com", + "phone": "+1 (825) 572-2854", + "address": "151 Jardine Place, Boonville, Idaho, 160", + "about": "Magna reprehenderit aliqua quis eiusmod eu minim ut. Consectetur non veniam est et aliqua mollit. Aliqua eiusmod sit fugiat qui quis nisi mollit officia do. Enim quis quis occaecat ullamco anim reprehenderit exercitation. Ad id id laborum ipsum ipsum cillum ipsum occaecat irure. Commodo voluptate ullamco excepteur ea laboris adipisicing veniam cillum commodo velit anim. Occaecat magna laborum non ex anim consequat dolor cillum excepteur velit duis commodo officia veniam.\r\n", + "registered": "2014-04-16T08:56:52 +07:00", + "latitude": 57.771446, + "longitude": -146.885322, + "tags": [ + "veniam", + "officia", + "magna", + "ipsum", + "nulla", + "ea", + "mollit" + ], + "friends": [ + { + "id": 0, + "name": "Marina Wise" + }, + { + "id": 1, + "name": "Ann Mercado" + }, + { + "id": 2, + "name": "Glenn Duran" + } + ], + "greeting": "Hello, Megan Morrow! You have 7 unread messages.", + "favoriteFruit": "banana" + }, + { + "_id": "54727a90776f7328f4df750f", + "index": 7, + "guid": "ef99cc91-061c-49c5-9901-3ac22a75bc92", + "isActive": true, + "balance": "$3,161.69", + "picture": "http://placehold.it/32x32", + "age": 37, + "eyeColor": "blue", + "name": "Lawson Kirby", + "gender": "male", + "company": "PLASMOSIS", + "email": "lawsonkirby@plasmosis.com", + "phone": "+1 (853) 583-2577", + "address": "122 Linden Boulevard, Edneyville, Palau, 6050", + "about": "Elit ullamco reprehenderit eiusmod in duis minim exercitation incididunt reprehenderit eiusmod nulla. Cupidatat ea anim incididunt esse ea eu esse laboris velit. Culpa sunt exercitation officia amet voluptate enim duis ipsum ex anim quis nisi. Dolor officia irure do veniam do amet ullamco eu.\r\n", + "registered": "2014-08-13T02:14:13 +07:00", + "latitude": -16.166232, + "longitude": 12.254111, + "tags": [ + "et", + "aliqua", + "aute", + "voluptate", + "officia", + "est", + "quis" + ], + "friends": [ + { + "id": 0, + "name": "Marquita Hutchinson" + }, + { + "id": 1, + "name": "Karla Conner" + }, + { + "id": 2, + "name": "Mattie Page" + } + ], + "greeting": "Hello, Lawson Kirby! You have 3 unread messages.", + "favoriteFruit": "banana" + }, + { + "_id": "54727a90b8e9fff0ed297a59", + "index": 8, + "guid": "9bb8d813-704c-4714-929f-1321576a2701", + "isActive": false, + "balance": "$1,275.37", + "picture": "http://placehold.it/32x32", + "age": 23, + "eyeColor": "brown", + "name": "Pat Medina", + "gender": "female", + "company": "PLEXIA", + "email": "patmedina@plexia.com", + "phone": "+1 (933) 557-3028", + "address": "623 Sunnyside Court, Edinburg, Minnesota, 2620", + "about": "Est aliqua sint adipisicing labore magna sunt laboris non eu. Aute deserunt commodo Lorem amet sunt amet qui qui incididunt anim Lorem culpa. Ea exercitation officia dolor aute incididunt ea enim. Nulla aliqua ut ullamco sunt velit cillum esse minim incididunt ut mollit aute. Fugiat eiusmod anim laborum duis aliquip aute reprehenderit qui dolor officia amet labore id. Enim officia reprehenderit incididunt sit. Nisi ullamco nisi adipisicing esse eiusmod dolore veniam cupidatat consequat sunt.\r\n", + "registered": "2014-10-22T20:29:14 +07:00", + "latitude": -9.032987, + "longitude": 71.98971, + "tags": [ + "laborum", + "dolore", + "aliqua", + "tempor", + "eu", + "elit", + "voluptate" + ], + "friends": [ + { + "id": 0, + "name": "Elnora Moses" + }, + { + "id": 1, + "name": "Alexandra Carter" + }, + { + "id": 2, + "name": "Beth Pacheco" + } + ], + "greeting": "Hello, Pat Medina! You have 5 unread messages.", + "favoriteFruit": "apple" + }, + { + "_id": "54727a908c17a619571cfd39", + "index": 9, + "guid": "0a5de094-eadc-4120-8941-964f27fbc898", + "isActive": true, + "balance": "$1,939.34", + "picture": "http://placehold.it/32x32", + "age": 35, + "eyeColor": "brown", + "name": "Gibbs Butler", + "gender": "male", + "company": "OPTIQUE", + "email": "gibbsbutler@optique.com", + "phone": "+1 (956) 574-3434", + "address": "552 Columbia Street, Richmond, Illinois, 903", + "about": "Laboris eu ut magna exercitation non laboris sint. Mollit velit est exercitation enim exercitation reprehenderit culpa eiusmod laboris fugiat veniam adipisicing. Voluptate enim id do eu officia duis in incididunt. Esse do laboris pariatur cupidatat elit.\r\n", + "registered": "2014-02-24T15:46:23 +08:00", + "latitude": -68.874573, + "longitude": -6.876165, + "tags": [ + "excepteur", + "deserunt", + "ea", + "labore", + "aliqua", + "deserunt", + "labore" + ], + "friends": [ + { + "id": 0, + "name": "Chen Langley" + }, + { + "id": 1, + "name": "Latonya Vaughan" + }, + { + "id": 2, + "name": "Simone Sutton" + } + ], + "greeting": "Hello, Gibbs Butler! You have 2 unread messages.", + "favoriteFruit": "apple" + }, + { + "_id": "54727a9049447027a378812c", + "index": 10, + "guid": "406ae437-820d-4e0f-b8dc-1da0ddcc561c", + "isActive": false, + "balance": "$1,348.37", + "picture": "http://placehold.it/32x32", + "age": 39, + "eyeColor": "brown", + "name": "Bond Peck", + "gender": "male", + "company": "DANCERITY", + "email": "bondpeck@dancerity.com", + "phone": "+1 (918) 554-2856", + "address": "361 Cortelyou Road, Hollins, Missouri, 131", + "about": "Nisi ut ea ut deserunt. Consequat pariatur dolor consequat sunt. Ullamco aute proident excepteur fugiat id consequat eu nisi occaecat.\r\n", + "registered": "2014-05-15T02:12:14 +07:00", + "latitude": -79.266187, + "longitude": 92.89454, + "tags": [ + "ex", + "est", + "sit", + "irure", + "qui", + "veniam", + "exercitation" + ], + "friends": [ + { + "id": 0, + "name": "Nettie Pope" + }, + { + "id": 1, + "name": "Alyssa Hensley" + }, + { + "id": 2, + "name": "Puckett Kinney" + } + ], + "greeting": "Hello, Bond Peck! You have 7 unread messages.", + "favoriteFruit": "strawberry" + }, + { + "_id": "54727a9062a82eff9506c4d7", + "index": 11, + "guid": "b7400b79-2b71-46cd-9260-13e0767b437e", + "isActive": true, + "balance": "$1,757.66", + "picture": "http://placehold.it/32x32", + "age": 20, + "eyeColor": "blue", + "name": "Garrison Warner", + "gender": "male", + "company": "NAMEBOX", + "email": "garrisonwarner@namebox.com", + "phone": "+1 (874) 417-2183", + "address": "927 Knapp Street, Shaft, Connecticut, 2188", + "about": "Sint commodo ipsum commodo id magna labore in. Pariatur nostrud reprehenderit adipisicing amet enim ut quis laboris culpa exercitation deserunt cillum. Adipisicing excepteur sunt do labore anim exercitation non excepteur. Minim consectetur sit dolore occaecat et aliquip aliquip excepteur aliquip ut do eiusmod ea nulla. Nostrud sunt dolore ea sunt est enim occaecat culpa minim. Sit elit mollit mollit aliquip eu ex. Tempor nulla voluptate dolore ex.\r\n", + "registered": "2014-06-18T03:58:19 +07:00", + "latitude": -87.629414, + "longitude": 96.653639, + "tags": [ + "eu", + "deserunt", + "dolore", + "nisi", + "culpa", + "ullamco", + "ipsum" + ], + "friends": [ + { + "id": 0, + "name": "Gutierrez Sears" + }, + { + "id": 1, + "name": "Holly Jacobson" + }, + { + "id": 2, + "name": "Henry Delgado" + } + ], + "greeting": "Hello, Garrison Warner! You have 4 unread messages.", + "favoriteFruit": "strawberry" + }, + { + "_id": "54727a904638f48ca7f9e85e", + "index": 12, + "guid": "4cd59615-46b7-4733-a439-dc59c0ca0118", + "isActive": true, + "balance": "$3,897.06", + "picture": "http://placehold.it/32x32", + "age": 24, + "eyeColor": "blue", + "name": "Consuelo Bray", + "gender": "female", + "company": "COMTEST", + "email": "consuelobray@comtest.com", + "phone": "+1 (945) 432-2620", + "address": "433 Clinton Street, Clarktown, Maine, 6916", + "about": "Do occaecat consectetur tempor Lorem ullamco commodo exercitation veniam reprehenderit nulla officia. Nisi irure sunt cupidatat amet et excepteur quis et do. Et commodo nulla occaecat do sint quis mollit reprehenderit do laboris magna. Dolore ea sit aute esse consequat fugiat Lorem occaecat adipisicing adipisicing qui aute elit. Amet veniam anim ipsum aute officia. Fugiat nisi magna anim pariatur minim magna exercitation duis officia.\r\n", + "registered": "2014-03-19T07:39:44 +07:00", + "latitude": 7.760448, + "longitude": -92.399314, + "tags": [ + "irure", + "veniam", + "ex", + "ullamco", + "anim", + "do", + "enim" + ], + "friends": [ + { + "id": 0, + "name": "Ellen Bullock" + }, + { + "id": 1, + "name": "Davis Vaughn" + }, + { + "id": 2, + "name": "Robert Mendoza" + } + ], + "greeting": "Hello, Consuelo Bray! You have 8 unread messages.", + "favoriteFruit": "apple" + }, + { + "_id": "54727a90fd85a45d33d54cf7", + "index": 13, + "guid": "53868eb7-df5c-445d-ad62-6124db081b6c", + "isActive": false, + "balance": "$2,988.04", + "picture": "http://placehold.it/32x32", + "age": 21, + "eyeColor": "green", + "name": "Clark Skinner", + "gender": "male", + "company": "OVOLO", + "email": "clarkskinner@ovolo.com", + "phone": "+1 (834) 587-2391", + "address": "967 Dewey Place, Gibsonia, Puerto Rico, 6398", + "about": "Duis irure exercitation ullamco amet aliquip minim sit consequat officia laborum id ad. Lorem duis velit consequat non irure nulla elit elit velit dolor ullamco qui fugiat. Quis ad velit ea consectetur veniam Lorem incididunt quis magna eiusmod. Et nostrud irure tempor nostrud esse.\r\n", + "registered": "2014-10-11T06:48:59 +07:00", + "latitude": -62.633073, + "longitude": -121.03338, + "tags": [ + "ut", + "deserunt", + "adipisicing", + "enim", + "amet", + "proident", + "officia" + ], + "friends": [ + { + "id": 0, + "name": "Francine Petersen" + }, + { + "id": 1, + "name": "Lena Robles" + }, + { + "id": 2, + "name": "Mcintyre Gardner" + } + ], + "greeting": "Hello, Clark Skinner! You have 6 unread messages.", + "favoriteFruit": "strawberry" + }, + { + "_id": "54727a908789850c55818269", + "index": 14, + "guid": "84cc7d0b-0544-40f8-900a-825429b0ee87", + "isActive": true, + "balance": "$3,012.07", + "picture": "http://placehold.it/32x32", + "age": 32, + "eyeColor": "blue", + "name": "Katie Allen", + "gender": "female", + "company": "SYBIXTEX", + "email": "katieallen@sybixtex.com", + "phone": "+1 (959) 504-2563", + "address": "543 Heath Place, Bartonsville, New Mexico, 4882", + "about": "Nisi ullamco anim in culpa in non nostrud ex aliqua ex. Nisi occaecat exercitation sint ad magna Lorem amet anim pariatur quis. Dolore consequat quis dolor ea. Aliquip sunt ex cillum tempor fugiat laboris ipsum mollit aliqua reprehenderit nulla fugiat exercitation ad.\r\n", + "registered": "2014-03-17T05:45:50 +07:00", + "latitude": -79.18988, + "longitude": -95.023826, + "tags": [ + "commodo", + "incididunt", + "voluptate", + "sit", + "mollit", + "veniam", + "et" + ], + "friends": [ + { + "id": 0, + "name": "Hampton Jimenez" + }, + { + "id": 1, + "name": "Lara Cline" + }, + { + "id": 2, + "name": "Jennings Cantu" + } + ], + "greeting": "Hello, Katie Allen! You have 3 unread messages.", + "favoriteFruit": "banana" + }, + { + "_id": "54727a90787015f61850162f", + "index": 15, + "guid": "d848ac32-1d24-471a-ad7e-d272f52cb5fc", + "isActive": true, + "balance": "$1,416.33", + "picture": "http://placehold.it/32x32", + "age": 38, + "eyeColor": "brown", + "name": "Pratt Watson", + "gender": "male", + "company": "HARMONEY", + "email": "prattwatson@harmoney.com", + "phone": "+1 (905) 557-3197", + "address": "867 Campus Road, Lindisfarne, Northern Mariana Islands, 8349", + "about": "Nisi mollit eu reprehenderit qui ut eu cillum cupidatat do. Et ex qui minim proident. Quis aliquip aliquip exercitation exercitation dolor aute nostrud fugiat ea. Id ullamco occaecat reprehenderit mollit occaecat ea ipsum cupidatat ea consequat fugiat.\r\n", + "registered": "2014-11-15T05:07:03 +08:00", + "latitude": -66.117872, + "longitude": 52.197654, + "tags": [ + "ullamco", + "sunt", + "ea", + "veniam", + "elit", + "sint", + "id" + ], + "friends": [ + { + "id": 0, + "name": "Dale Ray" + }, + { + "id": 1, + "name": "Beryl Hayes" + }, + { + "id": 2, + "name": "Millie Good" + } + ], + "greeting": "Hello, Pratt Watson! You have 2 unread messages.", + "favoriteFruit": "banana" + }, + { + "_id": "54727a90c4106283f0c1eed9", + "index": 16, + "guid": "6839b0af-5c69-45e2-b83b-381ff05034e6", + "isActive": false, + "balance": "$2,720.67", + "picture": "http://placehold.it/32x32", + "age": 31, + "eyeColor": "blue", + "name": "Shari Mendez", + "gender": "female", + "company": "INDEXIA", + "email": "sharimendez@indexia.com", + "phone": "+1 (895) 589-3754", + "address": "533 Conduit Boulevard, Forestburg, Mississippi, 6873", + "about": "Ex excepteur elit id laborum veniam dolore duis ea eiusmod minim. Consequat reprehenderit magna elit tempor voluptate esse officia minim reprehenderit consequat fugiat qui eiusmod. Et Lorem nisi voluptate tempor nulla cillum reprehenderit pariatur elit dolore occaecat laboris sunt. Anim cupidatat do veniam pariatur nostrud anim eu aliqua veniam ad cillum quis.\r\n", + "registered": "2014-05-04T10:15:37 +07:00", + "latitude": 31.931465, + "longitude": 155.732674, + "tags": [ + "enim", + "sint", + "est", + "aliqua", + "elit", + "laboris", + "occaecat" + ], + "friends": [ + { + "id": 0, + "name": "Desiree Norris" + }, + { + "id": 1, + "name": "Abigail Crosby" + }, + { + "id": 2, + "name": "Anderson Alston" + } + ], + "greeting": "Hello, Shari Mendez! You have 6 unread messages.", + "favoriteFruit": "banana" + }, + { + "_id": "54727a90474ecbf0a9c34382", + "index": 17, + "guid": "079bb238-0556-4ede-8243-2eaadabb3050", + "isActive": false, + "balance": "$2,629.01", + "picture": "http://placehold.it/32x32", + "age": 26, + "eyeColor": "green", + "name": "Hancock Rowland", + "gender": "male", + "company": "SOFTMICRO", + "email": "hancockrowland@softmicro.com", + "phone": "+1 (983) 565-2302", + "address": "168 Dooley Street, Driftwood, North Dakota, 3607", + "about": "Eu voluptate velit incididunt ipsum amet veniam. Lorem aliquip adipisicing incididunt laborum aliqua elit consectetur aute velit voluptate ea. Mollit irure duis consequat veniam sint nostrud est dolore sunt anim laboris fugiat. Dolor officia elit esse elit dolore. Minim non est duis culpa ullamco veniam excepteur. Veniam ullamco amet ullamco esse voluptate laboris velit.\r\n", + "registered": "2014-09-06T04:32:40 +07:00", + "latitude": -68.853851, + "longitude": 135.592762, + "tags": [ + "nulla", + "ut", + "magna", + "adipisicing", + "officia", + "nulla", + "cillum" + ], + "friends": [ + { + "id": 0, + "name": "Shannon Burch" + }, + { + "id": 1, + "name": "Marisol Nixon" + }, + { + "id": 2, + "name": "Poole Wolfe" + } + ], + "greeting": "Hello, Hancock Rowland! You have 4 unread messages.", + "favoriteFruit": "apple" + }, + { + "_id": "54727a90cf708eccc9032fd0", + "index": 18, + "guid": "8930775e-9271-400e-b662-77ee520b3369", + "isActive": false, + "balance": "$1,026.68", + "picture": "http://placehold.it/32x32", + "age": 33, + "eyeColor": "blue", + "name": "Luna Rice", + "gender": "male", + "company": "GEEKULAR", + "email": "lunarice@geekular.com", + "phone": "+1 (840) 541-2996", + "address": "417 Varick Avenue, Martell, Vermont, 2749", + "about": "Aliqua enim ullamco do eiusmod. Ipsum incididunt minim esse veniam nisi velit. Ipsum reprehenderit velit eiusmod nisi magna dolore consectetur reprehenderit magna culpa. Commodo excepteur labore proident adipisicing in velit sit occaecat reprehenderit id.\r\n", + "registered": "2014-10-15T05:13:55 +07:00", + "latitude": -57.335675, + "longitude": -173.387514, + "tags": [ + "fugiat", + "enim", + "exercitation", + "aliquip", + "Lorem", + "laboris", + "deserunt" + ], + "friends": [ + { + "id": 0, + "name": "Mclaughlin Schmidt" + }, + { + "id": 1, + "name": "Munoz Key" + }, + { + "id": 2, + "name": "Candace Stephenson" + } + ], + "greeting": "Hello, Luna Rice! You have 2 unread messages.", + "favoriteFruit": "strawberry" + }, + { + "_id": "54727a90a0fd17c9e4f5d33f", + "index": 19, + "guid": "570f0e20-085f-4c40-9e84-b555cc4e79c8", + "isActive": true, + "balance": "$3,333.73", + "picture": "http://placehold.it/32x32", + "age": 39, + "eyeColor": "green", + "name": "Beverly Newton", + "gender": "female", + "company": "ECLIPSENT", + "email": "beverlynewton@eclipsent.com", + "phone": "+1 (902) 595-3072", + "address": "903 Knight Court, Gardiner, Rhode Island, 3327", + "about": "Labore culpa tempor nisi commodo dolore exercitation est eu. Aute exercitation duis proident deserunt culpa ullamco. Irure cillum elit ea sint dolore ipsum adipisicing anim sit. Amet incididunt labore ex fugiat mollit quis reprehenderit nisi ut excepteur proident ullamco laboris. Reprehenderit voluptate aliqua labore culpa in non magna velit nostrud amet. Minim nulla ea culpa irure. Minim ea ex nisi proident ex ex quis ipsum culpa.\r\n", + "registered": "2014-09-23T10:25:17 +07:00", + "latitude": 23.973865, + "longitude": -71.604537, + "tags": [ + "ullamco", + "anim", + "id", + "pariatur", + "est", + "cupidatat", + "qui" + ], + "friends": [ + { + "id": 0, + "name": "James Garner" + }, + { + "id": 1, + "name": "Goff Reese" + }, + { + "id": 2, + "name": "Casey Bradford" + } + ], + "greeting": "Hello, Beverly Newton! You have 2 unread messages.", + "favoriteFruit": "apple" + }, + { + "_id": "54727a90fd0cafc2fa513aea", + "index": 20, + "guid": "c0e243a3-bf20-4112-8dab-0b0aed785060", + "isActive": true, + "balance": "$2,290.97", + "picture": "http://placehold.it/32x32", + "age": 28, + "eyeColor": "blue", + "name": "Stokes Dodson", + "gender": "male", + "company": "SLAMBDA", + "email": "stokesdodson@slambda.com", + "phone": "+1 (994) 443-2829", + "address": "232 Kosciusko Street, Manitou, Michigan, 2638", + "about": "Nostrud minim cillum elit reprehenderit ut do eu. Quis deserunt enim nisi do proident quis quis voluptate elit. Sit nostrud et amet nostrud pariatur exercitation cillum ullamco laborum ullamco do id. Tempor incididunt dolore consequat ut amet in reprehenderit magna anim laboris reprehenderit tempor adipisicing.\r\n", + "registered": "2014-05-21T16:30:03 +07:00", + "latitude": -86.112825, + "longitude": 56.089279, + "tags": [ + "ea", + "dolor", + "dolor", + "consequat", + "nulla", + "cillum", + "voluptate" + ], + "friends": [ + { + "id": 0, + "name": "Jodi Camacho" + }, + { + "id": 1, + "name": "Michele Miles" + }, + { + "id": 2, + "name": "Rene Mitchell" + } + ], + "greeting": "Hello, Stokes Dodson! You have 9 unread messages.", + "favoriteFruit": "banana" + }, + { + "_id": "54727a908be67242a33d9597", + "index": 21, + "guid": "8ad92a47-ac1d-46ad-9dc3-d1f96526bf1d", + "isActive": true, + "balance": "$1,134.78", + "picture": "http://placehold.it/32x32", + "age": 20, + "eyeColor": "green", + "name": "Jody Stewart", + "gender": "female", + "company": "EARGO", + "email": "jodystewart@eargo.com", + "phone": "+1 (925) 470-3426", + "address": "271 Norwood Avenue, Sperryville, Oklahoma, 9504", + "about": "Ut cillum ea pariatur Lorem ad veniam ex ullamco. Exercitation culpa sit occaecat aliquip eu quis magna exercitation quis reprehenderit nostrud consequat. Exercitation magna duis culpa nulla id proident. Adipisicing sunt consequat laborum consequat id dolore aute qui. Consectetur magna irure minim ut consectetur elit qui elit voluptate sint excepteur officia.\r\n", + "registered": "2014-04-29T09:04:08 +07:00", + "latitude": -51.736959, + "longitude": -37.406481, + "tags": [ + "officia", + "ullamco", + "velit", + "nulla", + "ipsum", + "eiusmod", + "mollit" + ], + "friends": [ + { + "id": 0, + "name": "Jodie Browning" + }, + { + "id": 1, + "name": "Collins Gamble" + }, + { + "id": 2, + "name": "Emerson Mccullough" + } + ], + "greeting": "Hello, Jody Stewart! You have 4 unread messages.", + "favoriteFruit": "banana" + }, + { + "_id": "54727a905956037e359d6786", + "index": 22, + "guid": "730467a3-9f5d-4d41-9503-09f30222dffa", + "isActive": false, + "balance": "$1,821.23", + "picture": "http://placehold.it/32x32", + "age": 24, + "eyeColor": "brown", + "name": "Wall Moss", + "gender": "male", + "company": "BOILICON", + "email": "wallmoss@boilicon.com", + "phone": "+1 (865) 518-2689", + "address": "902 Fleet Street, Cornfields, West Virginia, 9088", + "about": "Consectetur voluptate enim est elit dolor adipisicing reprehenderit ut in proident sunt. Fugiat cillum anim ullamco qui laborum sit. Dolore qui mollit ut irure proident consequat est veniam. Qui incididunt quis duis enim quis cupidatat do nostrud dolore labore consectetur laboris consectetur. Adipisicing veniam amet officia mollit incididunt non veniam ea laboris. Enim adipisicing velit in dolore proident Lorem esse et sunt.\r\n", + "registered": "2014-01-21T18:36:59 +08:00", + "latitude": -70.265889, + "longitude": -148.213176, + "tags": [ + "ea", + "cillum", + "ea", + "enim", + "aliqua", + "nostrud", + "do" + ], + "friends": [ + { + "id": 0, + "name": "Margaret Chavez" + }, + { + "id": 1, + "name": "Mendez Garrison" + }, + { + "id": 2, + "name": "Howard Ortiz" + } + ], + "greeting": "Hello, Wall Moss! You have 9 unread messages.", + "favoriteFruit": "banana" + }, + { + "_id": "54727a9062feb6c7bfa8710d", + "index": 23, + "guid": "1b428a55-1b50-4bcf-b2d9-06c2e8950768", + "isActive": true, + "balance": "$1,045.36", + "picture": "http://placehold.it/32x32", + "age": 25, + "eyeColor": "blue", + "name": "Adele Santana", + "gender": "female", + "company": "EBIDCO", + "email": "adelesantana@ebidco.com", + "phone": "+1 (981) 528-2138", + "address": "117 Kent Avenue, Chamizal, Iowa, 4289", + "about": "Culpa eu nostrud mollit voluptate consequat pariatur. Qui ex laboris velit cupidatat enim. Reprehenderit commodo eu excepteur ex elit amet dolore enim. Nisi dolor pariatur enim laborum voluptate Lorem magna ipsum enim aute do sunt. Ad consectetur velit laborum magna labore Lorem occaecat quis. Exercitation ipsum velit nostrud cupidatat consequat ex non velit deserunt pariatur officia. Magna occaecat Lorem qui aliqua id aliquip laborum.\r\n", + "registered": "2014-10-01T21:15:54 +07:00", + "latitude": 24.339451, + "longitude": -38.920718, + "tags": [ + "ullamco", + "labore", + "magna", + "fugiat", + "consectetur", + "nostrud", + "veniam" + ], + "friends": [ + { + "id": 0, + "name": "Sharpe Haley" + }, + { + "id": 1, + "name": "Patrice Horne" + }, + { + "id": 2, + "name": "Melanie Sosa" + } + ], + "greeting": "Hello, Adele Santana! You have 10 unread messages.", + "favoriteFruit": "apple" + }, + { + "_id": "54727a900e0eec7c0c194713", + "index": 24, + "guid": "cc7114a5-89ce-4fb6-9ad8-b5886360ab42", + "isActive": true, + "balance": "$2,505.31", + "picture": "http://placehold.it/32x32", + "age": 36, + "eyeColor": "blue", + "name": "Lindsey Colon", + "gender": "male", + "company": "XYLAR", + "email": "lindseycolon@xylar.com", + "phone": "+1 (952) 532-3896", + "address": "144 Poly Place, Detroit, Federated States Of Micronesia, 2004", + "about": "Ullamco nostrud Lorem duis duis aute sunt commodo Lorem. Esse cupidatat aliqua et laborum officia et. Ea magna est eiusmod id sit ea esse consectetur qui.\r\n", + "registered": "2014-04-05T02:52:07 +07:00", + "latitude": -55.350071, + "longitude": -20.446672, + "tags": [ + "id", + "sit", + "cillum", + "id", + "exercitation", + "reprehenderit", + "deserunt" + ], + "friends": [ + { + "id": 0, + "name": "Kathleen Berger" + }, + { + "id": 1, + "name": "Morales Tran" + }, + { + "id": 2, + "name": "Dionne Hunter" + } + ], + "greeting": "Hello, Lindsey Colon! You have 3 unread messages.", + "favoriteFruit": "strawberry" + }, + { + "_id": "54727a90a20ec5bce57f2f55", + "index": 25, + "guid": "c1d3f95b-25dd-4b48-8fe8-9af5f62895e2", + "isActive": true, + "balance": "$1,609.28", + "picture": "http://placehold.it/32x32", + "age": 21, + "eyeColor": "green", + "name": "Langley Moore", + "gender": "male", + "company": "ZYTRAX", + "email": "langleymoore@zytrax.com", + "phone": "+1 (912) 580-3688", + "address": "747 Abbey Court, Odessa, Kentucky, 4688", + "about": "Eiusmod adipisicing aliquip quis voluptate qui. Enim esse culpa elit id eu dolor culpa eiusmod. Deserunt ut ea ipsum ipsum non culpa ullamco non ipsum sunt cupidatat.\r\n", + "registered": "2014-06-28T08:29:15 +07:00", + "latitude": 65.464748, + "longitude": -129.638837, + "tags": [ + "deserunt", + "cillum", + "sint", + "proident", + "ad", + "adipisicing", + "mollit" + ], + "friends": [ + { + "id": 0, + "name": "Mcguire Vance" + }, + { + "id": 1, + "name": "Norma Buck" + }, + { + "id": 2, + "name": "Janelle Bailey" + } + ], + "greeting": "Hello, Langley Moore! You have 8 unread messages.", + "favoriteFruit": "apple" + }, + { + "_id": "54727a903c9a63ef7fccce96", + "index": 26, + "guid": "88c32c0f-a2c6-49c2-8261-bc323895067f", + "isActive": false, + "balance": "$3,748.41", + "picture": "http://placehold.it/32x32", + "age": 26, + "eyeColor": "blue", + "name": "Duran Bryan", + "gender": "male", + "company": "BULLZONE", + "email": "duranbryan@bullzone.com", + "phone": "+1 (911) 598-2827", + "address": "903 Village Road, Cressey, New Jersey, 9174", + "about": "Do in fugiat est deserunt in sit Lorem quis reprehenderit est ut tempor. Ullamco in veniam non quis cillum consectetur id. Elit exercitation reprehenderit et amet voluptate magna voluptate minim veniam enim exercitation aute aute esse. Exercitation magna voluptate laborum ipsum cupidatat exercitation ad eu aute deserunt et. Voluptate qui aute ut elit amet excepteur nostrud officia irure do.\r\n", + "registered": "2014-01-29T12:32:05 +08:00", + "latitude": -51.269785, + "longitude": 79.015891, + "tags": [ + "consequat", + "id", + "exercitation", + "incididunt", + "adipisicing", + "laboris", + "laboris" + ], + "friends": [ + { + "id": 0, + "name": "Jenny Allison" + }, + { + "id": 1, + "name": "Della Hobbs" + }, + { + "id": 2, + "name": "Bradshaw Owens" + } + ], + "greeting": "Hello, Duran Bryan! You have 5 unread messages.", + "favoriteFruit": "strawberry" + }, + { + "_id": "54727a907a2f07fbb3efec0f", + "index": 27, + "guid": "df997a84-5ec1-4f63-acb7-140b9fed981d", + "isActive": true, + "balance": "$1,249.61", + "picture": "http://placehold.it/32x32", + "age": 28, + "eyeColor": "blue", + "name": "Juarez House", + "gender": "male", + "company": "ZUVY", + "email": "juarezhouse@zuvy.com", + "phone": "+1 (841) 533-3140", + "address": "494 Atlantic Avenue, Shasta, Nevada, 8475", + "about": "Proident eu nostrud laboris adipisicing pariatur sint ipsum exercitation velit non incididunt. Qui cupidatat reprehenderit nostrud magna sunt aute nulla aliquip velit culpa commodo fugiat laborum. Dolore consectetur esse labore magna anim exercitation dolor velit qui sunt Lorem reprehenderit amet.\r\n", + "registered": "2014-03-16T19:21:13 +07:00", + "latitude": 57.96486, + "longitude": 130.460435, + "tags": [ + "incididunt", + "reprehenderit", + "consequat", + "duis", + "veniam", + "nulla", + "dolor" + ], + "friends": [ + { + "id": 0, + "name": "Keri Lara" + }, + { + "id": 1, + "name": "Celina Pace" + }, + { + "id": 2, + "name": "Bush Haynes" + } + ], + "greeting": "Hello, Juarez House! You have 7 unread messages.", + "favoriteFruit": "banana" + }, + { + "_id": "54727a903021f42c063be598", + "index": 28, + "guid": "1dc6349d-4354-42a9-9f73-7bc12d5ac9c2", + "isActive": false, + "balance": "$1,991.33", + "picture": "http://placehold.it/32x32", + "age": 26, + "eyeColor": "blue", + "name": "Sonja Horton", + "gender": "female", + "company": "VIDTO", + "email": "sonjahorton@vidto.com", + "phone": "+1 (990) 504-2432", + "address": "612 River Street, Carrizo, California, 5778", + "about": "Nisi reprehenderit occaecat anim ut minim aliqua aliquip velit veniam eiusmod reprehenderit laboris ad. Duis aliqua labore cillum proident est amet. Adipisicing nostrud proident labore laborum. Elit est sint ex veniam reprehenderit. Veniam ut dolor nulla tempor voluptate sit excepteur sit ut quis.\r\n", + "registered": "2014-10-30T05:07:28 +07:00", + "latitude": 85.37031, + "longitude": -122.082636, + "tags": [ + "tempor", + "ex", + "nostrud", + "ullamco", + "ullamco", + "nisi", + "cillum" + ], + "friends": [ + { + "id": 0, + "name": "Phillips Henry" + }, + { + "id": 1, + "name": "Leanne Sexton" + }, + { + "id": 2, + "name": "Alisha Chang" + } + ], + "greeting": "Hello, Sonja Horton! You have 1 unread messages.", + "favoriteFruit": "apple" + }, + { + "_id": "54727a903a33ff6bb03e049a", + "index": 29, + "guid": "4ef3a65d-5407-400b-aace-62bbb8a83c6a", + "isActive": true, + "balance": "$2,823.03", + "picture": "http://placehold.it/32x32", + "age": 21, + "eyeColor": "blue", + "name": "Lidia Hewitt", + "gender": "female", + "company": "PROWASTE", + "email": "lidiahewitt@prowaste.com", + "phone": "+1 (909) 562-3312", + "address": "625 Ralph Avenue, Kiskimere, Maryland, 2033", + "about": "Eu adipisicing eiusmod laboris veniam sunt id ad eiusmod consectetur nisi. Esse nulla ipsum Lorem nisi consequat laborum. Veniam ea exercitation ullamco pariatur consectetur. Cupidatat velit excepteur ex eu sunt id. In velit reprehenderit pariatur velit. Voluptate nostrud deserunt qui mollit et tempor nostrud eiusmod adipisicing ad est laborum. Fugiat nisi sit nulla eu ad.\r\n", + "registered": "2014-01-15T00:05:42 +08:00", + "latitude": -50.566931, + "longitude": -149.036259, + "tags": [ + "in", + "ipsum", + "tempor", + "magna", + "aliqua", + "duis", + "incididunt" + ], + "friends": [ + { + "id": 0, + "name": "Allie Baker" + }, + { + "id": 1, + "name": "Valdez Giles" + }, + { + "id": 2, + "name": "Knox Vargas" + } + ], + "greeting": "Hello, Lidia Hewitt! You have 3 unread messages.", + "favoriteFruit": "strawberry" + }, + { + "_id": "54727a90ce7ef56e53f98790", + "index": 30, + "guid": "9ae34b38-098b-4de6-aa0f-90359571ddf2", + "isActive": false, + "balance": "$3,152.82", + "picture": "http://placehold.it/32x32", + "age": 38, + "eyeColor": "brown", + "name": "Nieves Ewing", + "gender": "male", + "company": "QNEKT", + "email": "nievesewing@qnekt.com", + "phone": "+1 (888) 460-2384", + "address": "425 Highland Place, Hampstead, Washington, 7019", + "about": "Ipsum aliquip ullamco labore aliquip et. Eu pariatur exercitation ex fugiat fugiat. Nulla voluptate et cupidatat deserunt mollit et incididunt. Deserunt anim qui cupidatat veniam et et dolore qui sunt tempor ipsum. In et voluptate excepteur incididunt dolore cupidatat exercitation ullamco dolore Lorem nostrud sunt nostrud. Occaecat amet ut laborum laborum aliqua est incididunt ea excepteur commodo. Ipsum et elit nisi duis pariatur occaecat.\r\n", + "registered": "2014-06-15T18:44:29 +07:00", + "latitude": 8.010315, + "longitude": 69.049129, + "tags": [ + "exercitation", + "eiusmod", + "voluptate", + "ullamco", + "consectetur", + "reprehenderit", + "enim" + ], + "friends": [ + { + "id": 0, + "name": "Maggie Rodriguez" + }, + { + "id": 1, + "name": "Evans Roach" + }, + { + "id": 2, + "name": "Greer Mccoy" + } + ], + "greeting": "Hello, Nieves Ewing! You have 7 unread messages.", + "favoriteFruit": "strawberry" + }, + { + "_id": "54727a9049aa4bbedefd311d", + "index": 31, + "guid": "471d52a6-da38-4015-8d7a-6fe215a032d3", + "isActive": false, + "balance": "$1,456.93", + "picture": "http://placehold.it/32x32", + "age": 21, + "eyeColor": "green", + "name": "Reyna Clay", + "gender": "female", + "company": "KINETICA", + "email": "reynaclay@kinetica.com", + "phone": "+1 (865) 425-3747", + "address": "480 Dakota Place, Kimmell, Utah, 6677", + "about": "Tempor esse ex amet aliqua incididunt incididunt qui commodo laborum incididunt deserunt elit id consequat. Proident duis ut ullamco non ea magna fugiat fugiat Lorem minim. Incididunt tempor nostrud proident irure laboris consectetur elit labore adipisicing fugiat nulla quis ipsum consequat. Tempor mollit pariatur irure in nisi minim magna excepteur. Aliquip et laborum cillum adipisicing consequat.\r\n", + "registered": "2014-10-30T08:53:04 +07:00", + "latitude": 38.437675, + "longitude": 42.847793, + "tags": [ + "incididunt", + "est", + "mollit", + "nulla", + "ipsum", + "ea", + "ea" + ], + "friends": [ + { + "id": 0, + "name": "Glenna Macdonald" + }, + { + "id": 1, + "name": "Bertha Meadows" + }, + { + "id": 2, + "name": "Oneill Barnes" + } + ], + "greeting": "Hello, Reyna Clay! You have 6 unread messages.", + "favoriteFruit": "strawberry" + }, + { + "_id": "54727a900238319b9b407aa0", + "index": 32, + "guid": "fa5c52e1-9a9d-44d4-8e6b-5a65221ab142", + "isActive": true, + "balance": "$3,113.15", + "picture": "http://placehold.it/32x32", + "age": 24, + "eyeColor": "blue", + "name": "Felicia Harris", + "gender": "female", + "company": "FITCORE", + "email": "feliciaharris@fitcore.com", + "phone": "+1 (814) 449-2730", + "address": "641 Hazel Court, Bawcomville, Wisconsin, 4111", + "about": "Magna in elit aute ipsum anim dolore et exercitation sunt occaecat velit. Sint tempor nulla sit laborum dolor ex irure nisi nulla veniam in labore laborum. Nulla magna excepteur exercitation aute occaecat consequat laborum Lorem velit occaecat aliqua qui. Id in aliqua dolore fugiat duis elit laborum commodo cillum ex aute minim eu.\r\n", + "registered": "2014-04-15T21:31:39 +07:00", + "latitude": -58.891583, + "longitude": -162.554134, + "tags": [ + "eiusmod", + "dolor", + "enim", + "cupidatat", + "labore", + "sunt", + "consectetur" + ], + "friends": [ + { + "id": 0, + "name": "Rich Lott" + }, + { + "id": 1, + "name": "Rebecca Cardenas" + }, + { + "id": 2, + "name": "Jarvis Barron" + } + ], + "greeting": "Hello, Felicia Harris! You have 7 unread messages.", + "favoriteFruit": "strawberry" + }, + { + "_id": "54727a90f03941c94fe50d08", + "index": 33, + "guid": "49070cf3-b2f3-445e-86ec-3ae9cddc474d", + "isActive": false, + "balance": "$1,105.05", + "picture": "http://placehold.it/32x32", + "age": 35, + "eyeColor": "green", + "name": "Josefina Holland", + "gender": "female", + "company": "GOGOL", + "email": "josefinaholland@gogol.com", + "phone": "+1 (809) 411-2991", + "address": "778 McKibben Street, Whitehaven, Louisiana, 2079", + "about": "Cillum ipsum cupidatat et dolor minim aliqua. Laborum culpa magna ullamco nulla ut labore deserunt amet sunt est esse do. Consequat aliquip eiusmod ipsum tempor. Voluptate exercitation nisi nulla dolor esse ullamco occaecat. Sint minim reprehenderit anim tempor deserunt sit exercitation. Qui proident cillum eu voluptate adipisicing velit tempor sunt sunt ipsum. Enim anim ea ea eu excepteur excepteur laboris eu.\r\n", + "registered": "2014-09-13T12:46:51 +07:00", + "latitude": 81.172596, + "longitude": -151.851605, + "tags": [ + "velit", + "ad", + "tempor", + "tempor", + "adipisicing", + "nulla", + "minim" + ], + "friends": [ + { + "id": 0, + "name": "Lester Woods" + }, + { + "id": 1, + "name": "Audra Shepherd" + }, + { + "id": 2, + "name": "Chandler Church" + } + ], + "greeting": "Hello, Josefina Holland! You have 5 unread messages.", + "favoriteFruit": "banana" + }, + { + "_id": "54727a9008a3955509cf065f", + "index": 34, + "guid": "4c838bee-e8b1-4c22-b8ad-e0e5d0822334", + "isActive": false, + "balance": "$3,032.13", + "picture": "http://placehold.it/32x32", + "age": 32, + "eyeColor": "green", + "name": "Susie Cash", + "gender": "female", + "company": "DOGSPA", + "email": "susiecash@dogspa.com", + "phone": "+1 (991) 447-2298", + "address": "361 Quincy Street, Duryea, Florida, 7538", + "about": "Officia eu non proident ad ea quis eu ea amet irure aliqua qui. Ea in laborum do sit. Dolor proident voluptate excepteur sit. Tempor nulla anim ex proident ipsum laboris laboris cupidatat esse dolore ex fugiat proident. Excepteur exercitation pariatur ex velit. In adipisicing eu eiusmod elit dolore ullamco nulla sit ut ut anim aliquip. Et eu eu aliquip ex aute aliquip veniam sint pariatur non incididunt in aliqua sit.\r\n", + "registered": "2014-09-14T22:55:19 +07:00", + "latitude": 8.46119, + "longitude": -1.171475, + "tags": [ + "voluptate", + "irure", + "ex", + "proident", + "nulla", + "in", + "esse" + ], + "friends": [ + { + "id": 0, + "name": "Cassie Whitley" + }, + { + "id": 1, + "name": "Shawna Todd" + }, + { + "id": 2, + "name": "Antoinette Brooks" + } + ], + "greeting": "Hello, Susie Cash! You have 1 unread messages.", + "favoriteFruit": "banana" + }, + { + "_id": "54727a9079c5bce30e9c0a68", + "index": 35, + "guid": "7a70e0df-c23b-435d-8d19-864cc1bd09e6", + "isActive": false, + "balance": "$2,523.44", + "picture": "http://placehold.it/32x32", + "age": 21, + "eyeColor": "brown", + "name": "Marquez Hartman", + "gender": "male", + "company": "BUZZMAKER", + "email": "marquezhartman@buzzmaker.com", + "phone": "+1 (880) 574-2420", + "address": "326 Church Avenue, Yardville, Indiana, 6743", + "about": "Ullamco reprehenderit pariatur veniam enim est nulla laboris ullamco eiusmod eu Lorem amet in amet. Incididunt consectetur reprehenderit tempor Lorem aute eiusmod laborum sunt mollit excepteur qui ea enim. Consectetur enim excepteur proident incididunt adipisicing duis est amet quis proident laboris. Consectetur Lorem consequat incididunt eiusmod mollit id amet velit quis ipsum labore. Cupidatat id minim cillum qui consequat quis non quis irure dolor voluptate ea eu.\r\n", + "registered": "2014-06-16T07:23:30 +07:00", + "latitude": -88.970617, + "longitude": -28.068887, + "tags": [ + "nostrud", + "adipisicing", + "quis", + "voluptate", + "dolore", + "dolore", + "reprehenderit" + ], + "friends": [ + { + "id": 0, + "name": "Florence David" + }, + { + "id": 1, + "name": "Lynn Mcleod" + }, + { + "id": 2, + "name": "Catherine Abbott" + } + ], + "greeting": "Hello, Marquez Hartman! You have 10 unread messages.", + "favoriteFruit": "apple" + }, + { + "_id": "54727a902bf5baf83c4fafcd", + "index": 36, + "guid": "56ac4022-1ed3-4298-9b70-c6060c69b13c", + "isActive": false, + "balance": "$1,162.32", + "picture": "http://placehold.it/32x32", + "age": 35, + "eyeColor": "green", + "name": "Bishop Gibbs", + "gender": "male", + "company": "MICROLUXE", + "email": "bishopgibbs@microluxe.com", + "phone": "+1 (808) 584-2587", + "address": "801 Exeter Street, Trucksville, New Hampshire, 4871", + "about": "Incididunt sit eu sunt cupidatat aute do eu eu culpa. Laborum adipisicing sit anim sit dolor labore commodo minim proident ullamco laboris sit irure. Duis dolore cupidatat ullamco anim reprehenderit aliquip incididunt sunt eu id non proident non.\r\n", + "registered": "2014-09-10T02:39:14 +07:00", + "latitude": -3.268064, + "longitude": 149.311591, + "tags": [ + "enim", + "aute", + "commodo", + "consectetur", + "Lorem", + "est", + "cillum" + ], + "friends": [ + { + "id": 0, + "name": "Head Pickett" + }, + { + "id": 1, + "name": "Thornton Russo" + }, + { + "id": 2, + "name": "Hooper Rivera" + } + ], + "greeting": "Hello, Bishop Gibbs! You have 9 unread messages.", + "favoriteFruit": "apple" + }, + { + "_id": "54727a90a4406555b5bdab8f", + "index": 37, + "guid": "0f052dd2-283e-441e-86d7-b7f7b47224f1", + "isActive": true, + "balance": "$3,306.81", + "picture": "http://placehold.it/32x32", + "age": 34, + "eyeColor": "brown", + "name": "Carr Strickland", + "gender": "male", + "company": "EXERTA", + "email": "carrstrickland@exerta.com", + "phone": "+1 (862) 455-3845", + "address": "730 Aberdeen Street, Klondike, Kansas, 4412", + "about": "Pariatur velit qui Lorem cillum labore veniam minim. Nisi reprehenderit commodo consectetur commodo velit. Ipsum dolor ea mollit excepteur minim do excepteur. Aliquip cillum quis nostrud cillum duis eu laborum reprehenderit adipisicing adipisicing do exercitation. Laborum Lorem sunt voluptate qui quis officia nisi et elit sint veniam. Lorem velit ad do amet labore veniam consectetur.\r\n", + "registered": "2014-01-19T10:53:58 +08:00", + "latitude": -45.243563, + "longitude": -17.8448, + "tags": [ + "mollit", + "ex", + "qui", + "fugiat", + "consequat", + "consectetur", + "do" + ], + "friends": [ + { + "id": 0, + "name": "Rosario Gomez" + }, + { + "id": 1, + "name": "Robinson Robinson" + }, + { + "id": 2, + "name": "Vicki Moreno" + } + ], + "greeting": "Hello, Carr Strickland! You have 2 unread messages.", + "favoriteFruit": "banana" + }, + { + "_id": "54727a9097f6a585321fe001", + "index": 38, + "guid": "eee159c2-73ac-44b7-9054-d72295d3178a", + "isActive": true, + "balance": "$3,336.97", + "picture": "http://placehold.it/32x32", + "age": 30, + "eyeColor": "brown", + "name": "Stephens Harper", + "gender": "male", + "company": "KIDSTOCK", + "email": "stephensharper@kidstock.com", + "phone": "+1 (989) 464-3887", + "address": "315 Hewes Street, Cuylerville, Pennsylvania, 7331", + "about": "Et ea Lorem labore consequat laboris. Aliqua irure elit aliqua ad fugiat. Commodo cupidatat incididunt ut nostrud consequat elit ad esse magna nisi nostrud dolore eu. Minim incididunt esse ullamco esse ullamco deserunt reprehenderit commodo ut. Quis sint cupidatat excepteur et laboris incididunt id esse irure nostrud sint nostrud ut pariatur. Pariatur officia aute ullamco laboris nisi elit quis labore Lorem minim ad. Ea esse anim commodo fugiat exercitation voluptate eiusmod aliquip amet enim nulla mollit excepteur nisi.\r\n", + "registered": "2014-03-02T06:45:25 +08:00", + "latitude": -88.39292, + "longitude": -121.170605, + "tags": [ + "ullamco", + "est", + "mollit", + "id", + "commodo", + "Lorem", + "nostrud" + ], + "friends": [ + { + "id": 0, + "name": "Castaneda Dillon" + }, + { + "id": 1, + "name": "Morin Hodge" + }, + { + "id": 2, + "name": "Vincent Lamb" + } + ], + "greeting": "Hello, Stephens Harper! You have 2 unread messages.", + "favoriteFruit": "apple" + }, + { + "_id": "54727a90357d07212fdefd7a", + "index": 39, + "guid": "160a80a4-8e5d-483a-93ed-0a37ee359f04", + "isActive": true, + "balance": "$1,588.64", + "picture": "http://placehold.it/32x32", + "age": 32, + "eyeColor": "green", + "name": "Espinoza May", + "gender": "male", + "company": "ZIDOX", + "email": "espinozamay@zidox.com", + "phone": "+1 (955) 420-2244", + "address": "614 Alice Court, Vienna, Delaware, 5018", + "about": "Pariatur voluptate culpa enim enim sunt dolor laborum consequat officia est nostrud. Ad pariatur labore reprehenderit cillum dolor consequat quis eu fugiat. Ut fugiat do dolor minim voluptate incididunt laboris magna deserunt. Culpa incididunt fugiat nostrud qui incididunt velit laboris deserunt exercitation velit.\r\n", + "registered": "2014-09-16T06:10:45 +07:00", + "latitude": -28.413217, + "longitude": -76.45198, + "tags": [ + "ullamco", + "ut", + "nulla", + "consequat", + "ea", + "in", + "commodo" + ], + "friends": [ + { + "id": 0, + "name": "Virginia Obrien" + }, + { + "id": 1, + "name": "Snider Hopper" + }, + { + "id": 2, + "name": "Fannie Harrell" + } + ], + "greeting": "Hello, Espinoza May! You have 3 unread messages.", + "favoriteFruit": "banana" + }, + { + "_id": "54727a901e753e41d1232a42", + "index": 40, + "guid": "7f3923e7-2fad-4210-b051-bd805e505d06", + "isActive": false, + "balance": "$2,512.14", + "picture": "http://placehold.it/32x32", + "age": 28, + "eyeColor": "green", + "name": "Morrison Guerrero", + "gender": "male", + "company": "MARQET", + "email": "morrisonguerrero@marqet.com", + "phone": "+1 (881) 456-3335", + "address": "157 Huntington Street, Topaz, Georgia, 6068", + "about": "Velit cupidatat eiusmod elit ut adipisicing. Proident pariatur consequat ullamco velit dolore do esse adipisicing non est ea. Velit non amet nisi aliqua est veniam dolor. Cillum id labore qui ut aute pariatur exercitation ut incididunt velit aute.\r\n", + "registered": "2014-11-12T21:01:15 +08:00", + "latitude": -43.420946, + "longitude": 23.215515, + "tags": [ + "sit", + "dolore", + "aliqua", + "esse", + "et", + "cillum", + "mollit" + ], + "friends": [ + { + "id": 0, + "name": "Pamela Stanton" + }, + { + "id": 1, + "name": "Spence Banks" + }, + { + "id": 2, + "name": "Newton Cooley" + } + ], + "greeting": "Hello, Morrison Guerrero! You have 4 unread messages.", + "favoriteFruit": "strawberry" + }, + { + "_id": "54727a9098c06d55fa03398f", + "index": 41, + "guid": "c17e4f56-ca2b-48fd-bbc4-aea053062ebd", + "isActive": false, + "balance": "$3,405.25", + "picture": "http://placehold.it/32x32", + "age": 26, + "eyeColor": "brown", + "name": "Janna Porter", + "gender": "female", + "company": "NIMON", + "email": "jannaporter@nimon.com", + "phone": "+1 (974) 475-2497", + "address": "231 Wythe Place, Stonybrook, Alaska, 6291", + "about": "Veniam aute dolor Lorem dolore enim eiusmod veniam esse pariatur duis nisi. Eu sit sunt in exercitation amet veniam reprehenderit voluptate proident officia. Dolore aliquip laboris veniam cupidatat non cupidatat ipsum esse labore Lorem reprehenderit ex. Amet magna do officia proident laborum laboris enim. Ea sunt quis officia minim ea in id cillum. Aute ipsum aliquip fugiat tempor proident sit pariatur duis fugiat fugiat esse cillum eiusmod laboris.\r\n", + "registered": "2014-08-21T22:08:24 +07:00", + "latitude": -43.52587, + "longitude": 143.40506, + "tags": [ + "ipsum", + "consequat", + "labore", + "tempor", + "ipsum", + "exercitation", + "sint" + ], + "friends": [ + { + "id": 0, + "name": "Bray Francis" + }, + { + "id": 1, + "name": "Whitley Guthrie" + }, + { + "id": 2, + "name": "Christa Short" + } + ], + "greeting": "Hello, Janna Porter! You have 1 unread messages.", + "favoriteFruit": "banana" + }, + { + "_id": "54727a90ddf3f9e967357339", + "index": 42, + "guid": "5b194b7d-c5ca-4cdd-9239-6aa6f9b28e2f", + "isActive": false, + "balance": "$1,601.96", + "picture": "http://placehold.it/32x32", + "age": 31, + "eyeColor": "green", + "name": "Sandoval Melton", + "gender": "male", + "company": "GENMEX", + "email": "sandovalmelton@genmex.com", + "phone": "+1 (826) 536-3504", + "address": "726 Lester Court, Gracey, Colorado, 4092", + "about": "Fugiat pariatur elit Lorem amet fugiat tempor. Quis sint fugiat officia deserunt voluptate fugiat aliquip reprehenderit est laborum. Ut id ullamco Lorem esse occaecat eu officia veniam velit. Aliquip nisi voluptate id aliquip qui tempor commodo occaecat velit adipisicing nisi cillum id adipisicing.\r\n", + "registered": "2014-09-05T08:54:55 +07:00", + "latitude": -66.159672, + "longitude": -135.605108, + "tags": [ + "deserunt", + "minim", + "nulla", + "ea", + "tempor", + "reprehenderit", + "nulla" + ], + "friends": [ + { + "id": 0, + "name": "Veronica Goodwin" + }, + { + "id": 1, + "name": "Heather Pena" + }, + { + "id": 2, + "name": "Lynch Crane" + } + ], + "greeting": "Hello, Sandoval Melton! You have 2 unread messages.", + "favoriteFruit": "banana" + }, + { + "_id": "54727a904d114bb57f0826af", + "index": 43, + "guid": "57e4715d-f7e7-4843-9844-638648315628", + "isActive": false, + "balance": "$1,820.21", + "picture": "http://placehold.it/32x32", + "age": 34, + "eyeColor": "blue", + "name": "Flynn Fitzgerald", + "gender": "male", + "company": "ORBEAN", + "email": "flynnfitzgerald@orbean.com", + "phone": "+1 (931) 578-2443", + "address": "662 Degraw Street, Morgandale, Alabama, 5945", + "about": "Nulla anim qui duis ea do consectetur eiusmod commodo. Minim sunt aliqua velit ullamco velit dolor in amet. Eiusmod Lorem sint ea ea nisi ullamco ut officia magna id adipisicing. Ut eu minim pariatur incididunt non nisi in nostrud culpa magna anim. Veniam dolor consequat cillum sunt elit.\r\n", + "registered": "2014-06-21T08:11:23 +07:00", + "latitude": 17.108863, + "longitude": -21.608292, + "tags": [ + "officia", + "quis", + "sint", + "ipsum", + "esse", + "commodo", + "aute" + ], + "friends": [ + { + "id": 0, + "name": "Browning Mcdonald" + }, + { + "id": 1, + "name": "Austin Lane" + }, + { + "id": 2, + "name": "Blankenship Ferrell" + } + ], + "greeting": "Hello, Flynn Fitzgerald! You have 6 unread messages.", + "favoriteFruit": "strawberry" + }, + { + "_id": "54727a903a4a0629f547f5ab", + "index": 44, + "guid": "1e128e33-65bf-4420-ae93-f228d030401c", + "isActive": false, + "balance": "$3,158.96", + "picture": "http://placehold.it/32x32", + "age": 25, + "eyeColor": "brown", + "name": "Holden Golden", + "gender": "male", + "company": "QABOOS", + "email": "holdengolden@qaboos.com", + "phone": "+1 (825) 535-2422", + "address": "892 Vandervoort Place, Hessville, Guam, 3942", + "about": "Non sunt cupidatat ipsum nostrud qui ad ex nostrud fugiat laboris minim. Aliquip dolore est proident aliquip in non culpa. Minim ut laboris duis proident commodo occaecat duis duis cupidatat incididunt aliqua. Ad qui anim non occaecat excepteur labore consequat Lorem.\r\n", + "registered": "2014-09-11T00:33:16 +07:00", + "latitude": -3.274271, + "longitude": -151.539207, + "tags": [ + "nostrud", + "non", + "sint", + "laborum", + "deserunt", + "velit", + "sit" + ], + "friends": [ + { + "id": 0, + "name": "Barbara Sharpe" + }, + { + "id": 1, + "name": "Jerri Martinez" + }, + { + "id": 2, + "name": "Ronda Montoya" + } + ], + "greeting": "Hello, Holden Golden! You have 3 unread messages.", + "favoriteFruit": "apple" + }, + { + "_id": "54727a9079e20c148518a60a", + "index": 45, + "guid": "90fa284f-6cba-42d4-8484-6edb1ffc260b", + "isActive": false, + "balance": "$1,739.35", + "picture": "http://placehold.it/32x32", + "age": 27, + "eyeColor": "blue", + "name": "Maxwell Hodges", + "gender": "male", + "company": "DOGTOWN", + "email": "maxwellhodges@dogtown.com", + "phone": "+1 (962) 527-3585", + "address": "696 Baughman Place, Cucumber, South Carolina, 5454", + "about": "Officia ea in non veniam ipsum ea magna enim velit. Enim mollit duis consectetur magna fugiat nostrud cillum duis. Voluptate qui nostrud amet ea eiusmod consectetur cupidatat fugiat in eiusmod amet esse excepteur aute. Magna qui duis ex qui irure esse amet. Quis amet ex esse aliquip mollit. Deserunt consectetur eiusmod culpa reprehenderit. Duis quis excepteur non in consectetur commodo.\r\n", + "registered": "2014-03-20T11:37:19 +07:00", + "latitude": 19.760315, + "longitude": -26.731699, + "tags": [ + "magna", + "aute", + "consectetur", + "labore", + "sunt", + "pariatur", + "excepteur" + ], + "friends": [ + { + "id": 0, + "name": "Violet Vincent" + }, + { + "id": 1, + "name": "West Dorsey" + }, + { + "id": 2, + "name": "Concepcion Hull" + } + ], + "greeting": "Hello, Maxwell Hodges! You have 3 unread messages.", + "favoriteFruit": "strawberry" + }, + { + "_id": "54727a903c504d648884f367", + "index": 46, + "guid": "7fd30275-a097-41e0-8924-252f0a14d6ba", + "isActive": false, + "balance": "$1,153.05", + "picture": "http://placehold.it/32x32", + "age": 22, + "eyeColor": "brown", + "name": "Chasity Day", + "gender": "female", + "company": "EQUITAX", + "email": "chasityday@equitax.com", + "phone": "+1 (900) 484-3047", + "address": "858 Gelston Avenue, Succasunna, Arkansas, 3818", + "about": "Est ullamco deserunt cillum enim velit velit magna qui nisi eiusmod enim officia sit voluptate. Laboris laborum elit nostrud sit in elit labore occaecat mollit Lorem. Aliquip ipsum dolore cupidatat ad anim sint non. Commodo ut fugiat ut dolor irure id velit enim in Lorem.\r\n", + "registered": "2014-01-05T08:26:01 +08:00", + "latitude": -34.705083, + "longitude": -77.213981, + "tags": [ + "consectetur", + "velit", + "enim", + "excepteur", + "ipsum", + "non", + "adipisicing" + ], + "friends": [ + { + "id": 0, + "name": "Judy Trevino" + }, + { + "id": 1, + "name": "Rosie Cervantes" + }, + { + "id": 2, + "name": "Stella Cortez" + } + ], + "greeting": "Hello, Chasity Day! You have 1 unread messages.", + "favoriteFruit": "strawberry" + }, + { + "_id": "54727a90ac6406c3b9606052", + "index": 47, + "guid": "9bcd39b8-10db-40cc-a9f0-73e8179f181b", + "isActive": true, + "balance": "$1,755.70", + "picture": "http://placehold.it/32x32", + "age": 21, + "eyeColor": "green", + "name": "Richards Mcfadden", + "gender": "male", + "company": "ZILLACOM", + "email": "richardsmcfadden@zillacom.com", + "phone": "+1 (883) 447-2941", + "address": "241 Turnbull Avenue, Chesterfield, Ohio, 7594", + "about": "Fugiat ut qui qui et Lorem ipsum do anim veniam. Sunt ex Lorem et nostrud consectetur esse nostrud qui minim ut veniam commodo. Cillum enim laboris aliquip sunt quis ut et adipisicing deserunt. Est aute amet elit non duis deserunt nisi quis excepteur do velit. Nostrud laboris ullamco sunt occaecat Lorem nostrud laboris.\r\n", + "registered": "2014-07-04T03:08:44 +07:00", + "latitude": -66.813737, + "longitude": 75.337073, + "tags": [ + "elit", + "consequat", + "excepteur", + "qui", + "deserunt", + "sint", + "ipsum" + ], + "friends": [ + { + "id": 0, + "name": "Mercado Quinn" + }, + { + "id": 1, + "name": "Lucia Roberts" + }, + { + "id": 2, + "name": "Essie Cohen" + } + ], + "greeting": "Hello, Richards Mcfadden! You have 5 unread messages.", + "favoriteFruit": "banana" + }, + { + "_id": "54727a9033409e09e42cf3f1", + "index": 48, + "guid": "6ea51613-14f0-42b7-97c6-eb7a5cc32226", + "isActive": true, + "balance": "$3,907.64", + "picture": "http://placehold.it/32x32", + "age": 31, + "eyeColor": "blue", + "name": "Sargent Harrington", + "gender": "male", + "company": "DIGINETIC", + "email": "sargentharrington@diginetic.com", + "phone": "+1 (974) 427-2742", + "address": "883 Kermit Place, Rehrersburg, Virgin Islands, 4044", + "about": "Officia eiusmod do ut ipsum voluptate aute mollit minim ea incididunt ipsum commodo. Qui aute commodo dolor id pariatur ullamco adipisicing duis irure reprehenderit aliquip ullamco consequat. Sunt ad non deserunt velit consectetur ipsum. Sit voluptate aliquip nisi ea pariatur proident ut eu cillum. Irure sunt ad aliqua et enim. Deserunt deserunt incididunt Lorem commodo aliqua.\r\n", + "registered": "2014-06-16T00:32:02 +07:00", + "latitude": -88.301682, + "longitude": -16.268399, + "tags": [ + "Lorem", + "reprehenderit", + "consequat", + "officia", + "velit", + "ad", + "ex" + ], + "friends": [ + { + "id": 0, + "name": "Dolly Swanson" + }, + { + "id": 1, + "name": "Jeannette Underwood" + }, + { + "id": 2, + "name": "Ayers Wheeler" + } + ], + "greeting": "Hello, Sargent Harrington! You have 3 unread messages.", + "favoriteFruit": "apple" + }, + { + "_id": "54727a9083fe43074bb5b9c8", + "index": 49, + "guid": "d5835fea-0882-4e20-b86e-6dd8b9534b49", + "isActive": false, + "balance": "$2,481.41", + "picture": "http://placehold.it/32x32", + "age": 22, + "eyeColor": "green", + "name": "Kristin Perez", + "gender": "female", + "company": "JAMNATION", + "email": "kristinperez@jamnation.com", + "phone": "+1 (917) 575-2693", + "address": "737 Schroeders Avenue, Chemung, Nebraska, 8601", + "about": "Voluptate id id mollit in aliquip aliquip duis cupidatat elit voluptate proident sit sunt voluptate. Irure ipsum esse duis culpa esse et do officia consequat velit commodo Lorem. Dolore incididunt proident proident officia aliqua mollit nisi exercitation consectetur. Est dolore consectetur aliqua occaecat est. Labore nostrud ipsum aliquip labore elit aliquip magna ex esse do consequat minim id. Sit sint ea ad irure voluptate occaecat duis magna. Sint ex minim irure anim sint do cillum.\r\n", + "registered": "2014-08-12T23:35:39 +07:00", + "latitude": 75.002428, + "longitude": 12.266159, + "tags": [ + "anim", + "exercitation", + "excepteur", + "amet", + "aute", + "mollit", + "aliquip" + ], + "friends": [ + { + "id": 0, + "name": "Gilliam Steele" + }, + { + "id": 1, + "name": "Loretta Brennan" + }, + { + "id": 2, + "name": "Ratliff Norton" + } + ], + "greeting": "Hello, Kristin Perez! You have 9 unread messages.", + "favoriteFruit": "apple" + }, + { + "_id": "54727a90f594e03626363339", + "index": 50, + "guid": "bdb8284c-7b55-4791-90c0-d9e4abecd91f", + "isActive": true, + "balance": "$1,906.85", + "picture": "http://placehold.it/32x32", + "age": 33, + "eyeColor": "green", + "name": "Petra Scott", + "gender": "female", + "company": "BRAINCLIP", + "email": "petrascott@brainclip.com", + "phone": "+1 (942) 449-2471", + "address": "759 Coleridge Street, Tuskahoma, Virginia, 9943", + "about": "Consectetur magna consequat ea est. Minim veniam culpa deserunt aliqua in dolor ex aliqua occaecat reprehenderit. Proident in mollit ad est excepteur anim quis aliquip non consequat minim cillum deserunt. Occaecat sint ad et irure sit ad ad sit sint quis sunt nisi.\r\n", + "registered": "2014-11-12T20:54:05 +08:00", + "latitude": -64.192199, + "longitude": -144.535209, + "tags": [ + "cillum", + "id", + "aliqua", + "reprehenderit", + "officia", + "aliquip", + "in" + ], + "friends": [ + { + "id": 0, + "name": "Holmes Rasmussen" + }, + { + "id": 1, + "name": "Leach Hickman" + }, + { + "id": 2, + "name": "Noelle Battle" + } + ], + "greeting": "Hello, Petra Scott! You have 9 unread messages.", + "favoriteFruit": "banana" + }, + { + "_id": "54727a902f79c4cdada83391", + "index": 51, + "guid": "c79aaabd-212b-4dc8-b1b5-de14362b550c", + "isActive": true, + "balance": "$2,845.25", + "picture": "http://placehold.it/32x32", + "age": 32, + "eyeColor": "brown", + "name": "Kelli Gates", + "gender": "female", + "company": "MUSANPOLY", + "email": "kelligates@musanpoly.com", + "phone": "+1 (899) 414-3276", + "address": "888 Elm Place, Grayhawk, Wyoming, 8032", + "about": "Nisi excepteur laboris duis magna dolore occaecat dolor cupidatat. Ut commodo proident incididunt ea anim enim deserunt laboris occaecat anim cillum. In amet exercitation officia mollit officia quis exercitation aliqua culpa ullamco consequat excepteur aute mollit. Aliqua tempor consequat ullamco consequat qui duis tempor ex est aliqua id nulla Lorem occaecat. Et laborum culpa pariatur et ad minim. Nulla ad eiusmod pariatur velit aliquip magna duis duis tempor. Nisi ea reprehenderit aliquip magna esse occaecat consectetur ullamco esse.\r\n", + "registered": "2014-03-01T15:11:58 +08:00", + "latitude": 30.679655, + "longitude": -175.200369, + "tags": [ + "laborum", + "non", + "pariatur", + "ea", + "non", + "proident", + "culpa" + ], + "friends": [ + { + "id": 0, + "name": "Coleman Mejia" + }, + { + "id": 1, + "name": "Meyers Sellers" + }, + { + "id": 2, + "name": "Stuart Carney" + } + ], + "greeting": "Hello, Kelli Gates! You have 1 unread messages.", + "favoriteFruit": "strawberry" + }, + { + "_id": "54727a9040ef999266e0142c", + "index": 52, + "guid": "cb9bc903-5e95-4918-91ed-8485d75489fa", + "isActive": true, + "balance": "$1,352.24", + "picture": "http://placehold.it/32x32", + "age": 29, + "eyeColor": "green", + "name": "Maricela Conrad", + "gender": "female", + "company": "QUIZKA", + "email": "maricelaconrad@quizka.com", + "phone": "+1 (924) 592-2199", + "address": "339 Virginia Place, Lutsen, Marshall Islands, 1479", + "about": "Quis commodo cupidatat mollit et deserunt id ut anim nostrud nisi mollit esse commodo laborum. Cillum exercitation anim cillum esse quis consequat. Dolor laboris exercitation irure ullamco excepteur ipsum deserunt. Anim veniam dolore labore exercitation et consectetur eiusmod eu. Aliquip velit consectetur nostrud dolore.\r\n", + "registered": "2014-06-15T22:10:22 +07:00", + "latitude": -0.554318, + "longitude": -65.103334, + "tags": [ + "adipisicing", + "irure", + "deserunt", + "culpa", + "cupidatat", + "do", + "occaecat" + ], + "friends": [ + { + "id": 0, + "name": "Gentry Holden" + }, + { + "id": 1, + "name": "Dillard Herrera" + }, + { + "id": 2, + "name": "Guzman Patton" + } + ], + "greeting": "Hello, Maricela Conrad! You have 1 unread messages.", + "favoriteFruit": "strawberry" + }, + { + "_id": "54727a905369b0bb27f85607", + "index": 53, + "guid": "fa3a125f-2d10-4015-a0fd-68d7e2401a31", + "isActive": false, + "balance": "$2,858.28", + "picture": "http://placehold.it/32x32", + "age": 34, + "eyeColor": "green", + "name": "Simpson Cleveland", + "gender": "male", + "company": "ZAPPIX", + "email": "simpsoncleveland@zappix.com", + "phone": "+1 (808) 572-3724", + "address": "202 Georgia Avenue, Jamestown, Texas, 6347", + "about": "Reprehenderit elit in duis sunt quis consequat mollit ut consequat amet. Incididunt non sint culpa non mollit incididunt elit irure sint excepteur esse sit ut fugiat. Ullamco esse culpa excepteur magna laborum sunt magna ut reprehenderit aute laboris ullamco Lorem ea. Culpa ut sit amet dolor adipisicing veniam non occaecat ex ad ea. Quis nostrud sit mollit aliqua adipisicing.\r\n", + "registered": "2014-10-27T07:51:50 +07:00", + "latitude": -34.024135, + "longitude": 66.799767, + "tags": [ + "anim", + "pariatur", + "fugiat", + "reprehenderit", + "ullamco", + "labore", + "fugiat" + ], + "friends": [ + { + "id": 0, + "name": "Hester Howell" + }, + { + "id": 1, + "name": "Deena King" + }, + { + "id": 2, + "name": "Wilkerson Fox" + } + ], + "greeting": "Hello, Simpson Cleveland! You have 10 unread messages.", + "favoriteFruit": "apple" + }, + { + "_id": "54727a900271aa8695bc5cdf", + "index": 54, + "guid": "501e7876-6b3f-4f2e-bbaf-914e6ff23845", + "isActive": false, + "balance": "$2,015.78", + "picture": "http://placehold.it/32x32", + "age": 23, + "eyeColor": "brown", + "name": "Queen Mckay", + "gender": "female", + "company": "PROXSOFT", + "email": "queenmckay@proxsoft.com", + "phone": "+1 (954) 439-2402", + "address": "749 Wakeman Place, Sidman, Massachusetts, 3345", + "about": "Culpa irure velit cupidatat voluptate ad non anim sit sunt in esse adipisicing. Officia amet Lorem et id eiusmod non commodo deserunt irure tempor aute fugiat est cupidatat. Ut amet ad consequat nulla in in deserunt minim ipsum adipisicing eu adipisicing nisi nulla. Qui culpa sunt aute amet est consequat excepteur occaecat voluptate in do. In labore aute sit duis enim sunt qui ullamco est tempor labore aute aliquip. Sunt eu veniam in amet cillum nisi tempor quis in fugiat culpa exercitation sunt. Exercitation enim dolore sit exercitation in mollit culpa magna amet et amet.\r\n", + "registered": "2014-05-02T07:58:52 +07:00", + "latitude": -24.836277, + "longitude": -108.207588, + "tags": [ + "aliquip", + "dolor", + "velit", + "non", + "sint", + "deserunt", + "ut" + ], + "friends": [ + { + "id": 0, + "name": "Maynard Shannon" + }, + { + "id": 1, + "name": "Ernestine Sullivan" + }, + { + "id": 2, + "name": "Sullivan Juarez" + } + ], + "greeting": "Hello, Queen Mckay! You have 8 unread messages.", + "favoriteFruit": "strawberry" + }, + { + "_id": "54727a902c9d0c4f7379c125", + "index": 55, + "guid": "c13147c1-9aab-432b-9eaa-eda127454f06", + "isActive": false, + "balance": "$1,498.79", + "picture": "http://placehold.it/32x32", + "age": 21, + "eyeColor": "green", + "name": "Madeline Rhodes", + "gender": "female", + "company": "LOCAZONE", + "email": "madelinerhodes@locazone.com", + "phone": "+1 (817) 404-2650", + "address": "648 Rochester Avenue, Tetherow, Arizona, 751", + "about": "Sit velit ea enim mollit ad fugiat anim commodo minim qui sit dolor aliqua. Amet nostrud aliquip qui velit et ea reprehenderit sint ipsum quis. Ut amet aute enim proident. Et officia nostrud voluptate non tempor quis aliquip ullamco commodo consequat fugiat ut. Eiusmod sit excepteur non nostrud esse consequat nulla sunt deserunt aliqua. Commodo laborum voluptate ea eu non excepteur pariatur.\r\n", + "registered": "2014-03-14T19:50:42 +07:00", + "latitude": -31.489199, + "longitude": 124.798218, + "tags": [ + "tempor", + "culpa", + "pariatur", + "irure", + "nisi", + "proident", + "quis" + ], + "friends": [ + { + "id": 0, + "name": "Hebert Kline" + }, + { + "id": 1, + "name": "Daisy Cochran" + }, + { + "id": 2, + "name": "Russell Gilmore" + } + ], + "greeting": "Hello, Madeline Rhodes! You have 10 unread messages.", + "favoriteFruit": "strawberry" + }, + { + "_id": "54727a90b6d8621dab6c9126", + "index": 56, + "guid": "2ebcecc1-180e-46b7-bdca-9d9a6babc687", + "isActive": false, + "balance": "$3,190.82", + "picture": "http://placehold.it/32x32", + "age": 27, + "eyeColor": "blue", + "name": "Rasmussen Knapp", + "gender": "male", + "company": "BIOSPAN", + "email": "rasmussenknapp@biospan.com", + "phone": "+1 (860) 461-3219", + "address": "214 Williams Court, Brady, Oregon, 5174", + "about": "Tempor ullamco officia laborum irure cillum est culpa tempor pariatur aliqua officia incididunt tempor. Laboris adipisicing nostrud Lorem veniam enim consequat mollit nisi. Minim nulla culpa dolor esse dolore deserunt reprehenderit adipisicing aliquip.\r\n", + "registered": "2014-08-11T17:15:51 +07:00", + "latitude": -25.850361, + "longitude": -36.01581, + "tags": [ + "enim", + "laboris", + "dolore", + "amet", + "nisi", + "in", + "aliqua" + ], + "friends": [ + { + "id": 0, + "name": "Letha Peters" + }, + { + "id": 1, + "name": "Lavonne Mccarthy" + }, + { + "id": 2, + "name": "Hensley Kim" + } + ], + "greeting": "Hello, Rasmussen Knapp! You have 5 unread messages.", + "favoriteFruit": "banana" + }, + { + "_id": "54727a902e4d6731ddf406bf", + "index": 57, + "guid": "7a13b0b9-7cc4-477a-944f-a27eb7e74ae6", + "isActive": false, + "balance": "$1,711.06", + "picture": "http://placehold.it/32x32", + "age": 21, + "eyeColor": "brown", + "name": "Maryellen Russell", + "gender": "female", + "company": "MAXEMIA", + "email": "maryellenrussell@maxemia.com", + "phone": "+1 (839) 590-2573", + "address": "514 Roosevelt Court, Sugartown, American Samoa, 6602", + "about": "Pariatur laborum nostrud aliqua nisi cillum sunt laborum cillum minim pariatur et consectetur minim adipisicing. Exercitation non dolor id voluptate aute sint sunt. Nostrud cupidatat officia dolor cupidatat ex irure non. Fugiat laboris quis id aliqua sunt consectetur est ea. Eiusmod mollit enim Lorem cupidatat consectetur anim nostrud enim eu irure. Et eiusmod velit esse fugiat elit laboris labore voluptate ipsum. Excepteur consequat proident quis voluptate excepteur nulla in.\r\n", + "registered": "2014-05-17T21:19:21 +07:00", + "latitude": -15.634102, + "longitude": -81.860909, + "tags": [ + "ea", + "ipsum", + "esse", + "veniam", + "reprehenderit", + "adipisicing", + "do" + ], + "friends": [ + { + "id": 0, + "name": "Virgie Whitaker" + }, + { + "id": 1, + "name": "Earlene Ruiz" + }, + { + "id": 2, + "name": "Rosa Estrada" + } + ], + "greeting": "Hello, Maryellen Russell! You have 5 unread messages.", + "favoriteFruit": "apple" + }, + { + "_id": "54727a906ea1b53a8de569dd", + "index": 58, + "guid": "0e91224f-af4a-4cb0-a51e-5874ad140b32", + "isActive": false, + "balance": "$1,226.26", + "picture": "http://placehold.it/32x32", + "age": 21, + "eyeColor": "blue", + "name": "Wright Morris", + "gender": "male", + "company": "APPLICA", + "email": "wrightmorris@applica.com", + "phone": "+1 (968) 550-2677", + "address": "630 Hornell Loop, Sparkill, Montana, 7355", + "about": "Veniam commodo nostrud nostrud ullamco do aliquip quis dolore laboris culpa minim do est. In sunt consequat irure veniam minim duis ex commodo duis. Ullamco eu reprehenderit dolore eiusmod est exercitation nisi tempor.\r\n", + "registered": "2014-02-05T10:33:53 +08:00", + "latitude": -16.050009, + "longitude": -149.883606, + "tags": [ + "Lorem", + "in", + "est", + "consequat", + "cillum", + "adipisicing", + "commodo" + ], + "friends": [ + { + "id": 0, + "name": "Washington Carson" + }, + { + "id": 1, + "name": "Hines Bean" + }, + { + "id": 2, + "name": "Cox Powell" + } + ], + "greeting": "Hello, Wright Morris! You have 7 unread messages.", + "favoriteFruit": "banana" + }, + { + "_id": "54727a9047deb3b6b5122221", + "index": 59, + "guid": "f85bae2d-b72a-4f81-b596-b5338ec41578", + "isActive": true, + "balance": "$1,928.94", + "picture": "http://placehold.it/32x32", + "age": 26, + "eyeColor": "brown", + "name": "Agnes Guzman", + "gender": "female", + "company": "PEARLESSA", + "email": "agnesguzman@pearlessa.com", + "phone": "+1 (859) 451-3816", + "address": "874 Duffield Street, Benson, Hawaii, 1388", + "about": "Ad voluptate incididunt ullamco ullamco velit adipisicing culpa aute minim adipisicing non. Consectetur elit ullamco mollit ipsum aliqua in enim Lorem eiusmod nisi fugiat exercitation. Do amet pariatur deserunt ex labore exercitation non ad commodo aliquip. Nostrud magna ipsum reprehenderit qui consectetur cillum irure nostrud do quis excepteur cillum.\r\n", + "registered": "2014-07-28T12:22:31 +07:00", + "latitude": -89.041016, + "longitude": -4.513498, + "tags": [ + "eiusmod", + "deserunt", + "deserunt", + "eiusmod", + "minim", + "nisi", + "magna" + ], + "friends": [ + { + "id": 0, + "name": "Kari Trujillo" + }, + { + "id": 1, + "name": "Kaye Sloan" + }, + { + "id": 2, + "name": "Aguilar Fields" + } + ], + "greeting": "Hello, Agnes Guzman! You have 9 unread messages.", + "favoriteFruit": "banana" + }, + { + "_id": "54727a905ad56237e1e3ae99", + "index": 60, + "guid": "3244774e-3c8d-4c84-8ae6-d04486ce05d7", + "isActive": false, + "balance": "$3,045.23", + "picture": "http://placehold.it/32x32", + "age": 27, + "eyeColor": "green", + "name": "Jill Evans", + "gender": "female", + "company": "GOLISTIC", + "email": "jillevans@golistic.com", + "phone": "+1 (871) 577-2459", + "address": "738 Putnam Avenue, Ona, South Dakota, 4749", + "about": "Irure exercitation esse quis commodo sunt laborum esse id anim. Ut ut ad quis qui id labore ut tempor labore velit laborum pariatur. Dolore ipsum ea tempor excepteur esse cillum sit non eu sit irure adipisicing mollit. Nulla ut proident velit consequat officia magna ex duis proident aliqua amet exercitation do commodo. Nulla Lorem ad reprehenderit mollit deserunt veniam qui duis enim enim consectetur do.\r\n", + "registered": "2014-05-05T11:50:14 +07:00", + "latitude": -56.941561, + "longitude": -169.158104, + "tags": [ + "consequat", + "minim", + "minim", + "laborum", + "aute", + "nisi", + "aliqua" + ], + "friends": [ + { + "id": 0, + "name": "Compton Becker" + }, + { + "id": 1, + "name": "Conner Wall" + }, + { + "id": 2, + "name": "Bright Harvey" + } + ], + "greeting": "Hello, Jill Evans! You have 2 unread messages.", + "favoriteFruit": "banana" + }, + { + "_id": "54727a90f530d8bc9e6faf86", + "index": 61, + "guid": "a983ed9d-fb1b-48ee-94b7-54b33634ccbc", + "isActive": false, + "balance": "$3,091.12", + "picture": "http://placehold.it/32x32", + "age": 21, + "eyeColor": "brown", + "name": "Susana Berry", + "gender": "female", + "company": "POWERNET", + "email": "susanaberry@powernet.com", + "phone": "+1 (879) 454-3173", + "address": "141 Cambridge Place, Florence, District Of Columbia, 6760", + "about": "Magna occaecat laborum voluptate excepteur. Proident esse voluptate enim est exercitation elit voluptate minim ex. Velit officia cupidatat sit quis reprehenderit minim voluptate et nulla cupidatat duis mollit. Aute incididunt id magna nostrud cupidatat qui sit. Enim anim enim excepteur est sunt non enim proident sit non deserunt et veniam culpa. Ullamco irure ullamco id esse exercitation anim et fugiat labore. Do enim exercitation deserunt sint consectetur occaecat commodo commodo elit.\r\n", + "registered": "2014-06-08T14:24:28 +07:00", + "latitude": 75.590221, + "longitude": -127.23641, + "tags": [ + "esse", + "anim", + "est", + "anim", + "esse", + "adipisicing", + "mollit" + ], + "friends": [ + { + "id": 0, + "name": "Helene Holcomb" + }, + { + "id": 1, + "name": "Kramer Gregory" + }, + { + "id": 2, + "name": "Fitzgerald Graves" + } + ], + "greeting": "Hello, Susana Berry! You have 1 unread messages.", + "favoriteFruit": "strawberry" + }, + { + "_id": "54727a90e6f9c07f205357ec", + "index": 62, + "guid": "26cecce2-1202-4703-8bf5-8ff431336b37", + "isActive": false, + "balance": "$3,437.96", + "picture": "http://placehold.it/32x32", + "age": 33, + "eyeColor": "blue", + "name": "Weeks Wallace", + "gender": "male", + "company": "SUREMAX", + "email": "weekswallace@suremax.com", + "phone": "+1 (946) 528-2733", + "address": "219 Dekalb Avenue, Hasty, North Carolina, 7278", + "about": "Magna dolor ex dolor eiusmod sint laboris consequat non magna ipsum. Nostrud qui aute ut consectetur in amet deserunt aliqua voluptate. In velit nisi voluptate amet consequat. Tempor deserunt velit ut aliqua duis cupidatat laboris amet in ipsum aliquip adipisicing. Quis anim cillum labore ipsum commodo deserunt mollit tempor tempor pariatur dolore. Irure aute ipsum do occaecat laborum eiusmod ad proident exercitation elit cillum do.\r\n", + "registered": "2014-07-17T22:33:55 +07:00", + "latitude": -22.986103, + "longitude": -110.848014, + "tags": [ + "ut", + "irure", + "elit", + "quis", + "ut", + "fugiat", + "sunt" + ], + "friends": [ + { + "id": 0, + "name": "Colon Tyler" + }, + { + "id": 1, + "name": "Dianne Lucas" + }, + { + "id": 2, + "name": "Mathews Acosta" + } + ], + "greeting": "Hello, Weeks Wallace! You have 8 unread messages.", + "favoriteFruit": "banana" + }, + { + "_id": "54727a9034039bde61fe5fdb", + "index": 63, + "guid": "cad69671-eb0a-4128-8024-9a0f469cf1f8", + "isActive": true, + "balance": "$2,503.03", + "picture": "http://placehold.it/32x32", + "age": 21, + "eyeColor": "green", + "name": "Watson Tucker", + "gender": "male", + "company": "IMKAN", + "email": "watsontucker@imkan.com", + "phone": "+1 (841) 499-3837", + "address": "297 Falmouth Street, Woodlands, Tennessee, 2227", + "about": "Do aliquip laboris voluptate aliqua duis duis qui. Lorem officia consectetur et in nulla do aliquip occaecat labore officia sunt ipsum ad consequat. Culpa voluptate adipisicing dolore do velit ea.\r\n", + "registered": "2014-09-16T17:39:32 +07:00", + "latitude": 76.336221, + "longitude": -154.036452, + "tags": [ + "veniam", + "non", + "aliquip", + "ex", + "esse", + "sint", + "voluptate" + ], + "friends": [ + { + "id": 0, + "name": "Lolita Finch" + }, + { + "id": 1, + "name": "Gilmore Solis" + }, + { + "id": 2, + "name": "Faith Gallegos" + } + ], + "greeting": "Hello, Watson Tucker! You have 9 unread messages.", + "favoriteFruit": "strawberry" + }, + { + "_id": "54727a90780b195513995278", + "index": 64, + "guid": "625810dc-6353-4387-862c-e71ed6115966", + "isActive": false, + "balance": "$2,428.28", + "picture": "http://placehold.it/32x32", + "age": 33, + "eyeColor": "green", + "name": "Levy Ortega", + "gender": "male", + "company": "FIBEROX", + "email": "levyortega@fiberox.com", + "phone": "+1 (819) 514-2393", + "address": "485 Dunne Place, Sena, Idaho, 1583", + "about": "Exercitation reprehenderit voluptate aliqua laborum dolore consequat pariatur ipsum occaecat culpa et dolore voluptate. Laborum ut adipisicing exercitation irure ipsum ea. Occaecat aute officia et qui id elit adipisicing consectetur. Laborum ullamco pariatur eiusmod dolore aliqua ea nostrud. Occaecat ullamco nostrud deserunt ea officia. Deserunt incididunt et laboris veniam laboris adipisicing culpa laborum occaecat culpa sit labore. Irure in ipsum exercitation ea laboris culpa.\r\n", + "registered": "2014-06-19T01:29:28 +07:00", + "latitude": -66.489978, + "longitude": 35.142253, + "tags": [ + "consequat", + "ut", + "ipsum", + "ullamco", + "anim", + "irure", + "consectetur" + ], + "friends": [ + { + "id": 0, + "name": "Nellie Webb" + }, + { + "id": 1, + "name": "Sheri Roy" + }, + { + "id": 2, + "name": "Elizabeth Cooke" + } + ], + "greeting": "Hello, Levy Ortega! You have 3 unread messages.", + "favoriteFruit": "strawberry" + }, + { + "_id": "54727a901df67d5f687df4ab", + "index": 65, + "guid": "73d49a86-1caa-4ef5-b637-aef68b215e96", + "isActive": true, + "balance": "$3,990.52", + "picture": "http://placehold.it/32x32", + "age": 24, + "eyeColor": "blue", + "name": "Webster Conway", + "gender": "male", + "company": "PRISMATIC", + "email": "websterconway@prismatic.com", + "phone": "+1 (857) 462-3648", + "address": "557 Dekoven Court, Sandston, Palau, 8537", + "about": "Fugiat non velit fugiat sint minim magna occaecat deserunt enim adipisicing excepteur amet. Esse incididunt mollit nisi ut id consectetur qui laborum consequat et occaecat. Tempor cupidatat enim sunt cillum. Laborum consequat Lorem enim fugiat id voluptate incididunt aliquip eu esse dolor duis ad. Officia dolore duis nisi veniam ut ut dolore fugiat deserunt aute consectetur. Excepteur voluptate mollit velit duis ullamco voluptate ullamco.\r\n", + "registered": "2014-04-30T14:39:28 +07:00", + "latitude": -67.082095, + "longitude": 38.979656, + "tags": [ + "amet", + "aliquip", + "ea", + "culpa", + "incididunt", + "dolor", + "fugiat" + ], + "friends": [ + { + "id": 0, + "name": "Sharp Ramirez" + }, + { + "id": 1, + "name": "Leona Campbell" + }, + { + "id": 2, + "name": "Hyde Reyes" + } + ], + "greeting": "Hello, Webster Conway! You have 3 unread messages.", + "favoriteFruit": "banana" + }, + { + "_id": "54727a90f7b820f93d4df443", + "index": 66, + "guid": "1a306b16-3a38-426c-9254-22dd7264c108", + "isActive": true, + "balance": "$2,194.31", + "picture": "http://placehold.it/32x32", + "age": 33, + "eyeColor": "brown", + "name": "Hill Lancaster", + "gender": "male", + "company": "UNIWORLD", + "email": "hilllancaster@uniworld.com", + "phone": "+1 (836) 462-3865", + "address": "786 Dictum Court, Roulette, Minnesota, 3625", + "about": "Adipisicing ea commodo et nulla ullamco fugiat do magna occaecat consectetur cupidatat nisi fugiat consequat. Velit veniam eu cupidatat adipisicing culpa non non velit amet labore. Dolore dolor enim eiusmod ipsum excepteur non sint ullamco irure laboris nulla id.\r\n", + "registered": "2014-03-09T12:51:14 +07:00", + "latitude": -65.924237, + "longitude": 161.521943, + "tags": [ + "amet", + "id", + "aliquip", + "aliquip", + "exercitation", + "excepteur", + "cupidatat" + ], + "friends": [ + { + "id": 0, + "name": "Morrow Mullen" + }, + { + "id": 1, + "name": "Calderon Campos" + }, + { + "id": 2, + "name": "Janis Ramsey" + } + ], + "greeting": "Hello, Hill Lancaster! You have 10 unread messages.", + "favoriteFruit": "strawberry" + }, + { + "_id": "54727a906c7f0305536c965c", + "index": 67, + "guid": "d1dadd20-7ced-447d-ba72-61e886f4195e", + "isActive": true, + "balance": "$3,014.64", + "picture": "http://placehold.it/32x32", + "age": 25, + "eyeColor": "brown", + "name": "Fletcher Pearson", + "gender": "male", + "company": "QOT", + "email": "fletcherpearson@qot.com", + "phone": "+1 (930) 439-2213", + "address": "779 Middagh Street, Crayne, Illinois, 2229", + "about": "Nulla sit officia velit dolore eiusmod veniam anim laborum Lorem anim et enim irure. Quis labore ad proident occaecat dolore tempor occaecat dolor dolore aliqua laboris esse enim. Dolore tempor cupidatat aute labore aliqua nulla non est.\r\n", + "registered": "2014-04-25T09:09:10 +07:00", + "latitude": -2.329892, + "longitude": 135.411164, + "tags": [ + "magna", + "ipsum", + "tempor", + "velit", + "esse", + "magna", + "nisi" + ], + "friends": [ + { + "id": 0, + "name": "Tonya Ashley" + }, + { + "id": 1, + "name": "Latisha Burris" + }, + { + "id": 2, + "name": "Tracey Rowe" + } + ], + "greeting": "Hello, Fletcher Pearson! You have 9 unread messages.", + "favoriteFruit": "banana" + }, + { + "_id": "54727a9057e5269ab81d8e18", + "index": 68, + "guid": "4723bd56-76cb-4a30-bdf5-8b4c4c9805aa", + "isActive": false, + "balance": "$3,114.82", + "picture": "http://placehold.it/32x32", + "age": 23, + "eyeColor": "blue", + "name": "Odessa Lawson", + "gender": "female", + "company": "JOVIOLD", + "email": "odessalawson@joviold.com", + "phone": "+1 (921) 400-3177", + "address": "443 Ryder Avenue, Camino, Missouri, 487", + "about": "Labore aliquip nulla est eiusmod amet Lorem duis fugiat duis do excepteur voluptate in non. Consequat nisi reprehenderit ullamco eu sit id consectetur commodo culpa consequat dolore aliqua. Amet nulla ut in laboris dolor do ad laboris eu commodo qui dolore pariatur. Et qui cillum anim dolore ipsum excepteur id laboris minim dolor.\r\n", + "registered": "2014-03-26T22:07:14 +07:00", + "latitude": 18.291259, + "longitude": -86.22914, + "tags": [ + "nisi", + "ut", + "dolore", + "ullamco", + "cupidatat", + "nulla", + "laborum" + ], + "friends": [ + { + "id": 0, + "name": "Vonda Cote" + }, + { + "id": 1, + "name": "Lewis Gonzales" + }, + { + "id": 2, + "name": "Jacqueline Richmond" + } + ], + "greeting": "Hello, Odessa Lawson! You have 4 unread messages.", + "favoriteFruit": "apple" + }, + { + "_id": "54727a90f748a6195f1c2b42", + "index": 69, + "guid": "697c2775-d924-436d-ba9f-e21bd4fa0f73", + "isActive": false, + "balance": "$1,269.09", + "picture": "http://placehold.it/32x32", + "age": 40, + "eyeColor": "green", + "name": "Selena Nieves", + "gender": "female", + "company": "INTRAWEAR", + "email": "selenanieves@intrawear.com", + "phone": "+1 (862) 476-3196", + "address": "101 Harkness Avenue, Worton, Connecticut, 400", + "about": "Sunt aliquip exercitation dolor dolore nostrud anim enim anim est officia. Minim ea Lorem ullamco reprehenderit officia reprehenderit ex ex reprehenderit. Qui nulla ullamco consequat minim exercitation. Veniam id eu pariatur ut veniam dolore aliquip qui aliqua incididunt ut.\r\n", + "registered": "2014-03-07T15:11:53 +08:00", + "latitude": -43.588256, + "longitude": 43.731157, + "tags": [ + "duis", + "duis", + "reprehenderit", + "ad", + "magna", + "excepteur", + "officia" + ], + "friends": [ + { + "id": 0, + "name": "Rutledge Hines" + }, + { + "id": 1, + "name": "Carrillo Johnson" + }, + { + "id": 2, + "name": "Morgan Parks" + } + ], + "greeting": "Hello, Selena Nieves! You have 9 unread messages.", + "favoriteFruit": "banana" + }, + { + "_id": "54727a90628ac7e339a407a5", + "index": 70, + "guid": "6ddd302b-fd62-47f9-aa8a-9fb2c35172c5", + "isActive": true, + "balance": "$2,185.43", + "picture": "http://placehold.it/32x32", + "age": 34, + "eyeColor": "blue", + "name": "Georgia Moran", + "gender": "female", + "company": "EARTHMARK", + "email": "georgiamoran@earthmark.com", + "phone": "+1 (970) 439-3884", + "address": "848 Fay Court, Hayes, Maine, 7603", + "about": "Ea do et excepteur dolor cupidatat nisi. Quis deserunt cupidatat duis enim eu deserunt anim enim. Cillum consectetur occaecat exercitation occaecat duis dolor voluptate officia exercitation irure. Occaecat magna proident enim exercitation veniam. Est commodo ullamco minim esse enim commodo ea commodo nulla et voluptate aliqua anim. Quis magna commodo nulla quis sit duis id et ex id ea dolore anim.\r\n", + "registered": "2014-04-22T10:10:46 +07:00", + "latitude": -78.673083, + "longitude": 167.271688, + "tags": [ + "non", + "labore", + "adipisicing", + "cupidatat", + "cupidatat", + "quis", + "aliquip" + ], + "friends": [ + { + "id": 0, + "name": "Andrews Love" + }, + { + "id": 1, + "name": "Brianna Yates" + }, + { + "id": 2, + "name": "Jennifer Bass" + } + ], + "greeting": "Hello, Georgia Moran! You have 10 unread messages.", + "favoriteFruit": "strawberry" + }, + { + "_id": "54727a901ec4ee748cbbc125", + "index": 71, + "guid": "0e5fc95f-e605-4baa-bc36-b2f795c42e03", + "isActive": false, + "balance": "$2,256.63", + "picture": "http://placehold.it/32x32", + "age": 22, + "eyeColor": "blue", + "name": "House Sargent", + "gender": "male", + "company": "FANFARE", + "email": "housesargent@fanfare.com", + "phone": "+1 (877) 416-3590", + "address": "961 Olive Street, Sultana, Puerto Rico, 3764", + "about": "Cillum minim aliquip sit nulla aute commodo pariatur reprehenderit aliqua laboris in sint velit. Qui irure ut nostrud elit aliqua reprehenderit tempor quis laboris. Voluptate enim eiusmod laborum est excepteur enim est. Veniam non magna ea proident deserunt ipsum Lorem adipisicing velit eiusmod. Culpa id ea non ex ad.\r\n", + "registered": "2014-04-27T09:04:21 +07:00", + "latitude": -54.902834, + "longitude": 147.773359, + "tags": [ + "cupidatat", + "voluptate", + "dolor", + "excepteur", + "exercitation", + "id", + "in" + ], + "friends": [ + { + "id": 0, + "name": "Francis Alford" + }, + { + "id": 1, + "name": "Berta Sparks" + }, + { + "id": 2, + "name": "Laura Hahn" + } + ], + "greeting": "Hello, House Sargent! You have 9 unread messages.", + "favoriteFruit": "apple" + }, + { + "_id": "54727a90b51db1c7d287288e", + "index": 72, + "guid": "574450df-adad-4071-b642-0971f5f7928e", + "isActive": true, + "balance": "$2,263.30", + "picture": "http://placehold.it/32x32", + "age": 38, + "eyeColor": "green", + "name": "Roseann Lambert", + "gender": "female", + "company": "ROUGHIES", + "email": "roseannlambert@roughies.com", + "phone": "+1 (908) 551-2196", + "address": "142 Girard Street, Levant, New Mexico, 2920", + "about": "Aliquip ea elit anim aliqua in ea. Ex nisi nulla veniam amet. Occaecat pariatur qui consectetur consectetur anim ut anim cillum consectetur adipisicing pariatur. Cillum quis aliquip ad do in fugiat minim et ad labore sit ut aliqua cillum. Elit enim laboris incididunt laboris. Est in ullamco laboris deserunt aliqua veniam. Aute cillum culpa do dolore.\r\n", + "registered": "2014-04-29T13:57:00 +07:00", + "latitude": 0.812689, + "longitude": 127.517728, + "tags": [ + "veniam", + "quis", + "do", + "aliqua", + "deserunt", + "id", + "ut" + ], + "friends": [ + { + "id": 0, + "name": "Amelia Dunlap" + }, + { + "id": 1, + "name": "Benson Huff" + }, + { + "id": 2, + "name": "Aimee Fisher" + } + ], + "greeting": "Hello, Roseann Lambert! You have 6 unread messages.", + "favoriteFruit": "banana" + }, + { + "_id": "54727a90285dfadf5a8ab1db", + "index": 73, + "guid": "cf2c0b72-e90e-43d1-a5ee-ff85e28272ec", + "isActive": false, + "balance": "$3,053.88", + "picture": "http://placehold.it/32x32", + "age": 20, + "eyeColor": "brown", + "name": "Althea Burgess", + "gender": "female", + "company": "RODEMCO", + "email": "altheaburgess@rodemco.com", + "phone": "+1 (946) 406-2326", + "address": "127 Fleet Place, Northridge, Northern Mariana Islands, 2106", + "about": "Ea aliquip mollit consectetur non sunt. Deserunt adipisicing sint non excepteur veniam. Sunt eu ad Lorem qui laborum labore. Dolor ut esse veniam dolor officia. Minim occaecat labore voluptate exercitation fugiat eu labore non dolor ipsum do magna qui incididunt.\r\n", + "registered": "2014-03-16T23:19:14 +07:00", + "latitude": -63.483213, + "longitude": 118.593144, + "tags": [ + "amet", + "veniam", + "consequat", + "deserunt", + "magna", + "ea", + "aliqua" + ], + "friends": [ + { + "id": 0, + "name": "Delacruz Pollard" + }, + { + "id": 1, + "name": "Kelly Washington" + }, + { + "id": 2, + "name": "Irma Freeman" + } + ], + "greeting": "Hello, Althea Burgess! You have 10 unread messages.", + "favoriteFruit": "apple" + }, + { + "_id": "54727a902435e7e0219ce954", + "index": 74, + "guid": "e3079855-52fe-494a-bb64-cf88934d1f84", + "isActive": false, + "balance": "$1,615.23", + "picture": "http://placehold.it/32x32", + "age": 28, + "eyeColor": "brown", + "name": "Ursula French", + "gender": "female", + "company": "KLUGGER", + "email": "ursulafrench@klugger.com", + "phone": "+1 (803) 454-3759", + "address": "768 Bancroft Place, Layhill, Mississippi, 3591", + "about": "Anim proident aliquip non amet. Dolore occaecat non irure cillum excepteur eu officia irure ea enim incididunt. Adipisicing ad esse voluptate duis dolor irure. Non sunt cillum est exercitation labore cillum minim consequat occaecat est aliqua. Ex adipisicing consequat aliqua pariatur est elit deserunt. Proident fugiat aliquip culpa magna ut deserunt incididunt eu enim esse fugiat eu consequat amet. Ad sit do Lorem aliquip enim ea magna.\r\n", + "registered": "2014-08-01T00:12:36 +07:00", + "latitude": -31.044528, + "longitude": -131.432956, + "tags": [ + "consequat", + "enim", + "nisi", + "cupidatat", + "est", + "sint", + "nostrud" + ], + "friends": [ + { + "id": 0, + "name": "Mai Hudson" + }, + { + "id": 1, + "name": "Erickson Perkins" + }, + { + "id": 2, + "name": "Cleveland Armstrong" + } + ], + "greeting": "Hello, Ursula French! You have 8 unread messages.", + "favoriteFruit": "banana" + }, + { + "_id": "54727a906ae58205e4d302e3", + "index": 75, + "guid": "f8b68baa-b922-4a5f-9d4a-fa7d9eee543c", + "isActive": true, + "balance": "$1,500.61", + "picture": "http://placehold.it/32x32", + "age": 29, + "eyeColor": "blue", + "name": "Lee Kelley", + "gender": "male", + "company": "INQUALA", + "email": "leekelley@inquala.com", + "phone": "+1 (947) 551-3499", + "address": "973 Bayard Street, Orovada, North Dakota, 8499", + "about": "Ullamco labore fugiat in minim duis duis reprehenderit deserunt eiusmod nostrud cillum laborum. Incididunt occaecat duis esse consectetur voluptate velit pariatur. Pariatur et qui sint anim sunt fugiat ut proident nulla fugiat. Nostrud ea sunt occaecat nulla qui id cupidatat proident ut.\r\n", + "registered": "2014-11-01T01:18:21 +07:00", + "latitude": -59.393379, + "longitude": -110.276914, + "tags": [ + "sit", + "magna", + "in", + "consequat", + "excepteur", + "consequat", + "Lorem" + ], + "friends": [ + { + "id": 0, + "name": "Walton Daniels" + }, + { + "id": 1, + "name": "Hammond Robbins" + }, + { + "id": 2, + "name": "Evangelina Chaney" + } + ], + "greeting": "Hello, Lee Kelley! You have 8 unread messages.", + "favoriteFruit": "strawberry" + }, + { + "_id": "54727a902a956e2130c70b9c", + "index": 76, + "guid": "3f62418d-23f0-4ed2-a76f-51645437223b", + "isActive": false, + "balance": "$2,477.19", + "picture": "http://placehold.it/32x32", + "age": 28, + "eyeColor": "green", + "name": "Miles Poole", + "gender": "male", + "company": "YOGASM", + "email": "milespoole@yogasm.com", + "phone": "+1 (866) 412-2294", + "address": "744 Sutton Street, Richford, Vermont, 7668", + "about": "Nostrud reprehenderit officia officia ex proident sint nulla sint quis duis laborum duis. Anim adipisicing officia officia anim aliquip incididunt culpa duis sint do ullamco ex consectetur. Commodo et tempor eu consequat laboris tempor ipsum magna elit labore consectetur excepteur.\r\n", + "registered": "2014-07-20T11:37:28 +07:00", + "latitude": 23.618997, + "longitude": -80.142779, + "tags": [ + "magna", + "exercitation", + "Lorem", + "nostrud", + "pariatur", + "ut", + "laborum" + ], + "friends": [ + { + "id": 0, + "name": "Claudine Gill" + }, + { + "id": 1, + "name": "Huff Kramer" + }, + { + "id": 2, + "name": "Bryan Doyle" + } + ], + "greeting": "Hello, Miles Poole! You have 10 unread messages.", + "favoriteFruit": "apple" + }, + { + "_id": "54727a90357b2420c0dc0895", + "index": 77, + "guid": "ef7aa63d-53b9-4e85-ac36-4cfb1afd214a", + "isActive": true, + "balance": "$1,105.70", + "picture": "http://placehold.it/32x32", + "age": 39, + "eyeColor": "green", + "name": "Cohen Clemons", + "gender": "male", + "company": "EARBANG", + "email": "cohenclemons@earbang.com", + "phone": "+1 (936) 599-3992", + "address": "952 Paerdegat Avenue, Frizzleburg, Rhode Island, 7905", + "about": "Consequat exercitation fugiat ut labore. Ad magna sunt dolore magna nulla. Laborum deserunt magna eu incididunt magna occaecat ut sit aliqua nisi culpa dolor ullamco esse. Enim adipisicing proident proident enim qui est ad non. Ex proident sit irure cillum in nostrud veniam amet excepteur voluptate commodo eu eiusmod ullamco.\r\n", + "registered": "2014-06-15T00:23:03 +07:00", + "latitude": 78.28454, + "longitude": 64.170517, + "tags": [ + "non", + "ex", + "sit", + "ipsum", + "esse", + "enim", + "minim" + ], + "friends": [ + { + "id": 0, + "name": "Sanchez Wolf" + }, + { + "id": 1, + "name": "Trudy Melendez" + }, + { + "id": 2, + "name": "Magdalena Hatfield" + } + ], + "greeting": "Hello, Cohen Clemons! You have 3 unread messages.", + "favoriteFruit": "strawberry" + }, + { + "_id": "54727a90ae5beac7dec2ba78", + "index": 78, + "guid": "1bccbb43-2801-4c99-a646-001622f3653c", + "isActive": false, + "balance": "$1,246.07", + "picture": "http://placehold.it/32x32", + "age": 35, + "eyeColor": "blue", + "name": "Evelyn Combs", + "gender": "female", + "company": "BITENDREX", + "email": "evelyncombs@bitendrex.com", + "phone": "+1 (937) 463-3648", + "address": "498 Beayer Place, Caln, Michigan, 637", + "about": "Laboris ipsum ea est nisi exercitation adipisicing commodo ea ipsum tempor. Laboris duis sit aliquip reprehenderit id cillum officia. Tempor velit reprehenderit adipisicing dolor ut qui id magna consequat. Fugiat proident sunt sit reprehenderit duis. Eu ipsum adipisicing eu magna cupidatat mollit esse.\r\n", + "registered": "2014-06-14T20:28:41 +07:00", + "latitude": 13.771679, + "longitude": 58.844141, + "tags": [ + "ex", + "irure", + "quis", + "velit", + "deserunt", + "mollit", + "irure" + ], + "friends": [ + { + "id": 0, + "name": "Melton Wright" + }, + { + "id": 1, + "name": "Letitia Osborn" + }, + { + "id": 2, + "name": "Delgado Hebert" + } + ], + "greeting": "Hello, Evelyn Combs! You have 7 unread messages.", + "favoriteFruit": "apple" + }, + { + "_id": "54727a90a58e6a9e15665417", + "index": 79, + "guid": "6c039c25-e902-4121-9319-aa5e25f09b90", + "isActive": true, + "balance": "$1,839.17", + "picture": "http://placehold.it/32x32", + "age": 27, + "eyeColor": "blue", + "name": "Lakeisha Glover", + "gender": "female", + "company": "REALMO", + "email": "lakeishaglover@realmo.com", + "phone": "+1 (962) 444-3749", + "address": "259 Homecrest Court, Villarreal, Oklahoma, 5463", + "about": "Lorem cupidatat non elit mollit commodo tempor dolore sint qui officia fugiat mollit ex. Ea commodo minim labore commodo commodo sint occaecat eu aute est excepteur labore eiusmod ut. Fugiat voluptate laborum mollit aliqua ea. Ut fugiat culpa do velit non nisi voluptate exercitation. Duis elit velit adipisicing esse.\r\n", + "registered": "2014-10-07T01:42:52 +07:00", + "latitude": 7.777536, + "longitude": -148.148716, + "tags": [ + "officia", + "Lorem", + "eu", + "eiusmod", + "mollit", + "duis", + "exercitation" + ], + "friends": [ + { + "id": 0, + "name": "Hodge Snider" + }, + { + "id": 1, + "name": "Maritza Gilliam" + }, + { + "id": 2, + "name": "Barbra Harding" + } + ], + "greeting": "Hello, Lakeisha Glover! You have 5 unread messages.", + "favoriteFruit": "strawberry" + }, + { + "_id": "54727a904e60ffa71e64c330", + "index": 80, + "guid": "764804ce-2ded-4ab7-aef7-cc638d74a1f6", + "isActive": true, + "balance": "$3,096.79", + "picture": "http://placehold.it/32x32", + "age": 36, + "eyeColor": "green", + "name": "Hall Woodard", + "gender": "male", + "company": "HOTCAKES", + "email": "hallwoodard@hotcakes.com", + "phone": "+1 (923) 579-2251", + "address": "678 Johnson Avenue, Nescatunga, West Virginia, 5718", + "about": "Nulla Lorem proident incididunt nulla amet. Consectetur ea fugiat est adipisicing nisi exercitation ea irure. Id nisi anim culpa incididunt ea laborum. Non est aute anim deserunt ad cupidatat.\r\n", + "registered": "2014-07-25T16:17:12 +07:00", + "latitude": -72.300952, + "longitude": 149.908938, + "tags": [ + "magna", + "fugiat", + "laboris", + "nulla", + "tempor", + "consequat", + "officia" + ], + "friends": [ + { + "id": 0, + "name": "Tessa Mccray" + }, + { + "id": 1, + "name": "Hendricks Larson" + }, + { + "id": 2, + "name": "Cecilia Mooney" + } + ], + "greeting": "Hello, Hall Woodard! You have 1 unread messages.", + "favoriteFruit": "apple" + }, + { + "_id": "54727a9095c0ba3039bba2a0", + "index": 81, + "guid": "477bf131-1833-4ceb-a02d-367662e8a0ad", + "isActive": true, + "balance": "$3,975.04", + "picture": "http://placehold.it/32x32", + "age": 20, + "eyeColor": "brown", + "name": "Mccray Holman", + "gender": "male", + "company": "NETROPIC", + "email": "mccrayholman@netropic.com", + "phone": "+1 (888) 582-2650", + "address": "930 Alton Place, Stouchsburg, Iowa, 8307", + "about": "Officia laboris laboris ea magna nulla exercitation ullamco est magna proident cupidatat dolor. Et dolore fugiat nostrud elit in Lorem cillum eu incididunt ullamco irure eiusmod voluptate aliqua. Sint velit veniam nisi in amet incididunt ex et voluptate. Amet laborum sint fugiat nulla dolor adipisicing eiusmod ea. Labore amet nisi et pariatur duis non aliquip ea pariatur sit. Est eu dolore consequat ex quis qui adipisicing minim ea. Proident eiusmod enim irure cillum eu do laborum do voluptate occaecat id consectetur irure dolor.\r\n", + "registered": "2014-07-15T14:32:20 +07:00", + "latitude": 69.28999, + "longitude": 20.24303, + "tags": [ + "deserunt", + "labore", + "voluptate", + "sint", + "occaecat", + "non", + "sunt" + ], + "friends": [ + { + "id": 0, + "name": "Ashley Mcintosh" + }, + { + "id": 1, + "name": "Augusta Barr" + }, + { + "id": 2, + "name": "Page Wiley" + } + ], + "greeting": "Hello, Mccray Holman! You have 8 unread messages.", + "favoriteFruit": "strawberry" + }, + { + "_id": "54727a908bfd72d2f3594530", + "index": 82, + "guid": "e7128ea4-81e3-4888-ba11-4f3670e473ea", + "isActive": false, + "balance": "$3,306.06", + "picture": "http://placehold.it/32x32", + "age": 22, + "eyeColor": "green", + "name": "Sherri Villarreal", + "gender": "female", + "company": "TERRAGEN", + "email": "sherrivillarreal@terragen.com", + "phone": "+1 (881) 513-2832", + "address": "922 Surf Avenue, Oberlin, Federated States Of Micronesia, 8301", + "about": "Occaecat Lorem nostrud sint esse ullamco voluptate cillum sit aliquip sint nostrud. Velit aliqua cupidatat eu adipisicing sunt aute dolore cillum. Voluptate laboris exercitation magna non elit. Excepteur eiusmod enim amet fugiat quis. Anim cillum aute sit magna fugiat ut aliquip incididunt enim.\r\n", + "registered": "2014-01-29T03:48:07 +08:00", + "latitude": 70.685812, + "longitude": -159.885272, + "tags": [ + "adipisicing", + "officia", + "laborum", + "ipsum", + "voluptate", + "sint", + "cupidatat" + ], + "friends": [ + { + "id": 0, + "name": "Vinson Berg" + }, + { + "id": 1, + "name": "Emily Strong" + }, + { + "id": 2, + "name": "Lori Gonzalez" + } + ], + "greeting": "Hello, Sherri Villarreal! You have 1 unread messages.", + "favoriteFruit": "apple" + }, + { + "_id": "54727a90ed7615708c5d1f8e", + "index": 83, + "guid": "cb7d9a4c-9739-43c8-b75e-0d3cdf462e89", + "isActive": false, + "balance": "$3,087.41", + "picture": "http://placehold.it/32x32", + "age": 28, + "eyeColor": "brown", + "name": "Little Nielsen", + "gender": "male", + "company": "LUDAK", + "email": "littlenielsen@ludak.com", + "phone": "+1 (826) 557-2684", + "address": "842 Banner Avenue, Gadsden, Kentucky, 3196", + "about": "Officia nostrud anim aliqua veniam ut. Non culpa et dolore nostrud elit esse sint mollit anim pariatur id velit irure culpa. Officia irure adipisicing velit velit culpa sunt proident occaecat irure voluptate ullamco. Labore mollit pariatur minim in cillum deserunt. Sint irure ex laborum et minim id ea fugiat excepteur velit veniam velit consequat sint. Culpa anim velit elit officia irure exercitation ex labore est amet. Do do eiusmod ipsum officia veniam laboris irure sint eiusmod non cillum eiusmod.\r\n", + "registered": "2014-09-19T15:02:29 +07:00", + "latitude": 26.743234, + "longitude": -53.174043, + "tags": [ + "et", + "sint", + "culpa", + "dolore", + "ea", + "irure", + "excepteur" + ], + "friends": [ + { + "id": 0, + "name": "Gillespie Branch" + }, + { + "id": 1, + "name": "Cantu Kent" + }, + { + "id": 2, + "name": "Nell Meyer" + } + ], + "greeting": "Hello, Little Nielsen! You have 5 unread messages.", + "favoriteFruit": "strawberry" + }, + { + "_id": "54727a909137471ca6b126c8", + "index": 84, + "guid": "169b0cbf-781c-4b46-8285-e18b3aa6bc0e", + "isActive": true, + "balance": "$2,853.96", + "picture": "http://placehold.it/32x32", + "age": 33, + "eyeColor": "green", + "name": "Kristi Marquez", + "gender": "female", + "company": "RONELON", + "email": "kristimarquez@ronelon.com", + "phone": "+1 (838) 414-3765", + "address": "566 Love Lane, Fresno, New Jersey, 5219", + "about": "Proident enim commodo ut nisi minim esse eiusmod nisi irure consequat proident voluptate. Culpa ut sunt incididunt sint minim duis excepteur nulla cupidatat ullamco proident nisi ex enim. Qui culpa ex velit do pariatur Lorem dolor ad labore adipisicing magna sunt voluptate dolore. Lorem minim commodo non amet. Nulla reprehenderit consectetur ad nisi voluptate. Ea consectetur deserunt dolore ut. Esse duis consequat reprehenderit cillum commodo consequat ex consectetur do sint velit non deserunt.\r\n", + "registered": "2014-02-21T07:19:48 +08:00", + "latitude": 38.750345, + "longitude": -111.349096, + "tags": [ + "minim", + "minim", + "occaecat", + "tempor", + "dolore", + "fugiat", + "laborum" + ], + "friends": [ + { + "id": 0, + "name": "Eddie Soto" + }, + { + "id": 1, + "name": "Valencia Serrano" + }, + { + "id": 2, + "name": "Sears Richards" + } + ], + "greeting": "Hello, Kristi Marquez! You have 3 unread messages.", + "favoriteFruit": "apple" + }, + { + "_id": "54727a90deb8bb21d9c88b7a", + "index": 85, + "guid": "58c6180e-8bc6-4ae0-9988-52df23beedac", + "isActive": false, + "balance": "$2,028.59", + "picture": "http://placehold.it/32x32", + "age": 39, + "eyeColor": "blue", + "name": "Callie Sweeney", + "gender": "female", + "company": "POLARIA", + "email": "calliesweeney@polaria.com", + "phone": "+1 (999) 576-3446", + "address": "278 Gunnison Court, Wakulla, Nevada, 3605", + "about": "Minim non eu sint culpa. Non irure ea eiusmod est dolore id culpa laborum ex aliquip et eu. Laborum occaecat labore incididunt et ipsum adipisicing cupidatat eu consectetur reprehenderit quis dolor.\r\n", + "registered": "2014-11-06T17:55:38 +08:00", + "latitude": 22.578553, + "longitude": 70.713617, + "tags": [ + "veniam", + "ad", + "aliqua", + "id", + "quis", + "esse", + "est" + ], + "friends": [ + { + "id": 0, + "name": "Cochran Raymond" + }, + { + "id": 1, + "name": "Perry Pugh" + }, + { + "id": 2, + "name": "Walsh Cummings" + } + ], + "greeting": "Hello, Callie Sweeney! You have 8 unread messages.", + "favoriteFruit": "apple" + }, + { + "_id": "54727a9092b4caeee42e4083", + "index": 86, + "guid": "b37a99a1-89ea-4257-bd5c-f8070c6e5d72", + "isActive": false, + "balance": "$2,333.35", + "picture": "http://placehold.it/32x32", + "age": 27, + "eyeColor": "brown", + "name": "Henson Parrish", + "gender": "male", + "company": "MANTRO", + "email": "hensonparrish@mantro.com", + "phone": "+1 (983) 409-3702", + "address": "749 Malbone Street, Century, California, 6571", + "about": "Pariatur nisi magna laboris ipsum ad sint. Exercitation sit id reprehenderit fugiat ea dolor. Duis exercitation voluptate nulla duis enim culpa eiusmod nulla mollit et occaecat eu Lorem.\r\n", + "registered": "2014-06-21T02:15:00 +07:00", + "latitude": 42.27087, + "longitude": 88.230275, + "tags": [ + "sunt", + "excepteur", + "veniam", + "cillum", + "sunt", + "consequat", + "ullamco" + ], + "friends": [ + { + "id": 0, + "name": "Dunn Cantrell" + }, + { + "id": 1, + "name": "Mendoza Keller" + }, + { + "id": 2, + "name": "Josefa Green" + } + ], + "greeting": "Hello, Henson Parrish! You have 7 unread messages.", + "favoriteFruit": "strawberry" + }, + { + "_id": "54727a9001009b488b9deadf", + "index": 87, + "guid": "4a8e033a-6160-44a0-b6f6-e07f11455db9", + "isActive": false, + "balance": "$2,886.19", + "picture": "http://placehold.it/32x32", + "age": 33, + "eyeColor": "blue", + "name": "Mcgowan Hogan", + "gender": "male", + "company": "MAGNEMO", + "email": "mcgowanhogan@magnemo.com", + "phone": "+1 (816) 507-2353", + "address": "979 Reed Street, Roberts, Maryland, 9773", + "about": "Sunt sint labore aliqua nisi ipsum mollit. Lorem aliquip nisi Lorem eu velit. Laborum reprehenderit minim cillum culpa cupidatat commodo do aute dolore. Sunt ullamco consectetur ex officia anim fugiat quis fugiat laboris est quis officia aliqua pariatur. Adipisicing nulla culpa officia ut reprehenderit ea cupidatat.\r\n", + "registered": "2014-05-26T12:57:18 +07:00", + "latitude": -24.348796, + "longitude": 25.886101, + "tags": [ + "ex", + "ullamco", + "non", + "ea", + "enim", + "quis", + "ipsum" + ], + "friends": [ + { + "id": 0, + "name": "Terry Burton" + }, + { + "id": 1, + "name": "Cara Estes" + }, + { + "id": 2, + "name": "Johanna Dillard" + } + ], + "greeting": "Hello, Mcgowan Hogan! You have 1 unread messages.", + "favoriteFruit": "strawberry" + }, + { + "_id": "54727a9021cae47006152c91", + "index": 88, + "guid": "ebae8f41-1ba7-4f91-8d61-1a1a0d6b515f", + "isActive": false, + "balance": "$2,168.49", + "picture": "http://placehold.it/32x32", + "age": 25, + "eyeColor": "brown", + "name": "Riddle Alvarado", + "gender": "male", + "company": "INTERLOO", + "email": "riddlealvarado@interloo.com", + "phone": "+1 (892) 530-2012", + "address": "488 Loring Avenue, Homeworth, Washington, 8337", + "about": "Officia labore commodo eu consectetur. Consectetur consequat voluptate minim dolor do anim magna deserunt ullamco. Mollit laborum eiusmod veniam velit officia dolore dolore in ex veniam officia eu elit fugiat. Labore non in Lorem nulla irure ea id cupidatat eu consectetur. Tempor non quis eu nulla aliquip proident elit commodo duis laboris laborum eu amet occaecat.\r\n", + "registered": "2014-11-13T11:12:08 +08:00", + "latitude": 21.377099, + "longitude": 128.211659, + "tags": [ + "ex", + "excepteur", + "magna", + "enim", + "magna", + "et", + "incididunt" + ], + "friends": [ + { + "id": 0, + "name": "Elisa Vinson" + }, + { + "id": 1, + "name": "Peterson Reynolds" + }, + { + "id": 2, + "name": "Mason Odonnell" + } + ], + "greeting": "Hello, Riddle Alvarado! You have 1 unread messages.", + "favoriteFruit": "strawberry" + }, + { + "_id": "54727a901459251e4d519953", + "index": 89, + "guid": "6fe0652a-7055-47d0-8b6a-8bc3b3f6a7d0", + "isActive": true, + "balance": "$1,638.04", + "picture": "http://placehold.it/32x32", + "age": 29, + "eyeColor": "blue", + "name": "Stone Maynard", + "gender": "male", + "company": "CONJURICA", + "email": "stonemaynard@conjurica.com", + "phone": "+1 (827) 532-2021", + "address": "631 Orient Avenue, Homestead, Utah, 8151", + "about": "In voluptate voluptate veniam reprehenderit dolor est ut est voluptate dolore occaecat voluptate. Laboris cillum ex aliquip quis dolor qui qui fugiat sit. Veniam magna dolor mollit sint laborum duis id duis aliqua dolore reprehenderit qui et. Irure cupidatat ea sunt anim amet mollit adipisicing id sint deserunt veniam irure. Reprehenderit elit mollit do ex reprehenderit ipsum aliqua qui. Ea non eiusmod officia laboris dolor tempor deserunt elit velit ex aliqua. Duis reprehenderit duis duis elit irure elit dolore dolore.\r\n", + "registered": "2014-05-26T12:55:16 +07:00", + "latitude": -20.476755, + "longitude": 76.876321, + "tags": [ + "fugiat", + "dolore", + "consequat", + "do", + "esse", + "consectetur", + "anim" + ], + "friends": [ + { + "id": 0, + "name": "Mckenzie Bartlett" + }, + { + "id": 1, + "name": "Villarreal Welch" + }, + { + "id": 2, + "name": "Amparo Kelly" + } + ], + "greeting": "Hello, Stone Maynard! You have 5 unread messages.", + "favoriteFruit": "apple" + }, + { + "_id": "54727a9015625be6710ded3e", + "index": 90, + "guid": "d079e795-b71e-446b-91f8-6347ca0e2e57", + "isActive": false, + "balance": "$1,156.54", + "picture": "http://placehold.it/32x32", + "age": 28, + "eyeColor": "blue", + "name": "Baird Jones", + "gender": "male", + "company": "KNEEDLES", + "email": "bairdjones@kneedles.com", + "phone": "+1 (898) 574-3748", + "address": "890 Lancaster Avenue, Falconaire, Wisconsin, 9406", + "about": "Officia veniam sunt minim ex tempor labore consequat laborum adipisicing officia. Incididunt enim excepteur anim et do cupidatat magna excepteur culpa. Dolore enim ea excepteur non commodo aliqua nostrud commodo exercitation dolor duis. Consectetur consequat ullamco in esse fugiat pariatur anim mollit aliqua aliquip qui. Voluptate cupidatat ipsum labore aliquip fugiat cillum amet sunt voluptate occaecat occaecat nostrud.\r\n", + "registered": "2014-01-22T19:38:09 +08:00", + "latitude": -30.096555, + "longitude": -119.933566, + "tags": [ + "occaecat", + "qui", + "enim", + "in", + "pariatur", + "irure", + "officia" + ], + "friends": [ + { + "id": 0, + "name": "Gail Flynn" + }, + { + "id": 1, + "name": "Sanford Harmon" + }, + { + "id": 2, + "name": "Noble Chambers" + } + ], + "greeting": "Hello, Baird Jones! You have 3 unread messages.", + "favoriteFruit": "strawberry" + }, + { + "_id": "54727a90b147f5343b9ce16b", + "index": 91, + "guid": "af036dfd-72dd-451e-b93d-6dceea4796c4", + "isActive": false, + "balance": "$3,703.12", + "picture": "http://placehold.it/32x32", + "age": 33, + "eyeColor": "blue", + "name": "Leila Gay", + "gender": "female", + "company": "ZOXY", + "email": "leilagay@zoxy.com", + "phone": "+1 (845) 467-2535", + "address": "800 Little Street, Troy, Louisiana, 233", + "about": "Ea aliqua excepteur duis est velit eiusmod irure est eiusmod non elit. Consequat nostrud elit ullamco minim labore deserunt commodo. Mollit amet duis laboris mollit est ex aliquip. Minim et veniam reprehenderit voluptate aliqua id officia excepteur consequat fugiat non ex eu. Fugiat officia cupidatat pariatur voluptate excepteur in.\r\n", + "registered": "2014-08-02T18:50:58 +07:00", + "latitude": 59.481938, + "longitude": 141.038749, + "tags": [ + "ipsum", + "commodo", + "velit", + "sit", + "aliquip", + "ullamco", + "nisi" + ], + "friends": [ + { + "id": 0, + "name": "Conway Summers" + }, + { + "id": 1, + "name": "Deirdre Moody" + }, + { + "id": 2, + "name": "Curtis Dickerson" + } + ], + "greeting": "Hello, Leila Gay! You have 10 unread messages.", + "favoriteFruit": "apple" + }, + { + "_id": "54727a90ffed9e529a6fa6b2", + "index": 92, + "guid": "7deb0cd2-5374-40c4-a38d-060ef674b2df", + "isActive": true, + "balance": "$2,980.94", + "picture": "http://placehold.it/32x32", + "age": 20, + "eyeColor": "brown", + "name": "Alma England", + "gender": "female", + "company": "SOLAREN", + "email": "almaengland@solaren.com", + "phone": "+1 (941) 595-3246", + "address": "727 Covert Street, Nutrioso, Florida, 9152", + "about": "Commodo quis occaecat voluptate tempor commodo non ipsum quis tempor pariatur elit. Ea fugiat velit dolor ea et occaecat eu ad aute ipsum. In sunt ad reprehenderit duis. Qui deserunt voluptate proident eu officia laborum pariatur incididunt id nisi. Eiusmod adipisicing do pariatur et incididunt aliquip consectetur.\r\n", + "registered": "2014-08-08T20:51:29 +07:00", + "latitude": 70.990007, + "longitude": -119.193428, + "tags": [ + "irure", + "cillum", + "incididunt", + "nisi", + "magna", + "ullamco", + "ex" + ], + "friends": [ + { + "id": 0, + "name": "Downs Keith" + }, + { + "id": 1, + "name": "Dawn Velazquez" + }, + { + "id": 2, + "name": "Deanna Simpson" + } + ], + "greeting": "Hello, Alma England! You have 9 unread messages.", + "favoriteFruit": "strawberry" + }, + { + "_id": "54727a9075e4734b622a166a", + "index": 93, + "guid": "c0adc5f1-039a-4b52-a8cf-0196f3c23129", + "isActive": true, + "balance": "$2,658.69", + "picture": "http://placehold.it/32x32", + "age": 21, + "eyeColor": "brown", + "name": "Lou Rose", + "gender": "female", + "company": "INFOTRIPS", + "email": "lourose@infotrips.com", + "phone": "+1 (845) 564-3943", + "address": "343 Krier Place, Evergreen, Indiana, 5249", + "about": "Tempor ullamco id reprehenderit sunt veniam incididunt laboris. Ea ut officia do velit dolor officia Lorem consectetur nisi velit nisi. Aliquip dolore minim sint deserunt deserunt est.\r\n", + "registered": "2014-04-22T07:46:26 +07:00", + "latitude": 12.216368, + "longitude": 8.875707, + "tags": [ + "velit", + "consectetur", + "Lorem", + "est", + "adipisicing", + "ad", + "ullamco" + ], + "friends": [ + { + "id": 0, + "name": "Coleen Foley" + }, + { + "id": 1, + "name": "Boone Fitzpatrick" + }, + { + "id": 2, + "name": "Elise Osborne" + } + ], + "greeting": "Hello, Lou Rose! You have 5 unread messages.", + "favoriteFruit": "banana" + }, + { + "_id": "54727a90512b4f65287789e9", + "index": 94, + "guid": "26d470db-29c3-4c14-894b-5654462385a5", + "isActive": false, + "balance": "$2,751.47", + "picture": "http://placehold.it/32x32", + "age": 23, + "eyeColor": "blue", + "name": "Velez Wong", + "gender": "male", + "company": "FRANSCENE", + "email": "velezwong@franscene.com", + "phone": "+1 (821) 577-3492", + "address": "197 Huron Street, Hilltop, New Hampshire, 6969", + "about": "Minim id ullamco ullamco do proident Lorem commodo tempor ea. Est ut id non proident eiusmod. Deserunt fugiat enim culpa veniam sint.\r\n", + "registered": "2014-07-21T05:23:01 +07:00", + "latitude": -37.262537, + "longitude": 132.661281, + "tags": [ + "culpa", + "non", + "elit", + "nulla", + "laboris", + "elit", + "ex" + ], + "friends": [ + { + "id": 0, + "name": "Charmaine Curry" + }, + { + "id": 1, + "name": "Clara Randall" + }, + { + "id": 2, + "name": "Lauren Jacobs" + } + ], + "greeting": "Hello, Velez Wong! You have 4 unread messages.", + "favoriteFruit": "banana" + }, + { + "_id": "54727a9095dc4743a5a84bd7", + "index": 95, + "guid": "1d1b9166-affc-4d15-ab60-b2edc51f29b4", + "isActive": true, + "balance": "$1,063.39", + "picture": "http://placehold.it/32x32", + "age": 22, + "eyeColor": "brown", + "name": "Catalina Baxter", + "gender": "female", + "company": "GAZAK", + "email": "catalinabaxter@gazak.com", + "phone": "+1 (839) 435-3437", + "address": "904 Miller Avenue, Callaghan, Kansas, 7896", + "about": "Ut ex exercitation commodo sint sint ipsum ea incididunt. Sunt nostrud tempor sint occaecat qui laborum culpa ipsum ullamco veniam est excepteur nostrud. Consequat occaecat id adipisicing esse culpa occaecat. Proident veniam laboris aute minim dolore eiusmod nulla minim elit sint.\r\n", + "registered": "2014-05-02T10:13:41 +07:00", + "latitude": 18.545597, + "longitude": -99.991313, + "tags": [ + "do", + "proident", + "reprehenderit", + "minim", + "cillum", + "quis", + "esse" + ], + "friends": [ + { + "id": 0, + "name": "Monique Wilcox" + }, + { + "id": 1, + "name": "Hilda Craig" + }, + { + "id": 2, + "name": "Leola Higgins" + } + ], + "greeting": "Hello, Catalina Baxter! You have 10 unread messages.", + "favoriteFruit": "apple" + } +] \ No newline at end of file diff --git a/distributors-json/bench/data/geometry.json b/distributors-json/bench/data/geometry.json new file mode 100644 index 00000000..30174034 --- /dev/null +++ b/distributors-json/bench/data/geometry.json @@ -0,0 +1 @@ +{"geometry": {"type": "Polygon", "coordinates": [[[-0.939359853061118, 51.57401065198471], [-0.939440892477492, 51.57431080772057], [-0.939543636564569, 51.57460846194951], [-0.939564627628489, 51.574822653966265], [-0.939763179055758, 51.575406210178826], [-0.939787182642249, 51.575552991614], [-0.939819571231525, 51.57564949527348], [-0.939851290904264, 51.57571272360808], [-0.939975682132949, 51.57588648747347], [-0.940036822193859, 51.57598774653439], [-0.940072640734852, 51.57606090267849], [-0.940109693338918, 51.576205104339515], [-0.940125502187331, 51.57645611534466], [-0.940118623499009, 51.57662779459441], [-0.94008851367835, 51.57680555827417], [-0.939998015208524, 51.57709787034017], [-0.939928028667517, 51.577252794653916], [-0.939830628174189, 51.57740747134858], [-0.939796941313687, 51.57749078985784], [-0.939785586773343, 51.57754463746666], [-0.939770656147318, 51.57769016804059], [-0.939658154074368, 51.57824573765943], [-0.939485738834128, 51.57883313597966], [-0.93945717030888, 51.579192545519916], [-0.939524336079755, 51.57928306919007], [-0.939540939284811, 51.57931379092206], [-0.939553921057406, 51.579748206813974], [-0.939549110634237, 51.57983088690364], [-0.939520940649101, 51.58004913048237], [-0.93951863934971, 51.58014801827346], [-0.939525037302583, 51.580245186310094], [-0.939540364690294, 51.58033074581249], [-0.939561798495469, 51.58040197377017], [-0.939594984852117, 51.58046431619436], [-0.939708262827559, 51.580619996404984], [-0.939729069878358, 51.58065615108302], [-0.939759224390201, 51.58072476025555], [-0.939813615319267, 51.58093026195459], [-0.939900523550716, 51.58172321441459], [-0.939894144544868, 51.581997403240464], [-0.939910832471369, 51.58208657162566], [-0.940114353648015, 51.582457967531546], [-0.94022333049887, 51.58267475179605], [-0.940267247821581, 51.58277225843995], [-0.94038427828014, 51.583077233742756], [-0.940493362377966, 51.583289522851196], [-0.940571515796737, 51.58340442254201], [-0.940725857371931, 51.58359464061899], [-0.941198340240742, 51.584069167875626], [-0.941335307610427, 51.584261925920295], [-0.941372786463165, 51.5843261048293], [-0.941416540699353, 51.58443080287741], [-0.941461326187118, 51.584739621364996], [-0.941517445876004, 51.5849954910945], [-0.941575869597484, 51.58533860085252], [-0.941574762730556, 51.58538624677686], [-0.941565185406358, 51.58542572382202], [-0.941550002863301, 51.58545795698674], [-0.941515976834126, 51.58549361692739], [-0.941470510606583, 51.585524677868065], [-0.941423872780384, 51.585544039043356], [-0.94131509921043, 51.585566436558274], [-0.941075026707647, 51.58558675057684], [-0.940953181611661, 51.58561262652464], [-0.940734943851404, 51.58568708689612], [-0.940229533088359, 51.585883040066975], [-0.940067635923264, 51.58595531027499], [-0.939917220191166, 51.58603038143916], [-0.939797255285709, 51.586099433232604], [-0.939675637701456, 51.586177461657186], [-0.939611074554604, 51.58622273608784], [-0.939340396866166, 51.586441486256], [-0.93912244296424, 51.58662744303347], [-0.938817233975319, 51.58671729893312], [-0.938661522913105, 51.586771639765516], [-0.938087678078033, 51.586992141762096], [-0.937332636663603, 51.5873072119485], [-0.93492634290483, 51.58836081134952], [-0.934774110277819, 51.58845114531925], [-0.934663126573178, 51.588505886685766], [-0.934565467487243, 51.588546362183585], [-0.934462140700832, 51.588582290320545], [-0.934337145222589, 51.58861892084846], [-0.934213782000904, 51.588647473549656], [-0.934055887760941, 51.588671216763295], [-0.933259701136762, 51.58864510257983], [-0.933213278816969, 51.588716614209304], [-0.932681740160827, 51.588792708227174], [-0.931992471253759, 51.58900853446031], [-0.930629113767652, 51.58946908647644], [-0.928525036745892, 51.59005953842682], [-0.928533690860491, 51.59024394687689], [-0.928456010745829, 51.59047792078815], [-0.928256501298223, 51.5906748158337], [-0.927916132025856, 51.59066181734799], [-0.927671608556404, 51.590624516635486], [-0.927319567022116, 51.59061680481465], [-0.926850285435352, 51.59062240702726], [-0.926313746570405, 51.59066425819173], [-0.925516790702947, 51.59079184232522], [-0.925387133168341, 51.59078076476673], [-0.925293323156809, 51.59077990606886], [-0.925202187496562, 51.59078806346173], [-0.925112304116411, 51.59080432476366], [-0.925036768134577, 51.59082431403807], [-0.924968299737815, 51.59085066215826], [-0.924899640304234, 51.59088510100373], [-0.924851228495836, 51.590917926896914], [-0.924734051019008, 51.59105082982951], [-0.924694255912291, 51.59108553291224], [-0.924446018071168, 51.59126668934789], [-0.924204972773907, 51.59150995377465], [-0.923492520665307, 51.59215352189589], [-0.922775141969353, 51.59288246146081], [-0.922298613651092, 51.59343737077436], [-0.922101568270595, 51.59365046303728], [-0.92149319027045, 51.59422483935332], [-0.921029930136652, 51.59464499018023], [-0.919455791303858, 51.595519790418045], [-0.919908472816787, 51.59560757835559], [-0.919902358174605, 51.595621908790214], [-0.919721503870405, 51.59588190272939], [-0.919513222918683, 51.59614164398608], [-0.919057326435374, 51.59661490568889], [-0.918991959815932, 51.59669253146064], [-0.918853979663433, 51.59690975873926], [-0.91882720841051, 51.59694278142396], [-0.918711889332325, 51.597056812913756], [-0.918614808732714, 51.59713234806153], [-0.918297245740306, 51.59749448485627], [-0.918073703114389, 51.59778825130676], [-0.917853804369843, 51.59811082427763], [-0.917772408698363, 51.59831598343439], [-0.917709563771812, 51.59853030520902], [-0.917692745480418, 51.59856971355161], [-0.917634249201942, 51.59866178857289], [-0.917443039919903, 51.59887043094418], [-0.917335250471836, 51.598971042984616], [-0.916888284039272, 51.599309503426845], [-0.916921110547038, 51.59938623548714], [-0.916942485633783, 51.5995195094582], [-0.916937652924948, 51.599601289122916], [-0.916945811778801, 51.599683188627004], [-0.916964246289877, 51.599757989575366], [-0.917049297107238, 51.59994580090974], [-0.917089705367533, 51.60000731699611], [-0.917171120773417, 51.60010517795964], [-0.91752823274465, 51.60044925531009], [-0.917834023417531, 51.600765883511485], [-0.917913079603466, 51.600902386385464], [-0.918033251654948, 51.60107073894696], [-0.91851090277833, 51.601507638962644], [-0.918694916056997, 51.601663091331545], [-0.919167224655989, 51.60214309940451], [-0.919302231291783, 51.6024167896932], [-0.919552009673002, 51.60266096432073], [-0.919812571846437, 51.60293760761218], [-0.920091738726093, 51.60358667644501], [-0.920208566517809, 51.603592246724574], [-0.920644522919282, 51.60359715428394], [-0.921093152621479, 51.6036156641763], [-0.921168285587618, 51.603613657034074], [-0.921469264587163, 51.6035867495928], [-0.921584776688781, 51.603586911416876], [-0.921718864440287, 51.603595336217005], [-0.921999521996191, 51.60363387995426], [-0.922136050325758, 51.603661209181794], [-0.922248015684399, 51.60368921195661], [-0.922346882036963, 51.60372159023333], [-0.922478548042792, 51.60377135359644], [-0.922605777045377, 51.603825571929555], [-0.92269948345521, 51.60389297005248], [-0.922855181916126, 51.60396453348124], [-0.922908065211369, 51.60398749776935], [-0.923525984356841, 51.604174796116844], [-0.923689774691443, 51.6042095667925], [-0.923842334751645, 51.60423074681459], [-0.924020987014581, 51.604247669912816], [-0.924152253615336, 51.604253368572344], [-0.924379056519158, 51.60424915231234], [-0.924491916632975, 51.60423939614583], [-0.925129396784027, 51.604149022807746], [-0.925308707040747, 51.60413807581467], [-0.925396812395019, 51.604137083863186], [-0.925816640142735, 51.60415261457396], [-0.926339243350925, 51.604157394450915], [-0.926627592983669, 51.60417621577326], [-0.928219342008724, 51.60433911850777], [-0.928540897883304, 51.60435823822504], [-0.928666454251138, 51.6043611822271], [-0.928925123731038, 51.60435275210506], [-0.929272427371303, 51.60432085222454], [-0.929350681081097, 51.604308977474346], [-0.929525019586135, 51.60426381040009], [-0.929730308556221, 51.60419195021111], [-0.929806393059037, 51.60414948374236], [-0.929854111423592, 51.60408517871234], [-0.929877477717563, 51.604012559228565], [-0.929880189120251, 51.60395863398061], [-0.930157001898001, 51.603362311928585], [-0.930233415197893, 51.60324431822904], [-0.930397156019029, 51.60303540508514], [-0.93058677482955, 51.602831223239896], [-0.930747612253953, 51.60268432562219], [-0.931065151604954, 51.602443542878724], [-0.931358556224333, 51.60224659876122], [-0.931494751600125, 51.602165114969594], [-0.931807666849096, 51.601998019766675], [-0.932115553298882, 51.60186055047904], [-0.932344261944379, 51.601774512081256], [-0.932581062209752, 51.601712824287226], [-0.932837650566022, 51.60166929919289], [-0.93304760157037, 51.60164423223924], [-0.933247236692325, 51.60162806284857], [-0.933524572231589, 51.601623388892406], [-0.93367307135076, 51.60163283011416], [-0.933854562367985, 51.601651562386515], [-0.934222940436163, 51.60170526005669], [-0.934582321335698, 51.60177326158339], [-0.935176916778695, 51.60190903449902], [-0.935323237909383, 51.60194992468383], [-0.935449328012611, 51.60199153042619], [-0.935555166022244, 51.60203475076641], [-0.935754957696255, 51.60213547009268], [-0.935920944220561, 51.60219991608389], [-0.936105992086264, 51.60225194623237], [-0.936251123590137, 51.60228203448254], [-0.9362553703842, 51.602285669620606], [-0.935954861941404, 51.603034649313756], [-0.936025513047831, 51.60328615677915], [-0.937604653681525, 51.60374194595848], [-0.937842729718605, 51.6037494948452], [-0.937998245297976, 51.60376798569096], [-0.938149157504488, 51.60379812385097], [-0.938282536474463, 51.60383709493093], [-0.938398403200176, 51.60388400001471], [-0.938549544157173, 51.60396629131982], [-0.938542113846477, 51.60403725821696], [-0.938540670189083, 51.60403724516617], [-0.938690470772444, 51.60417707075241], [-0.93885671831091, 51.60429276731543], [-0.938949655717409, 51.60433227129961], [-0.939171393952754, 51.60435945147724], [-0.939491406642938, 51.60438302306183], [-0.939580914110842, 51.60438383145672], [-0.939698081584302, 51.604374998744255], [-0.939860253923854, 51.60435578228165], [-0.940131370864495, 51.60430877574863], [-0.940224037565311, 51.60429792302206], [-0.941065905352937, 51.604358569226044], [-0.941456261791824, 51.60439985396626], [-0.94172260946072, 51.604433725629356], [-0.942065117075164, 51.604483568721975], [-0.942405972956444, 51.60454238758566], [-0.942542307804962, 51.60457868292929], [-0.942668453620936, 51.60461848302318], [-0.942754322773386, 51.60465162617505], [-0.942930037674105, 51.6047332338937], [-0.94300827141212, 51.60478429141865], [-0.943050642772121, 51.60482513526179], [-0.943095505071305, 51.604883085645305], [-0.943175837511794, 51.60503037259752], [-0.943199044776033, 51.60508812802956], [-0.943264927978451, 51.605360268787045], [-0.94328295289835, 51.6055168856955], [-0.943285556153251, 51.605653582182974], [-0.94327790338372, 51.60573443814757], [-0.943262026480571, 51.60579633763445], [-0.943228365851772, 51.605877858692274], [-0.943092212068021, 51.60614458434088], [-0.943074097962666, 51.60624063192375], [-0.943061365824471, 51.606415854446915], [-0.943044862244347, 51.60650472320056], [-0.943017897594943, 51.606608783583646], [-0.942979591589439, 51.606703750216774], [-0.942905884027612, 51.60683076806164], [-0.942741267849139, 51.60707925374213], [-0.942655006715899, 51.607249318295594], [-0.942630361430127, 51.60731563455148], [-0.942616263944651, 51.607425205688976], [-0.942621958529523, 51.60749089598715], [-0.942636336634899, 51.60755576531453], [-0.942660904708633, 51.607617129739225], [-0.942696981288364, 51.607680396114986], [-0.942747433102709, 51.60774648940761], [-0.942856244975984, 51.6078490746924], [-0.94299552290573, 51.60794563997599], [-0.943040847342192, 51.60798381288104], [-0.943186973159248, 51.608158666884215], [-0.943285889122319, 51.60825217104693], [-0.943509689787491, 51.60844031193307], [-0.94379690141149, 51.609007570967925], [-0.943824004868445, 51.60908424372538], [-0.943831400135399, 51.609201201602104], [-0.943839541642426, 51.60922375393887], [-0.943852077204152, 51.6092436483043], [-0.943874740412961, 51.60926273459518], [-0.943900416430683, 51.60927645299323], [-0.944008015202393, 51.60930709311221], [-0.944074894993692, 51.60934995527111], [-0.944126815315737, 51.60941516198104], [-0.944143328071964, 51.60945037786937], [-0.944150844233183, 51.609499899486615], [-0.944148608042361, 51.60953404761941], [-0.944074023202655, 51.60969882315075], [-0.94403415265091, 51.60986121332522], [-0.944017357658548, 51.60996266784037], [-0.943992023164905, 51.61030771903426], [-0.943965568458423, 51.61051428886229], [-0.943938629028152, 51.61067949277199], [-0.943919488028492, 51.61075754789674], [-0.943885949921455, 51.61083367520212], [-0.943827406881077, 51.61092935920088], [-0.943739589608875, 51.61104186395993], [-0.943638735204063, 51.61115604969767], [-0.943533757272514, 51.611261206608894], [-0.942952360107171, 51.61179457356613], [-0.942768364001955, 51.61194397664764], [-0.942436714102017, 51.61217027698273], [-0.942010518369458, 51.61248743929258], [-0.941742162181165, 51.61266215641604], [-0.941369087685306, 51.61286829880399], [-0.941218061678922, 51.612965845186196], [-0.941055044244821, 51.613082165678385], [-0.940962318642569, 51.61315685920963], [-0.940802313735133, 51.613329853845215], [-0.940532273923746, 51.613638528438315], [-0.940201080800705, 51.61403027273604], [-0.940058816377521, 51.614185443187054], [-0.939985695447699, 51.614286388653916], [-0.939953592073967, 51.614362527773245], [-0.939906859457064, 51.614508669589505], [-0.939802341993177, 51.61490335803689], [-0.939554942446072, 51.615603370947234], [-0.939452722231603, 51.61596121406953], [-0.939421935085161, 51.61604275989804], [-0.939387192811998, 51.616108085051245], [-0.939207265482904, 51.61639149465681], [-0.939036585027605, 51.61671185322904], [-0.938852844916865, 51.61697274874371], [-0.938765881571911, 51.61710953487875], [-0.938636321443754, 51.617400592062225], [-0.93858227703968, 51.617550263869646], [-0.938563060896774, 51.61763101488344], [-0.938557821588965, 51.617793716095726], [-0.938568952285691, 51.6178738422429], [-0.938586194898738, 51.61793963701825], [-0.93864824402059, 51.61806608070808], [-0.938712639101221, 51.61815388154161], [-0.938801458484915, 51.61824729803767], [-0.938902019778203, 51.61833272809444], [-0.939001577491258, 51.61839926656718], [-0.939080060597956, 51.6184404379885], [-0.939144458958051, 51.618466196342986], [-0.93924483456823, 51.61849767462955], [-0.939389936057716, 51.61853135511866], [-0.939533886937889, 51.618552436752374], [-0.939605967169062, 51.618558482633226], [-0.939704125343146, 51.618561167280205], [-0.940011869234288, 51.61855765138392], [-0.940970156479417, 51.61846828865034], [-0.942814559287174, 51.61834913395653], [-0.9433943585448, 51.61832378069166], [-0.943791844341078, 51.61831207069643], [-0.944095316626396, 51.61830580819228], [-0.944345189840605, 51.61830625638639], [-0.944633949874169, 51.618311549349706], [-0.944866264500346, 51.618321729423634], [-0.945069571918896, 51.61833704343469], [-0.945259736594118, 51.618358533188456], [-0.945405071369022, 51.6183823175338], [-0.945538707551366, 51.61841229079249], [-0.945670733169093, 51.618449442740584], [-0.945789657802543, 51.61849097274293], [-0.945898390514756, 51.618536007789324], [-0.946002624502939, 51.61858819565799], [-0.946144975691139, 51.61867849034559], [-0.946290660655923, 51.61881197458077], [-0.946424293873759, 51.618966930407886], [-0.94648587943588, 51.619052004215185], [-0.946597289998464, 51.61923103785771], [-0.946748500992991, 51.619500344620654], [-0.946865282768134, 51.619759451627154], [-0.94692090631825, 51.619852564183816], [-0.946986743272162, 51.619941272483025], [-0.947121992710119, 51.62008904866086], [-0.947221067183078, 51.620177155655796], [-0.947357337089385, 51.62028088174252], [-0.947636341593443, 51.62045871900467], [-0.947732020809812, 51.62050633282523], [-0.947832261440868, 51.62054409665008], [-0.948024909405708, 51.6205835873772], [-0.948272727755043, 51.62061098363029], [-0.94903310890345, 51.62064836261257], [-0.949342820854191, 51.62068530212313], [-0.949548509996597, 51.62072310869445], [-0.949603327033706, 51.620726296510135], [-0.94966121922192, 51.62072141934501], [-0.949725095662238, 51.62070760405018], [-0.949813979767225, 51.620674230793945], [-0.949850856696741, 51.620766275113425], [-0.949938127431095, 51.62092800552347], [-0.95012170684362, 51.62142328688538], [-0.950137689181391, 51.621481875301626], [-0.950144591409982, 51.621558365780544], [-0.950143525838059, 51.62166715485939], [-0.950086848280287, 51.62218276713024], [-0.950081566444785, 51.62234906486587], [-0.950091380322934, 51.6227375905417], [-0.950012857804674, 51.623198158520914], [-0.949963053357781, 51.62366617649237], [-0.94993621019599, 51.62382778558582], [-0.949887611273865, 51.62405573809743], [-0.94981748429385, 51.62434014525264], [-0.949698012983878, 51.6246969431444], [-0.949601071539472, 51.62520410239216], [-0.949519655994856, 51.62547671925938], [-0.949509640700394, 51.62553507516918], [-0.949509569744091, 51.62560071332227], [-0.949517625184728, 51.6256898023632], [-0.949539397678852, 51.62581048474923], [-0.949602831958219, 51.626066413978656], [-0.949622600072634, 51.6262113557699], [-0.949625807500304, 51.62644786389373], [-0.949588359660548, 51.62688092470566], [-0.949587162842075, 51.62718303218221], [-0.949593421398238, 51.627287390862], [-0.949641886384285, 51.62762860642186], [-0.949677564559904, 51.627772791296934], [-0.949732061930258, 51.62791534613564], [-0.949847071945823, 51.62812767746571], [-0.95005020451512, 51.62890367131774], [-0.949860358893705, 51.62924185674224], [-0.949849459019953, 51.62927592739189], [-0.949848649628705, 51.62931098742953], [-0.949857806222275, 51.62935243070728], [-0.949882540677514, 51.62940750068883], [-0.949782851646605, 51.62940750843079], [-0.949684104107472, 51.6296170289926], [-0.949619670293909, 51.62984214210067], [-0.949589348281571, 51.62990391300069], [-0.949478823262764, 51.63006027755304], [-0.949419643728549, 51.63018293320961], [-0.949378577882241, 51.63033452402259], [-0.949364251310331, 51.63051692549393], [-0.949339228920643, 51.63059942443184], [-0.949248633732607, 51.63076855530058], [-0.949181283974238, 51.630869557872636], [-0.949044504574139, 51.63103647701982], [-0.948893935504611, 51.63136242402941], [-0.948761069414249, 51.631297394415576], [-0.948669492362367, 51.63125880992652], [-0.948537801268757, 51.63120547966423], [-0.948447461288637, 51.63117589768262], [-0.948353982967507, 51.63115707745748], [-0.948302104865814, 51.63115121794117], [-0.948079606840815, 51.63115102360314], [-0.947964190602531, 51.63114369566099], [-0.94782149485015, 51.63112892992514], [-0.947725107052886, 51.63111098229264], [-0.947684910040859, 51.63109983219839], [-0.947483021604023, 51.63102069524269], [-0.947447137482345, 51.63101048287877], [-0.947306094892948, 51.630986739722026], [-0.947000710620611, 51.63094713644845], [-0.946674033898238, 51.6308911565172], [-0.946364247153943, 51.63079216747898], [-0.946230490849763, 51.63076579091048], [-0.946172752135344, 51.63076347450912], [-0.94612066649297, 51.630766603772976], [-0.945914796224295, 51.63079712600587], [-0.94583241748209, 51.63079818492752], [-0.945382953779145, 51.63067905708907], [-0.945085984219956, 51.63058827220451], [-0.944883205963743, 51.630547786680644], [-0.944304065189339, 51.630538086402446], [-0.94394898927073, 51.630523204990325], [-0.943611477254356, 51.63049858971805], [-0.943603681926519, 51.6307098224617], [-0.943277115569317, 51.63102249010073], [-0.943359247728321, 51.63109426279834], [-0.942862682241593, 51.631385618132356], [-0.942777562378065, 51.63144239822567], [-0.942532313252267, 51.63161282917167], [-0.942337892928893, 51.63177202827151], [-0.94226606523137, 51.631816339444626], [-0.942197377359527, 51.63184988892168], [-0.942115813951467, 51.631877927416205], [-0.941937005967162, 51.631924871353945], [-0.941512981586086, 51.63201636159427], [-0.94144898217334, 51.6320346671529], [-0.94125937051438, 51.632111184999914], [-0.940790185204025, 51.6323425346351], [-0.940501042462563, 51.632535943664614], [-0.940243238615803, 51.63268647504363], [-0.940131608045529, 51.632764593869275], [-0.939328651391563, 51.63361514453957], [-0.939011405652477, 51.634145481445906], [-0.93882930544315, 51.63451878632893], [-0.93850479164515, 51.63486472819315], [-0.93841585373771, 51.63483694950617], [-0.938308667759282, 51.63503379600045], [-0.938237520065274, 51.63511048065125], [-0.938174497877949, 51.635148574806536], [-0.938097155068085, 51.63518114448376], [-0.938014243480848, 51.63520467214815], [-0.937885103100742, 51.635227781700706], [-0.937899482630853, 51.63529265131639], [-0.937852791962712, 51.635312010611116], [-0.937756752174709, 51.63534081433219], [-0.93768849662133, 51.635355482713884], [-0.937445207164159, 51.63537845841074], [-0.937282775985471, 51.6354039635962], [-0.936848828519967, 51.635485456519916], [-0.935951432459366, 51.63561220386278], [-0.935719677036262, 51.635636179646525], [-0.935420148631615, 51.63565414571281], [-0.935249454884316, 51.63560044703531], [-0.935077590540852, 51.635535048401415], [-0.934717727795324, 51.63535285185533], [-0.934413155884105, 51.635216113905294], [-0.934240481559584, 51.635123731852076], [-0.934130824273522, 51.63505529964683], [-0.934018404467151, 51.63498144729724], [-0.93379675026591, 51.63482118293064], [-0.933679892303923, 51.6347517857655], [-0.933595523374065, 51.63471415412531], [-0.933350473747258, 51.63462740768713], [-0.933261876876166, 51.63458524160035], [-0.933052343088727, 51.63446285066096], [-0.932887751506176, 51.63439571653097], [-0.932638117941304, 51.63431971687678], [-0.932307197466639, 51.63419801967628], [-0.931343887912331, 51.63380981222079], [-0.931071830619705, 51.63376597498289], [-0.930956833347264, 51.63374065092008], [-0.930823331188951, 51.63370346918478], [-0.930701576222194, 51.633658301797674], [-0.930601553796263, 51.63361063468632], [-0.930506119022842, 51.63355221932683], [-0.930386739592999, 51.633467510133144], [-0.930286034494439, 51.633387466714524], [-0.930225334024314, 51.63332666999925], [-0.930188937852857, 51.633276884582266], [-0.930114567680391, 51.63312155131756], [-0.92999324620862, 51.63293521875163], [-0.929900400330813, 51.63282827174111], [-0.929602366751531, 51.6325378240622], [-0.929499431873266, 51.632429885607195], [-0.929341000864788, 51.63222433167361], [-0.929059923028374, 51.631889079042224], [-0.928963213558906, 51.63176231446386], [-0.928896162303318, 51.6316645934755], [-0.928844852932023, 51.631573310156845], [-0.928688841592085, 51.63126527289447], [-0.928672375509884, 51.6312282570475], [-0.928615004479859, 51.631026321392014], [-0.928599834825331, 51.63099561149414], [-0.928552267379979, 51.63092953870757], [-0.928477466267079, 51.630854225808044], [-0.928389580173335, 51.630782390113474], [-0.928294323595921, 51.6307167812279], [-0.928190294396403, 51.63065558801307], [-0.928078937075949, 51.630598823630024], [-0.927494137115659, 51.630339021667446], [-0.927177150281751, 51.63017967221046], [-0.927053070740772, 51.63011110151437], [-0.926922044883713, 51.63003077810591], [-0.926774152423019, 51.6299305188448], [-0.926569924361936, 51.62976860145066], [-0.926465515994788, 51.62966244509719], [-0.926222881099496, 51.62935271335746], [-0.925807083215573, 51.62885077488713], [-0.925685153671251, 51.62869140695483], [-0.925627779063265, 51.628612654944924], [-0.925107975398826, 51.62780494620014], [-0.925039238852947, 51.627717997425265], [-0.924853081975605, 51.627525670804864], [-0.924566287633664, 51.62725149768458], [-0.924018135317732, 51.62666651663998], [-0.9236755124427, 51.62631000590676], [-0.923506463123086, 51.62618886774415], [-0.92325024557972, 51.62602736696645], [-0.923179326155173, 51.62597186775246], [-0.923151247824846, 51.62593744208942], [-0.923025917353845, 51.62573937605691], [-0.922746731858051, 51.625388839233764], [-0.922647729925315, 51.625421200084226], [-0.922438316532782, 51.62517470633975], [-0.922266691774008, 51.62491866820555], [-0.922176577184834, 51.624819832363215], [-0.921722712186069, 51.62440384906751], [-0.921324388846087, 51.624082786314446], [-0.921078577970903, 51.623909687134365], [-0.920860652296657, 51.62377910436709], [-0.920574889783577, 51.623646099345635], [-0.920239048968319, 51.623492851580735], [-0.920014292502202, 51.62371107994427], [-0.919774493442185, 51.623954346092496], [-0.9196346398006, 51.62406455586703], [-0.919395541436808, 51.62427815528515], [-0.919291601043514, 51.624396787581134], [-0.919216417933559, 51.6245210794288], [-0.919153464283899, 51.62467785367513], [-0.919134125069682, 51.624762197061855], [-0.919115026043568, 51.62495803894169], [-0.919049238753011, 51.62517323267518], [-0.919009465019033, 51.625266379578875], [-0.918926652164549, 51.625407685106715], [-0.91889138185638, 51.62549368011671], [-0.918887531877765, 51.62553410703284], [-0.918896749679156, 51.62569334383204], [-0.918892707420934, 51.62574186144837], [-0.918872585162246, 51.62579832350382], [-0.918836276012485, 51.62586722482348], [-0.918763089019947, 51.62596815648993], [-0.918486277330256, 51.626309088016214], [-0.918317614737411, 51.62653682130949], [-0.917905561785174, 51.626975413689514], [-0.917718470441796, 51.62724883363936], [-0.917588198962995, 51.627380709193844], [-0.917518986462533, 51.627435819379606], [-0.917391270738013, 51.627520961779815], [-0.916852199941663, 51.62783249660931], [-0.916708494011591, 51.62822500463541], [-0.916564194300437, 51.62882431452802], [-0.91642514281193, 51.62950639562586], [-0.916399138398425, 51.62974892972319], [-0.916394191477189, 51.62995659074321], [-0.917260413231125, 51.62992321851857], [-0.917422640699178, 51.63166639247214], [-0.91745600722272, 51.63232848375385], [-0.917204699151121, 51.632324368705305], [-0.916787813832452, 51.632356490901394], [-0.916473041038736, 51.63240843616508], [-0.91615824611563, 51.63246127954521], [-0.916096846672852, 51.632491284427324], [-0.916000979824314, 51.632573122584574], [-0.916035541448316, 51.63300234215989], [-0.916058746179642, 51.633180590521675], [-0.916070697537387, 51.63322475979131], [-0.916098260729099, 51.63328076225654], [-0.916287121367376, 51.6334803208717], [-0.916556537933578, 51.63369500893812], [-0.916833436931067, 51.63389897542989], [-0.916980624704717, 51.63396776999687], [-0.917236275570907, 51.634093312450645], [-0.91746761535009, 51.63414759643489], [-0.917599467742121, 51.63382870989293], [-0.917652284973834, 51.63367364156546], [-0.917677934007693, 51.63362802065708], [-0.917745133700401, 51.63359716923921], [-0.917749446066394, 51.633598108140106], [-0.917778102484095, 51.633608262991594], [-0.918084580428658, 51.633662338963], [-0.918258883815884, 51.633684625273325], [-0.918506861448772, 51.63370758977881], [-0.918953829589691, 51.63374767133924], [-0.919245145699076, 51.633771033193085], [-0.919300707852053, 51.63386505735126], [-0.919518444759651, 51.63449197843591], [-0.919277685382965, 51.63446908250848], [-0.919031520477806, 51.63467362436313], [-0.918786199566619, 51.63490335001199], [-0.918632752044247, 51.63503681158531], [-0.918623327237537, 51.63512933850577], [-0.918590569006466, 51.635413172104], [-0.918679820058316, 51.63554886817429], [-0.918329488250497, 51.63557621368664], [-0.918276435808259, 51.635741170885815], [-0.918247752304029, 51.6360358318421], [-0.918226764712395, 51.6364321689642], [-0.918316733144818, 51.63702374696847], [-0.918287332378286, 51.63783452012518], [-0.918306713699577, 51.63835621240955], [-0.918316674296085, 51.639213205140855], [-0.918347519668651, 51.639799742499974], [-0.918322169732004, 51.63995416480466], [-0.918318885834364, 51.64003146244247], [-0.91832686087795, 51.64012145202931], [-0.91837911416845, 51.640354816042915], [-0.918418495846573, 51.64070405330022], [-0.918530296534871, 51.64128953760163], [-0.918512952473936, 51.64147190762244], [-0.918367217757134, 51.64200916315153], [-0.917905817511154, 51.6420255938785], [-0.917874522823857, 51.64200462484983], [-0.9178264462409, 51.64196012300076], [-0.917792775459127, 51.641917552189355], [-0.917773553228143, 51.64187511449974], [-0.917765526057023, 51.64184806570082], [-0.917757894232724, 51.6417436926823], [-0.917749532884981, 51.64142711089125], [-0.917739557627689, 51.64136048104305], [-0.917720785029217, 51.641299165096676], [-0.917688816437575, 51.64124581999865], [-0.917649452591449, 51.641199600032465], [-0.917568381483579, 51.64114490323613], [-0.917433423830488, 51.64098630616572], [-0.917315173490429, 51.64079369481265], [-0.916601390868836, 51.640243120219885], [-0.916329281834837, 51.640018517003504], [-0.916001068304932, 51.63966211774633], [-0.915790319174844, 51.63947044935813], [-0.915502073944432, 51.63913509831614], [-0.915393357554307, 51.63902799332443], [-0.915169439572157, 51.63884339546647], [-0.914312592230519, 51.638234837864296], [-0.913969150495335, 51.63797270396478], [-0.913808719070197, 51.63773204326735], [-0.913709021859032, 51.63761063348384], [-0.913238840648949, 51.637814889395024], [-0.912211197236081, 51.63818662075986], [-0.912057780107923, 51.6382571327065], [-0.911911629192503, 51.63832591344631], [-0.911683066608314, 51.6384568717294], [-0.911571655864317, 51.638583520328496], [-0.910821072629623, 51.63897039510019], [-0.910799442348496, 51.63890815232427], [-0.910457034748542, 51.63884473254883], [-0.90959863753988, 51.63872527019996], [-0.909397970101408, 51.639078576087414], [-0.909048252097236, 51.63925965643008], [-0.909362542404515, 51.63959166868019], [-0.90780907162756, 51.64013291512084], [-0.906217399025103, 51.640939038154336], [-0.905898125060113, 51.64111499768922], [-0.905490384709512, 51.641363863281036], [-0.905329841704473, 51.64154939281248], [-0.905189541321435, 51.641794455508446], [-0.90489098319803, 51.64194992468491], [-0.904781623731163, 51.641990266433346], [-0.904676706895303, 51.64202615370086], [-0.904609919053975, 51.64203901826923], [-0.904237228330216, 51.64209218907456], [-0.90337364044862, 51.64224597828853], [-0.902975191138407, 51.642348358507896], [-0.90292303291413, 51.6422939216028], [-0.902563354675933, 51.64240655335107], [-0.902346768622897, 51.642458479170756], [-0.900824166346957, 51.64291090498388], [-0.900831401206159, 51.64297031739377], [-0.900456613238591, 51.64299018760407], [-0.900019098619797, 51.64297440185565], [-0.899740380937974, 51.64290615240652], [-0.899740489711103, 51.64290165761423], [-0.899316872364163, 51.642849133775655], [-0.899203336991784, 51.642822893203494], [-0.898949902655656, 51.64272520647125], [-0.898783095909619, 51.642631028913314], [-0.898613530793898, 51.64253143027416], [-0.898274969154989, 51.64230885935864], [-0.898003026265053, 51.642080618381755], [-0.897815191816853, 51.641840577798526], [-0.897681652652772, 51.6416262230417], [-0.897327401428262, 51.64091885338664], [-0.896908641882592, 51.6401308512027], [-0.896689777704333, 51.63985994571793], [-0.896199107519928, 51.639356299928586], [-0.896147069948886, 51.63929736526477], [-0.896071667668875, 51.63912941223961], [-0.896034388155249, 51.63881974973283], [-0.89604243255033, 51.63866696761571], [-0.896079873457203, 51.63849378104931], [-0.896158355572289, 51.63829670279626], [-0.896345617779906, 51.63796397393339], [-0.896436991088377, 51.637771512438086], [-0.896627579786388, 51.63748017587825], [-0.896853716275347, 51.63721255114492], [-0.896930541034958, 51.63714313797598], [-0.897052325259386, 51.63706695367484], [-0.897622203318074, 51.636806151704704], [-0.897875248140837, 51.636679946210485], [-0.898045509693898, 51.63657094674504], [-0.898161794997489, 51.63648302058021], [-0.898300490282884, 51.636364732965696], [-0.898761753797595, 51.63587451909389], [-0.898944791614438, 51.635595696246455], [-0.899167964890093, 51.63497197055003], [-0.899296205851425, 51.63450920414348], [-0.899574174378538, 51.633591065468096], [-0.89965934952667, 51.63323579470252], [-0.899745200652967, 51.632733067337156], [-0.89977291429982, 51.632065248259224], [-0.899749317297925, 51.63190587518938], [-0.899730833669311, 51.631833768913715], [-0.899698165870897, 51.631750739777836], [-0.89965967663145, 51.63166945441679], [-0.899415121605884, 51.63126703489972], [-0.899342021743563, 51.6311233827535], [-0.899274678557411, 51.630980683675816], [-0.899221406706553, 51.63067446858268], [-0.899099405183406, 51.63046202142283], [-0.899036514315775, 51.63037421293725], [-0.898969246754073, 51.63028816171176], [-0.898790586842518, 51.63008867047265], [-0.898592010806669, 51.62987640386868], [-0.898497321924236, 51.62978919602221], [-0.898330098469121, 51.62965455114822], [-0.898092642525963, 51.62949676796704], [-0.897090362270362, 51.62894426419184], [-0.896737033461809, 51.62879887742956], [-0.896347312922056, 51.6286648367393], [-0.895633444660858, 51.62837398981453], [-0.895432402381131, 51.628264199314984], [-0.895328663542796, 51.62819308870188], [-0.895257753282041, 51.62813847178444], [-0.895144755729953, 51.62803220648194], [-0.894948239644532, 51.627795675481295], [-0.894944118635818, 51.62766795529761], [-0.894659948504904, 51.62723368184], [-0.894597856997988, 51.62711350846984], [-0.894557343909314, 51.62699713484451], [-0.894469809950127, 51.62655661915932], [-0.894297931114171, 51.625960652861906], [-0.894027819576293, 51.62530531541029], [-0.893931965007508, 51.62514795788166], [-0.893770350871199, 51.62496210671055], [-0.893637995566781, 51.62476124514902], [-0.893507481839104, 51.62466290563429], [-0.892108104715385, 51.62369479825078], [-0.891788795844237, 51.623459800649094], [-0.891922368328922, 51.62337294285213], [-0.891402229815371, 51.62296161084893], [-0.891224922435199, 51.622768414566416], [-0.890089770742591, 51.621276764770215], [-0.890188416566163, 51.62120036880181], [-0.889947380146256, 51.62101466068101], [-0.889727152716072, 51.62086421627997], [-0.889328903798693, 51.62066892786315], [-0.889153387824523, 51.620758083474584], [-0.888409981594066, 51.6201459098237], [-0.888016456293258, 51.619876030785385], [-0.887588982852847, 51.619754191291285], [-0.887143566599165, 51.61965735685454], [-0.88701981132148, 51.61963820065132], [-0.886790744842007, 51.619613550199404], [-0.886603228328527, 51.619602780759124], [-0.886388075513318, 51.619599841439666], [-0.886090409498186, 51.61960421155123], [-0.8851368584814, 51.61967159165818], [-0.883828125903616, 51.61979133688442], [-0.883515973065361, 51.619797361107345], [-0.883424375160774, 51.6198216668555], [-0.883259776293847, 51.619877648328995], [-0.883163867754863, 51.61990101371408], [-0.883044634749604, 51.619815357981636], [-0.881854770311083, 51.61956485587701], [-0.881704286246311, 51.61951666620604], [-0.881635675440863, 51.619487239450166], [-0.881560131370525, 51.619446057447796], [-0.881477720403852, 51.619390423316226], [-0.881374708667671, 51.619291432867335], [-0.880834298239682, 51.61853547912722], [-0.880617549323506, 51.618127888748454], [-0.880388345702594, 51.61816796449318], [-0.879226788544387, 51.6185884841998], [-0.878534686661489, 51.61883184500677], [-0.878385021629543, 51.61898507235025], [-0.878148819949825, 51.61913297697072], [-0.878102165244257, 51.61915051459153], [-0.87804120240859, 51.61916252048532], [-0.877967464227806, 51.619165412606506], [-0.877896924603018, 51.61915574690363], [-0.877839648002824, 51.61913541789456], [-0.877812586845032, 51.61911987344738], [-0.877382402665225, 51.61869944717381], [-0.877261875140598, 51.61866682400238], [-0.877087293116294, 51.618600414623565], [-0.876592344555959, 51.61846350297477], [-0.876408990128558, 51.61845995037962], [-0.876374465270622, 51.61845422502283], [-0.876347205240439, 51.61844677083749], [-0.87630299358364, 51.61842386858449], [-0.876241963569583, 51.618380124514495], [-0.876216636094276, 51.618352907107045], [-0.876152781748704, 51.618131100785114], [-0.876106882196741, 51.61811807314475], [-0.876305643178539, 51.617614643124426], [-0.875030363348109, 51.6174927341714], [-0.874705473526163, 51.61748872204597], [-0.874564111923802, 51.6174810731233], [-0.874279482039409, 51.61730930128958], [-0.874259717266618, 51.61699889890464], [-0.874416434195306, 51.61673604585861], [-0.874423036602998, 51.61652750219062], [-0.870144618410033, 51.61769939147719], [-0.870074692270606, 51.617607003497994], [-0.869665459226217, 51.61768399010514], [-0.869137937974611, 51.617812887107476], [-0.868711126950696, 51.61789959196275], [-0.868460959800069, 51.617969115035805], [-0.866874516019656, 51.61827841686334], [-0.866642434191741, 51.6183175388698], [-0.866517885416195, 51.61833072340073], [-0.866392071649004, 51.61833670224208], [-0.865776872894858, 51.61833166083683], [-0.865633662902087, 51.618340168339564], [-0.865493072065054, 51.618359490991885], [-0.864874419821269, 51.618492883413026], [-0.864829070270363, 51.61851582340227], [-0.8648101986804, 51.61846169086974], [-0.864778464993556, 51.618402038980314], [-0.864733824417545, 51.61833866562683], [-0.864681918741689, 51.61827702035103], [-0.864649512487616, 51.61824433697217], [-0.864492159027339, 51.61812502442397], [-0.864510219622979, 51.618037979732996], [-0.864490008258273, 51.61792179156664], [-0.863791866117017, 51.616668790850674], [-0.863578496430752, 51.61619016667409], [-0.863939572338851, 51.6160749702936], [-0.864141702322916, 51.61602027805823], [-0.864343742093738, 51.615969181278444], [-0.864684853799959, 51.61590144547291], [-0.864287415633653, 51.61573755014447], [-0.864114344880943, 51.615611790807684], [-0.86394143216696, 51.615479738556914], [-0.863424226660599, 51.6150224515856], [-0.863108525016747, 51.61470918210108], [-0.862999136822108, 51.61463618943345], [-0.862947760773663, 51.614611414387845], [-0.862827479233939, 51.614569786988696], [-0.862764327092327, 51.6145538895073], [-0.862690954996651, 51.614542388851355], [-0.862422671693898, 51.614528100870835], [-0.862278208948609, 51.61452939875511], [-0.862025067586916, 51.614544929155834], [-0.861633333855888, 51.61461576315295], [-0.861195617216796, 51.61467715820802], [-0.860991546767721, 51.61469406144679], [-0.860819513274215, 51.61470048511226], [-0.860591345418716, 51.61469917048917], [-0.860366335624517, 51.61468709604235], [-0.860199196800327, 51.61467108707321], [-0.860140174693704, 51.6146633207896], [-0.859842784619867, 51.61460018922178], [-0.85969929013584, 51.61456282905675], [-0.859501466379857, 51.61450336097874], [-0.859306643699259, 51.614439425872085], [-0.859175017225196, 51.614389591981386], [-0.858977780895874, 51.61430675031806], [-0.858172868778381, 51.61392127488393], [-0.856305510909038, 51.61299763777437], [-0.855879431428414, 51.61282624136621], [-0.855413827571698, 51.612676038205095], [-0.855073660630441, 51.61259179657028], [-0.854915624510577, 51.612558784566126], [-0.854688372582268, 51.61252150056368], [-0.854459541396129, 51.6124895957323], [-0.854208848612115, 51.61246556965946], [-0.853413812340721, 51.612436228916096], [-0.851724243907319, 51.61242871018406], [-0.851450292115, 51.612410744947404], [-0.850998615679464, 51.61233888823236], [-0.850653274334699, 51.61223120468302], [-0.850372939737194, 51.61235164666859], [-0.850315593337778, 51.61233490012849], [-0.850193999216673, 51.612288751000705], [-0.850146601119627, 51.612278395984944], [-0.849926028861458, 51.61226274823948], [-0.849854084982468, 51.61225215268858], [-0.849714847013531, 51.612218418620564], [-0.849473435162227, 51.61217019573735], [-0.849372523204365, 51.61216291272777], [-0.849235958321253, 51.61219484371945], [-0.849170915863905, 51.6121969037703], [-0.849112126238191, 51.61218014249445], [-0.8487984760956, 51.61201881385575], [-0.848813983178796, 51.61186251023449], [-0.848805967905994, 51.611779707971536], [-0.848777693193183, 51.61169850541887], [-0.848751669639592, 51.61164250170296], [-0.848740414389996, 51.61163070213332], [-0.848685616135578, 51.61162746733029], [-0.848598109857592, 51.61148993537107], [-0.848561752293423, 51.61144282198033], [-0.848420551583887, 51.61131555337684], [-0.848346143135118, 51.61123120073643], [-0.848017978126262, 51.61073074025961], [-0.84803240586268, 51.61067423405594], [-0.848009203184881, 51.61062095534751], [-0.848010806265629, 51.61061467688053], [-0.848360723390725, 51.61054078070849], [-0.848731046077576, 51.61040234328455], [-0.848814480324059, 51.61035820278237], [-0.848820437461021, 51.610351067821576], [-0.848690278305866, 51.610072847084595], [-0.847947554822518, 51.60900543974003], [-0.847435103308081, 51.6083125448088], [-0.847167998407497, 51.60796823756615], [-0.846186886755928, 51.60662333116728], [-0.845549998419521, 51.605828497430636], [-0.845383680959569, 51.60566770865375], [-0.844840468159951, 51.60522267062485], [-0.84443530295085, 51.60497141150611], [-0.844232696249957, 51.60481835643492], [-0.843486943931864, 51.60416181103064], [-0.84332558359401, 51.60420428093958], [-0.842908147301968, 51.603868373383044], [-0.842663709069561, 51.603714004109015], [-0.842310199280505, 51.603533382087996], [-0.841471682375652, 51.60311958453644], [-0.841215384127901, 51.602977683579475], [-0.840873068217364, 51.60281155440105], [-0.840467421086961, 51.602637605395635], [-0.840268344470896, 51.602516948405764], [-0.840203154295604, 51.60246864832527], [-0.838474883614574, 51.601841924417336], [-0.838334815858368, 51.60178568911777], [-0.838125139250388, 51.60168470536249], [-0.837520083534699, 51.60134782062488], [-0.837365310402971, 51.60124558073874], [-0.837143016970701, 51.6010734356079], [-0.83702163004049, 51.600964332538595], [-0.836879440722268, 51.60082175386177], [-0.836733036616179, 51.60067463738169], [-0.836105420124444, 51.59992210370809], [-0.836001567218505, 51.59980508080317], [-0.835894758960057, 51.59969072601903], [-0.835646409012494, 51.5994652683849], [-0.835572705263831, 51.59941148620318], [-0.835355212679077, 51.599278049641256], [-0.835001490423373, 51.59910819321327], [-0.834666328550124, 51.59894661249016], [-0.834023851532118, 51.59860753956394], [-0.833813699592692, 51.59846967713012], [-0.832219972267628, 51.59727861587006], [-0.831975375091702, 51.59713321406168], [-0.83180286996819, 51.597047874561696], [-0.83156138306724, 51.59695015903964], [-0.831279067386554, 51.596868221715724], [-0.831119729288761, 51.59683246683902], [-0.830996129682144, 51.596810555210986], [-0.830798964246538, 51.59678611250204], [-0.829935838169309, 51.596720865686486], [-0.82967342169104, 51.596707460026586], [-0.829378950815281, 51.59670542343618], [-0.828672101908656, 51.596738836236966], [-0.828529092462618, 51.59674190522934], [-0.828241907711544, 51.596737240965595], [-0.828066024571149, 51.59672739285258], [-0.827854311754233, 51.596707295846045], [-0.827399248313258, 51.59666228882735], [-0.827164974703315, 51.59662128423301], [-0.827063074447412, 51.59659778687348], [-0.826830893268571, 51.59653162563389], [-0.826403126611598, 51.596379885757386], [-0.826320361645679, 51.596342192238744], [-0.826196596762853, 51.596270819297594], [-0.825930135887572, 51.596078429107884], [-0.825702044863314, 51.59590980062742], [-0.825239717878873, 51.595531118786504], [-0.824901250965003, 51.59522021379687], [-0.824412039116432, 51.59470908081712], [-0.8242790371805, 51.59460434384618], [-0.824162427084317, 51.59453573788591], [-0.823734544991122, 51.59433363318264], [-0.822923577534385, 51.59387232098135], [-0.82274220720895, 51.593740122024236], [-0.822758790294358, 51.59343366962803], [-0.822450529949737, 51.592123177421634], [-0.822408018987733, 51.591980681321466], [-0.82236394886053, 51.59184266543808], [-0.822242174035691, 51.59158338051977], [-0.821801765862476, 51.5908065697487], [-0.821372709449585, 51.59009371260957], [-0.821171850754746, 51.58982284235581], [-0.820679968304875, 51.58936291919855], [-0.820417155492676, 51.58914357740762], [-0.82015811620844, 51.5888901042506], [-0.820045903377484, 51.58876399099103], [-0.81975498206002, 51.5884040936899], [-0.819793038416411, 51.58838379523831], [-0.819648800144719, 51.588268149727725], [-0.819147039514258, 51.58763368041164], [-0.818936357700162, 51.58740856531028], [-0.818746726401906, 51.58698404449756], [-0.818744261992127, 51.58691208559554], [-0.818786542624285, 51.586561832259704], [-0.818798419467402, 51.58638211648965], [-0.818772601288344, 51.58593047014409], [-0.818622316220491, 51.585380460186784], [-0.818493730937228, 51.58471737211902], [-0.818460174123387, 51.58461992329734], [-0.818316632401033, 51.58436670899539], [-0.818092592164715, 51.58404524580265], [-0.817774082795079, 51.58341531231479], [-0.817553796530972, 51.58311636524129], [-0.817445537064436, 51.58300557512581], [-0.81689125274485, 51.582562990062094], [-0.816348587477007, 51.58217357091916], [-0.816214612729635, 51.58210837837547], [-0.816144330954904, 51.58209148442308], [-0.816059129697027, 51.58209332267878], [-0.815742672724781, 51.5820523651453], [-0.815217212787465, 51.58194545592985], [-0.815002344756643, 51.58188304223224], [-0.814826435408141, 51.5818210214772], [-0.814485295861823, 51.581730356582035], [-0.81444044205173, 51.581790148477246], [-0.813566956536122, 51.581635656767844], [-0.813282023122958, 51.58154825394594], [-0.813052037332166, 51.581456910143594], [-0.812870182657061, 51.581346270732034], [-0.812790810356639, 51.58129061819263], [-0.812604263086127, 51.581138568732094], [-0.812386509085548, 51.58085492331321], [-0.812249092317067, 51.58070067277682], [-0.812167619564544, 51.58055957666617], [-0.812051961231651, 51.58029045130041], [-0.812042798783181, 51.580254391465495], [-0.812034433182585, 51.580187767648724], [-0.812033188044369, 51.58012481260171], [-0.812058064730261, 51.580000977815104], [-0.81229781440549, 51.579440518478464], [-0.812247901650195, 51.57941753400863], [-0.812446355706805, 51.57916777205078], [-0.81277233113049, 51.578787120404634], [-0.813191367818544, 51.57821318632392], [-0.813476583358647, 51.57767926033569], [-0.81372993476285, 51.57714950751218], [-0.813894821439398, 51.57669169369027], [-0.813998634879093, 51.57614064720803], [-0.814138744624452, 51.57508193151095], [-0.814120940539715, 51.57493428638376], [-0.81419874804071, 51.57321943977239], [-0.814492542549023, 51.572575897898666], [-0.814547744449169, 51.57211787423915], [-0.814549364628156, 51.57200009817749], [-0.81449843948966, 51.57157247390041], [-0.81447275908744, 51.57022974030085], [-0.814470739157426, 51.56964165674743], [-0.814429823166273, 51.56938407823071], [-0.814416473674158, 51.5693425811485], [-0.814362577800679, 51.569251219648685], [-0.81406844007837, 51.5689659058573], [-0.813908308238922, 51.56874308971205], [-0.813853532979604, 51.56863013877188], [-0.81375715260415, 51.56839717647337], [-0.81371284208748, 51.56815934527622], [-0.813667666933597, 51.567788426746645], [-0.813915408556528, 51.567527470860746], [-0.814280993234198, 51.56684059466537], [-0.814704823511867, 51.56613272518902], [-0.814994772052415, 51.56569055892733], [-0.815202529336662, 51.56519091397622], [-0.815219131565213, 51.56505170869626], [-0.815351636137841, 51.564671793906264], [-0.815511116853932, 51.56436408558186], [-0.815565592175225, 51.5642108755608], [-0.815662011458114, 51.564053592855515], [-0.815731002538058, 51.56389693250399], [-0.815762954470268, 51.56377766396064], [-0.815882314039101, 51.56307031436626], [-0.815899206541573, 51.563030920866616], [-0.815918960262566, 51.5629924554096], [-0.816100387305838, 51.56272812828101], [-0.816239061970809, 51.562387838558415], [-0.816351227865814, 51.56217946080997], [-0.816402225233145, 51.562104443964415], [-0.816445731089239, 51.56204014171416], [-0.816755073070336, 51.56173843863565], [-0.81682883069147, 51.5615089920632], [-0.81709149295673, 51.56100450196165], [-0.817126546068515, 51.5610435199925], [-0.817036868291134, 51.56144185218239], [-0.817602599672938, 51.56148891511105], [-0.817650902097453, 51.56129517879352], [-0.81772376875861, 51.56109989153342], [-0.818544773098936, 51.56114952106405], [-0.818940645385275, 51.56112652991029], [-0.819286252234888, 51.56087194248433], [-0.820505192935939, 51.560762809232635], [-0.821152924392013, 51.56109751750433], [-0.821401734784996, 51.56112699167495], [-0.821468077854438, 51.561127657861135], [-0.821837057068471, 51.56108460493917], [-0.822551882107614, 51.56083281445182], [-0.822991148836609, 51.56069335159132], [-0.823298868990794, 51.56056425765945], [-0.823427756279142, 51.560489119484224], [-0.823816316952276, 51.56018999039105], [-0.823841530161624, 51.56016326766115], [-0.823879440321637, 51.5600917131651], [-0.823939663402364, 51.55926686943448], [-0.824000930577316, 51.55924050793579], [-0.823876052668265, 51.55798579953388], [-0.823797968341331, 51.557154174451156], [-0.823813910366727, 51.55698348995032], [-0.824268965579194, 51.556733581409404], [-0.824612742777356, 51.55649154853787], [-0.826344281900068, 51.55484359477631], [-0.826657025878971, 51.55457337099326], [-0.827233265990788, 51.554040521447654], [-0.827929376968602, 51.55344502444081], [-0.828029419518581, 51.553368693973354], [-0.828246668974642, 51.55322159923911], [-0.828485269800709, 51.5530855074047], [-0.828605105979095, 51.55302466009866], [-0.829372820563392, 51.55267264797847], [-0.830416538296143, 51.552300003050114], [-0.830341853307235, 51.55217517181714], [-0.830015969895102, 51.55217192349864], [-0.82991663595149, 51.55216463892005], [-0.829524156953837, 51.55211486704629], [-0.829282415323888, 51.552092673855796], [-0.828838545910614, 51.55207835426137], [-0.828599504055965, 51.55206338004898], [-0.828680519991051, 51.55199764928292], [-0.828534433277995, 51.55195752639793], [-0.828384829125967, 51.55188589688778], [-0.827987906418731, 51.55167242458396], [-0.827957477145366, 51.551621766572], [-0.827834232346298, 51.55159086272802], [-0.827633977763617, 51.551525919798664], [-0.827259642164726, 51.55144395104261], [-0.826879262755715, 51.5513727108443], [-0.826619197529414, 51.551334143723224], [-0.825020961294276, 51.55117248609027], [-0.825087548806697, 51.55099511486544], [-0.825080332863119, 51.55093929339289], [-0.825041927300218, 51.55086247849746], [-0.82502361605882, 51.55078946149474], [-0.825044884876699, 51.55069166368164], [-0.825058487270179, 51.550667521970404], [-0.82509857658956, 51.550622964257876], [-0.825145597538488, 51.55058926609727], [-0.825325151596322, 51.5505056412203], [-0.824909915146001, 51.550164291306395], [-0.82525013660448, 51.550002248032946], [-0.825332063085088, 51.549957209837], [-0.825638185418255, 51.54977504214384], [-0.82578350044032, 51.54967668704559], [-0.825923116734683, 51.54957557721289], [-0.826170603160388, 51.54937393870707], [-0.826371785812396, 51.54917813090106], [-0.826492161334072, 51.549039961540565], [-0.826611394860751, 51.548890091280356], [-0.82670116630089, 51.54876420424681], [-0.826782355507479, 51.54863553380353], [-0.826823019292071, 51.54856850170786], [-0.827062757600335, 51.548106920435835], [-0.827101368877001, 51.54800749719491], [-0.827194201898492, 51.54770629998806], [-0.827307057244965, 51.54741159704493], [-0.827582602426052, 51.54684696658141], [-0.827901482950928, 51.54639156924703], [-0.828226190833503, 51.54604592938406], [-0.828636291311094, 51.545744301711125], [-0.82879259021163, 51.54566673370386], [-0.828904643767125, 51.545627388779295], [-0.829074413403866, 51.54558682127211], [-0.829642313890905, 51.54554213206049], [-0.831137752395514, 51.5457125947128], [-0.831296230672639, 51.545718668970665], [-0.831381409559054, 51.545715021306385], [-0.831520416985355, 51.54569302674314], [-0.831658465956176, 51.54565213966273], [-0.832162223002951, 51.54540897973132], [-0.832259763552867, 51.545373083913695], [-0.832342495362879, 51.54535232675641], [-0.832449690786029, 51.545333611293344], [-0.832560958333776, 51.54532482723805], [-0.832748224427793, 51.54533298427906], [-0.833594396864807, 51.5455158387706], [-0.833803468208608, 51.5455736658201], [-0.834066591719905, 51.54566080332341], [-0.834319302360527, 51.54576042533909], [-0.834632701147966, 51.545911902800114], [-0.834743597643834, 51.54597414830218], [-0.834972095381443, 51.546118487532766], [-0.835101437527799, 51.546192605160904], [-0.835308853525451, 51.54642845092972], [-0.835597379030446, 51.546650714213946], [-0.835675530378703, 51.54669644865621], [-0.835765285050956, 51.54673960061442], [-0.835946924814448, 51.54679895002405], [-0.836738145066418, 51.54693268079673], [-0.837616543696299, 51.54698454508781], [-0.837668585980954, 51.546979665457], [-0.837867989708348, 51.546964555807335], [-0.83797367625272, 51.54694851789646], [-0.838105566972017, 51.54692284834119], [-0.838233315283634, 51.54688994418392], [-0.838329229403341, 51.54686122067977], [-0.838482151664417, 51.546802489195365], [-0.839036827411148, 51.54642762424692], [-0.83955396219585, 51.54605418383688], [-0.840116011657223, 51.54567219327131], [-0.840736658187885, 51.54525391246058], [-0.840941426195899, 51.54514083988849], [-0.841049279937165, 51.54509604683764], [-0.841194847094701, 51.5450426342828], [-0.841299520083949, 51.545009498946165], [-0.841898633062652, 51.544870644649805], [-0.842282244574123, 51.54481328536381], [-0.842762474116396, 51.54475597844143], [-0.843565178344648, 51.54477737891959], [-0.844086979548171, 51.54484366398717], [-0.845732620874625, 51.545006428046236], [-0.847066038668597, 51.54519847249473], [-0.847735465249349, 51.545415455459946], [-0.84773690700669, 51.54541546961599], [-0.848634731053663, 51.54572550693968], [-0.849946581441456, 51.54620234699594], [-0.850255922443757, 51.54628810259981], [-0.850450510421732, 51.5463493547082], [-0.850677807173489, 51.54642891042725], [-0.850994850981171, 51.546552505063595], [-0.852786328510159, 51.547342426670774], [-0.85300310746802, 51.547496506935786], [-0.853571212311598, 51.54778799706584], [-0.854020445083318, 51.54798930492918], [-0.854581807452525, 51.548205193183556], [-0.85478620907829, 51.54827822314386], [-0.854963577157503, 51.54833660211785], [-0.855161244465997, 51.54839068294659], [-0.855663052553423, 51.5485088736389], [-0.856166529832507, 51.54867563412252], [-0.856279761006, 51.54870371304979], [-0.856530960852844, 51.54875111981111], [-0.856804082121709, 51.54878705024175], [-0.857112033920981, 51.54881432744164], [-0.857381573472553, 51.548820548731904], [-0.857549123049589, 51.54881049056259], [-0.857844479857821, 51.548764809719025], [-0.858057604662229, 51.54872012637499], [-0.858337617310588, 51.54865361386837], [-0.858552497890933, 51.54859635820055], [-0.859049392399301, 51.548450127924276], [-0.859439117962245, 51.5483792842905], [-0.859697682244768, 51.54836291412634], [-0.859779823131423, 51.54836551056866], [-0.860170027263243, 51.548390881318824], [-0.860456238387038, 51.54842243448379], [-0.861009536104037, 51.548500639150554], [-0.861158816462501, 51.54852906321894], [-0.861352413335375, 51.54857320311727], [-0.861544411683264, 51.54862362144007], [-0.861731905414109, 51.5486811891874], [-0.862073439754406, 51.548807688741114], [-0.86254414698236, 51.54901726458452], [-0.86282747298222, 51.54916477803516], [-0.863015068128655, 51.549276295417606], [-0.863120154717426, 51.549342054318615], [-0.863285809311142, 51.54946594721784], [-0.863418211576468, 51.54959311456195], [-0.863530092020445, 51.54973357070672], [-0.863653360363745, 51.549937978681236], [-0.863733641061499, 51.550131180181424], [-0.863790336700716, 51.5503448343906], [-0.863824973966162, 51.550691353426465], [-0.863841717303786, 51.55100353042492], [-0.863889686614544, 51.55116225019172], [-0.863971345177536, 51.55135816235228], [-0.864192531443895, 51.5518009005184], [-0.864636908176204, 51.552606367995786], [-0.864885616784935, 51.55304487507487], [-0.864984710926909, 51.55317801261536], [-0.865042267578469, 51.5532415116859], [-0.86524661818949, 51.553434113390985], [-0.866448255146234, 51.55464702695421], [-0.866553639357719, 51.55475954277147], [-0.86713929523259, 51.555454866418074], [-0.86728119491555, 51.55560729781788], [-0.867357192432134, 51.55568356216347], [-0.867846797612144, 51.55612348793147], [-0.867948777192819, 51.5561991033314], [-0.868039688780355, 51.55625572917072], [-0.868162193200772, 51.55631805467487], [-0.868334859667638, 51.55639345221028], [-0.868507816648064, 51.556457162985154], [-0.868686743286876, 51.556512838449954], [-0.868885971532242, 51.55656421341042], [-0.869870431325262, 51.55700170522159], [-0.870538382015661, 51.557289577406756], [-0.87065953954758, 51.55734829060127], [-0.870968323528286, 51.55751940747054], [-0.871084688448939, 51.55759695683154], [-0.871173919806704, 51.55766345498963], [-0.871421843971099, 51.55790412108149], [-0.871517352960249, 51.558008444760674], [-0.871560414081151, 51.55807539786269], [-0.871689483441928, 51.558339198343305], [-0.871715457861831, 51.558455441841], [-0.871819115572425, 51.558871857901316], [-0.872116688986198, 51.559438501590606], [-0.87224925001588, 51.559678057158926], [-0.872395481580982, 51.5598898694294], [-0.872503199025109, 51.56002578071336], [-0.872616797176149, 51.56015725249727], [-0.872767427555836, 51.560307962534345], [-0.873712440787397, 51.560887112412736], [-0.874019840047307, 51.56105730856152], [-0.874413245272104, 51.56124990894107], [-0.875159636577155, 51.56157807024888], [-0.875469862748955, 51.561692540724444], [-0.875618818634067, 51.561736229028845], [-0.87605776549836, 51.56183754414599], [-0.876366373823489, 51.56190074371407], [-0.87668521195865, 51.561958645316366], [-0.876968369886447, 51.56200091867397], [-0.877197163756339, 51.56202468778881], [-0.877516822654725, 51.5620493254706], [-0.878098847659676, 51.56208186543848], [-0.879220205739232, 51.56212315048378], [-0.879742407250114, 51.562124539056946], [-0.8803196812009, 51.56211566057546], [-0.88047709073344, 51.562109069498774], [-0.880781923890852, 51.5620912956137], [-0.881058065229737, 51.56206695318683], [-0.881262135404653, 51.56204012483733], [-0.881418631531618, 51.562011943580096], [-0.881649213834679, 51.56196288783239], [-0.882003250428868, 51.56187993977645], [-0.882376388095226, 51.56178278572967], [-0.882764299497775, 51.56167138432022], [-0.883194585739291, 51.561537905452155], [-0.883498576630078, 51.5614364931922], [-0.883756281221724, 51.56134003501421], [-0.884086956514705, 51.56120920221847], [-0.884407665982054, 51.56107287871968], [-0.885457870533961, 51.5606602434964], [-0.885606584631741, 51.56059601575753], [-0.88578613479336, 51.56050960117672], [-0.88595858283258, 51.56041862303493], [-0.886091760097573, 51.560340759581955], [-0.886521253482028, 51.56006159461465], [-0.886883345687433, 51.559824949307504], [-0.887389733197074, 51.559468282123994], [-0.887580604245187, 51.55927227271282], [-0.887708691217493, 51.559107139161064], [-0.888191015763102, 51.55861266662589], [-0.888192457957821, 51.55861268028735], [-0.888287760756616, 51.55849039596854], [-0.888562664893145, 51.558278995716826], [-0.888677108662246, 51.55814070717499], [-0.888887527216288, 51.55791161122132], [-0.889030158653071, 51.55774121885465], [-0.889203011709727, 51.557514464273005], [-0.88945350380216, 51.55717964382524], [-0.889600043815338, 51.556967026485395], [-0.889736358446423, 51.55670036168757], [-0.889858423154084, 51.55648571413559], [-0.889957478394766, 51.55626815130874], [-0.88999480235023, 51.556157006507235], [-0.890171676314085, 51.5555274577222], [-0.89040150985715, 51.554855248874496], [-0.891496918227321, 51.55316795557777], [-0.892148150167392, 51.55212836271704], [-0.892302414411729, 51.5517746441604], [-0.892679622502675, 51.55097074336506], [-0.892968782461996, 51.55046633574481], [-0.893655961353766, 51.54930928124159], [-0.894173495307085, 51.548604708475054], [-0.894625223197592, 51.54805597035748], [-0.895275002004698, 51.547308578527485], [-0.895581553072133, 51.54691762432374], [-0.89567259455686, 51.54679079793778], [-0.895853734572665, 51.54651645501248], [-0.896746527292651, 51.54508077321264], [-0.896901839906062, 51.544860136456265], [-0.897255891587921, 51.54494888564188], [-0.898115394177492, 51.545187148067974], [-0.89822539056202, 51.54523044209882], [-0.898280925208036, 51.54525973711452], [-0.898317695099433, 51.54528975512979], [-0.898473190139101, 51.54530020648797], [-0.899619101095523, 51.54544313546729], [-0.901006352145532, 51.54562517973134], [-0.901825064903737, 51.54570208025918], [-0.903152296119515, 51.54586195719927], [-0.903215411109321, 51.54587603470979], [-0.903297183099556, 51.545893883241035], [-0.903017403675823, 51.54655396139701], [-0.902616538461231, 51.54745118838641], [-0.902395351374664, 51.54801290343283], [-0.902224993241029, 51.54837997226972], [-0.902166365216381, 51.54859882282856], [-0.902146545476892, 51.54876318664974], [-0.902208891983797, 51.54892921824649], [-0.902230894835185, 51.549033728477525], [-0.902380735585514, 51.54999904656443], [-0.902673692529055, 51.551610411429984], [-0.902806620567669, 51.55250003963136], [-0.902816651036337, 51.55268266601908], [-0.902804979597758, 51.55292803179951], [-0.902756997764027, 51.55318384821566], [-0.902654701329301, 51.55353896524768], [-0.902427419928527, 51.55423280167036], [-0.901847751389036, 51.555843197130926], [-0.901770133963284, 51.556011515784924], [-0.90172081219273, 51.556082988265544], [-0.902203201151337, 51.55617741874876], [-0.906010818638152, 51.55679743475821], [-0.906204734572883, 51.556771367660915], [-0.906311884484255, 51.55675438267928], [-0.906358975073264, 51.55689599188705], [-0.90638590166065, 51.55691602462513], [-0.906615524939952, 51.55696492104195], [-0.907278267614382, 51.55705831304524], [-0.907858939004531, 51.55720578727805], [-0.908174621569804, 51.5572752632291], [-0.908339760107985, 51.55730647205926], [-0.908420198492941, 51.557320707807335], [-0.908923514869315, 51.557385632424236], [-0.909322889103033, 51.5574540848968], [-0.909506497855653, 51.557497152980005], [-0.909658336207082, 51.557541723987356], [-0.909754316957776, 51.55756959081508], [-0.909871264277585, 51.557625526703404], [-0.91002439519459, 51.55767640345812], [-0.91014009429463, 51.557724234915874], [-0.910363938659539, 51.55783421414451], [-0.910769828656022, 51.55805288423369], [-0.910899633150579, 51.55817457810929], [-0.911134211672749, 51.55843931338367], [-0.911191431662737, 51.558519870694006], [-0.911262279817118, 51.55863382382822], [-0.911345597527786, 51.558829717406], [-0.911347039740573, 51.55882973078292], [-0.911354152248679, 51.55895478193117], [-0.911501156990394, 51.55932300828838], [-0.911744284152759, 51.55977395051585], [-0.911784714781588, 51.55983277167005], [-0.911848028397377, 51.559899897522016], [-0.911951124589094, 51.55999256899618], [-0.912043240814804, 51.56006176008463], [-0.912343203354435, 51.560247072388215], [-0.91252735254784, 51.560389049785144], [-0.912663001694362, 51.56050809825428], [-0.913644040185922, 51.561715780647766], [-0.914729932802775, 51.56149024267299], [-0.915936249212879, 51.561720788632314], [-0.917099342153636, 51.56255696600573], [-0.917716153850379, 51.56209778262442], [-0.918510926061236, 51.561494569835055], [-0.919190082061234, 51.56187308324347], [-0.919265061021478, 51.56187467281339], [-0.919319677161742, 51.561883268238525], [-0.919395565855925, 51.56190734542486], [-0.919450182060758, 51.561915940789575], [-0.919451624375034, 51.56191595406745], [-0.919612764956992, 51.561873377936905], [-0.919684473323871, 51.562134798108005], [-0.919731696029427, 51.56227280618616], [-0.919795125391412, 51.562396576626476], [-0.919877773921036, 51.56250074208832], [-0.920024454979703, 51.56264236275641], [-0.920273793481437, 51.562835281288635], [-0.920455811890565, 51.56300779833283], [-0.92054707457537, 51.56311384087594], [-0.920622684574115, 51.56321074767881], [-0.920768557091237, 51.56344767224896], [-0.920815933327546, 51.56357938704838], [-0.92087756775181, 51.56365728255545], [-0.920897207761338, 51.56368084160506], [-0.920950783915168, 51.5637334861553], [-0.921113636188415, 51.563862665653886], [-0.921195103215065, 51.56395602921301], [-0.921351882125165, 51.56422002842434], [-0.921395592904906, 51.56432383493418], [-0.921420893006769, 51.56441308549212], [-0.921438619701684, 51.56451755238376], [-0.921413985191466, 51.56464410933019], [-0.92167481147157, 51.56453500840272], [-0.923479752756133, 51.56373602685831], [-0.924155377789785, 51.5634113259626], [-0.924873111301507, 51.56399247344971], [-0.924951149378637, 51.56404803772923], [-0.925274524870032, 51.56428388466152], [-0.92664770764064, 51.56515336065692], [-0.927393574791524, 51.56558368874587], [-0.927927453464337, 51.5659491340051], [-0.92835633038721, 51.56599441223158], [-0.928244524844939, 51.56725223174753], [-0.928125342518282, 51.56741209518939], [-0.9281054698832, 51.56745956981058], [-0.927839528670842, 51.568092855254655], [-0.93052584537502, 51.568532778436946], [-0.930434864440691, 51.56872077542371], [-0.930290537945866, 51.568968530677175], [-0.93032458943141, 51.568993118606556], [-0.930407160146686, 51.56904062792432], [-0.930494248489543, 51.56908008580425], [-0.93056005729139, 51.5691040638391], [-0.930644619283805, 51.56912821268005], [-0.930755210497826, 51.569149901051155], [-0.931002865082897, 51.56917193845677], [-0.931506345671459, 51.5692367670135], [-0.9319179887186, 51.56928007686346], [-0.93222706378822, 51.569328746497334], [-0.932389335623021, 51.56936169347699], [-0.932508352034028, 51.56939334769875], [-0.932608510110525, 51.56942932617174], [-0.932871163025979, 51.56955040480943], [-0.933086053531851, 51.569616199317096], [-0.933414865356232, 51.569684826955594], [-0.93386895042082, 51.56976448240679], [-0.934635570791928, 51.5700537823344], [-0.934785550106084, 51.57011898456062], [-0.934985327167408, 51.57021431104797], [-0.935122135234023, 51.5702874858722], [-0.935333952219633, 51.570423383659445], [-0.935683954424458, 51.570697207984594], [-0.935948857561102, 51.57084617434456], [-0.936321009353978, 51.57109861741231], [-0.936776166293208, 51.57138058458356], [-0.936874033955222, 51.57139136186155], [-0.937185388877335, 51.57140497135624], [-0.937358713203379, 51.57139754881963], [-0.937474500211682, 51.571382411871916], [-0.937604964789291, 51.57135661760672], [-0.938082770631526, 51.571224267138255], [-0.938303744516349, 51.57115343316592], [-0.938622419406116, 51.57103852370375], [-0.938583754985448, 51.57127375671787], [-0.938615426417796, 51.5714008261012], [-0.938651384040882, 51.57152973256723], [-0.938810396393867, 51.572013125409214], [-0.938917102284257, 51.5723881447753], [-0.938977920287056, 51.572564931845086], [-0.939147081147104, 51.57298457478389], [-0.93921529881351, 51.57340150695511], [-0.939295227462625, 51.57374930879435], [-0.939359853061118, 51.57401065198471]]]}} diff --git a/distributors-json/bench/data/github-issues.json b/distributors-json/bench/data/github-issues.json new file mode 100644 index 00000000..409b859f --- /dev/null +++ b/distributors-json/bench/data/github-issues.json @@ -0,0 +1,1540 @@ +[ + { + "url": "https://api.github.com/repos/bos/aeson/issues/772", + "repository_url": "https://api.github.com/repos/bos/aeson", + "labels_url": "https://api.github.com/repos/bos/aeson/issues/772/labels{/name}", + "comments_url": "https://api.github.com/repos/bos/aeson/issues/772/comments", + "events_url": "https://api.github.com/repos/bos/aeson/issues/772/events", + "html_url": "https://github.com/bos/aeson/pull/772", + "id": 593935498, + "node_id": "MDExOlB1bGxSZXF1ZXN0Mzk4NjI4OTIx", + "number": 772, + "title": "WIP: Add cabal.bench.project for running benchmarks", + "user": { + "login": "phadej", + "id": 51087, + "node_id": "MDQ6VXNlcjUxMDg3", + "avatar_url": "https://avatars2.githubusercontent.com/u/51087?v=4", + "gravatar_id": "", + "url": "https://api.github.com/users/phadej", + "html_url": "https://github.com/phadej", + "followers_url": "https://api.github.com/users/phadej/followers", + "following_url": "https://api.github.com/users/phadej/following{/other_user}", + "gists_url": "https://api.github.com/users/phadej/gists{/gist_id}", + "starred_url": "https://api.github.com/users/phadej/starred{/owner}{/repo}", + "subscriptions_url": "https://api.github.com/users/phadej/subscriptions", + "organizations_url": "https://api.github.com/users/phadej/orgs", + "repos_url": "https://api.github.com/users/phadej/repos", + "events_url": "https://api.github.com/users/phadej/events{/privacy}", + "received_events_url": "https://api.github.com/users/phadej/received_events", + "type": "User", + "site_admin": false + }, + "labels": [ + + ], + "state": "open", + "locked": false, + "assignee": null, + "assignees": [ + + ], + "milestone": null, + "comments": 1, + "created_at": "2020-04-04T15:53:53Z", + "updated_at": "2020-04-07T11:10:42Z", + "closed_at": null, + "author_association": "CONTRIBUTOR", + "pull_request": { + "url": "https://api.github.com/repos/bos/aeson/pulls/772", + "html_url": "https://github.com/bos/aeson/pull/772", + "diff_url": "https://github.com/bos/aeson/pull/772.diff", + "patch_url": "https://github.com/bos/aeson/pull/772.patch" + }, + "body": "" + }, + { + "url": "https://api.github.com/repos/bos/aeson/issues/768", + "repository_url": "https://api.github.com/repos/bos/aeson", + "labels_url": "https://api.github.com/repos/bos/aeson/issues/768/labels{/name}", + "comments_url": "https://api.github.com/repos/bos/aeson/issues/768/comments", + "events_url": "https://api.github.com/repos/bos/aeson/issues/768/events", + "html_url": "https://github.com/bos/aeson/pull/768", + "id": 593798540, + "node_id": "MDExOlB1bGxSZXF1ZXN0Mzk4NTA2NDAy", + "number": 768, + "title": "Implement JSON parser using scanner", + "user": { + "login": "Yuras", + "id": 692251, + "node_id": "MDQ6VXNlcjY5MjI1MQ==", + "avatar_url": "https://avatars0.githubusercontent.com/u/692251?v=4", + "gravatar_id": "", + "url": "https://api.github.com/users/Yuras", + "html_url": "https://github.com/Yuras", + "followers_url": "https://api.github.com/users/Yuras/followers", + "following_url": "https://api.github.com/users/Yuras/following{/other_user}", + "gists_url": "https://api.github.com/users/Yuras/gists{/gist_id}", + "starred_url": "https://api.github.com/users/Yuras/starred{/owner}{/repo}", + "subscriptions_url": "https://api.github.com/users/Yuras/subscriptions", + "organizations_url": "https://api.github.com/users/Yuras/orgs", + "repos_url": "https://api.github.com/users/Yuras/repos", + "events_url": "https://api.github.com/users/Yuras/events{/privacy}", + "received_events_url": "https://api.github.com/users/Yuras/received_events", + "type": "User", + "site_admin": false + }, + "labels": [ + + ], + "state": "open", + "locked": false, + "assignee": null, + "assignees": [ + + ], + "milestone": null, + "comments": 4, + "created_at": "2020-04-04T11:05:26Z", + "updated_at": "2020-04-06T11:04:41Z", + "closed_at": null, + "author_association": "CONTRIBUTOR", + "pull_request": { + "url": "https://api.github.com/repos/bos/aeson/pulls/768", + "html_url": "https://github.com/bos/aeson/pull/768", + "diff_url": "https://github.com/bos/aeson/pull/768.diff", + "patch_url": "https://github.com/bos/aeson/pull/768.patch" + }, + "body": "This PR replaces `attoparsec` with non-backtracking parser `scanner`, which improves performance by 20%-40% (see the benchmark results below.) It's WIP yet, I'd like to hear people's opinion on that.\r\n\r\n# Issues\r\n\r\nThere are two main issues with this change:\r\n\r\n## Backward compatibility\r\n\r\nSince `aeson` exposes `attoparsec` parses from `Data.Aeson.Parser` module, replacing implementation will affect the API.\r\n\r\nThe possible solution is to convert parser based on `scanner` to one based on `attoparsec` using `toAtto` combinator from [here](https://github.com/Yuras/scanner-attoparsec/commit/f7fff690f2e565d94005c26320bcb742d4efc22b#diff-61024a57a5b895c8501edc2950c22cf7R30). It requires [this PR](https://github.com/bos/attoparsec/pull/165) to be merged though. Note that `toAtto` preserves the speedup, i.e. parser implemented using `scanner` and then converted to `attoparsec` is still faster then one written directly in `attoparsec`.\r\n\r\nAlternatively we can expose both implementations for some period of time.\r\n\r\n## Error messages\r\n\r\nThe error messages from the new parser lacks context. Here is a fragment of the output from the `ErrorMessages` test case:\r\n\r\n```\r\n --- Error in $: not enough input. Expecting ':'\r\n --- Error in $: not enough input. Expecting object value\r\n --- Error in $: not enough input. Expecting ',' or '}'\r\n +++ Error in $: No more input\r\n +++ Error in $: unexpected end of input\r\n +++ Error in $: No more input\r\n```\r\n\r\nThe reason is that `scanner` doesn't have a combinator similar to `` from `attoparsec`. It's possible to add it, but it affects performance negatively.\r\n\r\nNote that the error messages from `attoparsec` doesn't contain the error location, it makes them less useful. With `scanner` with [can add error location](https://github.com/Yuras/scanner/pull/12) to the error messages, it will make errors more useful.\r\n\r\n# Benchmarks\r\n\r\nI used the bench-parse.py for benchmarking. Here are the results on my computer. Before:\r\n\r\n```\r\n json-data/twitter1.json :: 60000 times\r\n 0.626 seconds, 95806 parses/sec, 78.120 MB/sec\r\n json-data/twitter1.json :: 60000 times\r\n 0.599 seconds, 100216 parses/sec, 81.716 MB/sec\r\n json-data/twitter1.json :: 60000 times\r\n 0.614 seconds, 97689 parses/sec, 79.655 MB/sec\r\n0.8 KB: 100217 msg\\/sec (81.7 MB\\/sec)\r\n json-data/twitter10.json :: 13000 times\r\n 0.636 seconds, 20430 parses/sec, 128.477 MB/sec\r\n json-data/twitter10.json :: 13000 times\r\n 0.624 seconds, 20830 parses/sec, 130.995 MB/sec\r\n json-data/twitter10.json :: 13000 times\r\n 0.637 seconds, 20412 parses/sec, 128.364 MB/sec\r\n6.4 KB: 20831 msg\\/sec (131.0 MB\\/sec)\r\n json-data/twitter20.json :: 7500 times\r\n 0.763 seconds, 9823 parses/sec, 113.058 MB/sec\r\n json-data/twitter20.json :: 7500 times\r\n 0.742 seconds, 10105 parses/sec, 116.303 MB/sec\r\n json-data/twitter20.json :: 7500 times\r\n 0.742 seconds, 10103 parses/sec, 116.280 MB/sec\r\n11.8 KB: 10105 msg\\/sec (116.3 MB\\/sec)\r\n json-data/twitter50.json :: 2500 times\r\n 0.699 seconds, 3575 parses/sec, 108.937 MB/sec\r\n json-data/twitter50.json :: 2500 times\r\n 0.703 seconds, 3554 parses/sec, 108.313 MB/sec\r\n json-data/twitter50.json :: 2500 times\r\n 0.706 seconds, 3540 parses/sec, 107.879 MB/sec\r\n31.2 KB: 3575 msg\\/sec (108.9 MB\\/sec)\r\n json-data/twitter100.json :: 1000 times\r\n 0.662 seconds, 1509 parses/sec, 90.703 MB/sec\r\n json-data/twitter100.json :: 1000 times\r\n 0.679 seconds, 1473 parses/sec, 88.514 MB/sec\r\n json-data/twitter100.json :: 1000 times\r\n 0.653 seconds, 1530 parses/sec, 91.961 MB/sec\r\n61.5 KB: 1531 msg\\/sec (92.0 MB\\/sec)\r\n json-data/jp10.json :: 4000 times\r\n 0.592 seconds, 6756 parses/sec, 96.536 MB/sec\r\n json-data/jp10.json :: 4000 times\r\n 0.600 seconds, 6661 parses/sec, 95.192 MB/sec\r\n json-data/jp10.json :: 4000 times\r\n 0.597 seconds, 6702 parses/sec, 95.772 MB/sec\r\n14.6 KB: 6756 msg\\/sec (96.5 MB\\/sec)\r\n json-data/jp50.json :: 1200 times\r\n 0.644 seconds, 1862 parses/sec, 80.163 MB/sec\r\n json-data/jp50.json :: 1200 times\r\n 0.627 seconds, 1914 parses/sec, 82.409 MB/sec\r\n json-data/jp50.json :: 1200 times\r\n 0.646 seconds, 1858 parses/sec, 80.009 MB/sec\r\n44.1 KB: 1914 msg\\/sec (82.4 MB\\/sec)\r\n json-data/jp100.json :: 700 times\r\n 0.743 seconds, 941 parses/sec, 76.231 MB/sec\r\n json-data/jp100.json :: 700 times\r\n 0.745 seconds, 939 parses/sec, 76.063 MB/sec\r\n json-data/jp100.json :: 700 times\r\n 0.747 seconds, 937 parses/sec, 75.874 MB/sec\r\n82.9 KB: 942 msg\\/sec (76.2 MB\\/sec)\r\n```\r\n\r\nAfter:\r\n\r\n```\r\n json-data/twitter1.json :: 60000 times\r\n 0.488 seconds, 122874 parses/sec, 100.190 MB/sec\r\n json-data/twitter1.json :: 60000 times\r\n 0.480 seconds, 125054 parses/sec, 101.969 MB/sec\r\n json-data/twitter1.json :: 60000 times\r\n 0.478 seconds, 125445 parses/sec, 102.287 MB/sec\r\n0.8 KB: 125445 msg\\/sec (102.3 MB\\/sec)\r\n json-data/twitter10.json :: 13000 times\r\n 0.459 seconds, 28311 parses/sec, 178.035 MB/sec\r\n json-data/twitter10.json :: 13000 times\r\n 0.466 seconds, 27877 parses/sec, 175.307 MB/sec\r\n json-data/twitter10.json :: 13000 times\r\n 0.462 seconds, 28159 parses/sec, 177.084 MB/sec\r\n6.4 KB: 28311 msg\\/sec (178.0 MB\\/sec)\r\n json-data/twitter20.json :: 7500 times\r\n 0.533 seconds, 14079 parses/sec, 162.038 MB/sec\r\n json-data/twitter20.json :: 7500 times\r\n 0.527 seconds, 14239 parses/sec, 163.882 MB/sec\r\n json-data/twitter20.json :: 7500 times\r\n 0.526 seconds, 14248 parses/sec, 163.981 MB/sec\r\n11.8 KB: 14248 msg\\/sec (164.0 MB\\/sec)\r\n json-data/twitter50.json :: 2500 times\r\n 0.498 seconds, 5019 parses/sec, 152.932 MB/sec\r\n json-data/twitter50.json :: 2500 times\r\n 0.492 seconds, 5076 parses/sec, 154.690 MB/sec\r\n json-data/twitter50.json :: 2500 times\r\n 0.496 seconds, 5035 parses/sec, 153.441 MB/sec\r\n31.2 KB: 5077 msg\\/sec (154.7 MB\\/sec)\r\n json-data/twitter100.json :: 1000 times\r\n 0.464 seconds, 2153 parses/sec, 129.369 MB/sec\r\n json-data/twitter100.json :: 1000 times\r\n 0.463 seconds, 2158 parses/sec, 129.672 MB/sec\r\n json-data/twitter100.json :: 1000 times\r\n 0.463 seconds, 2158 parses/sec, 129.690 MB/sec\r\n61.5 KB: 2159 msg\\/sec (129.7 MB\\/sec)\r\n json-data/jp10.json :: 4000 times\r\n 0.512 seconds, 7811 parses/sec, 111.625 MB/sec\r\n json-data/jp10.json :: 4000 times\r\n 0.521 seconds, 7677 parses/sec, 109.707 MB/sec\r\n json-data/jp10.json :: 4000 times\r\n 0.509 seconds, 7855 parses/sec, 112.243 MB/sec\r\n14.6 KB: 7855 msg\\/sec (112.2 MB\\/sec)\r\n json-data/jp50.json :: 1200 times\r\n 0.519 seconds, 2313 parses/sec, 99.590 MB/sec\r\n json-data/jp50.json :: 1200 times\r\n 0.540 seconds, 2222 parses/sec, 95.687 MB/sec\r\n json-data/jp50.json :: 1200 times\r\n 0.522 seconds, 2299 parses/sec, 98.975 MB/sec\r\n44.1 KB: 2313 msg\\/sec (99.6 MB\\/sec)\r\n json-data/jp100.json :: 700 times\r\n 0.623 seconds, 1123 parses/sec, 90.915 MB/sec\r\n json-data/jp100.json :: 700 times\r\n 0.605 seconds, 1156 parses/sec, 93.613 MB/sec\r\n json-data/jp100.json :: 700 times\r\n 0.600 seconds, 1166 parses/sec, 94.408 MB/sec\r\n82.9 KB: 1166 msg\\/sec (94.4 MB\\/sec)\r\n```\r\n\r\n" + }, + { + "url": "https://api.github.com/repos/bos/aeson/issues/766", + "repository_url": "https://api.github.com/repos/bos/aeson", + "labels_url": "https://api.github.com/repos/bos/aeson/issues/766/labels{/name}", + "comments_url": "https://api.github.com/repos/bos/aeson/issues/766/comments", + "events_url": "https://api.github.com/repos/bos/aeson/issues/766/events", + "html_url": "https://github.com/bos/aeson/issues/766", + "id": 593293818, + "node_id": "MDU6SXNzdWU1OTMyOTM4MTg=", + "number": 766, + "title": "Cleanup benchmarks", + "user": { + "login": "phadej", + "id": 51087, + "node_id": "MDQ6VXNlcjUxMDg3", + "avatar_url": "https://avatars2.githubusercontent.com/u/51087?v=4", + "gravatar_id": "", + "url": "https://api.github.com/users/phadej", + "html_url": "https://github.com/phadej", + "followers_url": "https://api.github.com/users/phadej/followers", + "following_url": "https://api.github.com/users/phadej/following{/other_user}", + "gists_url": "https://api.github.com/users/phadej/gists{/gist_id}", + "starred_url": "https://api.github.com/users/phadej/starred{/owner}{/repo}", + "subscriptions_url": "https://api.github.com/users/phadej/subscriptions", + "organizations_url": "https://api.github.com/users/phadej/orgs", + "repos_url": "https://api.github.com/users/phadej/repos", + "events_url": "https://api.github.com/users/phadej/events{/privacy}", + "received_events_url": "https://api.github.com/users/phadej/received_events", + "type": "User", + "site_admin": false + }, + "labels": [ + + ], + "state": "open", + "locked": false, + "assignee": null, + "assignees": [ + + ], + "milestone": null, + "comments": 0, + "created_at": "2020-04-03T10:49:30Z", + "updated_at": "2020-04-03T10:49:30Z", + "closed_at": null, + "author_association": "CONTRIBUTOR", + "body": "- Make `cabal.benchmarks.project` without `aeson` library. This would allow to not recompile `criterion` all the time.\r\n- remove old python scripts\r\n- rather make a script which would allow comparing benchmarks using https://hackage.haskell.org/package/criterion-compare\r\n - that script could run all benchmarks and collect their results, we have plenty of benchmarks for special cases\r\n- Add more examples than just Twitter. for example\r\n - GitHub issues listing\r\n - https://openweathermap.org/api\r\n - Some NPM package's `package.json` and or Cabal's `plan.json`" + }, + { + "url": "https://api.github.com/repos/bos/aeson/issues/748", + "repository_url": "https://api.github.com/repos/bos/aeson", + "labels_url": "https://api.github.com/repos/bos/aeson/issues/748/labels{/name}", + "comments_url": "https://api.github.com/repos/bos/aeson/issues/748/comments", + "events_url": "https://api.github.com/repos/bos/aeson/issues/748/events", + "html_url": "https://github.com/bos/aeson/issues/748", + "id": 555921820, + "node_id": "MDU6SXNzdWU1NTU5MjE4MjA=", + "number": 748, + "title": "how to parse json with field of optional and variant type in Haskell?", + "user": { + "login": "chakpongchung", + "id": 8110904, + "node_id": "MDQ6VXNlcjgxMTA5MDQ=", + "avatar_url": "https://avatars0.githubusercontent.com/u/8110904?v=4", + "gravatar_id": "", + "url": "https://api.github.com/users/chakpongchung", + "html_url": "https://github.com/chakpongchung", + "followers_url": "https://api.github.com/users/chakpongchung/followers", + "following_url": "https://api.github.com/users/chakpongchung/following{/other_user}", + "gists_url": "https://api.github.com/users/chakpongchung/gists{/gist_id}", + "starred_url": "https://api.github.com/users/chakpongchung/starred{/owner}{/repo}", + "subscriptions_url": "https://api.github.com/users/chakpongchung/subscriptions", + "organizations_url": "https://api.github.com/users/chakpongchung/orgs", + "repos_url": "https://api.github.com/users/chakpongchung/repos", + "events_url": "https://api.github.com/users/chakpongchung/events{/privacy}", + "received_events_url": "https://api.github.com/users/chakpongchung/received_events", + "type": "User", + "site_admin": false + }, + "labels": [ + + ], + "state": "open", + "locked": false, + "assignee": null, + "assignees": [ + + ], + "milestone": null, + "comments": 0, + "created_at": "2020-01-28T00:52:43Z", + "updated_at": "2020-01-28T00:52:43Z", + "closed_at": null, + "author_association": "NONE", + "body": "https://stackoverflow.com/questions/59903779/how-to-parse-json-with-field-of-optional-and-variant-type-in-haskell\r\n\r\nI looked at the Twitter example in this repo. Is it a working example? If so, where can I find its corresponding json? Though I am not sure that twitter example cover the features needed to parse the full example(not the minimal) shown in the link above.\r\n\r\n" + }, + { + "url": "https://api.github.com/repos/bos/aeson/issues/747", + "repository_url": "https://api.github.com/repos/bos/aeson", + "labels_url": "https://api.github.com/repos/bos/aeson/issues/747/labels{/name}", + "comments_url": "https://api.github.com/repos/bos/aeson/issues/747/comments", + "events_url": "https://api.github.com/repos/bos/aeson/issues/747/events", + "html_url": "https://github.com/bos/aeson/issues/747", + "id": 552518278, + "node_id": "MDU6SXNzdWU1NTI1MTgyNzg=", + "number": 747, + "title": "Add a data type and `FromJSON` instance that retains the original JSON", + "user": { + "login": "TomMD", + "id": 137806, + "node_id": "MDQ6VXNlcjEzNzgwNg==", + "avatar_url": "https://avatars2.githubusercontent.com/u/137806?v=4", + "gravatar_id": "", + "url": "https://api.github.com/users/TomMD", + "html_url": "https://github.com/TomMD", + "followers_url": "https://api.github.com/users/TomMD/followers", + "following_url": "https://api.github.com/users/TomMD/following{/other_user}", + "gists_url": "https://api.github.com/users/TomMD/gists{/gist_id}", + "starred_url": "https://api.github.com/users/TomMD/starred{/owner}{/repo}", + "subscriptions_url": "https://api.github.com/users/TomMD/subscriptions", + "organizations_url": "https://api.github.com/users/TomMD/orgs", + "repos_url": "https://api.github.com/users/TomMD/repos", + "events_url": "https://api.github.com/users/TomMD/events{/privacy}", + "received_events_url": "https://api.github.com/users/TomMD/received_events", + "type": "User", + "site_admin": false + }, + "labels": [ + + ], + "state": "open", + "locked": false, + "assignee": null, + "assignees": [ + + ], + "milestone": null, + "comments": 2, + "created_at": "2020-01-20T21:34:42Z", + "updated_at": "2020-01-21T10:17:08Z", + "closed_at": null, + "author_association": "CONTRIBUTOR", + "body": "With many APIs the Haskell types and the real world get out of sync. Updating the types is time consuming and often requires human interaction (because of separate packages, maintainers). For example, the GitHub API has lots of nooks that aren't reflected in the quite-rich (and appreciated) github package. For these cases I find it helpful to have access to the raw JSON both for debugging and for supporting functionality until the next release.\r\n\r\nTo restate, having a type decoded from an Aeson Value does not negate the utility of having the original Aeson Value around. This is a common situation and to support it I propose we add a type and `FromJSON` instance of:\r\n\r\n```\r\nmodule M (RetainedJSON, retainedJSON, decodedJSON) where\r\ndata RetainedJSON a = RetainedJSON\r\n { retainedJSON :: Value\r\n , decodedJSON :: a\r\n }\r\n\r\ninstance FromJSON a => FromJSON (RetainedJSON a) where\r\n parseJSON x = RetainedJSON x <$> parseJSON x\r\n```\r\n\r\nAnd either omit the `ToJSON` instance or use the admittedly-controversial instance of:\r\n\r\n```\r\ninstance ToJSON (RetainedJSON a) where\r\n toJSON = pure . retainedJSON\r\n```\r\n\r\nI'm checking for strong opinions against this proposal before I make a PR. Anyone have thoughts?" + }, + { + "url": "https://api.github.com/repos/bos/aeson/issues/744", + "repository_url": "https://api.github.com/repos/bos/aeson", + "labels_url": "https://api.github.com/repos/bos/aeson/issues/744/labels{/name}", + "comments_url": "https://api.github.com/repos/bos/aeson/issues/744/comments", + "events_url": "https://api.github.com/repos/bos/aeson/issues/744/events", + "html_url": "https://github.com/bos/aeson/issues/744", + "id": 536970276, + "node_id": "MDU6SXNzdWU1MzY5NzAyNzY=", + "number": 744, + "title": "Decode null to ()", + "user": { + "login": "domenkozar", + "id": 126339, + "node_id": "MDQ6VXNlcjEyNjMzOQ==", + "avatar_url": "https://avatars2.githubusercontent.com/u/126339?v=4", + "gravatar_id": "", + "url": "https://api.github.com/users/domenkozar", + "html_url": "https://github.com/domenkozar", + "followers_url": "https://api.github.com/users/domenkozar/followers", + "following_url": "https://api.github.com/users/domenkozar/following{/other_user}", + "gists_url": "https://api.github.com/users/domenkozar/gists{/gist_id}", + "starred_url": "https://api.github.com/users/domenkozar/starred{/owner}{/repo}", + "subscriptions_url": "https://api.github.com/users/domenkozar/subscriptions", + "organizations_url": "https://api.github.com/users/domenkozar/orgs", + "repos_url": "https://api.github.com/users/domenkozar/repos", + "events_url": "https://api.github.com/users/domenkozar/events{/privacy}", + "received_events_url": "https://api.github.com/users/domenkozar/received_events", + "type": "User", + "site_admin": false + }, + "labels": [ + + ], + "state": "open", + "locked": false, + "assignee": null, + "assignees": [ + + ], + "milestone": null, + "comments": 3, + "created_at": "2019-12-12T13:13:33Z", + "updated_at": "2019-12-12T13:32:44Z", + "closed_at": null, + "author_association": "NONE", + "body": "Sometimes you always expect `null` in a certain field and it would be great if that could get decoded to `()`." + }, + { + "url": "https://api.github.com/repos/bos/aeson/issues/733", + "repository_url": "https://api.github.com/repos/bos/aeson", + "labels_url": "https://api.github.com/repos/bos/aeson/issues/733/labels{/name}", + "comments_url": "https://api.github.com/repos/bos/aeson/issues/733/comments", + "events_url": "https://api.github.com/repos/bos/aeson/issues/733/events", + "html_url": "https://github.com/bos/aeson/issues/733", + "id": 506387744, + "node_id": "MDU6SXNzdWU1MDYzODc3NDQ=", + "number": 733, + "title": "Development Workflow", + "user": { + "login": "gdevanla", + "id": 1274371, + "node_id": "MDQ6VXNlcjEyNzQzNzE=", + "avatar_url": "https://avatars0.githubusercontent.com/u/1274371?v=4", + "gravatar_id": "", + "url": "https://api.github.com/users/gdevanla", + "html_url": "https://github.com/gdevanla", + "followers_url": "https://api.github.com/users/gdevanla/followers", + "following_url": "https://api.github.com/users/gdevanla/following{/other_user}", + "gists_url": "https://api.github.com/users/gdevanla/gists{/gist_id}", + "starred_url": "https://api.github.com/users/gdevanla/starred{/owner}{/repo}", + "subscriptions_url": "https://api.github.com/users/gdevanla/subscriptions", + "organizations_url": "https://api.github.com/users/gdevanla/orgs", + "repos_url": "https://api.github.com/users/gdevanla/repos", + "events_url": "https://api.github.com/users/gdevanla/events{/privacy}", + "received_events_url": "https://api.github.com/users/gdevanla/received_events", + "type": "User", + "site_admin": false + }, + "labels": [ + + ], + "state": "open", + "locked": false, + "assignee": null, + "assignees": [ + + ], + "milestone": null, + "comments": 10, + "created_at": "2019-10-13T21:56:41Z", + "updated_at": "2019-10-16T13:35:35Z", + "closed_at": null, + "author_association": "CONTRIBUTOR", + "body": "One challenge I have had while making incremental changes to the code base was that running `stack build` or `stack test` takes a while. What is the workflow other contributors follow in these scenarios? \r\n\r\nAt the least, when I run `stack test`, I would like to have a way to just run specific tests or just tests within a particular scope. Currently, when I run `stack test`,a lot of time is spent in building libraries like `criterion` and 'statistics`. Is there a way to turn them off as needed.\r\n\r\nOverall, I would like to contribute to a document (assuming this is not there already) that describes a development workflow which other contributors could use. Can someone point me to any resources or share their workflow. I can create a document by compiling those." + }, + { + "url": "https://api.github.com/repos/bos/aeson/issues/724", + "repository_url": "https://api.github.com/repos/bos/aeson", + "labels_url": "https://api.github.com/repos/bos/aeson/issues/724/labels{/name}", + "comments_url": "https://api.github.com/repos/bos/aeson/issues/724/comments", + "events_url": "https://api.github.com/repos/bos/aeson/issues/724/events", + "html_url": "https://github.com/bos/aeson/issues/724", + "id": 482230210, + "node_id": "MDU6SXNzdWU0ODIyMzAyMTA=", + "number": 724, + "title": "Add default wrapper", + "user": { + "login": "treeowl", + "id": 1893117, + "node_id": "MDQ6VXNlcjE4OTMxMTc=", + "avatar_url": "https://avatars2.githubusercontent.com/u/1893117?v=4", + "gravatar_id": "", + "url": "https://api.github.com/users/treeowl", + "html_url": "https://github.com/treeowl", + "followers_url": "https://api.github.com/users/treeowl/followers", + "following_url": "https://api.github.com/users/treeowl/following{/other_user}", + "gists_url": "https://api.github.com/users/treeowl/gists{/gist_id}", + "starred_url": "https://api.github.com/users/treeowl/starred{/owner}{/repo}", + "subscriptions_url": "https://api.github.com/users/treeowl/subscriptions", + "organizations_url": "https://api.github.com/users/treeowl/orgs", + "repos_url": "https://api.github.com/users/treeowl/repos", + "events_url": "https://api.github.com/users/treeowl/events{/privacy}", + "received_events_url": "https://api.github.com/users/treeowl/received_events", + "type": "User", + "site_admin": false + }, + "labels": [ + + ], + "state": "open", + "locked": false, + "assignee": null, + "assignees": [ + + ], + "milestone": null, + "comments": 2, + "created_at": "2019-08-19T10:27:18Z", + "updated_at": "2019-09-04T19:54:59Z", + "closed_at": null, + "author_association": "NONE", + "body": "```haskell\r\nnewtype DefaultJSON a = DefaultJSON a\r\n\r\ninstance (Generic a, GToJSON Zero (Rep a), GToEncoding Zero (Rep a))\r\n => ToJSON (DefaultJSON a) where\r\n toJSON (DefaultJSON a) = genericToJSON defaultOptions a\r\n toEncoding (DefaultJSON a) = genericToEncoding defaultOptions a\r\n\r\ninstance (Generic a, GFromJSON Zero (Rep a)) => FromJSON (DefaultJSON a) where\r\n parseJSON x = DefaultJSON <$> genericParseJSON defaultOptions x\r\n```\r\n\r\nThis can be used with `DerivingVia`:\r\n\r\n```haskell\r\ndata Message val = Message {val :: val, teamId :: Int, messageType :: Char}\r\n deriving Generic\r\n deriving (ToJSON, FromJSON) via DefaultJSON (Message val)\r\n```\r\n\r\nThis is almost as easy as writing empty instances, but it includes the `toEncoding` optimization for `ToJSON`." + }, + { + "url": "https://api.github.com/repos/bos/aeson/issues/720", + "repository_url": "https://api.github.com/repos/bos/aeson", + "labels_url": "https://api.github.com/repos/bos/aeson/issues/720/labels{/name}", + "comments_url": "https://api.github.com/repos/bos/aeson/issues/720/comments", + "events_url": "https://api.github.com/repos/bos/aeson/issues/720/events", + "html_url": "https://github.com/bos/aeson/issues/720", + "id": 473768871, + "node_id": "MDU6SXNzdWU0NzM3Njg4NzE=", + "number": 720, + "title": "Unexpected behaviour with Maybe typed fields and UntaggedValue", + "user": { + "login": "edwardb96", + "id": 8405233, + "node_id": "MDQ6VXNlcjg0MDUyMzM=", + "avatar_url": "https://avatars3.githubusercontent.com/u/8405233?v=4", + "gravatar_id": "", + "url": "https://api.github.com/users/edwardb96", + "html_url": "https://github.com/edwardb96", + "followers_url": "https://api.github.com/users/edwardb96/followers", + "following_url": "https://api.github.com/users/edwardb96/following{/other_user}", + "gists_url": "https://api.github.com/users/edwardb96/gists{/gist_id}", + "starred_url": "https://api.github.com/users/edwardb96/starred{/owner}{/repo}", + "subscriptions_url": "https://api.github.com/users/edwardb96/subscriptions", + "organizations_url": "https://api.github.com/users/edwardb96/orgs", + "repos_url": "https://api.github.com/users/edwardb96/repos", + "events_url": "https://api.github.com/users/edwardb96/events{/privacy}", + "received_events_url": "https://api.github.com/users/edwardb96/received_events", + "type": "User", + "site_admin": false + }, + "labels": [ + + ], + "state": "open", + "locked": false, + "assignee": null, + "assignees": [ + + ], + "milestone": null, + "comments": 1, + "created_at": "2019-07-28T17:49:45Z", + "updated_at": "2019-07-28T19:41:21Z", + "closed_at": null, + "author_association": "NONE", + "body": "I'm not sure if this is a bug or a feature so I thought I'd check. Here is a minimal working example.\r\n\r\n```haskell\r\n{-# LANGUAGE TemplateHaskell, OverloadedStrings #-}\r\nimport Data.Aeson\r\nimport Data.Aeson.TH\r\n\r\ndata Fruit = Apple { a :: Integer, b :: Maybe Bool }\r\n | Banana { a :: Integer }\r\n deriving Show\r\n$(deriveJSON defaultOptions { sumEncoding = UntaggedValue } 'Apple)\r\n\r\nmain :: IO ()\r\nmain = \r\n do\r\n putStrLn $ show (decode \"{ \\\"a\\\": 10 }\" :: Maybe Fruit) \r\n -- Expected Just (Banana {a = 10}), got Just (Apple {a = 10, b = Nothing})\r\n putStrLn $ show (decode \"{ \\\"a\\\": 10, \\\"b\\\": true }\" :: Maybe Fruit) \r\n -- Should be and got Just (Apple {a = 10, b = Just True}) \r\n\r\n```\r\n\r\nSince the `omitNothingFields` is `False` by default, and when it is false `Nothing`s are encoded as `null` (rather than omitted). I'd expect `{ \"a\": 10 }` to decode as a `Banana`.\r\n\r\nLikewise when `omitNothingFields` is false I'd expect to get `Nothing` for the following example.\r\n\r\n```haskell \r\n{-# LANGUAGE TemplateHaskell, OverloadedStrings #-}\r\nimport Data.Aeson\r\nimport Data.Aeson.TH\r\n\r\ndata Fruit = Apple { a :: Integer, b :: Maybe Bool }\r\n deriving Show\r\n$(deriveJSON defaultOptions 'Apple)\r\n\r\nmain :: IO ()\r\nmain = \r\n do\r\n putStrLn $ show (decode \"{ \\\"a\\\": 10 }\" :: Maybe Fruit) -- Expected Nothing, got (Apple { a = 10, b = Nothing})\r\n```\r\nI expect this is a design choice rather than a bug, If this is the case perhaps it could be documented more clearly or highlighted in the documentation for `UntaggedValue` e.g.\r\n\r\n> Note: Since omitted `Maybe` typed fields decode to `Nothing`, the set of non-maybe fields from each constructor should be disjoint. \r\n\r\nIf this is indeed a bug, I have hacked together a [patch](https://gist.github.com/edwardb96/aa9cefde626a5141b2cf28ce3c1a7962) for my own purposes but would be happy to tidy it up and turn it into a PR." + }, + { + "url": "https://api.github.com/repos/bos/aeson/issues/704", + "repository_url": "https://api.github.com/repos/bos/aeson", + "labels_url": "https://api.github.com/repos/bos/aeson/issues/704/labels{/name}", + "comments_url": "https://api.github.com/repos/bos/aeson/issues/704/comments", + "events_url": "https://api.github.com/repos/bos/aeson/issues/704/events", + "html_url": "https://github.com/bos/aeson/issues/704", + "id": 449409556, + "node_id": "MDU6SXNzdWU0NDk0MDk1NTY=", + "number": 704, + "title": "Ord instance for Value?", + "user": { + "login": "Gabriel439", + "id": 1313787, + "node_id": "MDQ6VXNlcjEzMTM3ODc=", + "avatar_url": "https://avatars3.githubusercontent.com/u/1313787?v=4", + "gravatar_id": "", + "url": "https://api.github.com/users/Gabriel439", + "html_url": "https://github.com/Gabriel439", + "followers_url": "https://api.github.com/users/Gabriel439/followers", + "following_url": "https://api.github.com/users/Gabriel439/following{/other_user}", + "gists_url": "https://api.github.com/users/Gabriel439/gists{/gist_id}", + "starred_url": "https://api.github.com/users/Gabriel439/starred{/owner}{/repo}", + "subscriptions_url": "https://api.github.com/users/Gabriel439/subscriptions", + "organizations_url": "https://api.github.com/users/Gabriel439/orgs", + "repos_url": "https://api.github.com/users/Gabriel439/repos", + "events_url": "https://api.github.com/users/Gabriel439/events{/privacy}", + "received_events_url": "https://api.github.com/users/Gabriel439/received_events", + "type": "User", + "site_admin": false + }, + "labels": [ + + ], + "state": "open", + "locked": false, + "assignee": null, + "assignees": [ + + ], + "milestone": null, + "comments": 17, + "created_at": "2019-05-28T18:16:49Z", + "updated_at": "2019-12-06T17:01:40Z", + "closed_at": null, + "author_association": "NONE", + "body": "I could add an `Ord` instance for `Value` if it would be welcome. The context for this to be able to store `Value`s inside of a `Set`" + }, + { + "url": "https://api.github.com/repos/bos/aeson/issues/700", + "repository_url": "https://api.github.com/repos/bos/aeson", + "labels_url": "https://api.github.com/repos/bos/aeson/issues/700/labels{/name}", + "comments_url": "https://api.github.com/repos/bos/aeson/issues/700/comments", + "events_url": "https://api.github.com/repos/bos/aeson/issues/700/events", + "html_url": "https://github.com/bos/aeson/issues/700", + "id": 443832632, + "node_id": "MDU6SXNzdWU0NDM4MzI2MzI=", + "number": 700, + "title": "Expose GToJSON", + "user": { + "login": "LukaHorvat", + "id": 370627, + "node_id": "MDQ6VXNlcjM3MDYyNw==", + "avatar_url": "https://avatars0.githubusercontent.com/u/370627?v=4", + "gravatar_id": "", + "url": "https://api.github.com/users/LukaHorvat", + "html_url": "https://github.com/LukaHorvat", + "followers_url": "https://api.github.com/users/LukaHorvat/followers", + "following_url": "https://api.github.com/users/LukaHorvat/following{/other_user}", + "gists_url": "https://api.github.com/users/LukaHorvat/gists{/gist_id}", + "starred_url": "https://api.github.com/users/LukaHorvat/starred{/owner}{/repo}", + "subscriptions_url": "https://api.github.com/users/LukaHorvat/subscriptions", + "organizations_url": "https://api.github.com/users/LukaHorvat/orgs", + "repos_url": "https://api.github.com/users/LukaHorvat/repos", + "events_url": "https://api.github.com/users/LukaHorvat/events{/privacy}", + "received_events_url": "https://api.github.com/users/LukaHorvat/received_events", + "type": "User", + "site_admin": false + }, + "labels": [ + + ], + "state": "open", + "locked": false, + "assignee": null, + "assignees": [ + + ], + "milestone": null, + "comments": 6, + "created_at": "2019-05-14T10:21:04Z", + "updated_at": "2019-07-28T22:56:05Z", + "closed_at": null, + "author_association": "NONE", + "body": "Currently, only `GFromJSON` is exposed. `GToJSON` is only exposed via the two type synonyms which means that I can't write custom instances for that class. My use case is that I have a type (`data Unset = Unset`) that I want to use for some fields in a record and I want those fields to be dropped from the JSON representation of that record. If `GToJSON` was exposed, I could just duplicate the trick used for `Maybe`. \r\n\r\nSince `GFromJSON` is already exposed, this already has a precedent." + }, + { + "url": "https://api.github.com/repos/bos/aeson/issues/694", + "repository_url": "https://api.github.com/repos/bos/aeson", + "labels_url": "https://api.github.com/repos/bos/aeson/issues/694/labels{/name}", + "comments_url": "https://api.github.com/repos/bos/aeson/issues/694/comments", + "events_url": "https://api.github.com/repos/bos/aeson/issues/694/events", + "html_url": "https://github.com/bos/aeson/pull/694", + "id": 433347757, + "node_id": "MDExOlB1bGxSZXF1ZXN0MjcwNTY4NzM5", + "number": 694, + "title": "Export isEmptyArray from Data.Aeson.Types", + "user": { + "login": "callummance", + "id": 4654774, + "node_id": "MDQ6VXNlcjQ2NTQ3NzQ=", + "avatar_url": "https://avatars1.githubusercontent.com/u/4654774?v=4", + "gravatar_id": "", + "url": "https://api.github.com/users/callummance", + "html_url": "https://github.com/callummance", + "followers_url": "https://api.github.com/users/callummance/followers", + "following_url": "https://api.github.com/users/callummance/following{/other_user}", + "gists_url": "https://api.github.com/users/callummance/gists{/gist_id}", + "starred_url": "https://api.github.com/users/callummance/starred{/owner}{/repo}", + "subscriptions_url": "https://api.github.com/users/callummance/subscriptions", + "organizations_url": "https://api.github.com/users/callummance/orgs", + "repos_url": "https://api.github.com/users/callummance/repos", + "events_url": "https://api.github.com/users/callummance/events{/privacy}", + "received_events_url": "https://api.github.com/users/callummance/received_events", + "type": "User", + "site_admin": false + }, + "labels": [ + + ], + "state": "open", + "locked": false, + "assignee": null, + "assignees": [ + + ], + "milestone": null, + "comments": 1, + "created_at": "2019-04-15T15:32:42Z", + "updated_at": "2019-04-23T16:05:39Z", + "closed_at": null, + "author_association": "NONE", + "pull_request": { + "url": "https://api.github.com/repos/bos/aeson/pulls/694", + "html_url": "https://github.com/bos/aeson/pull/694", + "diff_url": "https://github.com/bos/aeson/pull/694.diff", + "patch_url": "https://github.com/bos/aeson/pull/694.patch" + }, + "body": "Export `isEmptyArray` found in Data.Aeson.Types.Internal from Data.Aeson.Types. " + }, + { + "url": "https://api.github.com/repos/bos/aeson/issues/693", + "repository_url": "https://api.github.com/repos/bos/aeson", + "labels_url": "https://api.github.com/repos/bos/aeson/issues/693/labels{/name}", + "comments_url": "https://api.github.com/repos/bos/aeson/issues/693/comments", + "events_url": "https://api.github.com/repos/bos/aeson/issues/693/events", + "html_url": "https://github.com/bos/aeson/issues/693", + "id": 428959371, + "node_id": "MDU6SXNzdWU0Mjg5NTkzNzE=", + "number": 693, + "title": "Committed choice for parsing Objects", + "user": { + "login": "robrix", + "id": 59671, + "node_id": "MDQ6VXNlcjU5Njcx", + "avatar_url": "https://avatars0.githubusercontent.com/u/59671?v=4", + "gravatar_id": "", + "url": "https://api.github.com/users/robrix", + "html_url": "https://github.com/robrix", + "followers_url": "https://api.github.com/users/robrix/followers", + "following_url": "https://api.github.com/users/robrix/following{/other_user}", + "gists_url": "https://api.github.com/users/robrix/gists{/gist_id}", + "starred_url": "https://api.github.com/users/robrix/starred{/owner}{/repo}", + "subscriptions_url": "https://api.github.com/users/robrix/subscriptions", + "organizations_url": "https://api.github.com/users/robrix/orgs", + "repos_url": "https://api.github.com/users/robrix/repos", + "events_url": "https://api.github.com/users/robrix/events{/privacy}", + "received_events_url": "https://api.github.com/users/robrix/received_events", + "type": "User", + "site_admin": true + }, + "labels": [ + + ], + "state": "open", + "locked": false, + "assignee": null, + "assignees": [ + + ], + "milestone": null, + "comments": 1, + "created_at": "2019-04-03T20:27:00Z", + "updated_at": "2019-04-03T22:47:59Z", + "closed_at": null, + "author_association": "NONE", + "body": "Is there an idiomatic way to do committed choice when parsing an `Object`? E.g. we are parsing a structure which always has fields `a` and `b`, and may have `c`, `d`, or neither. Our naïve parser looks something like:\r\n\r\n```haskell\r\nparseJSON (Object v) = do\r\n a <- v .: \"a\"\r\n b <- v .: \"b\"\r\n C a b <$> v .: \"c\" <|> D a b <$> v .: \"d\" <|> pure (E a b)\r\n```\r\n\r\nUnfortunately, if parsing the values in `c` or `d` fails, we’ll silently discard the failures and fall back to the `E` case. Instead, we’d like to commit to parsing a `C` as soon as we see the `c` key, or a `D` as soon as we see the `d` key, and only parse the `E` if neither key exists.\r\n\r\nIn `trifecta` (for example), choices are committed by default, and can only be backtracked past with `try`; but there doesn’t seem to be an inverse `commit` operator in `aeson` (at least, not that I’ve found thus far). Our current approach is therefore agonizingly manual:\r\n\r\n```haskell\r\nparseJSON (Object v) = do\r\n a <- v .: \"a\"\r\n b <- v .: \"b\"\r\n c <- v .:? \"c\"\r\n case c of\r\n Just c -> pure (C a b c)\r\n Nothing -> do\r\n d <- v .:? \"d\"\r\n case d of\r\n Just d -> pure (D a b d)\r\n Nothing -> pure (E a b)\r\n```\r\n\r\nIs there a better way to implement this sort of choice?\r\n\r\ncc @aymannadeem" + }, + { + "url": "https://api.github.com/repos/bos/aeson/issues/687", + "repository_url": "https://api.github.com/repos/bos/aeson", + "labels_url": "https://api.github.com/repos/bos/aeson/issues/687/labels{/name}", + "comments_url": "https://api.github.com/repos/bos/aeson/issues/687/comments", + "events_url": "https://api.github.com/repos/bos/aeson/issues/687/events", + "html_url": "https://github.com/bos/aeson/issues/687", + "id": 417900732, + "node_id": "MDU6SXNzdWU0MTc5MDA3MzI=", + "number": 687, + "title": "Derived ToJSON1 instance does not respect omitNothingFields = True", + "user": { + "login": "ejconlon", + "id": 37287, + "node_id": "MDQ6VXNlcjM3Mjg3", + "avatar_url": "https://avatars2.githubusercontent.com/u/37287?v=4", + "gravatar_id": "", + "url": "https://api.github.com/users/ejconlon", + "html_url": "https://github.com/ejconlon", + "followers_url": "https://api.github.com/users/ejconlon/followers", + "following_url": "https://api.github.com/users/ejconlon/following{/other_user}", + "gists_url": "https://api.github.com/users/ejconlon/gists{/gist_id}", + "starred_url": "https://api.github.com/users/ejconlon/starred{/owner}{/repo}", + "subscriptions_url": "https://api.github.com/users/ejconlon/subscriptions", + "organizations_url": "https://api.github.com/users/ejconlon/orgs", + "repos_url": "https://api.github.com/users/ejconlon/repos", + "events_url": "https://api.github.com/users/ejconlon/events{/privacy}", + "received_events_url": "https://api.github.com/users/ejconlon/received_events", + "type": "User", + "site_admin": false + }, + "labels": [ + + ], + "state": "open", + "locked": false, + "assignee": null, + "assignees": [ + + ], + "milestone": null, + "comments": 8, + "created_at": "2019-03-06T16:38:45Z", + "updated_at": "2019-03-14T11:43:13Z", + "closed_at": null, + "author_association": "NONE", + "body": "For an instance\r\n\r\n```\r\ndata C a = C { required :: a, optional :: Maybe a }\r\n deriving (Eq, Show, Generic1)\r\n deriving (ToJSON1) via (AesonWrapper1 C)\r\n```\r\n\r\nwith a simple deriving via newtype wrapper `AesonWrapper1` I am seeing the value `C 1 Nothing` serialize with `null`\r\n\r\n```\r\n Example test case: FAIL\r\n Repro.hs:77:\r\n expected: \"{\\\"required\\\":1}\"\r\n but got: \"{\\\"required\\\":1,\\\"optional\\\":null}\"\r\n```\r\n\r\nSee https://gist.github.com/ejconlon/30dc50b183a0f72501c3e49ce57cae52 for a self-contained repro." + }, + { + "url": "https://api.github.com/repos/bos/aeson/issues/685", + "repository_url": "https://api.github.com/repos/bos/aeson", + "labels_url": "https://api.github.com/repos/bos/aeson/issues/685/labels{/name}", + "comments_url": "https://api.github.com/repos/bos/aeson/issues/685/comments", + "events_url": "https://api.github.com/repos/bos/aeson/issues/685/events", + "html_url": "https://github.com/bos/aeson/issues/685", + "id": 408401800, + "node_id": "MDU6SXNzdWU0MDg0MDE4MDA=", + "number": 685, + "title": "Feature request: a function to run Parser without pass-through", + "user": { + "login": "fumieval", + "id": 761865, + "node_id": "MDQ6VXNlcjc2MTg2NQ==", + "avatar_url": "https://avatars0.githubusercontent.com/u/761865?v=4", + "gravatar_id": "", + "url": "https://api.github.com/users/fumieval", + "html_url": "https://github.com/fumieval", + "followers_url": "https://api.github.com/users/fumieval/followers", + "following_url": "https://api.github.com/users/fumieval/following{/other_user}", + "gists_url": "https://api.github.com/users/fumieval/gists{/gist_id}", + "starred_url": "https://api.github.com/users/fumieval/starred{/owner}{/repo}", + "subscriptions_url": "https://api.github.com/users/fumieval/subscriptions", + "organizations_url": "https://api.github.com/users/fumieval/orgs", + "repos_url": "https://api.github.com/users/fumieval/repos", + "events_url": "https://api.github.com/users/fumieval/events{/privacy}", + "received_events_url": "https://api.github.com/users/fumieval/received_events", + "type": "User", + "site_admin": false + }, + "labels": [ + + ], + "state": "open", + "locked": false, + "assignee": null, + "assignees": [ + + ], + "milestone": null, + "comments": 1, + "created_at": "2019-02-09T05:45:49Z", + "updated_at": "2019-02-09T06:04:57Z", + "closed_at": null, + "author_association": "NONE", + "body": "I frequently end up writing `flip J.parseEither () $ const $ do ...`. The following function would be very useful:\r\n\r\n```haskell\r\nexecParser :: Parser a -> Either String a\r\nexecParser m = runParser m [] onError Right\r\n where onError path msg = Left (formatError path msg)\r\n```" + }, + { + "url": "https://api.github.com/repos/bos/aeson/issues/683", + "repository_url": "https://api.github.com/repos/bos/aeson", + "labels_url": "https://api.github.com/repos/bos/aeson/issues/683/labels{/name}", + "comments_url": "https://api.github.com/repos/bos/aeson/issues/683/comments", + "events_url": "https://api.github.com/repos/bos/aeson/issues/683/events", + "html_url": "https://github.com/bos/aeson/issues/683", + "id": 393410619, + "node_id": "MDU6SXNzdWUzOTM0MTA2MTk=", + "number": 683, + "title": "Custom error type", + "user": { + "login": "asheshambasta", + "id": 580365, + "node_id": "MDQ6VXNlcjU4MDM2NQ==", + "avatar_url": "https://avatars3.githubusercontent.com/u/580365?v=4", + "gravatar_id": "", + "url": "https://api.github.com/users/asheshambasta", + "html_url": "https://github.com/asheshambasta", + "followers_url": "https://api.github.com/users/asheshambasta/followers", + "following_url": "https://api.github.com/users/asheshambasta/following{/other_user}", + "gists_url": "https://api.github.com/users/asheshambasta/gists{/gist_id}", + "starred_url": "https://api.github.com/users/asheshambasta/starred{/owner}{/repo}", + "subscriptions_url": "https://api.github.com/users/asheshambasta/subscriptions", + "organizations_url": "https://api.github.com/users/asheshambasta/orgs", + "repos_url": "https://api.github.com/users/asheshambasta/repos", + "events_url": "https://api.github.com/users/asheshambasta/events{/privacy}", + "received_events_url": "https://api.github.com/users/asheshambasta/received_events", + "type": "User", + "site_admin": false + }, + "labels": [ + + ], + "state": "open", + "locked": false, + "assignee": null, + "assignees": [ + + ], + "milestone": null, + "comments": 6, + "created_at": "2018-12-21T10:38:51Z", + "updated_at": "2019-01-04T13:09:22Z", + "closed_at": null, + "author_association": "NONE", + "body": "We're using Haskell to write one of our services, and we're using Aeson for input-json parsing. \r\n\r\nHowever, the API of the platform as a whole _must_ expose standardised validation errors like my example:\r\n\r\n```javascript\r\n{\r\n \"errors\": [\r\n {\r\n \"code\": \"ERR.SOMEFIELD.INVALID\",\r\n \"field\": \"foo\",\r\n \"type\": \"field\",\r\n \"message\": \"Expecting an 'int' but got 'string'\"\r\n },\r\n {\r\n \"code\": \"ERR.PLAN.INVALID_NAME\",\r\n \"type\": \"field\",\r\n \"field\" : \"user.plan\", \r\n \"message\": \"All plan names must start with a 'urn:plan'\" // nullable \r\n }\r\n ],\r\n \"service\": \"SomeServiceIdentifier/version\"\r\n}\r\n```\r\nI see that in Aeson this is not possible, since the `Error` data constructor only uses `String` for its output errors. Also, my understanding is that accumulating JSON errors is achieved using `(<*>+)` which is quite cool. \r\n\r\nWhat I'd like to understand is how we achieve some sort of a custom error type that can be represented like the example above, if possible at all. The naive approach would be to use `fail` with some sort of standardized string and then parse the custom error fields out of it, but that is rather unsatisfactory. \r\n\r\nIs there a way to achieve this? \r\n\r\n#\r\n\r\nEdit: I'd like to contribute to this, but I'm quite new to Haskell. " + }, + { + "url": "https://api.github.com/repos/bos/aeson/issues/679", + "repository_url": "https://api.github.com/repos/bos/aeson", + "labels_url": "https://api.github.com/repos/bos/aeson/issues/679/labels{/name}", + "comments_url": "https://api.github.com/repos/bos/aeson/issues/679/comments", + "events_url": "https://api.github.com/repos/bos/aeson/issues/679/events", + "html_url": "https://github.com/bos/aeson/issues/679", + "id": 377974398, + "node_id": "MDU6SXNzdWUzNzc5NzQzOTg=", + "number": 679, + "title": "`FromJSON` and `ToJSON` don't roundtrip for `Double`", + "user": { + "login": "NorfairKing", + "id": 3521180, + "node_id": "MDQ6VXNlcjM1MjExODA=", + "avatar_url": "https://avatars3.githubusercontent.com/u/3521180?v=4", + "gravatar_id": "", + "url": "https://api.github.com/users/NorfairKing", + "html_url": "https://github.com/NorfairKing", + "followers_url": "https://api.github.com/users/NorfairKing/followers", + "following_url": "https://api.github.com/users/NorfairKing/following{/other_user}", + "gists_url": "https://api.github.com/users/NorfairKing/gists{/gist_id}", + "starred_url": "https://api.github.com/users/NorfairKing/starred{/owner}{/repo}", + "subscriptions_url": "https://api.github.com/users/NorfairKing/subscriptions", + "organizations_url": "https://api.github.com/users/NorfairKing/orgs", + "repos_url": "https://api.github.com/users/NorfairKing/repos", + "events_url": "https://api.github.com/users/NorfairKing/events{/privacy}", + "received_events_url": "https://api.github.com/users/NorfairKing/received_events", + "type": "User", + "site_admin": false + }, + "labels": [ + + ], + "state": "open", + "locked": false, + "assignee": null, + "assignees": [ + + ], + "milestone": null, + "comments": 7, + "created_at": "2018-11-06T18:20:53Z", + "updated_at": "2018-11-06T21:51:29Z", + "closed_at": null, + "author_association": "NONE", + "body": " ```\r\n1) Test.Validity.Aeson, JSON Double (unchecked), decode :: Data.ByteString.Lazy.ByteString -> Either String Double, ensures that encode and decode are inverses for \"unchecked Double\"'s\r\n Falsifiable (after 12 tests):\r\n Infinity\r\n Decoding succeeded, but the decoded value\r\n NaN\r\n differs from expected decoded value\r\n Infinity\r\n 'encode' encoded it to the json\r\n \"null\"\r\n```" + }, + { + "url": "https://api.github.com/repos/bos/aeson/issues/666", + "repository_url": "https://api.github.com/repos/bos/aeson", + "labels_url": "https://api.github.com/repos/bos/aeson/issues/666/labels{/name}", + "comments_url": "https://api.github.com/repos/bos/aeson/issues/666/comments", + "events_url": "https://api.github.com/repos/bos/aeson/issues/666/events", + "html_url": "https://github.com/bos/aeson/issues/666", + "id": 357916991, + "node_id": "MDU6SXNzdWUzNTc5MTY5OTE=", + "number": 666, + "title": "Add `withTypeableObject` that extracts name of the object from the type", + "user": { + "login": "chshersh", + "id": 4276606, + "node_id": "MDQ6VXNlcjQyNzY2MDY=", + "avatar_url": "https://avatars0.githubusercontent.com/u/4276606?v=4", + "gravatar_id": "", + "url": "https://api.github.com/users/chshersh", + "html_url": "https://github.com/chshersh", + "followers_url": "https://api.github.com/users/chshersh/followers", + "following_url": "https://api.github.com/users/chshersh/following{/other_user}", + "gists_url": "https://api.github.com/users/chshersh/gists{/gist_id}", + "starred_url": "https://api.github.com/users/chshersh/starred{/owner}{/repo}", + "subscriptions_url": "https://api.github.com/users/chshersh/subscriptions", + "organizations_url": "https://api.github.com/users/chshersh/orgs", + "repos_url": "https://api.github.com/users/chshersh/repos", + "events_url": "https://api.github.com/users/chshersh/events{/privacy}", + "received_events_url": "https://api.github.com/users/chshersh/received_events", + "type": "User", + "site_admin": false + }, + "labels": [ + + ], + "state": "open", + "locked": false, + "assignee": null, + "assignees": [ + + ], + "milestone": null, + "comments": 0, + "created_at": "2018-09-07T04:38:20Z", + "updated_at": "2018-09-07T04:38:20Z", + "closed_at": null, + "author_association": "NONE", + "body": "Usually when I have custom data type like this one:\r\n\r\n```haskell\r\ndata Foo = Foo\r\n { fooBar :: Int\r\n , fooBaz :: Double\r\n }\r\n```\r\n\r\nI write `FromJSON` instance like this:\r\n\r\n```haskell\r\ninstance FromJSON Foo where\r\n parseJSON = withObject \"Foo\" $ \\o -> ...\r\n```\r\n\r\nI need to specify name of the type to get good error messages. But if type name changes, I need to not forget to update this function. Also, it's not really convenient to write name of type each type. I propose to add the following function to the `aeson` library:\r\n\r\n```haskell\r\ntypeName :: forall a . Typeable a => Text\r\ntypeName = show $ typeRep $ Proxy @a\r\n\r\nwithTypeableObject :: forall a . Typeable a => (Object -> Parser a) -> Value -> Parser a\r\nwithTypeableObject = withObject (typeName @a)\r\n```" + }, + { + "url": "https://api.github.com/repos/bos/aeson/issues/660", + "repository_url": "https://api.github.com/repos/bos/aeson", + "labels_url": "https://api.github.com/repos/bos/aeson/issues/660/labels{/name}", + "comments_url": "https://api.github.com/repos/bos/aeson/issues/660/comments", + "events_url": "https://api.github.com/repos/bos/aeson/issues/660/events", + "html_url": "https://github.com/bos/aeson/issues/660", + "id": 348521320, + "node_id": "MDU6SXNzdWUzNDg1MjEzMjA=", + "number": 660, + "title": "Inconsistent encoding of Double depending on container structure", + "user": { + "login": "akhra", + "id": 3770453, + "node_id": "MDQ6VXNlcjM3NzA0NTM=", + "avatar_url": "https://avatars2.githubusercontent.com/u/3770453?v=4", + "gravatar_id": "", + "url": "https://api.github.com/users/akhra", + "html_url": "https://github.com/akhra", + "followers_url": "https://api.github.com/users/akhra/followers", + "following_url": "https://api.github.com/users/akhra/following{/other_user}", + "gists_url": "https://api.github.com/users/akhra/gists{/gist_id}", + "starred_url": "https://api.github.com/users/akhra/starred{/owner}{/repo}", + "subscriptions_url": "https://api.github.com/users/akhra/subscriptions", + "organizations_url": "https://api.github.com/users/akhra/orgs", + "repos_url": "https://api.github.com/users/akhra/repos", + "events_url": "https://api.github.com/users/akhra/events{/privacy}", + "received_events_url": "https://api.github.com/users/akhra/received_events", + "type": "User", + "site_admin": false + }, + "labels": [ + + ], + "state": "open", + "locked": false, + "assignee": null, + "assignees": [ + + ], + "milestone": null, + "comments": 3, + "created_at": "2018-08-07T23:24:53Z", + "updated_at": "2018-08-08T12:33:03Z", + "closed_at": null, + "author_association": "NONE", + "body": "This is closely related to #546. Initially I thought there was some oddness specific to derived instances, but [this comment](https://github.com/bos/aeson/issues/546#issuecomment-299991780) pointed me toward a nice trivial example of the underlying cause:\r\n```haskell\r\nλ. import Data.Aeson\r\nλ. encode 0.0\r\n\"0.0\"\r\nλ. encode $ toJSON 0.0\r\n\"0\"\r\n```\r\nAnd its consequence:\r\n```haskell\r\nλ. :set -XDeriveGeneric -XDeriveAnyClass -XDerivingStrategies -XGeneralizedNewtypeDeriving\r\nλ. newtype Foo = Foo Double deriving Generic\r\nλ. deriving newtype instance ToJSON Foo\r\nλ. encode $ Foo 0.0\r\n\"0.0\"\r\nλ. newtype Bar = Bar Double deriving Generic\r\nλ. deriving anyclass instance ToJSON Bar\r\nλ. encode $ Bar 0.0\r\n\"0\"\r\nλ. data Baz = Baz Double deriving (Generic, ToJSON)\r\nλ. encode $ Baz 0.0\r\n\"0\"\r\nλ. data Qux = Qux Foo deriving (Generic, ToJSON)\r\nλ. encode $ Qux (Foo 0.0)\r\n\"0\"\r\n```\r\nThat last one is especially irksome: checking the newtype encoding doesn't reflect what the full structure will look like. (And of course, that's exactly the context where I ran into this.)\r\n\r\nThis issue is specifically about the _inconsistency_. It is surprising and undesirable that `Double`s render differently depending on context. Which way they _should_ be rendered probably belongs to #546. However, I should add that at present it's not a clear-cut matter of `deriving newtype` being the odd one out:\r\n```haskell\r\nλ. encode (0.0, \"whoops\")\r\n\"[0.0,\\\"whoops\\\"]\"\r\n```" + }, + { + "url": "https://api.github.com/repos/bos/aeson/issues/659", + "repository_url": "https://api.github.com/repos/bos/aeson", + "labels_url": "https://api.github.com/repos/bos/aeson/issues/659/labels{/name}", + "comments_url": "https://api.github.com/repos/bos/aeson/issues/659/comments", + "events_url": "https://api.github.com/repos/bos/aeson/issues/659/events", + "html_url": "https://github.com/bos/aeson/issues/659", + "id": 348025769, + "node_id": "MDU6SXNzdWUzNDgwMjU3Njk=", + "number": 659, + "title": "FromJSONKeyCoerce warning", + "user": { + "login": "MaxGabriel", + "id": 1274145, + "node_id": "MDQ6VXNlcjEyNzQxNDU=", + "avatar_url": "https://avatars3.githubusercontent.com/u/1274145?v=4", + "gravatar_id": "", + "url": "https://api.github.com/users/MaxGabriel", + "html_url": "https://github.com/MaxGabriel", + "followers_url": "https://api.github.com/users/MaxGabriel/followers", + "following_url": "https://api.github.com/users/MaxGabriel/following{/other_user}", + "gists_url": "https://api.github.com/users/MaxGabriel/gists{/gist_id}", + "starred_url": "https://api.github.com/users/MaxGabriel/starred{/owner}{/repo}", + "subscriptions_url": "https://api.github.com/users/MaxGabriel/subscriptions", + "organizations_url": "https://api.github.com/users/MaxGabriel/orgs", + "repos_url": "https://api.github.com/users/MaxGabriel/repos", + "events_url": "https://api.github.com/users/MaxGabriel/events{/privacy}", + "received_events_url": "https://api.github.com/users/MaxGabriel/received_events", + "type": "User", + "site_admin": false + }, + "labels": [ + + ], + "state": "open", + "locked": false, + "assignee": null, + "assignees": [ + + ], + "milestone": { + "url": "https://api.github.com/repos/bos/aeson/milestones/21", + "html_url": "https://github.com/bos/aeson/milestone/21", + "labels_url": "https://api.github.com/repos/bos/aeson/milestones/21/labels", + "id": 5240808, + "node_id": "MDk6TWlsZXN0b25lNTI0MDgwOA==", + "number": 21, + "title": "v1.5.0.0", + "description": "", + "creator": { + "login": "bergmark", + "id": 100681, + "node_id": "MDQ6VXNlcjEwMDY4MQ==", + "avatar_url": "https://avatars2.githubusercontent.com/u/100681?v=4", + "gravatar_id": "", + "url": "https://api.github.com/users/bergmark", + "html_url": "https://github.com/bergmark", + "followers_url": "https://api.github.com/users/bergmark/followers", + "following_url": "https://api.github.com/users/bergmark/following{/other_user}", + "gists_url": "https://api.github.com/users/bergmark/gists{/gist_id}", + "starred_url": "https://api.github.com/users/bergmark/starred{/owner}{/repo}", + "subscriptions_url": "https://api.github.com/users/bergmark/subscriptions", + "organizations_url": "https://api.github.com/users/bergmark/orgs", + "repos_url": "https://api.github.com/users/bergmark/repos", + "events_url": "https://api.github.com/users/bergmark/events{/privacy}", + "received_events_url": "https://api.github.com/users/bergmark/received_events", + "type": "User", + "site_admin": false + }, + "open_issues": 1, + "closed_issues": 6, + "state": "open", + "created_at": "2020-03-26T15:59:09Z", + "updated_at": "2020-04-05T09:44:01Z", + "due_on": null, + "closed_at": null + }, + "comments": 1, + "created_at": "2018-08-06T18:02:56Z", + "updated_at": "2020-04-04T14:40:37Z", + "closed_at": null, + "author_association": "NONE", + "body": "Hi, I just installed aeson-1.4.0.0 and got this warning:\r\n\r\n```\r\nData/Aeson/Types/FromJSON.hs:468:3: warning: [-Winline-rule-shadowing]\r\n Rule \"FromJSONKeyCoerce: fmap id\" may never fire\r\n because ‘id’ might inline first\r\n Probable fix: add an INLINE[n] or NOINLINE[n] pragma for ‘id’\r\n |\r\n468 | \"FromJSONKeyCoerce: fmap id\" forall (x :: FromJSONKeyFunction a).\r\n |\r\n```\r\n\r\nIt's not causing me any problems, just wanted to let you know.\r\n\r\nLooks like the warning may have been around awhile since it appears here as well: https://github.com/bos/aeson/issues/543" + }, + { + "url": "https://api.github.com/repos/bos/aeson/issues/658", + "repository_url": "https://api.github.com/repos/bos/aeson", + "labels_url": "https://api.github.com/repos/bos/aeson/issues/658/labels{/name}", + "comments_url": "https://api.github.com/repos/bos/aeson/issues/658/comments", + "events_url": "https://api.github.com/repos/bos/aeson/issues/658/events", + "html_url": "https://github.com/bos/aeson/issues/658", + "id": 346293459, + "node_id": "MDU6SXNzdWUzNDYyOTM0NTk=", + "number": 658, + "title": "Make functions inlinable", + "user": { + "login": "flip111", + "id": 2244480, + "node_id": "MDQ6VXNlcjIyNDQ0ODA=", + "avatar_url": "https://avatars3.githubusercontent.com/u/2244480?v=4", + "gravatar_id": "", + "url": "https://api.github.com/users/flip111", + "html_url": "https://github.com/flip111", + "followers_url": "https://api.github.com/users/flip111/followers", + "following_url": "https://api.github.com/users/flip111/following{/other_user}", + "gists_url": "https://api.github.com/users/flip111/gists{/gist_id}", + "starred_url": "https://api.github.com/users/flip111/starred{/owner}{/repo}", + "subscriptions_url": "https://api.github.com/users/flip111/subscriptions", + "organizations_url": "https://api.github.com/users/flip111/orgs", + "repos_url": "https://api.github.com/users/flip111/repos", + "events_url": "https://api.github.com/users/flip111/events{/privacy}", + "received_events_url": "https://api.github.com/users/flip111/received_events", + "type": "User", + "site_admin": false + }, + "labels": [ + + ], + "state": "open", + "locked": false, + "assignee": null, + "assignees": [ + + ], + "milestone": null, + "comments": 2, + "created_at": "2018-07-31T17:49:10Z", + "updated_at": "2020-04-04T12:57:44Z", + "closed_at": null, + "author_association": "NONE", + "body": "When i compile with `-Wmissed-specialisations` actually indirectly by compiling with `-Weverything` i get the following warnings:\r\n\r\n```\r\nsrc/Main.hs: warning: \r\n Could not specialise imported function ‘aeson-1.3.1.1:Data.Aeson.Types.ToJSON.$w$ctoJSONKey’\r\n when specialising ‘aeson-1.3.1.1:Data.Aeson.Types.ToJSON.$fToJSONKey(,)_$ctoJSONKey’\r\n Probable fix: add INLINABLE pragma on ‘aeson-1.3.1.1:Data.Aeson.Types.ToJSON.$w$ctoJSONKey’\r\n\r\nsrc/Main.hs: warning: \r\n Could not specialise imported function ‘aeson-1.3.1.1:Data.Aeson.Types.ToJSON.$w$cgToJSON’\r\n when specialising ‘aeson-1.3.1.1:Data.Aeson.Types.ToJSON.$fGToJSONencarityM11_$cgToJSON’\r\n Probable fix: add INLINABLE pragma on ‘aeson-1.3.1.1:Data.Aeson.Types.ToJSON.$w$cgToJSON’\r\n \r\nsrc/Main.hs: warning: \r\n Could not specialise imported function ‘aeson-1.3.1.1:Data.Aeson.Types.ToJSON.$w$csumToJSON'2’\r\n when specialising ‘aeson-1.3.1.1:Data.Aeson.Types.ToJSON.$fSumToJSON'TYPETwoElemArrayValuearityM2’\r\n Probable fix: add INLINABLE pragma on ‘aeson-1.3.1.1:Data.Aeson.Types.ToJSON.$w$csumToJSON'2’\r\n \r\nsrc/Main.hs: warning: \r\n Could not specialise imported function ‘aeson-1.3.1.1:Data.Aeson.Types.ToJSON.$w$csumToJSON'’\r\n when specialising ‘aeson-1.3.1.1:Data.Aeson.Types.ToJSON.$fSumToJSON'TYPEObjectWithSingleFieldencarityM1_$csumToJSON'’\r\n Probable fix: add INLINABLE pragma on ‘aeson-1.3.1.1:Data.Aeson.Types.ToJSON.$w$csumToJSON'’\r\n \r\nsrc/Main.hs: warning: \r\n Could not specialise imported function ‘aeson-1.3.1.1:Data.Aeson.Types.ToJSON.$w$ctaggedObject’\r\n when specialising ‘aeson-1.3.1.1:Data.Aeson.Types.ToJSON.$fTaggedObjectencarityM1_$ctaggedObject’\r\n Probable fix: add INLINABLE pragma on ‘aeson-1.3.1.1:Data.Aeson.Types.ToJSON.$w$ctaggedObject’\r\n \r\nsrc/Main.hs: warning: \r\n Could not specialise imported function ‘aeson-1.3.1.1:Data.Aeson.Types.ToJSON.$fGToJSONValuearity:*:_$cgToJSON’\r\n Probable fix: add INLINABLE pragma on ‘aeson-1.3.1.1:Data.Aeson.Types.ToJSON.$fGToJSONValuearity:*:_$cgToJSON’\r\n \r\nsrc/Main.hs: warning: \r\n Could not specialise imported function ‘aeson-1.3.1.1:Data.Aeson.Types.ToJSON.$fKeyValuePairvDList_$cpair’\r\n when specialising ‘aeson-1.3.1.1:Data.Aeson.Types.ToJSON.$fKeyValuePairvDList’\r\n Probable fix: add INLINABLE pragma on ‘aeson-1.3.1.1:Data.Aeson.Types.ToJSON.$fKeyValuePairvDList_$cpair’\r\n \r\nsrc/Main.hs: warning: \r\n Could not specialise imported function ‘aeson-1.3.1.1:Data.Aeson.Types.ToJSON.$w$cwriteProduct’\r\n when specialising ‘aeson-1.3.1.1:Data.Aeson.Types.ToJSON.$fWriteProductarity:*:_$cwriteProduct’\r\n Probable fix: add INLINABLE pragma on ‘aeson-1.3.1.1:Data.Aeson.Types.ToJSON.$w$cwriteProduct’\r\n \r\nsrc/Main.hs: warning: \r\n Could not specialise imported function ‘aeson-1.3.1.1:Data.Aeson.Types.ToJSON.$w$cwriteProduct1’\r\n when specialising ‘aeson-1.3.1.1:Data.Aeson.Types.ToJSON.$fWriteProductaritya_$cwriteProduct’\r\n Probable fix: add INLINABLE pragma on ‘aeson-1.3.1.1:Data.Aeson.Types.ToJSON.$w$cwriteProduct1’\r\n \r\nsrc/Main.hs: warning: \r\n Could not specialise imported function ‘aeson-1.3.1.1:Data.Aeson.Types.ToJSON.$w$csumToJSON'1’\r\n when specialising ‘aeson-1.3.1.1:Data.Aeson.Types.ToJSON.$fSumToJSON'TYPETwoElemArrayEncoding'arityM2’\r\n Probable fix: add INLINABLE pragma on ‘aeson-1.3.1.1:Data.Aeson.Types.ToJSON.$w$csumToJSON'1’\r\n \r\nsrc/Main.hs: warning: \r\n Could not specialise imported function ‘aeson-1.3.1.1:Data.Aeson.Types.ToJSON.$fGToJSONEncoding'arity:*:1’\r\n Probable fix: add INLINABLE pragma on ‘aeson-1.3.1.1:Data.Aeson.Types.ToJSON.$fGToJSONEncoding'arity:*:1’\r\n \r\nsrc/Main.hs: warning: \r\n Could not specialise imported function ‘aeson-1.3.1.1:Data.Aeson.Types.ToJSON.$fEncodeProductarity:*:_$cencodeProduct’\r\n Probable fix: add INLINABLE pragma on ‘aeson-1.3.1.1:Data.Aeson.Types.ToJSON.$fEncodeProductarity:*:_$cencodeProduct’\r\n \r\nsrc/Main.hs: warning: \r\n Could not specialise imported function ‘aeson-1.3.1.1:Data.Aeson.Types.ToJSON.$fKeyValuePairvDList_$cpair’\r\n Probable fix: add INLINABLE pragma on ‘aeson-1.3.1.1:Data.Aeson.Types.ToJSON.$fKeyValuePairvDList_$cpair’\r\n```\r\n\r\nI think there is a missed optimization here. The inlinable pragma should be added in the module which export these functions." + }, + { + "url": "https://api.github.com/repos/bos/aeson/issues/653", + "repository_url": "https://api.github.com/repos/bos/aeson", + "labels_url": "https://api.github.com/repos/bos/aeson/issues/653/labels{/name}", + "comments_url": "https://api.github.com/repos/bos/aeson/issues/653/comments", + "events_url": "https://api.github.com/repos/bos/aeson/issues/653/events", + "html_url": "https://github.com/bos/aeson/pull/653", + "id": 343386192, + "node_id": "MDExOlB1bGxSZXF1ZXN0MjAzMDQ1MDcx", + "number": 653, + "title": "Rework GFromJSON instances to enable elimination of Generics", + "user": { + "login": "remyoudompheng", + "id": 175246, + "node_id": "MDQ6VXNlcjE3NTI0Ng==", + "avatar_url": "https://avatars3.githubusercontent.com/u/175246?v=4", + "gravatar_id": "", + "url": "https://api.github.com/users/remyoudompheng", + "html_url": "https://github.com/remyoudompheng", + "followers_url": "https://api.github.com/users/remyoudompheng/followers", + "following_url": "https://api.github.com/users/remyoudompheng/following{/other_user}", + "gists_url": "https://api.github.com/users/remyoudompheng/gists{/gist_id}", + "starred_url": "https://api.github.com/users/remyoudompheng/starred{/owner}{/repo}", + "subscriptions_url": "https://api.github.com/users/remyoudompheng/subscriptions", + "organizations_url": "https://api.github.com/users/remyoudompheng/orgs", + "repos_url": "https://api.github.com/users/remyoudompheng/repos", + "events_url": "https://api.github.com/users/remyoudompheng/events{/privacy}", + "received_events_url": "https://api.github.com/users/remyoudompheng/received_events", + "type": "User", + "site_admin": false + }, + "labels": [ + { + "id": 713822109, + "node_id": "MDU6TGFiZWw3MTM4MjIxMDk=", + "url": "https://api.github.com/repos/bos/aeson/labels/versioning%20level:%20minor/non-breaking%20addition", + "name": "versioning level: minor/non-breaking addition", + "color": "fbca04", + "default": false, + "description": null + } + ], + "state": "open", + "locked": false, + "assignee": null, + "assignees": [ + + ], + "milestone": null, + "comments": 9, + "created_at": "2018-07-22T07:55:44Z", + "updated_at": "2019-09-07T14:56:10Z", + "closed_at": null, + "author_association": "NONE", + "pull_request": { + "url": "https://api.github.com/repos/bos/aeson/pulls/653", + "html_url": "https://github.com/bos/aeson/pull/653", + "diff_url": "https://github.com/bos/aeson/pull/653.diff", + "patch_url": "https://github.com/bos/aeson/pull/653.patch" + }, + "body": "The Parser monad signature makes inlining very difficult\r\nbecause GHC only inlines saturated applications, which is\r\nhard to achieve with Parser.\r\n\r\nWe work around this by defining an alternate method in GFromJSON\r\nwhich manipulates the semantically equivalent IResult monad\r\n(Parser is technically more expressive but not for the terms appearing\r\nin GFromJSON). The existing method is left for API compatibility.\r\n\r\nThe resulting code achieves rougly the same compilation speed but\r\nreaches large performance improvements, for a generated code size\r\nnot far from the manually written instances in benchmarks.\r\n\r\nThe object file for Twitter.Generic grows to 332kB (from 285kB),\r\nbut the Twitter.Manual module is 300kB large. The inlining level of\r\ntypeMismatch has been reduced to curb code blow-up.\r\n\r\nDue to inlining levels differences, the Generic fromJSON is now\r\noften quicker than its TH or Manual counterpart in benchmarks.\r\n\r\nBenchmark results (Core i5 Haswell)\r\n\r\n| | TH | Generic (before) | Generic (after) | Manual |\r\n| --- | --- | --- | --- | --- |\r\n| D/fromJSON | 1.720 µs | 5.076 µs | 1.505 µs | - |\r\n| BigRecord/fromJSON | 3.720 µs | 8.450 µs | 2.964 µs | - |\r\n| BigProduct/fromJSON | 2.412 µs | 3.427 µs | 1.812 µs | - |\r\n| BigSum/fromJSON | 173 ns | 1230 ns | 171 ns | - |\r\n| twitter100 | 1.611 ms | 2.063 ms | 1.334 ms | 1.516 ms |\r\n| jp100 | 1.844 ms | 2.18 ms | 1.481 ms | 1.677 ms |\r\n" + }, + { + "url": "https://api.github.com/repos/bos/aeson/issues/651", + "repository_url": "https://api.github.com/repos/bos/aeson", + "labels_url": "https://api.github.com/repos/bos/aeson/issues/651/labels{/name}", + "comments_url": "https://api.github.com/repos/bos/aeson/issues/651/comments", + "events_url": "https://api.github.com/repos/bos/aeson/issues/651/events", + "html_url": "https://github.com/bos/aeson/issues/651", + "id": 340747607, + "node_id": "MDU6SXNzdWUzNDA3NDc2MDc=", + "number": 651, + "title": "Can't use .= operator to build JSON because of ambiguous instances.", + "user": { + "login": "LeifW", + "id": 28711, + "node_id": "MDQ6VXNlcjI4NzEx", + "avatar_url": "https://avatars2.githubusercontent.com/u/28711?v=4", + "gravatar_id": "", + "url": "https://api.github.com/users/LeifW", + "html_url": "https://github.com/LeifW", + "followers_url": "https://api.github.com/users/LeifW/followers", + "following_url": "https://api.github.com/users/LeifW/following{/other_user}", + "gists_url": "https://api.github.com/users/LeifW/gists{/gist_id}", + "starred_url": "https://api.github.com/users/LeifW/starred{/owner}{/repo}", + "subscriptions_url": "https://api.github.com/users/LeifW/subscriptions", + "organizations_url": "https://api.github.com/users/LeifW/orgs", + "repos_url": "https://api.github.com/users/LeifW/repos", + "events_url": "https://api.github.com/users/LeifW/events{/privacy}", + "received_events_url": "https://api.github.com/users/LeifW/received_events", + "type": "User", + "site_admin": false + }, + "labels": [ + + ], + "state": "open", + "locked": false, + "assignee": null, + "assignees": [ + + ], + "milestone": null, + "comments": 4, + "created_at": "2018-07-12T18:24:11Z", + "updated_at": "2018-07-15T17:11:21Z", + "closed_at": null, + "author_association": "NONE", + "body": "I put up a gist: https://gist.github.com/LeifW/f3e51437f4494eff9d7c23355f268ef7\r\n\r\nEssentially, this file\r\n```haskell\r\n{-# LANGUAGE OverloadedStrings #-}\r\n\r\nimport Data.Aeson \r\n\r\nthing = object [ \"foo\" .= \"bar\" ]\r\n```\r\ngives this error message when you try to compile it:\r\n```\r\ntest.hs:5:18: error:\r\n • Ambiguous type variable ‘v0’ arising from a use of ‘.=’\r\n prevents the constraint ‘(ToJSON v0)’ from being solved.\r\n Probable fix: use a type annotation to specify what ‘v0’ should be.\r\n These potential instances exist:\r\n instance ToJSON DotNetTime\r\n -- Defined in ‘aeson-1.3.1.1:Data.Aeson.Types.ToJSON’\r\n instance ToJSON Value\r\n -- Defined in ‘aeson-1.3.1.1:Data.Aeson.Types.ToJSON’\r\n instance (ToJSON a, ToJSON b) => ToJSON (Either a b)\r\n -- Defined in ‘aeson-1.3.1.1:Data.Aeson.Types.ToJSON’\r\n ...plus 25 others\r\n ...plus 55 instances involving out-of-scope types\r\n (use -fprint-potential-instances to see them all)\r\n • In the expression: \"foo\" .= \"bar\"\r\n In the first argument of ‘object’, namely ‘[\"foo\" .= \"bar\"]’\r\n In the expression: object [\"foo\" .= \"bar\"]\r\n |\r\n5 | thing = object [ \"foo\" .= \"bar\" ]\r\n | ^^^^^^^^^^^^^^\r\n\r\ntest.hs:5:27: error:\r\n • Ambiguous type variable ‘v0’ arising from the literal ‘\"bar\"’\r\n prevents the constraint ‘(Data.String.IsString\r\n v0)’ from being solved.\r\n Probable fix: use a type annotation to specify what ‘v0’ should be.\r\n These potential instances exist:\r\n instance Data.String.IsString Value\r\n -- Defined in ‘aeson-1.3.1.1:Data.Aeson.Types.Internal’\r\n instance (a ~ Char) => Data.String.IsString [a]\r\n -- Defined in ‘Data.String’\r\n ...plus 11 instances involving out-of-scope types\r\n (use -fprint-potential-instances to see them all)\r\n • In the second argument of ‘(.=)’, namely ‘\"bar\"’\r\n In the expression: \"foo\" .= \"bar\"\r\n In the first argument of ‘object’, namely ‘[\"foo\" .= \"bar\"]’\r\n |\r\n5 | thing = object [ \"foo\" .= \"bar\" ]\r\n```\r\nIt works in the repl and/or if you add `ExtendedDefaultRules`, though." + }, + { + "url": "https://api.github.com/repos/bos/aeson/issues/647", + "repository_url": "https://api.github.com/repos/bos/aeson", + "labels_url": "https://api.github.com/repos/bos/aeson/issues/647/labels{/name}", + "comments_url": "https://api.github.com/repos/bos/aeson/issues/647/comments", + "events_url": "https://api.github.com/repos/bos/aeson/issues/647/events", + "html_url": "https://github.com/bos/aeson/pull/647", + "id": 331981135, + "node_id": "MDExOlB1bGxSZXF1ZXN0MTk0NTc1ODg2", + "number": 647, + "title": "Export `withBoundedScientific`", + "user": { + "login": "qrilka", + "id": 70110, + "node_id": "MDQ6VXNlcjcwMTEw", + "avatar_url": "https://avatars2.githubusercontent.com/u/70110?v=4", + "gravatar_id": "", + "url": "https://api.github.com/users/qrilka", + "html_url": "https://github.com/qrilka", + "followers_url": "https://api.github.com/users/qrilka/followers", + "following_url": "https://api.github.com/users/qrilka/following{/other_user}", + "gists_url": "https://api.github.com/users/qrilka/gists{/gist_id}", + "starred_url": "https://api.github.com/users/qrilka/starred{/owner}{/repo}", + "subscriptions_url": "https://api.github.com/users/qrilka/subscriptions", + "organizations_url": "https://api.github.com/users/qrilka/orgs", + "repos_url": "https://api.github.com/users/qrilka/repos", + "events_url": "https://api.github.com/users/qrilka/events{/privacy}", + "received_events_url": "https://api.github.com/users/qrilka/received_events", + "type": "User", + "site_admin": false + }, + "labels": [ + { + "id": 713822109, + "node_id": "MDU6TGFiZWw3MTM4MjIxMDk=", + "url": "https://api.github.com/repos/bos/aeson/labels/versioning%20level:%20minor/non-breaking%20addition", + "name": "versioning level: minor/non-breaking addition", + "color": "fbca04", + "default": false, + "description": null + } + ], + "state": "open", + "locked": false, + "assignee": null, + "assignees": [ + + ], + "milestone": null, + "comments": 1, + "created_at": "2018-06-13T12:52:28Z", + "updated_at": "2018-06-14T19:59:58Z", + "closed_at": null, + "author_association": "NONE", + "pull_request": { + "url": "https://api.github.com/repos/bos/aeson/pulls/647", + "html_url": "https://github.com/bos/aeson/pull/647", + "diff_url": "https://github.com/bos/aeson/pull/647.diff", + "patch_url": "https://github.com/bos/aeson/pull/647.patch" + }, + "body": "http://hackage.haskell.org/package/aeson-1.4.0.0/docs/Data-Aeson.html#v:withScientific advises to use `withBoundedScientific` for unbounded types but the function wasn't exported" + }, + { + "url": "https://api.github.com/repos/bos/aeson/issues/646", + "repository_url": "https://api.github.com/repos/bos/aeson", + "labels_url": "https://api.github.com/repos/bos/aeson/issues/646/labels{/name}", + "comments_url": "https://api.github.com/repos/bos/aeson/issues/646/comments", + "events_url": "https://api.github.com/repos/bos/aeson/issues/646/events", + "html_url": "https://github.com/bos/aeson/issues/646", + "id": 331495282, + "node_id": "MDU6SXNzdWUzMzE0OTUyODI=", + "number": 646, + "title": "Allow accepting missing fields of other types than Maybe", + "user": { + "login": "lortabac", + "id": 1907333, + "node_id": "MDQ6VXNlcjE5MDczMzM=", + "avatar_url": "https://avatars3.githubusercontent.com/u/1907333?v=4", + "gravatar_id": "", + "url": "https://api.github.com/users/lortabac", + "html_url": "https://github.com/lortabac", + "followers_url": "https://api.github.com/users/lortabac/followers", + "following_url": "https://api.github.com/users/lortabac/following{/other_user}", + "gists_url": "https://api.github.com/users/lortabac/gists{/gist_id}", + "starred_url": "https://api.github.com/users/lortabac/starred{/owner}{/repo}", + "subscriptions_url": "https://api.github.com/users/lortabac/subscriptions", + "organizations_url": "https://api.github.com/users/lortabac/orgs", + "repos_url": "https://api.github.com/users/lortabac/repos", + "events_url": "https://api.github.com/users/lortabac/events{/privacy}", + "received_events_url": "https://api.github.com/users/lortabac/received_events", + "type": "User", + "site_admin": false + }, + "labels": [ + + ], + "state": "open", + "locked": false, + "assignee": null, + "assignees": [ + + ], + "milestone": null, + "comments": 13, + "created_at": "2018-06-12T08:51:26Z", + "updated_at": "2019-12-29T19:42:07Z", + "closed_at": null, + "author_association": "NONE", + "body": "When deriving `FromJSON` instances generically, there is no way to provide a default value to a missing field of a record if the field is not a `Maybe`.\r\n\r\nThis seems related to #614, in that the proposed solution may help fixing both issues." + }, + { + "url": "https://api.github.com/repos/bos/aeson/issues/644", + "repository_url": "https://api.github.com/repos/bos/aeson", + "labels_url": "https://api.github.com/repos/bos/aeson/issues/644/labels{/name}", + "comments_url": "https://api.github.com/repos/bos/aeson/issues/644/comments", + "events_url": "https://api.github.com/repos/bos/aeson/issues/644/events", + "html_url": "https://github.com/bos/aeson/issues/644", + "id": 326014300, + "node_id": "MDU6SXNzdWUzMjYwMTQzMDA=", + "number": 644, + "title": "Expose Data.Aeson.Encoding.Builder", + "user": { + "login": "alexbiehl", + "id": 1876617, + "node_id": "MDQ6VXNlcjE4NzY2MTc=", + "avatar_url": "https://avatars2.githubusercontent.com/u/1876617?v=4", + "gravatar_id": "", + "url": "https://api.github.com/users/alexbiehl", + "html_url": "https://github.com/alexbiehl", + "followers_url": "https://api.github.com/users/alexbiehl/followers", + "following_url": "https://api.github.com/users/alexbiehl/following{/other_user}", + "gists_url": "https://api.github.com/users/alexbiehl/gists{/gist_id}", + "starred_url": "https://api.github.com/users/alexbiehl/starred{/owner}{/repo}", + "subscriptions_url": "https://api.github.com/users/alexbiehl/subscriptions", + "organizations_url": "https://api.github.com/users/alexbiehl/orgs", + "repos_url": "https://api.github.com/users/alexbiehl/repos", + "events_url": "https://api.github.com/users/alexbiehl/events{/privacy}", + "received_events_url": "https://api.github.com/users/alexbiehl/received_events", + "type": "User", + "site_admin": false + }, + "labels": [ + { + "id": 563935541, + "node_id": "MDU6TGFiZWw1NjM5MzU1NDE=", + "url": "https://api.github.com/repos/bos/aeson/labels/needs%20decision", + "name": "needs decision", + "color": "c5def5", + "default": false, + "description": null + } + ], + "state": "open", + "locked": false, + "assignee": null, + "assignees": [ + + ], + "milestone": null, + "comments": 3, + "created_at": "2018-05-24T08:24:58Z", + "updated_at": "2018-08-05T20:38:09Z", + "closed_at": null, + "author_association": "NONE", + "body": "At work we have a JSON schema which demands composite keys for objects of this form: \r\n\r\n```\r\n\"_\": ... \r\n```\r\n\r\nNow, we used the venerable `toKey (n, d) = Text.pack (show n ++ '_' ++ show d)` but this turned out out to show up in our profiling and really was taking 10% of our overall runtime! So we went for some cruel hack: \r\n\r\n```haskell\r\n toKey (n ,d) = Encoding.unsafeToEncoding $\r\n Builder.char7 '\"' <> Builder.intDec r <> Builder.char7 '_'\r\n <> Encoding.fromEncoding (Encoding.day d) <> Builder.char7 '\"'\r\n```\r\n\r\nUnfortunately this results in invalid JSON as `Encoding.day` is wrapped into quotes! It would be really neat if we could access the unsafe stuff from Data.Aeson.Encoding.Builder to use the `Day` encoding without quotes.\r\n\r\n" + }, + { + "url": "https://api.github.com/repos/bos/aeson/issues/642", + "repository_url": "https://api.github.com/repos/bos/aeson", + "labels_url": "https://api.github.com/repos/bos/aeson/issues/642/labels{/name}", + "comments_url": "https://api.github.com/repos/bos/aeson/issues/642/comments", + "events_url": "https://api.github.com/repos/bos/aeson/issues/642/events", + "html_url": "https://github.com/bos/aeson/issues/642", + "id": 323568779, + "node_id": "MDU6SXNzdWUzMjM1Njg3Nzk=", + "number": 642, + "title": "Dealing with empty object from API service", + "user": { + "login": "Rizary", + "id": 7221768, + "node_id": "MDQ6VXNlcjcyMjE3Njg=", + "avatar_url": "https://avatars3.githubusercontent.com/u/7221768?v=4", + "gravatar_id": "", + "url": "https://api.github.com/users/Rizary", + "html_url": "https://github.com/Rizary", + "followers_url": "https://api.github.com/users/Rizary/followers", + "following_url": "https://api.github.com/users/Rizary/following{/other_user}", + "gists_url": "https://api.github.com/users/Rizary/gists{/gist_id}", + "starred_url": "https://api.github.com/users/Rizary/starred{/owner}{/repo}", + "subscriptions_url": "https://api.github.com/users/Rizary/subscriptions", + "organizations_url": "https://api.github.com/users/Rizary/orgs", + "repos_url": "https://api.github.com/users/Rizary/repos", + "events_url": "https://api.github.com/users/Rizary/events{/privacy}", + "received_events_url": "https://api.github.com/users/Rizary/received_events", + "type": "User", + "site_admin": false + }, + "labels": [ + { + "id": 315555511, + "node_id": "MDU6TGFiZWwzMTU1NTU1MTE=", + "url": "https://api.github.com/repos/bos/aeson/labels/question", + "name": "question", + "color": "5319e7", + "default": true, + "description": null + } + ], + "state": "open", + "locked": false, + "assignee": null, + "assignees": [ + + ], + "milestone": null, + "comments": 2, + "created_at": "2018-05-16T10:52:05Z", + "updated_at": "2018-06-23T15:08:38Z", + "closed_at": null, + "author_association": "NONE", + "body": "Hi, what is the best to handle when we got `name: {}` (this is from nodejs backend) response from api service, meanwhile what i want is to assume it is 'name: {first: \"\", last: \"\"}` so I can parse it to \r\n```Person {firstName :: Maybe Text, lastName :: Maybe Text}``` ?\r\n\r\nsupposed that I have the following types:\r\nhttps://gist.github.com/Rizary/3b3865a145853cf04df7fad4e348a5c3\r\n\r\nI finally use `optional` but actually that's not what I want, because I can't parsed the `name: {}` as `name: {first: \"\", last: \"\"}`" + }, + { + "url": "https://api.github.com/repos/bos/aeson/issues/641", + "repository_url": "https://api.github.com/repos/bos/aeson", + "labels_url": "https://api.github.com/repos/bos/aeson/issues/641/labels{/name}", + "comments_url": "https://api.github.com/repos/bos/aeson/issues/641/comments", + "events_url": "https://api.github.com/repos/bos/aeson/issues/641/events", + "html_url": "https://github.com/bos/aeson/issues/641", + "id": 322585124, + "node_id": "MDU6SXNzdWUzMjI1ODUxMjQ=", + "number": 641, + "title": "Building failed on GHC 8.0.2", + "user": { + "login": "pe200012", + "id": 13463539, + "node_id": "MDQ6VXNlcjEzNDYzNTM5", + "avatar_url": "https://avatars1.githubusercontent.com/u/13463539?v=4", + "gravatar_id": "", + "url": "https://api.github.com/users/pe200012", + "html_url": "https://github.com/pe200012", + "followers_url": "https://api.github.com/users/pe200012/followers", + "following_url": "https://api.github.com/users/pe200012/following{/other_user}", + "gists_url": "https://api.github.com/users/pe200012/gists{/gist_id}", + "starred_url": "https://api.github.com/users/pe200012/starred{/owner}{/repo}", + "subscriptions_url": "https://api.github.com/users/pe200012/subscriptions", + "organizations_url": "https://api.github.com/users/pe200012/orgs", + "repos_url": "https://api.github.com/users/pe200012/repos", + "events_url": "https://api.github.com/users/pe200012/events{/privacy}", + "received_events_url": "https://api.github.com/users/pe200012/received_events", + "type": "User", + "site_admin": false + }, + "labels": [ + + ], + "state": "open", + "locked": false, + "assignee": null, + "assignees": [ + + ], + "milestone": null, + "comments": 5, + "created_at": "2018-05-13T11:16:59Z", + "updated_at": "2018-06-23T15:23:48Z", + "closed_at": null, + "author_association": "NONE", + "body": "
\r\n[ 1 of 24] Compiling Data.Attoparsec.Time.Internal ( attoparsec-iso8601/Data/Attoparsec/Time/Internal.hs, dist/build/Data/Attoparsec/Time/Internal.o )\r\n[ 2 of 24] Compiling Data.Attoparsec.Time ( attoparsec-iso8601/Data/Attoparsec/Time.hs, dist/build/Data/Attoparsec/Time.o )\r\n[ 3 of 24] Compiling Data.Aeson.Types.Internal ( Data/Aeson/Types/Internal.hs, dist/build/Data/Aeson/Types/Internal.o )\r\n\r\nData/Aeson/Types/Internal.hs:397:17: error:\r\n    • Can't find interface-file declaration for type constructor or class Language.Haskell.TH.Lib.ExpQ\r\n        Probable cause: bug in .hi-boot file, or inconsistent .hi file\r\n        Use -ddump-if-trace to get an idea of which file caused the error\r\n    • In the expression: [| Null |]\r\n      In an equation for ‘lift’: lift Null = [| Null |]\r\n      In the instance declaration for ‘TH.Lift Value’\r\ncabal: Leaving directory '/tmp/cabal-tmp-12259/aeson-1.2.4.0'\r\ncabal: Error: some packages failed to install:\r\naeson-1.2.4.0 failed during the building phase. The exception was:\r\nExitFailure 1\r\nhttp-conduit-2.3.1 depends on aeson-1.2.4.0 which failed to install.\r\nidringen-0.1.0.3 depends on aeson-1.2.4.0 which failed to install.\r\nidris-1.2.0 depends on aeson-1.2.4.0 which failed to install.\r\n\r\n
\r\nbuild separately,\r\n
\r\nPreprocessing library aeson-1.3.1.1...\r\n[ 1 of 24] Compiling Data.Attoparsec.Time.Internal ( attoparsec-iso8601/Data/Attoparsec/Time/Internal.hs, dist/build/Data/Attoparsec/Time/Internal.o )\r\n[ 2 of 24] Compiling Data.Attoparsec.Time ( attoparsec-iso8601/Data/Attoparsec/Time.hs, dist/build/Data/Attoparsec/Time.o )\r\n[ 3 of 24] Compiling Data.Aeson.Types.Internal ( Data/Aeson/Types/Internal.hs, dist/build/Data/Aeson/Types/Internal.o )\r\n\r\nData/Aeson/Types/Internal.hs:399:17: error:\r\n    • Can't find interface-file declaration for type constructor or class Language.Haskell.TH.Lib.ExpQ\r\n        Probable cause: bug in .hi-boot file, or inconsistent .hi file\r\n        Use -ddump-if-trace to get an idea of which file caused the error\r\n    • In the expression: [| Null |]\r\n      In an equation for ‘lift’: lift Null = [| Null |]\r\n      In the instance declaration for ‘TH.Lift Value’\r\ncabal: Leaving directory '/tmp/cabal-tmp-12422/aeson-1.3.1.1'\r\ncabal: Error: some packages failed to install:\r\naeson-1.3.1.1 failed during the building phase. The exception was:\r\nExitFailure 1\r\n
" + }, + { + "url": "https://api.github.com/repos/bos/aeson/issues/624", + "repository_url": "https://api.github.com/repos/bos/aeson", + "labels_url": "https://api.github.com/repos/bos/aeson/issues/624/labels{/name}", + "comments_url": "https://api.github.com/repos/bos/aeson/issues/624/comments", + "events_url": "https://api.github.com/repos/bos/aeson/issues/624/events", + "html_url": "https://github.com/bos/aeson/issues/624", + "id": 299707462, + "node_id": "MDU6SXNzdWUyOTk3MDc0NjI=", + "number": 624, + "title": "Add some way (or document if it already exists) to extract data type name in 'defaultOptions'", + "user": { + "login": "chshersh", + "id": 4276606, + "node_id": "MDQ6VXNlcjQyNzY2MDY=", + "avatar_url": "https://avatars0.githubusercontent.com/u/4276606?v=4", + "gravatar_id": "", + "url": "https://api.github.com/users/chshersh", + "html_url": "https://github.com/chshersh", + "followers_url": "https://api.github.com/users/chshersh/followers", + "following_url": "https://api.github.com/users/chshersh/following{/other_user}", + "gists_url": "https://api.github.com/users/chshersh/gists{/gist_id}", + "starred_url": "https://api.github.com/users/chshersh/starred{/owner}{/repo}", + "subscriptions_url": "https://api.github.com/users/chshersh/subscriptions", + "organizations_url": "https://api.github.com/users/chshersh/orgs", + "repos_url": "https://api.github.com/users/chshersh/repos", + "events_url": "https://api.github.com/users/chshersh/events{/privacy}", + "received_events_url": "https://api.github.com/users/chshersh/received_events", + "type": "User", + "site_admin": false + }, + "labels": [ + + ], + "state": "open", + "locked": false, + "assignee": null, + "assignees": [ + + ], + "milestone": null, + "comments": 6, + "created_at": "2018-02-23T13:13:52Z", + "updated_at": "2018-09-07T04:07:09Z", + "closed_at": null, + "author_association": "NONE", + "body": "I want to add full data type name to every field of my data type. Like this:\r\n\r\n```haskell\r\ndata ProjectManager = ProjectManager\r\n { projectManagerName :: Text\r\n , projectManagerSalary :: Natural\r\n }\r\n```\r\n\r\nAnd I want to have JSON encoding like this: `{ name: \"Vasya Pupkin\", salary: 42 }`. I don't see any way to implement general `Options` data type which can automatically work for any type with [`fieldLabelModifier`](https://hackage.haskell.org/package/aeson-1.2.4.0/docs/Data-Aeson.html#v:fieldLabelModifier) because I don't know type name from context." + }, + { + "url": "https://api.github.com/repos/bos/aeson/issues/622", + "repository_url": "https://api.github.com/repos/bos/aeson", + "labels_url": "https://api.github.com/repos/bos/aeson/issues/622/labels{/name}", + "comments_url": "https://api.github.com/repos/bos/aeson/issues/622/comments", + "events_url": "https://api.github.com/repos/bos/aeson/issues/622/events", + "html_url": "https://github.com/bos/aeson/issues/622", + "id": 296505410, + "node_id": "MDU6SXNzdWUyOTY1MDU0MTA=", + "number": 622, + "title": "ToJSON/FromJSON instances fail for UTCTime, DiffTime", + "user": { + "login": "brainwave0", + "id": 3056980, + "node_id": "MDQ6VXNlcjMwNTY5ODA=", + "avatar_url": "https://avatars0.githubusercontent.com/u/3056980?v=4", + "gravatar_id": "", + "url": "https://api.github.com/users/brainwave0", + "html_url": "https://github.com/brainwave0", + "followers_url": "https://api.github.com/users/brainwave0/followers", + "following_url": "https://api.github.com/users/brainwave0/following{/other_user}", + "gists_url": "https://api.github.com/users/brainwave0/gists{/gist_id}", + "starred_url": "https://api.github.com/users/brainwave0/starred{/owner}{/repo}", + "subscriptions_url": "https://api.github.com/users/brainwave0/subscriptions", + "organizations_url": "https://api.github.com/users/brainwave0/orgs", + "repos_url": "https://api.github.com/users/brainwave0/repos", + "events_url": "https://api.github.com/users/brainwave0/events{/privacy}", + "received_events_url": "https://api.github.com/users/brainwave0/received_events", + "type": "User", + "site_admin": false + }, + "labels": [ + + ], + "state": "open", + "locked": false, + "assignee": null, + "assignees": [ + + ], + "milestone": null, + "comments": 3, + "created_at": "2018-02-12T20:00:41Z", + "updated_at": "2018-02-12T22:11:12Z", + "closed_at": null, + "author_association": "NONE", + "body": "If I try to make an instance for a custom type that includes a UTCTime or a DiffTime, I get a compile error. For example, if I try to compile the folowing code\r\n\r\n {-# LANGUAGE DeriveGeneric #-}\r\n import GHC.Generics\r\n import Data.Aeson\r\n import Data.Time\r\n data Foo = Foo UTCTime deriving (Generic, Show)\r\n instance ToJSON Foo\r\n instance FromJSON Foo\r\n\r\nI get\r\n\r\n /home/ian/test.hs:6:10:\r\n No instance for (ToJSON UTCTime)\r\n arising from a use of ‘aeson-1.2.4.0:Data.Aeson.Types.ToJSON.$gdmtoJSON’\r\n In the expression: aeson-1.2.4.0:Data.Aeson.Types.ToJSON.$gdmtoJSON\r\n In an equation for ‘toJSON’:\r\n toJSON = aeson-1.2.4.0:Data.Aeson.Types.ToJSON.$gdmtoJSON\r\n In the instance declaration for ‘ToJSON Foo’\r\n \r\n /home/ian/test.hs:7:10:\r\n No instance for (FromJSON UTCTime)\r\n arising from a use of ‘aeson-1.2.4.0:Data.Aeson.Types.FromJSON.$gdmparseJSON’\r\n In the expression:\r\n aeson-1.2.4.0:Data.Aeson.Types.FromJSON.$gdmparseJSON\r\n In an equation for ‘parseJSON’:\r\n parseJSON = aeson-1.2.4.0:Data.Aeson.Types.FromJSON.$gdmparseJSON\r\n In the instance declaration for ‘FromJSON Foo’" + } +] diff --git a/distributors-json/bench/data/jp100.json b/distributors-json/bench/data/jp100.json new file mode 100644 index 00000000..c45b1daf --- /dev/null +++ b/distributors-json/bench/data/jp100.json @@ -0,0 +1 @@ +{"results":[{"from_user_id_str":"178045354","profile_image_url":"http://a0.twimg.com/profile_images/1214479381/154722_10100141954893059_808622_55276626_7445050_n_normal.jpg","created_at":"Fri, 25 Feb 2011 17:40:04 +0000","from_user":"ChuriSta_gt","id_str":"41190705623732224","metadata":{"result_type":"recent"},"to_user_id":null,"text":"\u3072\u3089\u304c\u306a\u306e\u300c\u3064\u300d\u306f\u3082\u3046Twitter\u306e\u300c\u3064\u300d\u3060\uff01","id":41190705623732224,"from_user_id":178045354,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://twipple.jp/" rel="nofollow">\u3064\u3044\u3063\u3077\u308b for iPhone</a>"},{"from_user_id_str":"71746558","profile_image_url":"http://a2.twimg.com/profile_images/591641547/wwd_normal.gif","created_at":"Fri, 25 Feb 2011 17:40:02 +0000","from_user":"fuckkilldiestar","id_str":"41190699571494912","metadata":{"result_type":"recent"},"to_user_id":null,"text":"\u306b\u3057\u3066\u3082Twitter\u3084pixiv\u96e2\u308c\u3092\u3069\u3046\u306b\u304b\u3057\u308d\u674f\u4ec1\u30d6\u30eb\u30de","id":41190699571494912,"from_user_id":71746558,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://twitter.com/" rel="nofollow">Twitter for iPhone</a>"},{"from_user_id_str":"131230176","profile_image_url":"http://a2.twimg.com/sticky/default_profile_images/default_profile_5_normal.png","created_at":"Fri, 25 Feb 2011 17:39:58 +0000","from_user":"proory_bot","id_str":"41190683922546688","metadata":{"result_type":"recent"},"to_user_id":null,"text":"\u30ea\u30cd\u30f3\u30dd\u30fc\u30c1 http://bit.ly/btjqlH","id":41190683922546688,"from_user_id":131230176,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://proory.com/" rel="nofollow">proory tems</a>"},{"from_user_id_str":"120359038","profile_image_url":"http://a1.twimg.com/profile_images/946521484/200805161826000_normal.jpg","created_at":"Fri, 25 Feb 2011 17:39:58 +0000","from_user":"tukinosuke","id_str":"41190680835391488","metadata":{"result_type":"recent"},"to_user_id":null,"text":"RT @fuefukioyasumi: \u3082\u3046\u3044\u3044\u3002\u300c\u671d\u751f\u300d\u306a\u3093\u304b\u3044\u3044\u3002BBC\u3082CNN\u3082\u82f1\u8a9e\u653e\u9001\u3060\u3002\u307f\u3093\u306a\u3001\u30c6\u30ec\u30d3\u3092\u3076\u3061\u3063\u3068\u5207\u3063\u3066Twitter\u3092\u898b\u3088\u3046\u3002\u3053\u3053\u306b\u300c\u751f\u304d\u305f\u60c5\u5831\u300d\u304c\u6d41\u308c\u3066\u3044\u308b\u3002\u300c\u751f\u304d\u305f\u53eb\u3073\u300d\u304c\u3042\u308b\u3002\u3053\u3053\u304b\u3089\u3067\u3082\u6b74\u53f2\u306e\u8ee2\u63db\u70b9\u3092\u611f\u3058\u308b\u4e8b\u304c\u3067\u304d\u308b\u306e\u3060\u3002 @gjmorley #libjp","id":41190680835391488,"from_user_id":120359038,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://twitter.com/">web</a>"},{"from_user_id_str":"166512109","profile_image_url":"http://a3.twimg.com/profile_images/1224583217/image_normal.jpg","created_at":"Fri, 25 Feb 2011 17:39:50 +0000","from_user":"yurii1129","id_str":"41190649839620096","metadata":{"result_type":"recent"},"to_user_id":null,"text":"\u4eca\u6c17\u4ed8\u3044\u305f\u2026\u307f\u3043\u304f\u3093\u306eTwitter\u540d\u3001\u3084\u307e\u306d\u3084\u3093(\uffe3\u25c7\uffe3;)","id":41190649839620096,"from_user_id":166512109,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://twitter.com/" rel="nofollow">Twitter for iPhone</a>"},{"from_user_id_str":"228999619","profile_image_url":"http://a3.twimg.com/sticky/default_profile_images/default_profile_6_normal.png","created_at":"Fri, 25 Feb 2011 17:39:49 +0000","from_user":"takami926","id_str":"41190644793745408","metadata":{"result_type":"recent"},"to_user_id":null,"text":"\u7530\u539f\u3055\u3093\u3001\u5fdc\u63f4\u3057\u3066\u307e\u3059\u3002WEB\u3082TWITTER\u3082\u62dd\u898b\u3057\u3066\u307e\u3059\u3002\u7530\u539f\u3055\u3093\u304c\u653f\u6cbb\u5bb6\u306b\u306a\u3063\u3066\u3001\u65e5\u672c\u3092\u5909\u3048\u3066\u304f\u3060\u3055\u3044\u3002\u5c16\u95a3\u3001\u5317\u65b9\u554f\u984c\u5171\u306b\u65e5\u672c\u306e\u653f\u6cbb\u306e\u5931\u6557\u3067\u3059\u3002\u8a55\u8ad6\u5bb6\u306f\u8272\u3005\u8a00\u3063\u3066\u307e\u3059\u304c\u3001\u4e2d\u6771\u307b\u3069\u56fd\u6c11\u306e\u71b1\u6c17\u304c\u7121\u304f\u3001\u683c\u5dee\u304c\u3042\u308a\u3001\u4f55\u3082\u5909\u308f\u3089\u306a\u3044\u666f\u6c17\u4f4e\u8ff7\u306e\u65e5\u672c\u306b\u56fd\u6c11\u306f\u8ae6\u3081\u3066\u308b\u3093\u3067\u3059\u3002","id":41190644793745408,"from_user_id":228999619,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://twitter.com/">web</a>"},{"from_user_id_str":"151773701","profile_image_url":"http://a0.twimg.com/profile_images/1213699753/obi_nao_normal.jpg","created_at":"Fri, 25 Feb 2011 17:39:44 +0000","from_user":"obi_nao","id_str":"41190622949941248","metadata":{"result_type":"recent"},"to_user_id":null,"text":"\u3060\u3044\u3076\u5e74\u4e0b\u306e\u5f8c\u8f29\u306b\u3001\u30d3\u30b8\u30cd\u30b9\u3084\u308b\u306a\u3089\u771f\u5263\u306bTwitter\u3084\u308c\uff01\u3063\u3066\u6012\u3089\u308c\u305f\u3002\u306a\u306e\u3067\u4eca\u65e5\u304b\u3089\u771f\u5263\u306b\u3064\u3076\u3084\u304f\u3053\u3068\u306b\u3057\u307e\u3059\u3002\u3088\u308d\u3057\u304f\u3067\u3059\u3002","id":41190622949941248,"from_user_id":151773701,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://www.flight.co.jp/iPhone/TweetMe/" rel="nofollow">TweetMe for iPhone</a>"},{"from_user_id_str":"20817229","profile_image_url":"http://a0.twimg.com/profile_images/1212012721/205_normal.jpg","created_at":"Fri, 25 Feb 2011 17:39:43 +0000","from_user":"allte","id_str":"41190619804082176","metadata":{"result_type":"recent"},"to_user_id":null,"text":"\u7206\u7b11\u3057\u3066\u547c\u5438\u56f0\u96e3\u3067\u75d9\u6523\u3059\u308b\u5618\u304f\u3093\u304c\u898b\u308c\u308b\u306e\u306fTwitter\u3060\u3051","id":41190619804082176,"from_user_id":20817229,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://www.movatwi.jp" rel="nofollow">www.movatwi.jp</a>"},{"from_user_id_str":"166907967","profile_image_url":"http://a2.twimg.com/profile_images/1250526230/___normal.jpg","created_at":"Fri, 25 Feb 2011 17:39:43 +0000","from_user":"NTTYAHOOOOOOOI","id_str":"41190618235412480","metadata":{"result_type":"recent"},"to_user_id":106469594,"text":"@takahirororo \u3066\u304b\u4f55\u3067twitter\u4e0a\u3067\u30a2\u30c9\u30d0\u30a4\u30b9\u3082\u3089\u3063\u3066\u3093\u306d\u3093\uff57","id":41190618235412480,"from_user_id":166907967,"to_user":"takahirororo","geo":null,"iso_language_code":"ja","to_user_id_str":"106469594","source":"<a href="http://twitter.com/">web</a>"},{"from_user_id_str":"82581287","profile_image_url":"http://a0.twimg.com/profile_images/774721566/miyaru2_normal.jpg","created_at":"Fri, 25 Feb 2011 17:39:38 +0000","from_user":"kine_rahchaos","id_str":"41190598132244480","metadata":{"result_type":"recent"},"to_user_id":null,"text":"\u30a2\u30aa\u30b7\u30de\u3055\u3093\u304cTwitter\u59cb\u3081\u305f\u3060\u3068\u2026","id":41190598132244480,"from_user_id":82581287,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://sourceforge.jp/projects/tween/wiki/FrontPage" rel="nofollow">Tween</a>"},{"from_user_id_str":"136633905","profile_image_url":"http://a2.twimg.com/profile_images/1247161991/yama_normal.png","created_at":"Fri, 25 Feb 2011 17:39:35 +0000","from_user":"yamachi39","id_str":"41190584706285568","metadata":{"result_type":"recent"},"to_user_id":null,"text":"\u3084\u3063\u3071\u308amixi\u3088\u308atwitter\u306e\u304c\u597d\u304d\u304b\u3082","id":41190584706285568,"from_user_id":136633905,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://jigtwi.jp/?p=1" rel="nofollow">jigtwi</a>"},{"from_user_id_str":"44029295","profile_image_url":"http://a2.twimg.com/profile_images/1112965522/image_normal.jpg","created_at":"Fri, 25 Feb 2011 17:39:32 +0000","from_user":"no2yosee","id_str":"41190572769280000","metadata":{"result_type":"recent"},"to_user_id":97721124,"text":"@hn0345 \u3042\u3001\u500b\u4eba\u7684\u306b\u306f\u4eca\u306ftwitter\u306e\u30d7\u30ed\u30d5\u30a3\u30fc\u30eb\u306b\u66f8\u3044\u3066\u3042\u308b\u30d6\u30ed\u30b0\u306e\u30e6\u30cb\u30c3\u30c8\u3092\u306e\u3093\u3073\u308a\u3084\u3063\u3066\u307e\u3059w","id":41190572769280000,"from_user_id":44029295,"to_user":"hn0345","geo":null,"iso_language_code":"ja","to_user_id_str":"97721124","source":"<a href="http://www.flight.co.jp/iPhone/TweetMe/" rel="nofollow">TweetMe for iPhone</a>"},{"from_user_id_str":"149872179","profile_image_url":"http://a0.twimg.com/profile_images/1145770150/Winter11_normal.jpg","created_at":"Fri, 25 Feb 2011 17:39:31 +0000","from_user":"xmyyyxx","id_str":"41190566951653376","metadata":{"result_type":"recent"},"to_user_id":95069405,"text":"@rindofu \u653b\u7565\u672c\u3042\u308c\u3070\u3044\u3044\u306e\u306b\u3063\u3066\u601d\u3044\u307e\u3059(T\u03c9T)/~~~ \u79c1\u3082\u76f4\u3057\u305f\u3044\u3068\u3053\u3044\u3063\u3071\u3044\u3060\u3051\u3069\u3001\u3042\u306860\u5e74\u304f\u3089\u3044\u3044\u304d\u3089\u308c\u308b\u306f\u305a\u3060\u3057\u3001\u306e\u3093\u3073\u308a\u76f4\u308c\u3070\u3044\u3044\u306a\u3042 \u304a\u3084\u3059\u307f\u3067\u3059^^\uff01\u308a\u3093\u3055\u3093\u3068twitter\u3067\u4ef2\u826f\u304f\u306a\u308c\u3066\u3088\u304b\u3063\u305f\u3067\u3059\u3063","id":41190566951653376,"from_user_id":149872179,"to_user":"rindofu","geo":null,"iso_language_code":"ja","to_user_id_str":"95069405","source":"<a href="http://twtr.jp" rel="nofollow">Keitai Web</a>"},{"from_user_id_str":"105579892","profile_image_url":"http://a0.twimg.com/profile_images/1212950455/love_happy_pink_normal.jpg","created_at":"Fri, 25 Feb 2011 17:39:30 +0000","from_user":"love_happy_pink","id_str":"41190566494601216","metadata":{"result_type":"recent"},"to_user_id":null,"text":"\u305d\u308c\u898b\u305f\u3044\u306a\u266aRT @kazukt \u3046\u308b\u304a\u307c\u7d75\u3001\u4ed6\u306e\u4eba\u306e\u3082\u898b\u3066\u3044\u305f\u3089\u3084\u305f\u3089\u30de\u30f3\u30ac\u306e\u30ad\u30e3\u30e9\u30af\u30bf\u30fc\u3067\u3080\u3061\u3083\u304f\u3061\u3083\u4e0a\u624b\u3044\u4eba\u304c\uff01\u2026\u3068\u3001\u30d7\u30ed\u30d5\u30a3\u30fc\u30eb\u898b\u305f\u3089\u3001\u306a\u3093\u3068\u3054\u672c\u4eba\u304c\u66f8\u3044\u3066\u3044\u3089\u3063\u3057\u3083\u3063\u305f\u3002Twitter\u3063\u3066\u30b9\u30b4\u30a4\u308f\u3002","id":41190566494601216,"from_user_id":105579892,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://www.nibirutech.com/" rel="nofollow">TwitBird iPad</a>"},{"from_user_id_str":"16996368","profile_image_url":"http://a0.twimg.com/profile_images/1198892387/pochi_normal.jpg","created_at":"Fri, 25 Feb 2011 17:39:30 +0000","from_user":"HyoYoshikawa","id_str":"41190564187611136","metadata":{"result_type":"recent"},"to_user_id":1800565,"text":"@shinichiro_beck \u73fe\u5730\u304b\u3089\u306a\u3089\u826f\u304f\u3066\u4ed6\u306e\u5730\u57df\u304b\u3089\u3060\u4f59\u8a08\u306a\u3089\u3001\u4f55\u306e\u305f\u3081\u306bTwitter\u304c\u3042\u308b\u306e\u304b\u308f\u304b\u3089\u306a\u3044\u3088\u3002\u3044\u307e\u8d77\u304d\u3066\u308b\u3053\u3068\u306e\u8aac\u660e\u3082\u3064\u304b\u306a\u3044\u3002\u30a2\u30eb\u30b8\u30e3\u30b8\u30fc\u30e9\u304c\u4f1d\u3048\u3066\u308b\u3053\u3068\u304c\u5168\u3066\u3058\u3083\u306a\u3044\u3057\u3001\u65e5\u672c\u306eTV\u306f\u4f1d\u3048\u306a\u3044\u3067\u3057\u3087\u3046\u3002\u77e5\u308a\u305f\u304c\u3063\u3066\u308b\u4eba\u3082\u305f\u304f\u3055\u3093\u3044\u308b\u3002","id":41190564187611136,"from_user_id":16996368,"to_user":"shinichiro_beck","geo":null,"iso_language_code":"ja","to_user_id_str":"1800565","source":"<a href="http://www.hootsuite.com" rel="nofollow">HootSuite</a>"},{"from_user_id_str":"119070802","profile_image_url":"http://a2.twimg.com/profile_images/1229773005/346d8435099798113a1326e1ba4949ee_normal.jpeg","created_at":"Fri, 25 Feb 2011 17:39:25 +0000","from_user":"takotako726","id_str":"41190545439207424","metadata":{"result_type":"recent"},"to_user_id":null,"text":"\u9b54\u6cd5\u5c11\u5973\u307e\u3069\u304b\u30de\u30ae\u30ab\u306e\u53cd\u97ff\u304ctwitter\u3067\u306f\u3093\u3071\u306d\u3048\u4ef6\u3002","id":41190545439207424,"from_user_id":119070802,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://z.twipple.jp/" rel="nofollow">\u3064\u3044\u3063\u3077\u308b/twipple</a>"},{"from_user_id_str":"165695316","profile_image_url":"http://a1.twimg.com/profile_images/681748782/ring_normal.jpg","created_at":"Fri, 25 Feb 2011 17:39:21 +0000","from_user":"pandora_shotbar","id_str":"41190526447390720","metadata":{"result_type":"recent"},"to_user_id":null,"text":"\u300e\u30b7\u30e7\u30c3\u30c8\u30d0\u30fc\u3000\u30d1\u30f3\u30c9\u30e9\u3000\u30c4\u30a4\u30c3\u30bf\u30fc\u306e\u3064\u3076\u3084\u304d\u300f\u30b7\u30e7\u30c3\u30c8\u30d0\u30fc\u3000\u30d1\u30f3\u30c9\u30e9\u3000\u30c4\u30a4\u30c3\u30bf\u30fc\u306e\u3064\u2026\uff5chttp://pandora-twitter.seesaa.net/article/187809936.html","id":41190526447390720,"from_user_id":165695316,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://blog.seesaa.jp/" rel="nofollow">SeesaaBlog</a>"},{"from_user_id_str":"88862311","profile_image_url":"http://a2.twimg.com/profile_images/1182243698/161113_100001897885617_169366_q_normal.jpg","created_at":"Fri, 25 Feb 2011 17:39:16 +0000","from_user":"amebaguide","id_str":"41190504926416896","metadata":{"result_type":"recent"},"to_user_id":null,"text":"\u300e\u30a2\u30e1\u30d6\u30ed\u653b\u7565\u30ac\u30a4\u30c9\u306e\u30c4\u30a4\u30c3\u30bf\u30fc\u306e\u3064\u3076\u3084\u304d\u300f\u30d6\u30ed\u30b0\u306e\u653b\u7565\u3000\u30c4\u30a4\u30c3\u30bf\u30fc\u306e\u3064\u3076\u3084\u304d\u96c6\uff5chttp://accessup-twitter.seesaa.net/article/187809931.html","id":41190504926416896,"from_user_id":88862311,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://blog.seesaa.jp/" rel="nofollow">SeesaaBlog</a>"},{"from_user_id_str":"186895007","profile_image_url":"http://a2.twimg.com/profile_images/1229610799/image_normal.jpg","created_at":"Fri, 25 Feb 2011 17:39:11 +0000","from_user":"zizikt","id_str":"41190486123356161","metadata":{"result_type":"recent"},"to_user_id":null,"text":"\u3053\u308c\u306f\u500b\u4eba\u7684\u306b\u306f\u91cd\u5b9d\u3067\u3059\u3002\n\u25c6iPhone&iPad\u5411\u3051Twitter\u30a2\u30d7\u30ea\u300c\u3064\u3044\u3063\u3077\u308b\u300d\u306bEvernote\u3068\u306e\u9023\u643a\u6a5f\u80fd\u3092\u8ffd\u52a0 \nhttp://bit.ly/hPf44u","id":41190486123356161,"from_user_id":186895007,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://twitter.com/" rel="nofollow">Twitter for iPhone</a>"},{"from_user_id_str":"132320738","profile_image_url":"http://a3.twimg.com/profile_images/1229760475/image_normal.jpg","created_at":"Fri, 25 Feb 2011 17:39:04 +0000","from_user":"faina_","id_str":"41190453592334336","metadata":{"result_type":"recent"},"to_user_id":167894537,"text":"@gjmorley \u30e2\u30fc\u30ea\u30fc\u3055\u3093\u306e\u7ffb\u8a33\u306e\u8a00\u8449\u306e\u30bb\u30f3\u30b9\u304c\u3059\u304d\u3067\u3059\u3002\u305d\u3057\u3066\u3001Twitter\u3067\u77e5\u308b\u3001\u73fe\u5730\u306e\u4eba\u306e\u76ee\u306e\u529b\u3084\u3001\u60c5\u5831\u3092\u4f1d\u3048\u3066\u304f\u308c\u308b\u7686\u3055\u3093\u306e\u60c5\u71b1\u306b\u611f\u52d5\u3057\u3066\u3044\u307e\u3059\u3002\u611f\u52d5\u3059\u308b\u3063\u3066\u3059\u3054\u3044\u30a8\u30cd\u30eb\u30ae\u30fc\u3067\u3059\uff01\uff01","id":41190453592334336,"from_user_id":132320738,"to_user":"gjmorley","geo":null,"iso_language_code":"ja","to_user_id_str":"167894537","source":"<a href="http://twitter.com/" rel="nofollow">Twitter for iPhone</a>"},{"from_user_id_str":"24870552","profile_image_url":"http://a3.twimg.com/profile_images/907130634/4_normal.jpg","created_at":"Fri, 25 Feb 2011 17:39:03 +0000","from_user":"tana1192","id_str":"41190450480021504","metadata":{"result_type":"recent"},"to_user_id":null,"text":"\u500b\u4eba\u7684\u306b\u306f\u3001\u30bf\u30b0\u5f3e\u304d\u3059\u308c\u3070\u3044\u3044\uff08\u5f3e\u3051\u308b\u30c4\u30fc\u30eb\u3092\u4f7f\u3063\u3066Twitter\u3092\u3059\u308c\u3070\u3044\u3044\uff09\u3068\u601d\u3046\u3093\u3060\u3051\u3069\u306a\u3042\u3002\u307f\u3093\u306a\u305d\u308c\u306a\u308a\u306bTwitter\u3084\u308b\u4eba\u3060\u3057\u3001\u30c4\u30fc\u30eb\u9078\u3073\u304f\u3089\u3044\u5e45\u3092\u6301\u3063\u3066\u3084\u3063\u3066\u3082\u3002 \u307e\u3042\u3001\u4ffa\u30a2\u30cb\u30e1\u306f\u89b3\u308b\u89b3\u308b\u8a50\u6b3a\u3059\u308b\u3060\u3051\u306e\u4eba\u3060\u304b\u3089\u95a2\u4fc2\u306a\u3044\u3093\u3060\u3051\u3069\u3082\uff57\uff57\u5b9f\u6cc1\u306f\u697d\u3057\u305d\u3046\u306b\u898b\u3048\u308b\u3088\u3002","id":41190450480021504,"from_user_id":24870552,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://sourceforge.jp/projects/tween/wiki/FrontPage" rel="nofollow">Tween</a>"},{"from_user_id_str":"58509646","profile_image_url":"http://a3.twimg.com/sticky/default_profile_images/default_profile_2_normal.png","created_at":"Fri, 25 Feb 2011 17:39:02 +0000","from_user":"kakuyas","id_str":"41190446663344128","metadata":{"result_type":"recent"},"to_user_id":107076877,"text":"@Dayspool \u6df1\u591c\uff12\uff19\u6642\u304f\u3089\u3044\u307e\u3067\u306f\u6bce\u65e5\u55b6\u696d\u3057\u3066\u308b\u306e\u3067\u3001twitter\u3001\u30e1\u30c3\u30bb\u3001PS3\u306a\u3069\u3067\u3088\u3093\u3067\u3051\u308c\u3002\u3053\u3063\u3061\u304b\u3089\u58f0\u304b\u3051\u308b\u3053\u3068\u3082\u3042\u308b\u304b\u3082\u3060\u304c\uff57","id":41190446663344128,"from_user_id":58509646,"to_user":"Dayspool","geo":null,"iso_language_code":"ja","to_user_id_str":"107076877","source":"<a href="http://cheebow.info/chemt/archives/2007/04/twitterwindowst.html" rel="nofollow">Twit for Windows</a>"},{"from_user_id_str":"149128527","profile_image_url":"http://a2.twimg.com/profile_images/1254922702/image_normal.jpg","created_at":"Fri, 25 Feb 2011 17:39:00 +0000","from_user":"uni13yoki","id_str":"41190437087748096","metadata":{"result_type":"recent"},"to_user_id":119468594,"text":"@kuro_wr84 \u304a\u308c\u3068\u304a\u524d\u3067Twitter\u3067\u4f1a\u8a71\u3057\u305f\u3089\u3001\u5927\u5909\u306a\u3053\u3068\u306b\u306a\u308b\u306a","id":41190437087748096,"from_user_id":149128527,"to_user":"kuro_wr84","geo":null,"iso_language_code":"ja","to_user_id_str":"119468594","source":"<a href="http://twitter.com/" rel="nofollow">Twitter for iPhone</a>"},{"from_user_id_str":"18670595","profile_image_url":"http://a2.twimg.com/profile_images/1250674062/ProfilePhoto_normal.png","created_at":"Fri, 25 Feb 2011 17:38:59 +0000","from_user":"nyuuuuun","id_str":"41190436450222080","metadata":{"result_type":"recent"},"to_user_id":null,"text":"\u3078\u30fc\u3053\u3093\u306a\u306b\u3088\u304f\u4f3c\u308b\u3053\u3068\u3082\u3042\u308b\u3093\u3060\u30fc\nhttp://twitter.com/Re_44/status/35943233016168448\nhttp://twitter.com/3510_misaka/status/36122114821988352","id":41190436450222080,"from_user_id":18670595,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://twitter.com/">web</a>"},{"from_user_id_str":"96267603","profile_image_url":"http://a3.twimg.com/profile_images/1245253473/DSiLL3_normal.jpg","created_at":"Fri, 25 Feb 2011 17:38:59 +0000","from_user":"arivis","id_str":"41190433119940608","metadata":{"result_type":"recent"},"to_user_id":null,"text":"http://twitter.com/#!/arivis/status/40636755380142080 \u306a\u3093\u3064\u3046\u304b\u3053\u308c\u3067\u8d64\u3063\u3066\u306e\u3082\u3061\u3087\u3063\u3068\u3042\u308c\u3063\u3059\u306d\u3002\u305d\u3057\u3066\u4e88\u671f\u3057\u3066\u3044\u305f\u304b\u306e\u3088\u3046\u3060","id":41190433119940608,"from_user_id":96267603,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://www.tweetdeck.com" rel="nofollow">TweetDeck</a>"},{"from_user_id_str":"148097776","profile_image_url":"http://a3.twimg.com/profile_images/1166904064/broken-heart_normal.png","created_at":"Fri, 25 Feb 2011 17:38:56 +0000","from_user":"ReajuBreaker_A","id_str":"41190422135058432","metadata":{"result_type":"recent"},"to_user_id":null,"text":"\u672c\u57a2\u30d5\u30a9\u30ed\u30fc\u3088\u308d\u3057\u304f\u3067\u3059\u2192 http://twitter.com/ReajuBreaker \uff08\uff20\u3060\u3068\u30ea\u30d7\u30e9\u30a4\u304c\u57cb\u307e\u308b\u305f\u3081\u3001URL\u306b\u3057\u3066\u3042\u308a\u307e\u3059\uff09","id":41190422135058432,"from_user_id":148097776,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://www.twitter.com/ReajuBreaker" rel="nofollow">\u73fe\u5145\u6bba\u3057\u306e\u7121\u4eba\u9023\u545f\uff1c\u30aa\u30fc\u30c8\u30c4\u30a4\u30fc\u30c8\uff1e</a>"},{"from_user_id_str":"59711654","profile_image_url":"http://a2.twimg.com/profile_images/416212928/flowers-06-1_normal.jpg","created_at":"Fri, 25 Feb 2011 17:38:56 +0000","from_user":"agamo45","id_str":"41190421522546688","metadata":{"result_type":"recent"},"to_user_id":null,"text":"RT @ebizo66: \u30ea\u30d3\u30a2\u30fb\u30c8\u30ea\u30dd\u30ea\u306eTw\uff1a\u6551\u6025\u8eca\u304c\u6765\u305f\u304c\u3001\u8ca0\u50b7\u8005\u3092\u8eca\u5185\u3067\u6bba\u5bb3\u3057\u3066\u3044\u305f\u3001\u3068\u3002\uff08\u6ec5\u8336\u82e6\u8336\u3060\uff01\uff09http://ow.ly/43pQ2 #libjp","id":41190421522546688,"from_user_id":59711654,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://www.hootsuite.com" rel="nofollow">HootSuite</a>"},{"from_user_id_str":"145311373","profile_image_url":"http://a3.twimg.com/profile_images/1187802576/a_gam_02_normal.png","created_at":"Fri, 25 Feb 2011 17:38:55 +0000","from_user":"nogic1008","id_str":"41190418141937664","metadata":{"result_type":"recent"},"to_user_id":88117317,"text":"@runasoru \u307e\u3042\u5acc\u306a\u3089\u6df1\u591c\u5e2f\u306bTwitter\u898b\u306a\u304d\u3083\u3044\u3044\u3060\u3051\u3067\u3059\u304b\u3089\u306d\u30fc \u30103/19BDM\u30aa\u30d5http://twvt.us/bdoff_kansai\u3011","id":41190418141937664,"from_user_id":145311373,"to_user":"runasoru","geo":null,"iso_language_code":"ja","to_user_id_str":"88117317","source":"<a href="http://sourceforge.jp/projects/tween/wiki/FrontPage" rel="nofollow">Tween</a>"},{"from_user_id_str":"195851300","profile_image_url":"http://a2.twimg.com/profile_images/1124572815/be7b4c0a06cb60e8_normal.jpg","created_at":"Fri, 25 Feb 2011 17:38:49 +0000","from_user":"LoveLAscrewDoll","id_str":"41190391147540480","metadata":{"result_type":"recent"},"to_user_id":null,"text":"RT @jp_mjp: SCREW TV SHOW Vol.6\u306e\u653e\u9001\u304c\u7121\u4e8b\u306b\u7d42\u4e86\u3044\u305f\u3057\u307e\u3057\u305f\u3002\u3054\u89a7\u9802\u304d\u3042\u308a\u304c\u3068\u3046\u3054\u3056\u3044\u307e\u3057\u305f\uff01\u6b21\u56de\u653e\u9001\u306f3\u670818\u65e5(\u91d1)\u3067\u3059\u3002\u8996\u8074\u8005\u30d7\u30ec\u30bc\u30f3\u30c8\u306e\u8a73\u7d30\u306f\u5f8c\u65e5MJP\u3067\u304a\u77e5\u3089\u305b\u3044\u305f\u3057\u307e\u3059\u3002\u305d\u306e\u969b\u306b\u306f\u3001\u3053\u306eTwitter\u3067\u3082\u304a\u77e5\u3089\u305b\u3044\u305f\u3057\u307e\u3059\u306e\u3067\u3001\u304a\u697d\u3057\u307f\u306b\uff01#SCREWTV","id":41190391147540480,"from_user_id":195851300,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://z.twipple.jp/" rel="nofollow">\u3064\u3044\u3063\u3077\u308b/twipple</a>"},{"from_user_id_str":"178045354","profile_image_url":"http://a0.twimg.com/profile_images/1214479381/154722_10100141954893059_808622_55276626_7445050_n_normal.jpg","created_at":"Fri, 25 Feb 2011 17:38:48 +0000","from_user":"ChuriSta_gt","id_str":"41190389549510656","metadata":{"result_type":"recent"},"to_user_id":null,"text":"\u3053\u3053\u4e00\u9031\u9593Twitter\u304c\u3084\u305f\u3089\u697d\u3057\u3044\u306e\u3067\u3059\u3051\u3069\u30fc\u30fc\u30fc\uff01\u306b\u3072\u3072\u3063\u7b11","id":41190389549510656,"from_user_id":178045354,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://twipple.jp/" rel="nofollow">\u3064\u3044\u3063\u3077\u308b for iPhone</a>"},{"from_user_id_str":"50592111","profile_image_url":"http://a0.twimg.com/profile_images/1252176582/lFjpi_normal.jpg","created_at":"Fri, 25 Feb 2011 17:38:48 +0000","from_user":"crowNeko","id_str":"41190387271864320","metadata":{"result_type":"recent"},"to_user_id":null,"text":"\u30a8\u30ed\u30b2\u30d7\u30ec\u30a4\u3057\u306a\u304c\u3089\u307e\u3069\u30de\u30aeTL\u3092\u898b\u306a\u3044\u3088\u3046\u306b\u534a\u76ee\u306b\u306a\u308a\u306a\u304c\u3089Twitter\u3057\u3066\u308b\u6df1\u591c2\u6642\u534a\u3002","id":41190387271864320,"from_user_id":50592111,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://stone.com/Twittelator" rel="nofollow">Twittelator</a>"},{"from_user_id_str":"7141467","profile_image_url":"http://a3.twimg.com/profile_images/1198540741/icon12912579345276_normal.jpg","created_at":"Fri, 25 Feb 2011 17:38:40 +0000","from_user":"hina_geshi","id_str":"41190355961380864","metadata":{"result_type":"recent"},"to_user_id":null,"text":"\u7d50\u5c40\u30cd\u30bf\u30d0\u30ec\u3059\u3093\u306a\u3063\u3066\u8a00\u3046\u65b9\u304c\u30a2\u30ec\u3060\u3088\u306d\u3001\u3057\u306a\u3044\u308f\u3051\u7121\u3044\u3058\u3083\u306a\u3044\u8133\u5185\u5782\u308c\u6d41\u3057\u304cTwitter\u306a\u3093\u3060\u304b\u3089\u3055","id":41190355961380864,"from_user_id":7141467,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://projects.playwell.jp/go/Saezuri" rel="nofollow">Saezuri</a>"},{"from_user_id_str":"149608984","profile_image_url":"http://a0.twimg.com/profile_images/1205950885/090702_normal.jpg","created_at":"Fri, 25 Feb 2011 17:38:39 +0000","from_user":"Mr_Tsubaki","id_str":"41190349447774208","metadata":{"result_type":"recent"},"to_user_id":null,"text":"\u307e\u3069\u304b\u306fTwitter\u5408\u308f\u305b\u3066\uff11\u6642\u9593\u306f\u697d\u3057\u3044","id":41190349447774208,"from_user_id":149608984,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://z.twipple.jp/" rel="nofollow">\u3064\u3044\u3063\u3077\u308b/twipple</a>"},{"from_user_id_str":"122271550","profile_image_url":"http://a0.twimg.com/profile_images/961936499/neoneko_bot5jpg_____normal.jpg","created_at":"Fri, 25 Feb 2011 17:38:39 +0000","from_user":"neoneko_bot5","id_str":"41190348726345728","metadata":{"result_type":"recent"},"to_user_id":null,"text":"\u3010\u30c6\u30b9\u30c8\uff1a23\u3011\u4eca\u65e5\u304b\u3089\u5ba3\u4f1d\u958b\u59cb\u2606\u306d\u304a\u306d\u3053\u306eTwitter \u3067 EasyBottex\u3000\u3067\u304d\u308b\u307e\u3067\uff01\u2192http://neoneko.blog31.fc2.com/","id":41190348726345728,"from_user_id":122271550,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://www20.atpages.jp/neoneko/" rel="nofollow">neoneko_bot5</a>"},{"from_user_id_str":"127069188","profile_image_url":"http://a3.twimg.com/sticky/default_profile_images/default_profile_6_normal.png","created_at":"Fri, 25 Feb 2011 17:38:37 +0000","from_user":"MYCHEBOT","id_str":"41190340908163074","metadata":{"result_type":"recent"},"to_user_id":null,"text":"\u30eb\u30d5\u3055\u3093\u304c\u914d\u4fe1\u3092\u7d42\u4e86\u3057\u307e\u3057\u305f\uff01/ http://777labo.com/mychecker/view/745.php / \u30c8\u30d4\u30c3\u30af:XSplit\u30c6\u30b9\u30c8\u3000twitter\u2192http://twitter.com/rukh01","id":41190340908163074,"from_user_id":127069188,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://777labo.com/mychecker/" rel="nofollow">MYCHEBOT</a>"},{"from_user_id_str":"107626142","profile_image_url":"http://a1.twimg.com/profile_images/1104968421/SuperMaika1_normal.jpg","created_at":"Fri, 25 Feb 2011 17:38:34 +0000","from_user":"MaikaPaPa","id_str":"41190328614666240","metadata":{"result_type":"recent"},"to_user_id":null,"text":"75\u5e74\u524d\u306e\u4eca\u65e52\u670826\u65e5\u672a\u660e\u3001\u82e5\u304d\u9752\u5e74\u5c06\u6821\u3089\u304c\u653f\u6cbb\u8150\u6557\u3068\u8fb2\u6751\u306e\u56f0\u7aae\u306b\u5bfe\u3057\u3066\u6c7a\u8d77\u3057\u307e\u3057\u305f\u3002\u3082\u3061\u308d\u3093\u5f53\u6642\u306fTwitter\u3082FB\u3082\u3001\u307e\u305f\u5f53\u7136\u306a\u304c\u3089Internet\u3082\u3042\u308a\u307e\u305b\u3093\u3067\u3057\u305f\u3002\u4e00\u65b9\u3001\u30c1\u30e5\u30cb\u30b8\u30a2\u3001\u30a8\u30b8\u30d7\u30c8\u3001\u4e2d\u6771\u306b\u5e83\u304c\u308b\u53cd\u653f\u5e9c\u30c7\u30e2\u3068\u5f37\u6a29\u4f53\u5236\u306e\u5d29\u58ca\u3002\u73fe\u5728\u306e\u65e5\u672c\u3067\u306f\u8003\u3048\u3089\u308c\u306a\u3044\u3053\u3068\u3067\u3059\u3002","id":41190328614666240,"from_user_id":107626142,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://www.tweetdeck.com" rel="nofollow">TweetDeck</a>"},{"from_user_id_str":"11111695","profile_image_url":"http://a1.twimg.com/sticky/default_profile_images/default_profile_0_normal.png","created_at":"Fri, 25 Feb 2011 17:38:28 +0000","from_user":"kumatchipooh","id_str":"41190306145775617","metadata":{"result_type":"recent"},"to_user_id":null,"text":"RT @inosenaoki: \u306a\u308b\u307b\u3069\u306d\u3002 RT @dansrmz @inosenaoki \u3053\u3061\u3089\u304c\u30bd\u30d5\u30c8\u30d0\u30f3\u30af\u526f\u793e\u9577\u306e\u677e\u672c\u5fb9\u4e09\u3055\u3093\u306e\u3001Twitter\u306b\u95a2\u3059\u308b\u8ad6\u8003\u3067\u3059\u3002 \u25b6 "Twitter\u306e2\u30c1\u30e3\u30f3\u30cd\u30eb\u5316\u306f\u9632\u6b62\u51fa\u6765\u308b\u304b" http://t.co/Mwzb8Zf","id":41190306145775617,"from_user_id":11111695,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://twitter.com/">web</a>"},{"from_user_id_str":"212161909","profile_image_url":"http://a1.twimg.com/profile_images/1252895790/natm01_normal.gif","created_at":"Fri, 25 Feb 2011 17:38:28 +0000","from_user":"n34hitman","id_str":"41190303830511616","metadata":{"result_type":"recent"},"to_user_id":null,"text":"Twitter\u30fb\u30d6\u30ed\u30b0\u30a2\u30d5\u30a3\u30ea\u30a8\u30a4\u30c8\u81ea\u52d5\u6295.... http://goo.gl/a4RHB 4054","id":41190303830511616,"from_user_id":212161909,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://twibow.net/" rel="nofollow">Twibow</a>"},{"from_user_id_str":"105945593","profile_image_url":"http://a2.twimg.com/sticky/default_profile_images/default_profile_5_normal.png","created_at":"Fri, 25 Feb 2011 17:38:24 +0000","from_user":"nakano_bot","id_str":"41190285710983168","metadata":{"result_type":"recent"},"to_user_id":null,"text":"\u3053\u306ebot\u306f\u4e0d\u52d5\u7523\u4f1a\u793e\u69d8\u5411\u3051\u306e\u4e0d\u52d5\u7523\u30dd\u30fc\u30bf\u30eb\u30b5\u30a4\u30c8\u3078\u306e\u4e00\u62ec\u8ee2\u9001\uff0bTwitter\u7121\u6599\u8ee2\u9001\u30b5\u30fc\u30d3\u30b9\u306b\u3088\u308a\u3064\u3076\u3084\u304d\u307e\u3059\u3002\u3054\u5229\u7528\u306b\u306a\u308a\u305f\u3044\u5834\u5408\u306f http://bit.ly/demey0 \u306b\u304a\u6c17\u8efd\u306b\u304a\u554f\u3044\u5408\u308f\u305b\u4e0b\u3055\u3044\u3002","id":41190285710983168,"from_user_id":105945593,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://www.teramax.jp/aboutus.html" rel="nofollow">tmxbot</a>"},{"from_user_id_str":"170904226","profile_image_url":"http://a2.twimg.com/profile_images/1249020397/1789kb_normal.jpg","created_at":"Fri, 25 Feb 2011 17:38:21 +0000","from_user":"1789kb","id_str":"41190274428305408","metadata":{"result_type":"recent"},"to_user_id":null,"text":"\u3068\u308a\u3042\u3048\u305a\u4eca\u56de\u521d\u3081\u3066\u30ea\u30a2\u30eb\u30bf\u30a4\u30e0\u3067\u898b\u3066\u308f\u304b\u3063\u305f\u306e\u306f\u3001QB\u306f\u5168\u8eab\u304c\u30a2\u30f3\u30d1\u30f3\u30bf\u30a4\u30d7\u3060\u3068\u3044\u3046\u3053\u3068\u3068\u3001\u307e\u3069\u30de\u30ae\u7d42\u4e86\u5f8c\u306eTwitter\u306e\u3056\u308f\u3064\u304d\u304c\u3059\u3054\u3044\u3068\u3044\u3046\u3053\u3068","id":41190274428305408,"from_user_id":170904226,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://www.echofon.com/" rel="nofollow">Echofon</a>"},{"from_user_id_str":"166169644","profile_image_url":"http://a1.twimg.com/profile_images/1217017679/image_normal.jpg","created_at":"Fri, 25 Feb 2011 17:38:18 +0000","from_user":"Okkkkkkkkkkun","id_str":"41190262420017152","metadata":{"result_type":"recent"},"to_user_id":null,"text":"\u3063\u3066Twitter\u3067\u3064\u3076\u3084\u304f\u81ea\u5206\u3082\u76f8\u5f53\u5c0f\u3055\u3044\u306a\u3002","id":41190262420017152,"from_user_id":166169644,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://twitter.com/" rel="nofollow">Twitter for iPhone</a>"},{"from_user_id_str":"196623456","profile_image_url":"http://a3.twimg.com/profile_images/1219076661/image_normal.jpg","created_at":"Fri, 25 Feb 2011 17:38:06 +0000","from_user":"NoMoneyClub","id_str":"41190213342601216","metadata":{"result_type":"recent"},"to_user_id":195462431,"text":"@yosal15 \nTwitter\u3084\u3063\u3066\u308b\u3089\u3057\u3044\u3002\u3051\u3069\u3001\u898b\u3064\u304b\u3089\u306a\u3044\u3002","id":41190213342601216,"from_user_id":196623456,"to_user":"yosal15","geo":null,"iso_language_code":"ja","to_user_id_str":"195462431","source":"<a href="http://twitter.com/" rel="nofollow">Twitter for iPhone</a>"},{"from_user_id_str":"126984048","profile_image_url":"http://a3.twimg.com/profile_images/1254579571/zipyaru-20090829-23-0012_normal.png","created_at":"Fri, 25 Feb 2011 17:38:02 +0000","from_user":"minaduki_naduki","id_str":"41190196418584576","metadata":{"result_type":"recent"},"to_user_id":null,"text":"\u203b\u30e1\u30fc\u30eb\u3067\u5973\u306e\u5b50\u53e3\u8aac\u304f\u306e\u306b\u5fd9\u3057\u3044\u3093\u3060\u305d\u3046\u3067\u3059\u3000\u307e\u3058\u3058\u3054\u308d RT @yowano_k: \u5fd9\u3057\u304f\u3066\u3082Twitter\u306b\u9854\u3092\u51fa\u3057\u305f\u304f\u306a\u308b\u50d5\u30a7\u2026\u2026","id":41190196418584576,"from_user_id":126984048,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://seesmic.com/seesmic_desktop/sd2" rel="nofollow">Seesmic Desktop</a>"},{"from_user_id_str":"200568705","profile_image_url":"http://a3.twimg.com/profile_images/1242179765/101230_1355_01_normal.jpg","created_at":"Fri, 25 Feb 2011 17:38:01 +0000","from_user":"hammerstrap","id_str":"41190190428979200","metadata":{"result_type":"recent"},"to_user_id":null,"text":"\u6628\u65e5\u91d1\u66dc\u65e5\u306f\u732e\u8840\u306b\u5f80\u304f\u3002\u4eca\u306e\u50d5\u306e\u4eba\u9593\u3068\u3057\u3066\u306e\u4fa1\u5024\u306f\u3001\u7cbe\u3005\u3053\u306e\u7a0b\u5ea6\u3002\u8179\u304c\u6e1b\u3063\u305f\u3002\u5374\u8aac\u3002twitter\u306e\u767e\u56db\u5341\u6587\u5b57\u306b\u82db\u3005\u3068\u3057\u3066\u3001\u4e00\u3064\u306e\u4eee\u8aac\u306b\u4fe1\u6191\u6027\u3092\u5f97\u308b\u3002\u6226\u6642\u4e0b\u306e\u7d19\u306e\u7d71\u5236\u3068\u3001\u4e2d\u5cf6\u6566\u306e\u6587\u7ae0\u306e\u95a2\u4fc2\u6027\u3002\u73fe\u5728\u30a6\u30a7\u30d6\u30ed\u30b0\u306b\u3001\u7e8f\u3081\u3066\u3044\u308b\u6700\u4e2d\u3002\u8fd1\u65e5\u516c\u958b\u4e88\u5b9a\u3002","id":41190190428979200,"from_user_id":200568705,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://twitter.com/">web</a>"},{"from_user_id_str":"164970427","profile_image_url":"http://a0.twimg.com/profile_images/1227176662/9192b021ef85ce9902c28955f86e604b_normal.jpg","created_at":"Fri, 25 Feb 2011 17:37:59 +0000","from_user":"syuigetsuIT","id_str":"41190184041197569","metadata":{"result_type":"recent"},"to_user_id":141926331,"text":"@iliad_tga \u30a4\u30ea\u30a2\u30b9\u3055\u3093\u304c\u305d\u306e\u8fba\u7406\u89e3\u306e\u3042\u308b\u3053\u3068\u306f\u5206\u304b\u3063\u3066\u307e\u3059\uff57\u3000\u30cd\u30bf\u30d0\u30ec\u4e91\u3005\u306ftwitter\u306e\u6c7a\u5b9a\u7684\u306a\u6b20\u70b9\u3060\u3068\u601d\u3044\u307e\u3059\u306d\u3047\u3002","id":41190184041197569,"from_user_id":164970427,"to_user":"iliad_tga","geo":null,"iso_language_code":"ja","to_user_id_str":"141926331","source":"<a href="http://twitter.com/">web</a>"},{"from_user_id_str":"94526795","profile_image_url":"http://a0.twimg.com/profile_images/679411954/akb48_in_normal.jpg","created_at":"Fri, 25 Feb 2011 17:37:56 +0000","from_user":"akb48_in","id_str":"41190171248431104","metadata":{"result_type":"recent"},"to_user_id":null,"text":"AKB48\u67cf\u6728\u7531\u7d00 \u304a\u75b2\u308c\u69d8\u3002: \n\u3053\u3093\u3070\u3093\u306f(^O^)\uff0f\u266a\n\u3000\n\u3000\n\u3000\n\u4eca\u65e5\u306e\u516c\u6f14\u697d\u3057\u304b\u3063\u305f\u301c\n\u3000\n\u3000\n\u4e45\u3057\u3076\u308a\u3067\u7dca\u5f35\u3057\u305f\u3051\u3069\u3001\u306f\u3058\u3051\u307e\u304f\u3063\u305f\u305c\u3043\uff01\uff01\n\u3000\n\u3000\n\u3000\nMC\u306f\u565b\u307f\u307e\u304f\u308a\u306e\u30c6\u30f3\u30d1\u308a\u307e\u304f... http://bit.ly/ie8bEa akb48 twitter","id":41190171248431104,"from_user_id":94526795,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://twitterfeed.com" rel="nofollow">twitterfeed</a>"},{"from_user_id_str":"222270374","profile_image_url":"http://a3.twimg.com/profile_images/1250946143/P1040062_normal.jpg","created_at":"Fri, 25 Feb 2011 17:37:53 +0000","from_user":"chrxpac","id_str":"41190158455943168","metadata":{"result_type":"recent"},"to_user_id":null,"text":"\u3010\u5b9a\u671f\u3011Twitter\u306f\uff8a\uff9f\uff7f\uff7a\uff9d\u304b\u3089\u3057\u304b\u3067\u304d\u306a\u3044\u306e\u3067\uff98\uff8c\uff9f\u8fd4\u3057\u304c\u9045\u304f\u306a\u308a\u307e\u3059(\u00b4\u30fb\u03c9\u30fb\uff40)\u3054\u4e86\u627f\u4e0b\u3055\u3044!!","id":41190158455943168,"from_user_id":222270374,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://twittbot.net/" rel="nofollow">twittbot.net</a>"},{"from_user_id_str":"64009258","profile_image_url":"http://a2.twimg.com/profile_images/1154025023/Mixi___normal.jpg","created_at":"Fri, 25 Feb 2011 17:37:52 +0000","from_user":"Tatsuyuko","id_str":"41190153447944192","metadata":{"result_type":"recent"},"to_user_id":null,"text":"\u4f01\u696d\u304c\u5c31\u6d3b\u751f\u306bFacebook\u3092\u4f7f\u3063\u3066\u7533\u8acb\u305b\u3088\u3068\u3044\u3044\u3001\u4f01\u696d\u304cFacebook\u3092\u4f7f\u3048\u3068\u4f01\u696d\u304c\u8a00\u3063\u3066\u304d\u305f\u308a\u3059\u308c\u3070\u305d\u308c\u3069\u3053\u308d\u3058\u3083\u306a\u3044\u304b\u3068\u3002\u5c11\u306a\u304f\u3068\u3082\u5c31\u6d3b\u3067Twitter\u306e\u8a00\u52d5\u3084\u30d5\u30a9\u30ed\u30ef\u30fc\u3092\u8abf\u67fb\u3059\u308b\u4f01\u696d\u306f\u304b\u306a\u308a\u591a\u3044\u3067\u3059 RT @Isshee: \u4f01\u696d\u3067\u3082\u540c\u3058\u3067\u3057\u3087 RT","id":41190153447944192,"from_user_id":64009258,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://sourceforge.jp/projects/tween/wiki/FrontPage" rel="nofollow">Tween</a>"},{"from_user_id_str":"105145175","profile_image_url":"http://static.twitter.com/images/default_profile_normal.png","created_at":"Fri, 25 Feb 2011 17:37:49 +0000","from_user":"snao813","id_str":"41190141703753728","metadata":{"result_type":"recent"},"to_user_id":null,"text":"RT @yumisaiki: \u795e\u69d8\u306f\u672c\u5f53\u306b\u4eba\u9593\u3092\u3059\u3070\u3089\u3057\u3044\u30d0\u30e9\u30f3\u30b9\u3067\u914d\u7f6e\u3057\u3066\u304a\u3089\u308c\u308b\u3002\u795d\u5cf6\u307f\u305f\u3044\u306a\u5c0f\u3055\u3044\u3068\u3053\u308d\u306b\u306a\u3093\u3067\u3053\u3093\u306a\u306b\u7acb\u6d3e\u306a\u4eba\u304c\u305f\u304f\u3055\u3093\u3044\u308b\u3093\u3060\u308d\u3046\u3002\u795e\u69d8\u3042\u308a\u304c\u3068\u3046\u3002\u672c\u5f53\u306b\u3042\u308a\u304c\u3068\u3046\u3002\u4eba\u9593\u3063\u3066\u3059\u3070\u3089\u3057\u3044\u3068\u601d\u3048\u305f\u3002twitter\u3082\u3042\u308a\u304c\u3068\u3046\u3002\u3000#kaminoseki","id":41190141703753728,"from_user_id":105145175,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://seesmic.com/seesmic_desktop/sd2" rel="nofollow">Seesmic Desktop</a>"},{"from_user_id_str":"203667204","profile_image_url":"http://a2.twimg.com/profile_images/1254664000/eve_blackcat_normal.jpg","created_at":"Fri, 25 Feb 2011 17:37:46 +0000","from_user":"eve_blackcat","id_str":"41190129292943361","metadata":{"result_type":"recent"},"to_user_id":146894340,"text":"@kuroiso02 \u3057\u308a\u3068\u308a\u3068\u304b\uff1f\n\u2026\u3067\u3082Twitter\u3060\u3068\u7d42\u308f\u3089\u306a\u304f\u306a\u308b\u30b1\u30c9\u2026","id":41190129292943361,"from_user_id":203667204,"to_user":"kuroiso02","geo":null,"iso_language_code":"ja","to_user_id_str":"146894340","source":"<a href="http://twipple.jp/" rel="nofollow">\u3064\u3044\u3063\u3077\u308b for iPhone</a>"},{"from_user_id_str":"6528403","profile_image_url":"http://a0.twimg.com/profile_images/1240591244/image_normal.jpg","created_at":"Fri, 25 Feb 2011 17:37:45 +0000","from_user":"sortiee","id_str":"41190125924917248","metadata":{"result_type":"recent"},"to_user_id":null,"text":"\u30a2\u30cb\u30e1\u5b9f\u6cc1\u306ftwitter\u306e\u764c","id":41190125924917248,"from_user_id":6528403,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://sites.google.com/site/peraperaprv/Home" rel="nofollow">P3:PeraPeraPrv</a>"},{"from_user_id_str":"186058304","profile_image_url":"http://a0.twimg.com/profile_images/1250454564/IMG_0210_normal.JPG","created_at":"Fri, 25 Feb 2011 17:37:37 +0000","from_user":"00o8o00","id_str":"41190090386448384","metadata":{"result_type":"recent"},"to_user_id":null,"text":"RT @fuefukioyasumi: \u3082\u3046\u3044\u3044\u3002\u300c\u671d\u751f\u300d\u306a\u3093\u304b\u3044\u3044\u3002BBC\u3082CNN\u3082\u82f1\u8a9e\u653e\u9001\u3060\u3002\u307f\u3093\u306a\u3001\u30c6\u30ec\u30d3\u3092\u3076\u3061\u3063\u3068\u5207\u3063\u3066Twitter\u3092\u898b\u3088\u3046\u3002\u3053\u3053\u306b\u300c\u751f\u304d\u305f\u60c5\u5831\u300d\u304c\u6d41\u308c\u3066\u3044\u308b\u3002\u300c\u751f\u304d\u305f\u53eb\u3073\u300d\u304c\u3042\u308b\u3002\u3053\u3053\u304b\u3089\u3067\u3082\u6b74\u53f2\u306e\u8ee2\u63db\u70b9\u3092\u611f\u3058\u308b\u4e8b\u304c\u3067\u304d\u308b\u306e\u3060\u3002 @gjmorley #libjp","id":41190090386448384,"from_user_id":186058304,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://twitter.com/">web</a>"},{"from_user_id_str":"49219631","profile_image_url":"http://a2.twimg.com/profile_images/1231873117/__2-colornow__2__normal.jpg","created_at":"Fri, 25 Feb 2011 17:37:33 +0000","from_user":"irisgazer","id_str":"41190073227550720","metadata":{"result_type":"recent"},"to_user_id":null,"text":"\u3067\u3059\u3088\u306d\u3047 RT @minamitaiheiyou: \u6545\u306b\u30cd\u30bf\u30d0\u30ec\u3092\u3059\u308b\u306e\u3082\u81ea\u7531\u3002\u30cd\u30bf\u3070\u308c\u3057\u305f\u4eba\u3092\u30c7\u30a3\u30b9\u308b\u306e\u3082\u81ea\u7531\u3002\u3042\u3068\u306f\u5404\u3005\u306e\u88c1\u91cf\u3067\u4e57\u308a\u5207\u3063\u3066\u304f\u3060\u3055\u3044\u3088\u3081\u3093\u3069\u304f\u3055\u3044\u306a RT @kihirokiro: Twitter\u3067\u30cd\u30bf\u30d0\u30ec\u4e91\u3005\u3044\u3063\u3066\u3082\u5143\u3005Twitter\u3063\u3066\u300c\u500b\u4eba\u306e\u72ec\u308a\u8a00\u300d\u3060\u308d","id":41190073227550720,"from_user_id":49219631,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://sourceforge.jp/projects/tween/wiki/FrontPage" rel="nofollow">Tween</a>"},{"from_user_id_str":"98560114","profile_image_url":"http://a0.twimg.com/profile_images/1252332545/IMGP8170_normal.jpg","created_at":"Fri, 25 Feb 2011 17:37:32 +0000","from_user":"qess0093","id_str":"41190070706905088","metadata":{"result_type":"recent"},"to_user_id":null,"text":"\u30b7\u30e5\u30fc\u30c6\u30a3\u304f\u305d\u3046\u305c\u3048\uff57 RT @syu_thi_bot: \u3044\u3064\u307e\u3067Twitter\u3084\u3063\u3066\u308b\u3093\u3060\u3044\uff1f\u3044\u3044\u52a0\u6e1b\u73fe\u5b9f\u306b\u623b\u308a\u306a\u3088\u3002\u3053\u3053\u306f\u30ad\u30df\u305f\u3061\u4e09\u6b21\u5143\u306e\u4eba\u9593\u304c\u3044\u308b\u3079\u304d\u5834\u6240\u3058\u3083\u306a\u3044\u3093\u3060\u3088\u3002\u305d\u3093\u306a\u306e\u57fa\u672c\u3060\u308d\uff01\uff01","id":41190070706905088,"from_user_id":98560114,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://sourceforge.jp/projects/tween/wiki/FrontPage" rel="nofollow">Tween</a>"},{"from_user_id_str":"197459334","profile_image_url":"http://a3.twimg.com/profile_images/1210698414/shiratorishoko_normal.png","created_at":"Fri, 25 Feb 2011 17:37:31 +0000","from_user":"SyokoShiratori","id_str":"41190064243478528","metadata":{"result_type":"recent"},"to_user_id":null,"text":"+0.50kg \u540c\u3058\u304f\u30c0\u30a4\u30a8\u30c3\u30c8\u4e2d\u3067\u3059\u3002\u3088\u304f\u3053\u306e\u30b5\u30a4\u30c8\u3067\u4f53\u91cd\u5831\u544a\u3057\u3066\u307e\u3059\u266a http://bit.ly/fhN2fM RT @msophiah \u3046\u3046\u3046\u30fb\u30fb\u30fb\u304a\u8179\u3059\u3044\u305f\u301c\u30fb\u30fb\u30fb\u6211\u6162\u3001\u6211\u6162\u3001\u6211\u6162\u3002\u30c0\u30a4\u30a8\u30c3\u30c8\u3001\u30c0\u30a4\u30a8\u30c3\u30c8\u3001\u30c0\u30a4\u30a8\u30c3\u30c8\u3002","id":41190064243478528,"from_user_id":197459334,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://mob-mc.com" rel="nofollow">\uff08\u4eee\u79f0\uff09\u30c4\u30a4\u30af\u30ea\u30c3\u30af twiclick</a>"},{"from_user_id_str":"180410237","profile_image_url":"http://a3.twimg.com/profile_images/1254473979/icon_normal.jpg","created_at":"Fri, 25 Feb 2011 17:37:30 +0000","from_user":"ka_ph","id_str":"41190062184079360","metadata":{"result_type":"recent"},"to_user_id":null,"text":"\u3010\u5b9a\u671fpost\u3011\u30d5\u30a7\u30eb\u30c7\u30a3\u30ca\u30f3\u30c8bot( http://twitter.com/ferdinand_bot )\u4f5c\u308a\u307e\u3057\u305f\u3002\u304a\u5b50\u69d8\u306e\u540d\u524d\u304a\u501f\u308a\u3055\u305b\u3066\u304f\u308c\u308b\u65b9\u3044\u307e\u3057\u305f\u3089@ka_ph\u307e\u3067\u304a\u9858\u3044\u3057\u307e\u3059\u3002","id":41190062184079360,"from_user_id":180410237,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://twittbot.net/" rel="nofollow">twittbot.net</a>"},{"from_user_id_str":"52283906","profile_image_url":"http://a3.twimg.com/profile_images/387644016/10100654519_s_normal.jpg","created_at":"Fri, 25 Feb 2011 17:37:26 +0000","from_user":"rolling_bean","id_str":"41190043313913856","metadata":{"result_type":"recent"},"to_user_id":null,"text":"\u3081\u307e\u3044\u304c\u3057\u307e\u3059\u306d\u301cRT @yurikalin:\u30b3\u30a4\u30c4\u30e9\u5168\u54e1\u3044\u306a\u304f\u306a\u3063\u305f\u3089\u3001\u660e\u308b\u304f\u306a\u308b\u3060\u308d\u3046\u306a\u3041\uff5e\u266a\uff1e\u65e5\u672c\u306e\u30d3\u30b8\u30e7\u30f3 RT roll \u65e5\u7d4c\uff06CSIS\u30b7\u30f3\u30dd\u30b8\u30a6\u30e0\u300c\u5b89\u4fdd\u6539\u5b9a50\u5468\u5e74\u3001\u3069\u3046\u306a\u308b\u65e5\u7c73\u95a2\u4fc2\u300d http://bit.ly/dES8PY\u3000http://bit.ly/ihg0GT","id":41190043313913856,"from_user_id":52283906,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://tabtter.jp" rel="nofollow">\u30bf\u30d6\u30c3\u30bf\u30fc</a>"},{"from_user_id_str":"351896","profile_image_url":"http://a3.twimg.com/profile_images/1179865336/icon12911887173020_normal.jpg","created_at":"Fri, 25 Feb 2011 17:37:26 +0000","from_user":"cicada","id_str":"41190043292925952","metadata":{"result_type":"recent"},"to_user_id":null,"text":"\u4e2d\u5b66\u53d7\u9a13\u7a0b\u5ea6\u306e\u7b97\u6570\u306e\u554f\u984c\u3092\u51fa\u3059BOT http://twitter.com/arithmetic_bot \u6c17\u306b\u306f\u306a\u308b\u304c\u3001\u3061\u3083\u3093\u3068\u898b\u308b\u65e5\u304c\u6765\u308b\u3060\u308d\u3046\u304b\u30fb\u30fb\u3000#tearai\uff1a\u30ed\u30b3\u30e9\u30dc\u5bae\u5d0e\u770c http://locolabo.com/mz/ #mzlf","id":41190043292925952,"from_user_id":351896,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://locolabo.com/mz/" rel="nofollow">\u30ed\u30b3\u30e9\u30dc\u5bae\u5d0e\u770c</a>"},{"from_user_id_str":"744554","profile_image_url":"http://a1.twimg.com/profile_images/1088753125/11868894_normal.gif","created_at":"Fri, 25 Feb 2011 17:37:20 +0000","from_user":"Febreze","id_str":"41190019020505088","metadata":{"result_type":"recent"},"to_user_id":null,"text":"\u30cd\u30bf\u30d0\u30ec\u3042\u307e\u308a\u6c17\u306b\u3057\u306a\u3044\u30bf\u30a4\u30d7\u3060\u3051\u3069\u306a\u3093\u304b\u3053\u3046Twitter\u958b\u304f\u3060\u3051\u3067\u30ac\u30f3\u30ac\u30f3\u30cd\u30bf\u30d0\u30ec\u5165\u3063\u3066\u304f\u308b\u306e\u306f\u306a\u3093\u3068\u3082\u8a00\u3048\u306a\u3044\u306a\u3002","id":41190019020505088,"from_user_id":744554,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://twitter.com/" rel="nofollow">Twitter for iPhone</a>"},{"from_user_id_str":"203371794","profile_image_url":"http://a1.twimg.com/profile_images/1226537594/___normal.png","created_at":"Fri, 25 Feb 2011 17:37:16 +0000","from_user":"himeko24","id_str":"41190004139114496","metadata":{"result_type":"recent"},"to_user_id":null,"text":"\u6b21\u3044\u3063\u3066\u307f\u3088\u30fc\u3000\u306f\u3044\u3053\u308c\u3000 \u6fc0\u5b89\u26052010\u5e74\u590f\u65b0\u30c7\u30b6\u30a4\u30f3\u2605\u30bb\u30af\u30b7\u30fc\u306a\u9023\u4f53\u5f0f\u7121\u5730\u6c34\u7740 \u80f8\u30d1\u30c3\u30c9\u4ed8\u304dQ122 http://bit.ly/h72C4i","id":41190004139114496,"from_user_id":203371794,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://www.google.co.jp" rel="nofollow">himeko24</a>"},{"from_user_id_str":"119988932","profile_image_url":"http://a3.twimg.com/profile_images/1214344633/image_normal.jpg","created_at":"Fri, 25 Feb 2011 17:37:16 +0000","from_user":"7na_love_6sa","id_str":"41190002000007169","metadata":{"result_type":"recent"},"to_user_id":null,"text":"\u30d6\u30ed\u30b0\u66f4\u65b0\u3057\u307e\u3057\u305f\uff01Twitter\uff06mixi\u304b\u3089\u3082\u30b3\u30e1\u30f3\u30c8\u5b9c\u3057\u304f\u306d\u266a\n\u300c\u30cd\u30a4\u30eb\u30c1\u30a7\u30f3\u30b8\u266a\u300d http://amba.to/hy0Do2","id":41190002000007169,"from_user_id":119988932,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://twitter.com/">web</a>"},{"from_user_id_str":"217408835","profile_image_url":"http://a1.twimg.com/profile_images/1215428655/____4.0157_normal.jpg","created_at":"Fri, 25 Feb 2011 17:37:12 +0000","from_user":"nikubenki1123","id_str":"41189985424125952","metadata":{"result_type":"recent"},"to_user_id":null,"text":"RT @x68k: \u57fa\u672c\u7684\u306bTwitter\u4e0a\u3067\u306f"\u597d\u304d\u306b\u3084\u308c\u3070\u3044\u3044"\u3060\u3051\u3069\u3001\u540d\u524d\u3082\u30a2\u30a4\u30b3\u30f3\u3082\u30a2\u30f3\u30bf\u3058\u3083\u306a\u3044\u305f\u304f\u3055\u3093\u306e\u4eba\u305f\u3061\u306e\u9b42\u304c\u3053\u3082\u3063\u305f\u3082\u306e\u306a\u306e\u3060\u304b\u3089\u3001\u305d\u308c\u3060\u3051\u306f"\u80cc\u8ca0\u3048"\u3068\u601d\u3046\uff1e\u30ad\u30e3\u30e9\u30af\u30bf\u30fc\u30a2\u30ab\u30a6\u30f3\u30c8","id":41189985424125952,"from_user_id":217408835,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://tweetlogix.com" rel="nofollow">Tweetlogix</a>"},{"from_user_id_str":"139137996","profile_image_url":"http://a0.twimg.com/profile_images/1087408006/cut_work_18_normal.jpg","created_at":"Fri, 25 Feb 2011 17:37:12 +0000","from_user":"fujiokayouko","id_str":"41189984354566144","metadata":{"result_type":"recent"},"to_user_id":null,"text":"\u591c\u4e2d\u306bTwitter\u3092\u306a\u3093\u3068\u306a\u304f\u8997\u3044\u305f\u3089\u3082\u306e\u3059\u3054\u3044\u307e\u3069\u30de\u30aeTL\u3067","id":41189984354566144,"from_user_id":139137996,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://mobile.twitter.com" rel="nofollow">Mobile Web</a>"},{"from_user_id_str":"61221002","profile_image_url":"http://a3.twimg.com/profile_images/554916301/_1259757374_61_normal.png","created_at":"Fri, 25 Feb 2011 17:37:08 +0000","from_user":"hiromk63","id_str":"41189970613903360","metadata":{"result_type":"recent"},"to_user_id":null,"text":"RT @kenji_kohashi \u7121\u4e8b\u6620\u753b\u88fd\u4f5c\u306e\u5831\u544a\u306f\u3067\u304d\u305f\u3051\u3069\u4eca\u3060\u7de8\u96c6\u306f\u7d9a\u3044\u3066\u307e\u3059w \u305d\u3093\u306a\u3068\u3053\u3067 \u6620\u753b\u300cDON'T STOP!\u300d\u306eTwitter \u30a2\u30ab\u30a6\u30f3\u30c8 @DONTSTOPMOVIE \u3082\u958b\u59cb\u3001\u3082\u3057\u826f\u304b\u3063\u305f\u3089\u30d5\u30a9\u30ed\u30fc\u3057\u3066\u304f\u3060\u3055\u3044\uff01\u50d5\u3082\u542b\u3081\u6620\u753b\u88fd\u4f5c\u95a2\u4fc2\u8005\u304c\u6c17\u9577\u306b\u3064\u3076\u3084\u304d\u307e\u3059","id":41189970613903360,"from_user_id":61221002,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://www.hootsuite.com" rel="nofollow">HootSuite</a>"},{"from_user_id_str":"147393812","profile_image_url":"http://a1.twimg.com/profile_images/1114001122/hana_10_normal.jpg","created_at":"Fri, 25 Feb 2011 17:37:07 +0000","from_user":"tubasa_uki","id_str":"41189965924667392","metadata":{"result_type":"recent"},"to_user_id":null,"text":"\uff10\uff10\uff17\u3082\u3073\u3063\u304f\u308a\u3000\u5927\u56fd\u306e\u5927\u7d71\u9818\u9078\u304b\u3089\u3000\u5cf6\u56fd\u306e\u5730\u65b9\u9078\u306e\u9078\u6319\u307e\u3067\u306b\u3082\u3000\u6697\u8e8d\u3057\u3066\u3044\u308b\uff3e\uff3e\u3000\u3053\u306eTwitter \u30b9\u30ad\u30e3\u30f3\u30c0\u30eb\u3084\u60aa\u8cea\u306a\u4e8b\u4ef6\u306b\u3082\u7d61\u3080\u304c\u3000Twitter\u304b\u3089\u767a\u4fe1\u3055\u308c\u305f\u3000\u5e73\u548c\u3078\u306e\u8ca2\u732e\u306f\u3000\u307e\u3055\u306b\u30ce\u30fc\u3079\u30eb\u5e73\u548c\u8cde\u3082\u306e http://bit.ly/esjWDG #dotubo_ss","id":41189965924667392,"from_user_id":147393812,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://twittbot.net/" rel="nofollow">twittbot.net</a>"},{"from_user_id_str":"96081746","profile_image_url":"http://a0.twimg.com/profile_images/1244505419/illust832_normal.png","created_at":"Fri, 25 Feb 2011 17:37:07 +0000","from_user":"kazukt","id_str":"41189963131387904","metadata":{"result_type":"recent"},"to_user_id":null,"text":"\u3046\u308b\u304a\u307c\u7d75\u3001\u4ed6\u306e\u4eba\u306e\u3082\u898b\u3066\u3044\u305f\u3089\u3084\u305f\u3089\u30de\u30f3\u30ac\u306e\u30ad\u30e3\u30e9\u30af\u30bf\u30fc\u3067\u3080\u3061\u3083\u304f\u3061\u3083\u4e0a\u624b\u3044\u4eba\u304c\uff01\u2026\u3068\u3001\u30d7\u30ed\u30d5\u30a3\u30fc\u30eb\u898b\u305f\u3089\u3001\u306a\u3093\u3068\u3054\u672c\u4eba\u304c\u66f8\u3044\u3066\u3044\u3089\u3063\u3057\u3083\u3063\u305f\u3002Twitter\u3063\u3066\u30b9\u30b4\u30a4\u308f\u3002","id":41189963131387904,"from_user_id":96081746,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://janetter.net/" rel="nofollow">Janetter</a>"},{"from_user_id_str":"86306230","profile_image_url":"http://a1.twimg.com/profile_images/593004766/j2j_normal.jpg","created_at":"Fri, 25 Feb 2011 17:37:03 +0000","from_user":"excite_j2j","id_str":"41189949927596032","metadata":{"result_type":"recent"},"to_user_id":null,"text":"\u79c1\u306f\u3001\u65e9\u7a32\u7530\u5927\u5b66\u30aa\u30fc\u30d7\u30f3\u30ab\u30ec\u30c3\u30b8\u306e\u5b66\u751f\u306e\u8003\u3048\u3066\u3044\u308b\u3001\u5352\u696d\u751fSoudai /\u65e9\u7a32\u7530\u30ab\u30fc\u30c9\u4f1a\u54e1/ Soudai\u5b66\u751f\u89aa/\u3001\u8ab0\u304b\u304c\u30aa\u30fc\u30d7\u30f3\u30ab\u30ec\u30c3\u30b8\u65e9\u7a32\u7530\u5927\u5b662000\u5186\u306e\u5165\u5834\u6599\u306e\u30e1\u30f3\u30d0\u30fc\u3092\u7d39\u4ecb\u3057\u3066\u304f\u308c\u305f\u65b9\u304c\u305a\u3063\u3068\u5b89\u4e0a\u304c\u308a\u3060\u3002 (\u5143\u767a\u8a00 http://bit.ly/esxiwT )","id":41189949927596032,"from_user_id":86306230,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://d.hatena.ne.jp/fn7" rel="nofollow">\u65e5\u672c\u8a9e\u65e5\u672c\u8a9e\u7ffb\u8a33\u30b8\u30a7\u30cd\u30ec\u30fc\u30bf</a>"},{"from_user_id_str":"120927161","profile_image_url":"http://a0.twimg.com/profile_images/1230006483/20110131_13022_26776_normal.jpg","created_at":"Fri, 25 Feb 2011 17:37:00 +0000","from_user":"FRISKFOSSILFANG","id_str":"41189933855158272","metadata":{"result_type":"recent"},"to_user_id":null,"text":"RT @syu_thi_bot: \u3044\u3064\u307e\u3067Twitter\u3084\u3063\u3066\u308b\u3093\u3060\u3044\uff1f\u3044\u3044\u52a0\u6e1b\u73fe\u5b9f\u306b\u623b\u308a\u306a\u3088\u3002\u3053\u3053\u306f\u30ad\u30df\u305f\u3061\u4e09\u6b21\u5143\u306e\u4eba\u9593\u304c\u3044\u308b\u3079\u304d\u5834\u6240\u3058\u3083\u306a\u3044\u3093\u3060\u3088\u3002\u305d\u3093\u306a\u306e\u57fa\u672c\u3060\u308d\uff01\uff01","id":41189933855158272,"from_user_id":120927161,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://twittbot.net/" rel="nofollow">twittbot.net</a>"},{"from_user_id_str":"228973151","profile_image_url":"http://a1.twimg.com/sticky/default_profile_images/default_profile_0_normal.png","created_at":"Fri, 25 Feb 2011 17:36:59 +0000","from_user":"daisuke1589","id_str":"41189931887890432","metadata":{"result_type":"recent"},"to_user_id":null,"text":"twitter\u3063\u3066\u52dd\u624b\u306b\u30d5\u30a9\u30ed\u30fc\u3057\u3066\u3082\u3044\u3044\u3093\u3060\u3063\u3051\uff1f","id":41189931887890432,"from_user_id":228973151,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://twitter.com/">web</a>"},{"from_user_id_str":"54314110","profile_image_url":"http://a2.twimg.com/profile_images/1193541240/image_normal.jpg","created_at":"Fri, 25 Feb 2011 17:36:57 +0000","from_user":"Alohazuki","id_str":"41189922668953600","metadata":{"result_type":"recent"},"to_user_id":null,"text":"Twitter\u306e\u5e83\u5cf6\u5f01\u3082\u3042\u3063\u305f\u3093\u3060\u306d\u3002","id":41189922668953600,"from_user_id":54314110,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://www.flight.co.jp/iPhone/TweetMe/" rel="nofollow">TweetMe for iPhone</a>"},{"from_user_id_str":"72594681","profile_image_url":"http://a3.twimg.com/profile_images/1227240916/____normal.jpg","created_at":"Fri, 25 Feb 2011 17:36:56 +0000","from_user":"uri4ichi","id_str":"41189916922744832","metadata":{"result_type":"recent"},"to_user_id":226852303,"text":"@7_fuka Twitter\u304b\u3076\u308c\u306f\u3001\u3059\u3050\u306bD\u306b\u8d70\u308b\u306e\u3067\u3002\u306a\u3093\u3060\u304b\u5fae\u7b11\u307e\u3057\u3044\u306e\u3067\u3059( \u2579\u25e1\u2579)","id":41189916922744832,"from_user_id":72594681,"to_user":"7_fuka","geo":null,"iso_language_code":"ja","to_user_id_str":"226852303","source":"<a href="http://sites.google.com/site/yorufukurou/" rel="nofollow">YoruFukurou</a>"},{"from_user_id_str":"168393854","profile_image_url":"http://a3.twimg.com/profile_images/1253554518/GuNp3xVS_normal","created_at":"Fri, 25 Feb 2011 17:36:55 +0000","from_user":"makonyanhime","id_str":"41189913701515264","metadata":{"result_type":"recent"},"to_user_id":null,"text":"\u6589\u85e4\u3055\u3093\u3082\u30c0\u30e1\u3060...\u4eca\u591c\u306fTwitter\u5909\u3060\u306a\u3041(;_;)","id":41189913701515264,"from_user_id":168393854,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://mobile.twitter.com" rel="nofollow">Twitter for Android</a>"},{"from_user_id_str":"122636787","profile_image_url":"http://a2.twimg.com/profile_images/1189607563/DSC01987_normal.JPG","created_at":"Fri, 25 Feb 2011 17:36:54 +0000","from_user":"enpy1217","id_str":"41189908500594688","metadata":{"result_type":"recent"},"to_user_id":null,"text":"twitter\u4e45\u3057\u3076\u308a\u306b\u958b\u3044\u305f\u3002\u3068\u3066\u3082\u591a\u5fd9\u3060\u3063\u305f\u3002\u75b2\u308c\u305f\u3002\u304a\u98a8\u5442\u306b\u3082\u5165\u308c\u306a\u304b\u3063\u305f\u3002\u30ad\u30bf\u30cd\u2026","id":41189908500594688,"from_user_id":122636787,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://www.flight.co.jp/iPhone/TweetMe/" rel="nofollow">TweetMe for iPhone</a>"},{"from_user_id_str":"81663694","profile_image_url":"http://a3.twimg.com/profile_images/1177576126/__normal.png","created_at":"Fri, 25 Feb 2011 17:36:51 +0000","from_user":"progmiya","id_str":"41189895494049792","metadata":{"result_type":"recent"},"to_user_id":94050844,"text":"@hirasai_skyhigh \u6674\u308c\u541b\u3002\u30cd\u30bf\u30d0\u30ec\u306f\u898b\u305f\u304f\u306a\u3044\u3051\u3069\u30012ch\u3082twitter\u3082\u3084\u308a\u305f\u3044\u306e\u304c\u4eba\u3068\u8a00\u3046\u3082\u306e\u3088","id":41189895494049792,"from_user_id":81663694,"to_user":"hirasai_skyhigh","geo":null,"iso_language_code":"ja","to_user_id_str":"94050844","source":"<a href="http://www.tweetdeck.com" rel="nofollow">TweetDeck</a>"},{"from_user_id_str":"159237469","profile_image_url":"http://a3.twimg.com/profile_images/1140433484/______2_normal.png","created_at":"Fri, 25 Feb 2011 17:36:50 +0000","from_user":"hikari_juku","id_str":"41189892096532480","metadata":{"result_type":"recent"},"to_user_id":135634241,"text":"@sssukimasuky \n\u4f55\u304b\u3042\u3063\u305f\u98a8\u3067\u3059\u306d\uff08\u7b11\uff09\u3000\u78ba\u304b\u306bTwitter\u306f\u6c17\u8efd\u3067\u3059\u3057\u306d\u3002\u30e1\u30fc\u30eb\u306b\u306a\u308b\u3068\u30d5\u30c3\u30c8\u30ef\u30fc\u30af\u304c\u91cd\u304f\u306a\u308b\u5834\u5408\u3082\u3042\u308b\u304b\u3082\u3057\u308c\u307e\u305b\u3093\u306d\u3002\u305d\u3046\u8003\u3048\u308b\u3068\u3059\u3054\u3044\u6642\u4ee3\u3060\u3002","id":41189892096532480,"from_user_id":159237469,"to_user":"sssukimasuky","geo":null,"iso_language_code":"ja","to_user_id_str":"135634241","source":"<a href="http://www.hootsuite.com" rel="nofollow">HootSuite</a>"},{"from_user_id_str":"141915990","profile_image_url":"http://a0.twimg.com/profile_images/1248969898/icon679566266564378764images_normal.jpg","created_at":"Fri, 25 Feb 2011 17:36:48 +0000","from_user":"adashino_","id_str":"41189886878949376","metadata":{"result_type":"recent"},"to_user_id":null,"text":"RT @fuefukioyasumi: \u3082\u3046\u3044\u3044\u3002\u300c\u671d\u751f\u300d\u306a\u3093\u304b\u3044\u3044\u3002BBC\u3082CNN\u3082\u82f1\u8a9e\u653e\u9001\u3060\u3002\u307f\u3093\u306a\u3001\u30c6\u30ec\u30d3\u3092\u3076\u3061\u3063\u3068\u5207\u3063\u3066Twitter\u3092\u898b\u3088\u3046\u3002\u3053\u3053\u306b\u300c\u751f\u304d\u305f\u60c5\u5831\u300d\u304c\u6d41\u308c\u3066\u3044\u308b\u3002\u300c\u751f\u304d\u305f\u53eb\u3073\u300d\u304c\u3042\u308b\u3002\u3053\u3053\u304b\u3089\u3067\u3082\u6b74\u53f2\u306e\u8ee2\u63db\u70b9\u3092\u611f\u3058\u308b\u4e8b\u304c\u3067\u304d\u308b\u306e\u3060\u3002 @gjmorley #libjp","id":41189886878949376,"from_user_id":141915990,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://twitter.com/">web</a>"},{"from_user_id_str":"111308629","profile_image_url":"http://a1.twimg.com/profile_images/1137421845/mmooton_normal.png","created_at":"Fri, 25 Feb 2011 17:36:46 +0000","from_user":"mmooton","id_str":"41189877940748288","metadata":{"result_type":"recent"},"to_user_id":null,"text":"RT @minponjp: \u3010\u3064\u3076\u3084\u304f\u3060\u3051\u306710000\u5186\u5546\u54c1\u5238GET\u3011<<visa\u30ae\u30d5\u30c8\u30ab\u30fc\u30c910000\u5186\u5206\u3092\u6bce\u6708\u62bd\u9078\u3067\u30d7\u30ec\u30bc\u30f3\u30c8>> \u21d2\u8a73\u3057\u304f\u306f\u4e0b\u306e\uff35\uff32\uff2c\u3088\u308a\u2193\u2193\u2193\u2193\u2193 http://minpon.jp/user_data/twitter_campaign.php","id":41189877940748288,"from_user_id":111308629,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://twittbot.net/" rel="nofollow">twittbot.net</a>"},{"from_user_id_str":"140945098","profile_image_url":"http://a0.twimg.com/profile_images/1198948281/b7664c71-87bc-4187-9d46-a61ab8d41b96_normal.jpg","created_at":"Fri, 25 Feb 2011 17:36:46 +0000","from_user":"waruimayuko","id_str":"41189877122867200","metadata":{"result_type":"recent"},"to_user_id":113371008,"text":"@toumeisyoujyo \u3042\u3053\u3061\u3083\u3093Twitter\u3084\u3063\u3066\u305f\u306e\u306d\u3002\u307e\u3060\u304a\u5e2d\u3042\u308b\u305d\u3046\u306a\u306e\u3067\u662f\u975e\uff01","id":41189877122867200,"from_user_id":140945098,"to_user":"toumeisyoujyo","geo":null,"iso_language_code":"ja","to_user_id_str":"113371008","source":"<a href="http://twimi.jp/?r=via" rel="nofollow">twimi\u2606new</a>"},{"from_user_id_str":"167512527","profile_image_url":"http://a1.twimg.com/profile_images/1172286365/newspaper_normal.jpg","created_at":"Fri, 25 Feb 2011 17:36:45 +0000","from_user":"KoranKaget","id_str":"41189871775252480","metadata":{"result_type":"recent"},"to_user_id":null,"text":"http://bit.ly/93Eeud RT @motocentrism \u30d6\u30ed\u30b0\u8a18\u4e8b\u66f8\u304d\u307e\u3057\u305f\u30fc\uff1a MotoGP\u3000\u30d6\u30c3\u30af\u30e1\u30fc\u30ab\u30fc\u306b\u898b\u308b\u5404\u30e9\u30a4\u30c0\u30fc\u306e\u4e0b\u99ac\u8a55 - http://goo.gl/xVe6... http://bit.ly/hDYxyx @motogpudpate","id":41189871775252480,"from_user_id":167512527,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://twitterfeed.com" rel="nofollow">twitterfeed</a>"},{"from_user_id_str":"160251772","profile_image_url":"http://a3.twimg.com/profile_images/1150692471/_____normal.jpg","created_at":"Fri, 25 Feb 2011 17:36:45 +0000","from_user":"keikochaki","id_str":"41189870781075456","metadata":{"result_type":"recent"},"to_user_id":null,"text":"\u300c\u305a\u3063\u3068twitter\u3084\u3063\u3066\u308b\u3088\u306d\u300d\u3068\u6012\u3089\u308c\u3066\u3057\u307e\u3063\u305f(\u82e6\u7b11)","id":41189870781075456,"from_user_id":160251772,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://twtr.jp" rel="nofollow">Keitai Web</a>"},{"from_user_id_str":"211565766","profile_image_url":"http://a2.twimg.com/sticky/default_profile_images/default_profile_5_normal.png","created_at":"Fri, 25 Feb 2011 17:36:42 +0000","from_user":"sayap1yo","id_str":"41189858236043264","metadata":{"result_type":"recent"},"to_user_id":null,"text":"\u304a\u98df\u4e8b\u4f1a\u884c\u304d\u305f\u304b\u3063\u305f\u3051\u3069\n\u53cb\u9054\u3068\u904a\u3093\u3067\u307e\u3093\u305f\ue056\ue326\n\nTwitter\u898b\u3066\u307e\u3057\u305f\u3051\u3069\n\u3064\u3076\u3084\u304f\u30bf\u30a4\u30df\u30f3\u30b0\n\u5931\u3063\u3066\u305f\u3060\u3051\u3067\u3059( \u00b4 \u25bd ` )\uff89\u7b11","id":41189858236043264,"from_user_id":211565766,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://www.nibirutech.com" rel="nofollow">TwitBird</a>"},{"from_user_id_str":"19603191","profile_image_url":"http://a1.twimg.com/profile_images/1254077264/116_normal.gif","created_at":"Fri, 25 Feb 2011 17:36:40 +0000","from_user":"Purple_Flash","id_str":"41189851873157120","metadata":{"result_type":"recent"},"to_user_id":null,"text":"RT @syu_thi_bot: \u3044\u3064\u307e\u3067Twitter\u3084\u3063\u3066\u308b\u3093\u3060\u3044\uff1f\u3044\u3044\u52a0\u6e1b\u73fe\u5b9f\u306b\u623b\u308a\u306a\u3088\u3002\u3053\u3053\u306f\u30ad\u30df\u305f\u3061\u4e09\u6b21\u5143\u306e\u4eba\u9593\u304c\u3044\u308b\u3079\u304d\u5834\u6240\u3058\u3083\u306a\u3044\u3093\u3060\u3088\u3002\u305d\u3093\u306a\u306e\u57fa\u672c\u3060\u308d\uff01\uff01","id":41189851873157120,"from_user_id":19603191,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://twittbot.net/" rel="nofollow">twittbot.net</a>"},{"from_user_id_str":"215930291","profile_image_url":"http://a0.twimg.com/profile_images/1247906106/image_normal.jpg","created_at":"Fri, 25 Feb 2011 17:36:30 +0000","from_user":"minori_millie","id_str":"41189810055938048","metadata":{"result_type":"recent"},"to_user_id":212972774,"text":"@c_c_chika \u7b11\u3063\u3066\u305d\u3046\u3060\u306a\u3063\u3066\u601d\u3063\u3066\u305f(o^^o)\u30c1\u30ab\u306e\u7b11\u3044\u58f0\u304c\u805e\u3053\u3048\u3066\u304d\u305f\u3082\u3093\u3002mail\u306bTwitter\u3067\u5927\u5fd9\u3057\u3084\u3002","id":41189810055938048,"from_user_id":215930291,"to_user":"c_c_chika","geo":null,"iso_language_code":"ja","to_user_id_str":"212972774","source":"<a href="http://twitter.com/" rel="nofollow">Twitter for iPhone</a>"},{"from_user_id_str":"197459334","profile_image_url":"http://a3.twimg.com/profile_images/1210698414/shiratorishoko_normal.png","created_at":"Fri, 25 Feb 2011 17:36:30 +0000","from_user":"SyokoShiratori","id_str":"41189809586311168","metadata":{"result_type":"recent"},"to_user_id":null,"text":"+0.90kg \u30c0\u30a4\u30a8\u30c3\u30c8\u5fdc\u63f4\u3057\u3066\u307e\u3059\u3002(*^^*)\u30c0\u30a4\u30a8\u30c3\u30c8\u4f53\u91cd\u5831\u544a\u306e\u3064\u3076\u3084\u304d\u3067\u3059\u3002 http://bit.ly/fhN2fM RT @hayayumi \u3053\u3093\u306a\u6642\u9593\u306b\u3084\u304d\u306b\u304f\u30fc\u266b\u30c0\u30a4\u30a8\u30c3\u30c8\u671f\u9593\u306a\u306e\u306b\u306d....","id":41189809586311168,"from_user_id":197459334,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://mob-mc.com" rel="nofollow">\uff08\u4eee\u79f0\uff09\u30c4\u30a4\u30af\u30ea\u30c3\u30af twiclick</a>"},{"from_user_id_str":"12337665","profile_image_url":"http://a0.twimg.com/profile_images/1146194926/pixiv-icon_normal.png","created_at":"Fri, 25 Feb 2011 17:36:27 +0000","from_user":"t_a_k_i","id_str":"41189797364121600","metadata":{"result_type":"recent"},"to_user_id":null,"text":"Google\u30ea\u30fc\u30c0\u30fc\u3067\u30b5\u30a4\u30c8\u306e\u66f4\u65b0\u30c1\u30a7\u30c3\u30af\u3059\u308b\u3088\u308a\u3001Twitter\u30a2\u30ab\u30a6\u30f3\u30c8\u3092\u30d5\u30a9\u30ed\u30fc\u3057\u3066\u66f4\u65b0\u3092\u77e5\u308b\u307b\u3046\u304c\u4fbf\u5229\u3060\u306a\u3053\u308c","id":41189797364121600,"from_user_id":12337665,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://sites.google.com/site/yorufukurou/" rel="nofollow">YoruFukurou</a>"},{"from_user_id_str":"104862453","profile_image_url":"http://a3.twimg.com/profile_images/1248609864/Image014_normal.jpg","created_at":"Fri, 25 Feb 2011 17:36:25 +0000","from_user":"yuz_ume","id_str":"41189787943714816","metadata":{"result_type":"recent"},"to_user_id":null,"text":"RT @fuefukioyasumi: \u3082\u3046\u3044\u3044\u3002\u300c\u671d\u751f\u300d\u306a\u3093\u304b\u3044\u3044\u3002BBC\u3082CNN\u3082\u82f1\u8a9e\u653e\u9001\u3060\u3002\u307f\u3093\u306a\u3001\u30c6\u30ec\u30d3\u3092\u3076\u3061\u3063\u3068\u5207\u3063\u3066Twitter\u3092\u898b\u3088\u3046\u3002\u3053\u3053\u306b\u300c\u751f\u304d\u305f\u60c5\u5831\u300d\u304c\u6d41\u308c\u3066\u3044\u308b\u3002\u300c\u751f\u304d\u305f\u53eb\u3073\u300d\u304c\u3042\u308b\u3002\u3053\u3053\u304b\u3089\u3067\u3082\u6b74\u53f2\u306e\u8ee2\u63db\u70b9\u3092\u611f\u3058\u308b\u4e8b\u304c\u3067\u304d\u308b\u306e\u3060\u3002 @gjmorley #libjp","id":41189787943714816,"from_user_id":104862453,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://twitter.com/">web</a>"},{"from_user_id_str":"213846746","profile_image_url":"http://a1.twimg.com/profile_images/1242263342/haruhi1_normal.png","created_at":"Fri, 25 Feb 2011 17:36:23 +0000","from_user":"sloth888jpgame","id_str":"41189778409922560","metadata":{"result_type":"recent"},"to_user_id":null,"text":"\u643a\u5e2f\u96fb\u8a71\u7528\u306eTwitter\u3092\u5229\u7528\u3057\u305f\u30b2\u30fc\u30e0\u3092\u77e5\u3063\u3066\u3044\u308b\u4eba\u306f\u3001\u7d39\u4ecb\u3057\u3066\u304f\u3060\u3055\u3044\u3002 #TwitterGame","id":41189778409922560,"from_user_id":213846746,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://twittbot.net/" rel="nofollow">twittbot.net</a>"},{"from_user_id_str":"17484724","profile_image_url":"http://a2.twimg.com/profile_images/1138677235/iconue_normal.jpg","created_at":"Fri, 25 Feb 2011 17:36:22 +0000","from_user":"tsutcho","id_str":"41189777831231490","metadata":{"result_type":"recent"},"to_user_id":null,"text":"\u30a2\u30aa\u30b7\u30de\u3055\u3093twitter\u306b\u7acb\u3064\u30fb\u30fb\u30fb\u3060\u3068\u30fb\u30fb\u30fb\uff1f\uff12\u756a\u76ee\u306e\u30d5\u30a9\u30ed\u30ef\u30fc\u306e\u5ea7\u3092\u3044\u305f\u3060\u3044\u3066\u304a\u3053\u3046","id":41189777831231490,"from_user_id":17484724,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://twitter.com/">web</a>"},{"from_user_id_str":"220041064","profile_image_url":"http://a1.twimg.com/sticky/default_profile_images/default_profile_0_normal.png","created_at":"Fri, 25 Feb 2011 17:36:21 +0000","from_user":"sloth888jp_bot5","id_str":"41189772521254914","metadata":{"result_type":"recent"},"to_user_id":null,"text":"\u6642\u3005\u3001TwiAll\uff08\u30c4\u30a4\u30aa\u30fc\u30eb\uff09\u3067Twitter\u306e\u81ea\u52d5\u30d5\u30a9\u30ed\u30fc\u30fb\u30d5\u30a9\u30ed\u30fc\u8fd4\u3057\u3092\u3057\u3066\u3044\u307e\u3059\u3002","id":41189772521254914,"from_user_id":220041064,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://twittbot.net/" rel="nofollow">twittbot.net</a>"},{"from_user_id_str":"177693537","profile_image_url":"http://a0.twimg.com/profile_images/1240130924/20110207213206_normal.jpg","created_at":"Fri, 25 Feb 2011 17:36:21 +0000","from_user":"Na_Okinawa","id_str":"41189769912397824","metadata":{"result_type":"recent"},"to_user_id":null,"text":"RT @ebizo66: \u30ea\u30d3\u30a2\u30fb\u30c8\u30ea\u30dd\u30ea\u306eTw\uff1a\u6551\u6025\u8eca\u304c\u6765\u305f\u304c\u3001\u8ca0\u50b7\u8005\u3092\u8eca\u5185\u3067\u6bba\u5bb3\u3057\u3066\u3044\u305f\u3001\u3068\u3002\uff08\u6ec5\u8336\u82e6\u8336\u3060\uff01\uff09http://ow.ly/43pQ2 #libjp","id":41189769912397824,"from_user_id":177693537,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://www.hootsuite.com" rel="nofollow">HootSuite</a>"},{"from_user_id_str":"147006592","profile_image_url":"http://a2.twimg.com/profile_images/1251306448/image_normal.jpg","created_at":"Fri, 25 Feb 2011 17:36:19 +0000","from_user":"takasu_rika","id_str":"41189763532865536","metadata":{"result_type":"recent"},"to_user_id":null,"text":"RT @kihirokiro: Twitter\u3067\u30cd\u30bf\u30d0\u30ec\u4e91\u3005\u3044\u3063\u3066\u3082\u5143\u3005Twitter\u3063\u3066\u300c\u500b\u4eba\u306e\u72ec\u308a\u8a00\u300d\u3060\u308d","id":41189763532865536,"from_user_id":147006592,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://www.tweetdeck.com" rel="nofollow">TweetDeck</a>"},{"from_user_id_str":"100239985","profile_image_url":"http://a1.twimg.com/profile_images/733461294/CIMG0207_normal.JPG","created_at":"Fri, 25 Feb 2011 17:36:19 +0000","from_user":"strangebarjun","id_str":"41189762182152192","metadata":{"result_type":"recent"},"to_user_id":null,"text":"Twitter\u3092\u59cb\u3081\u3066\u3001\u305d\u308d\u305d\u308d\u4e00\u5e74\u306b\u306a\u308a\u307e\u3059\u3002\u632f\u308a\u8fd4\u308b\u3068\u3001\u307c\u304f\u306e\u4eba\u9593\u6027\u3092\u305d\u3063\u304f\u308a\u53cd\u6620\u3059\u308b\u304c\u5982\u304f\u3001\u534a\u7aef\u3067\u3059\u306d\u3002\u60c5\u5831\u53ce\u96c6\u30c4\u30fc\u30eb\u3001\u60c5\u5831\u767a\u4fe1\u30c4\u30fc\u30eb\u3001\u30b3\u30df\u30e5\u30cb\u30b1\u30fc\u30b7\u30e7\u30f3\u30c4\u30fc\u30eb\u3001\u3069\u308c\u3082\u6a5f\u80fd\u3057\u5207\u308c\u3066\u3044\u306a\u3044\u306a\u3042\u3001\u3068\u3002\u305d\u3057\u3066\u3042\u308b\u306e\u306f\u300c\u3069\u3053\u304b\u3089\u3082\u76f8\u624b\u306b\u3055\u308c\u3066\u3044\u306a\u3044\u300d\u3068\u3044\u3046\u3001\u65e2\u77e5\u306e\u73fe\u5b9f\u3067\u3059\u3002","id":41189762182152192,"from_user_id":100239985,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://www.echofon.com/" rel="nofollow">Echofon</a>"},{"from_user_id_str":"126390384","profile_image_url":"http://a2.twimg.com/profile_images/1176065038/nemunemu_normal.jpg","created_at":"Fri, 25 Feb 2011 17:36:18 +0000","from_user":"gesukapper","id_str":"41189757476286464","metadata":{"result_type":"recent"},"to_user_id":80935865,"text":"@tatsugorou \u306a\u3093\u304b\u4e16\u306e\u4e2d\u306b\u306f\u611a\u75f4\u3082\u4e0b\u30cd\u30bf\u3082\u8a00\u3044\u653e\u984c\u306etwitter\u3068\u3044\u3046\u3082\u306e\u304c\u3042\u308b\u305d\u3046\u3067\u3059\u3002","id":41189757476286464,"from_user_id":126390384,"to_user":"tatsugorou","geo":null,"iso_language_code":"ja","to_user_id_str":"80935865","source":"<a href="http://janetter.net/" rel="nofollow">Janetter</a>"},{"from_user_id_str":"196059029","profile_image_url":"http://a1.twimg.com/profile_images/1208831726/ruka2_normal.jpg","created_at":"Fri, 25 Feb 2011 17:36:17 +0000","from_user":"luka_m_bot","id_str":"41189756666777600","metadata":{"result_type":"recent"},"to_user_id":null,"text":"\u308f\u305f\u3057\u3082twitter\u306f\u3058\u3081\u307e\u3057\u305f","id":41189756666777600,"from_user_id":196059029,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://www24.atpages.jp/aoi2/bot.php" rel="nofollow">\u5de1\u308b\u97f3</a>"},{"from_user_id_str":"88135613","profile_image_url":"http://a3.twimg.com/profile_images/1088552877/P9280150_normal.JPG","created_at":"Fri, 25 Feb 2011 17:36:14 +0000","from_user":"Roko38","id_str":"41189740321587200","metadata":{"result_type":"recent"},"to_user_id":null,"text":"\uff46\uff42\u306b\u30ed\u30b0\u30a4\u30f3\u3059\u308b\u6a5f\u4f1a\u304c\u65e5\u306b\u65e5\u306b\u5897\u3048\u3066\u304d\u305f\uff3e\uff3e \u6163\u308c\u3066\u304f\u308b\u3068\u3042\u3063\u3061\u306e\u304c\u9762\u767d\u3044\uff06\u4f7f\u3044\u52dd\u624b\u304c\u3044\u3044\u3088\u3046\u306a\u6c17\u304c\u3059\u308b\u3002\u8907\u5408\u7684\u306b\u8272\u3005\u51fa\u6765\u307e\u3059\u3088\u306d\u2026\u3063\u3066\u3001\u601d\u3063\u305f\u3053\u3068\u3092\u545f\u304f\u306e\u306fTwitter\u3060\u3063\u305f\u308a\u3067\u3059\u304c\u2026(^_^; \u305d\u3057\u3066\u81ea\u5206\u306e\u5834\u5408\u306f\u30c4\u30a4\u3068\u9023\u52d5\u3057\u3065\u3089\u3044\u72b6\u6cc1\u3060\u3063\u305f\u308a\u3067\u2026\u3002","id":41189740321587200,"from_user_id":88135613,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://twitter.com/">web</a>"},{"from_user_id_str":"110825211","profile_image_url":"http://a2.twimg.com/profile_images/1108977866/o_t_normal.jpg","created_at":"Fri, 25 Feb 2011 17:36:12 +0000","from_user":"kou_nanjyo","id_str":"41189731941363712","metadata":{"result_type":"recent"},"to_user_id":null,"text":"RT @x68k: \u57fa\u672c\u7684\u306bTwitter\u4e0a\u3067\u306f"\u597d\u304d\u306b\u3084\u308c\u3070\u3044\u3044"\u3060\u3051\u3069\u3001\u540d\u524d\u3082\u30a2\u30a4\u30b3\u30f3\u3082\u30a2\u30f3\u30bf\u3058\u3083\u306a\u3044\u305f\u304f\u3055\u3093\u306e\u4eba\u305f\u3061\u306e\u9b42\u304c\u3053\u3082\u3063\u305f\u3082\u306e\u306a\u306e\u3060\u304b\u3089\u3001\u305d\u308c\u3060\u3051\u306f"\u80cc\u8ca0\u3048"\u3068\u601d\u3046\uff1e\u30ad\u30e3\u30e9\u30af\u30bf\u30fc\u30a2\u30ab\u30a6\u30f3\u30c8","id":41189731941363712,"from_user_id":110825211,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://tweetlogix.com" rel="nofollow">Tweetlogix</a>"},{"from_user_id_str":"2095960","profile_image_url":"http://a2.twimg.com/profile_images/1248999075/majiresu2_normal.jpg","created_at":"Fri, 25 Feb 2011 17:36:10 +0000","from_user":"guldeen","id_str":"41189726945947648","metadata":{"result_type":"recent"},"to_user_id":null,"text":"\u3042\u308a\u3083\u307e\u3041\u3002\u25bchttp://bit.ly/et4vVa \uff3b\u89d2\u5ddd\u66f8\u5e97\uff3d\u300c\u30b6\u30fb\u30b9\u30cb\u30fc\u30ab\u30fc\u300d\u4f11\u520a\u3078\u3000\u300c\u6dbc\u5bae\u30cf\u30eb\u30d2\u300d\u751f\u3093\u3060\u30e9\u30ce\u30d9\u96d1\u8a8c18\u5e74\u3067\u5e55 via http://twitter.com/lkj777","id":41189726945947648,"from_user_id":2095960,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://twitter.com/">web</a>"},{"from_user_id_str":"164121549","profile_image_url":"http://a1.twimg.com/profile_images/1251758789/m_108-07ae3_normal.jpg","created_at":"Fri, 25 Feb 2011 17:36:09 +0000","from_user":"hachi_touhi","id_str":"41189719299727360","metadata":{"result_type":"recent"},"to_user_id":null,"text":"\u30cd\u30bf\u30d0\u30ec\u6c17\u306b\u3057\u3066\u305f\u3089Twitter\u3084\u3063\u3066\u3089\u308c\u306a\u3044ww","id":41189719299727360,"from_user_id":164121549,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://twicca.r246.jp/" rel="nofollow">twicca</a>"},{"from_user_id_str":"194494659","profile_image_url":"http://a3.twimg.com/profile_images/1249717822/image_normal.jpg","created_at":"Fri, 25 Feb 2011 17:36:08 +0000","from_user":"tomonattomo","id_str":"41189715415801856","metadata":{"result_type":"recent"},"to_user_id":null,"text":"\u3046\u308f\u3001\u660e\u65e5\u671d\u304b\u3089\u30d0\u30a4\u30c8\u3084\u306e\u306b\u306a\u3093\u3060\u3053\u306e\u306d\u3075\u304b\u3057\u3002\u3042\u3001\u591c\u66f4\u304b\u3057\u3002\u30d1\u30d4\u30eb\u30b9\u3068BUMP\u3001\u3048\u307f\u3068Twitter\u306eDM\u3057\u3059\u304e\u305f\u306a\u2026","id":41189715415801856,"from_user_id":194494659,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://mixi.jp/promotion.pl?id=voice_twitter" rel="nofollow"> mixi \u30dc\u30a4\u30b9 </a>"},{"from_user_id_str":"97224364","profile_image_url":"http://a3.twimg.com/profile_images/1150074355/fb8bcca60d340862c053a756377bfae8_normal.jpeg","created_at":"Fri, 25 Feb 2011 17:36:06 +0000","from_user":"xxxheat","id_str":"41189709174677504","metadata":{"result_type":"recent"},"to_user_id":null,"text":"Twitter\u5b8c\u5168\u306b\u30d0\u30b0\u3063\u3066\u308borz","id":41189709174677504,"from_user_id":97224364,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://twitter.com/" rel="nofollow">Twitter for iPhone</a>"}],"max_id":41190705623732224,"since_id":38643906774044672,"refresh_url":"?since_id=41190705623732224&q=twitter","next_page":"?page=2&max_id=41190705623732224&rpp=100&lang=ja&q=twitter","results_per_page":100,"page":1,"completed_in":0.093336,"warning":"adjusted since_id to 38643906774044672 (), requested since_id was older than allowed -- since_id removed for pagination.","since_id_str":"38643906774044672","max_id_str":"41190705623732224","query":"twitter"} diff --git a/distributors-json/bench/data/twitter10.json b/distributors-json/bench/data/twitter10.json new file mode 100644 index 00000000..2245c0fa --- /dev/null +++ b/distributors-json/bench/data/twitter10.json @@ -0,0 +1 @@ +{"results":[{"from_user_id_str":"207858021","profile_image_url":"http://a3.twimg.com/sticky/default_profile_images/default_profile_2_normal.png","created_at":"Wed, 26 Jan 2011 04:30:38 +0000","from_user":"pboudarga","id_str":"30120402839666689","metadata":{"result_type":"recent"},"to_user_id":null,"text":"I'm at Rolla Sushi Grill (27737 Bouquet Canyon Road, #106, Btw Haskell Canyon and Rosedell Drive, Saugus) http://4sq.com/gqqdhs","id":30120402839666689,"from_user_id":207858021,"geo":null,"iso_language_code":"en","to_user_id_str":null,"source":"<a href="http://foursquare.com" rel="nofollow">foursquare</a>"},{"from_user_id_str":"69988683","profile_image_url":"http://a0.twimg.com/profile_images/1211955817/avatar_7888_normal.gif","created_at":"Wed, 26 Jan 2011 04:25:23 +0000","from_user":"YNK33","id_str":"30119083059978240","metadata":{"result_type":"recent"},"to_user_id":null,"text":"hsndfile 0.5.0: Free and open source Haskell bindings for libsndfile http://bit.ly/gHaBWG Mac Os","id":30119083059978240,"from_user_id":69988683,"geo":null,"iso_language_code":"en","to_user_id_str":null,"source":"<a href="http://twitterfeed.com" rel="nofollow">twitterfeed</a>"},{"from_user_id_str":"81492","profile_image_url":"http://a1.twimg.com/profile_images/423894208/Picture_7_normal.jpg","created_at":"Wed, 26 Jan 2011 04:24:28 +0000","from_user":"satzz","id_str":"30118851488251904","metadata":{"result_type":"recent"},"to_user_id":null,"text":"Emacs\u306e\u30e2\u30fc\u30c9\u8868\u793a\u304c\u4eca(Ruby Controller Outputz RoR Flymake REl hs)\u3068\u306a\u3063\u3066\u3066\u3088\u304f\u308f\u304b\u3089\u306a\u3044\u3093\u3060\u3051\u3069\u6700\u5f8c\u306eREl\u3068\u304bhs\u3063\u3066\u4f55\u3060\u308d\u3046\u2026haskell\u3068\u304b2\u5e74\u4ee5\u4e0a\u66f8\u3044\u3066\u306a\u3044\u3051\u3069\u2026","id":30118851488251904,"from_user_id":81492,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://www.hootsuite.com" rel="nofollow">HootSuite</a>"},{"from_user_id_str":"9518356","profile_image_url":"http://a2.twimg.com/profile_images/119165723/ocaml-icon_normal.png","created_at":"Wed, 26 Jan 2011 04:19:19 +0000","from_user":"planet_ocaml","id_str":"30117557788741632","metadata":{"result_type":"recent"},"to_user_id":null,"text":"I so miss #haskell type classes in #ocaml - i want to do something like refinement. Also why does ocaml not have... http://bit.ly/geYRwt","id":30117557788741632,"from_user_id":9518356,"geo":null,"iso_language_code":"en","to_user_id_str":null,"source":"<a href="http://twitterfeed.com" rel="nofollow">twitterfeed</a>"},{"from_user_id_str":"218059","profile_image_url":"http://a1.twimg.com/profile_images/1053837723/twitter-icon9_normal.jpg","created_at":"Wed, 26 Jan 2011 04:16:32 +0000","from_user":"aprikip","id_str":"30116854940835840","metadata":{"result_type":"recent"},"to_user_id":null,"text":"yatex-mode\u3084haskell-mode\u306e\u3053\u3068\u3067\u3059\u306d\u3001\u308f\u304b\u308a\u307e\u3059\u3002","id":30116854940835840,"from_user_id":218059,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://sites.google.com/site/yorufukurou/" rel="nofollow">YoruFukurou</a>"},{"from_user_id_str":"216363","profile_image_url":"http://a1.twimg.com/profile_images/72454310/Tim-Avatar_normal.png","created_at":"Wed, 26 Jan 2011 04:15:30 +0000","from_user":"dysinger","id_str":"30116594684264448","metadata":{"result_type":"recent"},"to_user_id":null,"text":"Haskell in Hawaii tonight for me... #fun","id":30116594684264448,"from_user_id":216363,"geo":null,"iso_language_code":"en","to_user_id_str":null,"source":"<a href="http://www.nambu.com/" rel="nofollow">Nambu</a>"},{"from_user_id_str":"1774820","profile_image_url":"http://a2.twimg.com/profile_images/61169291/dan_desert_thumb_normal.jpg","created_at":"Wed, 26 Jan 2011 04:13:36 +0000","from_user":"DanMil","id_str":"30116117682851840","metadata":{"result_type":"recent"},"to_user_id":1594784,"text":"@ojrac @chewedwire @tomheon Haskell isn't a language, it's a belief system. A seductive one...","id":30116117682851840,"from_user_id":1774820,"to_user":"ojrac","geo":null,"iso_language_code":"en","to_user_id_str":"1594784","source":"<a href="http://twitter.com/">web</a>"},{"from_user_id_str":"659256","profile_image_url":"http://a0.twimg.com/profile_images/746976711/angular-final_normal.jpg","created_at":"Wed, 26 Jan 2011 04:11:06 +0000","from_user":"djspiewak","id_str":"30115488931520512","metadata":{"result_type":"recent"},"to_user_id":null,"text":"One of the very nice things about Haskell as opposed to SML is the reduced proliferation of identifiers (e.g. andb, orb, etc). #typeclasses","id":30115488931520512,"from_user_id":659256,"geo":null,"iso_language_code":"en","to_user_id_str":null,"source":"<a href="http://itunes.apple.com/us/app/twitter/id409789998?mt=12" rel="nofollow">Twitter for Mac</a>"},{"from_user_id_str":"144546280","profile_image_url":"http://a1.twimg.com/a/1295051201/images/default_profile_1_normal.png","created_at":"Wed, 26 Jan 2011 04:06:12 +0000","from_user":"listwarenet","id_str":"30114255890026496","metadata":{"result_type":"recent"},"to_user_id":null,"text":"http://www.listware.net/201101/haskell-cafe/84752-re-haskell-cafe-gpl-license-of-h-matrix-and-prelude-numeric.html Re: Haskell-c","id":30114255890026496,"from_user_id":144546280,"geo":null,"iso_language_code":"no","to_user_id_str":null,"source":"<a href="http://1e10.org/cloud/" rel="nofollow">1e10</a>"},{"from_user_id_str":"1594784","profile_image_url":"http://a2.twimg.com/profile_images/378515773/square-profile_normal.jpg","created_at":"Wed, 26 Jan 2011 04:01:29 +0000","from_user":"ojrac","id_str":"30113067333324800","metadata":{"result_type":"recent"},"to_user_id":null,"text":"RT @tomheon: @ojrac @chewedwire Don't worry, learning Haskell will not give you any clear idea what monad means.","id":30113067333324800,"from_user_id":1594784,"geo":null,"iso_language_code":"en","to_user_id_str":null,"source":"<a href="http://twitter.com/">web</a>"}],"max_id":30120402839666689,"since_id":0,"refresh_url":"?since_id=30120402839666689&q=haskell","next_page":"?page=2&max_id=30120402839666689&rpp=10&q=haskell","results_per_page":10,"page":1,"completed_in":0.012714,"since_id_str":"0","max_id_str":"30120402839666689","query":"haskell"} diff --git a/distributors-json/bench/data/twitter100.json b/distributors-json/bench/data/twitter100.json new file mode 100644 index 00000000..461f3885 --- /dev/null +++ b/distributors-json/bench/data/twitter100.json @@ -0,0 +1 @@ +{"results":[{"from_user_id_str":"3646730","profile_image_url":"http://a3.twimg.com/profile_images/404973767/avatar_normal.jpg","created_at":"Wed, 26 Jan 2011 04:35:07 +0000","from_user":"nicolaslara","id_str":"30121530767708160","metadata":{"result_type":"recent"},"to_user_id":18616016,"text":"@josej30 Python y Clojure. Obviamente son diferentes, y cada uno tiene sus ventajas y desventajas. De Haskell faltar\u00eda pattern matching","id":30121530767708160,"from_user_id":3646730,"to_user":"josej30","geo":null,"iso_language_code":"es","to_user_id_str":"18616016","source":"<a href="http://twitter.com/" rel="nofollow">Twitter for iPhone</a>"},{"from_user_id_str":"207858021","profile_image_url":"http://a3.twimg.com/sticky/default_profile_images/default_profile_2_normal.png","created_at":"Wed, 26 Jan 2011 04:30:38 +0000","from_user":"pboudarga","id_str":"30120402839666689","metadata":{"result_type":"recent"},"to_user_id":null,"text":"I'm at Rolla Sushi Grill (27737 Bouquet Canyon Road, #106, Btw Haskell Canyon and Rosedell Drive, Saugus) http://4sq.com/gqqdhs","id":30120402839666689,"from_user_id":207858021,"geo":null,"iso_language_code":"en","to_user_id_str":null,"source":"<a href="http://foursquare.com" rel="nofollow">foursquare</a>"},{"from_user_id_str":"69988683","profile_image_url":"http://a0.twimg.com/profile_images/1211955817/avatar_7888_normal.gif","created_at":"Wed, 26 Jan 2011 04:25:23 +0000","from_user":"YNK33","id_str":"30119083059978240","metadata":{"result_type":"recent"},"to_user_id":null,"text":"hsndfile 0.5.0: Free and open source Haskell bindings for libsndfile http://bit.ly/gHaBWG Mac Os","id":30119083059978240,"from_user_id":69988683,"geo":null,"iso_language_code":"en","to_user_id_str":null,"source":"<a href="http://twitterfeed.com" rel="nofollow">twitterfeed</a>"},{"from_user_id_str":"81492","profile_image_url":"http://a1.twimg.com/profile_images/423894208/Picture_7_normal.jpg","created_at":"Wed, 26 Jan 2011 04:24:28 +0000","from_user":"satzz","id_str":"30118851488251904","metadata":{"result_type":"recent"},"to_user_id":null,"text":"Emacs\u306e\u30e2\u30fc\u30c9\u8868\u793a\u304c\u4eca(Ruby Controller Outputz RoR Flymake REl hs)\u3068\u306a\u3063\u3066\u3066\u3088\u304f\u308f\u304b\u3089\u306a\u3044\u3093\u3060\u3051\u3069\u6700\u5f8c\u306eREl\u3068\u304bhs\u3063\u3066\u4f55\u3060\u308d\u3046\u2026haskell\u3068\u304b2\u5e74\u4ee5\u4e0a\u66f8\u3044\u3066\u306a\u3044\u3051\u3069\u2026","id":30118851488251904,"from_user_id":81492,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://www.hootsuite.com" rel="nofollow">HootSuite</a>"},{"from_user_id_str":"9518356","profile_image_url":"http://a2.twimg.com/profile_images/119165723/ocaml-icon_normal.png","created_at":"Wed, 26 Jan 2011 04:19:19 +0000","from_user":"planet_ocaml","id_str":"30117557788741632","metadata":{"result_type":"recent"},"to_user_id":null,"text":"I so miss #haskell type classes in #ocaml - i want to do something like refinement. Also why does ocaml not have... http://bit.ly/geYRwt","id":30117557788741632,"from_user_id":9518356,"geo":null,"iso_language_code":"en","to_user_id_str":null,"source":"<a href="http://twitterfeed.com" rel="nofollow">twitterfeed</a>"},{"from_user_id_str":"218059","profile_image_url":"http://a1.twimg.com/profile_images/1053837723/twitter-icon9_normal.jpg","created_at":"Wed, 26 Jan 2011 04:16:32 +0000","from_user":"aprikip","id_str":"30116854940835840","metadata":{"result_type":"recent"},"to_user_id":null,"text":"yatex-mode\u3084haskell-mode\u306e\u3053\u3068\u3067\u3059\u306d\u3001\u308f\u304b\u308a\u307e\u3059\u3002","id":30116854940835840,"from_user_id":218059,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://sites.google.com/site/yorufukurou/" rel="nofollow">YoruFukurou</a>"},{"from_user_id_str":"216363","profile_image_url":"http://a1.twimg.com/profile_images/72454310/Tim-Avatar_normal.png","created_at":"Wed, 26 Jan 2011 04:15:30 +0000","from_user":"dysinger","id_str":"30116594684264448","metadata":{"result_type":"recent"},"to_user_id":null,"text":"Haskell in Hawaii tonight for me... #fun","id":30116594684264448,"from_user_id":216363,"geo":null,"iso_language_code":"en","to_user_id_str":null,"source":"<a href="http://www.nambu.com/" rel="nofollow">Nambu</a>"},{"from_user_id_str":"1774820","profile_image_url":"http://a2.twimg.com/profile_images/61169291/dan_desert_thumb_normal.jpg","created_at":"Wed, 26 Jan 2011 04:13:36 +0000","from_user":"DanMil","id_str":"30116117682851840","metadata":{"result_type":"recent"},"to_user_id":1594784,"text":"@ojrac @chewedwire @tomheon Haskell isn't a language, it's a belief system. A seductive one...","id":30116117682851840,"from_user_id":1774820,"to_user":"ojrac","geo":null,"iso_language_code":"en","to_user_id_str":"1594784","source":"<a href="http://twitter.com/">web</a>"},{"from_user_id_str":"659256","profile_image_url":"http://a0.twimg.com/profile_images/746976711/angular-final_normal.jpg","created_at":"Wed, 26 Jan 2011 04:11:06 +0000","from_user":"djspiewak","id_str":"30115488931520512","metadata":{"result_type":"recent"},"to_user_id":null,"text":"One of the very nice things about Haskell as opposed to SML is the reduced proliferation of identifiers (e.g. andb, orb, etc). #typeclasses","id":30115488931520512,"from_user_id":659256,"geo":null,"iso_language_code":"en","to_user_id_str":null,"source":"<a href="http://itunes.apple.com/us/app/twitter/id409789998?mt=12" rel="nofollow">Twitter for Mac</a>"},{"from_user_id_str":"144546280","profile_image_url":"http://a1.twimg.com/a/1295051201/images/default_profile_1_normal.png","created_at":"Wed, 26 Jan 2011 04:06:12 +0000","from_user":"listwarenet","id_str":"30114255890026496","metadata":{"result_type":"recent"},"to_user_id":null,"text":"http://www.listware.net/201101/haskell-cafe/84752-re-haskell-cafe-gpl-license-of-h-matrix-and-prelude-numeric.html Re: Haskell-c","id":30114255890026496,"from_user_id":144546280,"geo":null,"iso_language_code":"no","to_user_id_str":null,"source":"<a href="http://1e10.org/cloud/" rel="nofollow">1e10</a>"},{"from_user_id_str":"1594784","profile_image_url":"http://a2.twimg.com/profile_images/378515773/square-profile_normal.jpg","created_at":"Wed, 26 Jan 2011 04:01:29 +0000","from_user":"ojrac","id_str":"30113067333324800","metadata":{"result_type":"recent"},"to_user_id":null,"text":"RT @tomheon: @ojrac @chewedwire Don't worry, learning Haskell will not give you any clear idea what monad means.","id":30113067333324800,"from_user_id":1594784,"geo":null,"iso_language_code":"en","to_user_id_str":null,"source":"<a href="http://twitter.com/">web</a>"},{"from_user_id_str":"207589736","profile_image_url":"http://a3.twimg.com/profile_images/1225527428/headshot_1_normal.jpg","created_at":"Wed, 26 Jan 2011 04:00:13 +0000","from_user":"ashleevelazq101","id_str":"30112747555397632","metadata":{"result_type":"recent"},"to_user_id":null,"text":"Federal investigation finds safety violations at The Acadia Hospital: By Meg Haskell, BDN Staff The investigatio... http://bit.ly/dONnpn","id":30112747555397632,"from_user_id":207589736,"geo":null,"iso_language_code":"en","to_user_id_str":null,"source":"<a href="http://twitterfeed.com" rel="nofollow">twitterfeed</a>"},{"from_user_id_str":"17671137","profile_image_url":"http://a2.twimg.com/profile_images/290264834/Haskell-logo-outer-glow_normal.png","created_at":"Wed, 26 Jan 2011 03:58:00 +0000","from_user":"Hackage","id_str":"30112192346984448","metadata":{"result_type":"recent"},"to_user_id":null,"text":"streams 0.4, added by EdwardKmett: Various Haskell 2010 stream comonads http://bit.ly/idBkPe","id":30112192346984448,"from_user_id":17671137,"geo":null,"iso_language_code":"en","to_user_id_str":null,"source":"<a href="http://twitterfeed.com" rel="nofollow">twitterfeed</a>"},{"from_user_id_str":"17489366","profile_image_url":"http://a3.twimg.com/sticky/default_profile_images/default_profile_2_normal.png","created_at":"Wed, 26 Jan 2011 03:58:00 +0000","from_user":"aapnoot","id_str":"30112191881420800","metadata":{"result_type":"recent"},"to_user_id":null,"text":"streams 0.4, added by EdwardKmett: Various Haskell 2010 stream comonads http://bit.ly/idBkPe","id":30112191881420800,"from_user_id":17489366,"geo":null,"iso_language_code":"en","to_user_id_str":null,"source":"<a href="http://twitterfeed.com" rel="nofollow">twitterfeed</a>"},{"from_user_id_str":"8530482","profile_image_url":"http://a2.twimg.com/profile_images/137867266/n608671563_7396_normal.jpg","created_at":"Wed, 26 Jan 2011 03:50:12 +0000","from_user":"jeffmclamb","id_str":"30110229207187456","metadata":{"result_type":"recent"},"to_user_id":null,"text":"Angel - daemon to run and monitor processes like daemontools or god, written in Haskell http://ff.im/-wNyLk","id":30110229207187456,"from_user_id":8530482,"geo":null,"iso_language_code":"en","to_user_id_str":null,"source":"<a href="http://friendfeed.com" rel="nofollow">FriendFeed</a>"},{"from_user_id_str":"177539201","profile_image_url":"http://a0.twimg.com/profile_images/1178368800/img_normal.jpeg","created_at":"Wed, 26 Jan 2011 03:46:01 +0000","from_user":"tomheon","id_str":"30109174645919744","metadata":{"result_type":"recent"},"to_user_id":1594784,"text":"@ojrac @chewedwire Don't worry, learning Haskell will not give you any clear idea what monad means.","id":30109174645919744,"from_user_id":177539201,"to_user":"ojrac","geo":null,"iso_language_code":"en","to_user_id_str":"1594784","source":"<a href="http://twitter.com/">web</a>"},{"from_user_id_str":"1594784","profile_image_url":"http://a2.twimg.com/profile_images/378515773/square-profile_normal.jpg","created_at":"Wed, 26 Jan 2011 03:44:34 +0000","from_user":"ojrac","id_str":"30108808684503040","metadata":{"result_type":"recent"},"to_user_id":128028225,"text":"@chewedwire @tomheon Why are you making me curious about Haskell? I LIKE not knowing what monad means!!","id":30108808684503040,"from_user_id":1594784,"to_user":"chewedwire","geo":null,"iso_language_code":"en","to_user_id_str":"128028225","source":"<a href="http://twitter.com/">web</a>"},{"from_user_id_str":"23750094","profile_image_url":"http://a0.twimg.com/profile_images/951373780/Moeinthecar_normal.jpg","created_at":"Wed, 26 Jan 2011 03:41:54 +0000","from_user":"shokalshab","id_str":"30108140443795456","metadata":{"result_type":"recent"},"to_user_id":null,"text":"I'm at Magnitude Cheer @ Gymnastics Olympica USA (7735 Haskell Ave., btw Saticoy & Strathern, Van Nuys) http://4sq.com/gmXfaL","id":30108140443795456,"from_user_id":23750094,"geo":null,"iso_language_code":"en","place":{"id":"4e4a2a2f86cb2946","type_":"poi","full_name":"Gymnastics Olympica USA, Van Nuys"},"to_user_id_str":null,"source":"<a href="http://foursquare.com" rel="nofollow">foursquare</a>"},{"from_user_id_str":"8135112","profile_image_url":"http://a0.twimg.com/profile_images/1165240350/LIMITED_normal.jpg","created_at":"Wed, 26 Jan 2011 03:41:35 +0000","from_user":"Claricei","id_str":"30108059208515584","metadata":{"result_type":"recent"},"to_user_id":null,"text":"RT @kristenmchugh22: @KeithOlbermann Ryan looks like Jughead w/o the hat. And sounds as mealy-mouthed as Eddie Haskell.","id":30108059208515584,"from_user_id":8135112,"geo":null,"iso_language_code":"en","to_user_id_str":null,"source":"<a href="http://www.tweetdeck.com" rel="nofollow">TweetDeck</a>"},{"from_user_id_str":"128028225","profile_image_url":"http://a1.twimg.com/profile_images/1224994593/Coding_Drunk_normal.jpg","created_at":"Wed, 26 Jan 2011 03:40:02 +0000","from_user":"chewedwire","id_str":"30107670367182848","metadata":{"result_type":"recent"},"to_user_id":177539201,"text":"@tomheon Cool, I'll take a look. I feel like I should mention this: http://bit.ly/hVstDM","id":30107670367182848,"from_user_id":128028225,"to_user":"tomheon","geo":null,"iso_language_code":"en","to_user_id_str":"177539201","source":"<a href="http://twitter.com/">web</a>"},{"from_user_id_str":"8679778","profile_image_url":"http://a3.twimg.com/profile_images/1195318056/me_nyc_12_18_10_icon_normal.jpg","created_at":"Wed, 26 Jan 2011 03:38:42 +0000","from_user":"kristenmchugh22","id_str":"30107332381777920","metadata":{"result_type":"recent"},"to_user_id":756269,"text":"@KeithOlbermann Ryan looks like Jughead w/o the hat. And sounds as mealy-mouthed as Eddie Haskell.","id":30107332381777920,"from_user_id":8679778,"to_user":"KeithOlbermann","geo":null,"iso_language_code":"en","to_user_id_str":"756269","source":"<a href="http://www.tweetdeck.com" rel="nofollow">TweetDeck</a>"},{"from_user_id_str":"103316559","profile_image_url":"http://a1.twimg.com/profile_images/1179458751/bc3beab4-d59d-4e78-b13b-50747986cfa2_normal.png","created_at":"Wed, 26 Jan 2011 03:36:15 +0000","from_user":"cityslikr","id_str":"30106719153557504","metadata":{"result_type":"recent"},"to_user_id":null,"text":""Social safety net into a hammock." So says Eddie Haskell with the GOP response. #SOTU","id":30106719153557504,"from_user_id":103316559,"geo":null,"iso_language_code":"en","to_user_id_str":null,"source":"<a href="http://blackberry.com/twitter" rel="nofollow">Twitter for BlackBerry\u00ae</a>"},{"from_user_id_str":"169063143","profile_image_url":"http://a0.twimg.com/profile_images/1160506212/9697_1_normal.gif","created_at":"Wed, 26 Jan 2011 03:31:52 +0000","from_user":"wrkforce_safety","id_str":"30105614919143424","metadata":{"result_type":"recent"},"to_user_id":null,"text":"Federal investigation finds safety violations at The Acadia Hospital: By Meg Haskell, BDN Staff The investigatio... http://bit.ly/gA60C1","id":30105614919143424,"from_user_id":169063143,"geo":null,"iso_language_code":"en","to_user_id_str":null,"source":"<a href="http://twitterfeed.com" rel="nofollow">twitterfeed</a>"},{"from_user_id_str":"177539201","profile_image_url":"http://a0.twimg.com/profile_images/1178368800/img_normal.jpeg","created_at":"Wed, 26 Jan 2011 03:29:40 +0000","from_user":"tomheon","id_str":"30105060960632832","metadata":{"result_type":"recent"},"to_user_id":128028225,"text":"@chewedwire Great book on Haskell: http://oreilly.com/catalog/9780596514983","id":30105060960632832,"from_user_id":177539201,"to_user":"chewedwire","geo":null,"iso_language_code":"en","to_user_id_str":"128028225","source":"<a href="http://twitter.com/">web</a>"},{"from_user_id_str":"782692","profile_image_url":"http://a0.twimg.com/profile_images/1031304589/Profile.2007.1_normal.jpg","created_at":"Wed, 26 Jan 2011 03:29:19 +0000","from_user":"turnageb","id_str":"30104974591533057","metadata":{"result_type":"recent"},"to_user_id":null,"text":"RT @ovillalon: Paul Ryan solves the mystery of whatever happened to Eddie Haskell. #sotu","id":30104974591533057,"from_user_id":782692,"geo":null,"iso_language_code":"en","to_user_id_str":null,"source":"<a href="http://www.tweetdeck.com" rel="nofollow">TweetDeck</a>"},{"from_user_id_str":"128028225","profile_image_url":"http://a1.twimg.com/profile_images/1224994593/Coding_Drunk_normal.jpg","created_at":"Wed, 26 Jan 2011 03:28:04 +0000","from_user":"chewedwire","id_str":"30104657267265536","metadata":{"result_type":"recent"},"to_user_id":177539201,"text":"@tomheon I always loved the pattern matching in SML and it looks like Haskell is MUCH better at it. I'm messing around now at tryhaskell.org","id":30104657267265536,"from_user_id":128028225,"to_user":"tomheon","geo":null,"iso_language_code":"en","to_user_id_str":"177539201","source":"<a href="http://twitter.com/">web</a>"},{"from_user_id_str":"12834082","profile_image_url":"http://a3.twimg.com/profile_images/1083036140/mugshot_normal.png","created_at":"Wed, 26 Jan 2011 03:28:01 +0000","from_user":"ovillalon","id_str":"30104647213518848","metadata":{"result_type":"recent"},"to_user_id":null,"text":"Paul Ryan solves the mystery of whatever happened to Eddie Haskell. #sotu","id":30104647213518848,"from_user_id":12834082,"geo":null,"iso_language_code":"en","to_user_id_str":null,"source":"<a href="http://twitter.com/">web</a>"},{"from_user_id_str":"13540930","profile_image_url":"http://a1.twimg.com/profile_images/1205312219/23467_350321383101_821143101_5114147_3010041_n_normal.jpg","created_at":"Wed, 26 Jan 2011 03:26:02 +0000","from_user":"goodfox","id_str":"30104146455560192","metadata":{"result_type":"recent"},"to_user_id":10226179,"text":"@billykeene22 Bordeaux is one of my heroes. I was so excited when he accepted the invitation to campus. He's been a great friend to Haskell.","id":30104146455560192,"from_user_id":13540930,"to_user":"billykeene22","geo":null,"iso_language_code":"en","to_user_id_str":"10226179","source":"<a href="http://www.ubertwitter.com/bb/download.php" rel="nofollow">\u00dcberTwitter</a>"},{"from_user_id_str":"18616016","profile_image_url":"http://a2.twimg.com/profile_images/1173522726/214397343_normal.jpg","created_at":"Wed, 26 Jan 2011 03:25:18 +0000","from_user":"josej30","id_str":"30103962313031681","metadata":{"result_type":"recent"},"to_user_id":14870909,"text":"@cris7ian Ahh bueno multiparadigma ya es respetable :) Empezar\u00e9 a explotar la parte funcional de los lenguajes ahora #Haskell","id":30103962313031681,"from_user_id":18616016,"to_user":"Cris7ian","geo":null,"iso_language_code":"es","to_user_id_str":"14870909","source":"<a href="http://www.tweetdeck.com" rel="nofollow">TweetDeck</a>"},{"from_user_id_str":"14870909","profile_image_url":"http://a2.twimg.com/profile_images/1176930429/oso_yo_normal.png","created_at":"Wed, 26 Jan 2011 03:23:43 +0000","from_user":"Cris7ian","id_str":"30103562360983553","metadata":{"result_type":"recent"},"to_user_id":18616016,"text":"@josej30 hahaha no, es multiparadigma y es bastante lazy. Nothing like haskell, pero s\u00ed, el de Flash","id":30103562360983553,"from_user_id":14870909,"to_user":"josej30","geo":null,"iso_language_code":"es","to_user_id_str":"18616016","source":"<a href="http://www.echofon.com/" rel="nofollow">Echofon</a>"},{"from_user_id_str":"2421643","profile_image_url":"http://a0.twimg.com/profile_images/1190361665/ernestgrumbles-17_normal.jpg","created_at":"Wed, 26 Jan 2011 03:20:24 +0000","from_user":"ernestgrumbles","id_str":"30102730756333568","metadata":{"result_type":"recent"},"to_user_id":null,"text":"Wow... WolframAlpha did not know who Eddie Haskell is. Guess I'll never use that "knowledge engine" again.","id":30102730756333568,"from_user_id":2421643,"geo":null,"iso_language_code":"en","to_user_id_str":null,"source":"<a href="http://twitter.com/">web</a>"},{"from_user_id_str":"128028225","profile_image_url":"http://a1.twimg.com/profile_images/1224994593/Coding_Drunk_normal.jpg","created_at":"Wed, 26 Jan 2011 03:14:21 +0000","from_user":"chewedwire","id_str":"30101204428132352","metadata":{"result_type":"recent"},"to_user_id":177539201,"text":"@tomheon How is Haskell better/different from CL or Scheme? I honestly don't know, although I'm becoming more curious.","id":30101204428132352,"from_user_id":128028225,"to_user":"tomheon","geo":null,"iso_language_code":"en","to_user_id_str":"177539201","source":"<a href="http://twitter.com/">web</a>"},{"from_user_id_str":"13540930","profile_image_url":"http://a1.twimg.com/profile_images/1205312219/23467_350321383101_821143101_5114147_3010041_n_normal.jpg","created_at":"Wed, 26 Jan 2011 03:06:54 +0000","from_user":"goodfox","id_str":"30099329809129473","metadata":{"result_type":"recent"},"to_user_id":null,"text":"A day of vision & speeches. #SOTU now. And a wonderful Haskell Convocation address earlier today by Sinte Gleske President Lionel Bordeaux.","id":30099329809129473,"from_user_id":13540930,"geo":null,"iso_language_code":"en","to_user_id_str":null,"source":"<a href="http://www.ubertwitter.com/bb/download.php" rel="nofollow">\u00dcberTwitter</a>"},{"from_user_id_str":"119185220","profile_image_url":"http://a0.twimg.com/profile_images/1089027228/dfg_normal.jpg","created_at":"Wed, 26 Jan 2011 03:03:38 +0000","from_user":"LaLiciouz_03","id_str":"30098510623805440","metadata":{"result_type":"recent"},"to_user_id":null,"text":"The Game with the girl room 330 Haskell follow us...","id":30098510623805440,"from_user_id":119185220,"geo":null,"iso_language_code":"en","to_user_id_str":null,"source":"<a href="http://twitter.com/">web</a>"},{"from_user_id_str":"18616016","profile_image_url":"http://a2.twimg.com/profile_images/1173522726/214397343_normal.jpg","created_at":"Wed, 26 Jan 2011 02:57:25 +0000","from_user":"josej30","id_str":"30096946144215040","metadata":{"result_type":"recent"},"to_user_id":null,"text":"Voy a extra\u00f1ar Haskell cuando regrese al mundo imperativo. Hay alg\u00fan lenguaje imperativo que tenga este poder funcional? #ci3661","id":30096946144215040,"from_user_id":18616016,"geo":null,"iso_language_code":"es","to_user_id_str":null,"source":"<a href="http://www.tweetdeck.com" rel="nofollow">TweetDeck</a>"},{"from_user_id_str":"17671137","profile_image_url":"http://a2.twimg.com/profile_images/290264834/Haskell-logo-outer-glow_normal.png","created_at":"Wed, 26 Jan 2011 02:55:32 +0000","from_user":"Hackage","id_str":"30096471814574080","metadata":{"result_type":"recent"},"to_user_id":null,"text":"comonad-transformers 0.9.0, added by EdwardKmett: Haskell 98 comonad transformers http://bit.ly/h6xIsf","id":30096471814574080,"from_user_id":17671137,"geo":null,"iso_language_code":"no","to_user_id_str":null,"source":"<a href="http://twitterfeed.com" rel="nofollow">twitterfeed</a>"},{"from_user_id_str":"177539201","profile_image_url":"http://a0.twimg.com/profile_images/1178368800/img_normal.jpeg","created_at":"Wed, 26 Jan 2011 02:48:12 +0000","from_user":"tomheon","id_str":"30094626920603649","metadata":{"result_type":"recent"},"to_user_id":null,"text":"Every time I look at Haskell I love it more.","id":30094626920603649,"from_user_id":177539201,"geo":null,"iso_language_code":"en","to_user_id_str":null,"source":"<a href="http://twitter.com/">web</a>"},{"from_user_id_str":"60792568","profile_image_url":"http://a0.twimg.com/profile_images/1203647517/glenda-flash_normal.jpg","created_at":"Wed, 26 Jan 2011 02:40:42 +0000","from_user":"r_takaishi","id_str":"30092735935422464","metadata":{"result_type":"recent"},"to_user_id":null,"text":"Haskell\u3088\u308aD\u8a00\u8a9e\u304c\u4e0a\u3068\u306f\u601d\u308f\u306a\u304b\u3063\u305f\uff0e http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html","id":30092735935422464,"from_user_id":60792568,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://twmode.sf.net/" rel="nofollow">twmode</a>"},{"from_user_id_str":"160145510","profile_image_url":"http://a0.twimg.com/profile_images/1218108166/going_galt_normal.jpg","created_at":"Wed, 26 Jan 2011 02:39:31 +0000","from_user":"wtp1787","id_str":"30092439653974018","metadata":{"result_type":"recent"},"to_user_id":null,"text":"RT @KLSouth: Eddie Haskell Goes to Washington... "You look really nice tonight, Ms Cleaver"","id":30092439653974018,"from_user_id":160145510,"geo":null,"iso_language_code":"en","to_user_id_str":null,"source":"<a href="http://www.tweetdeck.com" rel="nofollow">TweetDeck</a>"},{"from_user_id_str":"96616016","profile_image_url":"http://a1.twimg.com/profile_images/1196978169/Picture0002_normal.jpg","created_at":"Wed, 26 Jan 2011 02:39:20 +0000","from_user":"MelissaRNMBA","id_str":"30092392203816960","metadata":{"result_type":"recent"},"to_user_id":14862975,"text":"@KLSouth At least Eddie Haskell was entertaining.","id":30092392203816960,"from_user_id":96616016,"to_user":"KLSouth","geo":null,"iso_language_code":"en","to_user_id_str":"14862975","source":"<a href="http://twitter.com/">web</a>"},{"from_user_id_str":"14862975","profile_image_url":"http://a0.twimg.com/profile_images/421596393/kls_4_normal.JPG","created_at":"Wed, 26 Jan 2011 02:38:29 +0000","from_user":"KLSouth","id_str":"30092178327871489","metadata":{"result_type":"recent"},"to_user_id":null,"text":"Eddie Haskell Goes to Washington... "You look really nice tonight, Ms Cleaver"","id":30092178327871489,"from_user_id":14862975,"geo":null,"iso_language_code":"en","to_user_id_str":null,"source":"<a href="http://www.tweetdeck.com" rel="nofollow">TweetDeck</a>"},{"from_user_id_str":"144546280","profile_image_url":"http://a1.twimg.com/a/1295051201/images/default_profile_1_normal.png","created_at":"Wed, 26 Jan 2011 02:36:17 +0000","from_user":"listwarenet","id_str":"30091626869161984","metadata":{"result_type":"recent"},"to_user_id":null,"text":"http://www.listware.net/201101/haskell-beginners/84641-haskell-beginners-wildcards-in-expressions.html Haskell-beginners - Wild","id":30091626869161984,"from_user_id":144546280,"geo":null,"iso_language_code":"no","to_user_id_str":null,"source":"<a href="http://1e10.org/cloud/" rel="nofollow">1e10</a>"},{"from_user_id_str":"24538048","profile_image_url":"http://a2.twimg.com/profile_images/1117267605/rope_normal.jpg","created_at":"Wed, 26 Jan 2011 02:23:14 +0000","from_user":"dbph","id_str":"30088341030440960","metadata":{"result_type":"recent"},"to_user_id":null,"text":"RT @dnene: Skilled Calisthenics. Haskell code that outputs python which spits ruby which emits the haskell source. http://j.mp/YlQUL via @mfeathers","id":30088341030440960,"from_user_id":24538048,"geo":null,"iso_language_code":"en","to_user_id_str":null,"source":"<a href="http://twitter.com/">web</a>"},{"from_user_id_str":"158951567","profile_image_url":"http://a3.twimg.com/profile_images/962721419/Logo_3_normal.jpg","created_at":"Wed, 26 Jan 2011 01:58:31 +0000","from_user":"YubaVetTech","id_str":"30082124207886336","metadata":{"result_type":"recent"},"to_user_id":null,"text":"Dr. Haskell has just been awarded the prestigious Hayward Award for \u2018Excellence in Education\u2019. This award honors... http://fb.me/QgQCxd74","id":30082124207886336,"from_user_id":158951567,"geo":null,"iso_language_code":"en","to_user_id_str":null,"source":"<a href="http://www.facebook.com/twitter" rel="nofollow">Facebook</a>"},{"from_user_id_str":"158951567","profile_image_url":"http://a3.twimg.com/profile_images/962721419/Logo_3_normal.jpg","created_at":"Wed, 26 Jan 2011 01:56:04 +0000","from_user":"YubaVetTech","id_str":"30081505476743168","metadata":{"result_type":"recent"},"to_user_id":null,"text":"Dr. Haskell has just been awarded the prestigous Haward Award for Excellence in Education. This award honors... http://fb.me/PC9mYmCR","id":30081505476743168,"from_user_id":158951567,"geo":null,"iso_language_code":"en","to_user_id_str":null,"source":"<a href="http://www.facebook.com/twitter" rel="nofollow">Facebook</a>"},{"from_user_id_str":"2331498","profile_image_url":"http://a3.twimg.com/profile_images/494632120/me_normal.jpg","created_at":"Wed, 26 Jan 2011 01:43:50 +0000","from_user":"Verus","id_str":"30078427155406848","metadata":{"result_type":"recent"},"to_user_id":79273052,"text":"@kami_joe \u3044\u3084\uff0c\u8ab2\u984c\u306f\u89e3\u6c7a\u5bfe\u8c61(\u30d1\u30ba\u30eb\u3068\u304b)\u3092\u4e0e\u3048\u3089\u308c\u3066\uff0c\u554f\u984c\u5b9a\u7fa9\u3068\u30d7\u30ed\u30b0\u30e9\u30df\u30f3\u30b0(\u6307\u5b9a\u8a00\u8a9e\u306fC++\u3082\u3057\u304f\u306fJava)\u3068\u3044\u3046\u3044\u308f\u3070\u666e\u901a\u306a\u8ab2\u984c\u3067\u306f\u3042\u308b\u3093\u3060\u3051\u3069\uff0e\u95a2\u6570\u578b\u8a00\u8a9e\u306fHaskell\u306e\u6388\u696d\u304c\u307e\u305f\u5225\u306b\u3042\u308b\u306e\uff0e","id":30078427155406848,"from_user_id":2331498,"to_user":"kami_joe","geo":null,"iso_language_code":"ja","to_user_id_str":"79273052","source":"<a href="http://itunes.apple.com/us/app/twitter/id409789998?mt=12" rel="nofollow">Twitter for Mac</a>"},{"from_user_id_str":"79151233","profile_image_url":"http://a2.twimg.com/a/1295051201/images/default_profile_2_normal.png","created_at":"Wed, 26 Jan 2011 01:40:37 +0000","from_user":"cz_newdrafts","id_str":"30077617361125376","metadata":{"result_type":"recent"},"to_user_id":null,"text":"Haskell programming language http://bit.ly/gpPAwB","id":30077617361125376,"from_user_id":79151233,"geo":null,"iso_language_code":"no","to_user_id_str":null,"source":"<a href="http://tommorris.org/" rel="nofollow">tommorris' hacksample</a>"},{"from_user_id_str":"2331498","profile_image_url":"http://a3.twimg.com/profile_images/494632120/me_normal.jpg","created_at":"Wed, 26 Jan 2011 01:02:57 +0000","from_user":"Verus","id_str":"30068139416879104","metadata":{"result_type":"recent"},"to_user_id":9252720,"text":"@shukukei Java\u3068C\u306f\u3042\u308b\u7a0b\u5ea6\u66f8\u3051\u3066\u3042\u305f\u308a\u307e\u3048\u306a\u3068\u3053\u308d\u304c\u3042\u308b\u304b\u3089\u306a\u30fc\uff0ePython\u306f\u500b\u4eba\u7684\u306b\u611f\u899a\u304c\u5408\u308f\u306a\u3044\uff0e\u611f\u899a\u306a\u306e\u3067\uff0c\u3082\u3046\u3069\u3046\u3057\u3088\u3046\u3082\u306a\u3044\uff57 \u3044\u307e\u306fScala\u3068Haskell\u3092\u3082\u3063\u3068\u6975\u3081\u305f\u3044\u3068\u3053\u308d\uff0e","id":30068139416879104,"from_user_id":2331498,"to_user":"shukukei","geo":null,"iso_language_code":"ja","to_user_id_str":"9252720","source":"<a href="http://itunes.apple.com/us/app/twitter/id409789998?mt=12" rel="nofollow">Twitter for Mac</a>"},{"from_user_id_str":"2781460","profile_image_url":"http://a0.twimg.com/profile_images/82526625/.joeyicon_normal.jpg","created_at":"Wed, 26 Jan 2011 01:02:35 +0000","from_user":"joeyhess","id_str":"30068046538219520","metadata":{"result_type":"recent"},"to_user_id":null,"text":"just figured out that I can use parameterized types to remove a dependency loop in git-annex's type definitions. whee #haskell","id":30068046538219520,"from_user_id":2781460,"geo":null,"iso_language_code":"en","to_user_id_str":null,"source":"<a href="http://identi.ca" rel="nofollow">identica</a>"},{"from_user_id_str":"144546280","profile_image_url":"http://a1.twimg.com/a/1295051201/images/default_profile_1_normal.png","created_at":"Wed, 26 Jan 2011 00:54:22 +0000","from_user":"listwarenet","id_str":"30065977920061440","metadata":{"result_type":"recent"},"to_user_id":null,"text":"http://www.listware.net/201101/haskell-beginners/84466-haskell-beginners-bytestring-question.html Haskell-beginners - Bytestrin","id":30065977920061440,"from_user_id":144546280,"geo":null,"iso_language_code":"no","to_user_id_str":null,"source":"<a href="http://1e10.org/cloud/" rel="nofollow">1e10</a>"},{"from_user_id_str":"1291845","profile_image_url":"http://a0.twimg.com/profile_images/1225743404/ThinOxygen-small-opaque-solidarity_normal.png","created_at":"Wed, 26 Jan 2011 00:52:07 +0000","from_user":"_aaron_","id_str":"30065412242669568","metadata":{"result_type":"recent"},"to_user_id":null,"text":"wanted: librly licensed high level native compiled lang with min runtime (otherwise cobra/mono would be perfect) for win. lua? haskell? ooc?","id":30065412242669568,"from_user_id":1291845,"geo":null,"iso_language_code":"en","to_user_id_str":null,"source":"<a href="http://twitter.com/">web</a>"},{"from_user_id_str":"5912444","profile_image_url":"http://a2.twimg.com/profile_images/546261026/ssf0xg11_normal.jpg","created_at":"Wed, 26 Jan 2011 00:45:45 +0000","from_user":"shelarcy","id_str":"30063810773516288","metadata":{"result_type":"recent"},"to_user_id":null,"text":"RT @Hackage: download 0.3.1.1, added by MagnusTherning: High-level file download based on URLs http://bit.ly/eHfiJB","id":30063810773516288,"from_user_id":5912444,"geo":null,"iso_language_code":"en","to_user_id_str":null,"source":"<a href="http://twitterfeed.com" rel="nofollow">twitterfeed</a>"},{"from_user_id_str":"135993","profile_image_url":"http://a2.twimg.com/profile_images/1190667086/myface2010small_normal.jpg","created_at":"Wed, 26 Jan 2011 00:41:00 +0000","from_user":"kudzu_naoki","id_str":"30062613287141376","metadata":{"result_type":"recent"},"to_user_id":null,"text":"RT @tanakh: \u9b54\u6cd5Haskell\u5c11\u5973\u5019\u88dc\u3092\u63a2\u3059\u306e\u3082\u5927\u5909\u306a\u3093\u3060","id":30062613287141376,"from_user_id":135993,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://www.hootsuite.com" rel="nofollow">HootSuite</a>"},{"from_user_id_str":"52620546","profile_image_url":"http://a1.twimg.com/profile_images/434693356/twitter-icon_normal.png","created_at":"Wed, 26 Jan 2011 00:40:25 +0000","from_user":"omasanori","id_str":"30062465656033280","metadata":{"result_type":"recent"},"to_user_id":null,"text":"\u9b54\u6cd5Haskell\u5c11\u5973\u306e\u4e00\u65e5\u306fGHC HEAD\u306e\u30d3\u30eb\u30c9\u304b\u3089\u59cb\u307e\u308b","id":30062465656033280,"from_user_id":52620546,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://www.movatwi.jp" rel="nofollow">www.movatwi.jp</a>"},{"from_user_id_str":"52620546","profile_image_url":"http://a1.twimg.com/profile_images/434693356/twitter-icon_normal.png","created_at":"Wed, 26 Jan 2011 00:37:12 +0000","from_user":"omasanori","id_str":"30061656331526144","metadata":{"result_type":"recent"},"to_user_id":null,"text":"RT @tanakh: \u50d5\u3068\u5951\u7d04\u3057\u3066\u9b54\u6cd5Haskell\u5c11\u5973\u306b\u306a\u308d\u3046\u3088\uff01","id":30061656331526144,"from_user_id":52620546,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://www.hootsuite.com" rel="nofollow">HootSuite</a>"},{"from_user_id_str":"135993","profile_image_url":"http://a2.twimg.com/profile_images/1190667086/myface2010small_normal.jpg","created_at":"Wed, 26 Jan 2011 00:35:42 +0000","from_user":"kudzu_naoki","id_str":"30061282665168896","metadata":{"result_type":"recent"},"to_user_id":null,"text":"RT @tanakh: \u50d5\u3068\u5951\u7d04\u3057\u3066\u9b54\u6cd5Haskell\u5c11\u5973\u306b\u306a\u308d\u3046\u3088\uff01","id":30061282665168896,"from_user_id":135993,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://www.hootsuite.com" rel="nofollow">HootSuite</a>"},{"from_user_id_str":"1631333","profile_image_url":"http://a1.twimg.com/profile_images/81268862/profile300_normal.jpg","created_at":"Wed, 26 Jan 2011 00:30:02 +0000","from_user":"qnighy","id_str":"30059855884582913","metadata":{"result_type":"recent"},"to_user_id":null,"text":"RT @tanakh: \u50d5\u3068\u5951\u7d04\u3057\u3066\u9b54\u6cd5Haskell\u5c11\u5973\u306b\u306a\u308d\u3046\u3088\uff01","id":30059855884582913,"from_user_id":1631333,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://www.hootsuite.com" rel="nofollow">HootSuite</a>"},{"from_user_id_str":"9093754","profile_image_url":"http://a1.twimg.com/profile_images/99435906/PHD_3d_col_blk_normal.jpg","created_at":"Wed, 26 Jan 2011 00:26:20 +0000","from_user":"phdwine","id_str":"30058925516656640","metadata":{"result_type":"recent"},"to_user_id":null,"text":"Last weekend of Tri Nations Tasting with PHD wines at Haskell Vineyards. Hope you didn't miss the Pinot Noir tasting last week !","id":30058925516656640,"from_user_id":9093754,"geo":null,"iso_language_code":"en","to_user_id_str":null,"source":"<a href="http://www.tweetdeck.com" rel="nofollow">TweetDeck</a>"},{"from_user_id_str":"2119923","profile_image_url":"http://a2.twimg.com/profile_images/1096701078/djayprofile_normal.jpg","created_at":"Wed, 26 Jan 2011 00:21:14 +0000","from_user":"djay75","id_str":"30057639543050240","metadata":{"result_type":"recent"},"to_user_id":null,"text":"RT @dnene: Skilled Calisthenics. Haskell code that outputs python which spits ruby which emits the haskell source. http://j.mp/YlQUL via @mfeathers","id":30057639543050240,"from_user_id":2119923,"geo":null,"iso_language_code":"en","to_user_id_str":null,"source":"<a href="http://twitter.com/">web</a>"},{"from_user_id_str":"134323731","profile_image_url":"http://a2.twimg.com/profile_images/1225818824/IMG00518-20110125-1547_normal.jpg","created_at":"Wed, 26 Jan 2011 00:19:30 +0000","from_user":"PrinceOfBrkeley","id_str":"30057205554216960","metadata":{"result_type":"recent"},"to_user_id":167093027,"text":"@PayThaPrince go to haskell.","id":30057205554216960,"from_user_id":134323731,"to_user":"PayThaPrince","geo":null,"iso_language_code":"en","to_user_id_str":"167093027","source":"<a href="http://blackberry.com/twitter" rel="nofollow">Twitter for BlackBerry\u00ae</a>"},{"from_user_id_str":"705857","profile_image_url":"http://a1.twimg.com/profile_images/429483912/ben_twitter_normal.jpg","created_at":"Wed, 26 Jan 2011 00:03:28 +0000","from_user":"bennadel","id_str":"30053166972141569","metadata":{"result_type":"recent"},"to_user_id":null,"text":"Using #Homebrew to install Haskell - the last of the Seven Languages (in Seven Weeks) http://bit.ly/eA9Cv1 This has been some journey.","id":30053166972141569,"from_user_id":705857,"geo":null,"iso_language_code":"en","to_user_id_str":null,"source":"<a href="http://www.tweetdeck.com" rel="nofollow">TweetDeck</a>"},{"from_user_id_str":"251466","profile_image_url":"http://a2.twimg.com/profile_images/1194100934/pass_normal.jpg","created_at":"Wed, 26 Jan 2011 00:02:54 +0000","from_user":"simonszu","id_str":"30053025502466048","metadata":{"result_type":"recent"},"to_user_id":null,"text":"Ouh yeah! Ich werde doch produktiv sein, diese Semesterferien. Ich werde funktional Programmieren lernen. #haskell, Baby.","id":30053025502466048,"from_user_id":251466,"geo":null,"iso_language_code":"de","to_user_id_str":null,"source":"<a href="http://www.echofon.com/" rel="nofollow">Echofon</a>"},{"from_user_id_str":"357786","profile_image_url":"http://a0.twimg.com/profile_images/612044841/FM_2010_normal.jpg","created_at":"Tue, 25 Jan 2011 23:59:13 +0000","from_user":"diligiant","id_str":"30052100973006848","metadata":{"result_type":"recent"},"to_user_id":null,"text":"RT @paulrbrown: "...we only discovered a single bug after compilation." (http://t.co/K0wlEYz) #haskell","id":30052100973006848,"from_user_id":357786,"geo":null,"iso_language_code":"en","to_user_id_str":null,"source":"<a href="http://itunes.apple.com/us/app/twitter/id409789998?mt=12" rel="nofollow">Twitter for Mac</a>"},{"from_user_id_str":"101597523","profile_image_url":"http://a1.twimg.com/profile_images/1206183256/2010-12-12-204902_normal.jpg","created_at":"Tue, 25 Jan 2011 23:54:46 +0000","from_user":"wlad_kent","id_str":"30050977964892160","metadata":{"result_type":"recent"},"to_user_id":86297184,"text":"@Nilson_Neto Isso eh bem basico. quando vc estiver estudando recurs\u00e3o em Haskell, ai vc vai ver oq eh papo de nerd - kkk - 1\u00ba periodo isso.","id":30050977964892160,"from_user_id":101597523,"to_user":"Nilson_Neto","geo":null,"iso_language_code":"pt","to_user_id_str":"86297184","source":"<a href="http://twitter.com/">web</a>"},{"from_user_id_str":"144546280","profile_image_url":"http://a1.twimg.com/a/1295051201/images/default_profile_1_normal.png","created_at":"Tue, 25 Jan 2011 23:51:22 +0000","from_user":"listwarenet","id_str":"30050123383832577","metadata":{"result_type":"recent"},"to_user_id":null,"text":"http://www.listware.net/201101/haskell-cafe/84336-haskell-cafe-monomorphic-let-bindings-and-darcs.html Haskell-cafe - Monomorph","id":30050123383832577,"from_user_id":144546280,"geo":null,"iso_language_code":"en","to_user_id_str":null,"source":"<a href="http://1e10.org/cloud/" rel="nofollow">1e10</a>"},{"from_user_id_str":"5776901","profile_image_url":"http://a0.twimg.com/profile_images/472682157/lucabw_normal.JPG","created_at":"Tue, 25 Jan 2011 23:48:40 +0000","from_user":"lsbardel","id_str":"30049446469312512","metadata":{"result_type":"recent"},"to_user_id":null,"text":"Very interesting technology stack these guys use http://bit.ly/ghAjS7 #python #redis #haskell","id":30049446469312512,"from_user_id":5776901,"geo":null,"iso_language_code":"en","to_user_id_str":null,"source":"<a href="http://www.tweetdeck.com" rel="nofollow">TweetDeck</a>"},{"from_user_id_str":"3005901","profile_image_url":"http://a0.twimg.com/profile_images/278943006/Lone_Pine_Peak_-_Peter_200x200_normal.jpg","created_at":"Tue, 25 Jan 2011 23:45:48 +0000","from_user":"pmonks","id_str":"30048721110573056","metadata":{"result_type":"recent"},"to_user_id":203834278,"text":"@techielicous Haskell: http://bit.ly/gy3oFi ;-)","id":30048721110573056,"from_user_id":3005901,"to_user":"techielicous","geo":null,"iso_language_code":"en","to_user_id_str":"203834278","source":"<a href="http://www.tweetdeck.com" rel="nofollow">TweetDeck</a>"},{"from_user_id_str":"162697074","profile_image_url":"http://a2.twimg.com/profile_images/826205838/ryan3_normal.jpg","created_at":"Tue, 25 Jan 2011 23:44:47 +0000","from_user":"TheRonaldMCD","id_str":"30048468781244416","metadata":{"result_type":"recent"},"to_user_id":null,"text":"I'm at Aldi Food Market (4122 Gaston Ave, Haskell, Dallas) http://4sq.com/ekqRY7","id":30048468781244416,"from_user_id":162697074,"geo":null,"iso_language_code":"no","to_user_id_str":null,"source":"<a href="http://foursquare.com" rel="nofollow">foursquare</a>"},{"from_user_id_str":"203834278","profile_image_url":"http://a0.twimg.com/profile_images/1223375080/me_normal.jpg","created_at":"Tue, 25 Jan 2011 23:44:04 +0000","from_user":"techielicous","id_str":"30048286589067264","metadata":{"result_type":"recent"},"to_user_id":3005901,"text":"@pmonks I was thinking Haskell or Scheme","id":30048286589067264,"from_user_id":203834278,"to_user":"pmonks","geo":null,"iso_language_code":"en","to_user_id_str":"3005901","source":"<a href="http://www.tweetdeck.com" rel="nofollow">TweetDeck</a>"},{"from_user_id_str":"537690","profile_image_url":"http://a3.twimg.com/profile_images/45665122/nushiostamp_normal.jpg","created_at":"Tue, 25 Jan 2011 23:38:14 +0000","from_user":"nushio","id_str":"30046818658164737","metadata":{"result_type":"recent"},"to_user_id":null,"text":"\u305d\u3046\u3044\u3084\u5951\u7d04\u306b\u3088\u308b\u30d7\u30ed\u30b0\u30e9\u30df\u30f3\u30b0\u3068\u304b\u3042\u3063\u305f\u306a\u3002Haskell\u306a\u3093\u304b\u3088\u308a\u3042\u3063\u3061\u306e\u65b9\u304c\u9b54\u6cd5\u5c11\u5973\u547c\u3070\u308f\u308a\u306b\u3075\u3055\u308f\u3057\u3044\u3002","id":30046818658164737,"from_user_id":537690,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://twitter.com/">web</a>"},{"from_user_id_str":"181192","profile_image_url":"http://a2.twimg.com/profile_images/1089890701/q530888600_9828_normal.jpg","created_at":"Tue, 25 Jan 2011 23:38:03 +0000","from_user":"aodag","id_str":"30046772223016960","metadata":{"result_type":"recent"},"to_user_id":null,"text":"RT @omasanori: \u300c\u3082\u3046\u4f55\u5e74\u3082Haskell\u306e\u3053\u3068\u3057\u304b\u8003\u3048\u3066\u306a\u304b\u3063\u305f\u304b\u3089\u306a\u3001\u30eb\u30fc\u30d7\u306e\u4f7f\u3044\u65b9\u5fd8\u308c\u3066\u305f\u300d","id":30046772223016960,"from_user_id":181192,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://www.movatwi.jp" rel="nofollow">www.movatwi.jp</a>"},{"from_user_id_str":"5886055","profile_image_url":"http://a3.twimg.com/profile_images/85531669/ichi_normal.jpg","created_at":"Tue, 25 Jan 2011 23:37:53 +0000","from_user":"kanaya","id_str":"30046729243983873","metadata":{"result_type":"recent"},"to_user_id":null,"text":"\u9e97\u3057\u3044\u3002\u201c@omasanori: \u300c\u3082\u3046\u4f55\u5e74\u3082Haskell\u306e\u3053\u3068\u3057\u304b\u8003\u3048\u3066\u306a\u304b\u3063\u305f\u304b\u3089\u306a\u3001\u30eb\u30fc\u30d7\u306e\u4f7f\u3044\u65b9\u5fd8\u308c\u3066\u305f\u300d\u201d","id":30046729243983873,"from_user_id":5886055,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://itunes.apple.com/app/twitter/id333903271?mt=8" rel="nofollow">Twitter for iPad</a>"},{"from_user_id_str":"52620546","profile_image_url":"http://a1.twimg.com/profile_images/434693356/twitter-icon_normal.png","created_at":"Tue, 25 Jan 2011 23:36:26 +0000","from_user":"omasanori","id_str":"30046367187476481","metadata":{"result_type":"recent"},"to_user_id":null,"text":"\u300c\u3082\u3046\u4f55\u5e74\u3082Haskell\u306e\u3053\u3068\u3057\u304b\u8003\u3048\u3066\u306a\u304b\u3063\u305f\u304b\u3089\u306a\u3001\u30eb\u30fc\u30d7\u306e\u4f7f\u3044\u65b9\u5fd8\u308c\u3066\u305f\u300d","id":30046367187476481,"from_user_id":52620546,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://www.movatwi.jp" rel="nofollow">www.movatwi.jp</a>"},{"from_user_id_str":"1659992","profile_image_url":"http://a1.twimg.com/profile_images/504488750/1_normal.jpg","created_at":"Tue, 25 Jan 2011 23:16:13 +0000","from_user":"finalfusion","id_str":"30041278544609280","metadata":{"result_type":"recent"},"to_user_id":null,"text":"RT @necocen: Haskell\u306e\u30df\u30b5\u30ef\u3001\u3068\u3044\u3046\u3082\u306e\u3092\u8003\u3048\u3066\u307f\u3066\u3071\u3063\u3068\u3057\u306a\u3044","id":30041278544609280,"from_user_id":1659992,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://twitter.com/" rel="nofollow">Twitter for iPhone</a>"},{"from_user_id_str":"272513","profile_image_url":"http://a2.twimg.com/profile_images/320244078/Mike_Painting2_normal.png","created_at":"Tue, 25 Jan 2011 23:05:09 +0000","from_user":"mikehadlow","id_str":"30038492373319680","metadata":{"result_type":"recent"},"to_user_id":null,"text":"Just written the same simple program in C#, F# and Haskell: 18, 12 and 9 LoC respectively. And I'm much better at C# than F# or Haskell.","id":30038492373319680,"from_user_id":272513,"geo":null,"iso_language_code":"en","to_user_id_str":null,"source":"<a href="http://www.tweetdeck.com" rel="nofollow">TweetDeck</a>"},{"from_user_id_str":"89393264","profile_image_url":"http://a0.twimg.com/profile_images/1169486472/020_portland_me_normal.jpg","created_at":"Tue, 25 Jan 2011 23:01:28 +0000","from_user":"newsportlandme","id_str":"30037564589084673","metadata":{"result_type":"recent"},"to_user_id":null,"text":"Governor's Choice to Run Maine DOC Under Scrutiny - MPBN: State Rep. Anne Haskell, a Portland Democrat, says Mai... http://bit.ly/fO30gC","id":30037564589084673,"from_user_id":89393264,"geo":null,"iso_language_code":"en","to_user_id_str":null,"source":"<a href="http://twitterfeed.com" rel="nofollow">twitterfeed</a>"},{"from_user_id_str":"38138","profile_image_url":"http://a3.twimg.com/profile_images/1212565885/Screen_shot_2011-01-11_at_5.28.47_PM_normal.png","created_at":"Tue, 25 Jan 2011 22:59:55 +0000","from_user":"michaelneale","id_str":"30037174615281664","metadata":{"result_type":"recent"},"to_user_id":null,"text":"The haskell EvilMangler http://t.co/P2Tls7J","id":30037174615281664,"from_user_id":38138,"geo":null,"iso_language_code":"no","to_user_id_str":null,"source":"<a href="http://itunes.apple.com/us/app/twitter/id409789998?mt=12" rel="nofollow">Twitter for Mac</a>"},{"from_user_id_str":"45692","profile_image_url":"http://a3.twimg.com/profile_images/1177741507/dogkarno_r_normal.jpg","created_at":"Tue, 25 Jan 2011 22:45:06 +0000","from_user":"karno","id_str":"30033448286552064","metadata":{"result_type":"recent"},"to_user_id":null,"text":"Haskell\u3063\u3066\u95a2\u6570\u306b\u30ab\u30ec\u30fc\u7c89\u3076\u3061\u8fbc\u3080\u3068\u304b\u306a\u3093\u3068\u304b","id":30033448286552064,"from_user_id":45692,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://yubitter.com/" rel="nofollow">yubitter</a>"},{"from_user_id_str":"27605","profile_image_url":"http://a2.twimg.com/profile_images/15826632/meron_normal.jpg","created_at":"Tue, 25 Jan 2011 22:44:23 +0000","from_user":"celeron1ghz","id_str":"30033268761956352","metadata":{"result_type":"recent"},"to_user_id":null,"text":"RT @necocen: Haskell\u306e\u30df\u30b5\u30ef\u3001\u3068\u3044\u3046\u3082\u306e\u3092\u8003\u3048\u3066\u307f\u3066\u3071\u3063\u3068\u3057\u306a\u3044","id":30033268761956352,"from_user_id":27605,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://twitter.com/" rel="nofollow">Twitter for iPhone</a>"},{"from_user_id_str":"12901","profile_image_url":"http://a1.twimg.com/profile_images/56091349/haruhi_nagato-Y_normal.jpg","created_at":"Tue, 25 Jan 2011 22:43:30 +0000","from_user":"necocen","id_str":"30033044035346432","metadata":{"result_type":"recent"},"to_user_id":null,"text":"\u307e\u3042Haskell\u77e5\u3089\u3093\u3057\u306d","id":30033044035346432,"from_user_id":12901,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://twitter.com/" rel="nofollow">Twitter for iPhone</a>"},{"from_user_id_str":"12901","profile_image_url":"http://a1.twimg.com/profile_images/56091349/haruhi_nagato-Y_normal.jpg","created_at":"Tue, 25 Jan 2011 22:42:54 +0000","from_user":"necocen","id_str":"30032894856531968","metadata":{"result_type":"recent"},"to_user_id":null,"text":"Haskell\u306e\u30df\u30b5\u30ef\u3001\u3068\u3044\u3046\u3082\u306e\u3092\u8003\u3048\u3066\u307f\u3066\u3071\u3063\u3068\u3057\u306a\u3044","id":30032894856531968,"from_user_id":12901,"geo":null,"iso_language_code":"ja","to_user_id_str":null,"source":"<a href="http://twitter.com/" rel="nofollow">Twitter for iPhone</a>"},{"from_user_id_str":"10821270","profile_image_url":"http://a0.twimg.com/profile_images/1195474259/Salto_Marlon_normal.jpg","created_at":"Tue, 25 Jan 2011 22:35:09 +0000","from_user":"jjedMoriAnktah","id_str":"30030942106025984","metadata":{"result_type":"recent"},"to_user_id":null,"text":""A Haskell program that outputs a Python program that outputs a Ruby program that outputs the original Haskell program" http://is.gd/E6Julu","id":30030942106025984,"from_user_id":10821270,"geo":null,"iso_language_code":"en","to_user_id_str":null,"source":"<a href="http://www.tweetdeck.com" rel="nofollow">TweetDeck</a>"},{"from_user_id_str":"7554762","profile_image_url":"http://a0.twimg.com/profile_images/100515212/ajay-photo_normal.jpg","created_at":"Tue, 25 Jan 2011 22:34:30 +0000","from_user":"comatose_kid","id_str":"30030780205899776","metadata":{"result_type":"recent"},"to_user_id":null,"text":"RT @bumptech: Bump Dev Blog - Why we use Haskell at Bump http://devblog.bu.mp/haskell-at-bump","id":30030780205899776,"from_user_id":7554762,"geo":null,"iso_language_code":"en","to_user_id_str":null,"source":"<a href="http://twitter.com/">web</a>"},{"from_user_id_str":"148474705","profile_image_url":"http://a0.twimg.com/profile_images/1119234716/fur_hat_-_gilbeys_vodka_-_life_-_11-30-1962_normal.JPG","created_at":"Tue, 25 Jan 2011 22:29:19 +0000","from_user":"landmvintage","id_str":"30029476003840000","metadata":{"result_type":"recent"},"to_user_id":null,"text":"RT @faerymoongodess: Magnificent Miriam Haskell Baroque Pearl Necklace by @MercyMadge http://etsy.me/hqRl51","id":30029476003840000,"from_user_id":148474705,"geo":null,"iso_language_code":"en","to_user_id_str":null,"source":"<a href="http://twitter.com/">web</a>"},{"from_user_id_str":"37715508","profile_image_url":"http://a1.twimg.com/profile_images/1207891411/ballerina_normal.jpg","created_at":"Tue, 25 Jan 2011 22:24:52 +0000","from_user":"faerymoongodess","id_str":"30028356326002688","metadata":{"result_type":"recent"},"to_user_id":null,"text":"Magnificent Miriam Haskell Baroque Pearl Necklace by @MercyMadge http://etsy.me/hqRl51","id":30028356326002688,"from_user_id":37715508,"geo":null,"iso_language_code":"en","to_user_id_str":null,"source":"<a href="http://twitter.com/">web</a>"},{"from_user_id_str":"17671137","profile_image_url":"http://a2.twimg.com/profile_images/290264834/Haskell-logo-outer-glow_normal.png","created_at":"Tue, 25 Jan 2011 22:17:16 +0000","from_user":"Hackage","id_str":"30026442456694784","metadata":{"result_type":"recent"},"to_user_id":null,"text":"base16-bytestring 0.1.0.0, added by BryanOSullivan: Fast base16 (hex) encoding and deconding for ByteStrings http://bit.ly/eu75TN","id":30026442456694784,"from_user_id":17671137,"geo":null,"iso_language_code":"en","to_user_id_str":null,"source":"<a href="http://twitterfeed.com" rel="nofollow">twitterfeed</a>"},{"from_user_id_str":"199750997","profile_image_url":"http://a3.twimg.com/sticky/default_profile_images/default_profile_2_normal.png","created_at":"Tue, 25 Jan 2011 22:12:07 +0000","from_user":"benreads","id_str":"30025146991382528","metadata":{"result_type":"recent"},"to_user_id":null,"text":"Writing Systems Software in a Functional Language -- brief, but fun. I want to see how well they can make Systems Haskell perform at scale.","id":30025146991382528,"from_user_id":199750997,"geo":null,"iso_language_code":"en","to_user_id_str":null,"source":"<a href="http://twitter.com/">web</a>"},{"from_user_id_str":"35359797","profile_image_url":"http://a1.twimg.com/profile_images/1173453785/48893_521140819_1896062_q_normal.jpg","created_at":"Tue, 25 Jan 2011 22:09:45 +0000","from_user":"jcawthorne1","id_str":"30024549265309696","metadata":{"result_type":"recent"},"to_user_id":null,"text":"Just saw Jeff Haskell give the middle finger!! Lol awesome","id":30024549265309696,"from_user_id":35359797,"geo":null,"iso_language_code":"en","to_user_id_str":null,"source":"<a href="http://twitter.com/" rel="nofollow">Twitter for iPhone</a>"},{"from_user_id_str":"13540930","profile_image_url":"http://a1.twimg.com/profile_images/1205312219/23467_350321383101_821143101_5114147_3010041_n_normal.jpg","created_at":"Tue, 25 Jan 2011 22:06:44 +0000","from_user":"goodfox","id_str":"30023790381498369","metadata":{"result_type":"recent"},"to_user_id":null,"text":"At the Haskell Convocation. (@ Haskell Indian Nations U Auditorium) http://4sq.com/eKKXyn","id":30023790381498369,"from_user_id":13540930,"geo":null,"iso_language_code":"en","to_user_id_str":null,"source":"<a href="http://foursquare.com" rel="nofollow">foursquare</a>"},{"from_user_id_str":"14674418","profile_image_url":"http://a2.twimg.com/profile_images/238230125/IMG_1030-1_normal.jpg","created_at":"Tue, 25 Jan 2011 22:02:31 +0000","from_user":"sanityinc","id_str":"30022731919523840","metadata":{"result_type":"recent"},"to_user_id":371289,"text":"@xshay Haskell's great, but Clojure's similarly lazy in all the ways that matter, and is more practical for day-to-day use.","id":30022731919523840,"from_user_id":14674418,"to_user":"xshay","geo":null,"iso_language_code":"en","to_user_id_str":"371289","source":"<a href="http://www.echofon.com/" rel="nofollow">Echofon</a>"},{"from_user_id_str":"371289","profile_image_url":"http://a2.twimg.com/profile_images/1113482439/me-brisbane_normal.jpg","created_at":"Tue, 25 Jan 2011 21:58:29 +0000","from_user":"xshay","id_str":"30021714444292096","metadata":{"result_type":"recent"},"to_user_id":null,"text":"Just made a lazy sequence of prime numbers in haskell. I'm smitten.","id":30021714444292096,"from_user_id":371289,"geo":null,"iso_language_code":"en","to_user_id_str":null,"source":"<a href="http://itunes.apple.com/us/app/twitter/id409789998?mt=12" rel="nofollow">Twitter for Mac</a>"},{"from_user_id_str":"199453873","profile_image_url":"http://a3.twimg.com/a/1294785484/images/default_profile_3_normal.png","created_at":"Tue, 25 Jan 2011 21:48:40 +0000","from_user":"stackfeed","id_str":"30019243982454784","metadata":{"result_type":"recent"},"to_user_id":null,"text":"Practical Scala reference manual, for searching things like method names: Hello, \n\nInspired by\nHaskell API Searc... http://bit.ly/g4zWZQ","id":30019243982454784,"from_user_id":199453873,"geo":null,"iso_language_code":"en","to_user_id_str":null,"source":"<a href="http://twitterfeed.com" rel="nofollow">twitterfeed</a>"},{"from_user_id_str":"17489366","profile_image_url":"http://a3.twimg.com/sticky/default_profile_images/default_profile_2_normal.png","created_at":"Tue, 25 Jan 2011 21:45:32 +0000","from_user":"aapnoot","id_str":"30018455189065728","metadata":{"result_type":"recent"},"to_user_id":null,"text":"download 0.3.1, added by MagnusTherning: High-level file download based on URLs http://bit.ly/i8mYvi","id":30018455189065728,"from_user_id":17489366,"geo":null,"iso_language_code":"en","to_user_id_str":null,"source":"<a href="http://twitterfeed.com" rel="nofollow">twitterfeed</a>"},{"from_user_id_str":"17489366","profile_image_url":"http://a3.twimg.com/sticky/default_profile_images/default_profile_2_normal.png","created_at":"Tue, 25 Jan 2011 21:45:31 +0000","from_user":"aapnoot","id_str":"30018452601180160","metadata":{"result_type":"recent"},"to_user_id":null,"text":"download 0.3.1.1, added by MagnusTherning: High-level file download based on URLs http://bit.ly/eHfiJB","id":30018452601180160,"from_user_id":17489366,"geo":null,"iso_language_code":"en","to_user_id_str":null,"source":"<a href="http://twitterfeed.com" rel="nofollow">twitterfeed</a>"},{"from_user_id_str":"17671137","profile_image_url":"http://a2.twimg.com/profile_images/290264834/Haskell-logo-outer-glow_normal.png","created_at":"Tue, 25 Jan 2011 21:45:31 +0000","from_user":"Hackage","id_str":"30018451867176960","metadata":{"result_type":"recent"},"to_user_id":null,"text":"download 0.3.1, added by MagnusTherning: High-level file download based on URLs http://bit.ly/i8mYvi","id":30018451867176960,"from_user_id":17671137,"geo":null,"iso_language_code":"en","to_user_id_str":null,"source":"<a href="http://twitterfeed.com" rel="nofollow">twitterfeed</a>"},{"from_user_id_str":"138502705","profile_image_url":"http://a1.twimg.com/profile_images/1083845614/yclogo_normal.gif","created_at":"Tue, 25 Jan 2011 21:45:04 +0000","from_user":"newsyc100","id_str":"30018340839755777","metadata":{"result_type":"recent"},"to_user_id":null,"text":"Haskell improves log processing 4x over Python http://devblog.bu.mp/haskell-at-bump (http://bit.ly/gQxxR8)","id":30018340839755777,"from_user_id":138502705,"geo":null,"iso_language_code":"en","to_user_id_str":null,"source":"<a href="http://news.ycombinator.com" rel="nofollow">newsyc</a>"},{"from_user_id_str":"1578246","profile_image_url":"http://a0.twimg.com/profile_images/59312315/avatar_simpson_small_normal.jpg","created_at":"Tue, 25 Jan 2011 21:43:32 +0000","from_user":"magthe","id_str":"30017953801969665","metadata":{"result_type":"recent"},"to_user_id":null,"text":"New version of download uploaded to #hackage #haskell","id":30017953801969665,"from_user_id":1578246,"geo":null,"iso_language_code":"en","to_user_id_str":null,"source":"<a href="http://api.supertweet.net" rel="nofollow">MyAuth API Proxy</a>"},{"from_user_id_str":"135838970","profile_image_url":"http://a2.twimg.com/profile_images/1079929891/logo_normal.png","created_at":"Tue, 25 Jan 2011 21:37:51 +0000","from_user":"reward999","id_str":"30016525180084224","metadata":{"result_type":"recent"},"to_user_id":null,"text":"Found Great Dane (Main & Haskell- Dallas): We found a great dane. 214-712-0000 http://bit.ly/fQ8iBw","id":30016525180084224,"from_user_id":135838970,"geo":null,"iso_language_code":"en","to_user_id_str":null,"source":"<a href="http://twitterfeed.com" rel="nofollow">twitterfeed</a>"},{"from_user_id_str":"137719265","profile_image_url":"http://a2.twimg.com/profile_images/1092224079/8__4__normal.jpg","created_at":"Tue, 25 Jan 2011 21:34:22 +0000","from_user":"WeiMatas","id_str":"30015646020411392","metadata":{"result_type":"recent"},"to_user_id":null,"text":"Fourth day Rez party Eddie Haskell County in second life \u2013 which took place in cabaret Tadd","id":30015646020411392,"from_user_id":137719265,"geo":null,"iso_language_code":"en","to_user_id_str":null,"source":"<a href="http://dlvr.it" rel="nofollow">dlvr.it</a>"},{"from_user_id_str":"144546280","profile_image_url":"http://a1.twimg.com/a/1295051201/images/default_profile_1_normal.png","created_at":"Tue, 25 Jan 2011 21:33:21 +0000","from_user":"listwarenet","id_str":"30015392571195392","metadata":{"result_type":"recent"},"to_user_id":null,"text":"http://www.listware.net/201101/haskell-cafe/83889-haskell-cafe-gpl-license-of-h-matrix-and-prelude-numeric.html Haskell-cafe -","id":30015392571195392,"from_user_id":144546280,"geo":null,"iso_language_code":"no","to_user_id_str":null,"source":"<a href="http://1e10.org/cloud/" rel="nofollow">1e10</a>"}],"max_id":30121530767708160,"since_id":0,"refresh_url":"?since_id=30121530767708160&q=haskell","next_page":"?page=2&max_id=30121530767708160&rpp=100&q=haskell","results_per_page":100,"page":1,"completed_in":1.195569,"since_id_str":"0","max_id_str":"30121530767708160","query":"haskell"} diff --git a/distributors-json/distributors-json.cabal b/distributors-json/distributors-json.cabal new file mode 100644 index 00000000..fa6ef42d --- /dev/null +++ b/distributors-json/distributors-json.cabal @@ -0,0 +1,362 @@ +cabal-version: 2.2 + +-- This file has been generated from package.yaml by hpack version 0.39.6. +-- +-- see: https://github.com/sol/hpack + +name: distributors-json +version: 0.1.0.0 +synopsis: JSON grammars, compatible with aeson & typed in TypeScript +description: One grammar per type parses, prints & encodes JSON compatibly with @aeson@, & declares its TypeScript types. See "Control.Lens.Grammar.Json". +category: JSON, Profunctors, Parsing +homepage: https://github.com/morphismtech/distributors#readme +bug-reports: https://github.com/morphismtech/distributors/issues +author: Eitan Chatav +maintainer: eitan.chatav@gmail.com +copyright: 2026 Eitan Chatav +license: BSD-3-Clause +license-file: LICENSE +build-type: Simple +extra-source-files: + README.md + test/Properties/fixture.d.ts + test/Properties/fixture.golden.d.ts + bench/data/buffer-builder.json + bench/data/geometry.json + bench/data/github-issues.json + bench/data/jp100.json + bench/data/twitter10.json + bench/data/twitter100.json + bench/data/README.md +extra-doc-files: + CHANGELOG.md + +source-repository head + type: git + location: https://github.com/morphismtech/distributors + +library + exposed-modules: + Control.Lens.Grammar.Json + Control.Lens.Grammar.TypeScript + other-modules: + Paths_distributors_json + autogen-modules: + Paths_distributors_json + hs-source-dirs: + src + default-extensions: + AllowAmbiguousTypes + Arrows + ConstraintKinds + DataKinds + DefaultSignatures + DeriveFoldable + DeriveFunctor + DeriveTraversable + DeriveGeneric + DerivingStrategies + DerivingVia + EmptyCase + FlexibleContexts + FlexibleInstances + FunctionalDependencies + GADTs + GeneralizedNewtypeDeriving + ImportQualifiedPost + ImpredicativeTypes + InstanceSigs + LambdaCase + MagicHash + MonoLocalBinds + QualifiedDo + QuantifiedConstraints + RankNTypes + RecursiveDo + ScopedTypeVariables + StandaloneDeriving + StandaloneKindSignatures + TemplateHaskell + TupleSections + TypeApplications + TypeFamilies + TypeOperators + UndecidableInstances + UndecidableSuperClasses + ghc-options: -Wall -Wcompat -Widentities -Wincomplete-record-updates -Wincomplete-uni-patterns -Wmissing-export-lists -Wmissing-home-modules -Wpartial-fields -Wredundant-constraints + build-depends: + aeson >=2.2 && <3 + , base >=4.20 && <5 + , bytestring >=0.11 && <1 + , containers >=0.6 && <1 + , data-fix >=0.3 && <1 + , distributors ==0.7.* + , distributors-grammar ==0.1.* + , dlist >=1.0 && <2 + , hashable >=1.4 && <2 + , lens >=5.0 && <6 + , network-uri >=2.6 && <3 + , primitive >=0.8 && <1 + , profunctors >=5.6 && <6 + , scientific >=0.3 && <1 + , sop-core >=0.5 && <1 + , strict >=0.5 && <1 + , tagged >=0.8 && <1 + , text ==2.* + , text-iso8601 >=0.1 && <1 + , text-short >=0.1 && <1 + , these >=1.2 && <2 + , time >=1.12 && <2 + , transformers >=0.5 && <1 + , unordered-containers >=0.2 && <1 + , uuid-types >=1.0 && <2 + , vector >=0.12 && <1 + , witherable >=0.4 && <1 + default-language: Haskell2010 + +test-suite doctests + type: exitcode-stdio-1.0 + main-is: Doctests.hs + other-modules: + Paths_distributors_json + autogen-modules: + Paths_distributors_json + hs-source-dirs: + doctest + default-extensions: + AllowAmbiguousTypes + Arrows + ConstraintKinds + DataKinds + DefaultSignatures + DeriveFoldable + DeriveFunctor + DeriveTraversable + DeriveGeneric + DerivingStrategies + DerivingVia + EmptyCase + FlexibleContexts + FlexibleInstances + FunctionalDependencies + GADTs + GeneralizedNewtypeDeriving + ImportQualifiedPost + ImpredicativeTypes + InstanceSigs + LambdaCase + MagicHash + MonoLocalBinds + QualifiedDo + QuantifiedConstraints + RankNTypes + RecursiveDo + ScopedTypeVariables + StandaloneDeriving + StandaloneKindSignatures + TemplateHaskell + TupleSections + TypeApplications + TypeFamilies + TypeOperators + UndecidableInstances + UndecidableSuperClasses + ghc-options: -Wall -Wcompat -Widentities -Wincomplete-record-updates -Wincomplete-uni-patterns -Wmissing-export-lists -Wmissing-home-modules -Wpartial-fields -Wredundant-constraints -threaded + build-depends: + aeson >=2.2 && <3 + , base >=4.20 && <5 + , bytestring >=0.11 && <1 + , containers >=0.6 && <1 + , data-fix >=0.3 && <1 + , distributors ==0.7.* + , distributors-grammar ==0.1.* + , distributors-json + , dlist >=1.0 && <2 + , doctest-parallel >=0.3 && <1 + , hashable >=1.4 && <2 + , lens >=5.0 && <6 + , network-uri >=2.6 && <3 + , primitive >=0.8 && <1 + , profunctors >=5.6 && <6 + , scientific >=0.3 && <1 + , sop-core >=0.5 && <1 + , strict >=0.5 && <1 + , tagged >=0.8 && <1 + , text ==2.* + , text-iso8601 >=0.1 && <1 + , text-short >=0.1 && <1 + , these >=1.2 && <2 + , time >=1.12 && <2 + , transformers >=0.5 && <1 + , unordered-containers >=0.2 && <1 + , uuid-types >=1.0 && <2 + , vector >=0.12 && <1 + , witherable >=0.4 && <1 + default-language: Haskell2010 + +test-suite test + type: exitcode-stdio-1.0 + main-is: Main.hs + other-modules: + Properties.Json + Properties.TypeScript + Paths_distributors_json + autogen-modules: + Paths_distributors_json + hs-source-dirs: + test + default-extensions: + AllowAmbiguousTypes + Arrows + ConstraintKinds + DataKinds + DefaultSignatures + DeriveFoldable + DeriveFunctor + DeriveTraversable + DeriveGeneric + DerivingStrategies + DerivingVia + EmptyCase + FlexibleContexts + FlexibleInstances + FunctionalDependencies + GADTs + GeneralizedNewtypeDeriving + ImportQualifiedPost + ImpredicativeTypes + InstanceSigs + LambdaCase + MagicHash + MonoLocalBinds + QualifiedDo + QuantifiedConstraints + RankNTypes + RecursiveDo + ScopedTypeVariables + StandaloneDeriving + StandaloneKindSignatures + TemplateHaskell + TupleSections + TypeApplications + TypeFamilies + TypeOperators + UndecidableInstances + UndecidableSuperClasses + ghc-options: -Wall -Wcompat -Widentities -Wincomplete-record-updates -Wincomplete-uni-patterns -Wmissing-export-lists -Wmissing-home-modules -Wpartial-fields -Wredundant-constraints + build-depends: + QuickCheck >=2.14 && <3 + , aeson >=2.2 && <3 + , base >=4.20 && <5 + , bytestring >=0.11 && <1 + , containers >=0.6 && <1 + , data-fix >=0.3 && <1 + , distributors ==0.7.* + , distributors-grammar ==0.1.* + , distributors-json + , dlist >=1.0 && <2 + , hashable >=1.4 && <2 + , hspec >=2.7 && <3 + , lens >=5.0 && <6 + , network-uri >=2.6 && <3 + , primitive >=0.8 && <1 + , profunctors >=5.6 && <6 + , quickcheck-instances >=0.3 && <1 + , scientific >=0.3 && <1 + , sop-core >=0.5 && <1 + , strict >=0.5 && <1 + , tagged >=0.8 && <1 + , text ==2.* + , text-iso8601 >=0.1 && <1 + , text-short >=0.1 && <1 + , these >=1.2 && <2 + , time >=1.12 && <2 + , transformers >=0.5 && <1 + , unordered-containers >=0.2 && <1 + , uuid-types >=1.0 && <2 + , vector >=0.12 && <1 + , witherable >=0.4 && <1 + default-language: Haskell2010 + +benchmark json + type: exitcode-stdio-1.0 + main-is: Main.hs + other-modules: + Documents + Paths_distributors_json + autogen-modules: + Paths_distributors_json + hs-source-dirs: + bench + default-extensions: + AllowAmbiguousTypes + Arrows + ConstraintKinds + DataKinds + DefaultSignatures + DeriveFoldable + DeriveFunctor + DeriveTraversable + DeriveGeneric + DerivingStrategies + DerivingVia + EmptyCase + FlexibleContexts + FlexibleInstances + FunctionalDependencies + GADTs + GeneralizedNewtypeDeriving + ImportQualifiedPost + ImpredicativeTypes + InstanceSigs + LambdaCase + MagicHash + MonoLocalBinds + QualifiedDo + QuantifiedConstraints + RankNTypes + RecursiveDo + ScopedTypeVariables + StandaloneDeriving + StandaloneKindSignatures + TemplateHaskell + TupleSections + TypeApplications + TypeFamilies + TypeOperators + UndecidableInstances + UndecidableSuperClasses + ghc-options: -Wall -Wcompat -Widentities -Wincomplete-record-updates -Wincomplete-uni-patterns -Wmissing-export-lists -Wmissing-home-modules -Wpartial-fields -Wredundant-constraints -O2 -rtsopts + build-depends: + aeson >=2.2 && <3 + , base >=4.20 && <5 + , bytestring >=0.11 && <1 + , containers >=0.6 && <1 + , data-fix >=0.3 && <1 + , deepseq >=1.4 && <2 + , distributors ==0.7.* + , distributors-grammar ==0.1.* + , distributors-json + , dlist >=1.0 && <2 + , file-embed >=0.0.15 && <1 + , hashable >=1.4 && <2 + , lens >=5.0 && <6 + , network-uri >=2.6 && <3 + , primitive >=0.8 && <1 + , profunctors >=5.6 && <6 + , scientific >=0.3 && <1 + , sop-core >=0.5 && <1 + , strict >=0.5 && <1 + , tagged >=0.8 && <1 + , tasty-bench >=0.3 && <1 + , text ==2.* + , text-iso8601 >=0.1 && <1 + , text-short >=0.1 && <1 + , these >=1.2 && <2 + , time >=1.12 && <2 + , transformers >=0.5 && <1 + , unordered-containers >=0.2 && <1 + , uuid-types >=1.0 && <2 + , vector >=0.12 && <1 + , witherable >=0.4 && <1 + default-language: Haskell2010 diff --git a/distributors-json/doctest/Doctests.hs b/distributors-json/doctest/Doctests.hs new file mode 100644 index 00000000..00d8f734 --- /dev/null +++ b/distributors-json/doctest/Doctests.hs @@ -0,0 +1,7 @@ +module Main (main) where + +import System.Environment (getArgs) +import Test.DocTest (mainFromCabal) + +main :: IO () +main = mainFromCabal "distributors-json" =<< getArgs diff --git a/distributors-json/package.yaml b/distributors-json/package.yaml new file mode 100644 index 00000000..106aad11 --- /dev/null +++ b/distributors-json/package.yaml @@ -0,0 +1,134 @@ +name: distributors-json +version: 0.1.0.0 +github: "morphismtech/distributors" +license: BSD-3-Clause +author: "Eitan Chatav" +maintainer: "eitan.chatav@gmail.com" +copyright: "2026 Eitan Chatav" + +extra-source-files: +- README.md +- test/Properties/*.d.ts +- bench/data/*.json +- bench/data/README.md +extra-doc-files: +- CHANGELOG.md + +category: JSON, Profunctors, Parsing +synopsis: JSON grammars, compatible with aeson & typed in TypeScript +description: + One grammar per type parses, prints & encodes JSON compatibly + with @aeson@, & declares its TypeScript types. + See "Control.Lens.Grammar.Json". + +dependencies: +- base >= 4.20 && < 5 +- aeson >= 2.2 && < 3 +- bytestring >= 0.11 && < 1 +- containers >= 0.6 && < 1 +- data-fix >= 0.3 && < 1 +- distributors >= 0.7 && < 0.8 +- distributors-grammar >= 0.1 && < 0.2 +- dlist >= 1.0 && < 2 +- hashable >= 1.4 && < 2 +- lens >= 5.0 && < 6 +- network-uri >= 2.6 && < 3 +- primitive >= 0.8 && < 1 +- profunctors >= 5.6 && < 6 +- scientific >= 0.3 && < 1 +- sop-core >= 0.5 && < 1 +- strict >= 0.5 && < 1 +- tagged >= 0.8 && < 1 +- text >= 2 && < 3 +- text-iso8601 >= 0.1 && < 1 +- text-short >= 0.1 && < 1 +- these >= 1.2 && < 2 +- time >= 1.12 && < 2 +- transformers >= 0.5 && < 1 +- unordered-containers >= 0.2 && < 1 +- uuid-types >= 1.0 && < 2 +- vector >= 0.12 && < 1 +- witherable >= 0.4 && < 1 + +ghc-options: +- -Wall +- -Wcompat +- -Widentities +- -Wincomplete-record-updates +- -Wincomplete-uni-patterns +- -Wmissing-export-lists +- -Wmissing-home-modules +- -Wpartial-fields +- -Wredundant-constraints + +library: + source-dirs: src + +default-extensions: +- AllowAmbiguousTypes +- Arrows +- ConstraintKinds +- DataKinds +- DefaultSignatures +- DeriveFoldable +- DeriveFunctor +- DeriveTraversable +- DeriveGeneric +- DerivingStrategies +- DerivingVia +- EmptyCase +- FlexibleContexts +- FlexibleInstances +- FunctionalDependencies +- GADTs +- GeneralizedNewtypeDeriving +- ImportQualifiedPost +- ImpredicativeTypes +- InstanceSigs +- LambdaCase +- MagicHash +- MonoLocalBinds +- QualifiedDo +- QuantifiedConstraints +- RankNTypes +- RecursiveDo +- ScopedTypeVariables +- StandaloneDeriving +- StandaloneKindSignatures +- TemplateHaskell +- TupleSections +- TypeApplications +- TypeFamilies +- TypeOperators +- UndecidableInstances +- UndecidableSuperClasses + +tests: + doctests: + main: Doctests.hs + source-dirs: doctest + ghc-options: -threaded + dependencies: + - distributors-json + - doctest-parallel >= 0.3 && < 1 + test: + main: Main.hs + source-dirs: test + dependencies: + - distributors-json + - hspec >= 2.7 && < 3 + - QuickCheck >= 2.14 && < 3 + - quickcheck-instances >= 0.3 && < 1 + +benchmarks: + json: + main: Main.hs + source-dirs: bench + ghc-options: + - -O2 + - -rtsopts + dependencies: + - deepseq >= 1.4 && < 2 + - distributors-json + - file-embed >= 0.0.15 && < 1 + - tasty-bench >= 0.3 && < 1 diff --git a/distributors-json/src/Control/Lens/Grammar/Json.hs b/distributors-json/src/Control/Lens/Grammar/Json.hs new file mode 100644 index 00000000..357f463c --- /dev/null +++ b/distributors-json/src/Control/Lens/Grammar/Json.hs @@ -0,0 +1,3501 @@ +{-# LANGUAGE OverloadedStrings, RequiredTypeArguments #-} + +{- | +Module : Control.Lens.Grammar.Json +Description : JSON grammars, compatible with aeson & typed in TypeScript +Copyright : (C) 2026 - Eitan Chatav +License : BSD-style (see the file LICENSE) +Maintainer : Eitan Chatav +Stability : provisional +Portability : non-portable + +A `Json` grammar of a type parses, prints & encodes its JSON, +compatibly with @aeson@, & types it in TypeScript, all at once. + += Deriving + +A `GHC.Generic` type derives its grammar, by @aeson@'s default options. + +>>> :{ +data Person = Person {name :: Text, age :: Int, email :: Maybe Text} + deriving stock (Show, Generic) + deriving anyclass Json +:} + +>>> LByteString.putStrLn (encodingToLazyByteString (jsonEncode (Person "Ada" 36 Nothing))) +{"name":"Ada","age":36,"email":null} +>>> jsonDecode @Person "{\"name\":\"Ada\",\"age\":36}" +Right (Person {name = "Ada", age = 36, email = Nothing}) + +Failures are located, & name what they expected. + +>>> either explain show (jsonDecode @Person "{\"name\":\"Ada\",\"age\":\"36\"}") +"Error in $.age: expected Int, but found \"36\"" + += @aeson@ + +t'ViaJson' derives @aeson@'s instances, & `jsonGeneric` takes +@aeson@'s `Aeson.Options`. + +>>> :{ +data Pet = Cat | Dog + deriving stock (Show, Generic) + deriving (Aeson.ToJSON, Aeson.FromJSON) via ViaJson Pet +instance Json Pet where + json = jsonGeneric Aeson.defaultOptions {Aeson.constructorTagModifier = map toLower} +:} + +>>> Aeson.encode [Cat, Dog] +"[\"cat\",\"dog\"]" + += Grammars + +A grammar is written once, with the combinators of `JsonVal`, +`JsonObj`, `JsonTup` & `JsonStr`, & `jsonTyped` 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) + >~ jsonObject ("x" !: json >*< "y" ?: json != 0) +:} + +>>> jsonDecode @Point "{\"x\":1}" +Right (Point 1.0 0.0) +>>> jsonPrint (Point 1 0) +Object (fromList [("x",Number 1.0)]) + +A tuple is an array of elements, & a sum is the alternative grammars +of its constructors, here tagged by string literals. + +>>> :{ +data Shape = Circle Double | Rectangle Double Double + deriving stock Show +_Circle :: Prism' Shape Double +_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 + [ _Circle >? jsonObject ("kind" !: "circle" >* "radius" !: json) + , _Rectangle >? jsonObject ("kind" !: "rectangle" >* "size" !: jsonTuple (jsonElem json >*< jsonElem json)) + ] +:} + +>>> LByteString.putStrLn (encodingToLazyByteString (jsonEncode [Circle 1, Rectangle 2 3])) +[{"kind":"circle","radius":1.0},{"kind":"rectangle","size":[2.0,3.0]}] + += Types + +`jsonTsPut` puts the TypeScript declarations of types' JSON, +which `jsonTsDeclarations` declares, by "Control.Lens.Grammar.TypeScript", +& `jsonType` types. + +>>> jsonTsPut (type '[Person, Point, Shape]) stdout +export type Double = number | null | "+inf" | "-inf"; +export type Int = number; +export type Person = { name: string; age: Int; email?: null | string }; +export type Point = { x: Double; y?: Double }; +export type Shape = { kind: "circle"; radius: Double } | { kind: "rectangle"; size: [Double, Double] }; +-} + +module Control.Lens.Grammar.Json + ( -- * Json + Json (..) + , jsonGeneric + , jsonParse + , jsonDecode + , jsonPrint + , jsonErrorPrint + , jsonEncode + , jsonErrorEncode + , ViaJson (..) + -- * Grammar + , JsonVal (..), jsonTyped + , JsonObj (..), (!=) + , JsonTup (..) + , JsonStr (..), jsonEnum + -- * Types + , jsonType + , jsonTsDeclarations + , jsonTsPut + , JsonType (..) + , JsonElements (..) + , JsonProperty (..) + -- * Errors + , JsonError (..) + , JsonErrorSort (..) + , jsonErrorMessage + ) where + +import Control.Applicative +import Control.Lens +import Control.Lens.Grammar +import Control.Lens.Comonocle (AComonocle, withComonocle) +import Control.Monad +import Control.Monad.Trans.Class (lift) +import Control.Monad.Trans.Reader (ReaderT, ask, local, runReaderT) +import Control.Monad.Trans.State.Strict +import Data.Aeson qualified as Aeson +import Data.Aeson.Encoding (Encoding) +import Data.Aeson.Encoding qualified as Encoding +import Data.Aeson.Encoding.Internal qualified as EncodingInternal +import Data.Aeson.Key (Key) +import Data.Aeson.Key qualified as Key +import Data.Aeson.KeyMap (KeyMap) +import Data.Aeson.KeyMap qualified as KeyMap +import Data.Aeson.Text (encodeToLazyText) +import Data.Aeson.Types + (DotNetTime (..), JSONPathElement (..), Object, Value (..)) +import Data.Aeson.Types qualified as Aeson (Parser, parserThrowError) +import Data.Char (isAlpha, isAlphaNum, isDigit, isUpper) +import Data.ByteString.Builder qualified as Builder +import Data.ByteString.Lazy qualified as LByteString +import Data.Coerce +import Data.DList (DList) +import Data.DList qualified as DList +import Data.DList.DNonEmpty (DNonEmpty) +import Data.DList.DNonEmpty qualified as DNonEmpty +import Data.Fix (Fix (..), Mu, Nu, foldMu, foldNu, unfoldMu, unfoldNu) +import Data.Fixed (Fixed, HasResolution (..), Nano) +import Data.Foldable (toList) +import Data.Function (fix) +import Data.Functor.Compose (Compose (..)) +import Data.Functor.Product qualified as Functor +import Data.Functor.Sum qualified as Functor +import Data.Functor.These (These1 (..)) +import Data.HashMap.Strict (HashMap) +import Data.HashMap.Strict qualified as HashMap +import Data.HashSet (HashSet) +import Data.HashSet qualified as HashSet +import Data.Hashable (Hashable) +import Data.Int (Int8, Int16, Int32, Int64) +import Data.IntMap (IntMap) +import Data.IntMap qualified as IntMap +import Data.IntSet (IntSet) +import Data.IntSet qualified as IntSet +import Data.Kind +import Data.Type.Bool (type (&&)) +import Data.List + (find, findIndices, intercalate, isPrefixOf, nub, sortOn, stripPrefix) +import Data.List.NonEmpty (NonEmpty, nonEmpty) +import Data.Map (Map) +import Data.Map qualified as Map +import Data.Maybe +import Data.Monoid (Ap (..)) +import Data.Monoid qualified as Monoid +import Data.Ord (Down (..)) +import Data.Primitive.Array (Array, arrayFromList, indexArray) +import Data.Primitive.PrimArray (PrimArray) +import Data.Primitive.SmallArray (SmallArray) +import Data.Primitive.Types (Prim) +import Data.Profunctor +import Data.Profunctor.Unsafe ((#.), (.#)) +import Data.Proxy (Proxy (..)) +import Data.Ratio (Ratio, denominator, numerator, (%)) +import Data.Scientific +import Data.SOP (All, K (..), NP, hcollapse, hcpure) +import Data.Semigroup qualified as Semigroup +import Data.Sequence (Seq) +import Data.Sequence qualified as Seq +import Data.Set (Set) +import Data.Set qualified as Set +import Data.Strict qualified as Strict +import Data.String (IsString (..)) +import Data.Tagged (Tagged (..)) +import Data.Text (Text) +import Data.Text qualified as Text +import Data.Text.Encoding qualified as Text +import Data.Text.Read qualified as TextRead +import Data.Text.Unsafe qualified as Text (lengthWord8) +import Data.Text.Lazy qualified as LText +import Data.Text.Short (ShortText) +import Data.Text.Short qualified as ShortText +import Data.These (These (..)) +import Data.Time + ( CalendarDiffDays (..), CalendarDiffTime (..), Day, DayOfWeek (..) + , DiffTime, LocalTime, NominalDiffTime, TimeOfDay, UTCTime, ZonedTime + , defaultTimeLocale, formatTime, parseTimeM + ) +import Data.Time.Calendar.Month (Month) +import Data.Time.Calendar.Quarter (Quarter, QuarterOfYear (..)) +import Data.Time.Clock.System (SystemTime (..)) +import Data.Time.FromText qualified as TimeText +import Data.Traversable (for) +import Data.Tree (Forest, Tree (..)) +import Data.Tuple (Solo (MkSolo), getSolo) +import Data.UUID.Types (UUID) +import Data.UUID.Types qualified as UUID +import Data.Vector (Vector) +import Data.Vector qualified as Vector +import Data.Vector.Mutable qualified as MVector +import Data.Vector.Generic qualified as VG +import Data.Vector.Primitive qualified as VP +import Data.Vector.Storable qualified as VS +import Data.Vector.Unboxed qualified as VU +import Data.Version (Version, parseVersion, showVersion) +import Data.Void (Void, absurd) +import Data.Word (Word8, Word16, Word32, Word64) +import Foreign.C.Types (CTime (..)) +import Foreign.Storable (Storable) +import Control.Lens.Grammar.TypeScript +import GHC.Exts qualified as Exts +import GHC.Generics qualified as GHC +import Network.URI (URI) +import Network.URI qualified as URI +import Numeric.Natural (Natural) +import System.IO (Handle, hPutStr) +import Text.ParserCombinators.ReadP (readP_to_S) +import Type.Reflection +import Witherable qualified + +-- $setup +-- >>> :set -XDeriveAnyClass -XDerivingStrategies -XDerivingVia +-- >>> :set -XOverloadedStrings -XRequiredTypeArguments -XTypeApplications +-- >>> import Control.Lens.Grammar +-- >>> import Data.Aeson qualified as Aeson +-- >>> import Data.Char (toLower) +-- >>> import Data.Text (Text) +-- >>> import GHC.Generics (Generic) +-- >>> import Data.Aeson.Encoding (encodingToLazyByteString) +-- >>> import Data.ByteString.Lazy.Char8 qualified as LByteString +-- >>> import Data.Aeson.Types (formatError) +-- >>> import System.IO (stdout) +-- >>> let explain err = formatError (jsonErrorPath err) (jsonErrorMessage err) + +makePrisms ''Value +makePrisms ''These + +-- Json grammars -- + +{- | A type with a JSON grammar, like @aeson@'s `Aeson.ToJSON` +& `Aeson.FromJSON` together, which every `JsonVal` interprets. +Its methods default to @aeson@'s defaults, & `json` to the +`GHC.Generic` grammar, by @aeson@'s default options. +-} +class Json a where + + -- | `Aeson.toJSON` & `Aeson.parseJSON`, as one grammar. + json :: JsonVal p => p a a + default json + :: forall d f p + . ( GHC.Generic a, GHC.Rep a ~ GHC.D1 d f, GSum f, Typeable a + , EnumTag (AllNullary f) a, JsonVal p ) + => p a a + json = jsonGeneric Aeson.defaultOptions + {-# INLINABLE json #-} + + {- | `Data.Aeson.toJSONList` & `Data.Aeson.parseJSONList`, + as one grammar, an array of values by default. + `Char` and wrappers override it, so that a t'String' is a JSON string. + -} + jsonList :: JsonVal p => p [a] [a] + jsonList = jsonArray json + {-# INLINE jsonList #-} + + {- | `Data.Aeson.toJSONKey` & `Data.Aeson.parseJSONKey` + as one grammar for the text keys of objects, + or else `Nothing` for the keys of arrays of pairs. + -} + jsonKey :: Maybe (forall k. JsonStr k => k a a) + jsonKey = Nothing + + {- | `Data.Aeson.toJSONKeyList` & `Data.Aeson.parseJSONKeyList` + as one grammar for keys of lists, like `jsonList`. + `Char` and wrappers override it. + -} + jsonKeyList :: Maybe (forall k. JsonStr k => k [a] [a]) + jsonKeyList = Nothing + + {- | `Data.Aeson.omitField` & `Data.Aeson.omittedField` together, + as the value of a record's field which may be omitted, like `nearly`: + it matches the value omitted by `Data.Aeson.omitNothingFields`, + & reviews the value of a field omitted by `Data.Aeson.allowOmittedFields`. + -} + jsonOmitField :: Maybe (APrism' a ()) + jsonOmitField = Nothing + +-- Running Json grammars -- + +-- | `Data.Aeson.parseJSON` +jsonParse :: Json a => Value -> Either JsonError a +jsonParse = runJsonParsor json + +{- | `Data.Aeson.eitherDecode`, which reads the JSON text by @aeson@, +failing by its message for text which isn't JSON. +-} +jsonDecode :: Json a => LByteString.ByteString -> Either JsonError a +jsonDecode bytes = case Aeson.eitherDecode bytes of + Left syntax -> Left (JsonError [] [] (Just (Left syntax)) JsonMismatch []) + Right v -> jsonParse v + +-- | `Data.Aeson.toJSON` +jsonPrint :: Json a => a -> Value +jsonPrint = either (\_ -> Null) id . jsonErrorPrint + +{- | `jsonPrint`, failing where the grammar doesn't print a value, +like a key which repeats. + +>>> jsonErrorPrint (1 :: Int) +Right (Number 1.0) +-} +jsonErrorPrint :: Json a => a -> Either JsonError Value +jsonErrorPrint = runJsonPrintor json + +-- | `Data.Aeson.toEncoding` +jsonEncode :: Json a => a -> Encoding +jsonEncode = either (\_ -> Encoding.null_) id . jsonErrorEncode +{-# INLINE jsonEncode #-} + +-- | `jsonEncode`, failing where the grammar doesn't print a value. +jsonErrorEncode :: Json a => a -> Either JsonError Encoding +jsonErrorEncode = runJsonPrintor json +{-# INLINE jsonErrorEncode #-} + +{- | @aeson@'s instances, derived from a `Json` instance, failing to parse +at the path of a t'JsonError', by its message: `Aeson.ToJSON` & +`Aeson.FromJSON`, with their fields omitted by `jsonOmitField`, & +`Aeson.ToJSONKey` & `Aeson.FromJSONKey`, by `jsonKey` & `jsonKeyList`, +or else as values, in arrays of pairs. + +> data Point = Point {x :: Int, y :: Int} +> deriving stock Generic +> deriving anyclass Json +> deriving (ToJSON, FromJSON) via ViaJson Point +-} +newtype ViaJson a = ViaJson a + deriving stock (Eq, Ord, Show) + +instance Json a => Aeson.ToJSON (ViaJson a) where + toJSON (ViaJson a) = jsonPrint a + toEncoding (ViaJson a) = jsonEncode a + toJSONList vs = either (\_ -> Null) id + (runJsonPrintor (jsonList @a) (coerce vs)) + toEncodingList vs = either (\_ -> Encoding.null_) id + (runJsonPrintor (jsonList @a) (coerce vs)) + omitField (ViaJson a) = case jsonOmitField @a of + Just omitted -> withPrism omitted $ \_ match -> + either (const False) (const True) (match a) + Nothing -> False +instance Json a => Aeson.FromJSON (ViaJson a) where + parseJSON = either parseFailure (pure . ViaJson) . jsonParse + parseJSONList = + either parseFailure (pure . coerce) . runJsonParsor (jsonList @a) + omittedField = case jsonOmitField @a of + Just omitted -> withPrism omitted $ \omit _ -> Just (ViaJson (omit ())) + Nothing -> Nothing +instance Json a => Aeson.ToJSONKey (ViaJson a) where + toJSONKey = case jsonKey @a of + Just key -> keyText (coerced >~ key) + Nothing -> Aeson.ToJSONKeyValue Aeson.toJSON Aeson.toEncoding + toJSONKeyList = case jsonKeyList @a of + Just key -> keyText (coerced >~ key) + Nothing -> Aeson.ToJSONKeyValue Aeson.toJSON Aeson.toEncoding +instance Json a => Aeson.FromJSONKey (ViaJson a) where + fromJSONKey = case jsonKey @a of + Just key -> keyParser (coerced >~ key) + Nothing -> Aeson.FromJSONKeyValue Aeson.parseJSON + fromJSONKeyList = case jsonKeyList @a of + Just key -> keyParser (coerced >~ key) + Nothing -> Aeson.FromJSONKeyValue Aeson.parseJSON + +-- | Print a key's text, by a key grammar. +keyText + :: (forall k. JsonStr k => k a a) -> Aeson.ToJSONKeyFunction a +keyText key = + Aeson.ToJSONKeyText (runKeyPrintor key) (runKeyPrintor key) + +-- | Parse a key's text, by a key grammar. +keyParser + :: (forall k. JsonStr k => k a a) -> Aeson.FromJSONKeyFunction a +keyParser key = Aeson.FromJSONKeyTextParser + (either parseFailure pure . runJsonParsor key . String) + +-- | Fail to parse at the path of a t'JsonError', by its message. +parseFailure :: JsonError -> Aeson.Parser x +parseFailure err = + Aeson.parserThrowError (jsonErrorPath err) (jsonErrorMessage err) + +{- | `JsonVal` grammars describe JSON values: @null@, booleans, numbers, +strings, by `JsonStr`, arrays & objects, by `JsonTup` & `JsonObj`. +As `CocartesianChoice`s & `Filtrator`s, they have alternatives +(`>+<`, `>|<`) & partial isomorphisms (`>?`, `?<`). +Its numbers are bounded, & its integers integral, as @aeson@'s are. +-} +class + ( CocartesianChoice p + , Filtrator p + , JsonStr p + ) => JsonVal p where + jsonNull :: p () () + jsonBool :: p Bool Bool + jsonNumber :: p Scientific Scientific + jsonInt :: p Int Int + jsonInt = jsonBoundedInteger + jsonInt8 :: p Int8 Int8 + jsonInt8 = jsonBoundedInteger + jsonInt16 :: p Int16 Int16 + jsonInt16 = jsonBoundedInteger + jsonInt32 :: p Int32 Int32 + jsonInt32 = jsonBoundedInteger + jsonInt64 :: p Int64 Int64 + jsonInt64 = jsonBoundedInteger + jsonWord :: p Word Word + jsonWord = jsonBoundedInteger + jsonWord8 :: p Word8 Word8 + jsonWord8 = jsonBoundedInteger + jsonWord16 :: p Word16 Word16 + jsonWord16 = jsonBoundedInteger + jsonWord32 :: p Word32 Word32 + jsonWord32 = jsonBoundedInteger + jsonWord64 :: p Word64 Word64 + jsonWord64 = jsonBoundedInteger + jsonInteger :: p Integer Integer + jsonInteger = _Integer ?< jsonNumber + jsonNatural :: p Natural Natural + jsonNatural = _Natural ?< jsonNumber + jsonDouble :: p Double Double + jsonDouble = iso fromFloatDigits toRealFloat >~ jsonNumber + {- | A homogeneous JSON array, like TypeScript's @T[]@, which is a tuple + of a rest element, though interpreters may define it more efficiently. + + @jsonArray p = jsonTuple (manyP (jsonElem p))@ + -} + jsonArray :: p a b -> p [a] [b] + jsonArray p = jsonTuple (manyP (jsonElem p)) + {- | @null@ or a value, like @aeson@'s `Maybe`, + though interpreters may define it more efficiently. + + @jsonNullable p = eotMaybe >~ jsonNull >+< p@ + -} + jsonNullable :: p a b -> p (Maybe a) (Maybe b) + jsonNullable p = eotMaybe >~ jsonNull >+< p + {- | A pair, as an array of its two elements, + though interpreters may define it more efficiently. + + @jsonPair p q = jsonTuple (jsonElem p >*< jsonElem q)@ + -} + jsonPair :: p a b -> p c d -> p (a, c) (b, d) + jsonPair p q = jsonTuple (jsonElem p >*< jsonElem q) + {- | An object of a single property, as @aeson@ tags `Either`'s & sums' + values, though interpreters may define it more efficiently. + + @jsonTag k p = jsonObjectStrict (k !: p)@ + -} + jsonTag :: Text -> p a b -> p a b + jsonTag k p = jsonObjectStrict (k !: p) + {- | A `jsonDict` object of a `Map`, whose keys can't repeat, + so that printing needn't check them. + -} + jsonMap + :: Ord b + => (forall k. JsonStr k => k a b) + -> p c d -> p (Map a c) (Map b d) + jsonMap key p = dimap Map.toList Map.fromList (jsonObject (jsonDict key p)) + {- | A `jsonDict` object of a `HashMap`, whose keys can't repeat, + so that printing needn't check them. + -} + jsonHashMap + :: (Eq b, Hashable b) + => (forall k. JsonStr k => k a b) + -> p c d -> p (HashMap a c) (HashMap b d) + jsonHashMap key p = + dimap HashMap.toList HashMap.fromList (jsonObject (jsonDict key p)) + jsonTuple :: (forall q. JsonTup p q => q a b) -> p a b + jsonObject :: (forall q. JsonObj p q => q a b) -> p a b + -- | A `jsonObject` which rejects the properties that it doesn't name. + jsonObjectStrict :: (forall q. JsonObj p q => q a b) -> p a b + jsonObjectStrict obj = + jsonObject (obj *< dimap (const []) (const ()) (jsonDict jsonText zeroP)) + jsonValue :: p Value Value + jsonValue = jsonTyped $ orP + [ _Null >? jsonNull + , _Bool >? jsonBool + , _Number >? jsonNumber + , _String >? jsonText + , _Array . iso Vector.toList Vector.fromList >? jsonArray jsonValue + , _Object . iso KeyMap.toList KeyMap.fromList + >? 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`. +-} +unqualified :: String -> String +unqualified = \case + [] -> [] + s@(c : rest) + | isUpper c, (_ : _, '.' : after@(_ : _)) <- span identifier s -> + unqualified after + | identifier c -> let (word, others) = span identifier s in + word <> unqualified others + | otherwise -> c : unqualified rest + where + identifier c = isAlphaNum c || c == '_' || c == '\'' + +{- | +@fromString s = only s ?< jsonString@ + +@jsonString = iso Text.pack Text.unpack >~ jsonText@ +-} +class + ( Cochoice p + , forall x y. (x ~ (), y ~ ()) => IsString (p x y) + , forall x y. BackusNaurForm (p x y) + ) => JsonStr p where + jsonText :: p Text Text + jsonString :: p String String + jsonString = iso Text.pack Text.unpack >~ jsonText + {- | A string matched from its `Text`, which is reviewed lazily + as both its `Text` & an @aeson@ string `Encoding.Encoding'`, + either of which an interpreter uses. + -} + jsonEncodedText + :: APrism Text (Text, Encoding.Encoding' Text) a a -> p a a + jsonEncodedText encoding = withPrism encoding $ \encode match -> + prism' (fst . encode) (either (const Nothing) Just . match) ?< jsonText + {- | An enumeration of strings, which a map's key may be, + like TypeScript's union of string literals, @"a" | "b"@, + by a table of strings & their values, & the index of each value in it, + so that printing needn't search it. + -} + jsonEnumWith :: (a -> Int) -> [(Text, a)] -> p a a + jsonEnumWith indexOf table = + prism' (indexArray names . indexOf) (`lookup` table) ?< jsonText + where + names = arrayFromList (map fst table) + +{- | An enumeration of strings, by `AComonocle`'s copies & their names, +which `jsonEnumWith` tables once, numbered as `fromEnumerable` numbers them. + +>>> import Control.Lens (coerced) +>>> import Control.Lens.Comonocle (_BoundedEnum) +>>> import Data.Text qualified as Text +>>> newtype Order = Order Ordering deriving (Show) +>>> let name = Text.toLower . Text.pack . show @Ordering +>>> instance Json Order where json = coerced >~ jsonEnum _BoundedEnum name +>>> jsonPrint (Order GT) +String "gt" +>>> jsonParse @Order (Aeson.String "lt") +Right (Order LT) +-} +jsonEnum :: JsonStr p => AComonocle a a () () -> (a -> Text) -> p a a +jsonEnum mon name = withComonocle mon $ \split merge -> + let copies = maybe [] enumerateFrom (preview fromEnumerable (0,())) + in jsonEnumWith (fromIntegral . fst . review fromEnumerable . split) + [(name a, a) | a <- map merge copies] +{-# INLINE jsonEnum #-} + +{- | `JsonTup` grammars describe the elements of a JSON array. +As `Alternator`s they have optional elements (`optionalP`, `optionP`), +rest elements (`manyP`, `someP`) and alternatives (`>+<`, `>|<`), +like TypeScript's variadic tuple types, @[A, B?, ...C[]]@. +Its elements are `JsonVal` grammars, which determine its type. +-} +class Alternator q => JsonTup p q | q -> p where + jsonElem :: p a b -> q a b + +{- | `JsonObj` grammars describe the properties of a JSON object. +Each key may be read or written at most once. +A required property, @k !: v@, is like TypeScript's @{k: T}@, +and an optional property, @k ?: v@, may be missing, like @{k?: T}@. +A property with a default, @"limit" ?: jsonInt != 10@, +like @aeson@'s @.:?@ & @.!=@, is missing exactly when it's the default. +Its properties are `JsonVal` grammars, which determine its type. +-} +class (Monoidal q, CocartesianChoice q) => JsonObj p q | q -> p where + (!:) :: Text -> p a b -> q a b + (?:) :: Text -> p a b -> q (Maybe a) (Maybe b) + {- | The properties of an object which aren't named by `!:` or `?:`, + as a list of key-value pairs, by a grammar of keys & a grammar of values. + + On its own, it's a dictionary. + + > jsonObject (jsonDict jsonText json) + > -- {"a": 1, "b": 2} <-> [("a", 1), ("b", 2)] + + Beside named properties, it's the rest of them. + + > jsonObject ("id" !: json >*< jsonDict jsonText json) + > -- {"id": 1, "a": true, "b": false} <-> (1, [("a", True), ("b", False)]) + + Parsing fails unless every remaining property matches both grammars, + so a narrower key grammar than `jsonText`, like `jsonEnumWith`, + restricts the keys allowed. Printing fails on a key which repeats, + or which is also named. An object has at most one `jsonDict`. + + In TypeScript, it's an index signature, @{ [key: string]: T }@, + or, of an enumeration of keys, a mapped type, @{ [key in K]?: T }@. + -} + jsonDict :: (forall k. JsonStr k => k a b) -> p c d -> q [(a, c)] [(b, d)] +infixr 7 !:, ?: + +-- Errors -- + +{- | A located failure to decode, parse or print a `Value`. +Its path is relative to that `Value`, root first. +It expected one of the alternatives, none meaning just "unexpected". +Parsing found a `Value`, or decoding found text which isn't JSON, +by @aeson@'s message; printing doesn't show the Haskell value it found. +It failed within `rule`s, outermost first, branching where alternatives +failed alike; a `rule` it failed for as a whole is its expectation instead. +-} +data JsonError = JsonError + { jsonErrorPath :: [JSONPathElement] + , jsonErrorExpected :: [String] + , jsonErrorFound :: Maybe (Either String Value) + , jsonErrorSort :: JsonErrorSort + , jsonErrorRules :: Forest String + } deriving stock (Eq, Show) + +-- | How a t'JsonError' failed, so that alternatives report the closest. +data JsonErrorSort + = JsonIlliteral + -- ^ a string literal mismatch; the alternative doesn't apply + | JsonMismatch + -- ^ the value was rejected as a whole + | JsonMissing + -- ^ the value was rejected for what it contains, lacks or repeats + deriving stock (Eq, Ord, Show) + +{- | The message of a t'JsonError', without its path, as @aeson@ words it. + +>>> either jsonErrorMessage show (jsonParse @Bool (Aeson.String "yes")) +"expected boolean, but found \"yes\"" +-} +jsonErrorMessage :: JsonError -> String +jsonErrorMessage err = case (jsonErrorFound err, jsonErrorExpected err) of + (Just (Left syntax), _) -> syntax + (Just (Right found), []) -> "unexpected " <> render found + (Just (Right found), expected) -> + "expected " <> alternatives expected <> ", but found " <> render found + (Nothing, []) -> "cannot print" + (Nothing, expected) + | jsonErrorSort err == JsonMissing -> + "cannot print " <> alternatives expected + | otherwise -> "cannot print as " <> alternatives expected + where + render = abbreviate . LText.unpack . encodeToLazyText + abbreviate str = if length str > 60 then take 57 str <> "..." else str + alternatives = \case + [] -> "" + [e] -> e + es -> intercalate ", " (init es) <> " or " <> last es + +jsonUnexpected :: Maybe Value -> Either JsonError a +jsonUnexpected found = + Left (JsonError [] [] (Right <$> found) JsonMismatch []) + +jsonMismatch :: String -> Value -> Either JsonError a +jsonMismatch expected found = + Left (JsonError [] [expected] (Just (Right found)) JsonMismatch []) + +jsonMissing :: String -> Maybe Value -> Either JsonError a +jsonMissing expected found = + Left (JsonError [] [expected] (Right <$> found) JsonMissing []) + +countElements :: Int -> String +countElements n = show n <> if n == 1 then " element" else " elements" + +jsonAt :: JSONPathElement -> Either JsonError a -> Either JsonError a +jsonAt el = onFailure (\err -> err {jsonErrorPath = el : jsonErrorPath err}) + +-- | Map a failure, sharing a success. +onFailure + :: (JsonError -> JsonError) -> Either JsonError a -> Either JsonError a +onFailure f = \case + Left err -> Left (f err) + success -> success + + +-- | Map a success strictly, sharing a failure. +onSuccess :: (a -> b) -> Either JsonError a -> Either JsonError b +onSuccess f = \case + Left err -> Left err + Right a -> Right $! f a + +{- | A `rule` labels its failures as a whole, +like @(\)@ for parser combinators, and encloses its other failures. +-} +jsonRelabel :: String -> JsonError -> JsonError +jsonRelabel name err + | null (jsonErrorPath err) + , jsonErrorSort err /= JsonMissing = err {jsonErrorExpected = [name]} + | otherwise = err {jsonErrorRules = [Node name (jsonErrorRules err)]} + +{- | Combine the failures of alternatives: the deepest failure wins, +failures on the same value merge their expectations & rules, +and a string literal mismatch loses to any other failure. +-} +jsonOrElse :: JsonError -> JsonError -> JsonError +jsonOrElse err1 err2 + | depth1 /= depth2 = if depth1 > depth2 then err1 else err2 + | jsonErrorPath err1 == jsonErrorPath err2 + , jsonErrorFound err1 == jsonErrorFound err2 = err2 + { jsonErrorExpected = + nub (jsonErrorExpected err1 <> jsonErrorExpected err2) + , jsonErrorSort = max (jsonErrorSort err1) (jsonErrorSort err2) + , jsonErrorRules = jsonErrorRules err1 <> jsonErrorRules err2 + } + | jsonErrorSort err2 == JsonIlliteral + , jsonErrorSort err1 /= JsonIlliteral = err1 + | otherwise = err2 + where + depth1 = length (jsonErrorPath err1) + depth2 = length (jsonErrorPath err2) + +-- Parsing interpreters -- + +{- | t'JsonParsor' parses a `Value`. It may also have a t'Dispatch', +when it only accepts string literals, as values or as the values of +a key of objects, so that alternatives are chosen by lookup, +rather than tried in turn. +-} +data JsonParsor a b = JsonParsor + { jsonParsorDispatch :: Maybe (Dispatch b) + , runJsonParsor :: Value -> Either JsonError b + -- | A primitive parses an array of its values at once, when they all match. + , jsonParsorArray :: Maybe (Vector Value -> Maybe [b]) + {- | A string's text, when it parses every string by a function of its text + which keeps its order, so that a map's keys parse by mapping them. + -} + , jsonParsorText :: Maybe (Text -> b) + } + +{- | Parsers by the string literal which they accept, +as the value itself, or as the value of a key. +-} +data Dispatch b = Dispatch + { dispatchKey :: Maybe Key + , dispatchTable :: Map Text (Value -> Either JsonError b) + } + +jsonParsor :: (Value -> Either JsonError b) -> JsonParsor a b +jsonParsor parse = JsonParsor Nothing parse Nothing Nothing + +-- | A primitive t'JsonParsor', matching its values. +primitiveParsor + :: String -> (Value -> Maybe b) -> JsonParsor a b +primitiveParsor expected match = JsonParsor Nothing parse (Just array) Nothing + where + parse v = maybe (jsonMismatch expected v) Right (match v) + array arr + | Vector.all (isJust . match) arr = + Just (Data.Maybe.mapMaybe match (Vector.toList arr)) + | otherwise = Nothing +{-# INLINE primitiveParsor #-} + +-- | Transform a parser and its dispatch table alike. +mapParsing + :: ((Value -> Either JsonError b) -> Value -> Either JsonError c) + -> JsonParsor a b -> JsonParsor x c +mapParsing f parsor = JsonParsor + { jsonParsorDispatch = retable <$> jsonParsorDispatch parsor + , runJsonParsor = f (runJsonParsor parsor) + , jsonParsorArray = Nothing + , jsonParsorText = Nothing + } + where + retable dispatch = dispatch {dispatchTable = f <$> dispatchTable dispatch} + +dispatching :: Dispatch b -> Value -> Either JsonError b +dispatching (Dispatch Nothing table) = \case + v@(String t) | Just p <- Map.lookup t table -> p v + v -> Left (JsonError [] (literals table) (Just (Right v)) JsonIlliteral []) +dispatching (Dispatch (Just key) table) = \case + v@(Object o) -> case KeyMap.lookup key o of + Nothing -> jsonMissing ("key " <> showKey key) (Just v) + Just (String t) | Just p <- Map.lookup t table -> p v + Just tag -> + Left $ JsonError [Key key] (literals table) (Just (Right tag)) + JsonIlliteral [] + v -> jsonMismatch "object" v + +literals :: Map Text a -> [String] +literals = map show . Map.keys + +orElse + :: (Value -> Either JsonError b) -> (Value -> Either JsonError b) + -> Value -> Either JsonError b +orElse p q v = case p v of + Left err1 -> onFailure (jsonOrElse err1) (q v) + success -> success + +{- | t'TupParsor' parses the elements of a JSON array from a position, +in every way it can, so that optional and rest elements backtrack. +A tuple of fixed length also parses its elements from known positions. +-} +data TupParsor a b = TupParsor + { tupParsorFixed :: Maybe (Int, Vector Value -> Int -> Either JsonError b) + , runTupParsor :: Vector Value -> Int -> [Either JsonError (b, Int)] + } + +{- | t'ObjParsor' reads keys of an t'Object', ignoring other keys, +unless it reads the rest of them, those which the object doesn't name. +Its keys are known before parsing, so overlapping keys are found once, +as are its tags, keys which only accept string literals, +& whether its keys are all required, so that it has all of a shape's keys. +-} +data ObjParsor a b = ObjParsor + { objParsorShapes :: [[Key]] + , objParsorTags :: [(Key, Set Text)] + , objParsorRequired :: Bool + , runObjParsor :: HashSet Key -> Object -> Either JsonError b + } + +instance Functor (JsonParsor a) where + fmap f p = (mapParsing (fmap (onSuccess f)) p) + {jsonParsorArray = fmap (fmap (map f) .) (jsonParsorArray p)} +instance Witherable.Filterable (JsonParsor a) where + mapMaybe = dimapMaybe Just +instance Filtrator JsonParsor +instance Profunctor JsonParsor where + dimap _ g = fmap g . coerce + _ #. p = coerce p + p .# _ = coerce p +instance Choice JsonParsor where + left' = mapParsing (fmap (fmap Left)) + right' = mapParsing (fmap (fmap Right)) +-- | An array of values which all match parses at once. +instance Cochoice JsonParsor where + unleft p = (mapParsing (\parse v -> + parse v >>= either pure (\_ -> jsonUnexpected (Just v))) p) + { jsonParsorArray = (traverse (either Just (const Nothing)) <=<) + <$> jsonParsorArray p + } + unright p = (mapParsing (\parse v -> + parse v >>= either (\_ -> jsonUnexpected (Just v)) pure) p) + { jsonParsorArray = (traverse (either (const Nothing) Just) <=<) + <$> jsonParsorArray p + } +instance CocartesianMonoidal JsonParsor where + zeroP = falseP + p >+< q = (Left <$> coerce p) >|< (Right <$> coerce q) +instance CocartesianChoice JsonParsor +instance DisjunctiveMonoid (JsonParsor a b) where + falseP = jsonParsor (jsonUnexpected . Just) + p >|< q = case (jsonParsorDispatch p, jsonParsorDispatch q) of + (Just dispatch0, Just dispatch1) + | dispatchKey dispatch0 == dispatchKey dispatch1 -> + let + dispatch = Dispatch (dispatchKey dispatch0) $ Map.unionWith orElse + (dispatchTable dispatch0) (dispatchTable dispatch1) + in + JsonParsor (Just dispatch) (dispatching dispatch) array Nothing + _ -> JsonParsor Nothing (orElse (runJsonParsor p) (runJsonParsor q)) + array Nothing + where + -- An array which the first alternative parses, element by element. + array = jsonParsorArray p +instance BackusNaurForm (JsonParsor a b) where + rule name p = (mapParsing (onFailure (jsonRelabel (unqualified name)) .) p) + {jsonParsorArray = jsonParsorArray p, jsonParsorText = jsonParsorText p} + ruleRec name f = fix (rule name . f) +instance (x ~ (), y ~ ()) => IsString (JsonParsor x y) where + fromString s = JsonParsor + (Just (Dispatch Nothing (Map.singleton literal parse))) parse Nothing + Nothing + where + literal = Text.pack s + parse = \case + String t | t == literal -> Right () + v -> Left (JsonError [] [show s] (Just (Right v)) JsonIlliteral []) +instance JsonStr JsonParsor where + jsonText = (primitiveParsor "string" $ \case + String t -> Just t + _ -> Nothing) {jsonParsorText = Just id} + -- | TsLiteral alternatives, dispatched by their string. + jsonEnumWith indexOf table = orP + [ dimap indexOf (const a) (only i >? fromString (Text.unpack literal)) + | (i, (literal, a)) <- zip [0 ..] table + ] +instance JsonVal JsonParsor where + jsonNull = jsonParsor $ \case + Null -> Right () + v -> jsonMismatch "null" v + -- | As the default, but without trying @null@ before every value. + jsonNullable p = jsonParsor $ \case + Null -> Right Nothing + v -> case runJsonParsor p v of + Right b -> Right (Just b) + Left err -> Left (jsonOrElse nullError err) + where + nullError = JsonError [] ["null"] (Just (Right v)) JsonMismatch [] + jsonBool = primitiveParsor "boolean" $ \case + Bool b -> Just b + _ -> Nothing + jsonNumber = primitiveParsor "number" $ \case + Number n -> Just n + _ -> Nothing + jsonValue = jsonParsor Right + -- | As the default, but mapping text keys, rather than parsing them. + jsonMap key p = case jsonParsorText key of + Just keyOf -> jsonParsor $ \case + Object o -> Map.fromDistinctAscList <$> entries (KeyMap.toAscList o) + where + entries = \case + [] -> Right [] + (k, v) : rest -> case runJsonParsor p v of + Right b -> ((keyOf (Key.toText k), b) :) <$> entries rest + Left err -> jsonAt (Key k) (Left err) + v -> jsonMismatch "object" v + Nothing -> dimap Map.toList Map.fromList (jsonObject (jsonDict key p)) + jsonArray p = jsonParsor $ \case + Array arr | Just parsed <- jsonParsorArray p >>= ($ arr) -> Right parsed + Array arr -> zipWithM + (\i v -> jsonAt (Index i) (runJsonParsor p v)) [0 ..] (Vector.toList arr) + v -> jsonMismatch "array" v + jsonTuple tup = jsonParsor $ \case + Array arr | Just (n, fixed) <- tupParsorFixed parsor -> + fixed arr 0 >>= \b -> + if n == Vector.length arr then Right b + else jsonMissing (countElements n) (Just (Array arr)) + Array arr -> + let + outcomes = runTupParsor parsor arr 0 + incomplete = \case + Left err -> err + Right (_, n) -> + JsonError [] [countElements n] (Just (Right (Array arr))) + JsonMissing [] + in + case [b | Right (b, n) <- outcomes, n == Vector.length arr] of + b : _ -> Right b + [] -> Left (foldl jsonOrElse unexpected (map incomplete outcomes)) + where + unexpected = + JsonError [] [] (Just (Right (Array arr))) JsonMismatch [] + v -> jsonMismatch "array" v + where + parsor = tup @TupParsor + jsonObject obj = objectParsor False obj + jsonObjectStrict obj = objectParsor True obj + +{- | Parse an t'Object' by its properties, and, if it's rejecting, +reject the first property which isn't named, as `jsonObjectStrict`'s +default would, but without parsing the rest of the properties. +-} +objectParsor :: Bool -> ObjParsor a b -> JsonParsor a b +objectParsor rejecting obj = JsonParsor dispatch parse Nothing Nothing + where + overlap = foldr ((<|>) . duplicateKey) Nothing (objParsorShapes obj) + parse = \case + Object o -> case overlap of + Just key -> + jsonMissing ("another key " <> showKey key) (Just (Object o)) + Nothing -> case runObjParsor obj named o of + Right _ + | rejecting + , exactSize /= Just (KeyMap.size o) + , Just (k, v) <- find (not . (`HashSet.member` named) . fst) + (KeyMap.toList o) -> + jsonAt (Key k) (jsonUnexpected (Just v)) + result -> result + v -> jsonMismatch "object" v + named = HashSet.fromList (concat (objParsorShapes obj)) + -- The size of an object having only the keys of its parsed shape, + -- when its keys are all required & its shapes are the same size. + exactSize = case nub (map length (objParsorShapes obj)) of + [size] | objParsorRequired obj -> Just size + _ -> Nothing + dispatch = case objParsorTags obj of + (key, tags) : _ -> + Just (Dispatch (Just key) (Map.fromSet (const parse) tags)) + [] -> Nothing + +instance Functor (TupParsor a) where + fmap f (TupParsor fixed general) = TupParsor + (fmap (\p arr i -> onSuccess f (p arr i)) <$> fixed) + (\arr i -> map (fmap (first' f)) (general arr i)) +instance Applicative (TupParsor a) where + pure b = TupParsor (Just (0, \_ _ -> Right b)) (\_ i -> [Right (b, i)]) + TupParsor fixed0 general0 <*> TupParsor fixed1 general1 = + TupParsor (liftA2 sequenced fixed0 fixed1) backtracking + where + sequenced (n0, p) (n1, q) = (n0 + n1, \arr i -> case p arr i of + Left err -> Left err + Right f -> onSuccess f (q arr $! i + n0)) + backtracking arr i = general0 arr i >>= \case + Left err -> [Left err] + Right (f, j) -> map (fmap (first' f)) (general1 arr j) +instance Profunctor TupParsor where + dimap _ g = coerce . fmap g + _ #. p = coerce p + p .# _ = coerce p +instance Choice TupParsor where + left' = alternate . Left + right' = alternate . Right +instance CocartesianMonoidal TupParsor +instance CocartesianChoice TupParsor where + alternate = either (fmap Left . coerce) (fmap Right . coerce) +instance DisjunctiveMonoid (TupParsor a b) where + falseP = TupParsor Nothing (\_ _ -> []) + p >|< q = TupParsor Nothing $ \arr i -> + runTupParsor p arr i <> runTupParsor q arr i +-- | `manyP` tries longer repetitions first, never repeating an empty match. +instance Distributor TupParsor where + manyP (TupParsor _ p) = TupParsor Nothing go + where + go arr i = concatMap step (p arr i) <> [Right ([], i)] + where + step = \case + Left err -> [Left err] + Right (b, j) | j > i -> map (fmap (first' (b :))) (go arr j) + Right _ -> [] +instance Alternative (TupParsor a) where + empty = falseP + (<|>) = (>|<) + many = lmap repeat . manyP + some = lmap repeat . someP +instance Alternator TupParsor +instance JsonTup JsonParsor TupParsor where + jsonElem p = TupParsor + (Just (1, jsonElement)) + (\arr i -> [(, i + 1) <$> jsonElement arr i]) + where + jsonElement arr i = case arr Vector.!? i of + Nothing -> + jsonMissing ("at least " <> countElements (i + 1)) (Just (Array arr)) + Just v -> jsonAt (Index i) (runJsonParsor p v) + +instance Functor (ObjParsor a) where + fmap f (ObjParsor keys tags required p) = + ObjParsor keys tags required (\named o -> onSuccess f (p named o)) +instance Applicative (ObjParsor a) where + pure b = ObjParsor [[]] [] True (\_ _ -> Right b) + ObjParsor keys0 tags0 required0 p0 <*> ObjParsor keys1 tags1 required1 p1 = + ObjParsor (liftA2 (<>) keys0 keys1) (tags0 <> tags1) + (required0 && required1) $ \named o -> + case p0 named o of + Left err -> Left err + Right f -> onSuccess f (p1 named o) +instance Profunctor ObjParsor where + dimap _ g (ObjParsor keys tags required p) = + ObjParsor keys tags required (\named o -> onSuccess g (p named o)) + _ #. p = coerce p + p .# _ = coerce p +instance Choice ObjParsor where + left' = fmap Left . coerce + right' = fmap Right . coerce +instance CocartesianMonoidal ObjParsor +instance CocartesianChoice ObjParsor where + alternate = either (fmap Left . coerce) (fmap Right . coerce) +instance DisjunctiveMonoid (ObjParsor a b) where + falseP = ObjParsor [] [] True (\_ o -> jsonUnexpected (Just (Object o))) + p >|< q = ObjParsor (objParsorShapes p <> objParsorShapes q) [] + (objParsorRequired p && objParsorRequired q) $ + \named o -> case runObjParsor p named o of + Left err -> onFailure (jsonOrElse err) (runObjParsor q named o) + success -> success +instance JsonObj JsonParsor ObjParsor where + jsonDict key p = ObjParsor [[]] [] False $ \named o -> + for [kv | kv@(k, _) <- KeyMap.toList o, not (HashSet.member k named)] $ + \(k, v) -> jsonAt (Key k) $ + (,) <$> runJsonParsor key (String (Key.toText k)) <*> runJsonParsor p v + k !: p = ObjParsor [[key]] tags True $ \_ o -> case KeyMap.lookup key o of + Nothing -> jsonMissing ("key " <> show k) (Just (Object o)) + Just v -> jsonAt (Key key) (runJsonParsor p v) + where + key = Key.fromText k + tags = case jsonParsorDispatch p of + Just (Dispatch Nothing table) -> [(key, Map.keysSet table)] + _ -> [] + k ?: p = ObjParsor [[key]] [] False $ \_ o -> + traverse (jsonAt (Key key) . runJsonParsor p) (KeyMap.lookup key o) + where + key = Key.fromText k + +duplicateKey :: [Key] -> Maybe Key +duplicateKey keys + | ascending id || ascending shortlex = Nothing + | HashSet.size (HashSet.fromList keys) == length keys = Nothing + | otherwise = go HashSet.empty keys + where + ascending :: Ord b => (Key -> b) -> Bool + ascending f = and (zipWith (\k j -> f k < f j) keys (drop 1 keys)) + shortlex key = (Text.lengthWord8 (Key.toText key), key) + go _ [] = Nothing + go seen (key : rest) + | HashSet.member key seen = Just key + | otherwise = go (HashSet.insert key seen) rest + +showKey :: Key -> String +showKey = show . Key.toText + +-- Printing interpreters -- + +-- | @aeson@'s representations of JSON strings, `Value`, `Encoding` & t'Key'. +class AesonStr val where + aesonText :: Text -> val + aesonString :: String -> val + -- | Render a string literal, which is rendered once. + aesonLiteral :: Text -> val + aesonLiteral = aesonText + -- | Render an array of a primitive at once, when that's faster. + aesonPrimitives :: (a -> val) -> Maybe ([a] -> val) + aesonPrimitives _ = Nothing + -- | Render text, or else its @aeson@ string `Encoding.Encoding'`. + aesonEncodedText :: (Text, Encoding.Encoding' Text) -> val + aesonEncodedText = aesonText . fst + +instance AesonStr Value where + aesonText = String + aesonString = String . Text.pack + {-# INLINE aesonText #-} + {-# INLINE aesonString #-} + +instance AesonStr Key where + aesonText = Key.fromText + aesonString = Key.fromString + +instance AesonStr (Encoding.Encoding' a) where + aesonText = Encoding.text + aesonString = Encoding.string + aesonLiteral = Encoding.unsafeToEncoding . Builder.byteString + . LByteString.toStrict . Encoding.encodingToLazyByteString . Encoding.text + aesonPrimitives render = + Just (retagEncoding . Encoding.list (retagEncoding . render)) + {-# INLINE aesonPrimitives #-} + aesonEncodedText = retagEncoding . snd + {-# INLINE aesonText #-} + {-# INLINE aesonString #-} + {-# INLINE aesonLiteral #-} + {-# INLINE aesonEncodedText #-} + +-- | Retag an @aeson@ `Encoding.Encoding'`. +retagEncoding :: Encoding.Encoding' a -> Encoding.Encoding' b +retagEncoding = Encoding.unsafeToEncoding . Encoding.fromEncoding + +{- | t'KeyPrintor' prints the key of an t'Object', which is total, +as a t'Key' or as its `Encoding.Encoding'`. +-} +newtype KeyPrintor key a b = KeyPrintor {runKeyPrintor :: a -> key} + +instance Profunctor (KeyPrintor key) where + dimap f _ (KeyPrintor render) = KeyPrintor (render . f) +instance Cochoice (KeyPrintor key) where + unleft (KeyPrintor render) = KeyPrintor (render . Left) + unright (KeyPrintor render) = KeyPrintor (render . Right) +instance (AesonStr key, x ~ (), y ~ ()) => IsString (KeyPrintor key x y) where + fromString s = KeyPrintor (const literal) + where + literal = aesonLiteral (Text.pack s) +-- | A key's `rule` names nothing to print. +instance BackusNaurForm (KeyPrintor key a b) where + rule _ = id + ruleRec _ = fix +instance AesonStr key => JsonStr (KeyPrintor key) where + jsonText = KeyPrintor aesonText + jsonString = KeyPrintor aesonString + jsonEncodedText encoding = withPrism encoding $ \encode _ -> + KeyPrintor (aesonEncodedText . encode) + -- | Literals rendered once, & printed by their index. + jsonEnumWith indexOf table = KeyPrintor (indexArray rendered . indexOf) + where + rendered = arrayFromList [aesonLiteral literal | (literal, _) <- table] + +-- | @aeson@'s representations of JSON values, `Value` & `Encoding`. +class AesonStr val => AesonVal val where + aesonNull :: val + aesonBool :: Bool -> val + aesonNumber :: Scientific -> val + aesonIntegral :: Integral a => (a -> Encoding) -> a -> val + aesonDouble :: Double -> val + aesonList :: (a -> val) -> [a] -> val + -- | An array of two elements. + aesonPair :: val -> val -> val + aesonObject :: [(Key, val)] -> val + -- | Render an object of distinct keys, folded from a map. + aesonMap + :: (forall k. JsonStr k => k a b) + -> (forall r. (a -> c -> r -> r) -> r -> m -> r) + -> (c -> val) -> m -> val + aesonValue :: Value -> val + -- | A key of an object, encoded once, before printing its properties. + type AesonKey val + -- | The properties of an object, as they're rendered. + type AesonProps val + aesonKey :: Key -> AesonKey val + aesonProp :: AesonKey val -> val -> AesonProps val -> AesonProps val + aesonPropsEmpty :: AesonProps val + aesonProps :: AesonProps val -> val + -- | An object of a single property. + aesonTag :: AesonKey val -> val -> val + -- | The elements of an array, as they're rendered. + type AesonElems val + aesonElem :: val -> AesonElems val -> AesonElems val + aesonElemsEmpty :: AesonElems val + aesonElems :: AesonElems val -> val + +-- | Elements of an `Encoding` array, separated by commas. +data EncodingElems = NoEncodingElems | EncodingElems Encoding + +instance AesonVal Value where + aesonNull = Null + aesonBool = Bool + aesonNumber = Number + aesonIntegral _ = Number . fromIntegral + aesonDouble = Number . fromFloatDigits + aesonList f as = Array $ Vector.create $ do + array <- MVector.unsafeNew (length as) + let + write _ [] = pure array + write i (a : rest) = + (MVector.unsafeWrite array i $! f a) >> write (i + 1) rest + write 0 as + aesonPair a b = Array $ Vector.create $ do + array <- MVector.unsafeNew 2 + MVector.unsafeWrite array 0 a + MVector.unsafeWrite array 1 b + pure array + aesonObject = Object . KeyMap.fromList + aesonMap key fold render = Object . KeyMap.fromList . fold property [] + where + property a c rest = let printed = render c in + printed `seq` (runKeyPrintor key a, printed) : rest + aesonValue = id + type AesonKey Value = Key + type AesonProps Value = [(Key, Value)] + aesonKey = id + aesonProp key value rest = (key, value) : rest + aesonPropsEmpty = [] + aesonProps = Object . KeyMap.fromList + aesonTag key value = Object (KeyMap.singleton key value) + type AesonElems Value = [Value] + aesonElem = (:) + aesonElemsEmpty = [] + -- Few elements are an array of a known size, which is allocated inline. + aesonElems = \case + [] -> Array Vector.empty + [a] -> Array (Vector.singleton a) + [a, b] -> aesonPair a b + [a, b, c] -> Array $ Vector.create $ do + array <- MVector.unsafeNew 3 + MVector.unsafeWrite array 0 a + MVector.unsafeWrite array 1 b + MVector.unsafeWrite array 2 c + pure array + [a, b, c, d] -> Array $ Vector.create $ do + array <- MVector.unsafeNew 4 + MVector.unsafeWrite array 0 a + MVector.unsafeWrite array 1 b + MVector.unsafeWrite array 2 c + MVector.unsafeWrite array 3 d + pure array + items -> aesonList id items + {-# INLINE aesonElem #-} + {-# INLINE aesonElemsEmpty #-} + {-# INLINE aesonElems #-} + {-# INLINE aesonNull #-} + {-# INLINE aesonBool #-} + {-# INLINE aesonNumber #-} + {-# INLINE aesonIntegral #-} + {-# INLINE aesonDouble #-} + {-# INLINE aesonList #-} + {-# INLINE aesonPair #-} + {-# INLINE aesonObject #-} + {-# INLINE aesonMap #-} + {-# INLINE aesonValue #-} + {-# INLINE aesonKey #-} + {-# INLINE aesonProp #-} + {-# INLINE aesonPropsEmpty #-} + {-# INLINE aesonProps #-} + +-- | Keys are rendered once, as their quoted strings, & properties as a series. +instance AesonVal Encoding where + aesonNull = Encoding.null_ + aesonBool = Encoding.bool + aesonNumber = Encoding.scientific + aesonIntegral = id + aesonDouble = Encoding.double + aesonList = Encoding.list + aesonPair a b = EncodingInternal.openBracket + EncodingInternal.>< a EncodingInternal.>< EncodingInternal.comma + EncodingInternal.>< b EncodingInternal.>< EncodingInternal.closeBracket + aesonObject = Encoding.pairs . foldMap (uncurry Encoding.pair) + aesonMap key fold render = Encoding.pairs . fold property mempty + where + property a c rest = + let encodedKey = runKeyPrintor key a; printed = render c + in encodedKey `seq` printed `seq` + Encoding.pair' encodedKey printed <> rest + aesonValue = Encoding.value + type AesonKey Encoding = Encoding.Encoding' Key + type AesonProps Encoding = Encoding.Series + aesonKey = aesonLiteral . Key.toText + aesonProp key value rest = Encoding.pair' key value <> rest + aesonPropsEmpty = mempty + aesonProps = Encoding.pairs + aesonTag key value = Encoding.pairs (Encoding.pair' key value) + type AesonElems Encoding = EncodingElems + aesonElem value = \case + NoEncodingElems -> EncodingElems value + EncodingElems rest -> + EncodingElems (value EncodingInternal.>< EncodingInternal.comma + EncodingInternal.>< rest) + aesonElemsEmpty = NoEncodingElems + aesonElems = \case + NoEncodingElems -> Encoding.emptyArray_ + EncodingElems items -> EncodingInternal.openBracket + EncodingInternal.>< items + EncodingInternal.>< EncodingInternal.closeBracket + {-# INLINE aesonElem #-} + {-# INLINE aesonElemsEmpty #-} + {-# INLINE aesonElems #-} + {-# INLINE aesonNull #-} + {-# INLINE aesonBool #-} + {-# INLINE aesonNumber #-} + {-# INLINE aesonIntegral #-} + {-# INLINE aesonDouble #-} + {-# INLINE aesonList #-} + {-# INLINE aesonPair #-} + {-# INLINE aesonObject #-} + {-# INLINE aesonMap #-} + {-# INLINE aesonValue #-} + {-# INLINE aesonKey #-} + {-# INLINE aesonProp #-} + {-# INLINE aesonPropsEmpty #-} + {-# INLINE aesonProps #-} + +{- | t'JsonPrintor' `printorTry`s to print a value, or else `printorCheck`s it +to locate the failure. A `printorTotal` printor prints every value, +so it `printorRender`s it without trying. Totality is determined +through `rule`s, assuming those being determined are total. +It's always taken lazily, as @\\rules -> printorTotal p rules@, +so that building a recursive printor doesn't force itself. +A primitive `printorRenderArray`s an array of its values at once. +-} +data JsonPrintor val a b = JsonPrintor + { printorTotal :: !(Set String -> Bool) + , printorTry :: !(a -> Maybe val) + , printorRender :: !(a -> val) + , printorCheck :: !(a -> Either JsonError val) + , printorRenderArray :: !(Maybe ([a] -> val)) + } + +runJsonPrintor :: JsonPrintor val a b -> a -> Either JsonError val +runJsonPrintor p + | printorTotal p Set.empty = Right . printorRender p + | otherwise = \a -> maybe (printorCheck p a) Right (printorTry p a) +{-# INLINE runJsonPrintor #-} + +-- | A total t'JsonPrintor'. +printing :: (a -> val) -> JsonPrintor val a b +printing render = + JsonPrintor (const True) (Just . render) render (Right . render) Nothing +{-# INLINE printing #-} + +-- | A total t'JsonPrintor' of a primitive. +primitive :: AesonStr val => (a -> val) -> JsonPrintor val a b +primitive render = + (printing render) {printorRenderArray = aesonPrimitives render} +{-# INLINE primitive #-} + +{- | A partial t'JsonPrintor', rendering what it tries, +or else null, as `jsonPrint` does. +-} +trying + :: AesonVal val + => (a -> Maybe val) -> (a -> Either JsonError val) -> JsonPrintor val a b +trying attempt check = JsonPrintor + (const False) attempt (fromMaybe aesonNull . attempt) check Nothing + +-- | Try each of the values, rendering them for a total printor. +tryAll + :: Traversable f + => (Set String -> Bool) -> (a -> Maybe b) -> (a -> b) -> f a -> Maybe (f b) +tryAll total attempt render = \as -> if isTotal + then Just (fmap render as) + else traverse attempt as + where + isTotal = total Set.empty + +{- | t'TupPrintor' prints the elements of a JSON array, +counted to locate a failure of a later element. +A single element keeps its rendering, so that mapping it composes. +-} +data TupPrintor val a b = TupPrintor + { tupPrintorTotal :: !(Set String -> Bool) + , tupPrintorTry :: !(a -> Maybe (DList val)) + , tupPrintorRender :: !(a -> AesonElems val -> AesonElems val) + , tupPrintorCheck :: !(a -> Elements val) + , tupPrintorElement :: !(Maybe (a -> val)) + } + +-- | Render a single element, before the rest. +renderElement + :: AesonVal val => (a -> val) -> a -> AesonElems val -> AesonElems val +renderElement render a rest = + let printed = render a in printed `seq` aesonElem printed rest +{-# INLINE renderElement #-} + +-- | Printed elements, counted to locate a failure of a later element. +newtype Elements val = Elements (Either JsonError (Int, DList val)) +instance Semigroup (Elements val) where + Elements (Right (count0, elements0)) <> Elements later = Elements $ + case later of + Right (count1, elements1) -> + Right (count0 + count1, elements0 <> elements1) + Left err -> Left $ case jsonErrorPath err of + Index i : path -> err {jsonErrorPath = Index (i + count0) : path} + _ -> err + failure <> _ = failure +instance Monoid (Elements val) where + mempty = Elements (Right (0, mempty)) + +{- | t'ObjPrintor' writes keys of an t'Object'. +Its keys are known before printing, so overlapping keys are found once, +unless it writes the rest of the properties, whose keys are checked. +-} +data ObjPrintor val a b = ObjPrintor + { objPrintorShapes :: [[Key]] + , objPrintorRest :: !Bool + , objPrintorTotal :: !(Set String -> Bool) + , objPrintorTry :: !(a -> Maybe (DList (Key, val))) + , objPrintorRender :: !(a -> AesonProps val -> AesonProps val) + , objPrintorCheck :: !(a -> Either JsonError [(Key, val)]) + } + +printDuplicate :: Key -> Either JsonError a +printDuplicate key = jsonMissing ("key " <> showKey key <> " twice") Nothing + +instance Functor (JsonPrintor val a) where + fmap _ (JsonPrintor total attempt render check renderArray) = + JsonPrintor total attempt render check renderArray + {-# INLINE fmap #-} +{- | A printor's results are phantom, so that `Witherable.mapMaybe`, +like `fmap`, keeps it, as @mapMaybe = dimapMaybe Just@ would observably, +but keeping its totality. +-} +instance Witherable.Filterable (JsonPrintor val a) where + mapMaybe _ = coerce +instance AesonVal val => Filtrator (JsonPrintor val) +instance Profunctor (JsonPrintor val) where + dimap f _ (JsonPrintor total attempt render check renderArray) = + JsonPrintor total (attempt . f) (\a -> render $! f a) (check . f) + (fmap (. map f) renderArray) + _ #. p = coerce p + p .# _ = coerce p + {-# INLINE dimap #-} + {-# INLINE (#.) #-} + {-# INLINE (.#) #-} +instance Cochoice (JsonPrintor val) where + unleft (JsonPrintor total attempt render check renderArray) = + JsonPrintor total (attempt . Left) (render . Left) (check . Left) + (fmap (. map Left) renderArray) + unright (JsonPrintor total attempt render check renderArray) = + JsonPrintor total (attempt . Right) (render . Right) (check . Right) + (fmap (. map Right) renderArray) + {-# INLINE unleft #-} + {-# INLINE unright #-} +instance CocartesianMonoidal (JsonPrintor val) where + zeroP = JsonPrintor (const True) absurd absurd absurd Nothing + p >+< q = JsonPrintor + (\rules -> printorTotal p rules && printorTotal q rules) + (either (printorTry p) (printorTry q)) + (either (printorRender p) (printorRender q)) + (either (printorCheck p) (printorCheck q)) + Nothing + {-# INLINE zeroP #-} + {-# INLINE (>+<) #-} +instance AesonVal val => Choice (JsonPrintor val) where + left' p = trying + (either (printorTry p) (const Nothing)) + (either (printorCheck p) (\_ -> jsonUnexpected Nothing)) + right' p = trying + (either (const Nothing) (printorTry p)) + (either (\_ -> jsonUnexpected Nothing) (printorCheck p)) + {-# INLINE left' #-} + {-# INLINE right' #-} +instance AesonVal val => CocartesianChoice (JsonPrintor val) +instance AesonVal val => DisjunctiveMonoid (JsonPrintor val a b) where + falseP = trying (const Nothing) (\_ -> jsonUnexpected Nothing) + p >|< q = JsonPrintor + (\rules -> printorTotal p rules || printorTotal q rules) + (\a -> printorTry p a <|> printorTry q a) + (\a -> fromMaybe (printorRender q a) (printorTry p a)) + (\a -> case printorCheck p a of + Left err1 -> onFailure (jsonOrElse err1) (printorCheck q a) + success -> success) + Nothing +{- | A `rule` labels its failures with its display name. +Its totality assumes the rules being determined are total, +by induction on the values printed. +-} +instance BackusNaurForm (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 (AesonStr val, x ~ (), y ~ ()) => IsString (JsonPrintor val x y) where + fromString s = printing (const literal) + where + literal = aesonLiteral (Text.pack s) +instance AesonStr val => JsonStr (JsonPrintor val) where + jsonText = primitive aesonText + {-# INLINE jsonText #-} + jsonString = primitive aesonString + jsonEncodedText encoding = withPrism encoding $ \encode _ -> + primitive (aesonEncodedText . encode) + -- | Literals rendered once, & printed by their index. + jsonEnumWith indexOf table = printing (indexArray rendered . indexOf) + where + rendered = arrayFromList [aesonLiteral literal | (literal, _) <- table] + {-# INLINE jsonString #-} + {-# INLINE jsonEncodedText #-} + {-# INLINE jsonEnumWith #-} +instance AesonVal val => JsonVal (JsonPrintor val) where + jsonNull = primitive (const aesonNull) + -- | As the default, but rendering without an `Either` for every value. + jsonNullable p = JsonPrintor + (\rules -> printorTotal p rules) + (maybe (Just aesonNull) (printorTry p)) + render + (maybe (Right aesonNull) (printorCheck p)) + (aesonPrimitives render) + where + render = maybe aesonNull (printorRender p) + jsonBool = primitive aesonBool + {-# INLINE jsonBool #-} + jsonNumber = primitive aesonNumber + jsonInt = primitive (aesonIntegral Encoding.int) + {-# INLINE jsonInt #-} + jsonInt8 = primitive (aesonIntegral Encoding.int8) + jsonInt16 = primitive (aesonIntegral Encoding.int16) + jsonInt32 = primitive (aesonIntegral Encoding.int32) + jsonInt64 = primitive (aesonIntegral Encoding.int64) + jsonWord = primitive (aesonIntegral Encoding.word) + jsonWord8 = primitive (aesonIntegral Encoding.word8) + jsonWord16 = primitive (aesonIntegral Encoding.word16) + jsonWord32 = primitive (aesonIntegral Encoding.word32) + jsonWord64 = primitive (aesonIntegral Encoding.word64) + jsonInteger = primitive (aesonIntegral Encoding.integer) + jsonNatural = primitive (aesonIntegral (Encoding.integer . toInteger)) + jsonDouble = primitive aesonDouble + jsonValue = printing aesonValue + jsonArray p = JsonPrintor + (\rules -> printorTotal p rules) + (\as -> if printorTotal p Set.empty + then Just (render as) + else aesonList id <$> traverse (printorTry p) as) + render + (\as -> aesonList id <$> + zipWithM (\i a -> jsonAt (Index i) (printorCheck p a)) [0 ..] as) + Nothing + where + render = fromMaybe (aesonList (printorRender p)) (printorRenderArray p) + {-# INLINE jsonArray #-} + -- | As the default, but rendering an array of two elements directly. + jsonPair p q = JsonPrintor + (\rules -> printorTotal p rules && printorTotal q rules) + (\(a, c) -> aesonPair <$> printorTry p a <*> printorTry q c) + render + (\(a, c) -> aesonPair + <$> jsonAt (Index 0) (printorCheck p a) + <*> jsonAt (Index 1) (printorCheck q c)) + Nothing + where + render (a, c) = + let x = printorRender p a; y = printorRender q c + in x `seq` y `seq` aesonPair x y + {-# INLINE jsonPair #-} + -- | As the default, but rendering its one property directly. + jsonTag k p = JsonPrintor + (\rules -> printorTotal p rules) + (fmap (aesonTag key) . printorTry p) + (\a -> let printed = printorRender p a + in printed `seq` aesonTag key printed) + (fmap (aesonTag key) . jsonAt (Key (Key.fromText k)) . printorCheck p) + Nothing + where + key = aesonKey @val (Key.fromText k) + {-# INLINE jsonTag #-} + jsonMap key = printDistinct Map.foldrWithKey key + jsonHashMap key = printDistinct HashMap.foldrWithKey key + jsonTuple = printTuple + {-# INLINE jsonTuple #-} + jsonObject obj = case + foldr ((<|>) . duplicateKey) Nothing (objPrintorShapes printor) of + Just key -> trying (const Nothing) (\_ -> printDuplicate key) + Nothing + | objPrintorRest printor -> trying + (\a -> do + props <- toList <$> objPrintorTry printor a + guard (isNothing (duplicateKey (map fst props))) + Just (aesonObject props)) + (\a -> do + props <- objPrintorCheck printor a + maybe (Right (aesonObject props)) printDuplicate + (duplicateKey (map fst props))) + | otherwise -> JsonPrintor + (\rules -> objPrintorTotal printor rules) + (fmap (aesonObject . toList) . objPrintorTry printor) + (\a -> aesonProps (objPrintorRender printor a (aesonPropsEmpty @val))) + (fmap aesonObject . objPrintorCheck printor) + Nothing + where + printor = obj @(ObjPrintor val) + -- | The properties which a strict object rejects are never printed. + jsonObjectStrict obj = jsonObject obj + {-# INLINE jsonNull #-} + {-# INLINE jsonNullable #-} + {-# INLINE jsonNumber #-} + {-# INLINE jsonInt8 #-} + {-# INLINE jsonInt16 #-} + {-# INLINE jsonInt32 #-} + {-# INLINE jsonInt64 #-} + {-# INLINE jsonWord #-} + {-# INLINE jsonWord8 #-} + {-# INLINE jsonWord16 #-} + {-# INLINE jsonWord32 #-} + {-# INLINE jsonWord64 #-} + {-# INLINE jsonInteger #-} + {-# INLINE jsonNatural #-} + {-# INLINE jsonDouble #-} + {-# INLINE jsonValue #-} + {-# INLINE jsonMap #-} + {-# INLINE jsonHashMap #-} + {-# INLINE jsonObject #-} + {-# INLINE jsonObjectStrict #-} + +instance Functor (TupPrintor val a) where + fmap _ (TupPrintor total attempt render check single) = + TupPrintor total attempt render check single + {-# INLINE fmap #-} +instance Applicative (TupPrintor val a) where + pure _ = TupPrintor + (const True) (const (Just mempty)) (\_ rest -> rest) mempty Nothing + p <*> q = TupPrintor + (\rules -> tupPrintorTotal p rules && tupPrintorTotal q rules) + (\a -> (<>) <$> tupPrintorTry p a <*> tupPrintorTry q a) + (\a rest -> tupPrintorRender p a $! tupPrintorRender q a rest) + (tupPrintorCheck p <> tupPrintorCheck q) + Nothing + liftA2 f p q = fmap f p <*> q + p *> q = fmap (\_ b -> b) p <*> q + p <* q = fmap const p <*> q + {-# INLINE pure #-} + {-# INLINE (<*>) #-} + {-# INLINE liftA2 #-} + {-# INLINE (*>) #-} + {-# INLINE (<*) #-} +instance AesonVal val => Profunctor (TupPrintor val) where + {-# SPECIALISE instance Profunctor (TupPrintor Value) #-} + {-# SPECIALISE instance Profunctor (TupPrintor Encoding) #-} + dimap f _ p = case tupPrintorElement p of + Just single -> + let projected a = single $! f a in TupPrintor total + (attempt . f) (renderElement projected) (check . f) (Just projected) + Nothing -> TupPrintor total (attempt . f) + (\a rest -> let b = f a in b `seq` render b rest) (check . f) Nothing + where + TupPrintor total attempt render check _ = p + {-# INLINE dimap #-} + lmap f = dimap f id + {-# INLINE lmap #-} + _ #. p = coerce p + p .# _ = coerce p +instance AesonVal val => CocartesianMonoidal (TupPrintor val) where + zeroP = TupPrintor (const True) absurd absurd absurd Nothing + p >+< q = TupPrintor + (\rules -> tupPrintorTotal p rules && tupPrintorTotal q rules) + (either (tupPrintorTry p) (tupPrintorTry q)) + (\e rest -> case e of + Left a -> tupPrintorRender p a rest + Right b -> tupPrintorRender q b rest) + (either (tupPrintorCheck p) (tupPrintorCheck q)) + Nothing +instance AesonVal val => Distributor (TupPrintor val) where + manyP p = TupPrintor + (\rules -> tupPrintorTotal p rules) + (fmap mconcat . tryAll (tupPrintorTotal p) (tupPrintorTry p) + (\a -> fromMaybe mempty (tupPrintorTry p a))) + (\as rest -> foldr (\a printed -> tupPrintorRender p a $! printed) rest as) + (foldMap (tupPrintorCheck p)) + Nothing + optionalP p = TupPrintor + (\rules -> tupPrintorTotal p rules) + (maybe (Just mempty) (tupPrintorTry p)) + (\ma rest -> maybe rest (\a -> tupPrintorRender p a rest) ma) + (foldMap (tupPrintorCheck p)) + Nothing +-- | `optionP` omits its default. +instance AesonVal val => Alternative (TupPrintor val a) where + empty = falseP + (<|>) = (>|<) + many = lmap repeat . manyP + some = lmap repeat . someP +instance AesonVal val => Alternator (TupPrintor val) where + optionP def p = pureP def >|< p +instance AesonVal val => Choice (TupPrintor val) where + left' = alternate . Left + right' = alternate . Right +unprintable :: Elements val +unprintable = Elements (jsonUnexpected Nothing) + +-- | A partial t'TupPrintor', rendering what it tries, or else nothing. +tupTrying + :: AesonVal val + => (a -> Maybe (DList val)) -> (a -> Elements val) -> TupPrintor val a b +tupTrying attempt check = TupPrintor (const False) attempt + (\a -> prependElems (fromMaybe mempty (attempt a))) check Nothing + +-- | Render tried elements before others. +prependElems :: AesonVal val => DList val -> AesonElems val -> AesonElems val +prependElems items rest = foldr aesonElem rest items + +instance AesonVal val => CocartesianChoice (TupPrintor val) where + alternate = \case + Left p -> tupTrying + (either (tupPrintorTry p) (const Nothing)) + (either (tupPrintorCheck p) (\_ -> unprintable)) + Right p -> tupTrying + (either (const Nothing) (tupPrintorTry p)) + (either (\_ -> unprintable) (tupPrintorCheck p)) +instance AesonVal val => DisjunctiveMonoid (TupPrintor val a b) where + falseP = tupTrying (const Nothing) (\_ -> unprintable) + p >|< q = TupPrintor + (\rules -> tupPrintorTotal p rules || tupPrintorTotal q rules) + (\a -> tupPrintorTry p a <|> tupPrintorTry q a) + (\a rest -> maybe + (tupPrintorRender q a rest) (`prependElems` rest) (tupPrintorTry p a)) + (\a -> case (tupPrintorCheck p a, tupPrintorCheck q a) of + (Elements (Left err0), Elements (Left err1)) -> + Elements (Left (jsonOrElse err0 err1)) + (Elements (Left _), printed) -> printed + (printed, _) -> printed) + Nothing + +instance AesonVal val => JsonTup (JsonPrintor val) (TupPrintor val) where + {-# SPECIALISE instance JsonTup (JsonPrintor Value) (TupPrintor Value) #-} + {-# SPECIALISE instance + JsonTup (JsonPrintor Encoding) (TupPrintor Encoding) #-} + jsonElem p = TupPrintor + (\rules -> printorTotal p rules) + (fmap DList.singleton . printorTry p) + (renderElement (printorRender p)) + (\a -> Elements $ (\printed -> (1, pure printed)) + <$> jsonAt (Index 0) (printorCheck p a)) + (Just (printorRender p)) + {-# INLINE jsonElem #-} + +instance Functor (ObjPrintor val a) where + fmap _ (ObjPrintor keys rest total attempt render check) = + ObjPrintor keys rest total attempt render check + {-# INLINE fmap #-} +instance Applicative (ObjPrintor val a) where + pure _ = ObjPrintor [[]] False + (const True) (const (Just mempty)) (\_ rest -> rest) (\_ -> Right []) + ObjPrintor keys0 rest0 total0 try0 render0 check0 + <*> ObjPrintor keys1 rest1 total1 try1 render1 check1 = ObjPrintor + (liftA2 (<>) keys0 keys1) + (rest0 || rest1) + (\rules -> total0 rules && total1 rules) + (\a -> (<>) <$> try0 a <*> try1 a) + (\a rest -> render0 a $! render1 a rest) + (\a -> (<>) <$> check0 a <*> check1 a) + liftA2 f p q = fmap f p <*> q + p *> q = fmap (\_ b -> b) p <*> q + p <* q = fmap const p <*> q + {-# INLINE pure #-} + {-# INLINE (<*>) #-} + {-# INLINE liftA2 #-} + {-# INLINE (*>) #-} + {-# INLINE (<*) #-} +instance Profunctor (ObjPrintor val) where + dimap f _ (ObjPrintor keys rest total attempt render check) = + ObjPrintor keys rest total + (attempt . f) (\a props -> let b = f a in b `seq` render b props) + (check . f) + _ #. p = coerce p + p .# _ = coerce p + {-# INLINE dimap #-} + {-# INLINE (#.) #-} + {-# INLINE (.#) #-} +instance AesonVal val => Choice (ObjPrintor val) where + left' = alternate . Left + right' = alternate . Right + {-# INLINE left' #-} + {-# INLINE right' #-} +instance CocartesianMonoidal (ObjPrintor val) where + zeroP = ObjPrintor [] False (const True) absurd absurd absurd + p >+< q = ObjPrintor + (objPrintorShapes p <> objPrintorShapes q) + (objPrintorRest p || objPrintorRest q) + (\rules -> objPrintorTotal p rules && objPrintorTotal q rules) + (either (objPrintorTry p) (objPrintorTry q)) + (\e props -> case e of + Left a -> objPrintorRender p a props + Right b -> objPrintorRender q b props) + (either (objPrintorCheck p) (objPrintorCheck q)) + {-# INLINE zeroP #-} + {-# INLINE (>+<) #-} +instance AesonVal val => CocartesianChoice (ObjPrintor val) where + alternate = \case + Left p -> objTrying p + (either (objPrintorTry p) (const Nothing)) + (either (objPrintorCheck p) (\_ -> jsonUnexpected Nothing)) + Right p -> objTrying p + (either (const Nothing) (objPrintorTry p)) + (either (\_ -> jsonUnexpected Nothing) (objPrintorCheck p)) + {-# INLINE alternate #-} +instance AesonVal val => DisjunctiveMonoid (ObjPrintor val a b) where + falseP = ObjPrintor [] False (const False) (const Nothing) + (\_ props -> props) (\_ -> jsonUnexpected Nothing) + p >|< q = ObjPrintor + (objPrintorShapes p <> objPrintorShapes q) + (objPrintorRest p || objPrintorRest q) + (\rules -> objPrintorTotal p rules || objPrintorTotal q rules) + (\a -> objPrintorTry p a <|> objPrintorTry q a) + (\a props -> maybe + (objPrintorRender q a props) (`prependProps` props) (objPrintorTry p a)) + (\a -> case objPrintorCheck p a of + Left err -> onFailure (jsonOrElse err) (objPrintorCheck q a) + success -> success) + +-- | A partial t'ObjPrintor' of another's shapes, rendering what it tries. +objTrying + :: AesonVal val + => ObjPrintor val x y + -> (a -> Maybe (DList (Key, val))) + -> (a -> Either JsonError [(Key, val)]) + -> ObjPrintor val a b +objTrying p attempt = ObjPrintor (objPrintorShapes p) (objPrintorRest p) + (const False) attempt + (\a props -> prependProps (fromMaybe mempty (attempt a)) props) + +-- | Render tried properties before others, encoding their keys. +prependProps + :: forall val. AesonVal val + => DList (Key, val) -> AesonProps val -> AesonProps val +prependProps props rest = + foldr (\(key, value) -> aesonProp (aesonKey @val key) value) rest props + +instance AesonVal val => JsonObj (JsonPrintor val) (ObjPrintor val) where + jsonDict key p = ObjPrintor [[]] True + (\rules -> printorTotal p rules) + (fmap DList.fromList . traverse (\(a, c) -> (keyOf a,) <$> printorTry p c)) + (\entries rest -> foldr + (\(a, c) props -> renderProperty (aesonKey @val (keyOf a)) p c props) + rest entries) + (traverse (\(a, c) -> let k = keyOf a in + (k,) <$> jsonAt (Key k) (printorCheck p c))) + where + keyOf = runKeyPrintor key + k !: p = ObjPrintor [[key]] False + (\rules -> printorTotal p rules) + (fmap property . printorTry p) + (renderProperty encodedKey p) + (printProperty key p) + where + key = Key.fromText k + encodedKey = aesonKey @val key + property printed = DList.singleton (key, printed) + k ?: p = ObjPrintor [[key]] False + (\rules -> printorTotal p rules) + (maybe (Just mempty) (fmap property . printorTry p)) + (\ma rest -> maybe rest (\a -> renderProperty encodedKey p a rest) ma) + (maybe (Right []) (printProperty key p)) + where + key = Key.fromText k + encodedKey = aesonKey @val key + property printed = DList.singleton (key, printed) + {-# INLINE jsonDict #-} + {-# INLINE (!:) #-} + {-# INLINE (?:) #-} + +{- | Print an array of elements. Outside the `JsonVal` instance, so that +the instance's specializations needn't break their recursion through +`jsonTuple` itself, which would stop it from inlining. +-} +printTuple + :: forall val a b. AesonVal val + => (forall q. JsonTup (JsonPrintor val) q => q a b) -> JsonPrintor val a b +printTuple tup = case tup @(TupPrintor val) of + -- The grammar's printor, instantiated once, rather than in each field. + TupPrintor total attempt render check _ -> JsonPrintor + (\rules -> total rules) + (fmap (aesonList id . toList) . attempt) + (\a -> aesonElems (render a (aesonElemsEmpty @val))) + (\a -> case check a of + Elements printed -> aesonList id . toList . snd <$> printed) + Nothing +{-# INLINE printTuple #-} + +-- | Print the properties of a map, whose keys are distinct, as an object. +printDistinct + :: AesonVal val + => (forall r. (a -> c -> r -> r) -> r -> m -> r) + -> (forall k. JsonStr k => k a b) + -> JsonPrintor val c d -> JsonPrintor val m n +printDistinct fold key p = JsonPrintor + (\rules -> printorTotal p rules) + (fmap aesonObject . fold attempt (Just [])) + (aesonMap key fold (printorRender p)) + (fmap aesonObject . fold check (Right [])) + Nothing + where + keyOf = runKeyPrintor key + attempt a c rest = (:) . (keyOf a,) <$> printorTry p c <*> rest + check a c rest = (:) . (k,) <$> jsonAt (Key k) (printorCheck p c) <*> rest + where + k = keyOf a + +renderProperty + :: AesonVal val + => AesonKey val -> JsonPrintor val a b -> a -> AesonProps val + -> AesonProps val +renderProperty key p a rest = + let printed = printorRender p a in printed `seq` aesonProp key printed rest +{-# INLINE renderProperty #-} + +printProperty + :: Key -> JsonPrintor val a b -> a -> Either JsonError [(Key, val)] +printProperty key p a = + (\printed -> [(key, printed)]) <$> jsonAt (Key key) (printorCheck p a) + +-- Types of JSON -- + +{- | The type of JSON values, which a grammar describes, +of rules by their names, in a t'Bnf', as `jsonType` describes them. +It's the union of its alternatives, so that `falseP` is the type of +no values. +-} +data JsonType + = JsonRule String -- ^ the type of a rule, by its name + | JsonNull -- ^ @null@ + | JsonBoolean -- ^ @true@ or @false@ + | JsonNumber -- ^ numbers + | JsonString -- ^ strings + | JsonLiteral Text -- ^ a string + | JsonSubtype JsonType -- ^ some values of a type + | JsonArray JsonElements -- ^ arrays of elements + | JsonObject [JsonProperty] -- ^ objects of properties + | JsonUnion [JsonType] -- ^ values of any of some types + deriving stock (Eq, Ord, Show, Read) + +-- | The `JsonElements` of a `JsonArray` are the `KleeneStarAlgebra` generated by `JsonType`. +data JsonElements + = JsonElement JsonType -- ^ an element + | JsonElements JsonElements -- ^ elements, repeated any number of times + | JsonElements1 JsonElements -- ^ elements, repeated at least once + | JsonElementsOpt JsonElements -- ^ elements, or none + | JsonElementsTup [JsonElements] -- ^ elements, in sequence + | JsonElementsAlt [JsonElements] -- ^ elements, any of some alternatives + deriving stock (Eq, Ord, Show, Read) + +-- | A property of a `JsonObject`. +data JsonProperty + = JsonProperty Text Bool JsonType + -- ^ a property, by its key, which is optional or not + | JsonDict JsonType JsonType + -- ^ the rest of the properties, by the types of their keys & values + deriving stock (Eq, Ord, Show, Read) + +instance DisjunctiveMonoid JsonType where + falseP = JsonUnion [] + a >|< b = jsonUnion [a, b] + +-- | A union, of the alternatives of some types. +jsonUnion :: [JsonType] -> JsonType +jsonUnion types = case nub (concatMap flatten types) of + [t] -> t + ts -> JsonUnion ts + where + flatten = \case + JsonUnion ts -> ts + t -> [t] + +jsonSubtype :: JsonType -> JsonType +jsonSubtype = \case + JsonUnion [] -> falseP + t@(JsonSubtype _) -> t + t -> JsonSubtype t + +instance Semigroup JsonElements where + JsonElementsAlt [] <> _ = falseP + _ <> JsonElementsAlt [] = falseP + JsonElements a <> b | a == b = plusK a + a <> JsonElements b | a == b = plusK a + a <> b = case (flatten a, flatten b) of + (Just as, Just bs) -> case as <> bs of + [els] -> els + els -> JsonElementsTup els + _ -> falseP + where + -- Sequenced elements, or none, for no sequence of elements. + flatten = \case + JsonElementsAlt [] -> Nothing + JsonElementsTup els -> Just els + els -> Just [els] +instance Monoid JsonElements where + mempty = JsonElementsTup [] +instance DisjunctiveMonoid JsonElements where + falseP = JsonElementsAlt [] + a >|< b | a == b = a + JsonElementsAlt [] >|< b = b + a >|< JsonElementsAlt [] = a + JsonElements1 a >|< JsonElementsTup [] = starK a + JsonElementsTup [] >|< JsonElements1 b = starK b + a >|< JsonElementsTup [] = optK a + JsonElementsTup [] >|< b = optK b + a >|< b = case nub (flatten a <> flatten b) of + [els] -> els + alts -> JsonElementsAlt alts + where + flatten = \case + JsonElementsAlt alts -> alts + els -> [els] +instance KleeneStarAlgebra JsonElements where + starK = \case + JsonElementsAlt [] -> mempty + JsonElementsTup [] -> mempty + els -> JsonElements els + plusK = \case + JsonElementsAlt [] -> falseP + JsonElementsTup [] -> mempty + els -> JsonElements1 els + optK = \case + JsonElementsAlt [] -> mempty + JsonElementsTup [] -> mempty + JsonElements1 els -> starK els + els@(JsonElements _) -> els + els@(JsonElementsOpt _) -> els + els -> JsonElementsOpt els + +{- | The type of the JSON of a type, by its rules, which are named +by their qualified names. + +>>> jsonType (type Bool) +Bnf {startBnf = JsonBoolean, rulesBnf = fromList []} +>>> jsonType (Maybe Ordering) +Bnf {startBnf = JsonUnion [JsonNull,JsonRule "GHC.Types.Ordering"], rulesBnf = fromList [("GHC.Types.Ordering",JsonUnion [JsonLiteral "LT",JsonLiteral "EQ",JsonLiteral "GT"])]} +-} +jsonType :: forall (a :: Type) -> Json a => Bnf JsonType +jsonType a = Bnf start (Set.fromList (Map.toList rules)) + where + JsonTypor typed = json @a @JsonTypor + (start, rules) = runState (runReaderT typed Map.empty) Map.empty + +{- | Type the JSON of types, in TypeScript, as a declaration of each rule +of their types, named by its unqualified name, or else its qualified name, +which `jsonTsPut` puts. + +>>> jsonTsDeclarations (type '[Maybe Ordering]) +[TypeAliasDeclaration [ExportKeyword] "Ordering" [] (UnionType [LiteralType (TextLiteral "LT"),LiteralType (TextLiteral "EQ"),LiteralType (TextLiteral "GT")])] +-} +jsonTsDeclarations :: forall (as :: [Type]) -> All Json as => [TsDeclaration] +jsonTsDeclarations as = tsDeclarations $ hcollapse + (hcpure (Proxy @Json) root :: NP (K (Bnf JsonType)) as) + where + root :: forall a. Json a => K (Bnf JsonType) a + root = K (jsonType (type a)) + +{- | Put the TypeScript declarations of the JSON of types to a handle, +like a @.ts@ file. + +>>> jsonTsPut (type '[Maybe Ordering]) stdout +export type Ordering = "LT" | "EQ" | "GT"; +-} +jsonTsPut :: forall (as :: [Type]) -> All Json as => Handle -> IO () +jsonTsPut as handle = case (parsecResult printed, parsecResult source) of + (Nothing, _) -> unprinted "tokens" printed + (_, Nothing) -> unprinted "characters" source + _ -> 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) + source = + unparsecG tsTokensGrammar (toList (parsecStream printed)) (Seq.empty @Char) + unprinted layer stage = ioError $ userError $ + "jsonTsPut: cannot print " <> layer <> " at " + <> show (parsecOffset stage) <> ", expecting " + <> show (parsecExpect (parsecFailure stage)) + +{- | t'JsonTypor' types the JSON of a grammar, reading the rules being typed +which are unguarded by an array, object or tuple, each noting whether it's +been unrolled, & updating the rules & their types. +-} +newtype JsonTypor a b = JsonTypor (Typing JsonType) + +-- | The elements of tuples, which `>*<` sequences. +newtype TupTypor a b = TupTypor + {runTupTypor :: Ap Typing JsonElements} + +-- | Alternative shapes of objects, which `>*<` concatenates. +newtype ObjTypor a b = ObjTypor + {runObjTypor :: Ap Typing (Ap [] [JsonProperty])} + +type Typing = ReaderT (Map String Bool) (State (Map String JsonType)) + +{- | Type a rule once, so that every other occurrence of it, recursive or +not, is a `JsonRule`. Its type is reserved, as `falseP`, while it's typed. +An unguarded occurrence is its least fixpoint instead, unrolled once, +so that a rule of a rule is the rule, & a rule recurring unguarded +contributes `falseP`, since JSON values are finite. +-} +typeRule :: String -> JsonTypor a b -> JsonTypor c d +typeRule key (JsonTypor body) = JsonTypor $ do + unguarded <- ask + typed <- lift get + case (Map.lookup key unguarded, Map.member key typed) of + (Just True, _) -> pure falseP + (Just False, _) -> local (Map.insert key True) body + (Nothing, True) -> pure (JsonRule key) + (Nothing, False) -> do + lift (modify (Map.insert key falseP)) + ruleType <- local (Map.insert key False) body + lift (modify (Map.insert key ruleType)) + pure (JsonRule key) + +guarded :: Typing a -> Typing a +guarded = local (const Map.empty) + +typing :: JsonType -> JsonTypor a b +typing = JsonTypor . pure + +deriving via Grammor (Typing JsonType) a + instance Functor (JsonTypor a) +deriving via Grammor (Typing JsonType) + instance Profunctor JsonTypor +deriving via Grammor (Typing JsonType) + instance Choice JsonTypor +-- | A partial isomorphism, like `?<`, matches a `JsonSubtype`. +instance Cochoice JsonTypor where + unleft (JsonTypor t) = JsonTypor (jsonSubtype <$> t) + unright (JsonTypor t) = JsonTypor (jsonSubtype <$> t) +instance Witherable.Filterable (JsonTypor a) where + mapMaybe = dimapMaybe Just +instance Filtrator JsonTypor +instance CocartesianMonoidal JsonTypor +instance CocartesianChoice JsonTypor where + alternate = either coerce coerce +instance DisjunctiveMonoid (JsonTypor a b) where + falseP = typing falseP + JsonTypor t0 >|< JsonTypor t1 = JsonTypor (liftA2 (>|<) t0 t1) +instance BackusNaurForm (JsonTypor a b) where + rule = typeRule + ruleRec name f = rule name (f (typeRule name falseP)) +instance (x ~ (), y ~ ()) => IsString (JsonTypor x y) where + fromString = typing . JsonLiteral . Text.pack +instance JsonStr JsonTypor where + jsonText = typing JsonString + jsonEnumWith _ table = + typing (jsonUnion [JsonLiteral literal | (literal, _) <- table]) +instance JsonVal JsonTypor where + jsonNull = typing JsonNull + jsonBool = typing JsonBoolean + jsonNumber = typing JsonNumber + jsonTuple tup = JsonTypor (tuple <$> getAp (runTupTypor tup)) + where + tuple = \case + JsonElementsAlt [] -> falseP + els -> JsonArray els + jsonObject obj = JsonTypor (objects <$> getAp (runObjTypor obj)) + where + objects (Ap shapes) = jsonUnion (map object shapes) + object props + | length (nub keys) == length keys = JsonObject props + | otherwise = falseP + where + keys = [key | JsonProperty key _ _ <- props] + +deriving via Grammor (Ap Typing JsonElements) a + instance Functor (TupTypor a) +deriving via Grammor (Ap Typing JsonElements) a + instance Applicative (TupTypor a) +deriving via Grammor (Ap Typing JsonElements) + instance Profunctor TupTypor +instance CocartesianMonoidal TupTypor +instance Choice TupTypor where + left' = coerce + right' = coerce +instance CocartesianChoice TupTypor where + alternate = either coerce coerce +instance DisjunctiveMonoid (TupTypor a b) where + falseP = TupTypor (pure falseP) + TupTypor s0 >|< TupTypor s1 = TupTypor (liftA2 (>|<) s0 s1) +-- | `manyP` is a repetition of elements, `starK`. +instance Distributor TupTypor where + manyP (TupTypor s) = TupTypor (starK <$> s) +instance Alternative (TupTypor a) where + empty = falseP + (<|>) = (>|<) + many = lmap repeat . manyP + some = lmap repeat . someP +instance Alternator TupTypor +instance JsonTup JsonTypor TupTypor where + jsonElem (JsonTypor t) = TupTypor (Ap (single <$> guarded t)) + where + single = \case + JsonUnion [] -> falseP + ty -> JsonElement ty + +deriving via Grammor (Ap Typing (Ap [] [JsonProperty])) a + instance Functor (ObjTypor a) +deriving via Grammor (Ap Typing (Ap [] [JsonProperty])) a + instance Applicative (ObjTypor a) +deriving via Grammor (Ap Typing (Ap [] [JsonProperty])) + instance Profunctor ObjTypor +instance Choice ObjTypor where + left' = coerce + right' = coerce +instance CocartesianMonoidal ObjTypor +instance CocartesianChoice ObjTypor where + alternate = either coerce coerce +instance DisjunctiveMonoid (ObjTypor a b) where + falseP = ObjTypor (pure (Ap [])) + ObjTypor s0 >|< ObjTypor s1 = ObjTypor (liftA2 unite s0 s1) + where + unite (Ap shapes0) (Ap shapes1) = Ap (shapes0 <> shapes1) +instance JsonObj JsonTypor ObjTypor where + jsonDict (JsonTypor k) (JsonTypor t) = + typedProperty (JsonDict <$> guarded k <*> guarded t) + k !: JsonTypor t = typedProperty (JsonProperty k False <$> guarded t) + k ?: JsonTypor t = typedProperty (JsonProperty k True <$> guarded t) + +-- | An object type of one property. +typedProperty :: Typing JsonProperty -> ObjTypor a b +typedProperty prop = ObjTypor (Ap ((\p -> Ap [[p]]) <$> prop)) + +-- | An element of a TypeScript tuple type. +data TupleElement + = RequiredElement JsonType -- ^ @T@ + | OptionalElement JsonType -- ^ @T?@ + | RestElement JsonType -- ^ @...T[]@ + deriving stock Eq + +elementType :: TupleElement -> JsonType +elementType = \case + RequiredElement t -> t + OptionalElement t -> t + RestElement t -> t + +-- | TypeScript tuple shapes, widening @(A B)*@ to @[...(A | B)[]]@. +tupleShapes :: JsonElements -> [[TupleElement]] +tupleShapes = \case + JsonElement t -> [[RequiredElement t]] + JsonElementsTup els -> map concat (traverse tupleShapes els) + JsonElementsAlt alts -> concatMap tupleShapes alts + JsonElements els -> case concatMap (map elementType) (tupleShapes els) of + [] -> [[]] + ts -> [[RestElement (jsonUnion ts)]] + JsonElements1 els -> + [ shape <> rest + | shape <- tupleShapes els, rest <- tupleShapes (JsonElements els) ] + JsonElementsOpt els -> tupleShapes els <> [[]] + +-- TypeScript -- + +{- | TypeScript declarations of the rules of some types, named by their +unqualified names, or else their qualified names, or else their numbered +qualified names, as TypeScript identifiers, in order of their names. +-} +tsDeclarations :: [Bnf JsonType] -> [TsDeclaration] +tsDeclarations bnfs = + [ TypeAliasDeclaration [ExportKeyword] identifier [] (tsType rules names ruleType) + | (identifier, ruleType) <- sortOn fst + [(names Map.! key, ruleType) | (key, ruleType) <- Map.toList rules] + ] + where + rules = Map.fromList (concatMap (Set.toList . rulesBnf) bnfs) + names = foldl' name Map.empty (Map.keys rules) + name named key = Map.insert key fresh named + where + taken = Map.elems named + fresh = fromMaybe qualified $ find + (\candidate -> candidate `notElem` taken + && candidate `notElem` tsReserved) + ( tsIdentifier (unqualified key) : qualified + : [qualified <> "_" <> Text.pack (show n) | n <- [2 :: Int ..]] ) + qualified = tsIdentifier key + +-- | Names of types which TypeScript reserves. +tsReserved :: [Text] +tsReserved = + [ "any", "bigint", "boolean", "false", "never", "null", "number" + , "object", "string", "symbol", "true", "undefined", "unknown", "void" + ] + +-- | A TypeScript identifier for a rule name, like @Box_List_Int@. +tsIdentifier :: String -> Text +tsIdentifier name = case Text.uncons ident of + Nothing -> "T" + Just (c, _) | isDigit c -> "T_" <> ident + _ -> ident + where + ident = Text.intercalate "_" + [part | part <- Text.split (not . isAlphaNum) (Text.pack spelled) + , not (Text.null part)] + spelled = concatMap (\c -> if c == '[' then " List " else [c]) name + +{- | The TypeScript type of a JSON type, by its rules & their names, +parenthesized as TypeScript parses it. +-} +tsType :: Map String JsonType -> Map String Text -> JsonType -> TsType +tsType rules names = typeNode + where + typeNode = \case + JsonRule key -> ReferenceType [names Map.! key] [] + JsonNull -> LiteralType NullLiteral + JsonBoolean -> KeywordType BooleanKeyword + JsonNumber -> KeywordType NumberKeyword + JsonString -> KeywordType StringKeyword + JsonLiteral text -> LiteralType (TextLiteral text) + JsonSubtype t -> typeNode t + t@(JsonArray _) -> typeNode (JsonUnion [t]) + JsonObject props -> object props + JsonUnion ts -> union $ case break isTuple ts of + (before, _ : _) -> + map typeNode before + <> map tuple + (tsTuples (concat [tupleShapes els | JsonArray els <- ts])) + <> [typeNode t | t <- drop (length before) ts, not (isTuple t)] + _ -> map typeNode ts + isTuple = \case JsonArray _ -> True; _ -> False + tuple = \case + [RestElement t] -> ArrayType (operand (typeNode t)) + els -> TupleType $ els <&> \case + RequiredElement t -> typeNode t + OptionalElement t -> OptionalType (operand (typeNode t)) + RestElement t -> RestType (ArrayType (operand (typeNode t))) + -- The intersected parts of an object type: its named properties + -- & index signature, of its string keys, & a mapped type + -- of its literal keys, but those which are named, which TypeScript + -- types apart, like @{ id: T } & { [key in K as …]?: U }@. + object props = case (named <> indexSignatures, mappedTypes) of + ([], []) -> ObjectType [] + ([], [objectPart]) -> objectPart + ([], objectParts) -> IntersectionType objectParts + (members, objectParts) -> case ObjectType members : objectParts of + [objectPart] -> objectPart + allObjectParts -> IntersectionType allObjectParts + where + named = + [ PropertySignature [] (propertyName key) isOptional (Just (typeNode t)) + | JsonProperty key isOptional t <- props ] + keys = [key | JsonProperty key _ _ <- props] + dicts = + [ (keyType, typeAlternatives rules keyType, t) + | JsonDict keyType t <- props, t /= falseP ] + indexSignatures = + [ IndexSignature [] "key" (KeywordType StringKeyword) $ union + (typeNode t : covered) + | (_, keyAlternatives, t) <- dicts, JsonString `elem` keyAlternatives ] + -- An index type also covers the named properties, + -- as TypeScript requires. + covered = + [typeNode t | JsonProperty _ _ t <- props] + <> [KeywordType UndefinedKeyword | or [o | JsonProperty _ o _ <- props]] + mappedTypes = + [ MappedType Nothing "key" base exclusion (Just QuestionToken) (typeNode t) + | (keyType, keyAlternatives, t) <- dicts + , let + literalKeys = [l | JsonLiteral l <- keyAlternatives] + excluded = [l | l <- literalKeys, l `elem` keys] + base + | length literalKeys == length keyAlternatives = typeNode keyType + | otherwise = union (map (LiteralType . TextLiteral) literalKeys) + exclusion + | null excluded = Nothing + | otherwise = Just $ ConditionalType + (ReferenceType ["key"] []) + (union (map (LiteralType . TextLiteral) excluded)) + (KeywordType NeverKeyword) + (ReferenceType ["key"] []) + , length excluded < length literalKeys + ] + propertyName key + | isIdentifier key = PropertyIdentifier key + | otherwise = PropertyString key + isIdentifier key = case Text.uncons key of + Just (c, rest) -> identifierStart c && Text.all identifierChar rest + Nothing -> False + identifierStart c = isAlpha c || c == '_' || c == '$' + identifierChar c = isAlphaNum c || c == '_' || c == '$' + +-- | A union of types, flattened, or else its only type, or else @never@. +union :: [TsType] -> TsType +union nodes = case nub (concatMap flatten nodes) of + [] -> KeywordType NeverKeyword + [node] -> node + alts -> UnionType (map member alts) + where + flatten = \case + UnionType alts -> alts + KeywordType NeverKeyword -> [] + node -> [node] + member = \case + node@(ConditionalType {}) -> ParenthesizedType node + node -> node + +-- | A type, parenthesized as an operand of an array or element type. +operand :: TsType -> TsType +operand = \case + node@(UnionType _) -> ParenthesizedType node + node@(IntersectionType _) -> ParenthesizedType node + node@(ConditionalType {}) -> ParenthesizedType node + node -> node + +-- | The alternatives of a type, resolving its rules & widening subtypes. +typeAlternatives :: Map String JsonType -> JsonType -> [JsonType] +typeAlternatives rules = go [] + where + go seen = \case + JsonRule key | key `notElem` seen, Just t <- Map.lookup key rules -> + go (key : seen) t + JsonUnion ts -> concatMap (go seen) ts + JsonSubtype t -> go seen t + t -> [t] + +{- | Tuples of some shapes, as TypeScript types them. TypeScript requires +that a tuple type has at most one rest element, no optional element after +a rest element, & no required element after an optional element. +So, the elements from the first rest element to the last are merged +into one rest element, & optional elements are expanded into +alternative shapes wherever they'd be followed by a required or +rest element, or a rest element precedes them. +Then, alternative shapes are merged exactly, where they differ by +one required or optional element's type, into a union, or by one more +element, into an optional or rest element, so that @[A] | [B]@ is @[A | B]@, +@[A] | [A, B]@ is @[A, B?]@ & @[] | [A, ...A[]]@ is @[...A[]]@. +-} +tsTuples :: [[TupleElement]] -> [[TupleElement]] +tsTuples shapes = merged (nub (concatMap (expand False . mergeRests) shapes)) + where + merged alts = + case [ (i, j, shape) + | merge <- [unioned, extended] + , (i, a) <- zip [0 :: Int ..] alts + , (j, b) <- zip [0 ..] alts + , i /= j + , Just shape <- [merge a b] + ] of + (i, j, shape) : _ -> merged + [ if k == min i j then shape else alt + | (k, alt) <- zip [0 ..] alts, k /= max i j ] + [] -> alts + unioned a b = case break (uncurry (/=)) (zip a b) of + (same, (x, y) : others) + | length a == length b, all (uncurry (==)) others + , Just el <- unionedElement x y -> + Just (map fst same <> [el] <> map fst others) + _ -> Nothing + unionedElement x y = case (x, y) of + (RequiredElement s, RequiredElement t) -> Just (RequiredElement (s >|< t)) + (OptionalElement s, OptionalElement t) -> Just (OptionalElement (s >|< t)) + _ -> Nothing + extended a b + | any isRest a = Nothing + | otherwise = stripPrefix a b >>= \case + [RequiredElement t] -> Just (a <> [OptionalElement t]) + [OptionalElement _] -> Just b + [RestElement _] -> Just b + [RequiredElement t, RestElement u] | t == u -> Just (a <> [RestElement t]) + _ -> Nothing + isRest = \case RestElement _ -> True; _ -> False + mergeRests els = case findIndices isRest els of + start : rests@(_ : _) -> + let + (before, others) = splitAt start els + (middle, after) = splitAt (last rests - start + 1) others + in + before <> [RestElement (jsonUnion (map elementType middle))] <> after + _ -> els + expand _ [] = [[]] + expand restBefore (el : els) = case el of + OptionalElement t | restBefore || not (optionalTail els) -> + expand restBefore els <> map (RequiredElement t :) (expand restBefore els) + RestElement _ -> map (el :) (expand True els) + _ -> map (el :) (expand restBefore els) + optionalTail = \case + [] -> True + [RestElement _] -> True + OptionalElement _ : els -> optionalTail els + _ -> False + +-- Json instance helpers + +-- | An enumeration of a bounded `Enum`, by the names of its values. +jsonEnumerated :: (Bounded a, Enum a, JsonStr p) => (a -> Text) -> p a a +jsonEnumerated name = jsonEnumWith + (\a -> fromEnum a - fromEnum (minBound `asTypeOf` a)) + [(name a, a) | a <- [minBound .. maxBound]] + +boundedScientific :: Scientific -> Maybe Scientific +boundedScientific s = s <$ guard (abs (base10Exponent s) <= 1024) + +_BoundedInteger :: (Integral a, Bounded a) => Prism' Scientific a +_BoundedInteger = prism' fromIntegral toBoundedInteger + +jsonBoundedInteger :: (Integral a, Bounded a, JsonVal p) => p a a +jsonBoundedInteger = _BoundedInteger ?< jsonNumber + +_Integer :: Prism' Scientific Integer +_Integer = prism' fromInteger $ + boundedScientific >=> either (const Nothing) Just . floatingOrInteger @Double + +_Natural :: Prism' Scientific Natural +_Natural = prism' fromIntegral $ \s -> do + i <- preview _Integer s + fromInteger i <$ guard (i >= 0) + +jsonRealFloat :: (RealFloat a, JsonVal p) => p a a -> p a a +jsonRealFloat finite = dimap finiteness (either id id) (finite >+< nonFinite) + where + finiteness x = if isNaN x || isInfinite x then Right x else Left x + nonFinite = dimap sign value (jsonNull >+< "+inf" >+< "-inf") + sign x + | isNaN x = Left () + | x > 0 = Right (Left ()) + | otherwise = Right (Right ()) + value = either (\_ -> 0/0) (either (\_ -> 1/0) (\_ -> negate 1/0)) + +jsonRealFrac :: (Fractional a, Real a, JsonVal p) => p a a +jsonRealFrac = + prism' realToFrac (fmap realToFrac . boundedScientific) ?< jsonNumber + + +jsonKeyText :: JsonStr p => p Key Key +jsonKeyText = iso Key.toText Key.fromText >~ jsonText + +-- | Read a `Scientific`, quickly when it's a canonical integer. +readScientific :: Text -> Maybe Scientific +readScientific t + | canonical, Right (i, _) <- TextRead.signed TextRead.decimal t = + Just (fromInteger i) + | otherwise = + listToMaybe [s | (s, "") <- readP_to_S scientificP (Text.unpack t)] + where + digits = fromMaybe t (Text.stripPrefix "-" t) + canonical = not (Text.null digits) && Text.all isDigit digits + && (Text.length digits == 1 || Text.take 1 digits /= "0") + +-- | `Scientific` map keys, as @aeson@ renders them. +jsonScientificKey :: JsonStr p => p Scientific Scientific +jsonScientificKey = prism' render readScientific ?< jsonText + where + render s + | e < 0 || e > 1024 = Text.pack (formatScientific Generic Nothing s) + | otherwise = Text.pack (show (coefficient s * 10 ^ e)) + where + e = base10Exponent s + +-- | Integral map keys, as @aeson@ renders them. +jsonIntKey :: (Show a, JsonStr p) => APrism' Scientific a -> p a a +jsonIntKey integral = jsonEncodedText $ prism shown $ \t -> + maybe (Left (t, Encoding.text t)) Right + (readScientific t >>= preview (clonePrism integral)) + where + shown a = (Text.pack (show a), Encoding.unsafeToEncoding + (Builder.char7 '"' <> Builder.string7 (show a) <> Builder.char7 '"')) + +-- | `RealFloat` map keys, as @aeson@ renders them. +jsonRealFloatKey :: (RealFloat a, Show a, JsonStr p) => p a a +jsonRealFloatKey = prism' render parse ?< jsonText + where + render d + | isInfinite d = if d > 0 then "+inf" else "-inf" + | otherwise = Text.pack (show d) + parse = \case + "NaN" -> Just (0/0) + "+inf" -> Just (1/0) + "-inf" -> Just (negate 1/0) + t -> toRealFloat <$> readScientific t + +-- | Transform a key, if there's one. +overKey + :: (forall k. JsonStr k => k a a -> k b b) + -> Maybe (forall k. JsonStr k => k a a) + -> Maybe (forall k. JsonStr k => k b b) +overKey f = \case + Just key -> Just (f key) + Nothing -> Nothing + +-- Json instances + +-- base +instance Json Bool where + json = jsonBool + {-# INLINE json #-} + jsonKey = Just (jsonEnumerated (\b -> if b then "true" else "false")) +instance Json Ordering where + json = jsonTyped (jsonEnumerated (Text.pack . show)) +instance Json () where + json = jsonTuple oneP + jsonOmitField = Just (only ()) +instance Json Void where + json = zeroP + jsonKey = Just (prism' absurd (const Nothing) ?< jsonText) + +jsonChar :: JsonStr p => p Char Char +jsonChar = prism' Text.singleton single ?< jsonText + where + single t = case Text.uncons t of + Just (c, rest) | Text.null rest -> Just c + _ -> Nothing + +instance Json Char where + json = jsonTyped jsonChar + jsonList = jsonString + jsonKey = Just jsonChar + jsonKeyList = Just jsonString +instance Json a => Json [a] where + json = jsonList + {-# INLINE json #-} + jsonKey = jsonKeyList @a +instance Json a => Json (Maybe a) where + json = jsonNullable json + jsonOmitField = Just _Nothing +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) + jsonKey = Just jsonRealFloatKey +instance Json Float where + json = jsonTyped $ + jsonRealFloat (iso fromFloatDigits toRealFloat >~ jsonNumber) + jsonKey = Just jsonRealFloatKey +instance (Integral a, Json a) => Json (Ratio a) where + json = prism' + (\r -> (numerator r, denominator r)) + (\(n, d) -> n % d <$ guard (d /= 0)) + ?< jsonObject ("numerator" !: json >*< "denominator" !: json) +instance HasResolution a => Json (Fixed a) where + json = jsonRealFrac + jsonKey = Just (iso realToFrac realToFrac >~ jsonScientificKey) +instance Json Int where + json = jsonTyped jsonInt + {-# INLINE json #-} + jsonKey = Just (jsonIntKey _BoundedInteger) +instance Json Int8 where + json = jsonTyped jsonInt8 + jsonKey = Just (jsonIntKey _BoundedInteger) +instance Json Int16 where + json = jsonTyped jsonInt16 + jsonKey = Just (jsonIntKey _BoundedInteger) +instance Json Int32 where + json = jsonTyped jsonInt32 + jsonKey = Just (jsonIntKey _BoundedInteger) +instance Json Int64 where + json = jsonTyped jsonInt64 + jsonKey = Just (jsonIntKey _BoundedInteger) +instance Json Word where + json = jsonTyped jsonWord + jsonKey = Just (jsonIntKey _BoundedInteger) +instance Json Word8 where + json = jsonTyped jsonWord8 + jsonKey = Just (jsonIntKey _BoundedInteger) +instance Json Word16 where + json = jsonTyped jsonWord16 + jsonKey = Just (jsonIntKey _BoundedInteger) +instance Json Word32 where + json = jsonTyped jsonWord32 + jsonKey = Just (jsonIntKey _BoundedInteger) +instance Json Word64 where + json = jsonTyped jsonWord64 + jsonKey = Just (jsonIntKey _BoundedInteger) +instance Json Integer where + json = jsonTyped jsonInteger + jsonKey = Just (jsonIntKey _Integer) +instance Json Natural where + json = jsonTyped jsonNatural + jsonKey = Just (jsonIntKey _Natural) +instance Json CTime where json = coerced >~ json @Int64 + +jsonVersion :: JsonStr p => p Version Version +jsonVersion = prism' (Text.pack . showVersion) version ?< jsonText + where + version t = + listToMaybe [v | (v, "") <- readP_to_S parseVersion (Text.unpack t)] + +instance Json Version where + json = jsonTyped jsonVersion + jsonKey = Just jsonVersion +instance Json a => Json (NonEmpty a) where + json = prism' toList nonEmpty ?< jsonTuple (someP (jsonElem json)) +instance Json a => Json (Solo a) where + json = iso getSolo MkSolo >~ json @a + jsonList = iso (map getSolo) (map MkSolo) >~ jsonList @a + jsonKey = overKey (iso getSolo MkSolo >~) (jsonKey @a) + jsonKeyList = overKey (iso (map getSolo) (map MkSolo) >~) (jsonKeyList @a) +instance Json a => Json (Identity a) where + json = coerced >~ json @a + jsonOmitField = (coerced .) <$> jsonOmitField @a + jsonList = coerced >~ jsonList @a + jsonKey = overKey (coerced >~) (jsonKey @a) + jsonKeyList = overKey (coerced >~) (jsonKeyList @a) +instance Json a => Json (Const a b) where + json = coerced >~ json @a + jsonOmitField = (coerced .) <$> jsonOmitField @a + jsonKey = overKey (coerced >~) (jsonKey @a) +instance Json (f (g a)) => Json (Compose f g a) where + json = coerced >~ json @(f (g a)) +instance (Json (f a), Json (g a)) => Json (Functor.Product f g a) where + json = gtuple +instance (Json (f a), Json (g a)) => Json (Functor.Sum f g a) where + json = iso + (\case Functor.InL x -> Left x; Functor.InR y -> Right y) + (either Functor.InL Functor.InR) + >~ jsonTag "InL" json >+< jsonTag "InR" json +instance Json a => Json (Down a) where + json = coerced >~ json @a + jsonList = coerced >~ jsonList @a +instance Json a => Json (Monoid.Dual a) where + json = coerced >~ json @a + jsonList = coerced >~ jsonList @a +instance Json a => Json (Monoid.First a) where json = coerced >~ json @(Maybe a) +instance Json a => Json (Monoid.Last a) where json = coerced >~ json @(Maybe a) +instance Json a => Json (Semigroup.Min a) where + json = coerced >~ json @a + jsonList = coerced >~ jsonList @a +instance Json a => Json (Semigroup.Max a) where + json = coerced >~ json @a + jsonList = coerced >~ jsonList @a +instance Json a => Json (Semigroup.First a) where + json = coerced >~ json @a + jsonList = coerced >~ jsonList @a +instance Json a => Json (Semigroup.Last a) where + json = coerced >~ json @a + jsonList = coerced >~ jsonList @a +instance Json a => Json (Semigroup.WrappedMonoid a) where + json = coerced >~ json @a + jsonList = coerced >~ jsonList @a +instance Json a => Json (Semigroup.Sum a) where + json = coerced >~ json @a + jsonList = coerced >~ jsonList @a +instance Json a => Json (Semigroup.Product a) where + json = coerced >~ json @a + jsonList = coerced >~ jsonList @a +instance Json Semigroup.All where json = coerced >~ json @Bool +instance Json Semigroup.Any where json = coerced >~ json @Bool +instance Json (Proxy a) where + json = dimap (const ()) (const Proxy) jsonNull + jsonOmitField = Just (only Proxy) +-- tuples +-- | An element of a tuple, by its projection. +projectElem :: (Json a, JsonVal p, JsonTup p q) => (s -> a) -> q s a +projectElem f = lmap f (jsonElem json) +{-# INLINE projectElem #-} + +instance (Json a, Json b) => Json (a, b) where + json = jsonPair json json + {-# INLINE json #-} + jsonList = jsonArray json + {-# INLINE jsonList #-} +instance (Json a, Json b, Json c) => Json (a, b, c) where + json = jsonTuple $ (,,) + <$> projectElem (\(a, _, _) -> a) + <*> projectElem (\(_, b, _) -> b) + <*> projectElem (\(_, _, c) -> c) + {-# INLINE json #-} + jsonList = jsonArray json + {-# INLINE jsonList #-} +instance (Json a, Json b, Json c, Json d) => Json (a, b, c, d) where + json = jsonTuple $ (,,,) + <$> projectElem (\(a, _, _, _) -> a) + <*> projectElem (\(_, b, _, _) -> b) + <*> projectElem (\(_, _, c, _) -> c) + <*> projectElem (\(_, _, _, d) -> d) +instance (Json a, Json b, Json c, Json d, Json e) => Json (a, b, c, d, e) where + json = jsonTuple $ (,,,,) + <$> projectElem (\(a, _, _, _, _) -> a) + <*> projectElem (\(_, b, _, _, _) -> b) + <*> projectElem (\(_, _, c, _, _) -> c) + <*> projectElem (\(_, _, _, d, _) -> d) + <*> projectElem (\(_, _, _, _, e) -> e) +instance + ( Json a, Json b, Json c, Json d, Json e, Json f ) + => Json (a, b, c, d, e, f) where + json = jsonTuple $ (,,,,,) + <$> projectElem (\(a, _, _, _, _, _) -> a) + <*> projectElem (\(_, b, _, _, _, _) -> b) + <*> projectElem (\(_, _, c, _, _, _) -> c) + <*> projectElem (\(_, _, _, d, _, _) -> d) + <*> projectElem (\(_, _, _, _, e, _) -> e) + <*> projectElem (\(_, _, _, _, _, f) -> f) +instance + ( Json a, Json b, Json c, Json d, Json e, Json f, Json g ) + => Json (a, b, c, d, e, f, g) where + json = jsonTuple $ (,,,,,,) + <$> projectElem (\(a, _, _, _, _, _, _) -> a) + <*> projectElem (\(_, b, _, _, _, _, _) -> b) + <*> projectElem (\(_, _, c, _, _, _, _) -> c) + <*> projectElem (\(_, _, _, d, _, _, _) -> d) + <*> projectElem (\(_, _, _, _, e, _, _) -> e) + <*> projectElem (\(_, _, _, _, _, f, _) -> f) + <*> projectElem (\(_, _, _, _, _, _, g) -> g) +instance + ( Json a, Json b, Json c, Json d, Json e, Json f, Json g, Json h ) + => Json (a, b, c, d, e, f, g, h) where + json = jsonTuple $ (,,,,,,,) + <$> projectElem (\(a, _, _, _, _, _, _, _) -> a) + <*> projectElem (\(_, b, _, _, _, _, _, _) -> b) + <*> projectElem (\(_, _, c, _, _, _, _, _) -> c) + <*> projectElem (\(_, _, _, d, _, _, _, _) -> d) + <*> projectElem (\(_, _, _, _, e, _, _, _) -> e) + <*> projectElem (\(_, _, _, _, _, f, _, _) -> f) + <*> projectElem (\(_, _, _, _, _, _, g, _) -> g) + <*> projectElem (\(_, _, _, _, _, _, _, h) -> h) +instance + ( Json a, Json b, Json c, Json d, Json e, Json f, Json g, Json h, Json i ) + => Json (a, b, c, d, e, f, g, h, i) where + json = jsonTuple $ (,,,,,,,,) + <$> projectElem (\(a, _, _, _, _, _, _, _, _) -> a) + <*> projectElem (\(_, b, _, _, _, _, _, _, _) -> b) + <*> projectElem (\(_, _, c, _, _, _, _, _, _) -> c) + <*> projectElem (\(_, _, _, d, _, _, _, _, _) -> d) + <*> projectElem (\(_, _, _, _, e, _, _, _, _) -> e) + <*> projectElem (\(_, _, _, _, _, f, _, _, _) -> f) + <*> projectElem (\(_, _, _, _, _, _, g, _, _) -> g) + <*> projectElem (\(_, _, _, _, _, _, _, h, _) -> h) + <*> projectElem (\(_, _, _, _, _, _, _, _, i) -> i) +instance + ( Json a, Json b, Json c, Json d, Json e, Json f, Json g, Json h, Json i + , Json j ) + => Json (a, b, c, d, e, f, g, h, i, j) where + json = jsonTuple $ (,,,,,,,,,) + <$> projectElem (\(a, _, _, _, _, _, _, _, _, _) -> a) + <*> projectElem (\(_, b, _, _, _, _, _, _, _, _) -> b) + <*> projectElem (\(_, _, c, _, _, _, _, _, _, _) -> c) + <*> projectElem (\(_, _, _, d, _, _, _, _, _, _) -> d) + <*> projectElem (\(_, _, _, _, e, _, _, _, _, _) -> e) + <*> projectElem (\(_, _, _, _, _, f, _, _, _, _) -> f) + <*> projectElem (\(_, _, _, _, _, _, g, _, _, _) -> g) + <*> projectElem (\(_, _, _, _, _, _, _, h, _, _) -> h) + <*> projectElem (\(_, _, _, _, _, _, _, _, i, _) -> i) + <*> projectElem (\(_, _, _, _, _, _, _, _, _, j) -> j) +instance + ( Json a, Json b, Json c, Json d, Json e, Json f, Json g, Json h, Json i + , Json j, Json k ) + => Json (a, b, c, d, e, f, g, h, i, j, k) where + json = jsonTuple $ (,,,,,,,,,,) + <$> projectElem (\(a, _, _, _, _, _, _, _, _, _, _) -> a) + <*> projectElem (\(_, b, _, _, _, _, _, _, _, _, _) -> b) + <*> projectElem (\(_, _, c, _, _, _, _, _, _, _, _) -> c) + <*> projectElem (\(_, _, _, d, _, _, _, _, _, _, _) -> d) + <*> projectElem (\(_, _, _, _, e, _, _, _, _, _, _) -> e) + <*> projectElem (\(_, _, _, _, _, f, _, _, _, _, _) -> f) + <*> projectElem (\(_, _, _, _, _, _, g, _, _, _, _) -> g) + <*> projectElem (\(_, _, _, _, _, _, _, h, _, _, _) -> h) + <*> projectElem (\(_, _, _, _, _, _, _, _, i, _, _) -> i) + <*> projectElem (\(_, _, _, _, _, _, _, _, _, j, _) -> j) + <*> projectElem (\(_, _, _, _, _, _, _, _, _, _, k) -> k) +instance + ( Json a, Json b, Json c, Json d, Json e, Json f, Json g, Json h, Json i + , Json j, Json k, Json l ) + => Json (a, b, c, d, e, f, g, h, i, j, k, l) where + json = jsonTuple $ (,,,,,,,,,,,) + <$> projectElem (\(a, _, _, _, _, _, _, _, _, _, _, _) -> a) + <*> projectElem (\(_, b, _, _, _, _, _, _, _, _, _, _) -> b) + <*> projectElem (\(_, _, c, _, _, _, _, _, _, _, _, _) -> c) + <*> projectElem (\(_, _, _, d, _, _, _, _, _, _, _, _) -> d) + <*> projectElem (\(_, _, _, _, e, _, _, _, _, _, _, _) -> e) + <*> projectElem (\(_, _, _, _, _, f, _, _, _, _, _, _) -> f) + <*> projectElem (\(_, _, _, _, _, _, g, _, _, _, _, _) -> g) + <*> projectElem (\(_, _, _, _, _, _, _, h, _, _, _, _) -> h) + <*> projectElem (\(_, _, _, _, _, _, _, _, i, _, _, _) -> i) + <*> projectElem (\(_, _, _, _, _, _, _, _, _, j, _, _) -> j) + <*> projectElem (\(_, _, _, _, _, _, _, _, _, _, k, _) -> k) + <*> projectElem (\(_, _, _, _, _, _, _, _, _, _, _, l) -> l) +instance + ( Json a, Json b, Json c, Json d, Json e, Json f, Json g, Json h, Json i + , Json j, Json k, Json l, Json m ) + => Json (a, b, c, d, e, f, g, h, i, j, k, l, m) where + json = jsonTuple $ (,,,,,,,,,,,,) + <$> projectElem (\(a, _, _, _, _, _, _, _, _, _, _, _, _) -> a) + <*> projectElem (\(_, b, _, _, _, _, _, _, _, _, _, _, _) -> b) + <*> projectElem (\(_, _, c, _, _, _, _, _, _, _, _, _, _) -> c) + <*> projectElem (\(_, _, _, d, _, _, _, _, _, _, _, _, _) -> d) + <*> projectElem (\(_, _, _, _, e, _, _, _, _, _, _, _, _) -> e) + <*> projectElem (\(_, _, _, _, _, f, _, _, _, _, _, _, _) -> f) + <*> projectElem (\(_, _, _, _, _, _, g, _, _, _, _, _, _) -> g) + <*> projectElem (\(_, _, _, _, _, _, _, h, _, _, _, _, _) -> h) + <*> projectElem (\(_, _, _, _, _, _, _, _, i, _, _, _, _) -> i) + <*> projectElem (\(_, _, _, _, _, _, _, _, _, j, _, _, _) -> j) + <*> projectElem (\(_, _, _, _, _, _, _, _, _, _, k, _, _) -> k) + <*> projectElem (\(_, _, _, _, _, _, _, _, _, _, _, l, _) -> l) + <*> projectElem (\(_, _, _, _, _, _, _, _, _, _, _, _, m) -> m) +instance + ( Json a, Json b, Json c, Json d, Json e, Json f, Json g, Json h, Json i + , Json j, Json k, Json l, Json m, Json n ) + => Json (a, b, c, d, e, f, g, h, i, j, k, l, m, n) where + json = jsonTuple $ (,,,,,,,,,,,,,) + <$> projectElem (\(a, _, _, _, _, _, _, _, _, _, _, _, _, _) -> a) + <*> projectElem (\(_, b, _, _, _, _, _, _, _, _, _, _, _, _) -> b) + <*> projectElem (\(_, _, c, _, _, _, _, _, _, _, _, _, _, _) -> c) + <*> projectElem (\(_, _, _, d, _, _, _, _, _, _, _, _, _, _) -> d) + <*> projectElem (\(_, _, _, _, e, _, _, _, _, _, _, _, _, _) -> e) + <*> projectElem (\(_, _, _, _, _, f, _, _, _, _, _, _, _, _) -> f) + <*> projectElem (\(_, _, _, _, _, _, g, _, _, _, _, _, _, _) -> g) + <*> projectElem (\(_, _, _, _, _, _, _, h, _, _, _, _, _, _) -> h) + <*> projectElem (\(_, _, _, _, _, _, _, _, i, _, _, _, _, _) -> i) + <*> projectElem (\(_, _, _, _, _, _, _, _, _, j, _, _, _, _) -> j) + <*> projectElem (\(_, _, _, _, _, _, _, _, _, _, k, _, _, _) -> k) + <*> projectElem (\(_, _, _, _, _, _, _, _, _, _, _, l, _, _) -> l) + <*> projectElem (\(_, _, _, _, _, _, _, _, _, _, _, _, m, _) -> m) + <*> projectElem (\(_, _, _, _, _, _, _, _, _, _, _, _, _, n) -> n) +instance + ( Json a, Json b, Json c, Json d, Json e, Json f, Json g, Json h, Json i + , Json j, Json k, Json l, Json m, Json n, Json o ) + => Json (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o) where + json = jsonTuple $ (,,,,,,,,,,,,,,) + <$> projectElem (\(a, _, _, _, _, _, _, _, _, _, _, _, _, _, _) -> a) + <*> projectElem (\(_, b, _, _, _, _, _, _, _, _, _, _, _, _, _) -> b) + <*> projectElem (\(_, _, c, _, _, _, _, _, _, _, _, _, _, _, _) -> c) + <*> projectElem (\(_, _, _, d, _, _, _, _, _, _, _, _, _, _, _) -> d) + <*> projectElem (\(_, _, _, _, e, _, _, _, _, _, _, _, _, _, _) -> e) + <*> projectElem (\(_, _, _, _, _, f, _, _, _, _, _, _, _, _, _) -> f) + <*> projectElem (\(_, _, _, _, _, _, g, _, _, _, _, _, _, _, _) -> g) + <*> projectElem (\(_, _, _, _, _, _, _, h, _, _, _, _, _, _, _) -> h) + <*> projectElem (\(_, _, _, _, _, _, _, _, i, _, _, _, _, _, _) -> i) + <*> projectElem (\(_, _, _, _, _, _, _, _, _, j, _, _, _, _, _) -> j) + <*> projectElem (\(_, _, _, _, _, _, _, _, _, _, k, _, _, _, _) -> k) + <*> projectElem (\(_, _, _, _, _, _, _, _, _, _, _, l, _, _, _) -> l) + <*> projectElem (\(_, _, _, _, _, _, _, _, _, _, _, _, m, _, _) -> m) + <*> projectElem (\(_, _, _, _, _, _, _, _, _, _, _, _, _, n, _) -> n) + <*> projectElem (\(_, _, _, _, _, _, _, _, _, _, _, _, _, _, o) -> o) + +-- text +instance Json Text where + json = jsonText + {-# INLINE json #-} + jsonKey = Just jsonText +instance Json LText.Text where + json = iso LText.toStrict LText.fromStrict >~ jsonText + jsonKey = Just (iso LText.toStrict LText.fromStrict >~ jsonText) +instance Json ShortText where + json = iso ShortText.toText ShortText.fromText >~ jsonText + jsonKey = Just (iso ShortText.toText ShortText.fromText >~ jsonText) + +-- scientific +instance Json Scientific where + json = jsonNumber + jsonKey = Just jsonScientificKey + +-- containers +instance Json a => Json (Seq a) where + json = iso toList Seq.fromList >~ jsonArray json +instance (Ord a, Json a) => Json (Set a) where + json = iso Set.toList Set.fromList >~ jsonArray json +instance Json IntSet where + json = iso IntSet.toList IntSet.fromList >~ json @[Int] +instance Json a => Json (IntMap a) where + json = iso IntMap.toList IntMap.fromList >~ json @[(Int, a)] +instance (Ord k, Json k, Json v) => Json (Map k v) where + json = case jsonKey @k of + Just key -> jsonMap key json + Nothing -> iso Map.toList Map.fromList >~ json +instance (Typeable a, Json a) => Json (Tree a) where + json = jsonTyped gtuple + +-- dlist +instance Json a => Json (DList a) where + json = iso DList.toList DList.fromList >~ jsonArray json +instance Json a => Json (DNonEmpty a) where + json = iso DNonEmpty.toNonEmpty DNonEmpty.fromNonEmpty >~ json @(NonEmpty a) + +-- vector +instance Json a => Json (Vector a) where + json = iso Vector.toList Vector.fromList >~ jsonArray json +instance (Storable a, Json a) => Json (VS.Vector a) where + json = iso VG.toList VG.fromList >~ jsonArray json +instance (VP.Prim a, Json a) => Json (VP.Vector a) where + json = iso VG.toList VG.fromList >~ jsonArray json +instance (VU.Unbox a, Json a) => Json (VU.Vector a) where + json = iso VG.toList VG.fromList >~ jsonArray json + +-- primitive +instance Json a => Json (Array a) where + json = iso Exts.toList Exts.fromList >~ json @[a] +instance Json a => Json (SmallArray a) where + json = iso Exts.toList Exts.fromList >~ json @[a] +instance (Prim a, Json a) => Json (PrimArray a) where + json = iso Exts.toList Exts.fromList >~ json @[a] + +-- unordered-containers +instance (Eq a, Hashable a, Json a) => Json (HashSet a) where + json = iso HashSet.toList HashSet.fromList >~ jsonArray json +instance (Eq k, Hashable k, Json k, Json v) => Json (HashMap k v) where + json = case jsonKey @k of + Just key -> jsonHashMap key json + Nothing -> iso HashMap.toList HashMap.fromList >~ json + +-- aeson +instance Json Key where + json = jsonKeyText + jsonKey = Just jsonKeyText +instance Json v => Json (KeyMap v) where + json = iso KeyMap.toList KeyMap.fromList + >~ jsonObject (jsonDict jsonKeyText json) +instance Json Value where + json = jsonValue +instance Json DotNetTime where + json = jsonTyped (prism' render parse ?< jsonText) + where + render (DotNetTime t) = Text.pack + ( formatTime defaultTimeLocale "/Date(%s" t + <> take 3 (formatTime defaultTimeLocale "%q" t) + <> ")/" ) + parse t = + let (s, m) = Text.splitAt (Text.length t - 5) t + in DotNetTime <$> parseTimeM True defaultTimeLocale + "/Date(%s%Q)/" (Text.unpack (Text.concat [s, ".", m])) + +-- time + +-- | A time, encoded as @aeson@ encodes it. +encodedTime + :: (a -> Encoding.Encoding' Text) -> (Text -> Either String a) + -> Prism Text (Text, Encoding.Encoding' Text) a a +encodedTime f g = prism + (\a -> let encoded = f a in (encodedText encoded, encoded)) + (\t -> either (\_ -> Left (t, Encoding.text t)) Right (g t)) + where + encodedText = Text.dropAround (== '"') . Text.decodeLatin1 + . LByteString.toStrict . Encoding.encodingToLazyByteString + +_Day :: Prism Text (Text, Encoding.Encoding' Text) Day Day +_Day = encodedTime Encoding.day TimeText.parseDay +instance Json Day where + json = jsonTyped (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) + 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) + 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) + 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) + 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) + 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) + jsonKey = Just (jsonEncodedText _UTCTime) +instance Json NominalDiffTime where json = jsonTyped jsonRealFrac +instance Json DiffTime where json = jsonTyped jsonRealFrac +instance Json SystemTime where + json = jsonTyped (prism' render parse ?< jsonNumber) + where + render (MkSystemTime s ns) = + realToFrac (fromIntegral s + fromIntegral ns / 1000000000 :: Nano) + parse sci = do + n <- realToFrac <$> boundedScientific sci :: Maybe Nano + let + r = resolution n + (s, ns) = floor (n * fromInteger r) `divMod` r + Just (MkSystemTime (fromInteger s) (fromInteger ns)) +instance Json CalendarDiffTime where + json = dimap (\(CalendarDiffTime m t) -> (m, t)) (uncurry CalendarDiffTime) + (jsonObject ("months" !: json >*< "time" !: json)) +instance Json CalendarDiffDays where + json = dimap (\(CalendarDiffDays m d) -> (m, d)) (uncurry CalendarDiffDays) + (jsonObject ("months" !: json >*< "days" !: json)) + +-- | Days of the week, named as @aeson@ names them. +weekdays :: JsonStr p => p DayOfWeek DayOfWeek +weekdays = jsonEnumWith (\day -> fromEnum day - 1) + [ (Text.toLower (Text.pack (show day)), day) + | day <- [Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday] + ] + +instance Json DayOfWeek where + json = jsonTyped weekdays + jsonKey = Just (jsonTyped 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) + +-- uuid-types + +jsonUUID :: JsonStr p => p UUID UUID +jsonUUID = prism' UUID.toText UUID.fromText ?< jsonText + +instance Json UUID where + json = jsonTyped jsonUUID + jsonKey = Just jsonUUID + +-- network-uri + +jsonURI :: JsonStr p => p URI URI +jsonURI = prism' + (\uri -> Text.pack (URI.uriToString id uri "")) + (URI.parseURI . Text.unpack) + ?< jsonText + +instance Json URI where + json = jsonTyped jsonURI + jsonKey = Just jsonURI + +-- data-fix +instance (Typeable f, Json (f (Fix f))) => Json (Fix f) where + json = jsonTyped (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 + json = iso (foldNu Fix) (unfoldNu unFix) >~ json @(Fix f) + +-- jsonTag +instance Json b => Json (Tagged a b) where + json = coerced >~ json @b + jsonOmitField = (coerced .) <$> jsonOmitField @b + jsonKey = overKey (coerced >~) (jsonKey @b) + jsonKeyList = overKey (coerced >~) (jsonKeyList @b) + +-- these +instance (Json a, Json b) => Json (These a b) where + json = orP + [ _These >? jsonObjectStrict ("This" !: json >*< "That" !: json) + , _This >? jsonTag "This" json + , _That >? jsonTag "That" json + ] +instance (Json (f a), Json (g a)) => Json (These1 f g a) where + json = iso fromThese1 toThese1 >~ json @(These (f a) (g a)) + where + fromThese1 = \case + This1 a -> This a + That1 b -> That b + These1 a b -> These a b + toThese1 = \case + This a -> This1 a + That b -> That1 b + These a b -> These1 a b + +-- strict +instance Json a => Json (Strict.Maybe a) where + json = iso Strict.toLazy Strict.toStrict >~ json @(Maybe a) + jsonOmitField = Just (nearly Strict.Nothing Strict.isNothing) +instance (Json a, Json b) => Json (Strict.Either a b) where + json = iso Strict.toLazy Strict.toStrict >~ json @(Either a b) +instance (Json a, Json b) => Json (Strict.These a b) where + json = iso Strict.toLazy Strict.toStrict >~ json @(These a b) +instance (Json a, Json b) => Json (Strict.Pair a b) where + json = iso Strict.toLazy Strict.toStrict >~ json @(a, b) + +-- Generics + +-- | The `GHC.Generic` `Json` grammar, by @aeson@'s default options. +instance + ( GHC.Generic a, GHC.Rep a ~ GHC.D1 d f, GSum f, Typeable a + , EnumTag (AllNullary f) a + ) => Json (GHC.Generically a) where + json = dimap (\(GHC.Generically a) -> a) GHC.Generically + (jsonGeneric Aeson.defaultOptions) + {-# INLINABLE json #-} + +{- | The `GHC.Generic` `Json` grammar by @aeson@'s `Aeson.Options`, +compatible with @aeson@'s generic instances by the same options, +defined as a `rule` named by its `Typeable` type, so that each +instantiation of a parametric type is its own (possibly recursive) +definition. +-} +jsonGeneric + :: forall a d f p + . ( 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 + (Just indexOf, Just table) + | Aeson.allNullaryToStringTag opts + , gconCount @f > 1 || Aeson.tagSingleConstructors opts -> + jsonEnumWith indexOf [(tag, GHC.to (GHC.M1 v)) | (tag, v) <- table] + _ -> dimap (GHC.unM1 . GHC.from) (GHC.to . GHC.M1) (gsum opts) +{-# INLINE jsonGeneric #-} + +-- | Whether a `GHC.Generic` representation's constructors are all nullary. +type AllNullary :: (Type -> Type) -> Bool +type family AllNullary f where + AllNullary (f GHC.:+: g) = AllNullary f && AllNullary g + AllNullary (GHC.C1 c GHC.U1) = 'True + AllNullary f = 'False + +{- | The index of an enumeration's constructor, by `Exts.dataToTag#`, +which only enumerations need, since newtypes have no `Exts.DataToTag`. +-} +class EnumTag (enum :: Bool) a where + enumIndex :: Maybe (a -> Int) +instance Exts.DataToTag a => EnumTag 'True a where + enumIndex = Just (\a -> Exts.I# (Exts.dataToTag# a)) +instance EnumTag 'False a where + enumIndex = Nothing + +gsum :: forall f p x. (GSum f, JsonVal p) => Aeson.Options -> p (f x) (f x) +gsum opts + | gconCount @f == 1, not (Aeson.tagSingleConstructors opts) = gcons opts + | Aeson.allNullaryToStringTag opts, Just names <- genum opts = names + | otherwise = case Aeson.sumEncoding opts of + Aeson.TaggedObject tagField contentsField -> + gtagged opts (Text.pack tagField) (Text.pack contentsField) + Aeson.UntaggedValue -> guntagged opts + Aeson.ObjectWithSingleField -> gsingleField opts + Aeson.TwoElemArray -> gtwoElements opts +{-# INLINE gsum #-} + +-- | An object, rejecting other properties by `Aeson.rejectUnknownFields`. +gobject + :: JsonVal p => Aeson.Options -> (forall q. JsonObj p q => q a b) -> p a b +gobject opts obj + | Aeson.rejectUnknownFields opts = jsonObjectStrict obj + | otherwise = jsonObject obj +{-# INLINE gobject #-} + +class GSum f where + gconCount :: Int + -- | The contents of a constructor, by itself. + gcons :: JsonVal p => Aeson.Options -> p (f x) (f x) + -- | Constructor names, when all constructors are nullary. + genum :: JsonVal p => Aeson.Options -> Maybe (p (f x) (f x)) + -- | Constructors, by their names, when all constructors are nullary. + gtable :: Aeson.Options -> Maybe [(Text, f x)] + -- | Constructors by `Aeson.TaggedObject`, with tag & contents fields. + gtagged :: JsonVal p => Aeson.Options -> Text -> Text -> p (f x) (f x) + -- | Constructors by `Aeson.UntaggedValue`. + guntagged :: JsonVal p => Aeson.Options -> p (f x) (f x) + -- | Constructors by `Aeson.ObjectWithSingleField`. + gsingleField :: JsonVal p => Aeson.Options -> p (f x) (f x) + -- | Constructors by `Aeson.TwoElemArray`. + gtwoElements :: JsonVal p => Aeson.Options -> p (f x) (f x) + +instance (GSum f, GSum g) => GSum (f GHC.:+: g) where + gconCount = gconCount @f + gconCount @g + gcons opts = sumIso >~ gcons opts >+< gcons opts + genum opts = + liftA2 (\l r -> sumIso >~ l >+< r) (genum @f opts) (genum @g opts) + gtable opts = liftA2 + (\l r -> map (fmap GHC.L1) l <> map (fmap GHC.R1) r) + (gtable @f opts) (gtable @g opts) + gtagged opts tagField contentsField = sumIso + >~ gtagged opts tagField contentsField + >+< gtagged opts tagField contentsField + guntagged opts = sumIso >~ guntagged opts >+< guntagged opts + gsingleField opts = sumIso >~ gsingleField opts >+< gsingleField opts + gtwoElements opts = sumIso >~ gtwoElements opts >+< gtwoElements opts + {-# INLINE gconCount #-} + {-# INLINE gcons #-} + {-# INLINE genum #-} + {-# INLINE gtable #-} + {-# INLINE gtagged #-} + {-# INLINE guntagged #-} + {-# INLINE gsingleField #-} + {-# INLINE gtwoElements #-} + +sumIso :: Iso' ((f GHC.:+: g) x) (Either (f x) (g x)) +sumIso = iso + (\case GHC.L1 a -> Left a; GHC.R1 b -> Right b) + (either GHC.L1 GHC.R1) + +instance (GHC.Constructor c, GFields f, GContents f, GNullary f) + => GSum (GHC.C1 c f) where + gconCount = 1 + gcons opts = GHC.M1 #. contents .# GHC.unM1 + where + contents + | gconIsRecord @c = case gfield of + Just field | Aeson.unwrapUnaryRecords opts -> field + _ -> gobject opts (gfields opts) + | otherwise = gcontents + genum opts = gnullary @f <&> \v -> + dimap (const ()) (const (GHC.M1 v)) (fromString (gconTag @c opts)) + gtable opts = + gnullary @f <&> \v -> [(Text.pack (gconTag @c opts), GHC.M1 v)] + gtagged opts tagField contentsField = + GHC.M1 #. gobject opts (tag >* contents) .# GHC.unM1 + where + tag :: (JsonVal p, JsonObj p q) => q () () + tag = tagField !: fromString (gconTag @c opts) + contents :: (JsonVal p, JsonObj p q) => q (f x) (f x) + contents + | gconIsRecord @c = gfields opts + | Just v <- gnullary @f = dimap (const ()) (const v) oneP + | otherwise = contentsField !: gcontents + guntagged opts = case gnullary @f of + Just v | not (gconIsRecord @c) -> + dimap (const ()) (const (GHC.M1 v)) (fromString (gconTag @c opts)) + _ -> gcons opts + gsingleField opts = + jsonTag (Text.pack (gconTag @c opts)) (gcons @(GHC.C1 c f) opts) + gtwoElements opts = dimap ((),) snd + (jsonPair (fromString (gconTag @c opts)) (gcons @(GHC.C1 c f) opts)) + {-# INLINE gconCount #-} + {-# INLINE gcons #-} + {-# INLINE genum #-} + {-# INLINE gtable #-} + {-# INLINE gtagged #-} + {-# INLINE guntagged #-} + {-# INLINE gsingleField #-} + {-# INLINE gtwoElements #-} + +-- | A constructor's tag, by `Aeson.constructorTagModifier`. +gconTag :: forall (c :: GHC.Meta). GHC.Constructor c => Aeson.Options -> String +gconTag opts = Aeson.constructorTagModifier opts (gconName @c) + +gconName :: forall (c :: GHC.Meta). GHC.Constructor c => String +gconName = GHC.conName (GHC.M1 GHC.U1 :: GHC.C1 c GHC.U1 ()) + +gconIsRecord :: forall (c :: GHC.Meta). GHC.Constructor c => Bool +gconIsRecord = GHC.conIsRecord (GHC.M1 GHC.U1 :: GHC.C1 c GHC.U1 ()) + +gselName :: forall (s :: GHC.Meta). GHC.Selector s => String +gselName = GHC.selName (GHC.M1 GHC.U1 :: GHC.S1 s GHC.U1 ()) + +class GFields f where + -- | A record's fields, by `Aeson.fieldLabelModifier`. + gfields :: (JsonVal p, JsonObj p q) => Aeson.Options -> q (f x) (f x) + -- | A record's field, when it's its only field. + gfield :: JsonVal p => Maybe (p (f x) (f x)) +instance (GHC.Selector s, Json a) => GFields (GHC.S1 s (GHC.K1 i a)) where + gfields opts = (GHC.M1 . GHC.K1) #. property .# GHC.unK1 . GHC.unM1 + where + key = Text.pack (Aeson.fieldLabelModifier opts (gselName @s)) + -- An omittable field, by `jsonOmitField`. + property :: (JsonVal p, JsonObj p q) => q a a + property = case jsonOmitField @a of + Just omitted + | Aeson.allowOmittedFields opts || Aeson.omitNothingFields opts -> + withPrism omitted $ \omit match -> + let + present a + | Aeson.omitNothingFields opts, Right () <- match a = + Nothing + | otherwise = Just a + in dimap present (fromMaybe (omit ())) (key ?: json) + _ -> key !: json + gfield = Just ((GHC.M1 . GHC.K1) #. json .# GHC.unK1 . GHC.unM1) + {-# INLINE gfields #-} + {-# INLINE gfield #-} +instance (GFields f, GFields g) => GFields (f GHC.:*: g) where + gfields opts = dimap2 (\(a GHC.:*: _) -> a) (\(_ GHC.:*: b) -> b) (GHC.:*:) + (gfields opts) (gfields opts) + gfield = Nothing + {-# INLINE gfields #-} + {-# INLINE gfield #-} +instance GFields GHC.U1 where + gfields _ = dimap (const ()) (const GHC.U1) oneP + gfield = Nothing + +class GElements f where + gelements :: (JsonVal p, JsonTup p q) => q (f x) (f x) + -- | A single field's grammar, or else `Nothing` for other products. + gelement :: Maybe (forall p. JsonVal p => p (f x) (f x)) +instance Json a => GElements (GHC.S1 s (GHC.K1 i a)) where + gelements = (GHC.M1 . GHC.K1) #. jsonElem json .# GHC.unK1 . GHC.unM1 + gelement = Just ((GHC.M1 . GHC.K1) #. json .# GHC.unK1 . GHC.unM1) + {-# INLINE gelements #-} + {-# INLINE gelement #-} +instance (GElements f, GElements g) => GElements (f GHC.:*: g) where + gelements = dimap2 + (\(a GHC.:*: _) -> a) (\(_ GHC.:*: b) -> b) (GHC.:*:) gelements gelements + gelement = Nothing + {-# INLINE gelements #-} + {-# INLINE gelement #-} +instance GElements GHC.U1 where + gelements = dimap (const ()) (const GHC.U1) oneP + gelement = Nothing + +-- | The `GHC.Generic` tuple of a single constructor's positional fields. +gtuple + :: (GHC.Generic a, GHC.Rep a ~ GHC.D1 d (GHC.C1 c f), GElements f, JsonVal p) + => p a a +gtuple = dimap (GHC.unM1 . GHC.unM1 . GHC.from) (GHC.to . GHC.M1 . GHC.M1) + (jsonTuple gelements) +{-# INLINE gtuple #-} + +class GContents f where + gcontents :: JsonVal p => p (f x) (f x) +instance Json a => GContents (GHC.S1 s (GHC.K1 i a)) where + gcontents = (GHC.M1 . GHC.K1) #. json .# GHC.unK1 . GHC.unM1 + {-# INLINE gcontents #-} +-- | Two fields are a `jsonPair`, & others a `jsonTuple`. +instance (GElements f, GElements g) => GContents (f GHC.:*: g) where + gcontents :: forall p x. JsonVal p => p ((f GHC.:*: g) x) ((f GHC.:*: g) x) + gcontents = case gelement @f @x of + Just a -> case gelement @g @x of + Just b -> dimap + (\(x GHC.:*: y) -> (x, y)) (uncurry (GHC.:*:)) (jsonPair a b) + Nothing -> jsonTuple gelements + Nothing -> jsonTuple gelements + {-# INLINE gcontents #-} +instance GContents GHC.U1 where + gcontents = jsonTuple gelements + +class GNullary f where + gnullary :: Maybe (f x) +instance GNullary GHC.U1 where + gnullary = Just GHC.U1 +instance GNullary (GHC.S1 s f) where + gnullary = Nothing + {-# INLINE gnullary #-} +instance GNullary (f GHC.:*: g) where + gnullary = Nothing + {-# INLINE gnullary #-} diff --git a/distributors-json/src/Control/Lens/Grammar/TypeScript.hs b/distributors-json/src/Control/Lens/Grammar/TypeScript.hs new file mode 100644 index 00000000..f81edb19 --- /dev/null +++ b/distributors-json/src/Control/Lens/Grammar/TypeScript.hs @@ -0,0 +1,1465 @@ +{-# LANGUAGE OverloadedStrings #-} + +{- | +Module : Control.Lens.Grammar.TypeScript +Description : TypeScript declaration files, as a grammar +Copyright : (C) 2026 - Eitan Chatav +License : BSD-style (see the file LICENSE) +Maintainer : Eitan Chatav +Stability : provisional +Portability : non-portable + +TypeScript's declaration files, @.d.ts@, like the TypeScript compiler, +in two layers: `tsTokensGrammar` of their tokens, by their +`TsTokenCategory`s, & `tsGrammar` of their declarations, of those tokens, +by the compiler's names of their nodes, so that they parse & print +together. + +Both layers parse by `parsecG` & print by `unparsecG`, locating failures, +since `tsTokensGrammar` scans tokens without their trivia, as the compiler +does. `tsGrammar` isn't @LL(1)@: it backtracks, by `try`, where TypeScript's +syntax needs more lookahead. Here, a declaration prints as tokens, +& as characters, & parses back. + +>>> :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)) +>>> putStr source +export type Point = { x: number }; +>>> parsecResult (parsecG tsGrammar (concat (parsecResult (parsecG tsTokensGrammar source)))) == Just [TypeAliasDeclaration [ExportKeyword] "Point" [] point] +True +-} + +module Control.Lens.Grammar.TypeScript + ( -- * Grammar + tsGrammar + , tsTokenGrammar + , tsTokensGrammar + -- * Declarations + , TsDeclaration (..) + , TsModuleName (..) + , TsImportClause (..) + , TsNamedBindings (..) + , TsImportSpecifier (..) + , TsModuleReference (..) + , TsExportClause (..) + , TsVariableDeclaration (..) + , TsEnumMember (..) + , TsHeritage (..) + , TsEntityName + -- * Types + , TsType (..) + , TsProperty (..) + , TsPropertyName (..) + , TsLiteral (..) + , TsTypeParameter (..) + , TsSignature (..) + , TsParameter (..) + , TsBindingName (..) + , TsBindingElement (..) + -- * Tokens + , TsToken (..) + , TsTokenCategory (..) + ) where + +import Control.Lens +import Control.Lens.Grammar +import Data.Char (chr, ord) +import Data.Maybe (fromMaybe, listToMaybe) +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 + +-- Declarations -- + +{- | A declaration of a declaration file, by the TypeScript compiler's +name of its node, most with its modifiers, like @export@ & @declare@. +-} +data TsDeclaration + = TypeAliasDeclaration [TsTokenCategory] Text [TsTypeParameter] TsType + -- ^ @type T\ = V;@ + | InterfaceDeclaration + [TsTokenCategory] Text [TsTypeParameter] [TsHeritage] [TsProperty] + -- ^ @interface I\ extends J { … }@ + | ClassDeclaration + [TsTokenCategory] Text [TsTypeParameter] + (Maybe TsHeritage) [TsHeritage] [TsProperty] + -- ^ @class C\ extends D implements I { … }@ + | FunctionDeclaration [TsTokenCategory] Text TsSignature + -- ^ @function f\(x: T): U;@ + | VariableStatement + [TsTokenCategory] TsTokenCategory [TsVariableDeclaration] + -- ^ @const x: T;@, by @var@, @let@ or @const@ + | EnumDeclaration [TsTokenCategory] Text [TsEnumMember] + -- ^ @enum E { A, B = 1 }@ + | ModuleDeclaration [TsTokenCategory] TsModuleName (Maybe [TsDeclaration]) + -- ^ @namespace N { … }@, @module "m" { … }@ or @global { … }@ + | ImportDeclaration Bool (Maybe TsImportClause) Text + -- ^ @import type { A } from "m";@, of types only or not + | ImportEqualsDeclaration [TsTokenCategory] Bool Text TsModuleReference + -- ^ @import x = require("m");@, of types only or not + | ExportDeclaration Bool TsExportClause (Maybe Text) + -- ^ @export type { A } from "m";@, of types only or not + | ExportAssignment Bool TsEntityName + -- ^ @export = x;@, or else @export default x;@ + | NamespaceExportDeclaration Text + -- ^ @export as namespace N;@ + deriving stock (Eq, Ord, Show, Read) + +-- | The name of a `ModuleDeclaration`. +data TsModuleName + = NamespaceName TsEntityName -- ^ @namespace N.M@ + | ModuleName TsEntityName -- ^ @module N.M@ + | ExternalModuleName Text -- ^ @module "m"@ + | GlobalAugmentation -- ^ @global@ + deriving stock (Eq, Ord, Show, Read) + +-- | The imports of an `ImportDeclaration`, by default & by name. +data TsImportClause = TsImportClause (Maybe Text) (Maybe TsNamedBindings) + deriving stock (Eq, Ord, Show, Read) + +-- | Imports by name. +data TsNamedBindings + = NamespaceImport Text -- ^ @* as n@ + | NamedImports [TsImportSpecifier] -- ^ @{ a, b as c }@ + deriving stock (Eq, Ord, Show, Read) + +-- | @type a as b@, an import or export, of a type or not, renamed or not. +data TsImportSpecifier = TsImportSpecifier Bool (Maybe Text) Text + deriving stock (Eq, Ord, Show, Read) + +-- | What an `ImportEqualsDeclaration` imports. +data TsModuleReference + = ExternalModuleReference Text -- ^ @require("m")@ + | EntityModuleReference TsEntityName -- ^ @N.M@ + deriving stock (Eq, Ord, Show, Read) + +-- | What an `ExportDeclaration` exports. +data TsExportClause + = NamespaceExport (Maybe Text) -- ^ @*@, or @* as n@ + | NamedExports [TsImportSpecifier] -- ^ @{ a, b as c }@ + deriving stock (Eq, Ord, Show, Read) + +-- | @x: T = 1@, a variable, of a type or not, & a literal value or not. +data TsVariableDeclaration = + TsVariableDeclaration Text (Maybe TsType) (Maybe TsLiteral) + deriving stock (Eq, Ord, Show, Read) + +-- | @A = 1@, a member of an `EnumDeclaration`, of a literal value or not. +data TsEnumMember = TsEnumMember TsPropertyName (Maybe TsLiteral) + deriving stock (Eq, Ord, Show, Read) + +-- | @N.M\@, a class or interface which a declaration extends. +data TsHeritage = TsHeritage TsEntityName [TsType] + deriving stock (Eq, Ord, Show, Read) + +-- | A qualified name, @N.M.x@, by its identifiers. +type TsEntityName = [Text] + +-- Types -- + +-- | A type, by the TypeScript compiler's name of its node. +data TsType + = KeywordType TsTokenCategory -- ^ @number@, @string@, @never@, … + | ThisType -- ^ @this@ + | LiteralType TsLiteral -- ^ @null@, @true@, @1@ or @"abc"@ + | ReferenceType TsEntityName [TsType] -- ^ @T@ or @N.T\@ + | ArrayType TsType -- ^ @T[]@ + | TupleType [TsType] -- ^ @[T, U]@ + | OptionalType TsType -- ^ @T?@, an element of a tuple + | RestType TsType -- ^ @...T@, an element of a tuple + | NamedTupleMember Bool Text Bool TsType + -- ^ @...x?: T@, an element of a tuple, rest or not, optional or not + | UnionType [TsType] -- ^ @T | U@ + | IntersectionType [TsType] -- ^ @T & U@ + | ParenthesizedType TsType -- ^ @(T)@ + | FunctionType TsSignature -- ^ @\(x: T) => U@ + | ConstructorType Bool TsSignature + -- ^ @abstract new \(x: T) => U@, abstract or not + | TypeOperator TsTokenCategory TsType + -- ^ @keyof T@, @readonly T@ or @unique T@ + | IndexedAccessType TsType TsType -- ^ @T[K]@ + | TypeQuery TsEntityName [TsType] -- ^ @typeof x\@ + | ImportType Bool Text TsEntityName [TsType] + -- ^ @typeof import("m").N.T\@, a @typeof@ or not + | InferType Text (Maybe TsType) -- ^ @infer T extends U@ + | TypePredicate Bool Text (Maybe TsType) + -- ^ @asserts x is T@ or @this is T@, a return type, asserting or not + | ObjectType [TsProperty] -- ^ @{ x: T; y?: U }@ + | MappedType + (Maybe TsTokenCategory) Text TsType (Maybe TsType) + (Maybe TsTokenCategory) TsType + {- ^ @{ -readonly [K in T as U]+?: V }@, by its @readonly@ modifier, + @readonly@, @+@ or @-@, its type parameter & its constraint & name type, + & its @?@ modifier, @?@, @+@ or @-@ -} + | ConditionalType TsType TsType TsType TsType + -- ^ @T extends U ? V : W@ + | TemplateLiteralType Text [(TsType, Text)] + -- ^ @\`a${T}b\`@, by its head & its spans' types & literals + deriving stock (Eq, Ord, Show, Read) + +{- | A member of an `ObjectType`, `InterfaceDeclaration` or +`ClassDeclaration`, by the TypeScript compiler's name of its node, +with its modifiers, like @readonly@ & @static@. +-} +data TsProperty + = PropertySignature [TsTokenCategory] TsPropertyName Bool (Maybe TsType) + -- ^ @x?: T@, optional or not, of a type or not + | MethodSignature [TsTokenCategory] TsPropertyName Bool TsSignature + -- ^ @f?\(x: T): U@, optional or not + | CallSignature TsSignature -- ^ @\(x: T): U@ + | ConstructSignature TsSignature -- ^ @new \(x: T): U@ + | IndexSignature [TsTokenCategory] Text TsType TsType -- ^ @[k: K]: T@ + | GetAccessor [TsTokenCategory] TsPropertyName (Maybe TsType) + -- ^ @get x(): T@ + | SetAccessor [TsTokenCategory] TsPropertyName TsParameter + -- ^ @set x(v: T)@ + | Constructor [TsTokenCategory] [TsParameter] + -- ^ @constructor(x: T)@, of a class + deriving stock (Eq, Ord, Show, Read) + +-- | The name of a member. +data TsPropertyName + = PropertyIdentifier Text -- ^ @x@ + | PropertyString Text -- ^ @"x y"@ + | PropertyNumeric Text -- ^ @1@ + | PropertyPrivate Text -- ^ @#x@ + | ComputedPropertyName TsEntityName -- ^ @[Symbol.iterator]@ + deriving stock (Eq, Ord, Show, Read) + +-- | A literal, of a `LiteralType` or a value. +data TsLiteral + = NullLiteral -- ^ @null@ + | TrueLiteral -- ^ @true@ + | FalseLiteral -- ^ @false@ + | TextLiteral Text -- ^ @"abc"@ + | NumberLiteral Text -- ^ @1@ or @-1.5@, as it's written + | BigIntegerLiteral Text -- ^ @1n@ or @-1n@, as it's written + deriving stock (Eq, Ord, Show, Read) + +-- | @const T extends U = V@, a type parameter, with its modifiers. +data TsTypeParameter = + TsTypeParameter [TsTokenCategory] Text (Maybe TsType) (Maybe TsType) + deriving stock (Eq, Ord, Show, Read) + +-- | @\(x: T): U@, type parameters, parameters & a return type or not. +data TsSignature = + TsSignature [TsTypeParameter] [TsParameter] (Maybe TsType) + deriving stock (Eq, Ord, Show, Read) + +-- | @...x?: T@, a parameter, rest or not, optional or not. +data TsParameter = TsParameter Bool TsBindingName Bool (Maybe TsType) + deriving stock (Eq, Ord, Show, Read) + +-- | The name of a parameter, or a pattern of names. +data TsBindingName + = BindingIdentifier Text -- ^ @x@, or @this@ + | ObjectBindingPattern [TsBindingElement] -- ^ @{ a, b: c }@ + | ArrayBindingPattern [TsBindingElement] -- ^ @[a, ...b]@ + deriving stock (Eq, Ord, Show, Read) + +-- | @...a: b@, an element of a binding pattern, rest or not. +data TsBindingElement = + TsBindingElement Bool (Maybe TsPropertyName) TsBindingName + deriving stock (Eq, Ord, Show, Read) + +-- Tokens -- + +{- | A token, of a `TsTokenCategory` & its text, as the scanner of +the TypeScript compiler scans it, with its trivia: its text is +an identifier's name, a string's value, a number's spelling, +a template's literal, or a comment. +-} +data TsToken = TsToken + { tokenCategory :: TsTokenCategory + , tokenText :: Text + } deriving stock (Eq, Ord, Show, Read) + +instance Categorized TsToken where + type Categorize TsToken = TsTokenCategory + categorize = tokenCategory + +-- | The categories of t'TsToken's, by the TypeScript compiler's names. +data TsTokenCategory + = WhitespaceTrivia + | NewLineTrivia + | SingleLineCommentTrivia + | MultiLineCommentTrivia + | Identifier + | PrivateIdentifier + | StringLiteral + | NumericLiteral + | BigIntLiteral + | NoSubstitutionTemplateLiteral + | TemplateHead + | TemplateMiddle + | TemplateTail + | OpenBraceToken + | CloseBraceToken + | OpenParenToken + | CloseParenToken + | OpenBracketToken + | CloseBracketToken + | DotToken + | DotDotDotToken + | SemicolonToken + | CommaToken + | LessThanToken + | GreaterThanToken + | QuestionToken + | ColonToken + | EqualsToken + | EqualsGreaterThanToken + | BarToken + | AmpersandToken + | MinusToken + | PlusToken + | AsteriskToken + | ExclamationToken + | ClassKeyword + | ConstKeyword + | DefaultKeyword + | EnumKeyword + | ExportKeyword + | ExtendsKeyword + | FalseKeyword + | FunctionKeyword + | ImportKeyword + | InKeyword + | NewKeyword + | NullKeyword + | ThisKeyword + | TrueKeyword + | TypeOfKeyword + | VarKeyword + | VoidKeyword + | AbstractKeyword + | AccessorKeyword + | AnyKeyword + | AsKeyword + | AssertsKeyword + | BigIntKeyword + | BooleanKeyword + | ConstructorKeyword + | DeclareKeyword + | FromKeyword + | GetKeyword + | GlobalKeyword + | ImplementsKeyword + | InferKeyword + | InterfaceKeyword + | IntrinsicKeyword + | IsKeyword + | KeyOfKeyword + | LetKeyword + | ModuleKeyword + | NamespaceKeyword + | NeverKeyword + | NumberKeyword + | ObjectKeyword + | OutKeyword + | OverrideKeyword + | PrivateKeyword + | ProtectedKeyword + | PublicKeyword + | ReadonlyKeyword + | RequireKeyword + | SetKeyword + | StaticKeyword + | StringKeyword + | SymbolKeyword + | TypeKeyword + | UndefinedKeyword + | UniqueKeyword + | UnknownKeyword + deriving stock (Eq, Ord, Show, Read, Enum, Bounded) + +makeNestedPrisms ''TsDeclaration +makeNestedPrisms ''TsModuleName +makeNestedPrisms ''TsImportClause +makeNestedPrisms ''TsNamedBindings +makeNestedPrisms ''TsImportSpecifier +makeNestedPrisms ''TsModuleReference +makeNestedPrisms ''TsExportClause +makeNestedPrisms ''TsVariableDeclaration +makeNestedPrisms ''TsEnumMember +makeNestedPrisms ''TsHeritage +makeNestedPrisms ''TsType +makeNestedPrisms ''TsProperty +makeNestedPrisms ''TsPropertyName +makeNestedPrisms ''TsLiteral +makeNestedPrisms ''TsTypeParameter +makeNestedPrisms ''TsSignature +makeNestedPrisms ''TsParameter +makeNestedPrisms ''TsBindingName +makeNestedPrisms ''TsBindingElement + +punctuation :: [(TsTokenCategory, Text)] +punctuation = + [ (OpenBraceToken, "{"), (CloseBraceToken, "}") + , (OpenParenToken, "("), (CloseParenToken, ")") + , (OpenBracketToken, "["), (CloseBracketToken, "]") + , (DotToken, "."), (DotDotDotToken, "..."), (SemicolonToken, ";") + , (CommaToken, ","), (LessThanToken, "<"), (GreaterThanToken, ">") + , (QuestionToken, "?"), (ColonToken, ":"), (EqualsToken, "=") + , (EqualsGreaterThanToken, "=>"), (BarToken, "|"), (AmpersandToken, "&") + , (MinusToken, "-"), (PlusToken, "+"), (AsteriskToken, "*") + , (ExclamationToken, "!") + ] + +-- | Keywords which aren't identifiers. +reservedWords :: [(TsTokenCategory, Text)] +reservedWords = + [ (ClassKeyword, "class"), (ConstKeyword, "const") + , (DefaultKeyword, "default"), (EnumKeyword, "enum") + , (ExportKeyword, "export"), (ExtendsKeyword, "extends") + , (FalseKeyword, "false"), (FunctionKeyword, "function") + , (ImportKeyword, "import"), (InKeyword, "in"), (NewKeyword, "new") + , (NullKeyword, "null"), (ThisKeyword, "this"), (TrueKeyword, "true") + , (TypeOfKeyword, "typeof"), (VarKeyword, "var"), (VoidKeyword, "void") + ] + +-- | Keywords which are also identifiers, by their context. +contextualKeywords :: [(TsTokenCategory, Text)] +contextualKeywords = + [ (AbstractKeyword, "abstract"), (AccessorKeyword, "accessor") + , (AnyKeyword, "any"), (AsKeyword, "as"), (AssertsKeyword, "asserts") + , (BigIntKeyword, "bigint"), (BooleanKeyword, "boolean") + , (ConstructorKeyword, "constructor"), (DeclareKeyword, "declare") + , (FromKeyword, "from"), (GetKeyword, "get"), (GlobalKeyword, "global") + , (ImplementsKeyword, "implements"), (InferKeyword, "infer") + , (InterfaceKeyword, "interface"), (IntrinsicKeyword, "intrinsic") + , (IsKeyword, "is"), (KeyOfKeyword, "keyof"), (LetKeyword, "let") + , (ModuleKeyword, "module"), (NamespaceKeyword, "namespace") + , (NeverKeyword, "never"), (NumberKeyword, "number") + , (ObjectKeyword, "object"), (OutKeyword, "out") + , (OverrideKeyword, "override"), (PrivateKeyword, "private") + , (ProtectedKeyword, "protected"), (PublicKeyword, "public") + , (ReadonlyKeyword, "readonly"), (RequireKeyword, "require") + , (SetKeyword, "set"), (StaticKeyword, "static") + , (StringKeyword, "string"), (SymbolKeyword, "symbol") + , (TypeKeyword, "type"), (UndefinedKeyword, "undefined") + , (UniqueKeyword, "unique"), (UnknownKeyword, "unknown") + ] + +keywords :: [(TsTokenCategory, Text)] +keywords = reservedWords <> contextualKeywords + +-- | The token of a punctuation or keyword category. +symbol :: TsTokenCategory -> TsToken +symbol category = + TsToken category (fromMaybe "" (lookup category (punctuation <> keywords))) + +-- | One of some punctuation tokens, by its category. +symbolOf :: [TsTokenCategory] -> Prism' TsToken TsTokenCategory +symbolOf categories = prism' symbol $ \t -> + if tokenCategory t `elem` categories && t == symbol (tokenCategory t) + then Just (tokenCategory t) else Nothing + +{- | A token, scanned from its characters. Its trivia, whitespace, +newlines & comments, are tokens, as the scanner of the TypeScript compiler +scans without skipping them. A @}@ is never a template's middle or tail, +which `tsTokensGrammar` rescans in its context, as the compiler's parser +rescans it. + +A number is spelled by its digits, letters, separators & points, +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 = 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 + , kindOf PrivateIdentifier >? terminal "#" + >* (identifierStart >:< manyP identifierPart) + , _Number >? asIn @Char DecimalNumber >:< manyP numberPart + , kindOf StringLiteral >? orP + [ terminal "\"" >* manyP (stringChar '"') *< terminal "\"" + , terminal "'" >* manyP (stringChar '\'') *< terminal "'" + ] + , _Template >? terminal "`" >* manyP templateChar >*< orP + [ only NoSubstitutionTemplateLiteral >? terminal "`" + , only TemplateHead >? terminal "${" + ] + , symbolOf [DotToken, DotDotDotToken] >? terminal "." >* orP + [only DotDotDotToken >? terminal "..", only DotToken >? oneP] + , symbolOf [EqualsToken, EqualsGreaterThanToken] >? terminal "=" >* orP + [only EqualsGreaterThanToken >? terminal ">", only EqualsToken >? oneP] + , orP + [ only (TsToken category text) >? terminal (Text.unpack text) + | (category, text) <- punctuation + , category `notElem` + [DotToken, DotDotDotToken, EqualsToken, EqualsGreaterThanToken] + ] + ] + where + identifierPart = orP + [ identifierStart, asIn @Char DecimalNumber, asIn @Char NonSpacingMark + , asIn @Char SpacingCombiningMark, asIn @Char ConnectorPunctuation + ] + numberPart = orP + [ asIn @Char DecimalNumber, asIn @Char UppercaseLetter + , asIn @Char LowercaseLetter, oneOf @Char ("_." :: String) + ] + -- @\*[^*]*\*+([^*/][^*]*\*+)*\/@, after its first @/@. + blockComment = _BlockComment >? terminal "*" + >* manyP (notOneOf @Char ("*" :: String)) + >*< someP (token '*') + >*< manyP + ( notOneOf @Char ("*/" :: String) + >*< manyP (notOneOf @Char ("*" :: String)) + >*< someP (token '*') + ) + *< terminal "/" + +identifierStart :: RegGrammar Char Char +identifierStart = orP + [ asIn @Char UppercaseLetter, asIn @Char LowercaseLetter + , asIn @Char TitlecaseLetter, asIn @Char ModifierLetter + , asIn @Char OtherLetter, asIn @Char LetterNumber + , oneOf @Char ("_$" :: String) + ] + +stringChar :: Char -> RegGrammar Char Char +stringChar quote = orP + [ notOneOf @Char (quote : '\\' : ['\0' .. '\31']) + , terminal "\\" >* orP + [ oneOf @Char ("\"\\/'" :: String) + , 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)) + ] + ] + where + hexDigits = "0123456789abcdefABCDEF" :: String + +templateChar :: RegGrammar Char Char +templateChar = orP + [ notOneOf @Char ("`$\\" :: String) + , terminal "\\" >* oneOf @Char ("`$\\" :: String) + ] + +{- | Tokens, scanned from their characters without their trivia, +as the TypeScript compiler's scanner skips trivia, & printed with them, +as `tsGrammar` prints them, so that `tsGrammar` parses by `parsecG`. +A @}@ which closes a template's substitution is scanned as the template's +middle or tail, by the depth of braces within the substitutions open, +as the compiler's parser rescans it. + +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 = rmap + (\scanned -> [t | t <- scanned, tokenCategory t `notElem` trivial]) + (tokensWithin []) + where + trivial = + [ WhitespaceTrivia, NewLineTrivia + , SingleLineCommentTrivia, MultiLineCommentTrivia + ] + +{- | Tokens, within the substitutions of templates, by the depth of braces +within each, innermost first. +-} +tokensWithin + :: (Lexical Char p, Alternator p, Filtrator p, MonadicTry p) + => [Int] -> p [TsToken] [TsToken] +tokensWithin depths = orP + [ _Cons >? (tokenWithin P.>>= tokensWithin . within depths) + , _Empty >? oneP + ] + where + tokenWithin = case depths of + 0 : _ -> orP [templateContinuation, tsTokenGrammar] + _ -> tsTokenGrammar + templateContinuation = _Template >? terminal "}" + >* manyP templateChar >*< orP + [ only TemplateTail >? terminal "`" + , only TemplateMiddle >? terminal "${" + ] + within ds (TsToken category _) = case (category, ds) of + (TemplateHead, _) -> 0 : ds + (TemplateTail, _) -> drop 1 ds + (OpenBraceToken, d : others) -> d + 1 : others + (CloseBraceToken, d : others) -> d - 1 : others + _ -> ds + +-- | A token of a category, by its text. +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) + +-- | An identifier or keyword, by its text. +_Word :: Prism' TsToken String +_Word = prism' word $ \(TsToken category text) -> + if category == Identifier || category `elem` map fst keywords + then Just (Text.unpack text) else Nothing + where + word chars = case lookup text [(t, k) | (k, t) <- keywords] of + Just category -> TsToken category text + Nothing -> TsToken Identifier text + where + text = Text.pack chars + +-- | A number, or a big integer, which ends in @n@, by its spelling. +_Number :: Prism' TsToken String +_Number = prism' number $ \case + TsToken NumericLiteral text -> Just (Text.unpack text) + TsToken BigIntLiteral text -> Just (Text.unpack text) + _ -> Nothing + where + number chars + | not (null chars) && last chars == 'n' && '.' `notElem` chars = + TsToken BigIntLiteral (Text.pack chars) + | otherwise = TsToken NumericLiteral (Text.pack chars) + +{- | A comment, by its text after its first @/@, of a line, after @//@, +or of a block, from its @*@. +-} +_Comment :: Prism' TsToken (Either String String) +_Comment = prism' + (\case + Left line -> TsToken SingleLineCommentTrivia (Text.pack ("//" <> line)) + Right block' -> TsToken MultiLineCommentTrivia (Text.pack ('/' : block'))) + (\case + TsToken SingleLineCommentTrivia text -> + Left . Text.unpack <$> Text.stripPrefix "//" text + TsToken MultiLineCommentTrivia text -> + Right . Text.unpack <$> Text.stripPrefix "/" text + _ -> Nothing) + +{- | A block comment's text, from its @*@, by the parts of +@\*[^*]*\*+([^*/][^*]*\*+)*\/@. +-} +_BlockComment + :: Prism' String (String, (String, [(Char, (String, String))])) +_BlockComment = prism' build split + where + build (start, (stars, others)) = '*' : start <> stars + <> concat [c : text <> more | (c, (text, more)) <- others] <> "/" + split = \case + '*' : str | not (null str), last str == '/' -> body (init str) + _ -> Nothing + body str = + let + (start, rest) = break (== '*') str + (stars, others) = span (== '*') rest + in + if null stars then Nothing else (start,) . (stars,) <$> pieces others + pieces = \case + [] -> Just [] + c : str | c /= '*', c /= '/' -> + let + (text, rest) = break (== '*') str + (more, others) = span (== '*') rest + in + if null more then Nothing + else ((c, (text, more)) :) <$> pieces others + _ -> Nothing + +-- | A template's literal & its category. +_Template :: Prism' TsToken (String, TsTokenCategory) +_Template = prism' + (\(chars, category) -> TsToken category (Text.pack chars)) + (\(TsToken category text) -> + if category `elem` templates + then Just (Text.unpack text, category) else Nothing) + where + templates = + [NoSubstitutionTemplateLiteral, TemplateHead, TemplateMiddle, TemplateTail] + +-- | A character, by the hexadecimal digits of a @\\u@ escape. +_HexCode :: Prism' Char String +_HexCode = prism' + (\digits -> chr (maybe 0 fst (listToMaybe (readHex digits)))) + (\c -> if ord c < 0x10000 + then Just (pad (showHex (ord c) "")) else Nothing) + where + pad digits = replicate (4 - length digits) '0' <> digits + +-- Syntax -- + +-- | The interpreters of TypeScript's syntax. +type TsGrammatical p = + (Lexical TsToken p, Alternator p, Filtrator p, MonadicTry p) + +{- | The declarations of a declaration file, of tokens, by the TypeScript +compiler's syntax, printed one per line, indented within blocks, & with +object types on one line. Trivia print conventionally, & parse only +from tokens with trivia, by `parseG`, since `tsTokensGrammar` scans +without them. Its @;@s print, & parse if they're there. + +It's a `CtxGrammar` by `try`, rather than by monadic bonding, since it +isn't @LL(1)@: TypeScript's syntax needs more lookahead in places, +where it backtracks by `try`: declarations' & members' modifiers, imports' +forms & their @type@ & @as@, comma-separated lists after their first item, +members' signatures, constructors & accessors, a binding's name before +its @:@, type parameters' modifiers, @asserts@ & @is@ predicates, +function, conditional, @typeof import@, mapped & named tuple member types. + +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 = manyP (declaration 0 *< newline) + +-- | A declaration, at a depth of indentation. +declaration :: TsGrammatical p => Int -> p TsDeclaration TsDeclaration +declaration depth = rule "declaration" $ orP + [ _Modified >? try + ( orP + [ only category >? tokenOf oneP category space + | category <- + [ ExportKeyword, DeclareKeyword, DefaultKeyword + , AbstractKeyword, ConstKeyword + ] + ] + >*< declaration depth + ) + , _TypeAliasDeclaration . noModifiers >? tokenOf oneP TypeKeyword space + >* identifier >*< typeParameters + >*< tokenOf space EqualsToken space >* typeNode + *< semicolon + , _InterfaceDeclaration . noModifiers + >? tokenOf oneP InterfaceKeyword space + >* identifier >*< typeParameters + >*< heritageClause ExtendsKeyword + >*< block depth memberSeparator (const member) + , _ClassDeclaration . noModifiers >? tokenOf oneP ClassKeyword space + >* identifier >*< typeParameters + >*< optionalP (tokenOf space ExtendsKeyword space >* heritage) + >*< heritageClause ImplementsKeyword + >*< block depth memberSeparator (const member) + , _FunctionDeclaration . noModifiers + >? tokenOf oneP FunctionKeyword space + >* identifier >*< signature *< semicolon + , _VariableStatement . noModifiers >? orP + [ only category >? tokenOf oneP category space + | category <- [VarKeyword, LetKeyword, ConstKeyword] + ] + >*< commas1 variable *< semicolon + , _EnumDeclaration . noModifiers >? tokenOf oneP EnumKeyword space + >* identifier >*< block depth enumSeparator (const enumMember) + , _ModuleDeclaration . noModifiers >? orP + [ _NamespaceName >? tokenOf oneP NamespaceKeyword space >* entityName + , _ExternalModuleName >? try + (tokenOf oneP ModuleKeyword space >* textOf StringLiteral) + , _ModuleName >? tokenOf oneP ModuleKeyword space >* entityName + , _GlobalAugmentation >? tokenOf oneP GlobalKeyword oneP + ] + >*< orP + [ _Just >? block depth oneP declaration + , only Nothing >? semicolon + ] + , _ImportEqualsDeclaration . noModifiers >? try + ( tokenOf oneP ImportKeyword space >* typeOnly >*< identifier + >*< tokenOf space EqualsToken space >* orP + [ _ExternalModuleReference >? tokenOf oneP RequireKeyword oneP + >* tokenOf oneP OpenParenToken oneP >* textOf StringLiteral + *< tokenOf oneP CloseParenToken oneP + , _EntityModuleReference >? entityName + ] + *< semicolon + ) + , _BareImport >? try + (tokenOf oneP ImportKeyword space >* textOf StringLiteral) + *< semicolon + , _ClauseImport >? tokenOf oneP ImportKeyword space >* typeOnly + >*< importClause + >*< tokenOf space FromKeyword space >* textOf StringLiteral + *< semicolon + , _Exported >? tokenOf oneP ExportKeyword oneP >* orP + [ _ExportAssignment >? orP + [ only True >? tokenOf space EqualsToken space + , only False >? tokenOf space DefaultKeyword space + ] + >*< entityName *< semicolon + , _NamespaceExportDeclaration >? tokenOf space AsKeyword space + >* tokenOf oneP NamespaceKeyword space >* identifier *< semicolon + , _ExportDeclaration >? space >* typeOnly + >*< orP + [ _NamespaceExport >? tokenOf oneP AsteriskToken oneP + >* optionalP (tokenOf space AsKeyword space >* identifier) + , _NamedExports >? braced specifier + ] + >*< optionalP + (tokenOf space FromKeyword space >* textOf StringLiteral) + *< semicolon + ] + ] + where + memberSeparator = printed (orP + [tokenOf oneP SemicolonToken oneP, tokenOf oneP CommaToken oneP]) + enumSeparator = printed (tokenOf oneP CommaToken oneP) + enumMember = _TsEnumMember >? propertyName + >*< optionalP (tokenOf space EqualsToken space >* literal) + +-- | Declarations without modifiers, which `_Modified` adds. +noModifiers :: Prism' ([TsTokenCategory], a) a +noModifiers = prism' ([],) $ \case + ([], a) -> Just a + _ -> Nothing + +-- | A declaration, with a modifier. +_Modified :: Prism' TsDeclaration (TsTokenCategory, TsDeclaration) +_Modified = prism' (\(m, decl) -> over modifiers (m :) decl) $ \decl -> + case decl ^? modifiers of + Just (m : ms) -> Just (m, set modifiers ms decl) + _ -> Nothing + where + modifiers :: Traversal' TsDeclaration [TsTokenCategory] + modifiers f = \case + TypeAliasDeclaration ms n t v -> + (\ms' -> TypeAliasDeclaration ms' n t v) <$> f ms + InterfaceDeclaration ms n t h b -> + (\ms' -> InterfaceDeclaration ms' n t h b) <$> f ms + ClassDeclaration ms n t e i b -> + (\ms' -> ClassDeclaration ms' n t e i b) <$> f ms + FunctionDeclaration ms n s -> + (\ms' -> FunctionDeclaration ms' n s) <$> f ms + VariableStatement ms k vs -> + (\ms' -> VariableStatement ms' k vs) <$> f ms + EnumDeclaration ms n es -> (\ms' -> EnumDeclaration ms' n es) <$> f ms + ModuleDeclaration ms n b -> + (\ms' -> ModuleDeclaration ms' n b) <$> f ms + ImportEqualsDeclaration ms t n r -> + (\ms' -> ImportEqualsDeclaration ms' t n r) <$> f ms + decl -> pure decl + +-- | An import of a module, for its effects. +_BareImport :: Prism' TsDeclaration Text +_BareImport = prism' (ImportDeclaration False Nothing) $ \case + ImportDeclaration False Nothing name -> Just name + _ -> Nothing + +-- | An import, of types only or not, by its clause, from a module. +_ClauseImport :: Prism' TsDeclaration (Bool, (TsImportClause, Text)) +_ClauseImport = prism' + (\(types, (clause, name)) -> ImportDeclaration types (Just clause) name) + (\case + ImportDeclaration types (Just clause) name -> Just (types, (clause, name)) + _ -> Nothing) + +-- | An export's declaration, which isn't a modified declaration. +_Exported :: Prism' TsDeclaration TsDeclaration +_Exported = prism' id $ \case + decl@(ExportAssignment {}) -> Just decl + decl@(NamespaceExportDeclaration _) -> Just decl + decl@(ExportDeclaration {}) -> Just decl + _ -> Nothing + +-- | Whether an import or export is of types only. +typeOnly :: TsGrammatical p => p Bool Bool +typeOnly = orP + [ only True >? try (tokenOf oneP TypeKeyword space) + , only False >? oneP + ] + +importClause :: TsGrammatical p => p TsImportClause TsImportClause +importClause = _TsImportClause >? orP + [ (_Just >? identifier) >*< orP + [ _Just >? tokenOf oneP CommaToken space >* namedBindings + , only Nothing >? oneP + ] + , (only Nothing >? oneP) >*< (_Just >? namedBindings) + ] + where + namedBindings = orP + [ _NamespaceImport >? tokenOf oneP AsteriskToken space + >* tokenOf oneP AsKeyword space >* identifier + , _NamedImports >? braced specifier + ] + +specifier :: TsGrammatical p => p TsImportSpecifier TsImportSpecifier +specifier = _TsImportSpecifier >? typeOnly + >*< orP + [ _Just >? try (identifierName *< tokenOf space AsKeyword space) + , only Nothing >? oneP + ] + >*< identifierName + +-- | A brace of comma separated items, on a line. +braced :: TsGrammatical p => p a a -> p [a] [a] +braced item = tokenOf oneP OpenBraceToken oneP >* orP + [ _Empty >? tokenOf oneP CloseBraceToken oneP + , space >* commas1 item + *< tokenOf space CloseBraceToken oneP + ] + +variable :: TsGrammatical p => p TsVariableDeclaration TsVariableDeclaration +variable = _TsVariableDeclaration >? identifier + >*< optionalP (tokenOf oneP ColonToken space >* typeNode) + >*< optionalP (tokenOf space EqualsToken space >* literal) + +-- | @extends@ or @implements@ & its heritage, or nothing for none. +heritageClause :: TsGrammatical p => TsTokenCategory -> p [TsHeritage] [TsHeritage] +heritageClause keyword = orP + [ _Cons >? tokenOf space keyword space >* heritage + >*< manyP (try (comma >* heritage)) + , _Empty >? oneP + ] + +heritage :: TsGrammatical p => p TsHeritage TsHeritage +heritage = _TsHeritage >? entityName >*< typeArguments + +{- | A block of items, each on its line, indented & separated, or @{}@. +-} +block + :: TsGrammatical p + => Int -> p () () -> (Int -> p a a) -> p [a] [a] +block depth separator item = space >* tokenOf oneP OpenBraceToken oneP >* orP + [ _Empty >? tokenOf oneP CloseBraceToken oneP + , someP (indented (depth + 1) >* item (depth + 1) *< separator) + *< indented depth *< tokenOf oneP CloseBraceToken oneP + ] + +-- | A member of an object type, interface or class. +member :: TsGrammatical p => p TsProperty TsProperty +member = ruleRec "member" $ \self -> orP + [ _ModifiedMember >? try + ( orP + [ only category >? tokenOf oneP category space + | category <- + [ PublicKeyword, PrivateKeyword, ProtectedKeyword, StaticKeyword + , ReadonlyKeyword, AbstractKeyword, OverrideKeyword + , DeclareKeyword, AccessorKeyword + ] + ] + >*< self + ) + , _CallSignature >? signature + , _ConstructSignature >? try (tokenOf oneP NewKeyword space >* signature) + , _IndexSignature . noModifiers >? try + ( tokenOf oneP OpenBracketToken oneP >* identifier + *< tokenOf oneP ColonToken space + ) + >*< typeNode *< tokenOf oneP CloseBracketToken oneP + >*< tokenOf oneP ColonToken space >* typeNode + , _Constructor . noModifiers >? try + (tokenOf oneP ConstructorKeyword oneP >* parameters) + , _GetAccessor . noModifiers >? try + (tokenOf oneP GetKeyword space >* propertyName) + >*< tokenOf oneP OpenParenToken oneP + >* tokenOf oneP CloseParenToken oneP + >* optionalP (tokenOf oneP ColonToken space >* typeNode) + , _SetAccessor . noModifiers >? try + (tokenOf oneP SetKeyword space >* propertyName) + >*< tokenOf oneP OpenParenToken oneP >* parameter + *< tokenOf oneP CloseParenToken oneP + , _Named >? propertyName >*< question >*< + ( signature + >+< optionalP (tokenOf oneP ColonToken space >* typeNode) + ) + ] + +-- | A member, with a modifier. +_ModifiedMember :: Prism' TsProperty (TsTokenCategory, TsProperty) +_ModifiedMember = prism' (\(m, prop) -> over modifiers (m :) prop) $ \prop -> + case prop ^? modifiers of + Just (m : ms) -> Just (m, set modifiers ms prop) + _ -> Nothing + where + modifiers :: Traversal' TsProperty [TsTokenCategory] + modifiers f = \case + PropertySignature ms n o t -> + (\ms' -> PropertySignature ms' n o t) <$> f ms + MethodSignature ms n o s -> + (\ms' -> MethodSignature ms' n o s) <$> f ms + IndexSignature ms n k t -> (\ms' -> IndexSignature ms' n k t) <$> f ms + GetAccessor ms n t -> (\ms' -> GetAccessor ms' n t) <$> f ms + SetAccessor ms n p -> (\ms' -> SetAccessor ms' n p) <$> f ms + Constructor ms ps -> (\ms' -> Constructor ms' ps) <$> f ms + prop -> pure prop + +{- | A method or property without modifiers, by its name, whether it's +optional, & its signature or type. +-} +_Named + :: Prism' TsProperty + (TsPropertyName, (Bool, Either TsSignature (Maybe TsType))) +_Named = prism' + (\case + (name, (optional, Left sig)) -> MethodSignature [] name optional sig + (name, (optional, Right t)) -> PropertySignature [] name optional t) + (\case + MethodSignature [] name optional sig -> Just (name, (optional, Left sig)) + PropertySignature [] name optional t -> Just (name, (optional, Right t)) + _ -> Nothing) + +propertyName :: TsGrammatical p => p TsPropertyName TsPropertyName +propertyName = orP + [ _PropertyIdentifier >? identifierName + , _PropertyString >? textOf StringLiteral + , _PropertyNumeric >? textOf NumericLiteral + , _PropertyPrivate >? textOf PrivateIdentifier + , _ComputedPropertyName >? tokenOf oneP OpenBracketToken oneP + >* entityName *< tokenOf oneP CloseBracketToken oneP + ] + +-- | @\(x: T): U@, with a return type or not. +signature :: TsGrammatical p => p TsSignature TsSignature +signature = _TsSignature >? typeParameters >*< parameters + >*< optionalP (tokenOf oneP ColonToken space >* returnType) + +parameters :: TsGrammatical p => p [TsParameter] [TsParameter] +parameters = tokenOf oneP OpenParenToken oneP + >* commas parameter + *< tokenOf oneP CloseParenToken oneP + +parameter :: TsGrammatical p => p TsParameter TsParameter +parameter = _TsParameter >? dots >*< bindingName >*< question + >*< optionalP (tokenOf oneP ColonToken space >* typeNode) + +bindingName :: TsGrammatical p => p TsBindingName TsBindingName +bindingName = ruleRec "binding" $ \self -> orP + [ _BindingIdentifier >? orP + [identifier, only "this" >? tokenOf oneP ThisKeyword oneP] + , _ObjectBindingPattern >? braced (bindingElement self) + , _ArrayBindingPattern >? tokenOf oneP OpenBracketToken oneP + >* commas (bindingElement self) *< tokenOf oneP CloseBracketToken oneP + ] + +-- | An element of a binding pattern, by a binding name. +bindingElement + :: TsGrammatical p + => p TsBindingName TsBindingName -> p TsBindingElement TsBindingElement +bindingElement name = _TsBindingElement >? dots + >*< orP + [ _Just >? try (propertyName *< tokenOf oneP ColonToken space) + , only Nothing >? oneP + ] + >*< name + +typeParameters :: TsGrammatical p => p [TsTypeParameter] [TsTypeParameter] +typeParameters = angled typeParameter + +typeParameter :: TsGrammatical p => p TsTypeParameter TsTypeParameter +typeParameter = ruleRec "type parameter" $ \self -> orP + [ _ModifiedParameter >? try + ( orP + [ only category >? tokenOf oneP category space + | category <- [ConstKeyword, InKeyword, OutKeyword] + ] + >*< self + ) + , _TsTypeParameter . noModifiers >? identifier + >*< optionalP (tokenOf space ExtendsKeyword space >* typeNode) + >*< optionalP (tokenOf space EqualsToken space >* typeNode) + ] + +-- | A type parameter, with a modifier. +_ModifiedParameter + :: Prism' TsTypeParameter (TsTokenCategory, TsTypeParameter) +_ModifiedParameter = prism' + (\(m, TsTypeParameter ms n c d) -> TsTypeParameter (m : ms) n c d) + (\case + TsTypeParameter (m : ms) n c d -> Just (m, TsTypeParameter ms n c d) + _ -> Nothing) + +-- | Type arguments, @\@, or none. +typeArguments :: TsGrammatical p => p [TsType] [TsType] +typeArguments = angled typeNode + +-- | @\@, or nothing for none. +angled :: TsGrammatical p => p a a -> p [a] [a] +angled item = orP + [ _Cons >? tokenOf oneP LessThanToken oneP >* item + >*< manyP (try (comma >* item)) + *< optionalToken CommaToken + *< tokenOf oneP GreaterThanToken oneP + , _Empty >? oneP + ] + +-- | A return type, which may be a type predicate. +returnType :: TsGrammatical p => p TsType TsType +returnType = orP + [ _AssertsPredicate >? try (tokenOf oneP AssertsKeyword space >* name) + >*< optionalP (tokenOf space IsKeyword space >* typeNode) + , _IsPredicate >? try (name *< tokenOf space IsKeyword space) + >*< typeNode + , typeNode + ] + where + name = orP [identifier, only "this" >? tokenOf oneP ThisKeyword oneP] + +-- | An asserting type predicate. +_AssertsPredicate :: Prism' TsType (Text, Maybe TsType) +_AssertsPredicate = prism' (uncurry (TypePredicate True)) $ \case + TypePredicate True name t -> Just (name, t) + _ -> Nothing + +-- | A type predicate, which isn't asserting. +_IsPredicate :: Prism' TsType (Text, TsType) +_IsPredicate = prism' + (\(name, t) -> TypePredicate False name (Just t)) + (\case + TypePredicate False name (Just t) -> Just (name, t) + _ -> Nothing) + +-- | A type. +typeNode :: TsGrammatical p => p TsType TsType +typeNode = ruleRec "type" $ \ty -> orP + [ _FunctionType . _Arrow >? try functionSignature + , _ConstructorType . aside _Arrow >? constructorSignature + , _Conditional >~ unionType ty >*< optionalP + ( tokenOf space ExtendsKeyword space >* orP + [ _FunctionType . _Arrow >? try functionSignature + , _ConstructorType . aside _Arrow >? constructorSignature + , unionType ty + ] + >*< tokenOf space QuestionToken space >* ty + >*< tokenOf space ColonToken space >* ty + ) + ] + where + functionSignature = typeParameters >*< parameters + >*< tokenOf space EqualsGreaterThanToken space >* returnType + constructorSignature = orP + [ only True >? tokenOf oneP AbstractKeyword space + , only False >? oneP + ] + >*< tokenOf oneP NewKeyword space >* functionSignature + +-- | A signature, with a return type. +_Arrow :: Prism' TsSignature ([TsTypeParameter], ([TsParameter], TsType)) +_Arrow = prism' + (\(tps, (ps, r)) -> TsSignature tps ps (Just r)) + (\case + TsSignature tps ps (Just r) -> Just (tps, (ps, r)) + _ -> Nothing) + +unionType :: TsGrammatical p => p TsType TsType -> p TsType TsType +unionType ty = rule "union" $ _Several _UnionType + >~ leading BarToken >* intersectionType ty >*< manyP + (tokenOf space BarToken space >* intersectionType ty) + +intersectionType :: TsGrammatical p => p TsType TsType -> p TsType TsType +intersectionType ty = rule "intersection" $ _Several _IntersectionType + >~ leading AmpersandToken >* operatorType ty >*< manyP + (tokenOf space AmpersandToken space >* operatorType ty) + +-- | A leading operator, which is parsed but not printed. +leading :: TsGrammatical p => TsTokenCategory -> p () () +leading category = dimap (const Nothing) (const ()) + (optionalP (tokenOf oneP category space)) + +operatorType :: TsGrammatical p => p TsType TsType -> p TsType TsType +operatorType ty = ruleRec "operator" $ \self -> orP + [ _TypeOperator >? orP + [ only category >? tokenOf oneP category space + | category <- [KeyOfKeyword, UniqueKeyword, ReadonlyKeyword] + ] + >*< self + , _InferType >? tokenOf oneP InferKeyword space >* identifier + >*< optionalP + (try (tokenOf space ExtendsKeyword space >* unionType ty)) + , postfixType ty + ] + +postfixType :: TsGrammatical p => p TsType TsType -> p TsType TsType +postfixType ty = rule "postfix" $ _Postfix + >~ primaryType ty >*< manyP + ( tokenOf oneP OpenBracketToken oneP >* orP + [ only Nothing >? tokenOf oneP CloseBracketToken oneP + , _Just >? ty *< tokenOf oneP CloseBracketToken oneP + ] + ) + +-- | A type of any arrays & indexed accesses of a type. +_Postfix :: Iso' TsType (TsType, [Maybe TsType]) +_Postfix = iso postfixes (uncurry (foldl postfix)) + where + postfixes = \case + ArrayType node -> (<> [Nothing]) <$> postfixes node + IndexedAccessType node key -> (<> [Just key]) <$> postfixes node + node -> (node, []) + postfix node = \case + Nothing -> ArrayType node + Just key -> IndexedAccessType node key + +primaryType :: TsGrammatical p => p TsType TsType -> p TsType TsType +primaryType ty = rule "primary" $ orP + [ _KeywordType >? orP + [ only category >? tokenOf oneP category oneP + | category <- + [ AnyKeyword, BigIntKeyword, BooleanKeyword, IntrinsicKeyword + , NeverKeyword, NumberKeyword, ObjectKeyword, StringKeyword + , SymbolKeyword, UndefinedKeyword, UnknownKeyword, VoidKeyword + ] + ] + , only ThisType >? tokenOf oneP ThisKeyword oneP + , _LiteralType >? literal + , _NoSubstitution >? textOf NoSubstitutionTemplateLiteral + , _TemplateLiteralType >? textOf TemplateHead >*< templateSpans + , _TypeOfImport >? try + (tokenOf oneP TypeOfKeyword space >* importType) + , _TypeImport >? importType + , _TypeQuery >? tokenOf oneP TypeOfKeyword space >* entityName + >*< typeArguments + , _ReferenceType >? entityName >*< typeArguments + , _TupleType >? tokenOf oneP OpenBracketToken oneP >* orP + [ _Empty >? tokenOf oneP CloseBracketToken oneP + , commas1 tupleElement + *< tokenOf oneP CloseBracketToken oneP + ] + , _ParenthesizedType >? tokenOf oneP OpenParenToken oneP + >* ty *< tokenOf oneP CloseParenToken oneP + , _Braced >? tokenOf oneP OpenBraceToken oneP >* orP + [ only (ObjectType []) >? tokenOf oneP CloseBraceToken oneP + , _MappedType >? try mappedType + , _ObjectType >? space >* (_Cons >? member >*< moreMembers) + ] + ] + where + importType = tokenOf oneP ImportKeyword oneP + >* tokenOf oneP OpenParenToken oneP >* textOf StringLiteral + *< tokenOf oneP CloseParenToken oneP + >*< manyP (tokenOf oneP DotToken oneP >* identifierName) + >*< typeArguments + templateSpans = ruleRec "spans" $ \rest -> _Spans >? ty + >*< (textOf TemplateMiddle >*< rest >+< textOf TemplateTail) + tupleElement = rule "element" $ orP + [ _NamedTupleMember . iso (\(r, (n, (o, t))) -> ((r, (n, o)), t)) (\((r, (n, o)), t) -> (r, (n, (o, t)))) >? try + (dots >*< identifier >*< question *< tokenOf oneP ColonToken space) + >*< ty + , _RestType >? tokenOf oneP DotDotDotToken oneP >* ty + , _Optional >~ ty >*< question + ] + mappedType = space >* orP + [ only (Just PlusToken) >? tokenOf oneP PlusToken oneP + >* tokenOf oneP ReadonlyKeyword space + , only (Just MinusToken) >? tokenOf oneP MinusToken oneP + >* tokenOf oneP ReadonlyKeyword space + , only (Just ReadonlyKeyword) >? tokenOf oneP ReadonlyKeyword space + , only Nothing >? oneP + ] + >*< tokenOf oneP OpenBracketToken oneP >* identifier + >*< tokenOf space InKeyword space >* ty + >*< optionalP (tokenOf space AsKeyword space >* ty) + >*< tokenOf oneP CloseBracketToken oneP >* orP + [ only (Just PlusToken) >? tokenOf oneP PlusToken oneP + >* tokenOf oneP QuestionToken oneP + , only (Just MinusToken) >? tokenOf oneP MinusToken oneP + >* tokenOf oneP QuestionToken oneP + , only (Just QuestionToken) >? tokenOf oneP QuestionToken oneP + , only Nothing >? oneP + ] + >*< tokenOf oneP ColonToken space >* ty + *< optionalToken SemicolonToken + *< tokenOf space CloseBraceToken oneP + -- The members after an object type's first, on its line, separated + -- by @;@ or @,@, or by nothing, & its closing brace. + moreMembers = ruleRec "members" $ \rest -> orP + [ _Empty >? tokenOf space CloseBraceToken oneP + , orP + [ tokenOf oneP SemicolonToken oneP + , tokenOf oneP CommaToken oneP + ] + >* orP + [ _Empty >? tokenOf space CloseBraceToken oneP + , _Cons >? space >* member >*< rest + ] + , _Cons >? space >* member >*< rest + ] + +-- | An import type, without its @typeof@. +_TypeImport :: Prism' TsType (Text, (TsEntityName, [TsType])) +_TypeImport = prism' + (\(name, (qualifier, args)) -> ImportType False name qualifier args) + (\case + ImportType False name qualifier args -> Just (name, (qualifier, args)) + _ -> Nothing) + +-- | An import type, with its @typeof@. +_TypeOfImport :: Prism' TsType (Text, (TsEntityName, [TsType])) +_TypeOfImport = prism' + (\(name, (qualifier, args)) -> ImportType True name qualifier args) + (\case + ImportType True name qualifier args -> Just (name, (qualifier, args)) + _ -> Nothing) + +-- | A literal. +literal :: TsGrammatical p => p TsLiteral TsLiteral +literal = orP + [ only NullLiteral >? tokenOf oneP NullKeyword oneP + , only TrueLiteral >? tokenOf oneP TrueKeyword oneP + , only FalseLiteral >? tokenOf oneP FalseKeyword oneP + , _TextLiteral >? textOf StringLiteral + , _NumberLiteral >? signed NumericLiteral + , _BigIntegerLiteral >? signed BigIntLiteral + ] + where + signed category = orP + [ _Negative >? tokenOf oneP MinusToken oneP >* textOf category + , textOf category + ] + +-- | A negative number, by its spelling without its sign. +_Negative :: Prism' Text Text +_Negative = prism' ("-" <>) (Text.stripPrefix "-") + +-- | A qualified name. +entityName :: TsGrammatical p => p TsEntityName TsEntityName +entityName = + identifier >:< manyP (tokenOf oneP DotToken oneP >* identifierName) + +-- | Comma separated items. +commas :: TsGrammatical p => p a a -> p [a] [a] +commas item = orP [commas1 item, _Empty >? oneP] + +-- | At least one comma separated item, & a trailing comma, if it's there. +commas1 :: TsGrammatical p => p a a -> p [a] [a] +commas1 item = _Cons >? item >*< manyP (try (comma >* item)) + *< optionalToken CommaToken + +comma :: TsGrammatical p => p () () +comma = tokenOf oneP CommaToken space + +-- | @...@, or not. +dots :: TsGrammatical p => p Bool Bool +dots = orP + [ only True >? tokenOf oneP DotDotDotToken oneP + , only False >? oneP + ] + +-- | @?@, or not. +question :: TsGrammatical p => p Bool Bool +question = orP + [ only True >? tokenOf oneP QuestionToken oneP + , only False >? oneP + ] + +-- | A @;@, which is printed, & parsed if it's there. +semicolon :: TsGrammatical p => p () () +semicolon = printed (tokenOf oneP SemicolonToken oneP) + +-- | A token, which is parsed if it's there, but not printed. +optionalToken :: TsGrammatical p => TsTokenCategory -> p () () +optionalToken category = dimap (const Nothing) (const ()) + (optionalP (tokenOf oneP category oneP)) + +-- | Syntax, which is printed, & parsed if it's there. +printed :: TsGrammatical p => p () () -> p () () +printed syntax = dimap (const (Just ())) (const ()) (optionalP syntax) + +-- | An identifier, or a contextual keyword, by its name. +identifier :: TsGrammatical p => p Text Text +identifier = orP + [ textOf Identifier + , orP + [ only text >? tokenOf oneP category oneP + | (category, text) <- contextualKeywords + ] + ] + +-- | An identifier, or any keyword, by its name. +identifierName :: TsGrammatical p => p Text Text +identifierName = orP + [ identifier + , orP + [ only text >? tokenOf oneP category oneP + | (category, text) <- reservedWords + ] + ] + +-- | A tuple's element, or else an optional element's type. +_Optional :: Iso' TsType (TsType, Bool) +_Optional = iso + (\case OptionalType node -> (node, True); node -> (node, False)) + (\case (node, True) -> OptionalType node; (node, False) -> node) + +-- | An object type or a mapped type, which are braced. +_Braced :: Prism' TsType TsType +_Braced = prism' id $ \case + node@(ObjectType _) -> Just node + node@(MappedType {}) -> Just node + _ -> Nothing + +-- | A template's spans, by the first's type & its middle or tail. +_Spans + :: Prism' [(TsType, Text)] + (TsType, Either (Text, [(TsType, Text)]) Text) +_Spans = prism' + (\case + (node, Left (middle, others)) -> (node, middle) : others + (node, Right tail') -> [(node, tail')]) + (\case + [(node, tail')] -> Just (node, Right tail') + (node, middle) : others@(_ : _) -> Just (node, Left (middle, others)) + [] -> Nothing) + +-- | A template literal type without substitutions. +_NoSubstitution :: Prism' TsType Text +_NoSubstitution = prism' (`TemplateLiteralType` []) $ \case + TemplateLiteralType text [] -> Just text + _ -> Nothing + +-- | A list of at least two, or else its only one. +_Several :: Prism' TsType [TsType] -> Iso' TsType (TsType, [TsType]) +_Several nodes = iso + (\node -> case node ^? nodes of + Just (first : others@(_ : _)) -> (first, others) + _ -> (node, [])) + (\case + (node, []) -> node + (first, others) -> review nodes (first : others)) + +-- | A conditional type, or else its check type. +_Conditional :: Iso' TsType (TsType, Maybe (TsType, (TsType, TsType))) +_Conditional = iso + (\case + ConditionalType check extends true false -> + (check, Just (extends, (true, false))) + node -> (node, Nothing)) + (\case + (node, Nothing) -> node + (check, Just (extends, (true, false))) -> + ConditionalType check extends true false) + +-- Trivia -- + +-- | Trivia, of whitespace & newlines, printed as some trivia. +trivia :: (Lexical TsToken p, Alternator p) => [TsToken] -> p () () +trivia shown = dimap (const shown) (const ()) + (manyP (asIn @TsToken WhitespaceTrivia >|< asIn @TsToken NewLineTrivia)) + +space :: (Lexical TsToken p, Alternator p) => p () () +space = trivia [TsToken WhitespaceTrivia " "] + +newline :: (Lexical TsToken p, Alternator p) => p () () +newline = trivia [TsToken NewLineTrivia "\n"] + +-- | A newline, indented four spaces for each depth. +indented :: (Lexical TsToken p, Alternator 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) + => 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 +textOf category = iso (TsToken category) tokenText >~ asIn @TsToken category diff --git a/distributors-json/test/Main.hs b/distributors-json/test/Main.hs new file mode 100644 index 00000000..852a7c90 --- /dev/null +++ b/distributors-json/test/Main.hs @@ -0,0 +1,22 @@ +module Main (main) where + +import Test.Hspec + +import Properties.Json +import Properties.TypeScript + +main :: IO () +main = hspec $ do + jsonTypeSpec + aesonSpec + jsonErrorSpec + jsonObjectSpec + jsonOptionsSpec + jsonTupleSpec + jsonTupleChoiceSpec + jsonOptionalSpec + jsonCodecSpec + jsonPrintSpec + jsonElementsSpec + typeScriptSpec + diff --git a/distributors-json/test/Properties/Json.hs b/distributors-json/test/Properties/Json.hs new file mode 100644 index 00000000..93d84ee0 --- /dev/null +++ b/distributors-json/test/Properties/Json.hs @@ -0,0 +1,1245 @@ +-- | Test records of sums, for aeson's generic options, have partial fields. +{-# OPTIONS_GHC -Wno-partial-fields #-} +{-# LANGUAGE DeriveAnyClass #-} +{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE RequiredTypeArguments #-} +module Properties.Json + ( jsonTypeSpec + , aesonSpec + , aesonCompat + , aesonEncodeCompat + , jsonErrorSpec + , jsonObjectSpec + , jsonOptionsSpec + , jsonTupleSpec + , jsonTupleChoiceSpec + , jsonOptionalSpec + , jsonCodecSpec + , jsonPrintSpec + , jsonElementsSpec + ) where + +import Control.Lens (coerced, only, prism') +import Control.Lens.Grammar + ( ParsecState (..), dimap, falseP, lmap, manyP, optK, optionP, optionalP + , parsecG, plusK, rule, someP, starK, unparsecG + , (>*<), (>+<), (>?), (>|<), (>~) + ) +import Control.Lens.Grammar.Json +import Data.Kind (Type) +import Data.SOP (All) +import Control.Lens.Grammar.TypeScript +import Data.Foldable (toList) +import Data.Sequence qualified as Seq +import Data.Aeson + ( FromJSON (..), Options (..), SumEncoding (..), ToJSON (..), ToJSONKey + , Value (String), camelTo2, decode, defaultOptions, encode, genericToJSON + , object, (.=) + ) +import Data.Aeson.Encoding (encodingToLazyByteString) +import Data.Aeson.Key (Key) +import Data.Aeson.KeyMap (KeyMap) +import Data.Aeson.Types + ( DotNetTime (..), GToJSON', Zero, formatError, parseEither ) +import Data.Char (toLower) +import Data.DList (DList) +import Data.DList qualified as DList +import Data.DList.DNonEmpty (DNonEmpty) +import Data.DList.DNonEmpty qualified as DNonEmpty +import Data.Either (isLeft, isRight) +import Data.Fix (Fix (..), Mu, Nu, unfoldMu, unfoldNu) +import Data.Fixed (E2, Fixed, Milli) +import Data.Functor.Compose (Compose) +import Data.Functor.Const (Const) +import Data.Functor.Identity (Identity) +import Data.Functor.Product qualified as Functor +import Data.Functor.Sum qualified as Functor +import Data.Functor.These (These1) +import Data.HashMap.Strict (HashMap) +import Data.HashSet (HashSet) +import Data.Int (Int8, Int16, Int32, Int64) +import Data.IntMap (IntMap) +import Data.IntSet (IntSet) +import Data.List.NonEmpty (NonEmpty) +import Data.Map (Map) +import Data.Map qualified as Map +import Data.Monoid qualified as Monoid +import Data.Ord (Down (..)) +import Data.Primitive.Array (Array) +import Data.Primitive.PrimArray (PrimArray) +import Data.Primitive.SmallArray (SmallArray) +import Data.Proxy (Proxy (..)) +import Data.Ratio (Ratio) +import Data.Scientific (Scientific) +import Data.Semigroup qualified as Semigroup +import Data.Sequence (Seq) +import Data.Set (Set) +import Data.Strict qualified as Strict +import Data.Tagged (Tagged) +import Data.Text (Text) +import Data.Text qualified as Text +import Data.Text.Lazy qualified as LText +import Data.Text.Short (ShortText) +import Data.These (These) +import Data.Time + ( CalendarDiffDays, CalendarDiffTime, Day, DayOfWeek, DiffTime, LocalTime + , NominalDiffTime, TimeOfDay, UTCTime, ZonedTime + ) +import Data.Time.Calendar.Month (Month) +import Data.Time.Calendar.Quarter (Quarter, QuarterOfYear) +import Data.Time.Clock.System (SystemTime) +import Data.Tree (Tree (..)) +import Data.Tuple (Solo) +import Data.Typeable (Typeable, typeRep) +import Data.UUID.Types (UUID) +import Data.Vector (Vector) +import Data.Vector.Primitive qualified as VP +import Data.Vector.Storable qualified as VS +import Data.Vector.Unboxed qualified as VU +import Data.Version (Version, makeVersion) +import Data.Void (Void) +import Data.Word (Word8, Word16, Word32, Word64) +import Foreign.C.Types (CTime (..)) +import GHC.Exts qualified as Exts +import GHC.Generics (Generic, Generically (..), Rep) +import Network.URI (URI, parseURI) +import Numeric.Natural (Natural) +import Test.Hspec +import Test.Hspec.QuickCheck (prop) +import Witherable qualified +import Test.QuickCheck hiding (Fixed) +import Test.QuickCheck.Instances () + +data Point = Point { px :: Scientific, py :: Scientific } + deriving stock (Show, Generic) + deriving anyclass (Json, ToJSON, FromJSON) + +newtype Wrap = Wrap Scientific + deriving stock (Show, Generic) + deriving anyclass (Json, ToJSON, FromJSON) + +data Pair = Pair Scientific Text + deriving stock (Show, Generic) + deriving anyclass (Json, ToJSON, FromJSON) + +data Unit = Unit + deriving stock (Show, Generic) + deriving anyclass (Json, ToJSON, FromJSON) + +data Color = Red | Green | Blue + deriving stock (Show, Generic, Bounded, Enum) + deriving anyclass (Json, ToJSON, FromJSON) + +data Shape + = Circle Scientific + | Square { _side :: Scientific } + deriving stock (Show, Generic) + deriving anyclass (Json, ToJSON, FromJSON) + +data Profile = Profile + { name :: Text + , tags :: Vector Text + , nickname :: Maybe Text + } deriving stock (Show, Generic) + deriving anyclass (Json, ToJSON, FromJSON) + +-- | @aeson@ instances derived via `Generically`, +-- mixing nullary & non-nullary constructors. +data Token = Word Text | Number Int | Pause + deriving stock (Show, Generic) + deriving anyclass Json + deriving (ToJSON, FromJSON) via Generically Token + +-- | Recursive. +data Peano = Zero | Succ Peano + deriving stock (Show, Generic) + deriving anyclass (Json, ToJSON, FromJSON) + +-- | Mutually recursive. +newtype Forest = Forest [Branch] + deriving stock (Show, Generic) + deriving anyclass (Json, ToJSON, FromJSON) +data Branch = Branch Scientific Forest + deriving stock (Show, Generic) + deriving anyclass (Json, ToJSON, FromJSON) + +-- | Parametric. +newtype Box a = Box a + deriving stock (Show, Generic) + deriving anyclass (ToJSON, FromJSON) +instance (Typeable a, Json a) => Json (Box a) + +-- | An ill-formed object grammar, reading the same key twice. +newtype Dup = Dup (Int, Int) + deriving stock Show +instance Json Dup where + json = jsonTyped $ 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 $ + 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 $ + 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 $ + 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 + (\case Cat n -> Left n; Dog age -> Right age) + (either Cat Dog) + (jsonObject ("Cat" !: json >+< "Dog" !: json)) + +-- | A total, and tallies by answers of the rest of the keys. +newtype Tally = Tally (Int, [(Bool, Int)]) + deriving stock (Eq, Show) +instance Json Tally where + json = jsonTyped $ dimap (\(Tally p) -> p) Tally $ jsonObject + ( "total" !: json + >*< jsonDict (jsonEnumWith fromEnum [("no", False), ("yes", True)]) + json + ) + +-- | A tally of the answer "yes", and of the rest of the answers. +newtype Votes = Votes (Int, [(Bool, Int)]) + deriving stock (Eq, Show) +instance Json Votes where + json = jsonTyped $ dimap (\(Votes p) -> p) Votes $ jsonObject + ( "yes" !: json + >*< jsonDict (jsonEnumWith fromEnum [("no", False), ("yes", True)]) + json + ) + +-- | A name, and scores by the numbers of the rest of the keys. +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 + Just key -> jsonObject ("name" !: json >*< jsonDict key json) + Nothing -> error "Int has a key" + +-- | An identifier and no other properties. +newtype Closed = Closed Int + deriving stock (Eq, Show) +instance Json Closed where + json = jsonTyped $ dimap (\(Closed n) -> n) Closed $ + jsonObjectStrict ("id" !: json) + +jsonObjectSpec :: Spec +jsonObjectSpec = describe "jsonObject" $ do + it "defaults a missing property" $ do + jsonParse @Limit (object []) `shouldBe` Right (Limit 10) + jsonErrorPrint (Limit 10) `shouldBe` Right (object []) + jsonErrorPrint (Limit 3) `shouldBe` Right (object ["limit" .= (3 :: Int)]) + it "reads & writes the rest of an object" $ do + let + extra = Extra (1, [("a", True), ("b", False)]) + value = + object ["id" .= (1 :: Int), "a" .= True, "b" .= False] + jsonParse @Extra value `shouldBe` Right extra + jsonErrorPrint extra `shouldBe` Right value + it "doesn't print the rest over a named key" $ + printError (Extra (1, [("id", True)])) `shouldBe` + Left "Error in $: cannot print key \"id\" twice" + it "rejects keys which an object doesn't name" $ do + jsonParse @Closed (object ["id" .= (1 :: Int)]) `shouldBe` Right (Closed 1) + parseError @Closed (object ["id" .= (1 :: Int), "x" .= True]) + `shouldBe` "Error in $.x: unexpected true" + it "chooses between alternative shapes" $ do + jsonParse @Pet (object ["Cat" .= ("tom" :: Text)]) + `shouldBe` Right (Cat "tom") + jsonParse @Pet (object ["Dog" .= (3 :: Int)]) `shouldBe` Right (Dog 3) + jsonErrorPrint (Dog 3) `shouldBe` Right (object ["Dog" .= (3 :: Int)]) + declares (type Pet) + [ "export type Int = number;" + , "export type Pet = { Cat: string } | { Dog: Int };" + ] + it "types maps of enumerated keys as mapped types" $ do + declares (type (Box (Map DayOfWeek Int))) + [ "export type Box_Map_DayOfWeek_Int = \ + \{ [key in DayOfWeek]?: Int };" + , "export type DayOfWeek = \"monday\" | \"tuesday\" | \"wednesday\" \ + \| \"thursday\" | \"friday\" | \"saturday\" | \"sunday\";" + , "export type Int = number;" + ] + declares (type Tally) + [ "export type Int = number;" + , "export type Tally = \ + \{ total: Int } & { [key in \"no\" | \"yes\"]?: Int };" + ] + roundTrip (object ["total" .= (2 :: Int), "yes" .= (2 :: Int)]) + (Tally (2, [(True, 2)])) + declares (type (Box (Map Bool Int))) + [ "export type Box_Map_Bool_Int = \ + \{ [key in \"false\" | \"true\"]?: Int };" + , "export type Int = number;" + ] + it "excludes named keys from the mapped type of the rest" $ do + declares (type Votes) + [ "export type Int = number;" + , "export type Votes = { yes: Int } & \ + \{ [key in \"no\" | \"yes\" as key extends \"yes\" ? never : key]?: Int };" + ] + roundTrip (object ["yes" .= (2 :: Int), "no" .= (1 :: Int)]) + (Votes (2, [(False, 1)])) + it "types number keys as strings" $ do + declares (type (Box (Map Int Bool))) + [ "export type Box_Map_Int_Bool = { [key: string]: boolean };" + ] + declares (type Scores) + [ "export type Scores = \ + \{ name: string; [key: string]: boolean | string };" + ] + it "types the rest of an object as an index signature" $ do + declares (type Extra) + [ "export type Extra = { id: Int; [key: string]: boolean | Int };" + , "export type Int = number;" + ] + declares (type Closed) + ["export type Closed = { id: Int };", "export type Int = number;"] + it "doesn't print overlapping keys" $ + printError (Dup (1, 2)) `shouldBe` + Left "Error in $: cannot print key \"k\" twice" + it "doesn't parse a key twice" $ + parseError @Dup (object ["k" .= (1 :: Int)]) `shouldBe` + "Error in $: expected another key \"k\", but found {\"k\":1}" + it "doesn't type overlapping keys" $ + declares (type Dup) + ["export type Dup = never;", "export type Int = number;"] + it "ignores extra keys" $ + jsonParse @Point + (object ["px" .= (1 :: Int), "py" .= (2 :: Int), "pz" .= (3 :: Int)]) + `shouldSatisfy` isRight + +-- | A tuple of a number and rest strings, @[number, ...string[]]@. +newtype Rest = Rest (Scientific, [Text]) + deriving stock (Eq, Show) +instance Json Rest where + json = jsonTyped $ 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 $ + 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 $ + 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 $ + 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 $ + jsonTuple (manyP (jsonElem json) >*< manyP (jsonElem json)) + +-- | Rest strings and an optional number, +-- @[...string[], number] | [...string[]]@. +newtype RestOptional = RestOptional ([Text], Maybe Scientific) + deriving stock (Eq, Show) +instance Json RestOptional where + json = jsonTyped $ 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 $ + 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 $ + 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 + (\(Middle (a, b, c)) -> (a, (b, c))) + (\(a, (b, c)) -> Middle (a, b, c)) + (jsonTuple (jsonElem json >*< manyP (jsonElem json) >*< jsonElem json)) + +-- | At least one element, @[number, ...number[]]@. +newtype AtLeastOne = AtLeastOne [Scientific] + deriving stock (Eq, Show) +instance Json AtLeastOne where + json = jsonTyped $ 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 $ + 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 $ + jsonElem json >*< optionP (only 0) (jsonElem json) + +jsonTupleChoiceSpec :: Spec +jsonTupleChoiceSpec = describe "jsonTuple choices" $ do + it "has rest elements in the middle" $ do + roundTrip (toJSON [toJSON (1 :: Int), "a", "b", toJSON True]) + (Middle (1, ["a", "b"], True)) + roundTrip (toJSON [toJSON (1 :: Int), toJSON False]) (Middle (1, [], False)) + declares (type Middle) + ["export type Middle = [number, ...string[], boolean];"] + it "has non-empty rest elements" $ do + roundTrip (toJSON [1, 2 :: Int]) (AtLeastOne [1, 2]) + jsonParse @AtLeastOne (toJSON ([] :: [Int])) `shouldSatisfy` isLeft + declares (type AtLeastOne) + ["export type AtLeastOne = [number, ...number[]];"] + it "has alternatives of the same type" $ do + roundTrip (toJSON [1, 2 :: Int]) (Coord (1, 2)) + jsonParse @Coord (toJSON [1 :: Int]) `shouldBe` Right (Coord (1, 0)) + declares (type Coord) ["export type Coord = [number, number?];"] + it "has defaulted elements" $ do + roundTrip (toJSON [1 :: Int]) (Defaulted (1, 0)) + roundTrip (toJSON [1, 2 :: Int]) (Defaulted (1, 2)) + declares (type Defaulted) ["export type Defaulted = [number, number?];"] + +-- | Round trip a `Value` through a `Json` grammar. +roundTrip :: forall a. (Json a, Eq a, Show a) => Value -> a -> Expectation +roundTrip value a = do + jsonParse @a value `shouldBe` Right a + jsonErrorPrint a `shouldBe` Right value + +-- | An array, as a tuple of a rest element. +newtype Elements = Elements [Int] + deriving stock (Eq, Show) +instance Json Elements where + json = coerced >~ jsonTuple (manyP (jsonElem (json @Int))) + +jsonTupleSpec :: Spec +jsonTupleSpec = describe "variadic jsonTuple" $ do + prop "is an array of a rest element" $ \(ns :: [Int]) -> + jsonPrint (Elements ns) === jsonPrint ns + .&&. jsonParse (jsonPrint ns) === Right (Elements ns) + it "has rest elements" $ do + roundTrip (toJSON [toJSON (1 :: Int)]) (Rest (1, [])) + roundTrip (toJSON [toJSON (1 :: Int), "a", "b"]) (Rest (1, ["a", "b"])) + declares (type Rest) ["export type Rest = [number, ...string[]];"] + it "backtracks leading rest elements" $ do + roundTrip (toJSON [toJSON (1 :: Int)]) (Leading ([], 1)) + roundTrip (toJSON ["a", "b", toJSON (1 :: Int)]) (Leading (["a", "b"], 1)) + declares (type Leading) ["export type Leading = [...string[], number];"] + it "has optional elements" $ do + roundTrip (toJSON [toJSON (1 :: Int)]) (Trailing (1, Nothing)) + roundTrip (toJSON [toJSON (1 :: Int), "a"]) (Trailing (1, Just "a")) + declares (type Trailing) ["export type Trailing = [number, string?];"] + it "expands optional elements before required elements" $ do + roundTrip (toJSON [toJSON (1 :: Int)]) (Before (Nothing, 1)) + roundTrip (toJSON ["a", toJSON (1 :: Int)]) (Before (Just "a", 1)) + declares (type Before) + ["export type Before = [string, number] | [number];"] + it "merges rest elements" $ do + roundTrip (toJSON [toJSON (1 :: Int), toJSON (2 :: Int), "a"]) + (Rests ([1, 2], ["a"])) + declares (type Rests) ["export type Rests = (number | string)[];"] + it "expands optional elements after rest elements" $ do + roundTrip (toJSON ["a", toJSON (1 :: Int)]) (RestOptional (["a"], Just 1)) + declares (type RestOptional) + ["export type RestOptional = [...string[], number] | string[];"] + it "has alternative elements" $ do + roundTrip (toJSON [toJSON (1 :: Int)]) (Alternative (Left 1)) + roundTrip (toJSON [String "a"]) (Alternative (Right "a")) + declares (type Alternative) + ["export type Alternative = [number | string];"] + it "has alternative rest elements" $ do + roundTrip (toJSON ["a", "b" :: Text]) (AlternativeRests (Right ["a", "b"])) + jsonParse @AlternativeRests (toJSON [toJSON (1 :: Int), "a"]) + `shouldSatisfy` isLeft + declares (type AlternativeRests) + ["export type AlternativeRests = number[] | string[];"] + it "locates failures in rest elements" $ + parseError @Rest (toJSON [toJSON (1 :: Int), "a", toJSON (2 :: Int)]) + `shouldBe` "Error in $[2]: expected string, but found 2" + it "reports lengths" $ + parseError @Trailing (toJSON [toJSON (1 :: Int), "a", "b"]) `shouldBe` + "Error in $: expected 2 elements or 1 element, \ + \but found [1,\"a\",\"b\"]" + +-- | A partial grammar, which can't print `Uncovered`. +data Partial = Covered Scientific | Uncovered + deriving stock (Eq, Show) +instance Json Partial where + json = rule "Partial" $ + prism' Covered (\case Covered n -> Just n; _ -> Nothing) >? json + +jsonPrintSpec :: Spec +jsonPrintSpec = describe "jsonErrorPrint" $ do + it "labels failures with rules" $ + printError Uncovered `shouldBe` Left "Error in $: cannot print as Partial" + it "locates failures" $ do + printError [Covered 1, Uncovered] `shouldBe` + Left "Error in $[1]: cannot print as Partial" + printError (Rest (1, ["a"]), Uncovered) `shouldBe` + Left "Error in $[1]: cannot print as Partial" + it "reports overlapping keys" $ + printError (Dup (1, 2)) `shouldBe` + Left "Error in $: cannot print key \"k\" twice" + +{- | TypeScript type declarations, one per line, +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 + where + declared = jsonTsDeclarations [a] + scanned = concat (parsecResult (parsecG tsTokensGrammar (tsSource declared))) + +jsonTypeSpec :: Spec +jsonTypeSpec = describe "jsonTsDeclarations" $ do + let point = "{ px: number; py: number }" + it "declares nothing for types without rules" $ do + declares Bool [] + declares Text [] + declares Scientific [] + declares (type String) [] + declares (Vector Text) [] + declares (Maybe Text) [] + declares (Map Text Scientific) [] + it "declares a record as an object" $ + declares (type Point) ["export type Point = " <> point <> ";"] + it "declares a single-field constructor as its contents" $ + declares (type Wrap) ["export type Wrap = number;"] + it "declares a positional multi-field constructor as a tuple" $ + declares (type Pair) ["export type Pair = [number, string];"] + it "declares a nullary single-constructor type as an empty tuple" $ + declares (type Unit) ["export type Unit = [];"] + it "declares an all-nullary sum as a union of string literals" $ + declares Color + ["export type Color = \"Red\" | \"Green\" | \"Blue\";"] + it "declares a mixed sum as a discriminated union of objects" $ + declares Shape + [ "export type Shape = { tag: \"Circle\"; contents: number } \ + \| { tag: \"Square\"; _side: number };" + ] + it "declares nested records" $ + declares (type Profile) + [ "export type Profile = \ + \{ name: string; tags: string[]; nickname?: null | string };" + ] + it "declares a recursive type" $ + declares Peano + [ "export type Peano = { tag: \"Zero\" } \ + \| { tag: \"Succ\"; contents: Peano };" + ] + it "declares mutually recursive types" $ do + let + declarations = + [ "export type Branch = [number, Forest];" + , "export type Forest = Branch[];" + ] + declares (type Forest) declarations + declares (type Branch) declarations + it "declares each instantiation of a parametric type" $ + declares (type (Box (Box Scientific))) + [ "export type Box_Box_Scientific = Box_Scientific;" + , "export type Box_Scientific = number;" + ] + it "declares recursive non-generic types" $ do + declares (Tree Scientific) + ["export type Tree_Scientific = [number, Tree_Scientific[]];"] + let + declarations = + [ "export type Fix_Either_Scientific = { Left: number } \ + \| { Right: Fix_Either_Scientific };" + ] + declares (type (Fix (Either Scientific))) declarations + declares (Mu (Either Scientific)) declarations + declares (Nu (Either Scientific)) declarations + declares Value + [ "export type Value = null | boolean | number | string \ + \| Value[] | { [key: string]: Value };" + ] + it "declares a non-empty list as a tuple with a rest element" $ + declares (type (Box (NonEmpty Text))) + ["export type Box_NonEmpty_Text = [string, ...string[]];"] + it "declares an enumeration as a union of string literals" $ do + declares Ordering ["export type Ordering = \"LT\" | \"EQ\" | \"GT\";"] + declares DayOfWeek + [ "export type DayOfWeek = \"monday\" | \"tuesday\" | \"wednesday\" \ + \| \"thursday\" | \"friday\" | \"saturday\" | \"sunday\";" + ] + declares QuarterOfYear + ["export type QuarterOfYear = \"q1\" | \"q2\" | \"q3\" | \"q4\";"] + it "declares the rules of types without rules" $ + declares (type (Vector Point)) ["export type Point = " <> point <> ";"] + it "declares each type once" $ + length (Text.lines (tsTypes [Twice16])) `shouldBe` 16 + it "names colliding declarations uniquely" $ + declares (type Collide) + [ "export type Collide = \ + \{ named: Point; typed: Properties_Json_Point };" + , "export type Point = number;" + , "export type Properties_Json_Point = " <> point <> ";" + ] + it "names declarations by distinct TypeScript identifiers" $ do + let pair = "Properties_Json_GHC_Types_Int_Data_Text_Internal_Text" + declares (type Sanitized) + [ "export type Exclude = number;" + , "export type Int = number;" + , "export type Int_Text = [Int, string];" + , "export type " <> pair <> " = \ + \{ tag: \"L\"; contents: Int } | { tag: \"R\"; contents: string };" + , "export type Sanitized = [" <> pair <> ", Int_Text, Exclude];" + ] + it "quotes property keys" $ + declares (type Optional) + ["export type Optional = { a: number; \"b c\"?: string | number };"] + it "declares types sharing their type aliases" $ + tsTypes (type [Point, Box Point]) `shouldBe` Text.unlines + [ "export type Box_Point = Point;" + , "export type Point = " <> point <> ";" + ] + it "declares a rule of a rule as the rule" $ + declares (type Retyped) ["export type Retyped = number;"] + it "declares unguarded recursion as its least fixpoint" $ do + declares (type Chain) ["export type Chain = null;"] + declares (type Loop) ["export type Loop = never;"] + +-- | A rule of a rule, `jsonTyped` twice. +newtype Retyped = Retyped Scientific + deriving stock Show +instance Json Retyped where + json = jsonTyped (jsonTyped (dimap (\(Retyped n) -> n) Retyped json)) + +-- | Unguarded recursion, which only encodes as @null@. +newtype Chain = Chain (Maybe Chain) + deriving stock (Show, Generic) + deriving anyclass Json + +-- | Unguarded recursion, which encodes nothing. +newtype Loop = Loop Loop + deriving stock (Show, Generic) + deriving anyclass Json + +-- | Sixteen nested pairs, of exponentially many paths. +type Twice16 = Twice (Twice (Twice (Twice Twice12))) +type Twice12 = Twice (Twice (Twice (Twice (Twice (Twice (Twice (Twice + (Twice (Twice (Twice (Twice Scientific))))))))))) +data Twice a = Twice a a + deriving stock (Show, Generic) +instance (Typeable a, Json a) => Json (Twice a) + +-- | A named rule and a type, both called @Point@. +data Collide = Collide {named :: Scientific, typed :: Point} + deriving stock Show +instance Json Collide where + json = jsonTyped $ jsonObject $ Collide + <$> lmap named ("named" !: rule "Point" jsonNumber) + <*> lmap typed ("typed" !: json) + +{- | Types named by the same identifier, @Int_Text@, & one named @Exclude@, +which TypeScript declares globally, but which declarations needn't use. +-} +data Sanitized = Sanitized (Int :+: Text) (Int :*: Text) Exclude + deriving stock (Show, Generic) + deriving anyclass Json +data a :+: b = L a | R b + deriving stock (Show, Generic) +instance (Typeable a, Typeable b, Json a, Json b) => Json (a :+: b) +data a :*: b = a :*: b + deriving stock (Show, Generic) +instance (Typeable a, Typeable b, Json a, Json b) => Json (a :*: b) +newtype Exclude = Exclude Scientific + deriving stock (Show, Generic) + deriving anyclass Json + +-- | An optional property, with a key which isn't an identifier. +data Optional = Optional Scientific (Maybe (Either Text Scientific)) + deriving stock (Eq, Show) +instance Json Optional where + json = jsonTyped $ jsonObject $ Optional + <$> lmap (\(Optional a _) -> a) ("a" !: json) + <*> lmap (\(Optional _ b) -> b) + ("b c" ?: (jsonText >+< jsonNumber)) + +jsonOptionalSpec :: Spec +jsonOptionalSpec = describe "(?:)" $ do + it "may be missing" $ + roundTrip (object ["a" .= (1 :: Int)]) (Optional 1 Nothing) + it "may be present" $ + roundTrip (object ["a" .= (1 :: Int), "b c" .= ("x" :: Text)]) + (Optional 1 (Just (Left "x"))) + it "must be valid when present" $ + parseError @Optional (object ["a" .= (1 :: Int), "b c" .= True]) + `shouldBe` "Error in $['b c']: expected string or number, but found true" + +-- | Encoding agrees with @aeson@. +jsonCodecSpec :: Spec +jsonCodecSpec = describe "jsonEncode" $ do + it "derives aeson's instances from Json's" $ do + let point = Point 1 2 + toJSON (ViaJson point) `shouldBe` jsonPrint point + encodingToLazyByteString (toEncoding (ViaJson point)) + `shouldBe` encodingToLazyByteString (jsonEncode point) + either Left (\(ViaJson p) -> Right (px p)) + (parseEither parseJSON (object ["px" .= True, "py" .= (2 :: Int)])) + `shouldBe` Left "Error in $.px: expected number, but found true" + codecCompat @Profile (Profile <$> arbitrary <*> arbitrary <*> arbitrary) + codecCompat @(Map Text [Int]) arbitrary + codecCompat @(Int, Maybe Bool, Text) arbitrary + codecCompat @Value arbitrary + codecCompat @Shape (oneof [Circle <$> arbitrary, Square <$> arbitrary]) + codecCompat @Color arbitraryBoundedEnum + it "encodes in order" $ + encodingToLazyByteString <$> jsonErrorEncode (Point 1 2) + `shouldBe` Right "{\"px\":1,\"py\":2}" + describe "ViaJson's keys agree with aeson's" $ do + viaKeys @Int + viaKeys @Text + viaKeys @(Int, Int) + prop "[Char]" $ \(m :: Map String Bool) -> + let via = Map.mapKeysMonotonic (map ViaJson) m + in encode via === encode m .&&. decode (encode m) === Just via + it "ViaJson omits fields as aeson does" $ do + omitField (ViaJson (Nothing :: Maybe Int)) `shouldBe` True + omitField (ViaJson (Just (1 :: Int))) `shouldBe` False + omitField (ViaJson (1 :: Int)) `shouldBe` False + omittedField `shouldBe` Just (ViaJson (Nothing :: Maybe Int)) + omittedField `shouldBe` (Nothing :: Maybe (ViaJson Int)) + +-- | `ViaJson`'s keys print & parse as @aeson@'s. +viaKeys + :: forall k + . (Json k, Ord k, ToJSONKey k, Arbitrary k, Show k, Typeable k) + => Spec +viaKeys = prop (show (typeRep (Proxy @k))) $ \(m :: Map k Bool) -> + let via = Map.mapKeysMonotonic ViaJson m + in encode via === encode m .&&. decode (encode m) === Just via + +codecCompat :: forall a. (Json a, ToJSON a, Show a, Typeable a) => Gen a -> Spec +codecCompat gen = it (show (typeRep (Proxy @a))) $ forAll gen $ \a -> + (decode . encodingToLazyByteString <$> jsonErrorEncode a) + === Right (Just (toJSON a)) + +-- | The error message of parsing a `Value`. +parseError :: forall a. (Json a, Show a) => Value -> String +parseError = either errorText show . jsonParse @a + +-- | The error message of printing a value. +printError :: Json a => a -> Either String Value +printError = either (Left . errorText) Right . jsonErrorPrint + +errorText :: JsonError -> String +errorText err = formatError (jsonErrorPath err) (jsonErrorMessage err) + +-- | The rules within which parsing a value failed. +parseRules :: forall a. Json a => Value -> [Tree String] +parseRules = either jsonErrorRules (const []) . jsonParse @a + +-- | Alternative rules, which fail alike. +newtype Ambiguous = Ambiguous Scientific +instance Json Ambiguous where + json = dimap (\(Ambiguous n) -> n) Ambiguous $ + rule "A" (jsonObject ("x" !: jsonNumber)) + >|< rule "B" (jsonObject ("x" !: jsonNumber)) + +jsonErrorSpec :: Spec +jsonErrorSpec = describe "jsonParse errors" $ do + it "fails to decode text which isn't JSON, by aeson's message" $ + either errorText show (jsonDecode @Int "[1,") + `shouldBe` "Error in $: Unexpected end-of-input, expecting JSON value" + it "filters what's parsed" $ do + jsonParse @Counted (toJSON (1 :: Int)) `shouldBe` Right (Counted 1) + parseError @Counted (toJSON (-1 :: Int)) `shouldBe` + "Error in $: expected Counted, but found -1" + it "labels failures with rules" $ do + parseError @Int (toJSON (1.5 :: Double)) `shouldBe` + "Error in $: expected Int, but found 1.5" + parseError @Natural (toJSON (-1 :: Int)) `shouldBe` + "Error in $: expected Natural, but found -1" + parseError @Char (String "ab") `shouldBe` + "Error in $: expected Char, but found \"ab\"" + parseError @Color (String "Purple") `shouldBe` + "Error in $: expected Color, but found \"Purple\"" + it "merges the expectations of alternatives" $ do + parseError @(Maybe Int) (String "x") `shouldBe` + "Error in $: expected null or Int, but found \"x\"" + parseError @(Either Int Text) (object ["Middle" .= (1 :: Int)]) `shouldBe` + "Error in $: expected key \"Left\" or key \"Right\", \ + \but found {\"Middle\":1}" + parseError @Shape (object ["tag" .= ("Triangle" :: Text)]) `shouldBe` + "Error in $.tag: expected \"Circle\" or \"Square\", \ + \but found \"Triangle\"" + it "collects the rules which failures are within" $ do + let + badPoint = object ["px" .= ("a" :: Text), "py" .= (1 :: Int)] + parseRules @Point badPoint `shouldBe` [Node "Point" []] + parseRules @(Box Point) badPoint + `shouldBe` [Node "Box Point" [Node "Point" []]] + parseRules @[Point] (toJSON [badPoint]) `shouldBe` [Node "Point" []] + parseRules @Point (object ["px" .= (1 :: Int)]) + `shouldBe` [Node "Point" []] + parseRules @Point (toJSON (1 :: Int)) `shouldBe` [] + parseRules @Ambiguous (object ["x" .= ("s" :: Text)]) + `shouldBe` [Node "A" [], Node "B" []] + it "prefers the failure of the alternative that applies" $ + parseError @Shape + (object ["tag" .= ("Circle" :: Text), "contents" .= ("x" :: Text)]) + `shouldBe` "Error in $.contents: expected number, but found \"x\"" + it "locates failures" $ do + parseError @Point (object ["px" .= (1 :: Int), "py" .= ("x" :: Text)]) + `shouldBe` "Error in $.py: expected number, but found \"x\"" + parseError @Point (object ["px" .= (1 :: Int)]) `shouldBe` + "Error in $: expected key \"py\", but found {\"px\":1}" + parseError @[Int] (toJSON [toJSON (1 :: Int), String "x"]) `shouldBe` + "Error in $[1]: expected Int, but found \"x\"" + parseError @(Map Text Int) (object ["a" .= (1 :: Int), "b" .= True]) + `shouldBe` "Error in $.b: expected Int, but found true" + parseError @[Bool] (toJSON [toJSON True, String "x"]) `shouldBe` + "Error in $[1]: expected boolean, but found \"x\"" + parseError @(Int, Text) (toJSON [1 :: Int]) `shouldBe` + "Error in $: expected at least 2 elements, but found [1]" + parseError @(Int, Text) (toJSON [toJSON (1 :: Int), toJSON (2 :: Int)]) + `shouldBe` "Error in $[1]: expected string, but found 2" + +{- | Validate a `Json` instance against @aeson@'s instances: +printing agrees with `toJSON`, and parsing @aeson@'s encoding +agrees with `parseJSON`, comparing results by their encodings. +-} +aesonCompat + :: forall a. (Json a, ToJSON a, FromJSON a, Show a, Typeable a) + => Gen a -> Spec +aesonCompat gen = it (show (typeRep (Proxy @a))) $ + forAll gen $ \a -> + let value = toJSON a + in encodeCompat a + .&&. parsed (jsonParse @a value) + === parsed (parseEither (parseJSON @a) value) + where + parsed :: Either e a -> Maybe Value + parsed = either (const Nothing) (Just . toJSON) + +{- | Validate a `Json` instance against @aeson@'s `ToJSON` instance, +for types @aeson@ can encode but not decode: +printing agrees with `toJSON`, and parsing it reproduces the encoding. +-} +aesonEncodeCompat + :: forall a. (Json a, ToJSON a, Show a, Typeable a) + => Gen a -> Spec +aesonEncodeCompat gen = it (show (typeRep (Proxy @a))) $ + forAll gen encodeCompat + +encodeCompat :: forall a. (Json a, ToJSON a) => a -> Property +encodeCompat a = + let value = toJSON a + in jsonErrorPrint a === Right value + .&&. fmap toJSON (jsonParse @a value) === Right value + +aesonSpec :: Spec +aesonSpec = describe "Json agrees with aeson" $ do + -- base + aesonCompat @Bool arbitrary + aesonCompat @Ordering arbitrary + aesonCompat @() arbitrary + aesonCompat @Char arbitrary + aesonCompat @String arbitrary + aesonCompat @[Int] arbitrary + aesonCompat @(Maybe Int) arbitrary + aesonCompat @(Maybe (Maybe Bool)) arbitrary + aesonCompat @(Either Int Text) arbitrary + aesonCompat @Double arbitrary + aesonCompat @Double (elements [0/0, 1/0, negate 1/0]) + aesonCompat @Float arbitrary + aesonCompat @(Ratio Integer) arbitrary + aesonCompat @Milli arbitrary + aesonCompat @Int arbitrary + aesonCompat @Int8 arbitrary + aesonCompat @Int16 arbitrary + aesonCompat @Int32 arbitrary + aesonCompat @Int64 arbitrary + aesonCompat @Word arbitrary + aesonCompat @Word8 arbitrary + aesonCompat @Word16 arbitrary + aesonCompat @Word32 arbitrary + aesonCompat @Word64 arbitrary + aesonCompat @Integer arbitrary + aesonCompat @Natural arbitrary + aesonCompat @CTime (CTime <$> arbitrary) + aesonCompat @Version genVersion + aesonCompat @(NonEmpty Int) arbitrary + aesonCompat @(Solo Int) arbitrary + aesonCompat @(Identity Int) arbitrary + aesonCompat @[Identity Char] arbitrary + aesonCompat @(Const Int Bool) arbitrary + aesonCompat @(Compose Maybe [] Int) arbitrary + aesonCompat @(Functor.Product Maybe [] Int) arbitrary + aesonCompat @(Functor.Sum Maybe [] Int) arbitrary + aesonCompat @(Down Int) (Down <$> arbitrary) + aesonCompat @[Down Char] (map Down <$> arbitrary) + aesonCompat @(Monoid.Dual Int) arbitrary + aesonCompat @(Monoid.First Int) arbitrary + aesonCompat @(Monoid.Last Int) arbitrary + aesonCompat @(Semigroup.Min Int) arbitrary + aesonCompat @(Semigroup.Max Int) arbitrary + aesonCompat @(Semigroup.First Int) arbitrary + aesonCompat @(Semigroup.Last Int) arbitrary + aesonCompat @(Semigroup.WrappedMonoid [Int]) arbitrary + aesonCompat @(Semigroup.Sum Int) arbitrary + aesonCompat @(Semigroup.Product Int) arbitrary + aesonCompat @Semigroup.All arbitrary + aesonCompat @Semigroup.Any arbitrary + aesonCompat @(Proxy Int) (pure Proxy) + it "Void never parses" $ + jsonParse @Void (toJSON ()) `shouldSatisfy` isLeft + -- generics + aesonCompat @Point (Point <$> arbitrary <*> arbitrary) + aesonCompat @Wrap (Wrap <$> arbitrary) + aesonCompat @Pair (Pair <$> arbitrary <*> arbitrary) + aesonCompat @Unit (pure Unit) + aesonCompat @Color arbitraryBoundedEnum + aesonCompat @Shape (oneof [Circle <$> arbitrary, Square <$> arbitrary]) + aesonCompat @Profile (Profile <$> arbitrary <*> arbitrary <*> arbitrary) + aesonCompat @Token + (oneof [Word <$> arbitrary, Number <$> arbitrary, pure Pause]) + aesonCompat @Peano genPeano + aesonCompat @Forest genForest + aesonCompat @(Box (Box Int)) (Box . Box <$> arbitrary) + -- tuples + aesonCompat @(Int, Text) arbitrary + aesonCompat @(Int, Text, Bool) arbitrary + aesonCompat @(Int, Text, Bool, Char) arbitrary + aesonCompat @(Int, Text, Bool, Char, Int) arbitrary + aesonCompat @(Int, Text, Bool, Char, Int, Text) arbitrary + aesonCompat @(Int, Text, Bool, Char, Int, Text, Bool) arbitrary + aesonCompat @(Int, Text, Bool, Char, Int, Text, Bool, Char) arbitrary + aesonCompat @(Int, Text, Bool, Char, Int, Text, Bool, Char, Int) arbitrary + aesonCompat @(Int, Text, Bool, Char, Int, Text, Bool, Char, Int, Text) + arbitrary + aesonCompat @(Int, Text, Bool, Char, Int, Text, Bool, Char, Int, Text, Bool) + ((,,,,,,,,,,) <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary + <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary + <*> arbitrary <*> arbitrary) + aesonCompat + @(Int, Text, Bool, Char, Int, Text, Bool, Char, Int, Text, Bool, Char) + ((,,,,,,,,,,,) <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary + <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary + <*> arbitrary <*> arbitrary <*> arbitrary) + aesonCompat + @(Int, Text, Bool, Char, Int, Text, Bool, Char, Int, Text, Bool, Char, Int) + ((,,,,,,,,,,,,) <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary + <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary + <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary) + aesonCompat + @( Int, Text, Bool, Char, Int, Text, Bool, Char, Int, Text, Bool, Char + , Int, Text ) + ((,,,,,,,,,,,,,) <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary + <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary + <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary) + aesonCompat + @( Int, Text, Bool, Char, Int, Text, Bool, Char, Int, Text, Bool, Char + , Int, Text, Bool ) + ((,,,,,,,,,,,,,,) <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary + <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary + <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary + <*> arbitrary) + -- text & scientific + aesonCompat @Text arbitrary + aesonCompat @LText.Text arbitrary + aesonCompat @ShortText arbitrary + aesonCompat @Scientific arbitrary + -- containers + aesonCompat @(Seq Int) arbitrary + aesonCompat @(Set Int) arbitrary + aesonCompat @IntSet arbitrary + aesonCompat @(IntMap Text) arbitrary + aesonCompat @(Tree Int) arbitrary + -- maps + aesonCompat @(Map [Int] Int) arbitrary + aesonCompat @(Map (Int, Bool) Text) arbitrary + aesonCompat @(Map (Int, Bool, Char) Text) arbitrary + aesonCompat @(Map (Int, Bool, Char, Text) Text) arbitrary + aesonCompat @(Map Text Int) arbitrary + aesonCompat @(Map String Int) arbitrary + aesonCompat @(Map Bool Int) arbitrary + aesonCompat @(Map Char Int) arbitrary + aesonCompat @(Map Int Bool) arbitrary + aesonCompat @(Map Int8 Bool) arbitrary + aesonCompat @(Map Word64 Bool) arbitrary + aesonCompat @(Map Integer Bool) arbitrary + aesonCompat @(Map Natural Bool) arbitrary + aesonCompat @(Map Double Bool) arbitrary + -- neither @aeson@ nor `Json` round trip @-0.0@ keys, through `Scientific` + aesonCompat @(Map Double Bool) (Map.fromList . map (, True) <$> + sublistOf [0/0, 1/0, negate 1/0, 0]) + aesonCompat @(Map Float Bool) arbitrary + aesonEncodeCompat @(Map (Fixed E2) Bool) arbitrary + aesonEncodeCompat @(Map Scientific Bool) arbitrary + aesonCompat @(Map LText.Text Bool) arbitrary + aesonCompat @(Map ShortText Bool) arbitrary + aesonCompat @(Map Version Bool) + (Map.fromList <$> listOf ((,) <$> genVersion <*> arbitrary)) + aesonCompat @(Map (Solo Int) Bool) arbitrary + aesonCompat @(Map (Identity Text) Bool) arbitrary + aesonCompat @(Map [Identity Char] Bool) arbitrary + aesonCompat @(Map (Const Int Bool) Bool) arbitrary + aesonCompat @(Map (Tagged Bool Int) Bool) arbitrary + aesonCompat @(Map UUID Bool) arbitrary + aesonCompat @(Map Key Bool) arbitrary + aesonCompat @(Map Day Bool) arbitrary + aesonCompat @(Map Month Bool) arbitrary + aesonCompat @(Map Quarter Bool) arbitrary + aesonCompat @(Map TimeOfDay Bool) arbitrary + aesonCompat @(Map LocalTime Bool) arbitrary + aesonCompat @(Map UTCTime Bool) arbitrary + aesonCompat @(Map DayOfWeek Bool) arbitrary + aesonCompat @(Map QuarterOfYear Bool) arbitrary + aesonCompat @(Map URI Bool) + (Map.fromList <$> listOf ((,) <$> genURI <*> arbitrary)) + aesonCompat @(HashMap Text Int) arbitrary + -- dlist + aesonCompat @(DList Int) (DList.fromList <$> arbitrary) + aesonCompat @(DNonEmpty Int) (DNonEmpty.fromNonEmpty <$> arbitrary) + -- vector + aesonCompat @(Vector Int) arbitrary + aesonCompat @(VS.Vector Int) arbitrary + aesonCompat @(VP.Vector Int) (VP.fromList <$> arbitrary) + aesonCompat @(VU.Vector Int) arbitrary + -- primitive + aesonCompat @(Array Char) (Exts.fromList <$> arbitrary) + aesonCompat @(SmallArray Int) (Exts.fromList <$> arbitrary) + aesonCompat @(PrimArray Int) (Exts.fromList <$> arbitrary) + -- unordered-containers + aesonCompat @(HashSet Int) arbitrary + aesonCompat @(HashMap (Int, Int) Bool) arbitrary + -- aeson + aesonCompat @Key arbitrary + aesonCompat @(KeyMap Int) arbitrary + aesonCompat @Value arbitrary + aesonCompat @DotNetTime (DotNetTime <$> arbitrary) + -- time + aesonCompat @Day arbitrary + aesonCompat @Month arbitrary + aesonCompat @Quarter arbitrary + aesonCompat @TimeOfDay arbitrary + aesonCompat @LocalTime arbitrary + aesonCompat @ZonedTime arbitrary + aesonCompat @UTCTime arbitrary + aesonCompat @NominalDiffTime arbitrary + aesonCompat @DiffTime arbitrary + aesonCompat @SystemTime arbitrary + aesonCompat @CalendarDiffTime arbitrary + aesonCompat @CalendarDiffDays arbitrary + aesonCompat @DayOfWeek arbitrary + aesonCompat @QuarterOfYear arbitrary + -- uuid-types & network-uri + aesonCompat @UUID arbitrary + aesonCompat @URI genURI + -- data-fix + aesonCompat @(Fix (Either Int)) genFix + aesonCompat @(Mu (Either Int)) (unfoldMu unFix <$> genFix) + aesonCompat @(Nu (Either Int)) (unfoldNu unFix <$> genFix) + -- tagged & these & strict + aesonCompat @(Tagged Bool Int) arbitrary + aesonCompat @(These Int Text) arbitrary + aesonCompat @(These1 Maybe [] Int) arbitrary + aesonCompat @(Strict.Maybe Int) arbitrary + aesonCompat @(Strict.Either Int Text) arbitrary + aesonCompat @(Strict.These Int Text) arbitrary + aesonCompat @(Strict.Pair Int Text) arbitrary + +genVersion :: Gen Version +genVersion = makeVersion <$> listOf1 (chooseInt (0, 100)) + +genURI :: Gen URI +genURI = elements + [ uri + | Just uri <- parseURI <$> + [ "https://example.com/a/b?c=d#e" + , "mailto:someone@example.com" + , "file:///tmp/x.txt" + , "urn:isbn:0451450523" + ] + ] + +genPeano :: Gen Peano +genPeano = sized $ \n -> if n <= 0 then pure Zero + else frequency [(1, pure Zero), (3, Succ <$> resize (n - 1) genPeano)] + +genForest :: Gen Forest +genForest = sized $ \n -> Forest <$> if n <= 0 then pure [] + else listOf (Branch <$> arbitrary <*> resize (n `div` 3) genForest) + +genFix :: Gen (Fix (Either Int)) +genFix = sized $ \n -> if n <= 0 + then Fix . Left <$> arbitrary + else frequency + [ (1, Fix . Left <$> arbitrary) + , (3, Fix . Right <$> resize (n `div` 2) genFix) + ] + +-- | Constructors of each kind, for @aeson@'s generic options, +-- whose records' fields are partial. +data Sample + = Nullary + | Unary Int + | Binary Int Text + | Record {recordInt :: Int, recordMaybe :: Maybe Text} + | Single {single :: Bool} + deriving stock (Eq, Show, Generic) +instance Arbitrary Sample where + arbitrary = oneof + [ pure Nullary, Unary <$> arbitrary, Binary <$> arbitrary <*> arbitrary + , Record <$> arbitrary <*> arbitrary, Single <$> arbitrary + ] + +-- | A single constructor of a single field. +data Lone = Lone {lone :: Int} + deriving stock (Eq, Show, Generic) +instance Arbitrary Lone where arbitrary = Lone <$> arbitrary + +-- | An enumeration. +data Hue = Cyan | Magenta | Yellow + deriving stock (Eq, Show, Generic, Enum, Bounded) +instance Arbitrary Hue where arbitrary = arbitraryBoundedEnum + +-- | Options, by a type. +class Optioned o where options :: Options +data Defaults +instance Optioned Defaults where options = defaultOptions +data Untagged +instance Optioned Untagged where + options = defaultOptions {sumEncoding = UntaggedValue} +data SingleField +instance Optioned SingleField where + options = defaultOptions {sumEncoding = ObjectWithSingleField} +data TwoElements +instance Optioned TwoElements where + options = defaultOptions {sumEncoding = TwoElemArray} +data Tweaked +instance Optioned Tweaked where + options = defaultOptions + { fieldLabelModifier = camelTo2 '_' + , constructorTagModifier = map toLower + , sumEncoding = TaggedObject "kind" "value" + , allNullaryToStringTag = False + , omitNothingFields = True + , unwrapUnaryRecords = True + , tagSingleConstructors = True + } + +-- | A value, by `jsonGeneric` of options. +newtype By o a = By a + deriving stock (Eq, Show) +instance Optioned o => Json (By o Sample) where + json = coerced >~ jsonGeneric @Sample (options @o) +instance Optioned o => Json (By o Lone) where + json = coerced >~ jsonGeneric @Lone (options @o) +instance Optioned o => Json (By o Hue) where + json = coerced >~ jsonGeneric @Hue (options @o) + +-- | `jsonGeneric` agrees with @aeson@'s generic instances by options. +agreesByOptions + :: forall o a + . ( Optioned o, Json (By o a), Arbitrary a, Eq a, Show a, Generic a + , GToJSON' Value Zero (Rep a) ) + => String -> Spec +agreesByOptions title = describe title $ do + prop "prints as aeson" $ \(a :: a) -> + jsonPrint (By @o a) === genericToJSON (options @o) a + prop "encodes as aeson" $ \(a :: a) -> + decode (encodingToLazyByteString (jsonEncode (By @o a))) + === Just (genericToJSON (options @o) a) + prop "parses what aeson prints" $ \(a :: a) -> + jsonParse (genericToJSON (options @o) a) === Right (By @o a) + +jsonOptionsSpec :: Spec +jsonOptionsSpec = describe "jsonGeneric" $ do + agreesByOptions @Defaults @Sample "defaultOptions" + agreesByOptions @Untagged @Sample "UntaggedValue" + agreesByOptions @SingleField @Sample "ObjectWithSingleField" + agreesByOptions @TwoElements @Sample "TwoElemArray" + agreesByOptions @Tweaked @Sample "tweaked options" + agreesByOptions @Tweaked @Lone "a single field, tweaked" + agreesByOptions @Tweaked @Hue "an enumeration, tweaked" + agreesByOptions @Defaults @Hue "an enumeration" + it "parses an omitted field" $ + jsonParse @(By Defaults Sample) + (object ["tag" .= ("Record" :: Text), "recordInt" .= (1 :: Int)]) + `shouldBe` Right (By (Record 1 Nothing)) + +-- | The TypeScript declarations of types, as text. +tsTypes :: forall (as :: [Type]) -> All Json as => Text.Text +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)))) + (Seq.empty @Char) + +-- | The `KleeneStarAlgebra` laws of `JsonElements`. +jsonElementsSpec :: Spec +jsonElementsSpec = describe "KleeneStarAlgebra JsonElements" $ do + law "starK x = optK (plusK x)" $ \x -> (starK x, optK (plusK x)) + law "plusK x = x <> starK x" $ \x -> (plusK x, x <> starK x) + law "optK x = mempty >|< x" $ \x -> (optK x, mempty >|< x) + law "x >|< x = x" $ \x -> (x >|< x, x) + law "falseP >|< x = x" $ \x -> (falseP >|< x, x) + law "x >|< falseP = x" $ \x -> (x >|< falseP, x) + law "x >|< mempty = optK x" $ \x -> (x >|< mempty, optK x) + law "falseP <> x = falseP" $ \x -> (falseP <> x, falseP) + law "x <> falseP = falseP" $ \x -> (x <> falseP, falseP) + law "mempty <> x = x" $ \x -> (mempty <> x, x) + law "x <> mempty = x" $ \x -> (x <> mempty, x) + where + law title sides = prop title $ forAll (sized genElements) $ \x -> + let (lhs, rhs) = sides x in lhs === rhs + genElements :: Int -> Gen JsonElements + genElements = \case + 0 -> frequency + [ (1, pure falseP) + , (1, pure mempty) + , (6, JsonElement <$> elements [JsonNull, JsonBoolean, JsonNumber]) + ] + n -> frequency + [ (2, genElements 0) + , (2, (<>) <$> genElements (n `div` 2) <*> genElements (n `div` 2)) + , (2, (>|<) <$> genElements (n `div` 2) <*> genElements (n `div` 2)) + , (1, starK <$> genElements (n - 1)) + , (1, plusK <$> genElements (n - 1)) + , (1, optK <$> genElements (n - 1)) + ] diff --git a/distributors-json/test/Properties/TypeScript.hs b/distributors-json/test/Properties/TypeScript.hs new file mode 100644 index 00000000..c243a3dd --- /dev/null +++ b/distributors-json/test/Properties/TypeScript.hs @@ -0,0 +1,38 @@ +module Properties.TypeScript (typeScriptSpec) where + +import Control.Lens.Grammar (ParsecState (..), parsecG, unparsecG) +import Control.Lens.Grammar.TypeScript +import Data.Foldable (toList) +import Data.Sequence qualified as Seq +import Test.Hspec + +typeScriptSpec :: Spec +typeScriptSpec = describe "tsGrammar" $ do + it "parses a declaration file as its canonical print parses" $ do + fixture <- readFile "test/Properties/fixture.d.ts" + golden <- readFile "test/Properties/fixture.golden.d.ts" + let parsed = declarations fixture + parsed `shouldSatisfy` (/= Nothing) + parsed `shouldBe` declarations golden + it "prints a declaration file canonically" $ 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: }")) + `shouldBe` 9 + +-- | Tokens, scanned without their trivia. +tokens :: String -> [TsToken] +tokens = concat . parsecResult . parsecG tsTokensGrammar + +-- | Declarations, parsed from all of their tokens. +declarations :: String -> Maybe [TsDeclaration] +declarations text = case parsecG tsGrammar (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)))) + (Seq.empty @Char) diff --git a/distributors-json/test/Properties/fixture.d.ts b/distributors-json/test/Properties/fixture.d.ts new file mode 100644 index 00000000..9aeee14d --- /dev/null +++ b/distributors-json/test/Properties/fixture.d.ts @@ -0,0 +1,74 @@ +/// +/** A declaration file, of every kind of declaration & type. */ +import "polyfill"; +import type { A, B as C, type D } from "./types"; +import Default, * as Everything from "everything"; +import Fs = require("fs"); +import Inner = Outer.Inner; +export type Alias = + | T + | readonly U[] + | keyof T + | unique symbol; +export type Conditional = T extends (infer U extends string)[] ? U : never; +export type Mapped = { -readonly [K in keyof T as `get${string & K}`]+?: T[K] }; +export type Templated = `prefix-${number}-middle-${string}-suffix`; +export type Functions = { + (x: number, ...rest: string[]): void + new (x?: number): Functions, + method?(this: Window, { a, b: c }: T, [d, ...e]: T[]): asserts this is T; + readonly [key: string]: unknown; + get value(): number; + set value(v: number); + "quoted name": 1; + 0: -1.5; + [Symbol.iterator](): Iterator; + big: 10n; +}; +export type Tuple = [name: string, age?: number, ...rest: boolean[]]; +export type Queried = typeof globalThis.console & typeof import("module").Thing; +export type Ctor = abstract new () => object; +export type Guard = (value: unknown) => value is string; +export type Intrinsic = intrinsic; +// Interfaces & classes. +export interface Shape extends Base, Other { + readonly kind: "shape"; + area(): number; + [index: number]: T +} +export declare abstract class Circle extends Shape implements Round { + #private; + private static readonly instances: number; + protected radius: number; + constructor(radius: number); + abstract area(): number; + get diameter(): number; +} +export declare function overloaded(x: string): string; +export declare function overloaded(x: number): number; +declare const answer = 42, question: string; +declare let mutable: boolean; +export declare const enum Direction { + Up = 1, + Down = -1, + Unknown, +} +declare namespace Outer.Middle { + namespace Inner { + type Deep = "deep"; + } +} +declare module "ambient" { + export = Ambient; +} +declare module "shorthand"; +declare global { + interface Window { + extra: string; + } +} +export default Circle; +export as namespace Library; +export { A as Renamed, type B } from "./types"; +export * as Namespace from "./namespace"; +export type { Shape as Shaped }; diff --git a/distributors-json/test/Properties/fixture.golden.d.ts b/distributors-json/test/Properties/fixture.golden.d.ts new file mode 100644 index 00000000..fe1d3a7b --- /dev/null +++ b/distributors-json/test/Properties/fixture.golden.d.ts @@ -0,0 +1,56 @@ +import "polyfill"; +import type { A, B as C, type D } from "./types"; +import Default, * as Everything from "everything"; +import Fs = require("fs"); +import Inner = Outer.Inner; +export type Alias = T | readonly U[] | keyof T | unique symbol; +export type Conditional = T extends (infer U extends string)[] ? U : never; +export type Mapped = { -readonly [K in keyof T as `get${string & K}`]+?: T[K] }; +export type Templated = `prefix-${number}-middle-${string}-suffix`; +export type Functions = { (x: number, ...rest: string[]): void; new (x?: number): Functions; method?(this: Window, { a, b: c }: T, [d, ...e]: T[]): asserts this is T; readonly [key: string]: unknown; get value(): number; set value(v: number); "quoted name": 1; 0: -1.5; [Symbol.iterator](): Iterator; big: 10n }; +export type Tuple = [name: string, age?: number, ...rest: boolean[]]; +export type Queried = typeof globalThis.console & typeof import("module").Thing; +export type Ctor = abstract new () => object; +export type Guard = (value: unknown) => value is string; +export type Intrinsic = intrinsic; +export interface Shape extends Base, Other { + readonly kind: "shape"; + area(): number; + [index: number]: T; +} +export declare abstract class Circle extends Shape implements Round { + #private; + private static readonly instances: number; + protected radius: number; + constructor(radius: number); + abstract area(): number; + get diameter(): number; +} +export declare function overloaded(x: string): string; +export declare function overloaded(x: number): number; +declare const answer = 42, question: string; +declare let mutable: boolean; +export declare const enum Direction { + Up = 1, + Down = -1, + Unknown, +} +declare namespace Outer.Middle { + namespace Inner { + type Deep = "deep"; + } +} +declare module "ambient" { + export = Ambient; +} +declare module "shorthand"; +declare global { + interface Window { + extra: string; + } +} +export default Circle; +export as namespace Library; +export { A as Renamed, type B } from "./types"; +export * as Namespace from "./namespace"; +export type { Shape as Shaped }; diff --git a/flake.lock b/flake.lock new file mode 100644 index 00000000..cda0a6ba --- /dev/null +++ b/flake.lock @@ -0,0 +1,61 @@ +{ + "nodes": { + "flake-utils": { + "inputs": { + "systems": "systems" + }, + "locked": { + "lastModified": 1791914995, + "narHash": "sha256-Zf/xfQEAasnwnmEfHqW/4hjDE/s44yn2hD4RuVIZRjA=", + "owner": "numtide", + "repo": "flake-utils", + "rev": "b7a79d3fea1e214f6d668d521cecec0c01e26544", + "type": "github" + }, + "original": { + "owner": "numtide", + "repo": "flake-utils", + "type": "github" + } + }, + "nixpkgs": { + "locked": { + "lastModified": 1793826729, + "narHash": "sha256-D5H7H+qMoTGI/jJtxKP4u7BdjkFnUyhOovTrf3pTOr0=", + "owner": "NixOS", + "repo": "nixpkgs", + "rev": "6dadaf4375be35033e1c84395adbd53ff5fded96", + "type": "github" + }, + "original": { + "owner": "NixOS", + "ref": "nixpkgs-unstable", + "repo": "nixpkgs", + "type": "github" + } + }, + "root": { + "inputs": { + "flake-utils": "flake-utils", + "nixpkgs": "nixpkgs" + } + }, + "systems": { + "locked": { + "lastModified": 1681028828, + "narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=", + "owner": "nix-systems", + "repo": "default", + "rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e", + "type": "github" + }, + "original": { + "owner": "nix-systems", + "repo": "default", + "type": "github" + } + } + }, + "root": "root", + "version": 7 +} diff --git a/flake.nix b/flake.nix new file mode 100644 index 00000000..3d2e1bb2 --- /dev/null +++ b/flake.nix @@ -0,0 +1,52 @@ +{ + description = "distributors, distributors-grammar & distributors-json"; + + inputs = { + nixpkgs.url = "github:NixOS/nixpkgs/nixpkgs-unstable"; + flake-utils.url = "github:numtide/flake-utils"; + }; + + outputs = { self, nixpkgs, flake-utils }: + flake-utils.lib.eachDefaultSystem (system: + let + pkgs = nixpkgs.legacyPackages.${system}; + lib = pkgs.haskell.lib; + # nixpkgs' default GHC, whose packages are cached by cache.nixos.org + haskellPackages = pkgs.haskellPackages.override { + overrides = self: super: { + distributors = self.callCabal2nix "distributors" + ./distributors-core { }; + distributors-grammar = self.callCabal2nix "distributors-grammar" + ./distributors-grammar { }; + distributors-json = self.callCabal2nix "distributors-json" + ./distributors-json { }; + }; + }; + in + { + packages = { + distributors = haskellPackages.distributors; + distributors-grammar = haskellPackages.distributors-grammar; + distributors-json = haskellPackages.distributors-json; + default = haskellPackages.distributors-json; + }; + + checks = { + distributors = lib.doBenchmark haskellPackages.distributors; + distributors-grammar = + lib.doBenchmark haskellPackages.distributors-grammar; + distributors-json = lib.doBenchmark haskellPackages.distributors-json; + }; + + devShells.default = haskellPackages.shellFor { + packages = p: + [ p.distributors p.distributors-grammar p.distributors-json ]; + withHoogle = false; + nativeBuildInputs = [ + pkgs.cabal-install + pkgs.hlint + pkgs.hpack + ]; + }; + }); +} diff --git a/src/Control/Lens/Bifocal.hs b/src/Control/Lens/Bifocal.hs deleted file mode 100644 index 439a07ff..00000000 --- a/src/Control/Lens/Bifocal.hs +++ /dev/null @@ -1,190 +0,0 @@ -{- | -Module : Control.Lens.Bifocal -Description : bifocals -Copyright : (C) 2026 - Eitan Chatav -License : BSD-style (see the file LICENSE) -Maintainer : Eitan Chatav -Stability : provisional -Portability : non-portable --} - -module Control.Lens.Bifocal - ( -- * Bifocal - Bifocal - , ABifocal - -- * Combinators - , bifocal - , mapBifocal - , cloneBifocal - , withBifocal - -- * Binocular - , Binocular (..), runBinocular - -- * Prismoid - , Prismoid - , somed - , opted - , lefted - , righted - , chained1 - , chained - -- * Filtroid - , Filtroid - , unlefted - , unrighted - ) where - -import Control.Applicative -import Control.Lens -import Control.Lens.Internal.Profunctor -import Control.Lens.PartialIso -import Data.Profunctor -import Data.Profunctor.Distributor -import Data.Profunctor.Filtrator -import Data.Profunctor.Separator -import Witherable - -{- | `Bifocal`s are bidirectional parser optics. - -Every one of the following is a `Bifocal`. - -* `Control.Lens.Iso.Iso` -* `Control.Lens.Prism.Prism` -* `Control.Lens.Monocle.Monocle` -* `Control.Lens.Diopter.Diopter` -* `Prismoid` & `Filtroid` - -`Bifocal`s are isomorphic to `Binocular`s. --} -type Bifocal s t a b = forall p f. - (Alternator p, Filtrator p, Alternative f, Filterable f) - => p a (f b) -> p s (f t) - -{- | `ABifocal` is monomorphically a `Bifocal`. -} -type ABifocal s t a b = - Binocular a b a (Maybe b) -> Binocular a b s (Maybe t) - -{- | `Prismoid`s generalize `Bifocal`s, combining -`Control.Lens.Prism.Prism`s and `Control.Lens.Diopter.Diopter`s. -} -type Prismoid s t a b = forall p f. - (Alternator p, Alternative f) - => p a (f b) -> p s (f t) - -{- | An optic for `Filtrator`s, `Filtroid`s generalize `Bifocal`s. -} -type Filtroid s t a b = forall p f. - (Filtrator p, Filterable f) - => p a (f b) -> p s (f t) - -{- | Build a `Bifocal` from a concrete `Binocular`. -} -bifocal :: Binocular a b s t -> Bifocal s t a b -bifocal bif = unwrapPafb . runBinocular bif . WrapPafb - -{- | Action of `ABifocal` on partial `Distributor`s. -} -mapBifocal - :: (Alternator p, Filtrator p) - => ABifocal s t a b -> p a b -> p s t -mapBifocal bif p = withBifocal bif $ \f -> dimapMaybe f Just p - -{- | Clone `ABifocal` so that you can reuse the same -monomorphically typed `Bifocal` for different purposes. --} -cloneBifocal :: ABifocal s t a b -> Bifocal s t a b -cloneBifocal bif = unwrapPafb . mapBifocal bif . WrapPafb - -{- | One or more. -} -somed :: Prismoid [a] [b] a b -somed = unwrapPafb . someP . WrapPafb - -{- | One or zero with default. -} -opted :: APrism a b () () -> Prismoid a b a b -opted def = unwrapPafb . optionP def . WrapPafb - -{- | `lefted` is like `_Left`, except -with heterogeneous `Right` parameters. -} -lefted :: Prismoid (Either a c) (Either b d) a b -lefted = unwrapPafb . alternate . Left . WrapPafb - - -{- | `righted` is like `_Right`, except -with heterogeneous `Left` parameters. -} -righted :: Prismoid (Either c a) (Either d b) a b -righted = unwrapPafb . alternate . Right . WrapPafb - -{- | Dual to `lefted`. -} -unlefted :: Filtroid a b (Either a c) (Either b d) -unlefted = unwrapPafb . fst . filtrate . WrapPafb - -{- | Dual to `righted`. -} -unrighted :: Filtroid a b (Either c a) (Either d b) -unrighted = unwrapPafb . snd . filtrate . WrapPafb - -{- | -Associate a binary constructor pattern to sequence one or more times. --} -chained1 - :: (forall x. x -> Either x x) - -> APartialIso a b (a,a) (b,b) - -> Prismoid a b a b -chained1 assoc binPat = unwrapPafb . chain1 assoc binPat noSep . WrapPafb - -{- | -Associate a binary constructor pattern to sequence one or more times, -or use a nilary constructor pattern to sequence zero times. --} -chained - :: (forall x. x -> Either x x) - -> APartialIso a b (a,a) (b,b) - -> APrism a b () () - -> Prismoid a b a b -chained assoc binPat nilPat = unwrapPafb . chain assoc binPat nilPat noSep . WrapPafb - -{- | Run `ABifocal` over an `Alternative` & `Filterable`. -} -withBifocal - :: (Alternative f, Filterable f) - => ABifocal s t a b -> ((s -> Maybe a) -> f b) -> f t -withBifocal bif = unBinocular (catMaybes (bif (Just <$> Binocular ($ Just)))) - -{- | `Binocular` provides an efficient -concrete representation of `Bifocal`s. -} -newtype Binocular a b s t = Binocular - { unBinocular - :: forall f. (Alternative f, Filterable f) - => ((s -> Maybe a) -> f b) -> f t - } -instance Profunctor (Binocular a b) where - dimap f g (Binocular k) = Binocular $ fmap g . k . (. (. f)) -instance Functor (Binocular a b s) where fmap = rmap -instance Applicative (Binocular a b s) where - pure t = Binocular (pure (pure t)) - Binocular x <*> Binocular y = Binocular (liftA2 (<*>) x y) -instance Alternative (Binocular a b s) where - empty = Binocular (pure empty) - Binocular x <|> Binocular y = Binocular (liftA2 (<|>) x y) -instance Filterable (Binocular a b s) where - mapMaybe f (Binocular k) = Binocular (mapMaybe f . k) - catMaybes (Binocular k) = Binocular (catMaybes . k) -instance Choice (Binocular a b) where - left' (Binocular k) - = Binocular $ fmap Left - . k . (. (\f -> either f (const Nothing))) - right' (Binocular k) - = Binocular $ fmap Right - . k . (. (\f -> either (const Nothing) f)) -instance Cochoice (Binocular a b) where - unleft (Binocular k) - = Binocular $ catMaybes - . fmap (either Just (const Nothing)) - . k . (. (. Left)) - unright (Binocular k) - = Binocular $ catMaybes - . fmap (either (const Nothing) Just) - . k . (. (. Right)) -instance Distributor (Binocular a b) -instance Alternator (Binocular a b) -instance Filtrator (Binocular a b) - -{- | Run a `Binocular` on a partial `Distributor`. -} -runBinocular - :: (Alternator p, Filtrator p) - => Binocular a b s t - -> p a b -> p s t -runBinocular (Binocular k) p = k $ \f -> dimapMaybe f Just p diff --git a/src/Control/Lens/Diopter.hs b/src/Control/Lens/Diopter.hs deleted file mode 100644 index 231209fd..00000000 --- a/src/Control/Lens/Diopter.hs +++ /dev/null @@ -1,125 +0,0 @@ -{- | -Module : Control.Lens.Diopter -Description : diopters -Copyright : (C) 2026 - Eitan Chatav -License : BSD-style (see the file LICENSE) -Maintainer : Eitan Chatav -Stability : provisional -Portability : non-portable --} - -module Control.Lens.Diopter - ( -- * Diopter - Diopter - , ADiopter - -- * Combinators - , diopter - , withDiopter - , cloneDiopter - , mapDiopter - , optioned - , manied - , homogenized - -- * Dioptrice - , Dioptrice (..), runDioptrice - ) where - -import Control.Lens -import Control.Lens.Internal.Profunctor -import Data.Profunctor.Distributor -import Data.Traversable.Homogeneous -import Data.Void -import GHC.Generics - -{- | `Diopter`s are an optic that generalizes -`Control.Lens.Bifocal.Bifocal`s and `Control.Lens.Traversal.Traversal`s. - -Every `Control.Lens.Iso.Iso` and `Control.Lens.Monocle` is a `Diopter`. - -`Diopter`s are isomorphic to `Dioptrice`s. --} -type Diopter s t a b = forall p f. - (Distributor p, Applicative f) - => p a (f b) -> p s (f t) - -{- | `ADiopter` is monomorphically a `Diopter`. -} -type ADiopter s t a b = - Dioptrice a b a (Identity b) -> Dioptrice a b s (Identity t) - -{- | Build a `Diopter`. -} -diopter :: Homogeneous h => (s -> h a) -> (h b -> t) -> Diopter s t a b -diopter f g = unwrapPafb . runDioptrice (Dioptrice f g) . WrapPafb - -{- | Convert `ADiopter` to the pair of functions that characterize it. -} -withDiopter - :: ADiopter s t a b - -> (forall h. Homogeneous h => (s -> h a) -> (h b -> t) -> r) - -> r -withDiopter dio k = case runIdentity <$> dio (Identity <$> Dioptrice Par1 unPar1) of - Dioptrice f g -> k f g - -{- | Action of `ADiopter` on `Distributor`s. -} -mapDiopter :: Distributor p => ADiopter s t a b -> p a b -> p s t -mapDiopter dio = withDiopter dio $ \f g -> dimap f g . homogeneously - -{- | Clone `ADiopter` so that you can reuse the same -monomorphically typed `Diopter` for different purposes. --} -cloneDiopter :: ADiopter s t a b -> Diopter s t a b -cloneDiopter dio = withDiopter dio diopter - -{- | One or none. -} -optioned :: Diopter (Maybe a) (Maybe b) a b -optioned = unwrapPafb . optionalP . WrapPafb - -{- | Zero or more. -} -manied :: Diopter [a] [b] a b -manied = unwrapPafb . manyP . WrapPafb - -{- | Build a `Diopter` from a `Homogeneous` -countable sum of countable products. - -prop> traverse = homogenized -prop> homogenized = ditraversed --} -homogenized :: Homogeneous t => Diopter (t a) (t b) a b -homogenized = unwrapPafb . homogeneously . WrapPafb - -{- | A `Dioptrice` provides efficient access -to some pair of functions that make up a `Diopter`. --} -data Dioptrice a b s t where - Dioptrice - :: Homogeneous h - => (s -> h a) - -> (h b -> t) - -> Dioptrice a b s t -instance Profunctor (Dioptrice a b) where - dimap f g (Dioptrice sa bt) = Dioptrice (sa . f) (g . bt) -instance Functor (Dioptrice a b s) where fmap = rmap -instance Applicative (Dioptrice a b s) where - pure t = Dioptrice (const U1) (const t) - Dioptrice fx gx <*> Dioptrice fy gy = Dioptrice - (\s -> fx s :*: fy s) - (\(h :*: g) -> gx h (gy g)) -instance Distributor (Dioptrice a b) where - zeroP = Dioptrice absurd ridiculous - where - ridiculous :: V1 b -> x - ridiculous = (\case) - Dioptrice fx gx >+< Dioptrice fy gy = Dioptrice - (either (L1 . fx) (R1 . fy)) - (\case {L1 h -> Left (gx h); R1 j -> Right (gy j)}) - optionalP (Dioptrice f g) = Dioptrice - (Comp1 . fmap f) - (fmap g . unComp1) - manyP (Dioptrice f g) = Dioptrice - (Comp1 . fmap f) - (fmap g . unComp1) - -{- | Run a `Dioptrice` on a `Distributor`. -} -runDioptrice - :: Distributor p - => Dioptrice a b s t - -> p a b -> p s t -runDioptrice (Dioptrice f g) = dimap f g . homogeneously diff --git a/src/Control/Lens/Grammar/Boole.hs b/src/Control/Lens/Grammar/Boole.hs deleted file mode 100644 index 96bf8c7c..00000000 --- a/src/Control/Lens/Grammar/Boole.hs +++ /dev/null @@ -1,80 +0,0 @@ -{- | -Module : Control.Lens.Grammar.Boole -Description : Boolean algebras -Copyright : (C) 2026 - Eitan Chatav -License : BSD-style (see the file LICENSE) -Maintainer : Eitan Chatav -Stability : provisional -Portability : non-portable - -See Boole, [The Mathematical Analysis of Logic] -(https://www.gutenberg.org/files/36884/36884-pdf.pdf). --} - -module Control.Lens.Grammar.Boole - ( -- * BooleanAlgebra - BooleanAlgebra (..) - , andB, orB, allB, anyB - ) where - -import Data.Monoid - --- | A `BooleanAlgebra`, like `Bool`, supporting classical logical operations. -class BooleanAlgebra b where - - -- | conjunction - (>&&<) :: b -> b -> b - default (>&&<) - :: (b ~ f bool, BooleanAlgebra bool, Applicative f) => b -> b -> b - (>&&<) = liftA2 (>&&<) - - -- | disjunction - (>||<) :: b -> b -> b - default (>||<) - :: (b ~ f bool, BooleanAlgebra bool, Applicative f) => b -> b -> b - (>||<) = liftA2 (>||<) - - -- | negation - notB :: b -> b - default notB - :: (b ~ f bool, BooleanAlgebra bool, Functor f) => b -> b - notB = fmap notB - - -- | true - trueB :: b - default trueB - :: (b ~ f bool, BooleanAlgebra bool, Applicative f) => b - trueB = pure trueB - - -- | false - falseB :: b - default falseB - :: (b ~ f bool, BooleanAlgebra bool, Applicative f) => b - falseB = pure falseB - --- | cumulative conjunction -andB :: (Foldable f, BooleanAlgebra b) => f b -> b -andB = foldl' (>&&<) trueB - --- | cumulative disjunction -orB :: (Foldable f, BooleanAlgebra b) => f b -> b -orB = foldl' (>||<) falseB - --- | universal -allB :: (Foldable f, BooleanAlgebra b) => (a -> b) -> f a -> b -allB f = foldl' (\b a -> b >&&< f a) trueB - --- | existential -anyB :: (Foldable f, BooleanAlgebra b) => (a -> b) -> f a -> b -anyB f = foldl' (\b a -> b >||< f a) falseB - ---instances -instance BooleanAlgebra (x -> Bool) -instance (Applicative f, BooleanAlgebra bool) - => BooleanAlgebra (Ap f bool) -instance BooleanAlgebra Bool where - falseB = False - trueB = True - notB = not - (>&&<) = (&&) - (>||<) = (||) diff --git a/src/Control/Lens/Grammar/Kleene.hs b/src/Control/Lens/Grammar/Kleene.hs deleted file mode 100644 index 78a0ae01..00000000 --- a/src/Control/Lens/Grammar/Kleene.hs +++ /dev/null @@ -1,437 +0,0 @@ -{- | -Module : Control.Lens.Grammar.Kleene -Description : Kleene star algebras, regular expressions & token classes -Copyright : (C) 2026 - Eitan Chatav -License : BSD-style (see the file LICENSE) -Maintainer : Eitan Chatav -Stability : provisional -Portability : non-portable - -Regular expressions form a Kleene star algebra. See Kleene, -[Representation of Events in Nerve Nets and Finite Automata] -(https://www.rand.org/pubs/research_memoranda/RM704.html) --} - -module Control.Lens.Grammar.Kleene - ( -- * KleeneStarAlgebra - KleeneStarAlgebra (..) - , orK, anyK - -- * TokenAlgebra - , TokenAlgebra (..) - -- * RegEx & TokenClass - , RegEx (..) - , TokenClass (..) - , RegExam (..) - , CategoryTest (..) - ) where - -import Control.Applicative -import Control.Lens.Grammar.Boole -import Control.Lens.Grammar.Symbol -import Control.Lens.Grammar.Token -import Control.Monad.Loops -import Control.Monad.State (StateT, state) -import Data.Bifunctor.Joker -import Data.Foldable -import Data.MemoTrie -import Data.Monoid -import Data.Profunctor -import Data.Profunctor.Distributor -import Data.Set (Set) -import qualified Data.Set as Set -import GHC.Generics -import System.Random (RandomGen, Random, random) -import Test.QuickCheck.Arbitrary -import Test.QuickCheck.Gen (Gen) -import qualified Test.QuickCheck.Gen as Gen -import Text.ParserCombinators.ReadP (ReadP) -import qualified Text.ParserCombinators.ReadP as ReadP - -{- | A `KleeneStarAlgebra` is a semiring -with a generally non-commutative multiplication, -the `Monoid` concatenation operator `<>` with identity `mempty`; -and an idempotent addition, the alternation operator `>|<` -with identity `zeroK`. - -prop> x >|< x = x -prop> zeroK >|< x = x = x >|< zeroK -prop> zeroK <> x = zeroK = x <> zeroK -prop> mempty <> x = x = x <> mempty - -It also has three unary Kleene quantifier operators; - -* `optK`, zero or one, - -prop> optK x = mempty >|< x = x >|< mempty - -* `plusK`, one or more, - -prop> plusK x = x <> starK x = starK x <> x - -* and the eponymous `starK`, zero or more. - -prop> starK x = optK (plusK x) - --} -class Monoid k => KleeneStarAlgebra k where - starK, plusK, optK :: k -> k - starK x = optK (plusK x) - plusK x = x <> starK x - optK x = mempty >|< x - infixl 3 >|< - (>|<) :: k -> k -> k - zeroK :: k - default (>|<) :: (k ~ f a, Alternative f) => k -> k -> k - default zeroK :: (k ~ f a, Alternative f) => k - (>|<) = (<|>) - zeroK = empty - --- | cumulative alternation -orK :: (Foldable f, KleeneStarAlgebra k) => f k -> k -orK = foldl' (>|<) zeroK - --- | existential -anyK :: (Foldable f, KleeneStarAlgebra k) => (a -> k) -> f a -> k -anyK f = foldl' (\b a -> b >|< f a) zeroK - -{- | The `RegEx`pression type forms the prototypical `KleeneStarAlgebra`. -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. --} -data RegEx token - = SeqEmpty - | Sequence (RegEx token) (RegEx token) - | NonTerminal String - | KleeneStar (RegEx token) - | KleeneOpt (RegEx token) - | KleenePlus (RegEx token) - | RegExam (RegExam token (RegEx token)) - -{- | Both `RegEx`pressions and `TokenClass`es are algebras over the t`RegExam` endo-`Functor`. -`TokenClass` is the fixed point of t`RegExam`. --} -data RegExam token alg - = OneOf (Set token) - | NotOneOf (Set token) (CategoryTest token) - | Alternate alg alg - -failExam :: RegExam token alg -failExam = OneOf Set.empty - -passExam :: RegExam token alg -passExam = NotOneOf Set.empty (AndNotAsIn Set.empty) - -isFailExam :: RegExam token alg -> Bool -isFailExam (OneOf xs) = Set.null xs -isFailExam _ = False - -isPassExam :: RegExam token alg -> Bool -isPassExam (NotOneOf xs (AndNotAsIn ys)) = Set.null xs && Set.null ys -isPassExam _ = 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)) - -{- | `TokenClass` forms a `Tokenized` `BooleanAlgebra`, -such that the following invariants hold. - -prop> trueB = anyToken -prop> trueB = notOneOf [] -prop> falseB = oneOf [] -prop> notB . oneOf = notOneOf -prop> notB . notOneOf = oneOf -prop> notB . asIn = notAsIn -prop> notB . notAsIn = asIn - -`TokenClass` is the fixed point algebra of t`RegExam`. -`TokenClass`es may be understood as normalizations of -`BooleanAlgebra` expressions generated by `Tokenized` -expressions. --} -newtype TokenClass token = TokenClass (RegExam token (TokenClass token)) - -{- | `TokenAlgebra` extends `Tokenized` methods to support -`BooleanAlgebra` operations within a `tokenClass`. -When a `TokenAlgebra` is an `Alternative`, -then `tokenClass` is expected to act homomorphically on disjunction. - -prop> empty = tokenClass falseB -prop> tokenClass x <|> tokenClass y = tokenClass (x >||< y) - -Likewise, when a `TokenAlgebra` is a `KleeneStarAlgebra`, -then `tokenClass` is expected to act homorphically on disjunction. - -prop> zeroK = tokenClass falseB -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 - tokenClass (TokenClass exam) = case exam of - OneOf chars -> oneOf chars - NotOneOf chars (AndAsIn cat) -> - satisfy (notOneOf chars >&&< asIn cat) - NotOneOf chars (AndNotAsIn cats) -> - satisfy (notOneOf chars >&&< allB notAsIn cats) - Alternate exam1 exam2 -> tokenClass exam1 <|> tokenClass exam2 - ---instances -instance (Alternative f, Monoid k) => KleeneStarAlgebra (Ap f k) -deriving stock instance Generic (RegEx token) -deriving stock instance Generic (RegExam token alg) -deriving stock instance Generic1 (RegExam token) -deriving stock instance Generic (TokenClass token) -deriving stock instance Generic (CategoryTest 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)) - => Read (RegEx token) -deriving stock instance - (Categorized token, Show token, Show (Categorize token)) - => Show (RegEx 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 => BooleanAlgebra (TokenClass token) -instance Categorized token - => TokenAlgebra token (TokenClass token) where - tokenClass = id -instance Categorized token - => TokenAlgebra token (RegExam token (TokenClass token)) where - tokenClass (TokenClass exam) = exam -instance Categorized 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 passExam - 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 (token -> Bool) where - tokenClass (TokenClass exam) x = case exam of - 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 exam1 exam2 -> - tokenClass exam1 x || tokenClass exam2 x -instance Categorized token => TokenAlgebra token (RegEx token) where - tokenClass (TokenClass exam) = case exam of - OneOf as -> RegExam (OneOf as) - NotOneOf as catTest -> RegExam (NotOneOf as catTest) - Alternate exam1 exam2 -> - RegExam (Alternate (tokenClass exam1) (tokenClass exam2)) -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 (Categorized token, Arbitrary token) => TokenAlgebra token (Gen token) where - tokenClass (TokenClass exam) = case exam of - 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 cls1 cls2 -> Gen.oneof [tokenClass cls1, tokenClass cls2] -instance (RandomGen g, Monad m, Categorized token, Random token) - => TokenAlgebra token (StateT g m token) where - tokenClass (TokenClass exam) = case exam of - 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 cls1 cls2 -> do - b <- state random - if (b :: Bool) then tokenClass cls1 else tokenClass cls2 -instance Categorized token => Monoid (RegEx token) where - mempty = SeqEmpty -instance Categorized token => Semigroup (RegEx token) where - SeqEmpty <> rex = rex - rex <> SeqEmpty = rex - RegExam exam <> _ | isFailExam exam = zeroK - _ <> RegExam exam | isFailExam exam = zeroK - KleeneStar rex0 <> rex1 | rex0 == rex1 = plusK rex0 - rex0 <> KleeneStar rex1 | rex0 == rex1 = plusK rex1 - rex0 <> rex1 = Sequence rex0 rex1 -instance Categorized token => KleeneStarAlgebra (RegEx token) where - zeroK = RegExam failExam - optK (RegExam exam) | isFailExam exam = mempty - optK SeqEmpty = mempty - optK (KleenePlus rex) = starK rex - optK rex = KleeneOpt rex - starK (RegExam exam) | isFailExam exam = mempty - starK SeqEmpty = mempty - starK rex = KleeneStar rex - plusK (RegExam exam) | isFailExam exam = zeroK - plusK SeqEmpty = mempty - plusK rex = KleenePlus rex - rex0 >|< rex1 | rex0 == rex1 = rex0 - KleenePlus rex >|< SeqEmpty = starK rex - SeqEmpty >|< KleenePlus rex = starK rex - rex >|< SeqEmpty = optK rex - SeqEmpty >|< rex = optK rex - rex >|< RegExam exam | isFailExam exam = rex - RegExam exam >|< rex | isFailExam exam = rex - rex0 >|< rex1 | Just tokenOr <- maybeOr = tokenClass tokenOr - where - toTokenClass (RegExam exam) = - TokenClass <$> traverse toTokenClass exam - toTokenClass _ = Nothing - maybeOr = (>||<) <$> toTokenClass rex0 <*> toTokenClass rex1 - rex0 >|< rex1 = RegExam (Alternate rex0 rex1) -instance Categorized token => Tokenized token (RegExam 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 - => BooleanAlgebra (RegExam token (TokenClass token)) where - falseB = failExam - trueB = passExam - notB exam | isFailExam exam = passExam - notB exam | isPassExam exam = failExam - notB (Alternate (TokenClass x) (TokenClass y)) = notB x >&&< notB y - notB (OneOf xs) = notOneOf xs - notB (NotOneOf xs (AndAsIn y)) = oneOf xs >||< notAsIn y - notB (NotOneOf xs (AndNotAsIn ys)) = oneOf xs >||< anyB 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 (TokenClass y) (TokenClass z) = (x >&&< y) >||< (x >&&< z) - Alternate (TokenClass x) (TokenClass y) >&&< z = (x >&&< z) >||< (y >&&< z) - 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) - x >||< y | x == y = x - x >||< exam | isFailExam exam = x - exam >||< y | isFailExam exam = y - _ >||< exam | isPassExam exam = passExam - exam >||< _ | isPassExam exam = passExam - OneOf xs >||< OneOf ys = oneOf (Set.union xs ys) - x >||< y = Alternate (TokenClass x) (TokenClass y) -deriving stock instance - (Categorized token, Read token, Read alg, Read (Categorize token)) - => Read (RegExam token alg) -deriving stock instance - (Categorized token, Show token, Show alg, Show (Categorize token)) - => Show (RegExam token alg) -deriving stock instance Functor (RegExam token) -deriving stock instance Foldable (RegExam token) -deriving stock instance Traversable (RegExam token) -deriving stock instance (Categorized token, Eq alg) => Eq (RegExam token alg) -deriving stock instance (Categorized token, Ord alg) => Ord (RegExam 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) -instance (Categorized token, HasTrie token) - => HasTrie (RegEx token) where - data (RegEx token :->: b) = RegExTrie - { seqEmptyTrie :: b - , nonTerminalTrie :: String :->: b - , sequenceTrie :: (RegEx token, RegEx token) :->: b - , alternateTrie :: (RegEx token, RegEx token) :->: b - , kleeneStarTrie :: RegEx token :->: b - , kleeneOptTrie :: RegEx token :->: b - , kleenePlusTrie :: RegEx token :->: b - , oneOfTrie :: [token] :->: b - , notOneOfTrie :: ([token], Either Int [Int]) :->: b - } - trie f = RegExTrie - { seqEmptyTrie = f mempty - , nonTerminalTrie = trie (f . nonTerminal) - , sequenceTrie = trie (f . uncurry (<>)) - , alternateTrie = trie (f . uncurry (>|<)) - , kleeneStarTrie = trie (f . starK) - , kleeneOptTrie = trie (f . optK) - , kleenePlusTrie = trie (f . plusK) - , oneOfTrie = trie (f . oneOf) - , notOneOfTrie = trie (f . testNotOneOf) - } - untrie rex = \case - SeqEmpty -> seqEmptyTrie rex - NonTerminal name -> untrie (nonTerminalTrie rex) name - Sequence x1 x2 -> untrie (sequenceTrie rex) (x1,x2) - KleeneStar x -> untrie (kleeneStarTrie rex) x - KleenePlus x -> untrie (kleenePlusTrie rex) x - KleeneOpt x -> untrie (kleeneOptTrie 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)) - RegExam (NotOneOf chars (AndNotAsIn cats)) -> - untrie (notOneOfTrie rex) - (Set.toList chars, Right (Set.toList (Set.map fromEnum cats))) - RegExam (Alternate x1 x2) -> untrie (alternateTrie rex) (x1,x2) - enumerate rex = mconcat - [ [(SeqEmpty, seqEmptyTrie rex)] - , first' NonTerminal <$> enumerate (nonTerminalTrie rex) - , first' (uncurry Sequence) <$> enumerate (sequenceTrie rex) - , first' (RegExam . uncurry Alternate) <$> enumerate (alternateTrie rex) - , first' KleeneStar <$> enumerate (kleeneStarTrie rex) - , first' KleeneOpt <$> enumerate (kleeneOptTrie rex) - , first' KleenePlus <$> enumerate (kleenePlusTrie 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) diff --git a/src/Control/Lens/Grammar/Token.hs b/src/Control/Lens/Grammar/Token.hs deleted file mode 100644 index 5ad21da5..00000000 --- a/src/Control/Lens/Grammar/Token.hs +++ /dev/null @@ -1,164 +0,0 @@ -{- | -Module : Control.Lens.Grammar.Token -Description : lexical tokens -Copyright : (C) 2026 - Eitan Chatav -License : BSD-style (see the file LICENSE) -Maintainer : Eitan Chatav -Stability : provisional -Portability : non-portable --} - -module Control.Lens.Grammar.Token - ( -- * Tokenized - Tokenized (..) - , satisfy - , tokens - -- * Categorized - , Categorized (..) - , GeneralCategory (..) - ) where - -import Control.Lens -import Control.Lens.PartialIso -import Control.Monad.Loops (iterateUntil) -import Data.Bifunctor.Joker -import Data.Char -import Data.Foldable -import Data.Profunctor -import Data.Profunctor.Monoidal -import Data.Word -import Control.Monad.State (StateT, state) -import System.Random (RandomGen, Random, random, randomR) -import Test.QuickCheck.Arbitrary -import Test.QuickCheck.Gen (Gen) -import qualified Test.QuickCheck.Gen as Gen -import Text.ParserCombinators.ReadP (ReadP) -import qualified Text.ParserCombinators.ReadP as ReadP - -{- | `Categorized` provides a type family `Categorize` -and a function to `categorize` tokens into disjoint categories. - ->>> :kind! Categorize Char -Categorize Char :: * -= GeneralCategory - ->>> categorize 'a' -LowercaseLetter --} -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. -} - anyToken :: p - - {- | A single specified `token`. -} - token :: token -> p - 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 - 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> anyToken = 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 - - {- | 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 >?< anyToken - -{- | A specified stream of `tokens`. -} -tokens - :: ( Foldable f, Tokenized a (p a a) - , Monoidal p, Choice p - , AsEmpty s, Cons s s a a - ) - => f a -> p s s -tokens = foldr ((>:<) . token) asEmpty - --- instances -instance Categorized token => Tokenized token (token -> Bool) where - anyToken _ = True - token = (==) - oneOf = flip elem - notOneOf = flip notElem - asIn = lmap categorize . (==) - notAsIn = lmap categorize . (/=) -instance Tokenized token (f token) - => Tokenized token (Joker f token token) where - anyToken = Joker (anyToken @token) - token = Joker . token @token - oneOf = Joker . oneOf @token - notOneOf = Joker . notOneOf @token - asIn = Joker . asIn @token - notAsIn = Joker . notAsIn @token -instance Tokenized Char (ReadP Char) where - anyToken = ReadP.get - token = ReadP.char - oneOf = ReadP.satisfy . oneOf - notOneOf = ReadP.satisfy . notOneOf - asIn = ReadP.satisfy . asIn - notAsIn = ReadP.satisfy . notAsIn -instance (Categorized token, Arbitrary token) => Tokenized token (Gen token) where - anyToken = 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) -instance (RandomGen g, Monad m, Categorized token, Random token) - => Tokenized token (StateT g m token) where - 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 diff --git a/src/Control/Lens/Monocle.hs b/src/Control/Lens/Monocle.hs deleted file mode 100644 index da093f78..00000000 --- a/src/Control/Lens/Monocle.hs +++ /dev/null @@ -1,105 +0,0 @@ -{- | -Module : Control.Lens.Monocle -Description : monocles -Copyright : (C) 2026 - Eitan Chatav -License : BSD-style (see the file LICENSE) -Maintainer : Eitan Chatav -Stability : provisional -Portability : non-portable - -See Oliveira, Jaskelioff & de Melo, -[On Structuring Functional Programs with Monoidal Profunctors](https://arxiv.org/abs/2207.00852) --} - -module Control.Lens.Monocle - ( -- * Monocle - Monocle - , AMonocle - -- * Combinators - , monocle - , withMonocle - , cloneMonocle - , imprism - , mapMonocle - , ditraversed - , forevered - -- * Monocular - , Monocular (..), runMonocular - ) where - -import Control.Lens hiding (Traversing) -import Control.Lens.Internal.Profunctor -import Data.Distributive -import Data.Profunctor.Monoidal - -{- | `Monocle`s are an optic that generalizes -`Control.Lens.Traversal.Traversal`s & `Control.Lens.Grate.Grate`s. - -Every `Control.Lens.Iso.Iso` is a `Monocle`. - -`Monocle`s are isomorphic to `Monocular`s. --} -type Monocle s t a b = forall p f. - (Monoidal p, Applicative f) - => p a (f b) -> p s (f t) - -{- | `AMonocle` is monomorphically a `Monocle`. -} -type AMonocle s t a b = - Monocular a b a (Identity b) -> Monocular a b s (Identity t) - -{- | Build a `Monocle` from a concrete `Monocular`. -} -monocle :: Monocular a b s t -> Monocle s t a b -monocle mon = unwrapPafb . runMonocular mon . WrapPafb - -{- | Action of `AMonocle` on `Monoidal` `Profunctor`s. -} -mapMonocle :: Monoidal p => AMonocle s t a b -> p a b -> p s t -mapMonocle mon p = withMonocle mon $ \f -> lmap f p - -{- | Clone `AMonocle` so that you can reuse the same -monomorphically typed `Monocle` for different purposes. --} -cloneMonocle :: AMonocle s t a b -> Monocle s t a b -cloneMonocle mon = unwrapPafb . mapMonocle mon . WrapPafb - -{- | Convert a `Monocle` to an improper `Control.Lens.Prism.Prism`. - ->>> review (imprism ditraversed) 1 :: Complex Int -1 :+ 1 ->>> preview (imprism ditraversed) (1 :+ 2 :: Complex Int) -Just 1 --} -imprism :: Monocle s t a b -> Prism s t a b -imprism mon = clonePrism mon - -{- | Build a `Monocle` from a `Traversable` & `Distributive`, -homogeneous, countable product. - -prop> traverse = ditraversed -prop> cotraversed = ditraversed --} -ditraversed :: (Traversable g, Distributive g) => Monocle (g a) (g b) a b -ditraversed = unwrapPafb . ditraverse . WrapPafb - -{- | Repeat action indefinitely. -} -forevered :: Monocle s t () b -forevered = unwrapPafb . foreverP . WrapPafb - -{- | Run `AMonocle` over an `Applicative`. -} -withMonocle :: Applicative f => AMonocle s t a b -> ((s -> a) -> f b) -> f t -withMonocle mon = unMonocular (runIdentity <$> mon (Identity <$> Monocular ($ id))) - -{- | `Monocular` provides an efficient -concrete representation of `Monocle`s. -} -newtype Monocular a b s t = Monocular - {unMonocular :: forall f. Applicative f => ((s -> a) -> f b) -> f t} -instance Profunctor (Monocular a b) where - dimap f g (Monocular k) = - Monocular (fmap g . k . (. (. f))) -instance Functor (Monocular a b s) where fmap = rmap -instance Applicative (Monocular a b s) where - pure t = Monocular (pure (pure t)) - Monocular x <*> Monocular y = Monocular (liftA2 (<*>) x y) - -{- | Run a `Monocular` on a `Monoidal` `Profunctor`. -} -runMonocular :: Monoidal p => Monocular a b s t -> p a b -> p s t -runMonocular (Monocular k) p = k $ \f -> lmap f p diff --git a/src/Control/Lens/PartialIso.hs b/src/Control/Lens/PartialIso.hs deleted file mode 100644 index a93dda6d..00000000 --- a/src/Control/Lens/PartialIso.hs +++ /dev/null @@ -1,331 +0,0 @@ -{- | -Module : Control.Lens.PartialIso -Description : partial isomorphisms -Copyright : (C) 2026 - Eitan Chatav -License : BSD-style (see the file LICENSE) -Maintainer : Eitan Chatav -Stability : provisional -Portability : non-portable - -See Rendel & Ostermann, -[Invertible syntax descriptions](https://www.informatik.uni-marburg.de/~rendel/unparse/) --} - -module Control.Lens.PartialIso - ( -- * PartialIso - dimapMaybe - , PartialIso - , PartialIso' - , APartialIso - , PartialExchange (PartialExchange) - -- * Combinators - , partialIso - , partialInvoluted - , withPartialIso - , clonePartialIso - , coPartialIso - , crossPartialIso - , altPartialIso - -- * Applicators - , (>?) - , (?<) - , (>?<) - , (>~) - , (~<) - , coPrism - -- * Patterns - , satisfied - , nulled - , notNulled - , eotMaybe - , eotList - -- * Iterators - , iterating - , difoldl1 - , difoldr1 - , difoldl - , difoldr - -- * Template Haskell - , makeNestedPrisms - -- * Re-exports - , module Control.Lens.Iso - , module Control.Lens.Prism - ) where - -import Control.Lens -import Control.Lens.Grammar.Internal.Orphanage () -import Control.Lens.Grammar.Internal.NestedPrismTH -import Control.Lens.Internal.Profunctor -import Control.Lens.Iso -import Control.Lens.Prism -import Control.Monad -import Data.Profunctor -import Witherable - -{- | The `dimapMaybe` function endows -`Choice` & `Cochoice` "partial profunctors" -with an action `>?<` of `PartialIso`s. --} -dimapMaybe - :: (Choice p, Cochoice p) - => (s -> Maybe a) -> (b -> Maybe t) - -> p a b -> p s t -dimapMaybe f g = - let - m2e h = maybe (Left ()) Right . h - fg = dimap (>>= m2e f) (>>= m2e g) - in - unright . fg . right' - -{- | `PartialIso` is a first class inexhaustive pattern, -similar to how `Control.Lens.Prism.Prism` is a first class exhaustive pattern, -by combining `Control.Lens.Prism.Prism`s and `coPrism`s. - -Every `Control.Lens.Iso.Iso` & `Control.Lens.Prism.Prism` is `APartialIso`. - -`PartialIso`s are isomorphic to `PartialExchange`s. --} -type PartialIso s t a b = forall p f. - (Choice p, Cochoice p, Applicative f, Filterable f) - => p a (f b) -> p s (f t) - -{- | -A simple `PartialIso'` @s a@ is an identification of -a subset of @s@ with a subset of @a@. - -Given a simple `PartialIso'`, @partialIso f g@, has properties: - -prop> Just = f <=< g -prop> Just = g <=< f - -These are left and right inverse laws for proper `PartialIso'`s. -However, sometimes an improper `PartialIso'` will be useful. -For an improper `PartialIso'`, only the left inverse law holds. - -prop> Just = f <=< g - -For an improper `PartialIso'`, @norm = g <=< f@ is an idempotent - -prop> norm = norm <=< norm - -and can be regarded as a normalization within -some equivalence class of terms. --} -type PartialIso' s a = PartialIso s s a a - -{- | `APartialIso` is monomorphically a `PartialIso`. -} -type APartialIso s t a b = - PartialExchange a b a (Maybe b) -> PartialExchange a b s (Maybe t) - -{- | A `PartialExchange` provides efficient access -to the two functions that make up a `PartialIso`. --} -data PartialExchange a b s t = - PartialExchange (s -> Maybe a) (b -> Maybe t) -instance Functor (PartialExchange a b s) where fmap = rmap -instance Filterable (PartialExchange a b s) where - mapMaybe = dimapMaybe Just -instance Profunctor (PartialExchange a b) where - dimap f' g' (PartialExchange f g) = - PartialExchange (f . f') (fmap g' . g) -instance Choice (PartialExchange a b) where - left' (PartialExchange f g) = - PartialExchange (either f (pure Nothing)) ((Left <$>) . g) - right' (PartialExchange f g) = - PartialExchange (either (pure Nothing) f) ((Right <$>) . g) -instance Cochoice (PartialExchange a b) where - unleft (PartialExchange f g) = - PartialExchange (f . Left) (either Just (pure Nothing) <=< g) - unright (PartialExchange f g) = - PartialExchange (f . Right) (either (pure Nothing) Just <=< g) - -{- | Build a `PartialIso`. -} -partialIso :: (s -> Maybe a) -> (b -> Maybe t) -> PartialIso s t a b -partialIso f g = - unright . iso (maybe (Left ()) Right . f =<<) (mapMaybe g) . right' - -{- | Given a partial function that is its own inverse, -this gives you a `PartialIso'` using it in both directions. -} -partialInvoluted :: (a -> Maybe a) -> PartialIso' a a -partialInvoluted f = partialIso f f - -{- | Convert `APartialIso` to the pair of functions that characterize it. -} -withPartialIso - :: APartialIso s t a b - -> ((s -> Maybe a) -> (b -> Maybe t) -> r) - -> r -withPartialIso pattern k = - case pattern (PartialExchange Just (Just . Just)) of - PartialExchange f g -> k f (join . g) - -{- | Clone `APartialIso` so that you can reuse the same -monomorphically typed partial isomorphism for different purposes. --} -clonePartialIso - :: APartialIso s t a b - -> PartialIso s t a b -clonePartialIso pattern = withPartialIso pattern $ \f g -> partialIso f g - -{- | Clone and invert `APartialIso`. -} -coPartialIso - :: APartialIso b a t s - -> PartialIso s t a b -coPartialIso pattern = - withPartialIso pattern $ \f g -> partialIso g f - -{- | Construct a `PartialIso` on pairs from components. -} -crossPartialIso - :: APartialIso s t a b - -> APartialIso u v c d - -> PartialIso (s,u) (t,v) (a,c) (b,d) -crossPartialIso x y = - withPartialIso x $ \e f -> - withPartialIso y $ \g h -> - partialIso - (\(s,u) -> (,) <$> e s <*> g u) - (\(t,v) -> (,) <$> f t <*> h v) - -{- | Construct a `PartialIso` on `Either`s from components. -} -altPartialIso - :: APartialIso s t a b - -> APartialIso u v c d - -> PartialIso - (Either s u) (Either t v) - (Either a c) (Either b d) -altPartialIso x y = - withPartialIso x $ \e f -> - withPartialIso y $ \g h -> - partialIso - (either ((Left <$>) . e) ((Right <$>) . g)) - (either ((Left <$>) . f) ((Right <$>) . h)) - -{- | Action of `APrism` on `Choice` `Profunctor`s. -} -(>?) - :: Choice p - => APrism s t a b - -> p a b - -> p s t -(>?) pat = withPrism pat $ \f g -> dimap g (either id f) . right' -infixl 4 >? - -{- | Action of a coPrism on `Cochoice` `Profunctor`s. -} -(?<) - :: Cochoice p - => APrism b a t s - -> p a b - -> p s t -(?<) pat = withPrism pat $ \f g -> unright . dimap (either id f) g -infixl 4 ?< - -{- | Action of `APartialIso` on `Choice` & `Cochoice` partial profunctors. -} -(>?<) - :: (Choice p, Cochoice p) - => APartialIso s t a b - -> p a b - -> p s t -(>?<) pat = withPartialIso pat dimapMaybe -infixl 4 >?< - -{- | Action of `AnIso` on `Profunctor`s. -} -(>~) :: Profunctor p => AnIso s t a b -> p a b -> p s t -(>~) pattern = withIso pattern dimap -infixl 2 >~ - -{- | Inverse action of `AnIso` on `Profunctor`s. -} -(~<) :: Profunctor p => AnIso b a t s -> p a b -> p s t -(~<) pattern = withIso pattern (flip dimap) -infixl 2 ~< - -{- | Action of a `coPrism` -on the composition of a `Profunctor` and `Filterable`. --} -coPrism :: (Profunctor p, Filterable f) => APrism b a t s -> p a (f b) -> p s (f t) -coPrism p = unwrapPafb . (?<) p . WrapPafb - -{- | `satisfied` is the prototypical proper partial isomorphism, -identifying a subset which satisfies a predicate. -} -satisfied :: (a -> Bool) -> PartialIso' a a -satisfied f = partialInvoluted satiate where - satiate a = if f a then Just a else Nothing - -{- | `nulled` matches an `Empty` pattern, like `_Empty`. -} -nulled :: (AsEmpty s, AsEmpty t) => PartialIso s t () () -nulled = partialIso empA empB where - empA s = if isn't _Empty s then Nothing else Just () - empB _ = Just Empty - -{- | `notNulled` matches a non-`Empty` pattern. -} -notNulled :: (AsEmpty s, AsEmpty t) => PartialIso s t s t -notNulled = partialIso nonEmp nonEmp where - nonEmp s = if isn't _Empty s then Just s else Nothing - -{- | The either-of-tuples representation of `Maybe`. -} -eotMaybe :: Iso (Maybe a) (Maybe b) (Either a ()) (Either b ()) -eotMaybe = iso - (maybe (Right ()) Left) - (either Just (const Nothing)) - -{- | The either-of-tuples representation of list-like streams. -} -eotList - :: (Cons s s a a, AsEmpty t, Cons t t b b) - => Iso s t (Either (a,s) ()) (Either (b,t) ()) -eotList = iso - (maybe (Right ()) Left . uncons) - (either (review _Cons) (const Empty)) - -{- | Iterate the application of a partial isomorphism, -useful for constructing fold/unfold isomorphisms. -} -iterating :: APartialIso a b a b -> Iso a b a b -iterating pattern = withPartialIso pattern $ \f g -> - iso (iter f) (iter g) where - iter h state = maybe state (iter h) (h state) - -{- | Left fold & unfold `APartialIso` to an `Control.Lens.Iso.Iso`. -} -difoldl1 - :: Cons s t a b - => APartialIso d c (d,b) (c,a) - -> Iso (d,t) (c,s) (d,t) (c,s) -difoldl1 pattern = - let - associate = iso - (\(c,(a,s)) -> ((c,a),s)) - (\((d,b),t) -> (d,(b,t))) - step - = crossPartialIso id _Cons - . associate - . crossPartialIso (coPartialIso pattern) id - in from (iterating step) - -{- | Right fold & unfold `APartialIso` to an `Control.Lens.Iso.Iso`. -} -difoldr1 - :: Snoc s t a b - => APartialIso d c (b,d) (a,c) - -> Iso (t,d) (s,c) (t,d) (s,c) -difoldr1 pattern = - let - reorder = iso - (\((s,a),c) -> (s,(a,c))) - (\(t,(b,d)) -> ((t,b),d)) - step - = crossPartialIso _Snoc id - . reorder - . crossPartialIso id (coPartialIso pattern) - in from (iterating step) - -{- | Left fold & unfold `APartialIso` to a `Control.Lens.Prism.Prism`. -} -difoldl - :: (AsEmpty t, Cons s t a b) - => APartialIso d c (d,b) (c,a) - -> Prism d c (d,t) (c,s) -difoldl pattern - = dimap (,Empty) (fmap fst) - . difoldl1 pattern - -{- | Right fold & unfold `APartialIso` to a `Control.Lens.Prism.Prism`. -} -difoldr - :: (AsEmpty t, Snoc s t a b) - => APartialIso d c (b,d) (a,c) - -> Prism d c (t,d) (s,c) -difoldr pattern - = dimap (Empty,) (fmap snd) - . difoldr1 pattern diff --git a/src/Data/Profunctor/Distributor.hs b/src/Data/Profunctor/Distributor.hs deleted file mode 100644 index c156538c..00000000 --- a/src/Data/Profunctor/Distributor.hs +++ /dev/null @@ -1,288 +0,0 @@ -{-| -Module : Data.Profunctor.Distributor -Description : distributors -Copyright : (C) 2026 - Eitan Chatav -License : BSD-style (see the file LICENSE) -Maintainer : Eitan Chatav -Stability : provisional -Portability : non-portable --} - -module Data.Profunctor.Distributor - ( -- * Distributor - Distributor (..) - , dialt - -- * Alternator - , Alternator (..) - , choice - ) where - -import Control.Applicative hiding (WrappedArrow) -import Control.Applicative qualified as Ap (WrappedArrow) -import Control.Arrow -import Control.Lens hiding (chosen) -import Control.Lens.Internal.Profunctor -import Control.Lens.PartialIso -import Data.Bifunctor.Clown -import Data.Bifunctor.Joker -import Data.Bifunctor.Product -import Data.Functor.Adjunction -import Data.Functor.Contravariant.Divisible -import Data.Profunctor hiding (WrappedArrow) -import Data.Profunctor qualified as Pro (WrappedArrow) -import Data.Profunctor.Cayley -import Data.Profunctor.Composition -import Data.Profunctor.Monad -import Data.Profunctor.Monoidal -import Data.Profunctor.Yoneda -import Data.Void - --- Distributor -- - -{- | A `Distributor`, or lax distributive profunctor, -respects [distributive category] -(https://ncatlab.org/nlab/show/distributive+category) -structure, that is nilary and binary products and coproducts, -@()@, @(,)@, `Void` and `Either`. It has zero `zeroP` -and sum `>+<` lax monoidal structure morphisms. - -In addition to the product laws for `Monoidal`, we have -sum laws for `Distributor`. - -Laws: - ->>> let lunit = dimap (either absurd id) Right ->>> let runit = dimap (either id absurd) Left ->>> :{ -let assoc = dimap - (either (Left . Left) (either (Left . Right) Right)) - (either (either Left (Right . Left)) (Right . Right)) -:} - -prop> zeroP >+< p = lunit p -prop> p >+< zeroP = runit p -prop> p >+< q >+< r = assoc ((p >+< q) >+< r) -prop> dimap (f >+< g) (h >+< i) (p >+< q) = dimap f h p >+< dimap g i q - -`Distributor` additionally has methods `manyP` & `optionalP`, -distributing an action over @[]@ and `Maybe` datatypes, -which generalize to `Data.Traversable.Homogeneous.homogeneously` -distributing an action over -`Data.Traversable.Homogeneous.Homogeneous` -sum-of-products datatypes. - --} -class Monoidal p => Distributor p where - - {- | The zero structure morphism of a `Distributor`. - - `zeroP` has a default for `Alternator`s. - - prop> zeroP = empty - -} - zeroP :: p Void Void - default zeroP :: Alternator p => p Void Void - zeroP = empty - - {- | The sum structure morphism of a `Distributor`. - - `>+<` has a default for `Alternator`s. - - prop> x >+< y = alternate (Left x) <|> alternate (Right y) - -} - (>+<) :: p a b -> p c d -> p (Either a c) (Either b d) - default (>+<) - :: Alternator p - => p a b -> p c d -> p (Either a c) (Either b d) - x >+< y = alternate (Left x) <|> alternate (Right y) - infixr 3 >+< - - {- | One or none. -} - optionalP :: p a b -> p (Maybe a) (Maybe b) - optionalP p = eotMaybe >~ p >+< oneP - - {- | Zero or more. -} - manyP :: p a b -> p [a] [b] - manyP p = eotList >~ p >*< manyP p >+< oneP - -instance Distributor (->) where - zeroP = id - (>+<) = (+++) -instance Monoid s => Distributor (Forget s) where - zeroP = Forget absurd - Forget kL >+< Forget kR = Forget (either kL kR) -instance Decidable f => Distributor (Clown f) where - zeroP = Clown lost - Clown x >+< Clown y = Clown (chosen x y) -instance Alternative f => Distributor (Joker f) where - zeroP = Joker empty - Joker x >+< Joker y = Joker (Left <$> x <|> Right <$> y) - optionalP (Joker x) = Joker (optional x) - manyP (Joker x) = Joker (many x) -instance (Distributor p, Applicative f) - => Distributor (WrappedPafb f p) where - zeroP = WrapPafb (rmap pure zeroP) - WrapPafb x >+< WrapPafb y = WrapPafb $ - dialt id (fmap Left) (fmap Right) x y - manyP (WrapPafb x) = WrapPafb (rmap sequenceA (manyP x)) - optionalP (WrapPafb x) = WrapPafb (rmap sequenceA (optionalP x)) -instance Applicative f => Distributor (Star f) where - zeroP = Star absurd - Star f >+< Star g = - Star (either (fmap Left . f) (fmap Right . g)) - optionalP (Star f) = Star (traverse f) - manyP (Star f) = Star (traverse f) -deriving via (Star m) instance Monad m => Distributor (Kleisli m) -instance Adjunction f u => Distributor (Costar f) where - zeroP = Costar unabsurdL - Costar f >+< Costar g = Costar (bimap f g . cozipL) -instance (Applicative f, Distributor p) - => Distributor (Cayley f p) where - zeroP = Cayley (pure zeroP) - Cayley x >+< Cayley y = Cayley ((>+<) <$> x <*> y) - optionalP (Cayley x) = Cayley (optionalP <$> x) - manyP (Cayley x) = Cayley (manyP <$> x) -instance (ArrowZero p, ArrowChoice p) - => Distributor (Pro.WrappedArrow p) where - zeroP = zeroArrow - (>+<) = (+++) -deriving via (Pro.WrappedArrow p) - instance (ArrowZero p, ArrowChoice p) - => Distributor (Ap.WrappedArrow p) -instance (Distributor p, Distributor q) - => Distributor (Procompose p q) where - zeroP = Procompose zeroP zeroP - Procompose xL yL >+< Procompose xR yR = - Procompose (xL >+< xR) (yL >+< yR) - optionalP (Procompose f g) = - Procompose (optionalP f) (optionalP g) - manyP (Procompose f g) = - Procompose (manyP f) (manyP g) -instance (Distributor p, Distributor q) - => Distributor (Product p q) where - zeroP = Pair zeroP zeroP - Pair x0 y0 >+< Pair x1 y1 = Pair (x0 >+< x1) (y0 >+< y1) - optionalP (Pair f g) = - Pair (optionalP f) (optionalP g) - manyP (Pair f g) = - Pair (manyP f) (manyP g) -instance Distributor p => Distributor (Yoneda p) where - zeroP = proreturn zeroP - ab >+< cd = proreturn (proextract ab >+< proextract cd) - optionalP = proreturn . optionalP . proextract - manyP = proreturn . manyP . proextract -instance Distributor p => Distributor (Coyoneda p) where - zeroP = proreturn zeroP - ab >+< cd = proreturn (proextract ab >+< proextract cd) - optionalP = proreturn . optionalP . proextract - manyP = proreturn . manyP . proextract - -{- | `dialt` is a functionalized form of `>+<`. -} -dialt - :: Distributor p - => (s -> Either a c) - -> (b -> t) - -> (d -> t) - -> p a b -> p c d -> p s t -dialt f g h p q = dimap f (either g h) (p >+< q) - --- Alternator -- - -{- | The `Alternator` class co-extends `Choice` and `Distributor`, -as well as `Alternative`, adding the `alternate` method, -which is a lax monoidal structure morphism on sums, -and methods `someP` & `optionP`, -with these these laws relating them. - -prop> left' = alternate . Left -prop> right' = alternate . Right -prop> zeroP = empty -prop> x >+< y = alternate (Left x) <|> alternate (Right y) -prop> manyP p = optionP _Empty (someP p) -prop> optionalP p = optionP _Nothing (_Just >? p) -prop> someP p = p >:< manyP p - -For the case of `Functor`s, the analog of `alternate` can be defined -without any other constraint, but the case of `Profunctor`s turns -out to be slighly more complex, necessitating `Alternator`. - ->>> :{ -alternateF :: Functor f => Either (f a) (f b) -> f (Either a b) -alternateF = either (fmap Left) (fmap Right) -:} - -Not all `Distributor`s are `Alternator`s, in particular @(->)@ is -a `Distributor` but cannot be `Alternative`, -because there is no general polymorphic function @empty :: a -> b@, -so @(->)@ isn't an `Alternator`. - --} -class (Choice p, Distributor p, forall x. Alternative (p x)) - => Alternator p where - - {- | The structure morphism for an `Alternator`, - `alternate` has a default for `Choice` & `Cochoice` partial distributors. - -} - alternate - :: Either (p a b) (p c d) - -> p (Either a c) (Either b d) - default alternate - :: Cochoice p - => Either (p a b) (p c d) - -> p (Either a c) (Either b d) - alternate = - dimapMaybe (either Just (pure Nothing)) (Just . Left) - ||| - dimapMaybe (either (pure Nothing) Just) (Just . Right) - - {- | One or more. -} - someP :: p a b -> p [a] [b] - someP x = x >:< manyP x - - {- | One or zero-with-default. -} - optionP :: APrism a b () () {- ^ default -} -> p a b -> p a b - optionP def p = p <|> pureP def - --- | Combines all `Alternative` choices in the specified list. -choice :: (Foldable f, Alternative p) => f (p a) -> p a -choice = foldl' (<|>) empty - -instance Alternative f - => Alternator (Star f) where - alternate = either - (\(Star f) -> Star (either (fmap Left . f) (const empty))) - (\(Star f) -> Star (either (const empty) (fmap Right . f))) -instance (Alternator p, Applicative f) - => Alternator (WrappedPafb f p) where - alternate = - let - f = WrapPafb - . rmap (either (fmap Left) pure) - . alternate - . Left - . unwrapPafb - g = WrapPafb - . rmap (either pure (fmap Right)) - . alternate - . Right - . unwrapPafb - in - either f g - someP (WrapPafb x) = WrapPafb (rmap sequenceA (someP x)) - optionP def (WrapPafb x) = WrapPafb (optionP (prism pure pure . def) x) -instance Alternator p => Alternator (Coyoneda p) where - alternate (Left p) = proreturn (alternate (Left (proextract p))) - alternate (Right p) = proreturn (alternate (Right (proextract p))) - someP = proreturn . someP . proextract - optionP def = proreturn . optionP def . proextract -instance Alternator p => Alternator (Yoneda p) where - alternate (Left p) = proreturn (alternate (Left (proextract p))) - alternate (Right p) = proreturn (alternate (Right (proextract p))) - someP = proreturn . someP . proextract - optionP def = proreturn . optionP def . proextract -instance Alternative f => Alternator (Joker f) where - alternate (Left (Joker x)) = Joker (Left <$> x) - alternate (Right (Joker y)) = Joker (Right <$> y) - someP (Joker x) = Joker (some x) - optionP def (Joker x) = - Joker (x <|> withPrism def (\f _ -> pure (f ()))) diff --git a/src/Data/Profunctor/Separator.hs b/src/Data/Profunctor/Separator.hs deleted file mode 100644 index bbbeaa9a..00000000 --- a/src/Data/Profunctor/Separator.hs +++ /dev/null @@ -1,315 +0,0 @@ -{-| -Module : Data.Profunctor.Separator -Description : separators -Copyright : (C) 2026 - Eitan Chatav -License : BSD-style (see the file LICENSE) -Maintainer : Eitan Chatav -Stability : provisional -Portability : non-portable --} - -module Data.Profunctor.Separator - ( -- * SepBy - SepBy (..) - , sepBy - , noSep - , sepWith - , beginWith - , endWith - -- * SepBy Combinators - , several - , several1 - , chain - , chain1 - , intercalateP - -- * Operator Expressions - , Operator (..) - , Assoc (..) - , withOperators - ) where - -import Control.Lens -import Control.Lens.PartialIso -import Control.Lens.Grammar.Symbol -import Data.Maybe (fromMaybe) -import Data.Profunctor.Distributor -import Data.Profunctor.Monoidal -import GHC.Exts - -{- | Used to sequence multiple times, -separated by a `separateBy`, -begun by a `beginBy`, -and ended by an `endBy`. -} -data SepBy p = SepBy - { beginBy :: p - , endBy :: p - , separateBy :: p - } deriving stock - ( Functor, Foldable, Traversable - , Eq, Ord, Show, Read - ) - -{- | A `SepBy` smart constructor, -setting the `separateBy` field. -Beginning and ending delimitors will be no-ops, -except by modifier record updates `beginBy` or `endBy`. -} -sepBy :: Applicative p => p () -> SepBy (p ()) -sepBy = SepBy (pure ()) (pure ()) - -{- | A `SepBy` smart constructor for no separator, -beginning or ending delimiters. -} -noSep :: Applicative p => SepBy (p ()) -noSep = sepBy (pure ()) - -{- | A `SepBy` smart constructor like `sepBy`, -with a `terminal` argument. -Beginning and ending delimitors will be no-ops, -except by applying smart modifiers `beginWith` or `endWith`. -} -sepWith - :: (Applicative p, TerminalSymbol c (p ())) - => [c] -> SepBy (p ()) -sepWith = sepBy . terminal - -{- | A `SepBy` smart modifier like `beginBy`, -with a `terminal` argument. -} -beginWith :: TerminalSymbol c p => [c] -> SepBy p -> SepBy p -beginWith str separator = separator {beginBy = terminal str} - -{- | A `SepBy` smart modifier like `endBy`, -with a `terminal` argument. -} -endWith :: TerminalSymbol c p => [c] -> SepBy p -> SepBy p -endWith str separator = separator {endBy = terminal str} - -{- | -@prop> several noSep = manyP@ --} -several - :: (IsList s, IsList t, Distributor p) - => SepBy (p () ()) -> p (Item s) (Item t) -> p s t -several (SepBy beg end sep) p = iso toList fromList . eotList >~ - beg >* (p >*< manyP (sep >* p) >+< oneP) *< end - -{- | -@prop> several1 noSep = someP@ --} -several1 - :: (IsList s, IsList t, Distributor p, Choice p) - => SepBy (p () ()) -> p (Item s) (Item t) -> p s t -several1 (SepBy beg end sep) p = iso toList fromList . _Cons >? - beg >* (p >*< manyP (sep >* p)) *< end - -{- | Use a nilary constructor pattern to sequence zero times, or -associate a binary constructor pattern to sequence one or more times. -} -chain - :: Alternator p - => (forall x. x -> Either x x) -- ^ `Left` or `Right` associate - -> APartialIso a b (a,a) (b,b) -- ^ binary constructor pattern - -> APrism a b () () -- ^ nilary constructor pattern - -> SepBy (p () ()) -> p a b -> p a b -chain association pat2 pat0 (SepBy beg end sep) p = - beg >* optionP pat0 (chain1 association pat2 (sepBy sep) p) *< end - -{- | Associate a binary constructor pattern to sequence one or more times. -} -chain1 - :: (Distributor p, Choice p) - => (forall x. x -> Either x x) -- ^ `Left` or `Right` associate - -> APartialIso a b (a,a) (b,b) -- ^ binary constructor pattern - -> SepBy (p () ()) -> p a b -> p a b -chain1 association pat (SepBy beg end sep) = leftOrRight chainl1 chainr1 - where - leftOrRight a b = case association () of Left _ -> a; Right _ -> b - chainl1 p = difoldl pat >? beg >* p >*< manyP (sep >* p) *< end - chainr1 p = difoldr pat >? beg >* manyP (p *< sep) >*< p *< end - -{- | Add a `SepBy` to `replicateP` using `intercalateP`. -} -intercalateP - :: (Monoidal p, Choice p, AsEmpty s, Cons s s a a) - => Int {- ^ number of repetitions -} - -> SepBy (p () ()) -> p a a -> p s s -intercalateP n (SepBy beg end _) _ | n <= 0 = - beg >* asEmpty *< end -intercalateP n (SepBy beg end comma) p = - beg >* p >:< replicateP (n-1) (comma >* p) *< end - -{- | An operator at some level of an operator table, for use with -`withOperators`. `Infix` takes an `Assoc` to distinguish binary operators; -`Prefix` & `Postfix` are for unary operators. -} -data Operator p a b where - Infix - :: Assoc -- ^ `NonAssoc`, `LeftAssoc`, `RightAssoc` - -> APartialIso a b (a,a) (b,b) -- ^ binary constructor pattern - -> p () () -- ^ operator symbol - -> Operator p a b - Prefix - :: APartialIso a b a b -- ^ unary endopattern - -> p () () -- ^ operator symbol - -> Operator p a b - Postfix - :: APartialIso a b a b -- ^ unary endopattern - -> p () () -- ^ operator symbol - -> Operator p a b - -{- | The associativity of an `Infix` binary operator. -} -data Assoc = NonAssoc | LeftAssoc | RightAssoc - deriving stock (Eq, Ord, Show, Read) - -{- | Build an expression `Alternator` from a table of `Operator`s and -an atomic term `Alternator`, analagous to @buildExpressionParser@ from -[parsec](https://hackage.haskell.org/package/parsec). - -The operator table is a list of list of operators, ordered from highest to lowest precedence. -Each level is a list of `Operator`s which share precedence. -Within a level, `Infix` takes an `Assoc` to set left, right or non-associativity for binary operators, -while `Prefix` & `Postfix` are for unary operators. - -For example, an expression grammar over natural numbers with a -postfix factorial @!@ (binding tightest, and not required to actually -compute a factorial), a right-associative exponent @^@, a left-associative -@*@, and left-associative @+@ & @-@ binding loosest: - ->>> import Numeric.Natural (Natural) ->>> import Control.Lens.Grammar hiding (Operator (..), Assoc (..), withOperators) ->>> import Control.Lens (Prism', prism', iso) ->>> :{ -data Expr - = Nat Natural - | Fac Expr - | Exp Expr Expr - | Mul Expr Expr - | Add Expr Expr - | Sub Expr Expr - deriving stock (Eq, Ord, Show, Read) -_Nat :: Prism' Expr Natural -_Nat = prism' Nat (\case Nat n -> Just n; _ -> Nothing) -_Fac :: Prism' Expr Expr -_Fac = prism' Fac (\case Fac x -> Just x; _ -> Nothing) -_Exp, _Mul, _Add, _Sub :: Prism' Expr (Expr, Expr) -_Exp = prism' (uncurry Exp) (\case Exp x y -> Just (x,y); _ -> Nothing) -_Mul = prism' (uncurry Mul) (\case Mul x y -> Just (x,y); _ -> Nothing) -_Add = prism' (uncurry Add) (\case Add x y -> Just (x,y); _ -> Nothing) -_Sub = prism' (uncurry Sub) (\case Sub x y -> Just (x,y); _ -> Nothing) -exprGrammar :: Grammar Char Expr -exprGrammar = ruleRec "expr" $ \expr -> - let atom = rule "atom" $ nat <|> terminal "(" >* expr *< terminal ")" - nat = rule "nat" $ _Nat . iso show read >? someP (asIn @Char DecimalNumber) - in withOperators - [ [ Postfix _Fac (terminal "!") ] - , [ Infix RightAssoc _Exp (terminal "^") ] - , [ Infix LeftAssoc _Mul (terminal "*") ] - , [ Infix LeftAssoc _Add (terminal "+"), Infix LeftAssoc _Sub (terminal "-") ] - ] atom -:} - -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"] -[Exp (Nat 2) (Exp (Nat 3) (Nat 2))] ->>> [e | (e,"") <- parseG exprGrammar "3-2-1"] -[Sub (Sub (Nat 3) (Nat 2)) (Nat 1)] ->>> [e | (e,"") <- parseG exprGrammar "2*3+4"] -[Add (Mul (Nat 2) (Nat 3)) (Nat 4)] ->>> [e | (e,"") <- parseG exprGrammar "2*(3+4)"] -[Mul (Nat 2) (Add (Nat 3) (Nat 4))] ->>> [e | (e,"") <- parseG exprGrammar "3!"] -[Fac (Nat 3)] ->>> [e | (e,"") <- parseG exprGrammar "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 -Just "2^3^2" ->>> unparseG exprGrammar (Exp (Nat 2) (Fac (Nat 3))) "" :: Maybe String -Just "2^3!" --} -withOperators - :: Alternator p - => [[Operator p a b]] -- ^ operator table - -> p a b -- ^ atomic term - -> p a b -- ^ expression -withOperators table p = foldl makeLevel p table - where - makeLevel term ops = - let - (infixes, pres, posts) = foldr splitOp ([],[],[]) ops - termP = withPostP posts (withPreP pres term) - in - infixP infixes termP - - splitOp oper (infixes, pres, posts) = case oper of - Infix assoc pat sym -> ((assoc,pat,sym):infixes, pres, posts) - Prefix pat sym -> (infixes, (pat,sym):pres, posts) - Postfix pat sym -> (infixes, pres, (pat,sym):posts) - - tagSepP syms = choice [only i >? sym | (i, sym) <- zip [0 :: Int ..] syms] - - withPreP ops inner = - difoldr (partialIso fwd bwd) >? manyP (tagSepP (snd <$> ops)) >*< inner - where - fns = [withPartialIso pat (,) | (pat, _) <- ops] - fwd x = choice - [ (\y -> (i,y)) <$> f x | (i, (f,_)) <- zip [0 :: Int ..] fns ] - bwd (i,y) = case drop i fns of - (_,g):_ -> g y - [] -> Nothing - - withPostP ops inner = - difoldl (partialIso fwd bwd) >? inner >*< manyP (tagSepP (snd <$> ops)) - where - fns = [withPartialIso pat (,) | (pat, _) <- ops] - fwd x = choice - [ (\y -> (y,i)) <$> f x | (i, (f,_)) <- zip [0 :: Int ..] fns ] - bwd (y,i) = case drop i fns of - (_,g):_ -> g y - [] -> Nothing - - {- | Parse one operand, then zero or more @(operator, operand)@ steps, - each testing its operator *before* consuming a further operand -- - the same shape parsec's & megaparsec's expression-table builders use. - A missing operator is therefore always a zero-consumption failure, so - the chain's end is found by plain alternation, with no backtracking - needed. (Parsing @(operand, operator)@ pairs instead, as a naive - right-associative reading would, over-consumes the final operand - before discovering there is no trailing operator, which is exactly - the bug this replaces.) - - The tagged steps are then folded according to each matched operator's - `Assoc`iativity: `RightAssoc` recurses into the tail before combining, - associating to the right; `LeftAssoc` & `NonAssoc` combine immediately - and continue, associating to the left. Mixing associativities within - one level, like parsec, only supports chaining within a single run of - the same associativity -- a differently-associating operator simply - ends the current run and begins a new one. - -} - infixP infixes term = - prism (uncurry go) (Right . fwd) >? term >*< manyP (tagSepP syms >*< term) - where - syms = [sym | (_,_,sym) <- infixes] - fns = [(assoc,f,g) | (assoc,pat,_) <- infixes, let (f,g) = withPartialIso pat (,)] - - assocOf i = let (assoc,_,_) = fns !! i in assoc - applyTag i (l,r) = let (_,_,g) = fns !! i in - fromMaybe (error "withOperators: impossible operator pattern") (g (l,r)) - - -- fold a shared seed together with a left-to-right list of tagged - -- steps, dispatching on each step's `Assoc`iativity in turn - go l [] = l - go l ((i,r):more) = case assocOf i of - RightAssoc -> applyTag i (l, go r more) - _ -> go (applyTag i (l,r)) more - - -- the exact inverse of `go`: decompose a value into a seed and the - -- list of tagged steps that `go` would fold back into that value - fwd x = decompose x - where - decompose y = case tryTags y of - Nothing -> (y, []) - Just (i,l,r) -> case assocOf i of - RightAssoc -> - let (r0, rest) = decompose r in (l, (i,r0) : rest) - _ -> - let (l0, prior) = decompose l in (l0, prior ++ [(i,r)]) - tryTags y = choice - [ (\(l,r) -> (i,l,r)) <$> f y - | (i,(_,f,_)) <- zip [0 :: Int ..] fns ] diff --git a/src/Data/Traversable/Homogeneous.hs b/src/Data/Traversable/Homogeneous.hs deleted file mode 100644 index 52589af0..00000000 --- a/src/Data/Traversable/Homogeneous.hs +++ /dev/null @@ -1,142 +0,0 @@ -{-| -Module : Data.Traversable.Homogeneous -Description : homogeneous -Copyright : (C) 2026 - Eitan Chatav -License : BSD-style (see the file LICENSE) -Maintainer : Eitan Chatav -Stability : provisional -Portability : non-portable --} - -module Data.Traversable.Homogeneous - ( -- * Homogeneous - Homogeneous (..) - ) where - -import Control.Applicative -import Control.Lens hiding (chosen) -import Control.Lens.PartialIso -import Data.Complex -import Data.Functor.Compose -import qualified Data.Functor.Product as Functor -import qualified Data.Functor.Sum as Functor -import qualified Data.Monoid as Monoid -import Data.Profunctor.Monoidal -import Data.Proxy -import Data.Sequence (Seq) -import Data.Tagged -import Data.Tree (Tree (..)) -import Data.Vector (Vector) -import Data.Void -import GHC.Generics - -import Data.Profunctor.Distributor - -{- | A class of `Homogeneous` -countable sums of countable products. --} -class Traversable t => Homogeneous t where - {- | Sequences actions `homogeneously`. - - prop> homogeneously @Maybe = optionalP - prop> homogeneously @[] = manyP - - Any `Traversable` & `Data.Distributive.Distributive` countable product - can be given a default implementation for the `homogeneously` method - with `ditraverse`. - - prop> homogeneously = ditraverse - - And any user-defined homogeneous algebraic datatype has - a default instance for `Homogeneous`, by deriving `Generic1`. - -} - homogeneously :: Distributor p => p a b -> p (t a) (t b) - default homogeneously - :: (Generic1 t, Homogeneous (Rep1 t), Distributor p) - => p a b -> p (t a) (t b) - homogeneously = dimap from1 to1 . homogeneously -instance Homogeneous Par1 where - homogeneously = dimap unPar1 Par1 -instance Homogeneous Identity where - homogeneously = dimap runIdentity Identity -instance Homogeneous Monoid.Dual where - homogeneously = dimap Monoid.getDual Monoid.Dual -instance Homogeneous Monoid.Product where - homogeneously = dimap Monoid.getProduct Monoid.Product -instance Homogeneous Monoid.Sum where - homogeneously = dimap Monoid.getSum Monoid.Sum -instance Homogeneous (Tagged s) where - homogeneously = dimap unTagged Tagged -instance Homogeneous U1 where - homogeneously _ = pure U1 -instance Homogeneous (K1 i ()) where - homogeneously _ = pure (K1 ()) -instance Homogeneous (Const ()) where - homogeneously _ = pure (Const ()) -instance Homogeneous Proxy where - homogeneously _ = pure Proxy -instance (Homogeneous s, Homogeneous t) - => Homogeneous (s :.: t) where - homogeneously - = dimap unComp1 Comp1 - . homogeneously . homogeneously -instance (Homogeneous s, Homogeneous t) - => Homogeneous (Compose s t) where - homogeneously - = dimap getCompose Compose - . homogeneously . homogeneously -instance (Homogeneous s, Homogeneous t) - => Homogeneous (s :*: t) where - homogeneously p = dimap2 - (\(s :*: _) -> s) - (\(_ :*: t) -> t) - (:*:) - (homogeneously p) - (homogeneously p) -instance (Homogeneous s, Homogeneous t) - => Homogeneous (Functor.Product s t) where - homogeneously p = dimap2 - (\(Functor.Pair s _) -> s) - (\(Functor.Pair _ t) -> t) - Functor.Pair - (homogeneously p) - (homogeneously p) -instance Homogeneous V1 where - homogeneously _ = dimap (\case) (\case) zeroP -instance Homogeneous (K1 i Void) where - homogeneously _ = dimap unK1 K1 zeroP -instance Homogeneous (Const Void) where - homogeneously _ = dimap getConst Const zeroP -instance (Homogeneous s, Homogeneous t) - => Homogeneous (s :+: t) where - homogeneously p = dialt - (\case {L1 s -> Left s; R1 t -> Right t}) - L1 - R1 - (homogeneously p) - (homogeneously p) -instance (Homogeneous s, Homogeneous t) - => Homogeneous (Functor.Sum s t) where - homogeneously p = dialt - (\case {Functor.InL s -> Left s; Functor.InR t -> Right t}) - Functor.InL - Functor.InR - (homogeneously p) - (homogeneously p) -instance Homogeneous t - => Homogeneous (M1 i c t) where - homogeneously = dimap unM1 M1 . homogeneously -instance Homogeneous f => Homogeneous (Rec1 f) where - homogeneously = dimap unRec1 Rec1 . homogeneously -instance Homogeneous Maybe where - homogeneously = optionalP -instance Homogeneous [] where - homogeneously = manyP -instance Homogeneous Vector where - homogeneously p = eotList >~ p >*< homogeneously p >+< oneP -instance Homogeneous Seq where - homogeneously p = eotList >~ p >*< homogeneously p >+< oneP -instance Homogeneous Complex where - homogeneously p = dimap2 realPart imagPart (:+) p p -instance Homogeneous Tree where - homogeneously p = dimap2 rootLabel subForest Node p (manyP (homogeneously p)) diff --git a/stack.yaml b/stack.yaml index d436f071..a8eb8e3b 100644 --- a/stack.yaml +++ b/stack.yaml @@ -1,3 +1,5 @@ resolver: nightly-2026-09-27 packages: -- . +- distributors-core +- distributors-grammar +- distributors-json diff --git a/test/Examples/RegString.hs b/test/Examples/RegString.hs deleted file mode 100644 index bdd1bdf4..00000000 --- a/test/Examples/RegString.hs +++ /dev/null @@ -1,60 +0,0 @@ -module Examples.RegString - ( regexExamples - ) where - -import Control.Lens.Grammar - -regexExamples :: [(RegString, String)] -regexExamples = - [ (terminal "abc123etc.", "abc123etc.") - , (terminal "x" <> terminal "y", "xy") - , (zeroK, "[]") - , (terminal "xy" >|< terminal "z", "xy|z") - , (token 'x' >|< token 'y', "[xy]") - , (optK (terminal "x"), "x?") - , (starK (terminal "x"), "x*") - , (plusK (terminal "x"), "x+") - , (anyToken, "[^]") - , (oneOf "abc", "[abc]") - , (notOneOf "abc", "[^abc]") - , (asIn UppercaseLetter, "\\p{Lu}") - , (notAsIn LowercaseLetter, "\\P{Ll}") - , (nonTerminal "rule-name", "\\q{rule-name}") - , (terminal "", "") - , (optK (terminal "abc"), "(abc)?") - , (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 (asIn UppercaseLetter >||< asIn LowercaseLetter), "\\p{Lu}|\\p{Ll}") - , (tokenClass (oneOf "abc" >||< asIn DecimalNumber), "[abc]|\\p{Nd}") - - -- Boolean AND (>&&<) operations - , (tokenClass (oneOf "abcdef" >&&< oneOf "def123"), "[def]") - , (tokenClass (notOneOf "abc" >&&< notOneOf "xyz"), "[^abcxyz]") - , (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 (notAsIn Control >&&< notAsIn Space), "\\P{Zs|Cc}") - , (tokenClass (oneOf "0123456789xyz" >&&< asIn DecimalNumber), "[0123456789]") - - -- Boolean NOT (notB) operations - , (tokenClass (notB (oneOf "abc")), "[^abc]") - , (tokenClass (notB (notOneOf "abc")), "[abc]") - , (tokenClass (notB (oneOf "abc" >||< oneOf "xyz")), "[^abcxyz]") - , (tokenClass (notB (asIn UppercaseLetter)), "\\P{Lu}") - , (tokenClass (notB (notAsIn Control)), "\\p{Cc}") - , (tokenClass (notB (notOneOf "abc" >&&< asIn LowercaseLetter)), "[abc]|\\P{Ll}") - - -- trueB & falseB - , (tokenClass trueB, "[^]") - , (tokenClass falseB, "[]") - - -- 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 (notB (oneOf "abc" >||< asIn MathSymbol)), "[^abc\\P{Sm}]") - ] diff --git a/test/Properties/Kleene.hs b/test/Properties/Kleene.hs deleted file mode 100644 index f3ae1652..00000000 --- a/test/Properties/Kleene.hs +++ /dev/null @@ -1,137 +0,0 @@ -{-# OPTIONS_GHC -Wno-orphans #-} -module Properties.Kleene (kleeneProperties) where - -import Control.Lens.Grammar -import Data.Foldable (for_) -import Test.Hspec -import Test.Hspec.QuickCheck (prop) -import Test.QuickCheck - -instance Arbitrary (TokenClass Char) where - arbitrary = sized go - where - go 0 = frequency - [ (1, pure falseB) - , (1, pure trueB) - , (4, oneOf <$> (arbitrary :: Gen [Char])) - , (4, notOneOf <$> (arbitrary :: Gen [Char])) - , (3, asIn <$> arbitrary) - , (3, notAsIn <$> arbitrary) - ] - go n = frequency - [ (2, go 0) - , (2, (>||<) <$> go (n `div` 2) <*> go (n `div` 2)) - , (2, (>&&<) <$> go (n `div` 2) <*> go (n `div` 2)) - , (1, notB <$> go (n - 1)) - ] - -instance Arbitrary (RegEx Char) where - arbitrary = sized go - where - go 0 = frequency - [ (1, pure (zeroK :: RegEx Char)) - , (1, pure (mempty :: RegEx Char)) - , (6, tokenClass <$> (arbitrary :: Gen (TokenClass Char))) - ] - go n = frequency - [ (2, go 0) - , (2, (<>) <$> go (n `div` 2) <*> go (n `div` 2)) - , (2, (>|<) <$> go (n `div` 2) <*> go (n `div` 2)) - , (1, starK <$> go (n - 1)) - , (1, plusK <$> go (n - 1)) - , (1, optK <$> go (n - 1)) - ] - -kleeneProperties :: Spec -kleeneProperties = do - describe "KleeneStarAlgebra" $ do - prop "starK x = optK (plusK x)" $ \(x :: RegEx Char) -> - starK x == optK (plusK x) - prop "plusK x = x <> starK x" $ \(x :: RegEx Char) -> - plusK x == x <> starK x - prop "optK x = mempty >|< x" $ \(x :: RegEx Char) -> - optK x == (mempty >|< x) - prop "x >|< x = x" $ \(x :: RegEx Char) -> - (x >|< x) == x - prop "zeroK >|< x = x" $ \(x :: RegEx Char) -> - (zeroK >|< x) == x - prop "x >|< zeroK = x" $ \(x :: RegEx Char) -> - (x >|< zeroK) == x - prop "x >|< mempty = optK x" $ \(x :: RegEx Char) -> - (x >|< mempty) == optK x - prop "zeroK <> x = zeroK" $ \(x :: RegEx Char) -> - (zeroK <> x) == zeroK - prop "x <> zeroK = zeroK" $ \(x :: RegEx Char) -> - (x <> zeroK) == zeroK - prop "mempty <> x = x" $ \(x :: RegEx Char) -> - (mempty <> x) == x - prop "x <> mempty = x" $ \(x :: RegEx Char) -> - (x <> mempty) == x - describe "TokenAlgebra" $ do - it "zeroK = tokenClass falseB" $ - (zeroK :: RegEx Char) `shouldBe` tokenClass falseB - prop "tokenClass x >|< tokenClass y = tokenClass (x >||< y)" $ - \(x :: TokenClass Char) (y :: TokenClass Char) -> - ((tokenClass x :: RegEx Char) >|< tokenClass y) - == tokenClass (x >||< y) - describe "TokenAlgebra RegEx" $ do - 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) - prop "oneOf cs = tokenClass (oneOf cs)" $ - \(cs :: [Char]) -> - (oneOf cs :: RegEx Char) == tokenClass (oneOf cs) - prop "notOneOf cs = tokenClass (notOneOf cs)" $ - \(cs :: [Char]) -> - (notOneOf cs :: RegEx Char) == tokenClass (notOneOf cs) - prop "asIn cat = tokenClass (asIn cat)" $ - \(cat :: GeneralCategory) -> - (asIn cat :: RegEx Char) == tokenClass (asIn cat) - prop "notAsIn cat = tokenClass (notAsIn cat)" $ - \(cat :: GeneralCategory) -> - (notAsIn cat :: RegEx Char) == tokenClass (notAsIn cat) - it "matching agrees with lifted Bnf on examples" $ do - let - cases = - [ ("", mempty :: RegEx Char) - , ("a", token 'a') - , ("b", token 'a') - , ("ab", token 'a' <> token 'b') - , ("a", token 'a' >|< token 'b') - , ("bbb", starK (token 'b')) - , ("bbb", plusK (token 'b')) - , ("", optK (token 'b')) - , ("x", oneOf "xyz") - , ("x", notOneOf "abc") - , ("A", asIn UppercaseLetter) - , ("a", notAsIn UppercaseLetter) - , ("abbb", token 'a' <> starK (token 'b')) - , ("cat", terminal "cat" >|< terminal "dog") - ] - for_ cases $ \(word, rex) -> - (word =~ rex) `shouldBe` (word =~ liftBnf0 rex) - describe "BooleanAlgebra TokenClass" $ do - it "trueB = anyToken" $ - (trueB :: TokenClass Char) `shouldBe` anyToken - it "trueB = notOneOf []" $ - (trueB :: TokenClass Char) `shouldBe` notOneOf [] - it "falseB = oneOf []" $ - (falseB :: TokenClass Char) `shouldBe` oneOf [] - prop "notB . oneOf = notOneOf" $ - \(cs :: [Char]) -> - notB (oneOf cs :: TokenClass Char) == notOneOf cs - prop "notB . notOneOf = oneOf" $ - \(cs :: [Char]) -> - notB (notOneOf cs :: TokenClass Char) == oneOf cs - prop "notB . asIn = notAsIn" $ - \(cat :: GeneralCategory) -> - notB (asIn cat :: TokenClass Char) == notAsIn cat - prop "notB . notAsIn = asIn" $ - \(cat :: GeneralCategory) -> - notB (notAsIn cat :: TokenClass Char) == asIn cat - prop "x >||< x = x" $ \(x :: TokenClass Char) -> - (x >||< x) == x - prop "x >&&< x = x" $ \(x :: TokenClass Char) -> - (x >&&< x) == x