From a00a4e87680bb7053be4d25347fdd07120300d06 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Thu, 5 Nov 2026 08:25:31 -0800 Subject: [PATCH 001/130] JSON grammars, disjunctive monoids & cocartesian choice Control.Lens.Grammar.Json: bidirectional JSON grammars, compatible with aeson, which parse, decode, print & encode JSON and generate TypeScript types, from one grammar. * Classes of grammars for strings (JsonStr), values (JsonVal), array elements (JsonTup) & object properties (JsonObj), and a Json class of types with grammars, including map key grammars. * Object combinators: required (!:) & optional (?:) properties, defaults (!=), the rest of an object (jsonDict), strict objects (jsonObjectStrict) & alternative object shapes. * Runners: jsonParse & jsonPrint to & from aeson Values, jsonDecode & jsonEncode to & from bytes, with errors (JsonError) located by path & labeled by rules; jsonTypes for TypeScript. * jsonGeneric derives grammars by aeson's Options, agreeing with aeson's generic instances, and ViaJson derives aeson's instances. * TypeScript: rules name type aliases; tuples, unions, index signatures, mapped types of enumerated keys & `${number}` keys. * Performance within 2x of aeson across a benchmark suite (bench/Main.hs), checking agreement with aeson first. Data.Monoid.Disjunctive: DisjunctiveMonoid (falseP, >|<), BooleanAlgebra & KleeneStarAlgebra, replacing the Boole & Kleene modules; Kleene's regular expressions move to Control.Lens.Grammar.RegEx. Data.Profunctor.Distributor: CocartesianMonoidal (zeroP, >+<) is split from Distributor, and CocartesianChoice ties it to Choice & a DisjunctiveMonoid, by alternate, without requiring Monoidal. Data.Profunctor.Monoidal: idP & arrP for Monoidal & Strong profunctors, and Monoidally, to derive Traversing & Arrow instances. Co-Authored-By: Claude Opus 5.5 --- .gitignore | 1 + bench/Main.hs | 290 ++ distributors.cabal | 129 +- package.yaml | 28 + src/Control/Lens/Bifocal.hs | 6 + src/Control/Lens/Diopter.hs | 3 +- src/Control/Lens/Grammar.hs | 71 +- src/Control/Lens/Grammar/BackusNaur.hs | 17 +- src/Control/Lens/Grammar/Boole.hs | 80 - src/Control/Lens/Grammar/Json.hs | 2682 +++++++++++++++++ src/Control/Lens/Grammar/Machine.hs | 8 +- .../Lens/Grammar/{Kleene.hs => RegEx.hs} | 195 +- src/Data/Monoid/Disjunctive.hs | 395 +++ src/Data/Profunctor/Distributor.hs | 186 +- src/Data/Profunctor/Filtrator.hs | 6 +- src/Data/Profunctor/Grammar.hs | 32 +- src/Data/Profunctor/Grammar/Parsector.hs | 15 +- src/Data/Profunctor/Monoidal.hs | 83 + src/Data/Profunctor/Separator.hs | 11 +- test/Examples/Arithmetic.hs | 3 +- test/Examples/Chain.hs | 5 +- test/Examples/Expression.hs | 7 +- test/Examples/Json.hs | 13 +- test/Examples/Lambda.hs | 6 +- test/Examples/RegString.hs | 58 +- test/Examples/SExpr.hs | 2 +- test/Examples/SemVer.hs | 13 +- test/Main.hs | 11 + test/Properties/Json.hs | 1136 +++++++ test/Properties/Kleene.hs | 72 +- 30 files changed, 5122 insertions(+), 442 deletions(-) create mode 100644 bench/Main.hs delete mode 100644 src/Control/Lens/Grammar/Boole.hs create mode 100644 src/Control/Lens/Grammar/Json.hs rename src/Control/Lens/Grammar/{Kleene.hs => RegEx.hs} (76%) create mode 100644 src/Data/Monoid/Disjunctive.hs create mode 100644 test/Properties/Json.hs diff --git a/.gitignore b/.gitignore index 972ef579..7b4c9fb4 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 diff --git a/bench/Main.hs b/bench/Main.hs new file mode 100644 index 00000000..8dc93a24 --- /dev/null +++ b/bench/Main.hs @@ -0,0 +1,290 @@ +{-# LANGUAGE DeriveAnyClass #-} +{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE RequiredTypeArguments #-} +-- | Keep constant benchmarks, like `jsonTypes`, 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.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 + +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 + , bgroup "typescript" + [ bench "records" (nf (\() -> jsonTypes (type '[Person])) ()) + , bench "sums" (nf (\() -> jsonTypes [Shape]) ()) + , bench "rose" (nf (\() -> jsonTypes (type '[Rose])) ()) + , bench "value" (nf (\() -> jsonTypes [Value]) ()) + , bench "twice12" (nf (\() -> jsonTypes [Twice12]) ()) + ] + ] diff --git a/distributors.cabal b/distributors.cabal index 5d68dd41..f086156a 100644 --- a/distributors.cabal +++ b/distributors.cabal @@ -1,6 +1,6 @@ cabal-version: 2.2 --- This file has been generated from package.yaml by hpack version 0.39.6. +-- This file has been generated from package.yaml by hpack version 0.39.1. -- -- see: https://github.com/sol/hpack @@ -32,11 +32,11 @@ library 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.Json Control.Lens.Grammar.Machine + Control.Lens.Grammar.RegEx Control.Lens.Grammar.Symbol Control.Lens.Grammar.Token Control.Lens.Grate @@ -44,6 +44,7 @@ library Control.Lens.PartialIso Control.Lens.Wither Control.Monad.Fail.Try + Data.Monoid.Disjunctive Data.Profunctor.Distributor Data.Profunctor.Filtrator Data.Profunctor.Grammar @@ -101,22 +102,37 @@ library MemoTrie >=0.6 && <1 , QuickCheck >=2.14 && <3 , adjunctions >=4.4 && <5 + , aeson , base >=4.15 && <5 , bifunctors >=5.5 && <6 , bytestring >=0.11 && <1 , containers >=0.6 && <1 , contravariant >=1.5 && <2 + , data-fix , distributive >=0.6 && <1 + , dlist + , hashable , lens >=5.0 && <6 , monad-loops >=0.4.3 && <1 , mtl >=2.2 && <3 + , network-uri + , primitive , profunctors >=5.6 && <6 , random >=1.2 && <2 + , scientific + , sop-core + , strict , tagged >=0.8 && <1 , template-haskell >=2.17 && <3 , text ==2.* + , text-iso8601 + , text-short , th-abstraction >=0.4 && <1 + , these + , time , transformers >=0.5 && <1 + , unordered-containers + , uuid-types , vector >=0.12 && <1 , witherable >=0.4 && <1 default-language: Haskell2010 @@ -134,6 +150,7 @@ test-suite test Examples.RegString Examples.SemVer Examples.SExpr + Properties.Json Properties.Kleene Paths_distributors autogen-modules: @@ -183,26 +200,132 @@ test-suite test MemoTrie >=0.6 && <1 , QuickCheck >=2.14 && <3 , adjunctions >=4.4 && <5 + , aeson , base >=4.15 && <5 , bifunctors >=5.5 && <6 , bytestring >=0.11 && <1 , containers >=0.6 && <1 , contravariant >=1.5 && <2 + , data-fix , distributive >=0.6 && <1 , distributors + , dlist , doctest >=0.18 && <1 + , hashable , hspec >=2.7 && <3 , lens >=5.0 && <6 , megaparsec >=9.0 && <10 , monad-loops >=0.4.3 && <1 , mtl >=2.2 && <3 + , network-uri + , primitive , profunctors >=5.6 && <6 + , quickcheck-instances , random >=1.2 && <2 + , scientific + , sop-core + , strict , tagged >=0.8 && <1 , template-haskell >=2.17 && <3 , text ==2.* + , text-iso8601 + , text-short , th-abstraction >=0.4 && <1 + , these + , time , transformers >=0.5 && <1 + , unordered-containers + , uuid-types + , vector >=0.12 && <1 + , witherable >=0.4 && <1 + default-language: Haskell2010 + +benchmark json + type: exitcode-stdio-1.0 + main-is: Main.hs + other-modules: + Paths_distributors + autogen-modules: + Paths_distributors + 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: + MemoTrie >=0.6 && <1 + , QuickCheck >=2.14 && <3 + , adjunctions >=4.4 && <5 + , aeson + , base >=4.15 && <5 + , bifunctors >=5.5 && <6 + , bytestring >=0.11 && <1 + , containers >=0.6 && <1 + , contravariant >=1.5 && <2 + , data-fix + , deepseq + , distributive >=0.6 && <1 + , distributors + , dlist + , hashable + , lens >=5.0 && <6 + , monad-loops >=0.4.3 && <1 + , mtl >=2.2 && <3 + , network-uri + , primitive + , profunctors >=5.6 && <6 + , random >=1.2 && <2 + , scientific + , sop-core + , strict + , tagged >=0.8 && <1 + , tasty-bench + , template-haskell >=2.17 && <3 + , text ==2.* + , text-iso8601 + , text-short + , th-abstraction >=0.4 && <1 + , these + , time + , transformers >=0.5 && <1 + , unordered-containers + , uuid-types , vector >=0.12 && <1 , witherable >=0.4 && <1 default-language: Haskell2010 diff --git a/package.yaml b/package.yaml index 4319745c..aee63e07 100644 --- a/package.yaml +++ b/package.yaml @@ -19,24 +19,39 @@ description: dependencies: - base >= 4.15 && < 5 +- aeson - adjunctions >= 4.4 && < 5 - bifunctors >= 5.5 && < 6 - bytestring >= 0.11 && < 1 - containers >= 0.6 && < 1 - contravariant >= 1.5 && < 2 +- data-fix +- dlist - distributive >= 0.6 && < 1 +- hashable - lens >= 5.0 && < 6 - MemoTrie >= 0.6 && < 1 - QuickCheck >= 2.14 && < 3 - monad-loops >=0.4.3 && < 1 - mtl >= 2.2 && < 3 +- network-uri +- primitive - random >= 1.2 && < 2 - transformers >= 0.5 && < 1 +- unordered-containers +- uuid-types - profunctors >= 5.6 && < 6 +- scientific +- sop-core +- strict - tagged >= 0.8 && < 1 - template-haskell >= 2.17 && < 3 - text >= 2 && < 3 +- text-iso8601 +- text-short - th-abstraction >= 0.4 && < 1 +- these +- time - vector >= 0.12 && < 1 - witherable >= 0.4 && < 1 @@ -103,3 +118,16 @@ tests: - hspec >= 2.7 && < 3 - megaparsec >= 9.0 && < 10 - QuickCheck >= 2.14 && < 3 + - quickcheck-instances + +benchmarks: + json: + main: Main.hs + source-dirs: bench + ghc-options: + - -O2 + - -rtsopts + dependencies: + - deepseq + - distributors + - tasty-bench diff --git a/src/Control/Lens/Bifocal.hs b/src/Control/Lens/Bifocal.hs index 439a07ff..30c8df93 100644 --- a/src/Control/Lens/Bifocal.hs +++ b/src/Control/Lens/Bifocal.hs @@ -37,6 +37,7 @@ import Control.Applicative import Control.Lens import Control.Lens.Internal.Profunctor import Control.Lens.PartialIso +import Data.Monoid.Disjunctive (DisjunctiveMonoid) import Data.Profunctor import Data.Profunctor.Distributor import Data.Profunctor.Filtrator @@ -159,6 +160,9 @@ instance Applicative (Binocular a b s) where 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) @@ -178,7 +182,9 @@ instance Cochoice (Binocular a b) where = 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) diff --git a/src/Control/Lens/Diopter.hs b/src/Control/Lens/Diopter.hs index 231209fd..31e66548 100644 --- a/src/Control/Lens/Diopter.hs +++ b/src/Control/Lens/Diopter.hs @@ -102,7 +102,7 @@ instance Applicative (Dioptrice a b s) where Dioptrice fx gx <*> Dioptrice fy gy = Dioptrice (\s -> fx s :*: fy s) (\(h :*: g) -> gx h (gy g)) -instance Distributor (Dioptrice a b) where +instance CocartesianMonoidal (Dioptrice a b) where zeroP = Dioptrice absurd ridiculous where ridiculous :: V1 b -> x @@ -110,6 +110,7 @@ instance Distributor (Dioptrice a b) where 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) diff --git a/src/Control/Lens/Grammar.hs b/src/Control/Lens/Grammar.hs index 7c3dcaf1..b6739471 100644 --- a/src/Control/Lens/Grammar.hs +++ b/src/Control/Lens/Grammar.hs @@ -44,14 +44,14 @@ 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.Filtrator import Data.Profunctor.Monadic @@ -69,13 +69,13 @@ 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.Monad.Fail.Try as X +import Data.Monoid.Disjunctive as X import Data.Profunctor.Distributor as X import Data.Profunctor.Filtrator as X import Data.Profunctor.Grammar as X @@ -140,16 +140,15 @@ semverGrammar = _SemVer numberG = iso show read >~ someP (asIn @Char DecimalNumber) identifiersG = several1 (sepWith ".") (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 +165,11 @@ combinators like `<|>` work both `Functor`ially and `Profunctor`ially. +------------+---------------+ | `<*>` | `>*<` | +------------+---------------+ -| `empty` | `empty` | +| `empty` | `falseP` | +------------+---------------+ -| `<|>` | `<|>` | +| `<|>` | `>|<` | +------------+---------------+ -| `choice` | `choice` | +| `choice` | `orP` | +------------+---------------+ | `many` | `manyP` | +------------+---------------+ @@ -254,7 +253,7 @@ arithGrammar = ruleRec "arith" sumG prodG arith = rule "product" $ chain1 Left _Mul (sepWith "*") (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) :} @@ -382,7 +381,7 @@ restores full lookahead to `Parsector`. Since both `Parsor` & `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" @@ -421,7 +420,7 @@ ab|c `RegString`s can be generated from `RegGrammar`s with `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`. @@ -470,7 +469,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 "[^]" @@ -489,15 +488,15 @@ intersection of character classes as well. `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. @@ -508,7 +507,7 @@ 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 @@ -553,7 +552,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 @@ -600,20 +599,20 @@ regexGrammar = _RegString >~ ruleRec "regex" altG seqG rex = rule "sequence" $ chain Left _Sequence _SeqEmpty noSep (exprG 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,24 +645,24 @@ 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 ] - classOneOfG = rule "class-one-of" $ choice + classOneOfG = rule "class-one-of" $ orP [ onlyOne charG , terminal "[" >* several noSep charG *< terminal "]" ] - classNotOneOfG = rule "class-not-one-of" $ choice + classNotOneOfG = rule "class-not-one-of" $ orP [ asEmpty >*< classCatG , terminal "[^" >* several noSep charG >*< optionP (_AndNotAsIn . _Empty) classCatG *< terminal "]" @@ -675,15 +674,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" @@ -1024,7 +1023,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) @@ -1043,7 +1042,7 @@ instance Read RegString where instance IsList RegBnf where type Item RegBnf = Char fromList - = fromMaybe zeroK + = fromMaybe falseP . listToMaybe . mapMaybe prsF . readP_to_S (readG regbnfGrammar) diff --git a/src/Control/Lens/Grammar/BackusNaur.hs b/src/Control/Lens/Grammar/BackusNaur.hs index 274d9d4b..9a02b106 100644 --- a/src/Control/Lens/Grammar/BackusNaur.hs +++ b/src/Control/Lens/Grammar/BackusNaur.hs @@ -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) @@ -123,8 +124,8 @@ 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) + SeqEmpty -> falseP + NonTerminal nameY -> anyP (diff1B x) (rulesNamed nameY rules) Sequence y1 y2 -> if δ (Bnf y1 rules) then y1'y2 >|< y1y2' else y1'y2 where @@ -134,13 +135,13 @@ diffB prefix (Bnf start rules) = 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 + then falseP else mempty RegExam (Alternate y1 y2) -> diff1B x y1 >|< diff1B x y2 -- | Does a pattern match the empty word? @@ -195,7 +196,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/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/Json.hs b/src/Control/Lens/Grammar/Json.hs new file mode 100644 index 00000000..66e8d5e3 --- /dev/null +++ b/src/Control/Lens/Grammar/Json.hs @@ -0,0 +1,2682 @@ +{-# LANGUAGE OverloadedStrings, RequiredTypeArguments #-} + +module Control.Lens.Grammar.Json + ( -- * Json + Json (..) + , jsonParse + , jsonDecode + , jsonPrint + , jsonPrintError + , jsonEncode + , jsonEncodeError + , jsonTypes + , ViaJson (..) + , jsonGeneric + -- * Grammar + , JsonVal (..), jsonTyped + , JsonStr (..) + , JsonTup (..) + , JsonObj (..) + , jsonObjectStrict + , (!=) + -- * Errors + , JsonError (..) + , JsonErrorSort (..) + , jsonErrorMessage + ) where + +import Control.Applicative +import Control.Lens +import Control.Lens.Grammar +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.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, traverse_) +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.List + (find, findIndices, intercalate, isPrefixOf, nub, 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) +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 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 Text.Read (readMaybe) +import Text.ParserCombinators.ReadP (readP_to_S) +import Type.Reflection +import Witherable qualified + +makePrisms ''Value + +-- Json grammars -- + +class Json a where + + json :: JsonVal p => p a a + default json :: (Json (GHC.Generically a), JsonVal p) => p a a + json = iso GHC.Generically coerce >~ json + + {- | `Data.Aeson.toJSONList`, an array of values by default. + `Char` overrides it, so that a `String` is a JSON string, + as do types wrapping a `Char`, by forwarding it. + -} + jsonList :: JsonVal p => p [a] [a] + jsonList = jsonArray json + + {- | `Data.Aeson.toJSONKey`, as 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`, keys of lists, like `jsonList`. + `Char` overrides it, so that a `String` is a key. + -} + jsonKeyList :: Maybe (forall k. JsonStr k => k [a] [a]) + jsonKeyList = Nothing + + {- | `Data.Aeson.omitField`, whether a record's field of the value + may be omitted, by `Aeson.omitNothingFields`. + -} + jsonOmitField :: a -> Bool + jsonOmitField _ = False + + {- | `Data.Aeson.omittedField`, the value of a record's field which is + omitted, by `Aeson.allowOmittedFields`. + -} + jsonOmittedField :: Maybe a + jsonOmittedField = 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 . jsonPrintError + +jsonPrintError :: Json a => a -> Either JsonError Value +jsonPrintError = runJsonPrintor json + +-- | `Data.Aeson.toEncoding` +jsonEncode :: Json a => a -> Encoding +jsonEncode = either (\_ -> Encoding.null_) id . jsonEncodeError + +jsonEncodeError :: Json a => a -> Either JsonError Encoding +jsonEncodeError = runJsonPrintor json + +jsonTypes :: forall (as :: [Type]) -> All Json as => Text +jsonTypes as = renderTypeScript $ hcollapse + (hcpure (Proxy @Json) tsRoot :: NP (K (TsGrammor () ())) as) + where + tsRoot :: forall a. Json a => K (TsGrammor () ()) a + tsRoot = K (coerce (json @a @TsGrammor)) + +{- | @aeson@'s instances, derived from a `Json` instance, failing to parse +at the path of a `JsonError`, by its message. + +> data Point = Point {x :: Int, y :: Int} +> deriving stock Generic +> deriving anyclass Json +> deriving (ToJSON, FromJSON) via ViaJson Point +-} +newtype ViaJson a = ViaJson a + +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)) +instance Json a => Aeson.FromJSON (ViaJson a) where + parseJSON = either parseFailure (pure . ViaJson) . jsonParse + parseJSONList = + either parseFailure (pure . coerce) . runJsonParsor (jsonList @a) + +-- | Fail to parse at the path of a `JsonError`, by its message. +parseFailure :: JsonError -> Aeson.Parser x +parseFailure err = + Aeson.parserThrowError (jsonErrorPath err) (jsonErrorMessage err) + +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 + 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. + + prop> jsonArray p = jsonTuple (manyP (jsonElem p)) + -} + jsonArray :: p a b -> p [a] [b] + jsonArray p = jsonTuple (manyP (jsonElem 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 + 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))) + +-- | 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 == '\'' + +{- | +prop> fromString s = only s ?< jsonString +prop> 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"@. + -} + jsonEnumWith :: (a -> Text) -> [a] -> p a a + jsonEnumWith f as = + prism' f (\t -> lookup t [(f a, a) | a <- as]) ?< jsonText + {- | Strings of numbers, like an integral map key's, + like TypeScript's template literal type, @\`${number}\`@. + -} + jsonNumeric :: p a a -> p a a + jsonNumeric = id + +{- | `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 (JsonVal p, 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 (JsonVal p, 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 which aren't named, of any keys, all of a key grammar, + & their values, all of a value grammar, read as a list of pairs, + like TypeScript's index signature, @[key: string]: T@, + or, of an enumeration of keys, its mapped type, @{[key in K]?: T}@. + An object of a `jsonDict` alone, @jsonObject (jsonDict key value)@, + is a dictionary, @{[key: string]: T}@. With named properties, + a `jsonDict` reads the rest of the object, those which it doesn't name. + It names no key of its own, so an object has at most one `jsonDict`, + which printing checks, as it does for a list which repeats a key. + -} + jsonDict :: (forall k. JsonStr k => k a b) -> p c d -> q [(a, c)] [(b, d)] +infixr 7 !:, ?: + +{- | An optional property with a default, missing exactly when it's the +default, like @aeson@'s @.:?@ & @.!=@, by the `non` isomorphism. + +prop> prop != def = non def ~< prop +-} +(!=) :: (Eq a, Profunctor q) => q (Maybe a) (Maybe a) -> a -> q a a +prop != def = non def ~< prop +infix 6 != + +-- | A `jsonObject` which rejects the properties that it doesn't name. +jsonObjectStrict :: JsonVal p => (forall q. JsonObj p q => q a b) -> p a b +jsonObjectStrict obj = + jsonObject (obj *< dimap (const []) (const ()) (jsonDict jsonText zeroP)) + +-- 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) + +data JsonErrorSort + = JsonLiteral + -- ^ 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) + +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 == JsonLiteral + , jsonErrorSort err1 /= JsonLiteral = err1 + | otherwise = err2 + where + depth1 = length (jsonErrorPath err1) + depth2 = length (jsonErrorPath err2) + +-- Parsing interpreters -- + +{- | `JsonParsor` parses a `Value`. It may also have a `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 + } + +{- | 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 = JsonParsor Nothing + +-- | 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) + } + 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)) JsonLiteral []) +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)) + JsonLiteral [] + 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 + +{- | `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)] + } + +{- | `ObjParsor` reads keys of an `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. +-} +data ObjParsor a b = ObjParsor + { objParsorShapes :: [[Key]] + , objParsorTags :: [(Key, Set Text)] + , runObjParsor :: HashSet Key -> Object -> Either JsonError b + } + +instance Functor (JsonParsor a) where + fmap f = mapParsing (fmap (onSuccess f)) +instance Witherable.Filterable (JsonParsor a) where + mapMaybe = dimapMaybe Just +instance Filtrator JsonParsor +instance Profunctor JsonParsor where + dimap _ g = mapParsing (fmap (onSuccess g)) + _ #. p = coerce p + p .# _ = coerce p +instance Choice JsonParsor where + left' = mapParsing (fmap (fmap Left)) + right' = mapParsing (fmap (fmap Right)) +instance Cochoice JsonParsor where + unleft = mapParsing $ \p v -> + p v >>= either pure (\_ -> jsonUnexpected (Just v)) + unright = mapParsing $ \p v -> + p v >>= either (\_ -> jsonUnexpected (Just v)) pure +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) + _ -> jsonParsor (orElse (runJsonParsor p) (runJsonParsor q)) +instance BackusNaurForm (JsonParsor a b) where + rule name = mapParsing (onFailure (jsonRelabel (unqualified name)) .) + 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 + where + literal = Text.pack s + parse = \case + String t | t == literal -> Right () + v -> Left (JsonError [] [show s] (Just (Right v)) JsonLiteral []) +instance JsonStr JsonParsor where + jsonText = jsonParsor $ \case + String t -> Right t + v -> jsonMismatch "string" v +instance JsonVal JsonParsor where + jsonNull = jsonParsor $ \case + Null -> Right () + v -> jsonMismatch "null" v + jsonBool = jsonParsor $ \case + Bool b -> Right b + v -> jsonMismatch "boolean" v + jsonNumber = jsonParsor $ \case + Number n -> Right n + v -> jsonMismatch "number" v + jsonValue = jsonParsor Right + jsonArray p = jsonParsor $ \case + 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 = JsonParsor dispatch parse + 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 -> runObjParsor obj named o + v -> jsonMismatch "object" v + named = HashSet.fromList (concat (objParsorShapes obj)) + 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 p) = + ObjParsor keys tags (\named o -> onSuccess f (p named o)) +instance Applicative (ObjParsor a) where + pure b = ObjParsor [[]] [] (\_ _ -> Right b) + ObjParsor keys0 tags0 p0 <*> ObjParsor keys1 tags1 p1 = + ObjParsor (liftA2 (<>) keys0 keys1) (tags0 <> tags1) $ \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 p) = + ObjParsor keys tags (\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 [] [] (\_ o -> jsonUnexpected (Just (Object o))) + p >|< q = ObjParsor (objParsorShapes p <> objParsorShapes 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 [[]] [] $ \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 $ \_ 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]] [] $ \_ 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` & `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 + +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 + +-- | Retag an @aeson@ `Encoding.Encoding'`. +retagEncoding :: Encoding.Encoding' a -> Encoding.Encoding' b +retagEncoding = Encoding.unsafeToEncoding . Encoding.fromEncoding + +{- | `KeyPrintor` prints the key of an `Object`, which is total, +as a `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) + +-- | @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 + 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 + +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 + 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 + +instance AesonVal Encoding where + aesonNull = Encoding.null_ + aesonBool = Encoding.bool + aesonNumber = Encoding.scientific + aesonIntegral = id + aesonDouble = Encoding.double + aesonList = Encoding.list + 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 + +{- | `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) + +-- | A total `JsonPrintor`. +printing :: (a -> val) -> JsonPrintor val a b +printing render = + JsonPrintor (const True) (Just . render) render (Right . render) Nothing + +-- | A total `JsonPrintor` of a primitive. +primitive :: AesonStr val => (a -> val) -> JsonPrintor val a b +primitive render = + (printing render) {printorRenderArray = aesonPrimitives render} +{-# INLINE primitive #-} + +{- | A partial `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 + +{- | `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 -> [val] -> [val]) + , tupPrintorCheck :: !(a -> Elements val) + , tupPrintorElement :: !(Maybe (a -> val)) + } + +-- | Render a single element, before the rest. +renderElement :: (a -> val) -> a -> [val] -> [val] +renderElement render a rest = + let printed = render a in printed `seq` printed : rest + +-- | 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)) + +{- | `ObjPrintor` writes keys of an `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 -> [(Key, val)] -> [(Key, 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 +{- | 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 +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) +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 +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)) +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) + +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 + jsonString = primitive aesonString + jsonEncodedText encoding = withPrism encoding $ \encode _ -> + primitive (aesonEncodedText . encode) +instance AesonVal val => JsonVal (JsonPrintor val) where + jsonNull = primitive (const aesonNull) + jsonBool = primitive aesonBool + jsonNumber = primitive aesonNumber + jsonInt = primitive (aesonIntegral Encoding.int) + 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) + 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) + jsonMap key = printDistinct Map.foldrWithKey key + jsonHashMap key = printDistinct HashMap.foldrWithKey key + jsonTuple tup = JsonPrintor + (\rules -> tupPrintorTotal tup rules) + (fmap (aesonList id . toList) . tupPrintorTry tup) + (\a -> aesonList id (tupPrintorRender tup a [])) + (\a -> case tupPrintorCheck tup a of + Elements printed -> aesonList id . toList . snd <$> printed) + Nothing + 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 -> aesonObject (objPrintorRender printor a [])) + (fmap aesonObject . objPrintorCheck printor) + Nothing + where + printor = obj @(ObjPrintor val) + +instance Functor (TupPrintor val a) where + fmap _ (TupPrintor total attempt render check single) = + TupPrintor total attempt render check single +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 +instance Profunctor (TupPrintor val) where + 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 + _ #. p = coerce p + p .# _ = coerce p +instance 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 Distributor (TupPrintor val) where + manyP p = TupPrintor + (\rules -> tupPrintorTotal p rules) + (fmap mconcat . tryAll (tupPrintorTotal p) (tupPrintorTry p) + (\a -> DList.fromList (tupPrintorRender 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 Alternative (TupPrintor val a) where + empty = falseP + (<|>) = (>|<) + many = lmap repeat . manyP + some = lmap repeat . someP +instance Alternator (TupPrintor val) where + optionP def p = pureP def >|< p +instance Choice (TupPrintor val) where + left' = alternate . Left + right' = alternate . Right +unprintable :: Elements val +unprintable = Elements (jsonUnexpected Nothing) + +-- | A partial `TupPrintor`, rendering what it tries, or else nothing. +tupTrying + :: (a -> Maybe (DList val)) -> (a -> Elements val) -> TupPrintor val a b +tupTrying attempt check = TupPrintor (const False) attempt + (\a -> DList.apply (fromMaybe mempty (attempt a))) check Nothing + +instance 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 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) (`DList.apply` 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 + 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)) + +instance Functor (ObjPrintor val a) where + fmap _ (ObjPrintor keys rest total attempt render check) = + ObjPrintor keys rest total attempt render check +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) +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 +instance Choice (ObjPrintor val) where + left' = alternate . Left + right' = alternate . 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)) +instance 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)) +instance 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) (`DList.apply` props) (objPrintorTry p a)) + (\a -> case objPrintorCheck p a of + Left err -> onFailure (jsonOrElse err) (objPrintorCheck q a) + success -> success) + +-- | A partial `ObjPrintor` of another's shapes, rendering what it tries. +objTrying + :: 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 -> DList.apply (fromMaybe mempty (attempt a)) 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 (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 key p) + (printProperty key p) + where + key = Key.fromText k + 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 key p a rest) ma) + (maybe (Right []) (printProperty key p)) + where + key = Key.fromText k + property printed = DList.singleton (key, printed) + +-- | 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 + :: Key -> JsonPrintor val a b -> a -> [(Key, val)] -> [(Key, val)] +renderProperty key p a rest = + let printed = printorRender p a in printed `seq` (key, printed) : rest + +printProperty + :: Key -> JsonPrintor val a b -> a -> Either JsonError [(Key, val)] +printProperty key p a = + (\printed -> [(key, printed)]) <$> jsonAt (Key key) (printorCheck p a) + +-- TypeScript interpreters -- + +data TsType + = TsAlias String -- ^ @T@, a reference to a type alias + | TsNull -- ^ @null@ + | TsUndefined -- ^ @undefined@ + | TsBoolean -- ^ @boolean@ + | TsNumber -- ^ @number@ + | TsString -- ^ @string@ + | TsNumeric -- ^ @\`${number}\`@ + | TsLiteral Text -- ^ @"abc"@ + | TsArray TsType -- ^ @T[]@ + | TsTuple [TsElement] -- ^ @[T, U?, ...V[]]@ + | TsObject [TsProperty] -- ^ @{abc: T, xyz?: U}@ + | TsUnion [TsType] -- ^ @T | U@, or @never@ when empty + deriving stock (Eq, Ord) + +data TsElement + = TsRequired TsType -- ^ @T@ + | TsOptional TsType -- ^ @T?@ + | TsRest TsType -- ^ @...T[]@ + deriving stock (Eq, Ord) + +-- | A property of a TypeScript object type. +data TsProperty + = TsProperty Text Bool TsType -- ^ @abc: T@ or @abc?: T@ + | TsIndex TsType [TsType] TsType + {- ^ @[key: string]: T@ or @{[key in K]?: T}@, the rest of its properties, + of a key type, & its alternatives, with its aliases resolved -} + deriving stock (Eq, Ord) + +newtype TsGrammor a b = TsGrammor (TsDefining TsType) + +newtype TsTupGrammor a b = TsTupGrammor + {runTsTupGrammor :: Ap TsDefining TsShapes} + +newtype TsObjGrammor a b = TsObjGrammor + {runTsObjGrammor :: Ap TsDefining (Ap [] [TsProperty])} + +{- | Defining TypeScript types, reading the rules being defined which are +unguarded by an array, object or tuple, each noting whether it's been +unrolled, and updating the named rules & their definitions. +-} +type TsDefining = ReaderT (Map String Bool) (State TsDefinitions) + +data TsDefinitions = TsDefinitions + { tsRuleNames :: Map String String + , tsRules :: Map String TsType + } + +{- | Define a rule once, under its unqualified name, or else its qualified +name, if taken, so that every other occurrence of it, recursive or not, +is its name. Its name is reserved, as `never`, while it's being defined. +An unguarded occurrence is its least fixpoint instead, unrolled once, +so that a rule of a rule is the rule, and a rule recurring unguarded +contributes `never`, since JSON values are finite. +-} +tsDefine :: String -> TsGrammor a b -> TsGrammor c d +tsDefine key (TsGrammor body) = TsGrammor $ do + unguarded <- ask + defs <- lift get + case (Map.lookup key unguarded, Map.lookup key (tsRuleNames defs)) of + (Just True, _) -> pure (tsUnion []) + (Just False, _) -> local (Map.insert key True) body + (Nothing, Just name) -> pure (TsAlias name) + (Nothing, Nothing) -> do + let name = freshName (tsRules defs) + lift $ put defs + { tsRuleNames = Map.insert key name (tsRuleNames defs) + , tsRules = Map.insert name (tsUnion []) (tsRules defs) + } + definition <- local (Map.insert key False) body + lift $ modify $ \defined -> + defined {tsRules = Map.insert name definition (tsRules defined)} + pure (TsAlias name) + where + freshName taken = fromMaybe + (until (`Map.notMember` taken) (<> "'") key) + (find (`Map.notMember` taken) [unqualified key, key]) + +tsGuarded :: TsDefining a -> TsDefining a +tsGuarded = local (const Map.empty) + +tsType :: TsType -> TsGrammor a b +tsType = TsGrammor . pure + +tsUnion :: [TsType] -> TsType +tsUnion types = case nub (concatMap alternatives types) of + [t] -> t + ts -> TsUnion ts + where + alternatives = \case + TsUnion ts -> ts + t -> [t] + +{- | Alternative shapes of a TypeScript tuple type, +so that `>*<` concatenates each pair of shapes and `>+<` unites them. +-} +type TsShapes = Ap [] [TsElement] + +tsElementType :: TsElement -> TsType +tsElementType = \case + TsRequired t -> t + TsOptional t -> t + TsRest t -> t + +{- | The union of tuple types of some shapes. TypeScript requires that +a tuple type has at most one rest element, no optional element after +a rest element, and no required element after an optional element. +So, the elements from the first rest element to the last are merged +into one rest element, and 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[]]@. +-} +tsTuple :: TsShapes -> TsType +tsTuple (Ap shapes) = tsUnion $ TsTuple <$> + merged (nub (concatMap (expand False . mergeRests) shapes)) + where + merged alternatives = + case [ (i, j, shape) + | merge <- [unioned, extended] + , (i, a) <- zip [0 :: Int ..] alternatives + , (j, b) <- zip [0 ..] alternatives + , i /= j + , Just shape <- [merge a b] + ] of + (i, j, shape) : _ -> merged + [ if k == min i j then shape else alternative + | (k, alternative) <- zip [0 ..] alternatives, k /= max i j ] + [] -> alternatives + 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 + (TsRequired s, TsRequired t) -> Just (TsRequired (tsUnion [s, t])) + (TsOptional s, TsOptional t) -> Just (TsOptional (tsUnion [s, t])) + _ -> Nothing + extended a b + | any isRest a = Nothing + | otherwise = stripPrefix a b >>= \case + [TsRequired t] -> Just (a <> [TsOptional t]) + [TsOptional _] -> Just b + [TsRest _] -> Just b + [TsRequired t, TsRest u] | t == u -> Just (a <> [TsRest t]) + _ -> Nothing + isRest = \case TsRest _ -> 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 <> [TsRest (tsUnion (map tsElementType middle))] <> after + _ -> els + expand _ [] = [[]] + expand restBefore (el : els) = case el of + TsOptional t | restBefore || not (optionalTail els) -> + expand restBefore els <> map (TsRequired t :) (expand restBefore els) + TsRest _ -> map (el :) (expand True els) + _ -> map (el :) (expand restBefore els) + optionalTail = \case + [] -> True + [TsRest _] -> True + TsOptional _ : els -> optionalTail els + _ -> False + +deriving via Grammor (TsDefining TsType) a + instance Functor (TsGrammor a) +deriving via Grammor (TsDefining TsType) + instance Profunctor TsGrammor +deriving via Grammor (TsDefining TsType) + instance Choice TsGrammor +instance Cochoice TsGrammor where + unleft = coerce + unright = coerce +instance Witherable.Filterable (TsGrammor a) where + mapMaybe = dimapMaybe Just +instance Filtrator TsGrammor +instance CocartesianMonoidal TsGrammor +instance CocartesianChoice TsGrammor where + alternate = either coerce coerce +instance DisjunctiveMonoid (TsGrammor a b) where + falseP = tsType (tsUnion []) + TsGrammor t0 >|< TsGrammor t1 = + TsGrammor (liftA2 (\a b -> tsUnion [a, b]) t0 t1) +instance BackusNaurForm (TsGrammor a b) where + rule = tsDefine + ruleRec name f = rule name (f (tsDefine name falseP)) +instance (x ~ (), y ~ ()) => IsString (TsGrammor x y) where + fromString = tsType . TsLiteral . Text.pack +instance JsonStr TsGrammor where + jsonText = tsType TsString + jsonEnumWith f as = tsType (tsUnion [TsLiteral (f a) | a <- as]) + jsonNumeric _ = tsType TsNumeric +instance JsonVal TsGrammor where + jsonNull = tsType TsNull + jsonBool = tsType TsBoolean + jsonNumber = tsType TsNumber + jsonArray (TsGrammor t) = TsGrammor (TsArray <$> tsGuarded t) + jsonTuple tup = TsGrammor (tsTuple <$> getAp (runTsTupGrammor tup)) + jsonObject obj = + TsGrammor (objects <$> getAp (runTsObjGrammor obj)) + where + objects (Ap shapes) = tsUnion (map object shapes) + object props + | length (nub names) == length names = TsObject props + | otherwise = tsUnion [] + where + names = [name | TsProperty name _ _ <- props] + +deriving via Grammor (Ap TsDefining TsShapes) a + instance Functor (TsTupGrammor a) +deriving via Grammor (Ap TsDefining TsShapes) a + instance Applicative (TsTupGrammor a) +deriving via Grammor (Ap TsDefining TsShapes) + instance Profunctor TsTupGrammor +instance CocartesianMonoidal TsTupGrammor +instance Choice TsTupGrammor where + left' = coerce + right' = coerce +instance CocartesianChoice TsTupGrammor where + alternate = either coerce coerce +instance DisjunctiveMonoid (TsTupGrammor a b) where + falseP = TsTupGrammor (pure (Ap [])) + TsTupGrammor s0 >|< TsTupGrammor s1 = TsTupGrammor (liftA2 unite s0 s1) + where + unite (Ap shapes0) (Ap shapes1) = Ap (shapes0 <> shapes1) +-- | `manyP` is a rest element, of the union of the elements of its shapes. +instance Distributor TsTupGrammor where + manyP (TsTupGrammor s) = TsTupGrammor (rest <$> s) + where + rest (Ap shapes) = Ap $ + case concatMap (map tsElementType) shapes of + [] -> [[]] + ts -> [[TsRest (tsUnion ts)]] +instance Alternative (TsTupGrammor a) where + empty = falseP + (<|>) = (>|<) + many = lmap repeat . manyP + some = lmap repeat . someP +instance Alternator TsTupGrammor +instance JsonTup TsGrammor TsTupGrammor where + jsonElem (TsGrammor t) = + TsTupGrammor (Ap ((\ty -> Ap [[TsRequired ty]]) <$> tsGuarded t)) + +deriving via Grammor (Ap TsDefining (Ap [] [TsProperty])) a + instance Functor (TsObjGrammor a) +deriving via Grammor (Ap TsDefining (Ap [] [TsProperty])) a + instance Applicative (TsObjGrammor a) +deriving via Grammor (Ap TsDefining (Ap [] [TsProperty])) + instance Profunctor TsObjGrammor +instance Choice TsObjGrammor where + left' = coerce + right' = coerce +instance CocartesianMonoidal TsObjGrammor +instance CocartesianChoice TsObjGrammor where + alternate = either coerce coerce +instance DisjunctiveMonoid (TsObjGrammor a b) where + falseP = TsObjGrammor (pure (Ap [])) + TsObjGrammor s0 >|< TsObjGrammor s1 = TsObjGrammor (liftA2 unite s0 s1) + where + unite (Ap shapes0) (Ap shapes1) = Ap (shapes0 <> shapes1) +instance JsonObj TsGrammor TsObjGrammor where + jsonDict key (TsGrammor t) = tsProperty $ do + keyType <- tsGuarded k + rules <- lift (gets tsRules) + TsIndex keyType (tsAlternatives rules keyType) <$> tsGuarded t + where + TsGrammor k = key + k !: TsGrammor t = tsProperty (TsProperty k False <$> tsGuarded t) + k ?: TsGrammor t = tsProperty (TsProperty k True <$> tsGuarded t) + +-- | The alternatives of a type, resolving its aliases. +tsAlternatives :: Map String TsType -> TsType -> [TsType] +tsAlternatives rules = go [] + where + go seen = \case + TsAlias name | name `notElem` seen, Just t <- Map.lookup name rules -> + go (name : seen) t + TsUnion ts -> concatMap (go seen) ts + t -> [t] + +-- | An object type of one property. +tsProperty :: TsDefining TsProperty -> TsObjGrammor a b +tsProperty prop = TsObjGrammor (Ap ((\p -> Ap [[p]]) <$> prop)) + +-- Rendering TypeScript -- + +-- | Render the TypeScript type alias declarations of rules, sharing them. +renderTypeScript :: [TsGrammor () ()] -> Text +renderTypeScript roots = + Text.unlines (map declaration (Map.toList (tsRules definitions))) + where + definitions = execState + (runReaderT (traverse_ (\(TsGrammor ts) -> ts) roots) Map.empty) + (TsDefinitions Map.empty Map.empty) + declaration (name, ty) = + "export type " <> tsIdentifier name <> " = " <> renderTsType ty <> ";" + +renderTsType :: TsType -> Text +renderTsType = \case + TsAlias name -> tsIdentifier name + TsNull -> "null" + TsUndefined -> "undefined" + TsBoolean -> "boolean" + TsNumber -> "number" + TsString -> "string" + TsNumeric -> "`${number}`" + TsLiteral t -> tsStringLiteral t + TsArray t -> renderTsOperand t <> "[]" + TsTuple els -> "[" <> Text.intercalate ", " (map renderTsElement els) <> "]" + TsObject props -> Text.intercalate " & " (renderTsObject props) + TsUnion [] -> "never" + TsUnion ts -> Text.intercalate " | " (map renderTsType ts) + +renderTsOperand :: TsType -> Text +renderTsOperand = \case + TsUnion ts@(_ : _ : _) -> "(" <> renderTsType (TsUnion ts) <> ")" + TsObject props | length (renderTsObject props) > 1 -> + "(" <> renderTsType (TsObject props) <> ")" + t -> renderTsType t + +{- | The intersected parts of an object type: its named properties +& index signatures, of its @string@ or @\`${number}\`@ keys, & a mapped type +of its literal keys, but those which are named, which TypeScript types +apart, like @{ id: T } & { [key in Exclude]?: U }@. +-} +renderTsObject :: [TsProperty] -> [Text] +renderTsObject props = case (named <> indexSignatures, keyedTypes) of + ([], []) -> ["{}"] + ([], _) -> keyedTypes + (rendered, _) -> + ("{ " <> Text.intercalate "; " rendered <> " }") : keyedTypes + where + named = [renderTsProperty k o t | TsProperty k o t <- props] + names = [k | TsProperty k _ _ <- props] + indexSignatures = + [ "[key: " <> renderTsType pattern <> "]: " + <> renderTsType (tsUnion (t : covered pattern)) + | TsIndex _ alternatives t <- props + , t /= TsUnion [] + , pattern <- take 1 + [p | p <- [TsString, TsNumeric], p `elem` alternatives] + ] + -- An index type also covers the named properties it matches, + -- as TypeScript requires. + covered pattern = + [t | TsProperty k _ t <- props, matches pattern k] + <> [TsUndefined | or [o | TsProperty k o _ <- props, matches pattern k]] + matches = \case + TsNumeric -> isJust . readScientific + _ -> const True + keyedTypes = + [ "{ [key in " <> keys <> "]?: " <> renderTsType t <> " }" + | TsIndex k alternatives t <- props + , t /= TsUnion [] + , let + literalKeys = [TsLiteral l | TsLiteral l <- alternatives] + excluded = [l | l@(TsLiteral name) <- literalKeys, name `elem` names] + base + | length literalKeys == length alternatives = renderTsType k + | otherwise = renderTsType (tsUnion literalKeys) + keys + | null excluded = base + | otherwise = + "Exclude<" <> base <> ", " <> renderTsType (tsUnion excluded) + <> ">" + , length excluded < length literalKeys + ] + +renderTsElement :: TsElement -> Text +renderTsElement = \case + TsRequired t -> renderTsType t + TsOptional t -> renderTsOperand t <> "?" + TsRest t -> "..." <> renderTsOperand t <> "[]" + +renderTsProperty :: Text -> Bool -> TsType -> Text +renderTsProperty name isOptional t = + tsPropertyKey name <> (if isOptional then "?: " else ": ") <> renderTsType t + +tsPropertyKey :: Text -> Text +tsPropertyKey name + | isIdentifier name = name + | otherwise = tsStringLiteral name + where + isIdentifier t = case Text.uncons t of + Just (c, rest) -> identifierStart c && Text.all identifierChar rest + Nothing -> False + identifierStart c = isAlpha c || c == '_' || c == '$' + identifierChar c = isAlphaNum c || c == '_' || c == '$' + +tsStringLiteral :: Text -> Text +tsStringLiteral = LText.toStrict . encodeToLazyText . String + +-- | 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 + +-- Json instance helpers + +-- | An enumeration of string literals, typed as their union. +jsonEnum :: (Eq a, JsonVal p) => (a -> Text) -> [a] -> p a a +jsonEnum f as = orP [only a >? fromString (Text.unpack (f a)) | a <- as] + +jsonTag :: JsonVal p => Text -> p a b -> p a b +jsonTag k p = jsonObject (k !: p) + +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 + +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 = readMaybe (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 = jsonNumeric (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 = jsonNumeric $ 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 + +makePrisms ''These + +-- base +instance Json Bool where + json = jsonBool + jsonKey = + Just (jsonEnumWith (\b -> if b then "true" else "false") [False, True]) +instance Json Ordering where + json = jsonTyped (jsonEnum (Text.pack . show) [LT, EQ, GT]) +instance Json () where + json = jsonTuple oneP + jsonOmitField _ = True + jsonOmittedField = Just () +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 + jsonKey = jsonKeyList @a +instance Json a => Json (Maybe a) where + json = eotMaybe . swapped >~ jsonNull >+< json + jsonOmitField = isNothing + jsonOmittedField = 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 + 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) +_Integer :: Prism' Scientific Integer +_Integer = prism' fromInteger $ + boundedScientific >=> either (const Nothing) Just . floatingOrInteger @Double +instance Json Integer where + json = jsonTyped (_Integer ?< jsonNumber) + jsonKey = Just (jsonIntKey _Integer) +_Natural :: Prism' Scientific Natural +_Natural = prism' fromIntegral $ \s -> do + i <- preview _Integer s + fromInteger i <$ guard (i >= 0) +instance Json Natural where + json = jsonTyped (_Natural ?< jsonNumber) + 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 = coerce (jsonOmitField @a) + jsonOmittedField = coerce (jsonOmittedField @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 = coerce (jsonOmitField @a) + jsonOmittedField = coerce (jsonOmittedField @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 _ = True + jsonOmittedField = Just Proxy +-- tuples +-- | An element of a tuple, by its projection. +projectElem :: (Json a, JsonTup p q) => (s -> a) -> q s a +projectElem f = lmap f (jsonElem json) + +instance (Json a, Json b) => Json (a, b) where + json = jsonTuple (jsonElem json >*< jsonElem json) +instance (Json a, Json b, Json c) => Json (a, b, c) where + json = jsonTuple $ (,,) + <$> projectElem (\(a, _, _) -> a) + <*> projectElem (\(_, b, _) -> b) + <*> projectElem (\(_, _, c) -> c) +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 + 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 :: ((DayOfWeek -> Text) -> [DayOfWeek] -> r) -> r +weekdays enumerate = enumerate (Text.toLower . Text.pack . show) + [Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday] + +instance Json DayOfWeek where + json = jsonTyped (weekdays jsonEnum) + jsonKey = Just (jsonTyped (weekdays jsonEnumWith)) + +-- | Quarters of the year, named as @aeson@ names them. +quarters :: ((QuarterOfYear -> Text) -> [QuarterOfYear] -> r) -> r +quarters enumerate = + enumerate (Text.toLower . Text.pack . show) [Q1, Q2, Q3, Q4] + +instance Json QuarterOfYear where + json = jsonTyped (quarters jsonEnum) + jsonKey = Just (jsonTyped (quarters jsonEnumWith)) + +-- 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 = coerce (jsonOmitField @b) + jsonOmittedField = coerce (jsonOmittedField @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 >? jsonObject ("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 = Strict.isNothing + jsonOmittedField = Just Strict.Nothing +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) + => Json (GHC.Generically a) where + json = dimap (\(GHC.Generically a) -> a) GHC.Generically + (jsonGeneric Aeson.defaultOptions) + +{- | 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, JsonVal p) + => Aeson.Options -> p a a +jsonGeneric opts = + jsonTyped (dimap (GHC.unM1 . GHC.from) (GHC.to . GHC.M1) (gsum opts)) + +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 + +-- | 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 + +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 `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) + 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 + +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)) + gtagged opts tagField contentsField = + GHC.M1 #. gobject opts (tag >* contents) .# GHC.unM1 + where + tag :: JsonObj p q => q () () + tag = tagField !: fromString (gconTag @c opts) + contents :: 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 = + jsonObject (Text.pack (gconTag @c opts) !: gcons @(GHC.C1 c f) opts) + gtwoElements opts = jsonTuple + ( lmap (const ()) (jsonElem (fromString (gconTag @c opts))) + *> jsonElem (gcons @(GHC.C1 c f) opts) + ) + +-- | 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 :: 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` & `jsonOmittedField`. + property :: JsonObj p q => q a a + property = case jsonOmittedField @a of + Just omitted + | Aeson.allowOmittedFields opts || Aeson.omitNothingFields opts -> + dimap present (fromMaybe omitted) (key ?: json) + _ -> key !: json + present a + | Aeson.omitNothingFields opts && jsonOmitField a = Nothing + | otherwise = Just a + gfield = Just ((GHC.M1 . GHC.K1) #. json .# GHC.unK1 . GHC.unM1) +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 +instance GFields GHC.U1 where + gfields _ = dimap (const ()) (const GHC.U1) oneP + gfield = Nothing + +class GElements f where + gelements :: JsonTup p q => q (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 +instance (GElements f, GElements g) => GElements (f GHC.:*: g) where + gelements = dimap2 + (\(a GHC.:*: _) -> a) (\(_ GHC.:*: b) -> b) (GHC.:*:) gelements gelements +instance GElements GHC.U1 where + gelements = dimap (const ()) (const GHC.U1) oneP + +-- | 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) + +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 +instance (GElements f, GElements g) => GContents (f GHC.:*: g) where + gcontents = jsonTuple gelements +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 +instance GNullary (f GHC.:*: g) where + gnullary = Nothing diff --git a/src/Control/Lens/Grammar/Machine.hs b/src/Control/Lens/Grammar/Machine.hs index 0fb7f508..63b15e08 100644 --- a/src/Control/Lens/Grammar/Machine.hs +++ b/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 (..)) @@ -366,13 +366,13 @@ prefixGen et word = go 0 (initialChart et) word {- | What token is expected next? The scanner frontier, `expectNext` returns the `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 diff --git a/src/Control/Lens/Grammar/Kleene.hs b/src/Control/Lens/Grammar/RegEx.hs similarity index 76% rename from src/Control/Lens/Grammar/Kleene.hs rename to src/Control/Lens/Grammar/RegEx.hs index 78a0ae01..0f0ba61a 100644 --- a/src/Control/Lens/Grammar/Kleene.hs +++ b/src/Control/Lens/Grammar/RegEx.hs @@ -1,6 +1,6 @@ {- | -Module : Control.Lens.Grammar.Kleene -Description : Kleene star algebras, regular expressions & token classes +Module : Control.Lens.Grammar.RegEx +Description : regular expressions & token classes Copyright : (C) 2026 - Eitan Chatav License : BSD-style (see the file LICENSE) Maintainer : Eitan Chatav @@ -12,12 +12,9 @@ Regular expressions form a Kleene star algebra. See Kleene, (https://www.rand.org/pubs/research_memoranda/RM704.html) -} -module Control.Lens.Grammar.Kleene - ( -- * KleeneStarAlgebra - KleeneStarAlgebra (..) - , orK, anyK - -- * TokenAlgebra - , TokenAlgebra (..) +module Control.Lens.Grammar.RegEx + ( -- * TokenAlgebra + TokenAlgebra (..) -- * RegEx & TokenClass , RegEx (..) , TokenClass (..) @@ -25,8 +22,6 @@ module Control.Lens.Grammar.Kleene , CategoryTest (..) ) where -import Control.Applicative -import Control.Lens.Grammar.Boole import Control.Lens.Grammar.Symbol import Control.Lens.Grammar.Token import Control.Monad.Loops @@ -34,7 +29,7 @@ import Control.Monad.State (StateT, state) import Data.Bifunctor.Joker import Data.Foldable import Data.MemoTrie -import Data.Monoid +import Data.Monoid.Disjunctive import Data.Profunctor import Data.Profunctor.Distributor import Data.Set (Set) @@ -47,53 +42,6 @@ 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 @@ -140,13 +88,13 @@ data CategoryTest 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 +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 `TokenClass` is the fixed point algebra of t`RegExam`. `TokenClass`es may be understood as normalizations of @@ -157,17 +105,16 @@ 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`, +When a `TokenAlgebra` is a `DisjunctiveMonoid`, then `tokenClass` is expected to act homomorphically on disjunction. -prop> empty = tokenClass falseB -prop> tokenClass x <|> tokenClass y = tokenClass (x >||< y) +prop> falseP = tokenClass falseP +prop> tokenClass x >|< tokenClass y = tokenClass (x >|< y) -Likewise, when a `TokenAlgebra` is a `KleeneStarAlgebra`, -then `tokenClass` is expected to act homorphically on disjunction. +Likewise, when a `TokenAlgebra` is `Alternative`, -prop> zeroK = tokenClass falseB -prop> tokenClass x >|< tokenClass y = tokenClass (x >||< y) +prop> empty = tokenClass falseP +prop> tokenClass x <|> tokenClass y = tokenClass (x >|< y) -} class Tokenized token p => TokenAlgebra token p where @@ -178,13 +125,12 @@ class Tokenized token p => TokenAlgebra token p where tokenClass (TokenClass exam) = case exam of OneOf chars -> oneOf chars NotOneOf chars (AndAsIn cat) -> - satisfy (notOneOf chars >&&< asIn cat) + satisfy (notOneOf chars >&< asIn cat) NotOneOf chars (AndNotAsIn cats) -> - satisfy (notOneOf chars >&&< allB notAsIn cats) - Alternate exam1 exam2 -> tokenClass exam1 <|> tokenClass exam2 + satisfy (notOneOf chars >&< allP 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) @@ -207,6 +153,8 @@ deriving stock instance 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 @@ -270,23 +218,13 @@ instance Categorized token => Monoid (RegEx token) where instance Categorized token => Semigroup (RegEx token) where SeqEmpty <> rex = rex rex <> SeqEmpty = rex - RegExam exam <> _ | isFailExam exam = zeroK - _ <> RegExam exam | isFailExam exam = zeroK + RegExam exam <> _ | isFailExam exam = falseP + _ <> RegExam exam | isFailExam exam = falseP 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 +instance Categorized token => DisjunctiveMonoid (RegEx token) where + falseP = RegExam failExam rex0 >|< rex1 | rex0 == rex1 = rex0 KleenePlus rex >|< SeqEmpty = starK rex SeqEmpty >|< KleenePlus rex = starK rex @@ -299,8 +237,19 @@ instance Categorized token => KleeneStarAlgebra (RegEx token) where toTokenClass (RegExam exam) = TokenClass <$> traverse toTokenClass exam toTokenClass _ = Nothing - maybeOr = (>||<) <$> toTokenClass rex0 <*> toTokenClass rex1 + maybeOr = (>|<) <$> toTokenClass rex0 <*> toTokenClass rex1 rex0 >|< rex1 = RegExam (Alternate rex0 rex1) +instance Categorized token => KleeneStarAlgebra (RegEx token) where + 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 = falseP + plusK SeqEmpty = mempty + plusK rex = KleenePlus rex instance Categorized token => Tokenized token (RegExam token alg) where anyToken = passExam token a = OneOf (Set.singleton a) @@ -311,42 +260,51 @@ instance Categorized token => Tokenized token (RegExam token alg) where 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 (RegExam token (TokenClass token)) where + falseP = failExam + 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) 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 + trueP = passExam + notP exam | isFailExam exam = passExam + notP exam | isPassExam exam = failExam + notP (Alternate (TokenClass x) (TokenClass y)) = notP x >&< notP y + 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 (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 + NotOneOf xs (AndAsIn y) >&< OneOf zs = OneOf (Set.filter (\z -> categorize z == y) (Set.difference zs xs)) - OneOf xs >&&< NotOneOf ys (AndNotAsIn zs) = OneOf + 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 + 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) = + 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) = + 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) = + 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) = + NotOneOf xs (AndNotAsIn ys) >&< NotOneOf ws (AndNotAsIn zs) = let xws = Set.union xs ws yzs = Set.union ys zs @@ -354,13 +312,6 @@ instance Categorized token 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) diff --git a/src/Data/Monoid/Disjunctive.hs b/src/Data/Monoid/Disjunctive.hs new file mode 100644 index 00000000..3616103d --- /dev/null +++ b/src/Data/Monoid/Disjunctive.hs @@ -0,0 +1,395 @@ +{- | +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 GHC.Conc (STM) +import GHC.Generics +import Text.ParserCombinators.ReadP (ReadP) +import Text.ParserCombinators.ReadPrec (ReadPrec) + +{- | 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 + +--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) +instance DisjunctiveMonoid (Maybe a) +instance DisjunctiveMonoid (IO a) +instance DisjunctiveMonoid (STM a) +instance DisjunctiveMonoid (ZipList a) +instance DisjunctiveMonoid (ReadP a) +instance DisjunctiveMonoid (ReadPrec a) +instance DisjunctiveMonoid (U1 p) +instance MonadPlus m => DisjunctiveMonoid (WrappedMonad m a) +instance ArrowPlus a => DisjunctiveMonoid (WrappedArrow a b c) +instance ArrowPlus a => DisjunctiveMonoid (ArrowMonad a b) +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 (Applicative f, DisjunctiveMonoid (f k), Monoid k) + => KleeneStarAlgebra (Ap f k) +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/src/Data/Profunctor/Distributor.hs b/src/Data/Profunctor/Distributor.hs index c156538c..1c7de6dc 100644 --- a/src/Data/Profunctor/Distributor.hs +++ b/src/Data/Profunctor/Distributor.hs @@ -9,12 +9,15 @@ Portability : non-portable -} module Data.Profunctor.Distributor - ( -- * Distributor - Distributor (..) + ( -- * CocartesianMonoidal + CocartesianMonoidal (..) , dialt + -- * Distributor + , Distributor (..) + -- * CocartesianChoice + , CocartesianChoice (..) -- * Alternator , Alternator (..) - , choice ) where import Control.Applicative hiding (WrappedArrow) @@ -28,6 +31,7 @@ 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 @@ -72,31 +76,33 @@ distributing an action over sum-of-products datatypes. -} -class Monoidal p => Distributor p where +class Profunctor p => CocartesianMonoidal p where {- | The zero structure morphism of a `Distributor`. - `zeroP` has a default for `Alternator`s. + `zeroP` has a default for `CocartesianChoice`s. - prop> zeroP = empty + prop> zeroP = falseP -} zeroP :: p Void Void - default zeroP :: Alternator p => p Void Void - zeroP = empty + default zeroP :: CocartesianChoice p => p Void Void + zeroP = falseP {- | The sum structure morphism of a `Distributor`. - `>+<` has a default for `Alternator`s. + `>+<` has a default for `CocartesianChoice`s. - prop> x >+< y = alternate (Left x) <|> alternate (Right y) + 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 + :: CocartesianChoice p => p a b -> p c d -> p (Either a c) (Either b d) - x >+< y = alternate (Left x) <|> alternate (Right y) + x >+< y = alternate (Left x) >|< alternate (Right y) infixr 3 >+< +class (Monoidal p, CocartesianMonoidal p) => Distributor p where + {- | One or none. -} optionalP :: p a b -> p (Maybe a) (Maybe b) optionalP p = eotMaybe >~ p >+< oneP @@ -105,111 +111,166 @@ class Monoidal p => Distributor p where manyP :: p a b -> p [a] [b] manyP p = eotList >~ p >*< manyP p >+< oneP -instance Distributor (->) where +instance CocartesianMonoidal (->) where zeroP = id (>+<) = (+++) -instance Monoid s => Distributor (Forget s) where +instance Distributor (->) +instance CocartesianMonoidal (Forget s) where zeroP = Forget absurd Forget kL >+< Forget kR = Forget (either kL kR) -instance Decidable f => Distributor (Clown f) where +instance Monoid s => Distributor (Forget s) +instance Decidable f => CocartesianMonoidal (Clown f) where zeroP = Clown lost Clown x >+< Clown y = Clown (chosen x y) -instance Alternative f => Distributor (Joker f) where +instance Decidable f => Distributor (Clown f) +instance Alternative f => CocartesianMonoidal (Joker f) where zeroP = Joker empty Joker x >+< Joker y = Joker (Left <$> x <|> Right <$> y) +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 +instance (CocartesianMonoidal p, Applicative f) + => CocartesianMonoidal (WrappedPafb f p) where zeroP = WrapPafb (rmap pure zeroP) WrapPafb x >+< WrapPafb y = WrapPafb $ dialt id (fmap Left) (fmap Right) x y +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 +instance Functor f => CocartesianMonoidal (Star f) where zeroP = Star absurd Star f >+< Star g = Star (either (fmap Left . f) (fmap Right . g)) +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 => CocartesianMonoidal (Kleisli m) deriving via (Star m) instance Monad m => Distributor (Kleisli m) -instance Adjunction f u => Distributor (Costar f) where +instance Adjunction f u => CocartesianMonoidal (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 +instance Adjunction f u => Distributor (Costar f) +instance (Applicative f, CocartesianMonoidal p) + => CocartesianMonoidal (Cayley f p) where zeroP = Cayley (pure zeroP) Cayley x >+< Cayley y = Cayley ((>+<) <$> x <*> y) +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) where + => CocartesianMonoidal (Pro.WrappedArrow p) where zeroP = zeroArrow (>+<) = (+++) +instance (ArrowZero p, ArrowChoice p) + => Distributor (Pro.WrappedArrow p) +deriving via (Pro.WrappedArrow p) + instance (ArrowZero p, ArrowChoice p) + => CocartesianMonoidal (Ap.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 +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 (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 +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 (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 +instance CocartesianMonoidal p => CocartesianMonoidal (Yoneda p) where zeroP = proreturn zeroP ab >+< cd = proreturn (proextract ab >+< proextract cd) +instance Distributor p => Distributor (Yoneda p) where optionalP = proreturn . optionalP . proextract manyP = proreturn . manyP . proextract -instance Distributor p => Distributor (Coyoneda p) where +instance CocartesianMonoidal p => CocartesianMonoidal (Coyoneda p) where zeroP = proreturn zeroP ab >+< cd = proreturn (proextract ab >+< proextract cd) +instance Distributor p => Distributor (Coyoneda p) where optionalP = proreturn . optionalP . proextract manyP = proreturn . manyP . proextract {- | `dialt` is a functionalized form of `>+<`. -} dialt - :: Distributor p + :: 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) --- Alternator -- +-- CocartesianChoice -- -{- | 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. +{- | `CocartesianChoice` co-extends `Choice` and `CocartesianMonoidal`, +with `DisjunctiveMonoid` failure `falseP` and choice `>|<`, +like `Alternative` but without requiring `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 = 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 +prop> zeroP = falseP +prop> x >+< y = alternate (Left x) >|< alternate (Right y) 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`. +out to be slighly 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) + +-- 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 + +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`, @@ -217,43 +278,19 @@ 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)) +class (Distributor p, CocartesianChoice 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 + 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 + => CocartesianChoice (WrappedPafb f p) where alternate = let f = WrapPafb @@ -268,21 +305,26 @@ instance (Alternator p, Applicative f) . unwrapPafb in either f g +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) -instance Alternator p => Alternator (Coyoneda p) where +instance Alternator p => CocartesianChoice (Coyoneda p) where alternate (Left p) = proreturn (alternate (Left (proextract p))) alternate (Right p) = proreturn (alternate (Right (proextract p))) +instance Alternator p => Alternator (Coyoneda p) where someP = proreturn . someP . proextract optionP def = proreturn . optionP def . proextract -instance Alternator p => Alternator (Yoneda p) where +instance Alternator p => CocartesianChoice (Yoneda p) where alternate (Left p) = proreturn (alternate (Left (proextract p))) alternate (Right p) = proreturn (alternate (Right (proextract p))) +instance Alternator p => Alternator (Yoneda p) where someP = proreturn . someP . proextract optionP def = proreturn . optionP def . proextract -instance Alternative f => Alternator (Joker f) where +instance Alternative f => CocartesianChoice (Joker f) where alternate (Left (Joker x)) = Joker (Left <$> x) alternate (Right (Joker y)) = Joker (Right <$> y) +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/src/Data/Profunctor/Filtrator.hs index 4adc28df..b2c122c9 100644 --- a/src/Data/Profunctor/Filtrator.hs +++ b/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 @@ -71,9 +71,9 @@ mfiltrate => 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 diff --git a/src/Data/Profunctor/Grammar.hs b/src/Data/Profunctor/Grammar.hs index ee88cc91..ee5eb6dc 100644 --- a/src/Data/Profunctor/Grammar.hs +++ b/src/Data/Profunctor/Grammar.hs @@ -26,14 +26,15 @@ 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.RegEx import Control.Lens.Grammar.Symbol import Control.Lens.Grammar.Token import Control.Monad import Control.Monad.Fail.Try import Data.Coerce import Data.Monoid +import Data.Monoid.Disjunctive import Data.Profunctor import Data.Profunctor.Distributor import Data.Profunctor.Filtrator @@ -106,11 +107,13 @@ 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) => CocartesianMonoidal (Parsor s m) instance (Alternative m, Monad m) => Distributor (Parsor s m) 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 +123,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 @@ -210,16 +214,19 @@ 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 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 +instance Applicative f => Distributor (Printor s f) +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) = @@ -304,18 +311,21 @@ 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) instance Tokenized token k => Tokenized token (Grammor k a b) where diff --git a/src/Data/Profunctor/Grammar/Parsector.hs b/src/Data/Profunctor/Grammar/Parsector.hs index bf00e228..4f8590e9 100644 --- a/src/Data/Profunctor/Grammar/Parsector.hs +++ b/src/Data/Profunctor/Grammar/Parsector.hs @@ -27,13 +27,13 @@ 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.RegEx 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.Distributor import Data.Profunctor.Filtrator @@ -119,7 +119,7 @@ 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 +144,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) @@ -337,8 +337,10 @@ instance Strong (Parsector s) where instance Categorized (Item s) => Choice (Parsector s) where left' = alternate . Left right' = alternate . Right +instance Categorized (Item s) => CocartesianMonoidal (Parsector s) instance Categorized (Item s) => Distributor (Parsector s) -instance Categorized (Item s) => Alternator (Parsector s) where +instance Categorized (Item s) => DisjunctiveMonoid (Parsector s a b) +instance Categorized (Item s) => CocartesianChoice (Parsector s) where alternate (Left p) = Parsector $ \callback query -> callback $ let replyOk = query @@ -369,6 +371,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/src/Data/Profunctor/Monoidal.hs b/src/Data/Profunctor/Monoidal.hs index a1e83e36..ed9f78c4 100644 --- a/src/Data/Profunctor/Monoidal.hs +++ b/src/Data/Profunctor/Monoidal.hs @@ -17,15 +17,24 @@ module Data.Profunctor.Monoidal , dimap2, foreverP, ditraverse -- * Monoidal & Choice , pureP, asEmpty, (>:<), snocP, replicateP, onlyOne + -- * Monoidal & Strong + , idP, arrP -- * Monoidal, Choice & Strong , meander, traverseP, foldP + -- * Deriving via Monoidal + , 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 @@ -236,3 +245,77 @@ 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 + +{- | 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/src/Data/Profunctor/Separator.hs b/src/Data/Profunctor/Separator.hs index bbbeaa9a..f050660c 100644 --- a/src/Data/Profunctor/Separator.hs +++ b/src/Data/Profunctor/Separator.hs @@ -32,6 +32,7 @@ import Control.Lens import Control.Lens.PartialIso import Control.Lens.Grammar.Symbol import Data.Maybe (fromMaybe) +import Data.Monoid.Disjunctive (orP) import Data.Profunctor.Distributor import Data.Profunctor.Monoidal import GHC.Exts @@ -190,7 +191,7 @@ _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 ")" + let atom = rule "atom" $ nat >|< terminal "(" >* expr *< terminal ")" nat = rule "nat" $ _Nat . iso show read >? someP (asIn @Char DecimalNumber) in withOperators [ [ Postfix _Fac (terminal "!") ] @@ -242,13 +243,13 @@ withOperators table p = foldl makeLevel p table 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] + tagSepP syms = orP [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 + fwd x = orP [ (\y -> (i,y)) <$> f x | (i, (f,_)) <- zip [0 :: Int ..] fns ] bwd (i,y) = case drop i fns of (_,g):_ -> g y @@ -258,7 +259,7 @@ withOperators table p = foldl makeLevel p table difoldl (partialIso fwd bwd) >? inner >*< manyP (tagSepP (snd <$> ops)) where fns = [withPartialIso pat (,) | (pat, _) <- ops] - fwd x = choice + fwd x = orP [ (\y -> (y,i)) <$> f x | (i, (f,_)) <- zip [0 :: Int ..] fns ] bwd (y,i) = case drop i fns of (_,g):_ -> g y @@ -310,6 +311,6 @@ withOperators table p = foldl makeLevel p table let (r0, rest) = decompose r in (l, (i,r0) : rest) _ -> let (l0, prior) = decompose l in (l0, prior ++ [(i,r)]) - tryTags y = choice + tryTags y = orP [ (\(l,r) -> (i,l,r)) <$> f y | (i,(_,f,_)) <- zip [0 :: Int ..] fns ] diff --git a/test/Examples/Arithmetic.hs b/test/Examples/Arithmetic.hs index f7ee1bb6..9bb1fa7d 100644 --- a/test/Examples/Arithmetic.hs +++ b/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 @@ -25,7 +24,7 @@ arithGrammar = ruleRec "arith" sumG prodG arith = rule "product" $ chain1 Left _Mul (sepWith "*") (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/test/Examples/Chain.hs index 1b54285a..c806557e 100644 --- a/test/Examples/Chain.hs +++ b/test/Examples/Chain.hs @@ -4,7 +4,6 @@ module Examples.Chain , chainExamples ) where -import Control.Applicative import Control.Lens import Control.Lens.Grammar @@ -22,9 +21,9 @@ chainGrammar = ruleRec "chain" seqG seqG chn = rule "seq" $ chain Left _Seq _Emp noSep (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/test/Examples/Expression.hs index ba237aa9..65184077 100644 --- a/test/Examples/Expression.hs +++ b/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,7 +72,7 @@ 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 @@ -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/test/Examples/Json.hs b/test/Examples/Json.hs index eb1b24d6..e7cdeaf7 100644 --- a/test/Examples/Json.hs +++ b/test/Examples/Json.hs @@ -4,7 +4,6 @@ module Examples.Json , jsonExamples ) where -import Control.Applicative import Control.Lens import Control.Lens.Grammar import qualified Data.Map.Strict as Map @@ -38,7 +37,7 @@ jsonGrammar = rule "json" elementG ws >* 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 >~ @@ -65,7 +64,7 @@ jsonGrammar = rule "json" elementG 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 "]" ] @@ -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 "/" diff --git a/test/Examples/Lambda.hs b/test/Examples/Lambda.hs index 3c43425c..1c13c972 100644 --- a/test/Examples/Lambda.hs +++ b/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 ] @@ -37,7 +37,7 @@ lambdaGrammar = ruleRec "lambda" termG chain1 Left _App (sepWith " ") (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/RegString.hs b/test/Examples/RegString.hs index bdd1bdf4..1069a603 100644 --- a/test/Examples/RegString.hs +++ b/test/Examples/RegString.hs @@ -8,7 +8,7 @@ regexExamples :: [(RegString, String)] regexExamples = [ (terminal "abc123etc.", "abc123etc.") , (terminal "x" <> terminal "y", "xy") - , (zeroK, "[]") + , (falseP, "[]") , (terminal "xy" >|< terminal "z", "xy|z") , (token 'x' >|< token 'y', "[xy]") , (optK (terminal "x"), "x?") @@ -24,37 +24,37 @@ regexExamples = , (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 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 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}") + -- 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}") - -- trueB & falseB - , (tokenClass trueB, "[^]") - , (tokenClass falseB, "[]") + -- 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 (notB (oneOf "abc" >||< asIn MathSymbol)), "[^abc\\P{Sm}]") + , (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/test/Examples/SExpr.hs index 5cef3e42..5fad88ab 100644 --- a/test/Examples/SExpr.hs +++ b/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 ] diff --git a/test/Examples/SemVer.hs b/test/Examples/SemVer.hs index c8f2ba55..a204b856 100644 --- a/test/Examples/SemVer.hs +++ b/test/Examples/SemVer.hs @@ -5,7 +5,6 @@ module Examples.SemVer , semverExamples ) where -import Control.Applicative import Control.Lens import Control.Lens.Grammar import qualified Data.Profunctor.Monadic as P @@ -44,9 +43,9 @@ semverGrammar = _SemVer numberG = iso show read >~ someP (asIn @Char DecimalNumber) identifiersG = several1 (sepWith ".") (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 @@ -55,9 +54,9 @@ semverCtxGrammar = _SemVer >? P.do numberG = iso show read >~ someP (asIn @Char DecimalNumber) identifiersG = several1 (sepWith ".") (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/test/Main.hs index 7477aa8e..0c102b1b 100644 --- a/test/Main.hs +++ b/test/Main.hs @@ -24,6 +24,7 @@ import Examples.LenVec import Examples.RegString import Examples.SemVer import Examples.SExpr +import Properties.Json import Properties.Kleene main :: IO () @@ -49,6 +50,16 @@ main = do describe "Parsector try rollback" tryRollbackTests describe "Kleene" kleeneProperties describe "meander" meanderProperties + jsonTypeSpec + aesonSpec + jsonErrorSpec + jsonObjectSpec + jsonOptionsSpec + jsonTupleSpec + jsonTupleChoiceSpec + jsonOptionalSpec + jsonCodecSpec + jsonPrintSpec parseForestTests :: Spec parseForestTests = do diff --git a/test/Properties/Json.hs b/test/Properties/Json.hs new file mode 100644 index 00000000..cf2fedef --- /dev/null +++ b/test/Properties/Json.hs @@ -0,0 +1,1136 @@ +-- | 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 + ) where + +import Control.Lens (coerced, only, prism') +import Control.Lens.Grammar + ( dimap, lmap, manyP, optionP, optionalP, rule, someP + , (>*<), (>+<), (>?), (>|<), (>~) + ) +import Control.Lens.Grammar.Json +import Data.Aeson + ( FromJSON (..), Options (..), SumEncoding (..), ToJSON (..), Value (String) + , camelTo2, decode, defaultOptions, 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 (\b -> if b then "yes" else "no") [False, 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 (\b -> if b then "yes" else "no") [False, 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) + jsonPrintError (Limit 10) `shouldBe` Right (object []) + jsonPrintError (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 + jsonPrintError 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) + jsonPrintError (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 Exclude<\"no\" | \"yes\", \"yes\">]?: Int };" + ] + roundTrip (object ["yes" .= (2 :: Int), "no" .= (1 :: Int)]) + (Votes (2, [(False, 1)])) + it "types numeric keys as template literals" $ do + declares (type (Box (Map Int Bool))) + [ "export type Box_Map_Int_Bool = { [key: `${number}`]: boolean };" + ] + declares (type Scores) + [ "export type Scores = \ + \{ name: string; [key: `${number}`]: boolean };" + ] + 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 + jsonPrintError 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 "jsonPrintError" $ 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. +declares :: forall a -> Json a => [Text] -> Expectation +declares a declarations = jsonTypes [a] `shouldBe` Text.unlines declarations + +jsonTypeSpec :: Spec +jsonTypeSpec = describe "jsonTypes" $ 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 (jsonTypes [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 "quotes property keys" $ + declares (type Optional) + ["export type Optional = { a: number; \"b c\"?: string | number };"] + it "declares types sharing their type aliases" $ + jsonTypes (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) + +-- | 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 <$> jsonEncodeError (Point 1 2) + `shouldBe` Right "{\"px\":1,\"py\":2}" + +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 <$> jsonEncodeError 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 . jsonPrintError + +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 @(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 jsonPrintError 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) arbitrary + aesonCompat @[Down Char] 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)) diff --git a/test/Properties/Kleene.hs b/test/Properties/Kleene.hs index f3ae1652..629805e3 100644 --- a/test/Properties/Kleene.hs +++ b/test/Properties/Kleene.hs @@ -11,8 +11,8 @@ instance Arbitrary (TokenClass Char) where arbitrary = sized go where go 0 = frequency - [ (1, pure falseB) - , (1, pure trueB) + [ (1, pure falseP) + , (1, pure trueP) , (4, oneOf <$> (arbitrary :: Gen [Char])) , (4, notOneOf <$> (arbitrary :: Gen [Char])) , (3, asIn <$> arbitrary) @@ -20,16 +20,16 @@ instance Arbitrary (TokenClass Char) where ] 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)) + , (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 (zeroK :: RegEx Char)) + [ (1, pure (falseP :: RegEx Char)) , (1, pure (mempty :: RegEx Char)) , (6, tokenClass <$> (arbitrary :: Gen (TokenClass Char))) ] @@ -53,27 +53,27 @@ kleeneProperties = do 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 "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 "zeroK <> x = zeroK" $ \(x :: RegEx Char) -> - (zeroK <> x) == zeroK - prop "x <> zeroK = zeroK" $ \(x :: RegEx Char) -> - (x <> zeroK) == zeroK + 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 describe "TokenAlgebra" $ do - it "zeroK = tokenClass falseB" $ - (zeroK :: RegEx Char) `shouldBe` tokenClass falseB - prop "tokenClass x >|< tokenClass y = tokenClass (x >||< y)" $ + 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) + == tokenClass (x >|< y) describe "TokenAlgebra RegEx" $ do it "anyToken = tokenClass anyToken" $ (anyToken :: RegEx Char) `shouldBe` tokenClass anyToken @@ -113,25 +113,25 @@ kleeneProperties = do 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" $ + 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]) -> - notB (oneOf cs :: TokenClass Char) == notOneOf cs - prop "notB . notOneOf = oneOf" $ + notP (oneOf cs :: TokenClass Char) == notOneOf cs + prop "notP . notOneOf = oneOf" $ \(cs :: [Char]) -> - notB (notOneOf cs :: TokenClass Char) == oneOf cs - prop "notB . asIn = notAsIn" $ + notP (notOneOf cs :: TokenClass Char) == oneOf cs + prop "notP . asIn = notAsIn" $ \(cat :: GeneralCategory) -> - notB (asIn cat :: TokenClass Char) == notAsIn cat - prop "notB . notAsIn = asIn" $ + notP (asIn cat :: TokenClass Char) == notAsIn cat + prop "notP . 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 + 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 From 206c287fa96491be164cda206946a8590f390e31 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Thu, 5 Nov 2026 09:30:39 -0800 Subject: [PATCH 002/130] Update Json.hs --- src/Control/Lens/Grammar/Json.hs | 31 +++++++++++++++++++++---------- 1 file changed, 21 insertions(+), 10 deletions(-) diff --git a/src/Control/Lens/Grammar/Json.hs b/src/Control/Lens/Grammar/Json.hs index 66e8d5e3..31ac3a81 100644 --- a/src/Control/Lens/Grammar/Json.hs +++ b/src/Control/Lens/Grammar/Json.hs @@ -10,8 +10,8 @@ module Control.Lens.Grammar.Json , jsonEncode , jsonEncodeError , jsonTypes - , ViaJson (..) , jsonGeneric + , ViaJson (..) -- * Grammar , JsonVal (..), jsonTyped , JsonStr (..) @@ -416,15 +416,26 @@ class (JsonVal p, 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 which aren't named, of any keys, all of a key grammar, - & their values, all of a value grammar, read as a list of pairs, - like TypeScript's index signature, @[key: string]: T@, - or, of an enumeration of keys, its mapped type, @{[key in K]?: T}@. - An object of a `jsonDict` alone, @jsonObject (jsonDict key value)@, - is a dictionary, @{[key: string]: T}@. With named properties, - a `jsonDict` reads the rest of the object, those which it doesn't name. - It names no key of its own, so an object has at most one `jsonDict`, - which printing checks, as it does for a list which repeats a key. + {- | 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 !:, ?: From 5181ec40fe4f50d4b9c4a1b7bacf1b9f76908a52 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Thu, 5 Nov 2026 09:37:18 -0800 Subject: [PATCH 003/130] Data.Profunctor.Monoidal.Cocartesian, split from Distributor CocartesianMonoidal, dialt & CocartesianChoice move to their own module, the cocartesian counterpart of Data.Profunctor.Monoidal, leaving Distributor & Alternator, which combine the two, in Data.Profunctor.Distributor. Each class is documented by its own laws. The CocartesianChoice instances of Yoneda, Coyoneda & WrappedPafb require only CocartesianChoice, rather than Alternator. Co-Authored-By: Claude Opus 5.5 --- distributors.cabal | 1 + src/Control/Lens/Bifocal.hs | 1 + src/Control/Lens/Diopter.hs | 1 + src/Control/Lens/Grammar.hs | 2 + src/Data/Profunctor/Distributor.hs | 185 +---------------- src/Data/Profunctor/Grammar.hs | 1 + src/Data/Profunctor/Grammar/Parsector.hs | 1 + src/Data/Profunctor/Monoidal/Cocartesian.hs | 213 ++++++++++++++++++++ src/Data/Profunctor/Separator.hs | 1 + src/Data/Traversable/Homogeneous.hs | 1 + 10 files changed, 228 insertions(+), 179 deletions(-) create mode 100644 src/Data/Profunctor/Monoidal/Cocartesian.hs diff --git a/distributors.cabal b/distributors.cabal index f086156a..dec42447 100644 --- a/distributors.cabal +++ b/distributors.cabal @@ -51,6 +51,7 @@ library Data.Profunctor.Grammar.Parsector Data.Profunctor.Monadic Data.Profunctor.Monoidal + Data.Profunctor.Monoidal.Cocartesian Data.Profunctor.Separator Data.Traversable.Homogeneous other-modules: diff --git a/src/Control/Lens/Bifocal.hs b/src/Control/Lens/Bifocal.hs index 30c8df93..5bef52f9 100644 --- a/src/Control/Lens/Bifocal.hs +++ b/src/Control/Lens/Bifocal.hs @@ -40,6 +40,7 @@ import Control.Lens.PartialIso import Data.Monoid.Disjunctive (DisjunctiveMonoid) import Data.Profunctor import Data.Profunctor.Distributor +import Data.Profunctor.Monoidal.Cocartesian import Data.Profunctor.Filtrator import Data.Profunctor.Separator import Witherable diff --git a/src/Control/Lens/Diopter.hs b/src/Control/Lens/Diopter.hs index 31e66548..bea153d4 100644 --- a/src/Control/Lens/Diopter.hs +++ b/src/Control/Lens/Diopter.hs @@ -27,6 +27,7 @@ module Control.Lens.Diopter import Control.Lens import Control.Lens.Internal.Profunctor import Data.Profunctor.Distributor +import Data.Profunctor.Monoidal.Cocartesian import Data.Traversable.Homogeneous import Data.Void import GHC.Generics diff --git a/src/Control/Lens/Grammar.hs b/src/Control/Lens/Grammar.hs index b6739471..98d20b44 100644 --- a/src/Control/Lens/Grammar.hs +++ b/src/Control/Lens/Grammar.hs @@ -53,6 +53,7 @@ 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.Monoidal @@ -77,6 +78,7 @@ import Control.Lens.PartialIso 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 diff --git a/src/Data/Profunctor/Distributor.hs b/src/Data/Profunctor/Distributor.hs index 1c7de6dc..7f2b3d87 100644 --- a/src/Data/Profunctor/Distributor.hs +++ b/src/Data/Profunctor/Distributor.hs @@ -9,17 +9,13 @@ Portability : non-portable -} module Data.Profunctor.Distributor - ( -- * CocartesianMonoidal - CocartesianMonoidal (..) - , dialt - -- * Distributor - , Distributor (..) - -- * CocartesianChoice - , CocartesianChoice (..) + ( -- * Distributor + Distributor (..) -- * Alternator , Alternator (..) ) where + import Control.Applicative hiding (WrappedArrow) import Control.Applicative qualified as Ap (WrappedArrow) import Control.Arrow @@ -39,7 +35,7 @@ import Data.Profunctor.Composition import Data.Profunctor.Monad import Data.Profunctor.Monoidal import Data.Profunctor.Yoneda -import Data.Void +import Data.Profunctor.Monoidal.Cocartesian -- Distributor -- @@ -47,26 +43,8 @@ import Data.Void 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 +@()@, @(,)@, `Data.Void.Void` and `Either`, being both +`Monoidal` and `CocartesianMonoidal`. `Distributor` additionally has methods `manyP` & `optionalP`, distributing an action over @[]@ and `Maybe` datatypes, @@ -74,33 +52,7 @@ which generalize to `Data.Traversable.Homogeneous.homogeneously` distributing an action over `Data.Traversable.Homogeneous.Homogeneous` sum-of-products datatypes. - -} -class Profunctor p => CocartesianMonoidal p where - - {- | The zero structure morphism of a `Distributor`. - - `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 `Distributor`. - - `>+<` 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 >+< - class (Monoidal p, CocartesianMonoidal p) => Distributor p where {- | One or none. -} @@ -111,149 +63,49 @@ class (Monoidal p, CocartesianMonoidal p) => Distributor p where manyP :: p a b -> p [a] [b] manyP p = eotList >~ p >*< manyP p >+< oneP -instance CocartesianMonoidal (->) where - zeroP = id - (>+<) = (+++) instance Distributor (->) -instance CocartesianMonoidal (Forget s) where - zeroP = Forget absurd - Forget kL >+< Forget kR = Forget (either kL kR) instance Monoid s => Distributor (Forget s) -instance Decidable f => CocartesianMonoidal (Clown f) where - zeroP = Clown lost - Clown x >+< Clown y = Clown (chosen x y) instance Decidable f => Distributor (Clown f) -instance Alternative f => CocartesianMonoidal (Joker f) where - zeroP = Joker empty - Joker x >+< Joker y = Joker (Left <$> x <|> Right <$> y) instance Alternative f => Distributor (Joker f) where optionalP (Joker x) = Joker (optional x) manyP (Joker x) = Joker (many x) -instance (CocartesianMonoidal p, Applicative f) - => CocartesianMonoidal (WrappedPafb f p) where - zeroP = WrapPafb (rmap pure zeroP) - WrapPafb x >+< WrapPafb y = WrapPafb $ - dialt id (fmap Left) (fmap Right) x y 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 Functor f => CocartesianMonoidal (Star f) where - zeroP = Star absurd - Star f >+< Star g = - Star (either (fmap Left . f) (fmap Right . g)) 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 => CocartesianMonoidal (Kleisli m) deriving via (Star m) instance Monad m => Distributor (Kleisli m) -instance Adjunction f u => CocartesianMonoidal (Costar f) where - zeroP = Costar unabsurdL - Costar f >+< Costar g = Costar (bimap f g . cozipL) instance Adjunction f u => Distributor (Costar f) -instance (Applicative f, CocartesianMonoidal p) - => CocartesianMonoidal (Cayley f p) where - zeroP = Cayley (pure zeroP) - Cayley x >+< Cayley y = Cayley ((>+<) <$> x <*> y) 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) - => CocartesianMonoidal (Pro.WrappedArrow p) where - zeroP = zeroArrow - (>+<) = (+++) instance (ArrowZero p, ArrowChoice p) => Distributor (Pro.WrappedArrow p) -deriving via (Pro.WrappedArrow p) - instance (ArrowZero p, ArrowChoice p) - => CocartesianMonoidal (Ap.WrappedArrow p) deriving via (Pro.WrappedArrow p) instance (ArrowZero p, ArrowChoice p) => Distributor (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 (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 (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 (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 CocartesianMonoidal p => CocartesianMonoidal (Yoneda p) where - zeroP = proreturn zeroP - ab >+< cd = proreturn (proextract ab >+< proextract cd) instance Distributor p => Distributor (Yoneda p) where optionalP = proreturn . optionalP . proextract manyP = proreturn . manyP . proextract -instance CocartesianMonoidal p => CocartesianMonoidal (Coyoneda p) where - zeroP = proreturn zeroP - ab >+< cd = proreturn (proextract ab >+< proextract cd) instance Distributor p => Distributor (Coyoneda p) where optionalP = proreturn . optionalP . proextract manyP = proreturn . manyP . proextract -{- | `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 `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) - -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 `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) - -- Alternator -- {- | The `Alternator` class co-extends `CocartesianChoice` and `Distributor`, @@ -289,41 +141,16 @@ class (Distributor p, CocartesianChoice p, forall x. Alternative (p x)) optionP :: APrism a b () () {- ^ default -} -> p a b -> p a b optionP def p = p >|< pureP def -instance (Alternator 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 (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) -instance Alternator p => CocartesianChoice (Coyoneda p) where - alternate (Left p) = proreturn (alternate (Left (proextract p))) - alternate (Right p) = proreturn (alternate (Right (proextract p))) instance Alternator p => Alternator (Coyoneda p) where someP = proreturn . someP . proextract optionP def = proreturn . optionP def . proextract -instance Alternator p => CocartesianChoice (Yoneda p) where - alternate (Left p) = proreturn (alternate (Left (proextract p))) - alternate (Right p) = proreturn (alternate (Right (proextract p))) instance Alternator p => Alternator (Yoneda p) where someP = proreturn . someP . proextract optionP def = proreturn . optionP def . proextract -instance Alternative f => CocartesianChoice (Joker f) where - alternate (Left (Joker x)) = Joker (Left <$> x) - alternate (Right (Joker y)) = Joker (Right <$> y) instance Alternative f => Alternator (Joker f) where someP (Joker x) = Joker (some x) optionP def (Joker x) = diff --git a/src/Data/Profunctor/Grammar.hs b/src/Data/Profunctor/Grammar.hs index ee5eb6dc..6000b7ca 100644 --- a/src/Data/Profunctor/Grammar.hs +++ b/src/Data/Profunctor/Grammar.hs @@ -37,6 +37,7 @@ 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.Void diff --git a/src/Data/Profunctor/Grammar/Parsector.hs b/src/Data/Profunctor/Grammar/Parsector.hs index 4f8590e9..7ee968df 100644 --- a/src/Data/Profunctor/Grammar/Parsector.hs +++ b/src/Data/Profunctor/Grammar/Parsector.hs @@ -36,6 +36,7 @@ import Control.Monad.Fail.Try 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.Tree diff --git a/src/Data/Profunctor/Monoidal/Cocartesian.hs b/src/Data/Profunctor/Monoidal/Cocartesian.hs new file mode 100644 index 00000000..f041644f --- /dev/null +++ b/src/Data/Profunctor/Monoidal/Cocartesian.hs @@ -0,0 +1,213 @@ +{-| +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 + +-- 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, Applicative f) + => CocartesianMonoidal (WrappedPafb f p) where + zeroP = WrapPafb (rmap pure 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) + +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 `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/src/Data/Profunctor/Separator.hs b/src/Data/Profunctor/Separator.hs index f050660c..daff3087 100644 --- a/src/Data/Profunctor/Separator.hs +++ b/src/Data/Profunctor/Separator.hs @@ -34,6 +34,7 @@ import Control.Lens.Grammar.Symbol import Data.Maybe (fromMaybe) import Data.Monoid.Disjunctive (orP) import Data.Profunctor.Distributor +import Data.Profunctor.Monoidal.Cocartesian import Data.Profunctor.Monoidal import GHC.Exts diff --git a/src/Data/Traversable/Homogeneous.hs b/src/Data/Traversable/Homogeneous.hs index 52589af0..6b02f10e 100644 --- a/src/Data/Traversable/Homogeneous.hs +++ b/src/Data/Traversable/Homogeneous.hs @@ -31,6 +31,7 @@ import Data.Void import GHC.Generics import Data.Profunctor.Distributor +import Data.Profunctor.Monoidal.Cocartesian {- | A class of `Homogeneous` countable sums of countable products. From c4a2670c116333683dafadcd838288769f8b6937 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Thu, 5 Nov 2026 09:48:29 -0800 Subject: [PATCH 004/130] pun "err or" --- src/Control/Lens/Grammar/Json.hs | 16 ++++++++-------- test/Properties/Json.hs | 20 ++++++++++---------- 2 files changed, 18 insertions(+), 18 deletions(-) diff --git a/src/Control/Lens/Grammar/Json.hs b/src/Control/Lens/Grammar/Json.hs index 31ac3a81..88daf029 100644 --- a/src/Control/Lens/Grammar/Json.hs +++ b/src/Control/Lens/Grammar/Json.hs @@ -6,9 +6,9 @@ module Control.Lens.Grammar.Json , jsonParse , jsonDecode , jsonPrint - , jsonPrintError + , jsonErrorPrint , jsonEncode - , jsonEncodeError + , jsonErrorEncode , jsonTypes , jsonGeneric , ViaJson (..) @@ -199,17 +199,17 @@ jsonDecode bytes = case Aeson.eitherDecode bytes of -- | `Data.Aeson.toJSON` jsonPrint :: Json a => a -> Value -jsonPrint = either (\_ -> Null) id . jsonPrintError +jsonPrint = either (\_ -> Null) id . jsonErrorPrint -jsonPrintError :: Json a => a -> Either JsonError Value -jsonPrintError = runJsonPrintor json +jsonErrorPrint :: Json a => a -> Either JsonError Value +jsonErrorPrint = runJsonPrintor json -- | `Data.Aeson.toEncoding` jsonEncode :: Json a => a -> Encoding -jsonEncode = either (\_ -> Encoding.null_) id . jsonEncodeError +jsonEncode = either (\_ -> Encoding.null_) id . jsonErrorEncode -jsonEncodeError :: Json a => a -> Either JsonError Encoding -jsonEncodeError = runJsonPrintor json +jsonErrorEncode :: Json a => a -> Either JsonError Encoding +jsonErrorEncode = runJsonPrintor json jsonTypes :: forall (as :: [Type]) -> All Json as => Text jsonTypes as = renderTypeScript $ hcollapse diff --git a/test/Properties/Json.hs b/test/Properties/Json.hs index cf2fedef..aab290f1 100644 --- a/test/Properties/Json.hs +++ b/test/Properties/Json.hs @@ -238,15 +238,15 @@ jsonObjectSpec :: Spec jsonObjectSpec = describe "jsonObject" $ do it "defaults a missing property" $ do jsonParse @Limit (object []) `shouldBe` Right (Limit 10) - jsonPrintError (Limit 10) `shouldBe` Right (object []) - jsonPrintError (Limit 3) `shouldBe` Right (object ["limit" .= (3 :: Int)]) + 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 - jsonPrintError extra `shouldBe` Right value + 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" @@ -258,7 +258,7 @@ jsonObjectSpec = describe "jsonObject" $ do jsonParse @Pet (object ["Cat" .= ("tom" :: Text)]) `shouldBe` Right (Cat "tom") jsonParse @Pet (object ["Dog" .= (3 :: Int)]) `shouldBe` Right (Dog 3) - jsonPrintError (Dog 3) `shouldBe` Right (object ["Dog" .= (3 :: Int)]) + jsonErrorPrint (Dog 3) `shouldBe` Right (object ["Dog" .= (3 :: Int)]) declares (type Pet) [ "export type Int = number;" , "export type Pet = { Cat: string } | { Dog: Int };" @@ -433,7 +433,7 @@ jsonTupleChoiceSpec = describe "jsonTuple choices" $ do roundTrip :: forall a. (Json a, Eq a, Show a) => Value -> a -> Expectation roundTrip value a = do jsonParse @a value `shouldBe` Right a - jsonPrintError a `shouldBe` Right value + jsonErrorPrint a `shouldBe` Right value -- | An array, as a tuple of a rest element. newtype Elements = Elements [Int] @@ -498,7 +498,7 @@ instance Json Partial where prism' Covered (\case Covered n -> Just n; _ -> Nothing) >? json jsonPrintSpec :: Spec -jsonPrintSpec = describe "jsonPrintError" $ do +jsonPrintSpec = describe "jsonErrorPrint" $ do it "labels failures with rules" $ printError Uncovered `shouldBe` Left "Error in $: cannot print as Partial" it "locates failures" $ do @@ -685,12 +685,12 @@ jsonCodecSpec = describe "jsonEncode" $ do codecCompat @Shape (oneof [Circle <$> arbitrary, Square <$> arbitrary]) codecCompat @Color arbitraryBoundedEnum it "encodes in order" $ - encodingToLazyByteString <$> jsonEncodeError (Point 1 2) + encodingToLazyByteString <$> jsonErrorEncode (Point 1 2) `shouldBe` Right "{\"px\":1,\"py\":2}" 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 <$> jsonEncodeError a) + (decode . encodingToLazyByteString <$> jsonErrorEncode a) === Right (Just (toJSON a)) -- | The error message of parsing a `Value`. @@ -699,7 +699,7 @@ 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 . jsonPrintError +printError = either (Left . errorText) Right . jsonErrorPrint errorText :: JsonError -> String errorText err = formatError (jsonErrorPath err) (jsonErrorMessage err) @@ -800,7 +800,7 @@ aesonEncodeCompat gen = it (show (typeRep (Proxy @a))) $ encodeCompat :: forall a. (Json a, ToJSON a) => a -> Property encodeCompat a = let value = toJSON a - in jsonPrintError a === Right value + in jsonErrorPrint a === Right value .&&. fmap toJSON (jsonParse @a value) === Right value aesonSpec :: Spec From 04bca43d27f7b62d9506d1c0301a4c2da52d36cc Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Thu, 5 Nov 2026 09:54:14 -0800 Subject: [PATCH 005/130] Update Distributor.hs --- src/Data/Profunctor/Distributor.hs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/Data/Profunctor/Distributor.hs b/src/Data/Profunctor/Distributor.hs index 7f2b3d87..d4118279 100644 --- a/src/Data/Profunctor/Distributor.hs +++ b/src/Data/Profunctor/Distributor.hs @@ -15,7 +15,6 @@ module Data.Profunctor.Distributor , Alternator (..) ) where - import Control.Applicative hiding (WrappedArrow) import Control.Applicative qualified as Ap (WrappedArrow) import Control.Arrow From 258f495b36e295e9bcc79155ce735e9dfba52d0b Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Thu, 5 Nov 2026 11:25:47 -0800 Subject: [PATCH 006/130] Update Json.hs --- src/Control/Lens/Grammar/Json.hs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/Control/Lens/Grammar/Json.hs b/src/Control/Lens/Grammar/Json.hs index 88daf029..96a7ae10 100644 --- a/src/Control/Lens/Grammar/Json.hs +++ b/src/Control/Lens/Grammar/Json.hs @@ -13,11 +13,10 @@ module Control.Lens.Grammar.Json , jsonGeneric , ViaJson (..) -- * Grammar - , JsonVal (..), jsonTyped + , JsonVal (..), jsonTyped, jsonObjectStrict , JsonStr (..) , JsonTup (..) , JsonObj (..) - , jsonObjectStrict , (!=) -- * Errors , JsonError (..) From 6f55733af43f00a53749723361089c3e4fb7e540 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Thu, 5 Nov 2026 12:09:02 -0800 Subject: [PATCH 007/130] Update Json.hs --- src/Control/Lens/Grammar/Json.hs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Control/Lens/Grammar/Json.hs b/src/Control/Lens/Grammar/Json.hs index 96a7ae10..a16a59e8 100644 --- a/src/Control/Lens/Grammar/Json.hs +++ b/src/Control/Lens/Grammar/Json.hs @@ -14,9 +14,9 @@ module Control.Lens.Grammar.Json , ViaJson (..) -- * Grammar , JsonVal (..), jsonTyped, jsonObjectStrict - , JsonStr (..) - , JsonTup (..) , JsonObj (..) + , JsonTup (..) + , JsonStr (..) , (!=) -- * Errors , JsonError (..) From 3c3f763d10a7c6372e9a57bfba2d83085deb4eef Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Thu, 5 Nov 2026 16:48:27 -0800 Subject: [PATCH 008/130] != --- src/Control/Lens/Grammar/Json.hs | 12 +----------- src/Control/Lens/PartialIso.hs | 16 ++++++++++++++++ 2 files changed, 17 insertions(+), 11 deletions(-) diff --git a/src/Control/Lens/Grammar/Json.hs b/src/Control/Lens/Grammar/Json.hs index a16a59e8..e8dc6a1d 100644 --- a/src/Control/Lens/Grammar/Json.hs +++ b/src/Control/Lens/Grammar/Json.hs @@ -14,10 +14,9 @@ module Control.Lens.Grammar.Json , ViaJson (..) -- * Grammar , JsonVal (..), jsonTyped, jsonObjectStrict - , JsonObj (..) + , JsonObj (..), (!=) , JsonTup (..) , JsonStr (..) - , (!=) -- * Errors , JsonError (..) , JsonErrorSort (..) @@ -439,15 +438,6 @@ class (JsonVal p, Monoidal q, CocartesianChoice q) jsonDict :: (forall k. JsonStr k => k a b) -> p c d -> q [(a, c)] [(b, d)] infixr 7 !:, ?: -{- | An optional property with a default, missing exactly when it's the -default, like @aeson@'s @.:?@ & @.!=@, by the `non` isomorphism. - -prop> prop != def = non def ~< prop --} -(!=) :: (Eq a, Profunctor q) => q (Maybe a) (Maybe a) -> a -> q a a -prop != def = non def ~< prop -infix 6 != - -- | A `jsonObject` which rejects the properties that it doesn't name. jsonObjectStrict :: JsonVal p => (forall q. JsonObj p q => q a b) -> p a b jsonObjectStrict obj = diff --git a/src/Control/Lens/PartialIso.hs b/src/Control/Lens/PartialIso.hs index a93dda6d..7b609d3f 100644 --- a/src/Control/Lens/PartialIso.hs +++ b/src/Control/Lens/PartialIso.hs @@ -32,6 +32,7 @@ module Control.Lens.PartialIso , (>?<) , (>~) , (~<) + , (!=) , coPrism -- * Patterns , satisfied @@ -236,6 +237,21 @@ infixl 2 >~ (~<) 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 != + {- | Action of a `coPrism` on the composition of a `Profunctor` and `Filterable`. -} From 2d5588aa219360ce53ea9e39aee1807ed5e88b89 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Thu, 5 Nov 2026 22:02:04 -0800 Subject: [PATCH 009/130] jsonTypes examples --- src/Control/Lens/Grammar/Json.hs | 60 ++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) diff --git a/src/Control/Lens/Grammar/Json.hs b/src/Control/Lens/Grammar/Json.hs index e8dc6a1d..ee124baa 100644 --- a/src/Control/Lens/Grammar/Json.hs +++ b/src/Control/Lens/Grammar/Json.hs @@ -209,6 +209,66 @@ jsonEncode = either (\_ -> Encoding.null_) id . jsonErrorEncode jsonErrorEncode :: Json a => a -> Either JsonError Encoding jsonErrorEncode = runJsonPrintor json +{- | + +>>> :set -XDeriveAnyClass -XDerivingStrategies -XRequiredTypeArguments +>>> import Data.Map (Map) +>>> import Data.Text (Text) +>>> import Data.Text.IO qualified as Text +>>> import GHC.Generics (Generic) + +>>> :{ +data Suit = Hearts | Diamonds | Clubs | Spades + deriving stock Generic + deriving anyclass Json +:} + +>>> Text.putStr (jsonTypes [Suit]) +export type Suit = "Hearts" | "Diamonds" | "Clubs" | "Spades"; + +>>> :{ +data Point = Point {x :: Double, y :: Double} + deriving stock Generic + deriving anyclass Json +:} + +>>> Text.putStr (jsonTypes (type '[Point])) +export type Double = number | null | "+inf" | "-inf"; +export type Point = { x: Double; y: Double }; + +>>> :{ +data Shape = Circle Point Double | Polygon {vertices :: [Point]} + deriving stock Generic + deriving anyclass Json +:} + +>>> Text.putStr (jsonTypes [Shape]) +export type Double = number | null | "+inf" | "-inf"; +export type Point = { x: Double; y: Double }; +export type Shape = { tag: "Circle"; contents: [Point, Double] } | { tag: "Polygon"; vertices: Point[] }; + +>>> :{ +data User = User {name :: Text, email :: Maybe Text, scores :: Map Int Double} + deriving stock Generic + deriving anyclass Json +:} + +>>> Text.putStr (jsonTypes (type '[User])) +export type Double = number | null | "+inf" | "-inf"; +export type User = { name: string; email?: null | string; scores: { [key: `${number}`]: Double } }; + +>>> :{ +data Tree a = Leaf | Node (Tree a) a (Tree a) + deriving stock Generic + deriving anyclass Json +:} + +>>> Text.putStr (jsonTypes [Tree Text, Tree Suit]) +export type Suit = "Hearts" | "Diamonds" | "Clubs" | "Spades"; +export type Tree_Suit = { tag: "Leaf" } | { tag: "Node"; contents: [Tree_Suit, Suit, Tree_Suit] }; +export type Tree_Text = { tag: "Leaf" } | { tag: "Node"; contents: [Tree_Text, string, Tree_Text] }; + +-} jsonTypes :: forall (as :: [Type]) -> All Json as => Text jsonTypes as = renderTypeScript $ hcollapse (hcpure (Proxy @Json) tsRoot :: NP (K (TsGrammor () ())) as) From ecb4151f9829a4341ee8809ead890eef44e2784d Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Thu, 5 Nov 2026 22:36:41 -0800 Subject: [PATCH 010/130] fix typescript name collision --- src/Control/Lens/Grammar/Json.hs | 22 +++++++++++++++------- test/Properties/Json.hs | 25 +++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 7 deletions(-) diff --git a/src/Control/Lens/Grammar/Json.hs b/src/Control/Lens/Grammar/Json.hs index ee124baa..6bf7fafb 100644 --- a/src/Control/Lens/Grammar/Json.hs +++ b/src/Control/Lens/Grammar/Json.hs @@ -1468,7 +1468,7 @@ printProperty key p a = -- TypeScript interpreters -- data TsType - = TsAlias String -- ^ @T@, a reference to a type alias + = TsAlias String -- ^ @T@, a reference to a type alias, by its identifier | TsNull -- ^ @null@ | TsUndefined -- ^ @undefined@ | TsBoolean -- ^ @boolean@ @@ -1516,7 +1516,8 @@ data TsDefinitions = TsDefinitions } {- | Define a rule once, under its unqualified name, or else its qualified -name, if taken, so that every other occurrence of it, recursive or not, +name, or else its numbered qualified name, if taken, as TypeScript +identifiers, so that every other occurrence of it, recursive or not, is its name. Its name is reserved, as `never`, while it's being defined. An unguarded occurrence is its least fixpoint instead, unrolled once, so that a rule of a rule is the rule, and a rule recurring unguarded @@ -1541,9 +1542,16 @@ tsDefine key (TsGrammor body) = TsGrammor $ do defined {tsRules = Map.insert name definition (tsRules defined)} pure (TsAlias name) where - freshName taken = fromMaybe - (until (`Map.notMember` taken) (<> "'") key) - (find (`Map.notMember` taken) [unqualified key, key]) + freshName taken = fromMaybe qualified (find free candidates) + where + free name = Map.notMember name taken && name `notElem` tsReserved + candidates = Text.unpack (tsIdentifier (unqualified key)) : qualified + : [qualified <> "_" <> show n | n <- [2 :: Int ..]] + qualified = Text.unpack (tsIdentifier key) + +-- | Global type names the rendered TypeScript refers to. +tsReserved :: [String] +tsReserved = ["Exclude"] tsGuarded :: TsDefining a -> TsDefining a tsGuarded = local (const Map.empty) @@ -1769,11 +1777,11 @@ renderTypeScript roots = (runReaderT (traverse_ (\(TsGrammor ts) -> ts) roots) Map.empty) (TsDefinitions Map.empty Map.empty) declaration (name, ty) = - "export type " <> tsIdentifier name <> " = " <> renderTsType ty <> ";" + "export type " <> Text.pack name <> " = " <> renderTsType ty <> ";" renderTsType :: TsType -> Text renderTsType = \case - TsAlias name -> tsIdentifier name + TsAlias name -> Text.pack name TsNull -> "null" TsUndefined -> "undefined" TsBoolean -> "boolean" diff --git a/test/Properties/Json.hs b/test/Properties/Json.hs index aab290f1..bf7f41aa 100644 --- a/test/Properties/Json.hs +++ b/test/Properties/Json.hs @@ -601,6 +601,17 @@ jsonTypeSpec = describe "jsonTypes" $ do , "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 Int = number;" + , "export type Int_Text = \ + \{ tag: \"L\"; contents: Int } | { tag: \"R\"; contents: string };" + , "export type Properties_Json_Exclude = number;" + , "export type " <> pair <> " = [Int, string];" + , "export type Sanitized = \ + \[Int_Text, " <> pair <> ", Properties_Json_Exclude];" + ] it "quotes property keys" $ declares (type Optional) ["export type Optional = { a: number; \"b c\"?: string | number };"] @@ -647,6 +658,20 @@ instance Json Collide where <$> lmap named ("named" !: rule "Point" jsonNumber) <*> lmap typed ("typed" !: json) +-- | Types named by the same identifier, @Int_Text@, & one named @Exclude@. +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) From ab2a9aace009b48608b3ea7e4634af090ba42f43 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Thu, 5 Nov 2026 22:44:55 -0800 Subject: [PATCH 011/130] Update Json.hs --- src/Control/Lens/Grammar/Json.hs | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/src/Control/Lens/Grammar/Json.hs b/src/Control/Lens/Grammar/Json.hs index 6bf7fafb..bc0d34b7 100644 --- a/src/Control/Lens/Grammar/Json.hs +++ b/src/Control/Lens/Grammar/Json.hs @@ -135,7 +135,6 @@ import GHC.Generics qualified as GHC import Network.URI (URI) import Network.URI qualified as URI import Numeric.Natural (Natural) -import Text.Read (readMaybe) import Text.ParserCombinators.ReadP (readP_to_S) import Type.Reflection import Witherable qualified @@ -1892,8 +1891,9 @@ tsIdentifier name = case Text.uncons ident of jsonEnum :: (Eq a, JsonVal p) => (a -> Text) -> [a] -> p a a jsonEnum f as = orP [only a >? fromString (Text.unpack (f a)) | a <- as] +-- | An object of a single property, as @aeson@ requires of sums' tags. jsonTag :: JsonVal p => Text -> p a b -> p a b -jsonTag k p = jsonObject (k !: p) +jsonTag k p = jsonObjectStrict (k !: p) boundedScientific :: Scientific -> Maybe Scientific boundedScientific s = s <$ guard (abs (base10Exponent s) <= 1024) @@ -1928,7 +1928,8 @@ readScientific :: Text -> Maybe Scientific readScientific t | canonical, Right (i, _) <- TextRead.signed TextRead.decimal t = Just (fromInteger i) - | otherwise = readMaybe (Text.unpack t) + | 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 @@ -2541,7 +2542,7 @@ instance Json b => Json (Tagged a b) where -- these instance (Json a, Json b) => Json (These a b) where json = orP - [ _These >? jsonObject ("This" !: json >*< "That" !: json) + [ _These >? jsonObjectStrict ("This" !: json >*< "That" !: json) , _This >? jsonTag "This" json , _That >? jsonTag "That" json ] @@ -2667,7 +2668,7 @@ instance (GHC.Constructor c, GFields f, GContents f, GNullary f) dimap (const ()) (const (GHC.M1 v)) (fromString (gconTag @c opts)) _ -> gcons opts gsingleField opts = - jsonObject (Text.pack (gconTag @c opts) !: gcons @(GHC.C1 c f) opts) + jsonTag (Text.pack (gconTag @c opts)) (gcons @(GHC.C1 c f) opts) gtwoElements opts = jsonTuple ( lmap (const ()) (jsonElem (fromString (gconTag @c opts))) *> jsonElem (gcons @(GHC.C1 c f) opts) From fc4be760dc5d20fc811dcd062414c926c60a0b58 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Thu, 5 Nov 2026 23:43:08 -0800 Subject: [PATCH 012/130] Update Json.hs --- src/Control/Lens/Grammar/Json.hs | 91 ++++++++++++++++++++------------ 1 file changed, 58 insertions(+), 33 deletions(-) diff --git a/src/Control/Lens/Grammar/Json.hs b/src/Control/Lens/Grammar/Json.hs index bc0d34b7..0bc1a01f 100644 --- a/src/Control/Lens/Grammar/Json.hs +++ b/src/Control/Lens/Grammar/Json.hs @@ -13,7 +13,7 @@ module Control.Lens.Grammar.Json , jsonGeneric , ViaJson (..) -- * Grammar - , JsonVal (..), jsonTyped, jsonObjectStrict + , JsonVal (..), jsonTyped , JsonObj (..), (!=) , JsonTup (..) , JsonStr (..) @@ -358,6 +358,10 @@ class 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 @@ -497,11 +501,6 @@ class (JsonVal p, Monoidal q, CocartesianChoice q) jsonDict :: (forall k. JsonStr k => k a b) -> p c d -> q [(a, c)] [(b, d)] infixr 7 !:, ?: --- | A `jsonObject` which rejects the properties that it doesn't name. -jsonObjectStrict :: JsonVal p => (forall q. JsonObj p q => q a b) -> p a b -jsonObjectStrict obj = - jsonObject (obj *< dimap (const []) (const ()) (jsonDict jsonText zeroP)) - -- Errors -- {- | A located failure to decode, parse or print a `Value`. @@ -678,11 +677,13 @@ data TupParsor a b = TupParsor {- | `ObjParsor` reads keys of an `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. +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 } @@ -771,20 +772,40 @@ instance JsonVal JsonParsor where v -> jsonMismatch "array" v where parsor = tup @TupParsor - jsonObject obj = JsonParsor dispatch parse - 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 -> runObjParsor obj named o - v -> jsonMismatch "object" v - named = HashSet.fromList (concat (objParsorShapes obj)) - dispatch = case objParsorTags obj of - (key, tags) : _ -> - Just (Dispatch (Just key) (Map.fromSet (const parse) tags)) - [] -> Nothing + jsonObject obj = objectParsor False obj + jsonObjectStrict obj = objectParsor True obj + +{- | Parse an `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 + 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 @@ -842,18 +863,19 @@ instance JsonTup JsonParsor TupParsor where Just v -> jsonAt (Index i) (runJsonParsor p v) instance Functor (ObjParsor a) where - fmap f (ObjParsor keys tags p) = - ObjParsor keys tags (\named o -> onSuccess f (p named o)) + 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 [[]] [] (\_ _ -> Right b) - ObjParsor keys0 tags0 p0 <*> ObjParsor keys1 tags1 p1 = - ObjParsor (liftA2 (<>) keys0 keys1) (tags0 <> tags1) $ \named o -> + 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 p) = - ObjParsor keys tags (\named o -> onSuccess g (p named o)) + 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 @@ -863,17 +885,18 @@ instance CocartesianMonoidal ObjParsor instance CocartesianChoice ObjParsor where alternate = either (fmap Left . coerce) (fmap Right . coerce) instance DisjunctiveMonoid (ObjParsor a b) where - falseP = ObjParsor [] [] (\_ o -> jsonUnexpected (Just (Object o))) - p >|< q = ObjParsor (objParsorShapes p <> objParsorShapes q) [] $ + 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 [[]] [] $ \named o -> + 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 $ \_ o -> case KeyMap.lookup key o of + 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 @@ -881,7 +904,7 @@ instance JsonObj JsonParsor ObjParsor where tags = case jsonParsorDispatch p of Just (Dispatch Nothing table) -> [(key, Map.keysSet table)] _ -> [] - k ?: p = ObjParsor [[key]] [] $ \_ o -> + k ?: p = ObjParsor [[key]] [] False $ \_ o -> traverse (jsonAt (Key key) . runJsonParsor p) (KeyMap.lookup key o) where key = Key.fromText k @@ -1242,6 +1265,8 @@ instance AesonVal val => JsonVal (JsonPrintor val) where Nothing where printor = obj @(ObjPrintor val) + -- | The properties which a strict object rejects are never printed. + jsonObjectStrict obj = jsonObject obj instance Functor (TupPrintor val a) where fmap _ (TupPrintor total attempt render check single) = From cc9b08439150011767d8b3b4f006a749ad67c1f0 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Fri, 6 Nov 2026 00:33:15 -0800 Subject: [PATCH 013/130] Split into distributors-core & distributors-json packages distributors-core holds the distributors package, unchanged but for Control.Lens.Grammar.Json & its tests and benchmarks, which move to the new distributors-json package, along with their dependencies. Co-Authored-By: Claude Opus 5.5 --- .../CHANGELOG.md | 0 LICENSE => distributors-core/LICENSE | 0 README.md => distributors-core/README.md | 0 Setup.hs => distributors-core/Setup.hs | 0 .../distributors.cabal | 123 -------- .../package.yaml | 28 -- .../src}/Control/Lens/Bifocal.hs | 0 .../src}/Control/Lens/Diopter.hs | 0 .../src}/Control/Lens/Grammar.hs | 0 .../src}/Control/Lens/Grammar/BackusNaur.hs | 0 .../Lens/Grammar/Internal/NestedPrismTH.hs | 0 .../Lens/Grammar/Internal/Orphanage.hs | 0 .../src}/Control/Lens/Grammar/Machine.hs | 0 .../src}/Control/Lens/Grammar/RegEx.hs | 0 .../src}/Control/Lens/Grammar/Symbol.hs | 0 .../src}/Control/Lens/Grammar/Token.hs | 0 .../src}/Control/Lens/Grate.hs | 0 .../src}/Control/Lens/Monocle.hs | 0 .../src}/Control/Lens/PartialIso.hs | 0 .../src}/Control/Lens/Wither.hs | 0 .../src}/Control/Monad/Fail/Try.hs | 0 .../src}/Data/Monoid/Disjunctive.hs | 0 .../src}/Data/Profunctor/Distributor.hs | 0 .../src}/Data/Profunctor/Filtrator.hs | 0 .../src}/Data/Profunctor/Grammar.hs | 0 .../src}/Data/Profunctor/Grammar/Parsector.hs | 0 .../src}/Data/Profunctor/Monadic.hs | 0 .../src}/Data/Profunctor/Monoidal.hs | 0 .../Data/Profunctor/Monoidal/Cocartesian.hs | 0 .../src}/Data/Profunctor/Separator.hs | 0 .../src}/Data/Traversable/Homogeneous.hs | 0 .../test}/Examples/Arithmetic.hs | 0 .../test}/Examples/Chain.hs | 0 .../test}/Examples/Expression.hs | 0 .../test}/Examples/Json.hs | 0 .../test}/Examples/Lambda.hs | 0 .../test}/Examples/LenVec.hs | 0 .../test}/Examples/RegString.hs | 0 .../test}/Examples/SExpr.hs | 0 .../test}/Examples/SemVer.hs | 0 {test => distributors-core/test}/Main.hs | 11 - .../test}/Properties/Kleene.hs | 0 distributors-json/CHANGELOG.md | 5 + distributors-json/LICENSE | 30 ++ distributors-json/README.md | 3 + {bench => distributors-json/bench}/Main.hs | 0 distributors-json/distributors-json.cabal | 267 ++++++++++++++++++ distributors-json/package.yaml | 123 ++++++++ .../src}/Control/Lens/Grammar/Json.hs | 0 distributors-json/test/Main.hs | 87 ++++++ .../test}/Properties/Json.hs | 0 stack.yaml | 3 +- 52 files changed, 517 insertions(+), 163 deletions(-) rename CHANGELOG.md => distributors-core/CHANGELOG.md (100%) rename LICENSE => distributors-core/LICENSE (100%) rename README.md => distributors-core/README.md (100%) rename Setup.hs => distributors-core/Setup.hs (100%) rename distributors.cabal => distributors-core/distributors.cabal (67%) rename package.yaml => distributors-core/package.yaml (84%) rename {src => distributors-core/src}/Control/Lens/Bifocal.hs (100%) rename {src => distributors-core/src}/Control/Lens/Diopter.hs (100%) rename {src => distributors-core/src}/Control/Lens/Grammar.hs (100%) rename {src => distributors-core/src}/Control/Lens/Grammar/BackusNaur.hs (100%) rename {src => distributors-core/src}/Control/Lens/Grammar/Internal/NestedPrismTH.hs (100%) rename {src => distributors-core/src}/Control/Lens/Grammar/Internal/Orphanage.hs (100%) rename {src => distributors-core/src}/Control/Lens/Grammar/Machine.hs (100%) rename {src => distributors-core/src}/Control/Lens/Grammar/RegEx.hs (100%) rename {src => distributors-core/src}/Control/Lens/Grammar/Symbol.hs (100%) rename {src => distributors-core/src}/Control/Lens/Grammar/Token.hs (100%) rename {src => distributors-core/src}/Control/Lens/Grate.hs (100%) rename {src => distributors-core/src}/Control/Lens/Monocle.hs (100%) rename {src => distributors-core/src}/Control/Lens/PartialIso.hs (100%) rename {src => distributors-core/src}/Control/Lens/Wither.hs (100%) rename {src => distributors-core/src}/Control/Monad/Fail/Try.hs (100%) rename {src => distributors-core/src}/Data/Monoid/Disjunctive.hs (100%) rename {src => distributors-core/src}/Data/Profunctor/Distributor.hs (100%) rename {src => distributors-core/src}/Data/Profunctor/Filtrator.hs (100%) rename {src => distributors-core/src}/Data/Profunctor/Grammar.hs (100%) rename {src => distributors-core/src}/Data/Profunctor/Grammar/Parsector.hs (100%) rename {src => distributors-core/src}/Data/Profunctor/Monadic.hs (100%) rename {src => distributors-core/src}/Data/Profunctor/Monoidal.hs (100%) rename {src => distributors-core/src}/Data/Profunctor/Monoidal/Cocartesian.hs (100%) rename {src => distributors-core/src}/Data/Profunctor/Separator.hs (100%) rename {src => distributors-core/src}/Data/Traversable/Homogeneous.hs (100%) rename {test => distributors-core/test}/Examples/Arithmetic.hs (100%) rename {test => distributors-core/test}/Examples/Chain.hs (100%) rename {test => distributors-core/test}/Examples/Expression.hs (100%) rename {test => distributors-core/test}/Examples/Json.hs (100%) rename {test => distributors-core/test}/Examples/Lambda.hs (100%) rename {test => distributors-core/test}/Examples/LenVec.hs (100%) rename {test => distributors-core/test}/Examples/RegString.hs (100%) rename {test => distributors-core/test}/Examples/SExpr.hs (100%) rename {test => distributors-core/test}/Examples/SemVer.hs (100%) rename {test => distributors-core/test}/Main.hs (97%) rename {test => distributors-core/test}/Properties/Kleene.hs (100%) create mode 100644 distributors-json/CHANGELOG.md create mode 100644 distributors-json/LICENSE create mode 100644 distributors-json/README.md rename {bench => distributors-json/bench}/Main.hs (100%) create mode 100644 distributors-json/distributors-json.cabal create mode 100644 distributors-json/package.yaml rename {src => distributors-json/src}/Control/Lens/Grammar/Json.hs (100%) create mode 100644 distributors-json/test/Main.hs rename {test => distributors-json/test}/Properties/Json.hs (100%) diff --git a/CHANGELOG.md b/distributors-core/CHANGELOG.md similarity index 100% rename from CHANGELOG.md rename to distributors-core/CHANGELOG.md diff --git a/LICENSE b/distributors-core/LICENSE similarity index 100% rename from LICENSE rename to distributors-core/LICENSE diff --git a/README.md b/distributors-core/README.md similarity index 100% rename from README.md rename to distributors-core/README.md 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 67% rename from distributors.cabal rename to distributors-core/distributors.cabal index dec42447..421de401 100644 --- a/distributors.cabal +++ b/distributors-core/distributors.cabal @@ -34,7 +34,6 @@ library Control.Lens.Grammar.BackusNaur Control.Lens.Grammar.Internal.NestedPrismTH Control.Lens.Grammar.Internal.Orphanage - Control.Lens.Grammar.Json Control.Lens.Grammar.Machine Control.Lens.Grammar.RegEx Control.Lens.Grammar.Symbol @@ -103,37 +102,22 @@ library MemoTrie >=0.6 && <1 , QuickCheck >=2.14 && <3 , adjunctions >=4.4 && <5 - , aeson , base >=4.15 && <5 , bifunctors >=5.5 && <6 , bytestring >=0.11 && <1 , containers >=0.6 && <1 , contravariant >=1.5 && <2 - , data-fix , distributive >=0.6 && <1 - , dlist - , hashable , lens >=5.0 && <6 , monad-loops >=0.4.3 && <1 , mtl >=2.2 && <3 - , network-uri - , primitive , profunctors >=5.6 && <6 , random >=1.2 && <2 - , scientific - , sop-core - , strict , tagged >=0.8 && <1 , template-haskell >=2.17 && <3 , text ==2.* - , text-iso8601 - , text-short , th-abstraction >=0.4 && <1 - , these - , time , transformers >=0.5 && <1 - , unordered-containers - , uuid-types , vector >=0.12 && <1 , witherable >=0.4 && <1 default-language: Haskell2010 @@ -151,7 +135,6 @@ test-suite test Examples.RegString Examples.SemVer Examples.SExpr - Properties.Json Properties.Kleene Paths_distributors autogen-modules: @@ -201,132 +184,26 @@ test-suite test MemoTrie >=0.6 && <1 , QuickCheck >=2.14 && <3 , adjunctions >=4.4 && <5 - , aeson , base >=4.15 && <5 , bifunctors >=5.5 && <6 , bytestring >=0.11 && <1 , containers >=0.6 && <1 , contravariant >=1.5 && <2 - , data-fix , distributive >=0.6 && <1 , distributors - , dlist , doctest >=0.18 && <1 - , hashable , hspec >=2.7 && <3 , lens >=5.0 && <6 , megaparsec >=9.0 && <10 , monad-loops >=0.4.3 && <1 , mtl >=2.2 && <3 - , network-uri - , primitive , profunctors >=5.6 && <6 - , quickcheck-instances , random >=1.2 && <2 - , scientific - , sop-core - , strict , tagged >=0.8 && <1 , template-haskell >=2.17 && <3 , text ==2.* - , text-iso8601 - , text-short , th-abstraction >=0.4 && <1 - , these - , time , transformers >=0.5 && <1 - , unordered-containers - , uuid-types - , vector >=0.12 && <1 - , witherable >=0.4 && <1 - default-language: Haskell2010 - -benchmark json - type: exitcode-stdio-1.0 - main-is: Main.hs - other-modules: - Paths_distributors - autogen-modules: - Paths_distributors - 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: - MemoTrie >=0.6 && <1 - , QuickCheck >=2.14 && <3 - , adjunctions >=4.4 && <5 - , aeson - , base >=4.15 && <5 - , bifunctors >=5.5 && <6 - , bytestring >=0.11 && <1 - , containers >=0.6 && <1 - , contravariant >=1.5 && <2 - , data-fix - , deepseq - , distributive >=0.6 && <1 - , distributors - , dlist - , hashable - , lens >=5.0 && <6 - , monad-loops >=0.4.3 && <1 - , mtl >=2.2 && <3 - , network-uri - , primitive - , profunctors >=5.6 && <6 - , random >=1.2 && <2 - , scientific - , sop-core - , strict - , tagged >=0.8 && <1 - , tasty-bench - , template-haskell >=2.17 && <3 - , text ==2.* - , text-iso8601 - , text-short - , th-abstraction >=0.4 && <1 - , these - , time - , transformers >=0.5 && <1 - , unordered-containers - , uuid-types , vector >=0.12 && <1 , witherable >=0.4 && <1 default-language: Haskell2010 diff --git a/package.yaml b/distributors-core/package.yaml similarity index 84% rename from package.yaml rename to distributors-core/package.yaml index aee63e07..4319745c 100644 --- a/package.yaml +++ b/distributors-core/package.yaml @@ -19,39 +19,24 @@ description: dependencies: - base >= 4.15 && < 5 -- aeson - adjunctions >= 4.4 && < 5 - bifunctors >= 5.5 && < 6 - bytestring >= 0.11 && < 1 - containers >= 0.6 && < 1 - contravariant >= 1.5 && < 2 -- data-fix -- dlist - distributive >= 0.6 && < 1 -- hashable - lens >= 5.0 && < 6 - MemoTrie >= 0.6 && < 1 - QuickCheck >= 2.14 && < 3 - monad-loops >=0.4.3 && < 1 - mtl >= 2.2 && < 3 -- network-uri -- primitive - random >= 1.2 && < 2 - transformers >= 0.5 && < 1 -- unordered-containers -- uuid-types - profunctors >= 5.6 && < 6 -- scientific -- sop-core -- strict - tagged >= 0.8 && < 1 - template-haskell >= 2.17 && < 3 - text >= 2 && < 3 -- text-iso8601 -- text-short - th-abstraction >= 0.4 && < 1 -- these -- time - vector >= 0.12 && < 1 - witherable >= 0.4 && < 1 @@ -118,16 +103,3 @@ tests: - hspec >= 2.7 && < 3 - megaparsec >= 9.0 && < 10 - QuickCheck >= 2.14 && < 3 - - quickcheck-instances - -benchmarks: - json: - main: Main.hs - source-dirs: bench - ghc-options: - - -O2 - - -rtsopts - dependencies: - - deepseq - - distributors - - tasty-bench diff --git a/src/Control/Lens/Bifocal.hs b/distributors-core/src/Control/Lens/Bifocal.hs similarity index 100% rename from src/Control/Lens/Bifocal.hs rename to distributors-core/src/Control/Lens/Bifocal.hs diff --git a/src/Control/Lens/Diopter.hs b/distributors-core/src/Control/Lens/Diopter.hs similarity index 100% rename from src/Control/Lens/Diopter.hs rename to distributors-core/src/Control/Lens/Diopter.hs diff --git a/src/Control/Lens/Grammar.hs b/distributors-core/src/Control/Lens/Grammar.hs similarity index 100% rename from src/Control/Lens/Grammar.hs rename to distributors-core/src/Control/Lens/Grammar.hs diff --git a/src/Control/Lens/Grammar/BackusNaur.hs b/distributors-core/src/Control/Lens/Grammar/BackusNaur.hs similarity index 100% rename from src/Control/Lens/Grammar/BackusNaur.hs rename to distributors-core/src/Control/Lens/Grammar/BackusNaur.hs diff --git a/src/Control/Lens/Grammar/Internal/NestedPrismTH.hs b/distributors-core/src/Control/Lens/Grammar/Internal/NestedPrismTH.hs similarity index 100% rename from src/Control/Lens/Grammar/Internal/NestedPrismTH.hs rename to distributors-core/src/Control/Lens/Grammar/Internal/NestedPrismTH.hs diff --git a/src/Control/Lens/Grammar/Internal/Orphanage.hs b/distributors-core/src/Control/Lens/Grammar/Internal/Orphanage.hs similarity index 100% rename from src/Control/Lens/Grammar/Internal/Orphanage.hs rename to distributors-core/src/Control/Lens/Grammar/Internal/Orphanage.hs diff --git a/src/Control/Lens/Grammar/Machine.hs b/distributors-core/src/Control/Lens/Grammar/Machine.hs similarity index 100% rename from src/Control/Lens/Grammar/Machine.hs rename to distributors-core/src/Control/Lens/Grammar/Machine.hs diff --git a/src/Control/Lens/Grammar/RegEx.hs b/distributors-core/src/Control/Lens/Grammar/RegEx.hs similarity index 100% rename from src/Control/Lens/Grammar/RegEx.hs rename to distributors-core/src/Control/Lens/Grammar/RegEx.hs diff --git a/src/Control/Lens/Grammar/Symbol.hs b/distributors-core/src/Control/Lens/Grammar/Symbol.hs similarity index 100% rename from src/Control/Lens/Grammar/Symbol.hs rename to distributors-core/src/Control/Lens/Grammar/Symbol.hs diff --git a/src/Control/Lens/Grammar/Token.hs b/distributors-core/src/Control/Lens/Grammar/Token.hs similarity index 100% rename from src/Control/Lens/Grammar/Token.hs rename to distributors-core/src/Control/Lens/Grammar/Token.hs diff --git a/src/Control/Lens/Grate.hs b/distributors-core/src/Control/Lens/Grate.hs similarity index 100% rename from src/Control/Lens/Grate.hs rename to distributors-core/src/Control/Lens/Grate.hs diff --git a/src/Control/Lens/Monocle.hs b/distributors-core/src/Control/Lens/Monocle.hs similarity index 100% rename from src/Control/Lens/Monocle.hs rename to distributors-core/src/Control/Lens/Monocle.hs diff --git a/src/Control/Lens/PartialIso.hs b/distributors-core/src/Control/Lens/PartialIso.hs similarity index 100% rename from src/Control/Lens/PartialIso.hs rename to distributors-core/src/Control/Lens/PartialIso.hs diff --git a/src/Control/Lens/Wither.hs b/distributors-core/src/Control/Lens/Wither.hs similarity index 100% rename from src/Control/Lens/Wither.hs rename to distributors-core/src/Control/Lens/Wither.hs diff --git a/src/Control/Monad/Fail/Try.hs b/distributors-core/src/Control/Monad/Fail/Try.hs similarity index 100% rename from src/Control/Monad/Fail/Try.hs rename to distributors-core/src/Control/Monad/Fail/Try.hs diff --git a/src/Data/Monoid/Disjunctive.hs b/distributors-core/src/Data/Monoid/Disjunctive.hs similarity index 100% rename from src/Data/Monoid/Disjunctive.hs rename to distributors-core/src/Data/Monoid/Disjunctive.hs diff --git a/src/Data/Profunctor/Distributor.hs b/distributors-core/src/Data/Profunctor/Distributor.hs similarity index 100% rename from src/Data/Profunctor/Distributor.hs rename to distributors-core/src/Data/Profunctor/Distributor.hs diff --git a/src/Data/Profunctor/Filtrator.hs b/distributors-core/src/Data/Profunctor/Filtrator.hs similarity index 100% rename from src/Data/Profunctor/Filtrator.hs rename to distributors-core/src/Data/Profunctor/Filtrator.hs diff --git a/src/Data/Profunctor/Grammar.hs b/distributors-core/src/Data/Profunctor/Grammar.hs similarity index 100% rename from src/Data/Profunctor/Grammar.hs rename to distributors-core/src/Data/Profunctor/Grammar.hs diff --git a/src/Data/Profunctor/Grammar/Parsector.hs b/distributors-core/src/Data/Profunctor/Grammar/Parsector.hs similarity index 100% rename from src/Data/Profunctor/Grammar/Parsector.hs rename to distributors-core/src/Data/Profunctor/Grammar/Parsector.hs diff --git a/src/Data/Profunctor/Monadic.hs b/distributors-core/src/Data/Profunctor/Monadic.hs similarity index 100% rename from src/Data/Profunctor/Monadic.hs rename to distributors-core/src/Data/Profunctor/Monadic.hs diff --git a/src/Data/Profunctor/Monoidal.hs b/distributors-core/src/Data/Profunctor/Monoidal.hs similarity index 100% rename from src/Data/Profunctor/Monoidal.hs rename to distributors-core/src/Data/Profunctor/Monoidal.hs diff --git a/src/Data/Profunctor/Monoidal/Cocartesian.hs b/distributors-core/src/Data/Profunctor/Monoidal/Cocartesian.hs similarity index 100% rename from src/Data/Profunctor/Monoidal/Cocartesian.hs rename to distributors-core/src/Data/Profunctor/Monoidal/Cocartesian.hs diff --git a/src/Data/Profunctor/Separator.hs b/distributors-core/src/Data/Profunctor/Separator.hs similarity index 100% rename from src/Data/Profunctor/Separator.hs rename to distributors-core/src/Data/Profunctor/Separator.hs diff --git a/src/Data/Traversable/Homogeneous.hs b/distributors-core/src/Data/Traversable/Homogeneous.hs similarity index 100% rename from src/Data/Traversable/Homogeneous.hs rename to distributors-core/src/Data/Traversable/Homogeneous.hs diff --git a/test/Examples/Arithmetic.hs b/distributors-core/test/Examples/Arithmetic.hs similarity index 100% rename from test/Examples/Arithmetic.hs rename to distributors-core/test/Examples/Arithmetic.hs diff --git a/test/Examples/Chain.hs b/distributors-core/test/Examples/Chain.hs similarity index 100% rename from test/Examples/Chain.hs rename to distributors-core/test/Examples/Chain.hs diff --git a/test/Examples/Expression.hs b/distributors-core/test/Examples/Expression.hs similarity index 100% rename from test/Examples/Expression.hs rename to distributors-core/test/Examples/Expression.hs diff --git a/test/Examples/Json.hs b/distributors-core/test/Examples/Json.hs similarity index 100% rename from test/Examples/Json.hs rename to distributors-core/test/Examples/Json.hs diff --git a/test/Examples/Lambda.hs b/distributors-core/test/Examples/Lambda.hs similarity index 100% rename from test/Examples/Lambda.hs rename to distributors-core/test/Examples/Lambda.hs diff --git a/test/Examples/LenVec.hs b/distributors-core/test/Examples/LenVec.hs similarity index 100% rename from test/Examples/LenVec.hs rename to distributors-core/test/Examples/LenVec.hs diff --git a/test/Examples/RegString.hs b/distributors-core/test/Examples/RegString.hs similarity index 100% rename from test/Examples/RegString.hs rename to distributors-core/test/Examples/RegString.hs diff --git a/test/Examples/SExpr.hs b/distributors-core/test/Examples/SExpr.hs similarity index 100% rename from test/Examples/SExpr.hs rename to distributors-core/test/Examples/SExpr.hs diff --git a/test/Examples/SemVer.hs b/distributors-core/test/Examples/SemVer.hs similarity index 100% rename from test/Examples/SemVer.hs rename to distributors-core/test/Examples/SemVer.hs diff --git a/test/Main.hs b/distributors-core/test/Main.hs similarity index 97% rename from test/Main.hs rename to distributors-core/test/Main.hs index 0c102b1b..7477aa8e 100644 --- a/test/Main.hs +++ b/distributors-core/test/Main.hs @@ -24,7 +24,6 @@ import Examples.LenVec import Examples.RegString import Examples.SemVer import Examples.SExpr -import Properties.Json import Properties.Kleene main :: IO () @@ -50,16 +49,6 @@ main = do describe "Parsector try rollback" tryRollbackTests describe "Kleene" kleeneProperties describe "meander" meanderProperties - jsonTypeSpec - aesonSpec - jsonErrorSpec - jsonObjectSpec - jsonOptionsSpec - jsonTupleSpec - jsonTupleChoiceSpec - jsonOptionalSpec - jsonCodecSpec - jsonPrintSpec parseForestTests :: Spec parseForestTests = do diff --git a/test/Properties/Kleene.hs b/distributors-core/test/Properties/Kleene.hs similarity index 100% rename from test/Properties/Kleene.hs rename to distributors-core/test/Properties/Kleene.hs diff --git a/distributors-json/CHANGELOG.md b/distributors-json/CHANGELOG.md new file mode 100644 index 00000000..90661062 --- /dev/null +++ b/distributors-json/CHANGELOG.md @@ -0,0 +1,5 @@ +# Changelog for distributors-json + +## 0.1.0.0 + +- Split out of `distributors` as its own package. 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..018cdb73 --- /dev/null +++ b/distributors-json/README.md @@ -0,0 +1,3 @@ +# distributors-json + +See the documentation of `Control.Lens.Grammar.Json`. diff --git a/bench/Main.hs b/distributors-json/bench/Main.hs similarity index 100% rename from bench/Main.hs rename to distributors-json/bench/Main.hs diff --git a/distributors-json/distributors-json.cabal b/distributors-json/distributors-json.cabal new file mode 100644 index 00000000..36aa1c06 --- /dev/null +++ b/distributors-json/distributors-json.cabal @@ -0,0 +1,267 @@ +cabal-version: 2.2 + +-- This file has been generated from package.yaml by hpack version 0.39.1. +-- +-- 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 +extra-doc-files: + CHANGELOG.md + +source-repository head + type: git + location: https://github.com/morphismtech/distributors + +library + exposed-modules: + Control.Lens.Grammar.Json + 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.15 && <5 + , bytestring >=0.11 && <1 + , containers >=0.6 && <1 + , data-fix >=0.3 && <1 + , distributors ==0.6.* + , 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 test + type: exitcode-stdio-1.0 + main-is: Main.hs + other-modules: + Properties.Json + 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.15 && <5 + , bytestring >=0.11 && <1 + , containers >=0.6 && <1 + , data-fix >=0.3 && <1 + , distributors ==0.6.* + , distributors-json + , dlist >=1.0 && <2 + , doctest >=0.18 && <1 + , 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: + 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.15 && <5 + , bytestring >=0.11 && <1 + , containers >=0.6 && <1 + , data-fix >=0.3 && <1 + , deepseq >=1.4 && <2 + , distributors ==0.6.* + , distributors-json + , 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 + , 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/package.yaml b/distributors-json/package.yaml new file mode 100644 index 00000000..9d0d2697 --- /dev/null +++ b/distributors-json/package.yaml @@ -0,0 +1,123 @@ +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 +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.15 && < 5 +- aeson >= 2.2 && < 3 +- bytestring >= 0.11 && < 1 +- containers >= 0.6 && < 1 +- data-fix >= 0.3 && < 1 +- distributors >= 0.6 && < 0.7 +- 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: + test: + main: Main.hs + source-dirs: test + dependencies: + - distributors-json + - doctest >= 0.18 && < 1 + - 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 + - tasty-bench >= 0.3 && < 1 diff --git a/src/Control/Lens/Grammar/Json.hs b/distributors-json/src/Control/Lens/Grammar/Json.hs similarity index 100% rename from src/Control/Lens/Grammar/Json.hs rename to distributors-json/src/Control/Lens/Grammar/Json.hs diff --git a/distributors-json/test/Main.hs b/distributors-json/test/Main.hs new file mode 100644 index 00000000..c0bec4b6 --- /dev/null +++ b/distributors-json/test/Main.hs @@ -0,0 +1,87 @@ +module Main (main) where + +import Control.Monad (when) +import Data.Foldable (for_) +import Data.Maybe (isJust) +import System.Environment (lookupEnv) +import Test.DocTest +import Test.Hspec + +import Properties.Json + +main :: IO () +main = do + shouldRunDoctests <- isJust <$> lookupEnv "DISTRIBUTORS_RUN_DOCTESTS" + hspec $ do + when shouldRunDoctests $ + describe "doctest" $ + it "should run haddock examples" doctests + jsonTypeSpec + aesonSpec + jsonErrorSpec + jsonObjectSpec + jsonOptionsSpec + jsonTupleSpec + jsonTupleChoiceSpec + jsonOptionalSpec + jsonCodecSpec + jsonPrintSpec + +doctests :: IO () +doctests = do + stackExe <- lookupEnv "STACK_EXE" + ghcEnvironment <- lookupEnv "GHC_ENVIRONMENT" + let + modulePaths = + [ "src/Control/Lens/Grammar/Json.hs" + ] + packageEnvFlags = case ghcEnvironment of + Just "-" -> [] + Just path -> ["-package-env=" <> path] + Nothing -> [] + runnerFlags + | isJust stackExe = [] + | otherwise = "-isrc" : packageEnvFlags + languageExtensions = + [ "-XHaskell2010" + , "-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) diff --git a/test/Properties/Json.hs b/distributors-json/test/Properties/Json.hs similarity index 100% rename from test/Properties/Json.hs rename to distributors-json/test/Properties/Json.hs diff --git a/stack.yaml b/stack.yaml index d436f071..ad8feb13 100644 --- a/stack.yaml +++ b/stack.yaml @@ -1,3 +1,4 @@ resolver: nightly-2026-09-27 packages: -- . +- distributors-core +- distributors-json From 57f53c74790977af37d19b4f59f3c06d4744b607 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Fri, 6 Nov 2026 00:57:43 -0800 Subject: [PATCH 014/130] Build with stack, cabal or nix, & revisit CI - cabal.project builds both packages; GHC 9.10 & 9.12 build & pass. - flake.nix builds & checks both packages with nixpkgs' cached GHC. - CI lints (HLint, & .cabal files generated from package.yaml), builds & tests with stack (with doctests), cabal (GHC 9.10 & 9.12) & nix, caches each, & builds the documentation, deploying it to GitHub Pages from main. - .hlint.yaml ignores the hints in today's code, so new hints fail CI. - Tests no longer need QuickCheck 2.17's GeneralCategory & Down instances. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 168 ++++++++++++++++++-- .hlint.yaml | 95 +++++++++++ cabal.project | 6 + distributors-core/test/Properties/Kleene.hs | 10 ++ distributors-json/test/Properties/Json.hs | 6 +- flake.lock | 61 +++++++ flake.nix | 46 ++++++ 7 files changed, 376 insertions(+), 16 deletions(-) create mode 100644 .hlint.yaml create mode 100644 cabal.project create mode 100644 flake.lock create mode 100644 flake.nix diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4a049442..8bf6ed8b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,37 +1,179 @@ 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-json/"]' + fail-on: suggestion + + - name: Check generated .cabal files match package.yaml + run: | + curl -sSL https://github.com/sol/hpack/releases/download/0.38.1/hpack_linux.gz \ + | gunzip > hpack + chmod +x hpack + for package in distributors-core distributors-json; do + (cd "$package" && ../hpack --force) + done + git diff --exit-code -- '*.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-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 + - name: Test, with doctests env: DISTRIBUTORS_RUN_DOCTESTS: "1" 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 + + # Doctests run in the stack job, since doctest needs the package + # environment, which stack provides to test suites but cabal doesn't. + - name: Test + run: cabal test all --test-show-details=direct + + - name: Check packages + run: | + for package in distributors-core 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 + + docs: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Set up GHC & Cabal + id: setup + uses: haskell-actions/setup@v2 + with: + ghc-version: "9.12.4" + cabal-update: true + + - name: Plan the build + run: cabal build all --dry-run + + - name: Cache the Cabal store + uses: actions/cache@v4 + with: + path: ${{ steps.setup.outputs.cabal-store }} + key: docs-${{ runner.os }}-${{ hashFiles('dist-newstyle/cache/plan.json') }} + restore-keys: docs-${{ runner.os }}- + + - name: Build the documentation + run: | + cabal haddock-project --hackage \ + --haddock-hyperlink-source --haddock-quickjump --output=docs + + - name: Upload the documentation + uses: actions/upload-pages-artifact@v3 + with: + path: docs + + deploy-docs: + if: github.event_name == 'push' && github.ref == 'refs/heads/main' + needs: [docs, stack, cabal, nix, lint] + runs-on: ubuntu-latest + permissions: + pages: write + id-token: write + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + steps: + - name: Deploy the documentation to GitHub Pages + id: deployment + uses: actions/deploy-pages@v4 diff --git a/.hlint.yaml b/.hlint.yaml new file mode 100644 index 00000000..2388c45e --- /dev/null +++ b/.hlint.yaml @@ -0,0 +1,95 @@ +# 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] diff --git a/cabal.project b/cabal.project new file mode 100644 index 00000000..c70e7b0a --- /dev/null +++ b/cabal.project @@ -0,0 +1,6 @@ +packages: + distributors-core + distributors-json + +tests: True +benchmarks: True diff --git a/distributors-core/test/Properties/Kleene.hs b/distributors-core/test/Properties/Kleene.hs index 629805e3..9cb4253a 100644 --- a/distributors-core/test/Properties/Kleene.hs +++ b/distributors-core/test/Properties/Kleene.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE CPP #-} {-# OPTIONS_GHC -Wno-orphans #-} module Properties.Kleene (kleeneProperties) where @@ -7,6 +8,15 @@ import Test.Hspec import Test.Hspec.QuickCheck (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 diff --git a/distributors-json/test/Properties/Json.hs b/distributors-json/test/Properties/Json.hs index bf7f41aa..2fab8769 100644 --- a/distributors-json/test/Properties/Json.hs +++ b/distributors-json/test/Properties/Json.hs @@ -57,7 +57,7 @@ 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.Ord (Down (..)) import Data.Primitive.Array (Array) import Data.Primitive.PrimArray (PrimArray) import Data.Primitive.SmallArray (SmallArray) @@ -867,8 +867,8 @@ aesonSpec = describe "Json agrees with aeson" $ do aesonCompat @(Compose Maybe [] Int) arbitrary aesonCompat @(Functor.Product Maybe [] Int) arbitrary aesonCompat @(Functor.Sum Maybe [] Int) arbitrary - aesonCompat @(Down Int) arbitrary - aesonCompat @[Down Char] 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 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..7912ebe4 --- /dev/null +++ b/flake.nix @@ -0,0 +1,46 @@ +{ + description = "distributors & 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-json = self.callCabal2nix "distributors-json" + ./distributors-json { }; + }; + }; + in + { + packages = { + distributors = haskellPackages.distributors; + distributors-json = haskellPackages.distributors-json; + default = haskellPackages.distributors-json; + }; + + checks = { + distributors = lib.doBenchmark haskellPackages.distributors; + distributors-json = lib.doBenchmark haskellPackages.distributors-json; + }; + + devShells.default = haskellPackages.shellFor { + packages = p: [ p.distributors p.distributors-json ]; + withHoogle = false; + nativeBuildInputs = [ + pkgs.cabal-install + pkgs.hlint + pkgs.hpack + ]; + }; + }); +} From 0f8ad1a33af0631f9f76d6518c757a8a211cdcf9 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Fri, 6 Nov 2026 01:05:23 -0800 Subject: [PATCH 015/130] Type JSON as JsonType, declared in TypeScript by a grammar - jsonType types a type's JSON as a Bnf of JsonTypes, by its rules, & jsonTsDeclarations declares the rules of types in TypeScript, replacing jsonTypes. - Control.Lens.Grammar.TypeScript models TypeScript's type declarations after its compiler: tsTokenGrammar, a RegGrammar Char TsToken of its scanner's tokens & trivia, & tsGrammar, a Grammar TsToken of its syntax, so that tsPrint & tsParse print & parse declarations. - Mapped types exclude named keys by an as clause, rather than Exclude, so that declarations refer to no global types. - Document the JSON package by doctested examples, & add a root README. Co-Authored-By: Claude Opus 5.5 --- README.md | 35 + distributors-json/CHANGELOG.md | 8 + distributors-json/README.md | 21 +- distributors-json/bench/Main.hs | 19 +- distributors-json/distributors-json.cabal | 1 + .../src/Control/Lens/Grammar/Json.hs | 1001 ++++++++++------- .../src/Control/Lens/Grammar/TypeScript.hs | 505 +++++++++ distributors-json/test/Main.hs | 1 + distributors-json/test/Properties/Json.hs | 42 +- 9 files changed, 1176 insertions(+), 457 deletions(-) create mode 100644 README.md create mode 100644 distributors-json/src/Control/Lens/Grammar/TypeScript.hs diff --git a/README.md b/README.md new file mode 100644 index 00000000..26bceb0a --- /dev/null +++ b/README.md @@ -0,0 +1,35 @@ +# distributors + +Unifying parsers, printers & grammars, in two packages: + +- [`distributors-core`](distributors-core): the `distributors` package, + of profunctor grammars, which parse, print & generate together. +- [`distributors-json`](distributors-json): the `distributors-json` + package, of JSON grammars, compatible with `aeson` & typed in TypeScript. + +## Building + +With Stack: + +```sh +stack build --test --bench +DISTRIBUTORS_RUN_DOCTESTS=1 stack test +``` + +With Cabal: + +```sh +cabal build all +cabal test all +``` + +With Nix: + +```sh +nix build .#distributors-json +nix flake check +nix develop # a shell with GHC, Cabal, HLint & hpack +``` + +Each package's `.cabal` file is generated from its `package.yaml`, +by `hpack`, which Stack runs. diff --git a/distributors-json/CHANGELOG.md b/distributors-json/CHANGELOG.md index 90661062..23da6732 100644 --- a/distributors-json/CHANGELOG.md +++ b/distributors-json/CHANGELOG.md @@ -3,3 +3,11 @@ ## 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, replacing `jsonTypes`. +- `Control.Lens.Grammar.TypeScript` parses & prints TypeScript type + declarations, by `tsTokenGrammar` & `tsGrammar`, after the TypeScript + compiler's scanner & syntax. +- 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. diff --git a/distributors-json/README.md b/distributors-json/README.md index 018cdb73..1e9cff1e 100644 --- a/distributors-json/README.md +++ b/distributors-json/README.md @@ -1,3 +1,22 @@ # distributors-json -See the documentation of `Control.Lens.Grammar.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}) +>>> mapM_ putStr (tsPrint (jsonTsDeclarations (type '[Person]))) +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/Main.hs b/distributors-json/bench/Main.hs index 8dc93a24..30ab1b85 100644 --- a/distributors-json/bench/Main.hs +++ b/distributors-json/bench/Main.hs @@ -1,7 +1,7 @@ {-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RequiredTypeArguments #-} --- | Keep constant benchmarks, like `jsonTypes`, from being shared. +-- | 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 #-} @@ -9,6 +9,9 @@ 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.TypeScript (tsPrint) import Data.Aeson ( FromJSON (..), ToJSON (..), Value (..), decode, defaultOptions, encode , genericToEncoding, object, (.=) @@ -281,10 +284,14 @@ main = defaultMain , dataset "hashMap" hashMap , dataset "value" value , bgroup "typescript" - [ bench "records" (nf (\() -> jsonTypes (type '[Person])) ()) - , bench "sums" (nf (\() -> jsonTypes [Shape]) ()) - , bench "rose" (nf (\() -> jsonTypes (type '[Rose])) ()) - , bench "value" (nf (\() -> jsonTypes [Value]) ()) - , bench "twice12" (nf (\() -> jsonTypes [Twice12]) ()) + [ 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 = maybe "" Text.pack (tsPrint (jsonTsDeclarations as)) diff --git a/distributors-json/distributors-json.cabal b/distributors-json/distributors-json.cabal index 36aa1c06..f746a648 100644 --- a/distributors-json/distributors-json.cabal +++ b/distributors-json/distributors-json.cabal @@ -29,6 +29,7 @@ source-repository head library exposed-modules: Control.Lens.Grammar.Json + Control.Lens.Grammar.TypeScript other-modules: Paths_distributors_json autogen-modules: diff --git a/distributors-json/src/Control/Lens/Grammar/Json.hs b/distributors-json/src/Control/Lens/Grammar/Json.hs index 0bc1a01f..4f98a609 100644 --- a/distributors-json/src/Control/Lens/Grammar/Json.hs +++ b/distributors-json/src/Control/Lens/Grammar/Json.hs @@ -1,5 +1,104 @@ {-# 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@ + +`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 + +`jsonTsDeclarations` declares the TypeScript types of types' JSON, +which "Control.Lens.Grammar.TypeScript" prints, & `jsonType` types it. + +>>> mapM_ putStr (tsPrint (jsonTsDeclarations (type '[Person, Point, Shape]))) +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 (..) @@ -9,7 +108,6 @@ module Control.Lens.Grammar.Json , jsonErrorPrint , jsonEncode , jsonErrorEncode - , jsonTypes , jsonGeneric , ViaJson (..) -- * Grammar @@ -17,6 +115,12 @@ module Control.Lens.Grammar.Json , JsonObj (..), (!=) , JsonTup (..) , JsonStr (..) + -- * Types + , JsonType (..) + , JsonElement (..) + , JsonProperty (..) + , jsonType + , jsonTsDeclarations -- * Errors , JsonError (..) , JsonErrorSort (..) @@ -51,7 +155,7 @@ 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, traverse_) +import Data.Foldable (toList) import Data.Function (fix) import Data.Functor.Compose (Compose (..)) import Data.Functor.Product qualified as Functor @@ -69,7 +173,7 @@ import Data.IntSet (IntSet) import Data.IntSet qualified as IntSet import Data.Kind import Data.List - (find, findIndices, intercalate, isPrefixOf, nub, stripPrefix) + (find, findIndices, intercalate, isPrefixOf, nub, sortOn, stripPrefix) import Data.List.NonEmpty (NonEmpty, nonEmpty) import Data.Map (Map) import Data.Map qualified as Map @@ -130,6 +234,7 @@ 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) @@ -139,12 +244,29 @@ import Text.ParserCombinators.ReadP (readP_to_S) import Type.Reflection import Witherable qualified +-- $setup +-- >>> :set -XDeriveAnyClass -XDerivingStrategies -XDerivingVia +-- >>> :set -XOverloadedStrings -XRequiredTypeArguments -XTypeApplications +-- >>> 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) +-- >>> let explain err = formatError (jsonErrorPath err) (jsonErrorMessage err) + makePrisms ''Value -- 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 :: (Json (GHC.Generically a), JsonVal p) => p a a json = iso GHC.Generically coerce >~ json @@ -198,6 +320,12 @@ jsonDecode bytes = case Aeson.eitherDecode bytes of 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 @@ -205,76 +333,10 @@ jsonErrorPrint = runJsonPrintor json jsonEncode :: Json a => a -> Encoding jsonEncode = either (\_ -> Encoding.null_) id . jsonErrorEncode +-- | `jsonEncode`, failing where the grammar doesn't print a value. jsonErrorEncode :: Json a => a -> Either JsonError Encoding jsonErrorEncode = runJsonPrintor json -{- | - ->>> :set -XDeriveAnyClass -XDerivingStrategies -XRequiredTypeArguments ->>> import Data.Map (Map) ->>> import Data.Text (Text) ->>> import Data.Text.IO qualified as Text ->>> import GHC.Generics (Generic) - ->>> :{ -data Suit = Hearts | Diamonds | Clubs | Spades - deriving stock Generic - deriving anyclass Json -:} - ->>> Text.putStr (jsonTypes [Suit]) -export type Suit = "Hearts" | "Diamonds" | "Clubs" | "Spades"; - ->>> :{ -data Point = Point {x :: Double, y :: Double} - deriving stock Generic - deriving anyclass Json -:} - ->>> Text.putStr (jsonTypes (type '[Point])) -export type Double = number | null | "+inf" | "-inf"; -export type Point = { x: Double; y: Double }; - ->>> :{ -data Shape = Circle Point Double | Polygon {vertices :: [Point]} - deriving stock Generic - deriving anyclass Json -:} - ->>> Text.putStr (jsonTypes [Shape]) -export type Double = number | null | "+inf" | "-inf"; -export type Point = { x: Double; y: Double }; -export type Shape = { tag: "Circle"; contents: [Point, Double] } | { tag: "Polygon"; vertices: Point[] }; - ->>> :{ -data User = User {name :: Text, email :: Maybe Text, scores :: Map Int Double} - deriving stock Generic - deriving anyclass Json -:} - ->>> Text.putStr (jsonTypes (type '[User])) -export type Double = number | null | "+inf" | "-inf"; -export type User = { name: string; email?: null | string; scores: { [key: `${number}`]: Double } }; - ->>> :{ -data Tree a = Leaf | Node (Tree a) a (Tree a) - deriving stock Generic - deriving anyclass Json -:} - ->>> Text.putStr (jsonTypes [Tree Text, Tree Suit]) -export type Suit = "Hearts" | "Diamonds" | "Clubs" | "Spades"; -export type Tree_Suit = { tag: "Leaf" } | { tag: "Node"; contents: [Tree_Suit, Suit, Tree_Suit] }; -export type Tree_Text = { tag: "Leaf" } | { tag: "Node"; contents: [Tree_Text, string, Tree_Text] }; - --} -jsonTypes :: forall (as :: [Type]) -> All Json as => Text -jsonTypes as = renderTypeScript $ hcollapse - (hcpure (Proxy @Json) tsRoot :: NP (K (TsGrammor () ())) as) - where - tsRoot :: forall a. Json a => K (TsGrammor () ()) a - tsRoot = K (coerce (json @a @TsGrammor)) - {- | @aeson@'s instances, derived from a `Json` instance, failing to parse at the path of a `JsonError`, by its message. @@ -302,6 +364,12 @@ 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 @@ -335,7 +403,7 @@ class {- | A homogeneous JSON array, like TypeScript's @T[]@, which is a tuple of a rest element, though interpreters may define it more efficiently. - prop> jsonArray p = jsonTuple (manyP (jsonElem p)) + @jsonArray p = jsonTuple (manyP (jsonElem p))@ -} jsonArray :: p a b -> p [a] [b] jsonArray p = jsonTuple (manyP (jsonElem p)) @@ -425,8 +493,9 @@ unqualified = \case identifier c = isAlphaNum c || c == '_' || c == '\'' {- | -prop> fromString s = only s ?< jsonString -prop> jsonString = iso Text.pack Text.unpack >~ jsonText +@fromString s = only s ?< jsonString@ + +@jsonString = iso Text.pack Text.unpack >~ jsonText@ -} class ( Cochoice p @@ -519,6 +588,7 @@ data JsonError = JsonError , jsonErrorRules :: Forest String } deriving stock (Eq, Show) +-- | How a `JsonError` failed, so that alternatives report the closest. data JsonErrorSort = JsonLiteral -- ^ a string literal mismatch; the alternative doesn't apply @@ -528,6 +598,11 @@ data JsonErrorSort -- ^ the value was rejected for what it contains, lacks or repeats deriving stock (Eq, Ord, Show) +{- | A `JsonError`'s message, 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 @@ -1489,414 +1564,278 @@ printProperty printProperty key p a = (\printed -> [(key, printed)]) <$> jsonAt (Key key) (printorCheck p a) --- TypeScript interpreters -- - -data TsType - = TsAlias String -- ^ @T@, a reference to a type alias, by its identifier - | TsNull -- ^ @null@ - | TsUndefined -- ^ @undefined@ - | TsBoolean -- ^ @boolean@ - | TsNumber -- ^ @number@ - | TsString -- ^ @string@ - | TsNumeric -- ^ @\`${number}\`@ - | TsLiteral Text -- ^ @"abc"@ - | TsArray TsType -- ^ @T[]@ - | TsTuple [TsElement] -- ^ @[T, U?, ...V[]]@ - | TsObject [TsProperty] -- ^ @{abc: T, xyz?: U}@ - | TsUnion [TsType] -- ^ @T | U@, or @never@ when empty - deriving stock (Eq, Ord) - -data TsElement - = TsRequired TsType -- ^ @T@ - | TsOptional TsType -- ^ @T?@ - | TsRest TsType -- ^ @...T[]@ - deriving stock (Eq, Ord) - --- | A property of a TypeScript object type. -data TsProperty - = TsProperty Text Bool TsType -- ^ @abc: T@ or @abc?: T@ - | TsIndex TsType [TsType] TsType - {- ^ @[key: string]: T@ or @{[key in K]?: T}@, the rest of its properties, - of a key type, & its alternatives, with its aliases resolved -} - deriving stock (Eq, Ord) - -newtype TsGrammor a b = TsGrammor (TsDefining TsType) - -newtype TsTupGrammor a b = TsTupGrammor - {runTsTupGrammor :: Ap TsDefining TsShapes} - -newtype TsObjGrammor a b = TsObjGrammor - {runTsObjGrammor :: Ap TsDefining (Ap [] [TsProperty])} - -{- | Defining TypeScript types, reading the rules being defined which are -unguarded by an array, object or tuple, each noting whether it's been -unrolled, and updating the named rules & their definitions. +-- Types of JSON -- + +{- | The type of JSON values, which a grammar describes, +of rules by their names, in a `Bnf`, as `jsonType` describes them. +It's the union of its alternatives, so that `mempty` is the type of +no values. -} -type TsDefining = ReaderT (Map String Bool) (State TsDefinitions) +data JsonType + = JsonRule String -- ^ the type of a rule, by its name + | JsonNull -- ^ @null@ + | JsonBoolean -- ^ @true@ or @false@ + | JsonNumber -- ^ numbers + | JsonString -- ^ strings + | JsonNumeric -- ^ strings of numbers + | JsonStringLiteral Text -- ^ a string + | JsonArray JsonType -- ^ arrays of a type + | JsonTuple [JsonElement] -- ^ arrays of elements, in order + | JsonObject [JsonProperty] -- ^ objects of properties + | JsonUnion [JsonType] -- ^ values of any of some types + deriving stock (Eq, Ord, Show, Read) + +-- | An element of a `JsonTuple`. +data JsonElement + = JsonRequired JsonType -- ^ an element + | JsonOptional JsonType -- ^ an element, or none + | JsonRest JsonType -- ^ any elements + 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 Semigroup JsonType where + a <> b = jsonUnion [a, b] +instance Monoid JsonType where + mempty = JsonUnion [] + +-- | 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] -data TsDefinitions = TsDefinitions - { tsRuleNames :: Map String String - , tsRules :: Map String TsType - } +{- | The type of the JSON of a type, by its rules, which are named +by their qualified names. -{- | Define a rule once, under its unqualified name, or else its qualified -name, or else its numbered qualified name, if taken, as TypeScript -identifiers, so that every other occurrence of it, recursive or not, -is its name. Its name is reserved, as `never`, while it's being defined. -An unguarded occurrence is its least fixpoint instead, unrolled once, -so that a rule of a rule is the rule, and a rule recurring unguarded -contributes `never`, since JSON values are finite. +>>> 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 [JsonStringLiteral "LT",JsonStringLiteral "EQ",JsonStringLiteral "GT"])]} -} -tsDefine :: String -> TsGrammor a b -> TsGrammor c d -tsDefine key (TsGrammor body) = TsGrammor $ do - unguarded <- ask - defs <- lift get - case (Map.lookup key unguarded, Map.lookup key (tsRuleNames defs)) of - (Just True, _) -> pure (tsUnion []) - (Just False, _) -> local (Map.insert key True) body - (Nothing, Just name) -> pure (TsAlias name) - (Nothing, Nothing) -> do - let name = freshName (tsRules defs) - lift $ put defs - { tsRuleNames = Map.insert key name (tsRuleNames defs) - , tsRules = Map.insert name (tsUnion []) (tsRules defs) - } - definition <- local (Map.insert key False) body - lift $ modify $ \defined -> - defined {tsRules = Map.insert name definition (tsRules defined)} - pure (TsAlias name) +jsonType :: forall a -> Json a => Bnf JsonType +jsonType a = Bnf start (Set.fromList (Map.toList rules)) where - freshName taken = fromMaybe qualified (find free candidates) - where - free name = Map.notMember name taken && name `notElem` tsReserved - candidates = Text.unpack (tsIdentifier (unqualified key)) : qualified - : [qualified <> "_" <> show n | n <- [2 :: Int ..]] - qualified = Text.unpack (tsIdentifier key) - --- | Global type names the rendered TypeScript refers to. -tsReserved :: [String] -tsReserved = ["Exclude"] + JsonTypor typed = json @a @JsonTypor + (start, rules) = runState (runReaderT typed Map.empty) Map.empty -tsGuarded :: TsDefining a -> TsDefining a -tsGuarded = local (const 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. -tsType :: TsType -> TsGrammor a b -tsType = TsGrammor . pure +>>> :set -XDeriveAnyClass -XDerivingStrategies +>>> import GHC.Generics (Generic) +>>> :{ +data Shape = Circle Double | Square {side :: Double} + deriving stock Generic + deriving anyclass Json +:} -tsUnion :: [TsType] -> TsType -tsUnion types = case nub (concatMap alternatives types) of - [t] -> t - ts -> TsUnion ts +>>> mapM_ putStr (tsPrint (jsonTsDeclarations [Shape])) +export type Double = number | null | "+inf" | "-inf"; +export type Shape = { tag: "Circle"; contents: Double } | { tag: "Square"; side: Double }; +-} +jsonTsDeclarations :: forall (as :: [Type]) -> All Json as => [TsDeclaration] +jsonTsDeclarations as = tsDeclarations $ hcollapse + (hcpure (Proxy @Json) root :: NP (K (Bnf JsonType)) as) where - alternatives = \case - TsUnion ts -> ts - t -> [t] + root :: forall a. Json a => K (Bnf JsonType) a + root = K (jsonType (type a)) -{- | Alternative shapes of a TypeScript tuple type, -so that `>*<` concatenates each pair of shapes and `>+<` unites them. +{- | `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. -} -type TsShapes = Ap [] [TsElement] +newtype JsonTypor a b = JsonTypor (Typing JsonType) -tsElementType :: TsElement -> TsType -tsElementType = \case - TsRequired t -> t - TsOptional t -> t - TsRest t -> t +-- | Alternative shapes of tuples, which `>*<` concatenates. +newtype TupTypor a b = TupTypor + {runTupTypor :: Ap Typing (Ap [] [JsonElement])} -{- | The union of tuple types of some shapes. TypeScript requires that -a tuple type has at most one rest element, no optional element after -a rest element, and no required element after an optional element. -So, the elements from the first rest element to the last are merged -into one rest element, and 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[]]@. --} -tsTuple :: TsShapes -> TsType -tsTuple (Ap shapes) = tsUnion $ TsTuple <$> - merged (nub (concatMap (expand False . mergeRests) shapes)) - where - merged alternatives = - case [ (i, j, shape) - | merge <- [unioned, extended] - , (i, a) <- zip [0 :: Int ..] alternatives - , (j, b) <- zip [0 ..] alternatives - , i /= j - , Just shape <- [merge a b] - ] of - (i, j, shape) : _ -> merged - [ if k == min i j then shape else alternative - | (k, alternative) <- zip [0 ..] alternatives, k /= max i j ] - [] -> alternatives - 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 - (TsRequired s, TsRequired t) -> Just (TsRequired (tsUnion [s, t])) - (TsOptional s, TsOptional t) -> Just (TsOptional (tsUnion [s, t])) - _ -> Nothing - extended a b - | any isRest a = Nothing - | otherwise = stripPrefix a b >>= \case - [TsRequired t] -> Just (a <> [TsOptional t]) - [TsOptional _] -> Just b - [TsRest _] -> Just b - [TsRequired t, TsRest u] | t == u -> Just (a <> [TsRest t]) - _ -> Nothing - isRest = \case TsRest _ -> 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 <> [TsRest (tsUnion (map tsElementType middle))] <> after - _ -> els - expand _ [] = [[]] - expand restBefore (el : els) = case el of - TsOptional t | restBefore || not (optionalTail els) -> - expand restBefore els <> map (TsRequired t :) (expand restBefore els) - TsRest _ -> map (el :) (expand True els) - _ -> map (el :) (expand restBefore els) - optionalTail = \case - [] -> True - [TsRest _] -> True - TsOptional _ : els -> optionalTail els - _ -> False +-- | Alternative shapes of objects, which `>*<` concatenates. +newtype ObjTypor a b = ObjTypor + {runObjTypor :: Ap Typing (Ap [] [JsonProperty])} -deriving via Grammor (TsDefining TsType) a - instance Functor (TsGrammor a) -deriving via Grammor (TsDefining TsType) - instance Profunctor TsGrammor -deriving via Grammor (TsDefining TsType) - instance Choice TsGrammor -instance Cochoice TsGrammor where +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 `mempty`, 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 `mempty`, 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 mempty + (Just False, _) -> local (Map.insert key True) body + (Nothing, True) -> pure (JsonRule key) + (Nothing, False) -> do + lift (modify (Map.insert key mempty)) + 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 +instance Cochoice JsonTypor where unleft = coerce unright = coerce -instance Witherable.Filterable (TsGrammor a) where +instance Witherable.Filterable (JsonTypor a) where mapMaybe = dimapMaybe Just -instance Filtrator TsGrammor -instance CocartesianMonoidal TsGrammor -instance CocartesianChoice TsGrammor where +instance Filtrator JsonTypor +instance CocartesianMonoidal JsonTypor +instance CocartesianChoice JsonTypor where alternate = either coerce coerce -instance DisjunctiveMonoid (TsGrammor a b) where - falseP = tsType (tsUnion []) - TsGrammor t0 >|< TsGrammor t1 = - TsGrammor (liftA2 (\a b -> tsUnion [a, b]) t0 t1) -instance BackusNaurForm (TsGrammor a b) where - rule = tsDefine - ruleRec name f = rule name (f (tsDefine name falseP)) -instance (x ~ (), y ~ ()) => IsString (TsGrammor x y) where - fromString = tsType . TsLiteral . Text.pack -instance JsonStr TsGrammor where - jsonText = tsType TsString - jsonEnumWith f as = tsType (tsUnion [TsLiteral (f a) | a <- as]) - jsonNumeric _ = tsType TsNumeric -instance JsonVal TsGrammor where - jsonNull = tsType TsNull - jsonBool = tsType TsBoolean - jsonNumber = tsType TsNumber - jsonArray (TsGrammor t) = TsGrammor (TsArray <$> tsGuarded t) - jsonTuple tup = TsGrammor (tsTuple <$> getAp (runTsTupGrammor tup)) - jsonObject obj = - TsGrammor (objects <$> getAp (runTsObjGrammor obj)) +instance DisjunctiveMonoid (JsonTypor a b) where + falseP = typing mempty + 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 . JsonStringLiteral . Text.pack +instance JsonStr JsonTypor where + jsonText = typing JsonString + jsonEnumWith f as = typing (jsonUnion [JsonStringLiteral (f a) | a <- as]) + jsonNumeric _ = typing JsonNumeric +instance JsonVal JsonTypor where + jsonNull = typing JsonNull + jsonBool = typing JsonBoolean + jsonNumber = typing JsonNumber + jsonArray (JsonTypor t) = JsonTypor (JsonArray <$> guarded t) + jsonTuple tup = JsonTypor (tuples <$> getAp (runTupTypor tup)) + where + tuples (Ap shapes) = jsonUnion (map JsonTuple shapes) + jsonObject obj = JsonTypor (objects <$> getAp (runObjTypor obj)) where - objects (Ap shapes) = tsUnion (map object shapes) + objects (Ap shapes) = jsonUnion (map object shapes) object props - | length (nub names) == length names = TsObject props - | otherwise = tsUnion [] + | length (nub keys) == length keys = JsonObject props + | otherwise = mempty where - names = [name | TsProperty name _ _ <- props] - -deriving via Grammor (Ap TsDefining TsShapes) a - instance Functor (TsTupGrammor a) -deriving via Grammor (Ap TsDefining TsShapes) a - instance Applicative (TsTupGrammor a) -deriving via Grammor (Ap TsDefining TsShapes) - instance Profunctor TsTupGrammor -instance CocartesianMonoidal TsTupGrammor -instance Choice TsTupGrammor where + keys = [key | JsonProperty key _ _ <- props] + +deriving via Grammor (Ap Typing (Ap [] [JsonElement])) a + instance Functor (TupTypor a) +deriving via Grammor (Ap Typing (Ap [] [JsonElement])) a + instance Applicative (TupTypor a) +deriving via Grammor (Ap Typing (Ap [] [JsonElement])) + instance Profunctor TupTypor +instance CocartesianMonoidal TupTypor +instance Choice TupTypor where left' = coerce right' = coerce -instance CocartesianChoice TsTupGrammor where +instance CocartesianChoice TupTypor where alternate = either coerce coerce -instance DisjunctiveMonoid (TsTupGrammor a b) where - falseP = TsTupGrammor (pure (Ap [])) - TsTupGrammor s0 >|< TsTupGrammor s1 = TsTupGrammor (liftA2 unite s0 s1) +instance DisjunctiveMonoid (TupTypor a b) where + falseP = TupTypor (pure (Ap [])) + TupTypor s0 >|< TupTypor s1 = TupTypor (liftA2 unite s0 s1) where unite (Ap shapes0) (Ap shapes1) = Ap (shapes0 <> shapes1) -- | `manyP` is a rest element, of the union of the elements of its shapes. -instance Distributor TsTupGrammor where - manyP (TsTupGrammor s) = TsTupGrammor (rest <$> s) +instance Distributor TupTypor where + manyP (TupTypor s) = TupTypor (rest <$> s) where rest (Ap shapes) = Ap $ - case concatMap (map tsElementType) shapes of + case concatMap (map elementType) shapes of [] -> [[]] - ts -> [[TsRest (tsUnion ts)]] -instance Alternative (TsTupGrammor a) where + ts -> [[JsonRest (jsonUnion ts)]] +instance Alternative (TupTypor a) where empty = falseP (<|>) = (>|<) many = lmap repeat . manyP some = lmap repeat . someP -instance Alternator TsTupGrammor -instance JsonTup TsGrammor TsTupGrammor where - jsonElem (TsGrammor t) = - TsTupGrammor (Ap ((\ty -> Ap [[TsRequired ty]]) <$> tsGuarded t)) - -deriving via Grammor (Ap TsDefining (Ap [] [TsProperty])) a - instance Functor (TsObjGrammor a) -deriving via Grammor (Ap TsDefining (Ap [] [TsProperty])) a - instance Applicative (TsObjGrammor a) -deriving via Grammor (Ap TsDefining (Ap [] [TsProperty])) - instance Profunctor TsObjGrammor -instance Choice TsObjGrammor where +instance Alternator TupTypor +instance JsonTup JsonTypor TupTypor where + jsonElem (JsonTypor t) = + TupTypor (Ap ((\ty -> Ap [[JsonRequired ty]]) <$> guarded t)) + +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 TsObjGrammor -instance CocartesianChoice TsObjGrammor where +instance CocartesianMonoidal ObjTypor +instance CocartesianChoice ObjTypor where alternate = either coerce coerce -instance DisjunctiveMonoid (TsObjGrammor a b) where - falseP = TsObjGrammor (pure (Ap [])) - TsObjGrammor s0 >|< TsObjGrammor s1 = TsObjGrammor (liftA2 unite s0 s1) +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 TsGrammor TsObjGrammor where - jsonDict key (TsGrammor t) = tsProperty $ do - keyType <- tsGuarded k - rules <- lift (gets tsRules) - TsIndex keyType (tsAlternatives rules keyType) <$> tsGuarded t - where - TsGrammor k = key - k !: TsGrammor t = tsProperty (TsProperty k False <$> tsGuarded t) - k ?: TsGrammor t = tsProperty (TsProperty k True <$> tsGuarded t) - --- | The alternatives of a type, resolving its aliases. -tsAlternatives :: Map String TsType -> TsType -> [TsType] -tsAlternatives rules = go [] - where - go seen = \case - TsAlias name | name `notElem` seen, Just t <- Map.lookup name rules -> - go (name : seen) t - TsUnion ts -> concatMap (go seen) ts - t -> [t] +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. -tsProperty :: TsDefining TsProperty -> TsObjGrammor a b -tsProperty prop = TsObjGrammor (Ap ((\p -> Ap [[p]]) <$> prop)) +typedProperty :: Typing JsonProperty -> ObjTypor a b +typedProperty prop = ObjTypor (Ap ((\p -> Ap [[p]]) <$> prop)) --- Rendering TypeScript -- +elementType :: JsonElement -> JsonType +elementType = \case + JsonRequired t -> t + JsonOptional t -> t + JsonRest t -> t --- | Render the TypeScript type alias declarations of rules, sharing them. -renderTypeScript :: [TsGrammor () ()] -> Text -renderTypeScript roots = - Text.unlines (map declaration (Map.toList (tsRules definitions))) - where - definitions = execState - (runReaderT (traverse_ (\(TsGrammor ts) -> ts) roots) Map.empty) - (TsDefinitions Map.empty Map.empty) - declaration (name, ty) = - "export type " <> Text.pack name <> " = " <> renderTsType ty <> ";" - -renderTsType :: TsType -> Text -renderTsType = \case - TsAlias name -> Text.pack name - TsNull -> "null" - TsUndefined -> "undefined" - TsBoolean -> "boolean" - TsNumber -> "number" - TsString -> "string" - TsNumeric -> "`${number}`" - TsLiteral t -> tsStringLiteral t - TsArray t -> renderTsOperand t <> "[]" - TsTuple els -> "[" <> Text.intercalate ", " (map renderTsElement els) <> "]" - TsObject props -> Text.intercalate " & " (renderTsObject props) - TsUnion [] -> "never" - TsUnion ts -> Text.intercalate " | " (map renderTsType ts) - -renderTsOperand :: TsType -> Text -renderTsOperand = \case - TsUnion ts@(_ : _ : _) -> "(" <> renderTsType (TsUnion ts) <> ")" - TsObject props | length (renderTsObject props) > 1 -> - "(" <> renderTsType (TsObject props) <> ")" - t -> renderTsType t - -{- | The intersected parts of an object type: its named properties -& index signatures, of its @string@ or @\`${number}\`@ keys, & a mapped type -of its literal keys, but those which are named, which TypeScript types -apart, like @{ id: T } & { [key in Exclude]?: U }@. +-- 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. -} -renderTsObject :: [TsProperty] -> [Text] -renderTsObject props = case (named <> indexSignatures, keyedTypes) of - ([], []) -> ["{}"] - ([], _) -> keyedTypes - (rendered, _) -> - ("{ " <> Text.intercalate "; " rendered <> " }") : keyedTypes - where - named = [renderTsProperty k o t | TsProperty k o t <- props] - names = [k | TsProperty k _ _ <- props] - indexSignatures = - [ "[key: " <> renderTsType pattern <> "]: " - <> renderTsType (tsUnion (t : covered pattern)) - | TsIndex _ alternatives t <- props - , t /= TsUnion [] - , pattern <- take 1 - [p | p <- [TsString, TsNumeric], p `elem` alternatives] - ] - -- An index type also covers the named properties it matches, - -- as TypeScript requires. - covered pattern = - [t | TsProperty k _ t <- props, matches pattern k] - <> [TsUndefined | or [o | TsProperty k o _ <- props, matches pattern k]] - matches = \case - TsNumeric -> isJust . readScientific - _ -> const True - keyedTypes = - [ "{ [key in " <> keys <> "]?: " <> renderTsType t <> " }" - | TsIndex k alternatives t <- props - , t /= TsUnion [] - , let - literalKeys = [TsLiteral l | TsLiteral l <- alternatives] - excluded = [l | l@(TsLiteral name) <- literalKeys, name `elem` names] - base - | length literalKeys == length alternatives = renderTsType k - | otherwise = renderTsType (tsUnion literalKeys) - keys - | null excluded = base - | otherwise = - "Exclude<" <> base <> ", " <> renderTsType (tsUnion excluded) - <> ">" - , length excluded < length literalKeys - ] - -renderTsElement :: TsElement -> Text -renderTsElement = \case - TsRequired t -> renderTsType t - TsOptional t -> renderTsOperand t <> "?" - TsRest t -> "..." <> renderTsOperand t <> "[]" - -renderTsProperty :: Text -> Bool -> TsType -> Text -renderTsProperty name isOptional t = - tsPropertyKey name <> (if isOptional then "?: " else ": ") <> renderTsType t - -tsPropertyKey :: Text -> Text -tsPropertyKey name - | isIdentifier name = name - | otherwise = tsStringLiteral name +tsDeclarations :: [Bnf JsonType] -> [TsDeclaration] +tsDeclarations bnfs = + [ TypeAliasDeclaration True identifier (tsType rules names ruleType) + | (identifier, ruleType) <- sortOn fst + [(names Map.! key, ruleType) | (key, ruleType) <- Map.toList rules] + ] where - isIdentifier t = case Text.uncons t of - Just (c, rest) -> identifierStart c && Text.all identifierChar rest - Nothing -> False - identifierStart c = isAlpha c || c == '_' || c == '$' - identifierChar c = isAlphaNum c || c == '_' || c == '$' - -tsStringLiteral :: Text -> Text -tsStringLiteral = LText.toStrict . encodeToLazyText . String + 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 @@ -1910,6 +1849,196 @@ tsIdentifier name = case Text.uncons ident of , 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 -> TypeNode +tsType rules names = typeNode + where + typeNode = \case + JsonRule key -> TypeReference (names Map.! key) [] + JsonNull -> LiteralType NullLiteral + JsonBoolean -> KeywordType BooleanKeyword + JsonNumber -> KeywordType NumberKeyword + JsonString -> KeywordType StringKeyword + JsonNumeric -> numeric + JsonStringLiteral text -> LiteralType (TextLiteral text) + JsonArray t -> ArrayType (operand (typeNode t)) + t@(JsonTuple _) -> typeNode (JsonUnion [t]) + JsonObject props -> object props + JsonUnion ts -> union $ case break isTuple ts of + (before, _ : _) -> + map typeNode before + <> map tuple (tsTuples [els | JsonTuple els <- ts]) + <> [typeNode t | t <- drop (length before) ts, not (isTuple t)] + _ -> map typeNode ts + isTuple = \case JsonTuple _ -> True; _ -> False + numeric = TemplateLiteralType "" [(KeywordType NumberKeyword, "")] + tuple els = TupleType $ els <&> \case + JsonRequired t -> typeNode t + JsonOptional t -> OptionalType (operand (typeNode t)) + JsonRest t -> RestType (ArrayType (operand (typeNode t))) + -- The intersected parts of an object type: its named properties + -- & index signatures, of its string or numeric 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 + ([], []) -> TypeLiteral [] + ([], [objectPart]) -> objectPart + ([], objectParts) -> IntersectionType objectParts + (members, objectParts) -> case TypeLiteral members : objectParts of + [objectPart] -> objectPart + allObjectParts -> IntersectionType allObjectParts + where + named = + [ PropertySignature (propertyName key) isOptional (typeNode t) + | JsonProperty key isOptional t <- props ] + keys = [key | JsonProperty key _ _ <- props] + dicts = + [ (keyType, typeAlternatives rules keyType, t) + | JsonDict keyType t <- props, t /= mempty ] + indexSignatures = + [ IndexSignature "key" (typeNode pattern) $ union + (typeNode t : covered pattern) + | (_, keyAlternatives, t) <- dicts + , pattern <- take 1 + [p | p <- [JsonString, JsonNumeric], p `elem` keyAlternatives] + ] + -- An index type also covers the named properties it matches, + -- as TypeScript requires. + covered pattern = + [typeNode t | JsonProperty key _ t <- props, matches pattern key] + <> [ KeywordType UndefinedKeyword + | or [o | JsonProperty key o _ <- props, matches pattern key] ] + matches = \case + JsonNumeric -> isJust . readScientific + _ -> const True + mappedTypes = + [ MappedType "key" base exclusion True (typeNode t) + | (keyType, keyAlternatives, t) <- dicts + , let + literalKeys = [l | JsonStringLiteral 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 + (TypeReference "key" []) + (union (map (LiteralType . TextLiteral) excluded)) + (KeywordType NeverKeyword) + (TypeReference "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 :: [TypeNode] -> TypeNode +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 :: TypeNode -> TypeNode +operand = \case + node@(UnionType _) -> ParenthesizedType node + node@(IntersectionType _) -> ParenthesizedType node + node@(ConditionalType {}) -> ParenthesizedType node + node -> node + +-- | The alternatives of a type, resolving its rules. +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 + 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 :: [[JsonElement]] -> [[JsonElement]] +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 + (JsonRequired s, JsonRequired t) -> Just (JsonRequired (s <> t)) + (JsonOptional s, JsonOptional t) -> Just (JsonOptional (s <> t)) + _ -> Nothing + extended a b + | any isRest a = Nothing + | otherwise = stripPrefix a b >>= \case + [JsonRequired t] -> Just (a <> [JsonOptional t]) + [JsonOptional _] -> Just b + [JsonRest _] -> Just b + [JsonRequired t, JsonRest u] | t == u -> Just (a <> [JsonRest t]) + _ -> Nothing + isRest = \case JsonRest _ -> 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 <> [JsonRest (jsonUnion (map elementType middle))] <> after + _ -> els + expand _ [] = [[]] + expand restBefore (el : els) = case el of + JsonOptional t | restBefore || not (optionalTail els) -> + expand restBefore els <> map (JsonRequired t :) (expand restBefore els) + JsonRest _ -> map (el :) (expand True els) + _ -> map (el :) (expand restBefore els) + optionalTail = \case + [] -> True + [JsonRest _] -> True + JsonOptional _ : els -> optionalTail els + _ -> False + -- Json instance helpers -- | An enumeration of string literals, typed as their union. 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..2d9d793f --- /dev/null +++ b/distributors-json/src/Control/Lens/Grammar/TypeScript.hs @@ -0,0 +1,505 @@ +{-# LANGUAGE OverloadedStrings #-} + +{- | +Module : Control.Lens.Grammar.TypeScript +Description : TypeScript type declarations, as a grammar +Copyright : (C) 2026 - Eitan Chatav +License : BSD-style (see the file LICENSE) +Maintainer : Eitan Chatav +Stability : provisional +Portability : non-portable + +The type declarations of TypeScript, like the TypeScript compiler, +in two layers: a `tsTokenGrammar` of its tokens, by their `SyntaxKind`s, +& a `tsGrammar` of its syntax, of those tokens, by the compiler's +names of its nodes, so that they parse & print together. + +>>> :set -XOverloadedStrings +>>> let point = TypeLiteral [PropertySignature (PropertyIdentifier "x") False (KeywordType NumberKeyword)] +>>> mapM_ putStr (tsPrint [TypeAliasDeclaration True "Point" point]) +export type Point = { x: number }; + +>>> tsParse "type Pair = [string, number?];" +Just [TypeAliasDeclaration False "Pair" (TupleType [KeywordType StringKeyword,OptionalType (KeywordType NumberKeyword)])] +-} + +module Control.Lens.Grammar.TypeScript + ( -- * Syntax + TsDeclaration (..) + , TypeNode (..) + , TypeElement (..) + , PropertyName (..) + , Literal (..) + , tsGrammar + -- * Tokens + , TsToken (..) + , SyntaxKind (..) + , tsTokenGrammar + -- * Text + , tsPrint + , tsParse + ) where + +import Control.Lens +import Control.Lens.Grammar +import Data.Char (chr, ord) +import Data.Maybe (fromMaybe, listToMaybe) +import Data.Text (Text) +import Data.Text qualified as Text +import Numeric (readHex, showHex) + +-- Syntax -- + +-- | A type alias, @export type T = U;@, exported or not. +data TsDeclaration = TypeAliasDeclaration Bool Text TypeNode + deriving stock (Eq, Ord, Show, Read) + +-- | A type, by the TypeScript compiler's name of its node. +data TypeNode + = KeywordType SyntaxKind -- ^ @number@, @string@, @never@, … + | LiteralType Literal -- ^ @null@, @true@ or @"abc"@ + | TypeReference Text [TypeNode] -- ^ @T@ or @T\@ + | ArrayType TypeNode -- ^ @T[]@ + | TupleType [TypeNode] -- ^ @[T, U]@ + | OptionalType TypeNode -- ^ @T?@, an element of a tuple + | RestType TypeNode -- ^ @...T@, an element of a tuple + | UnionType [TypeNode] -- ^ @T | U@ + | IntersectionType [TypeNode] -- ^ @T & U@ + | ParenthesizedType TypeNode -- ^ @(T)@ + | TypeLiteral [TypeElement] -- ^ @{ x: T; y?: U }@ + | MappedType Text TypeNode (Maybe TypeNode) Bool TypeNode + -- ^ @{ [k in K as L]?: T }@, with a name type & an optional token or not + | ConditionalType TypeNode TypeNode TypeNode TypeNode + -- ^ @T extends U ? V : W@ + | TemplateLiteralType Text [(TypeNode, Text)] + -- ^ @\`a${T}b\`@, by its head & its spans' types & literals + deriving stock (Eq, Ord, Show, Read) + +-- | A member of a `TypeLiteral`. +data TypeElement + = PropertySignature PropertyName Bool TypeNode + -- ^ @x: T@ or @x?: T@ + | IndexSignature Text TypeNode TypeNode -- ^ @[k: K]: T@ + deriving stock (Eq, Ord, Show, Read) + +-- | The name of a `PropertySignature`. +data PropertyName + = PropertyIdentifier Text -- ^ @x@ + | PropertyString Text -- ^ @"x y"@ + deriving stock (Eq, Ord, Show, Read) + +-- | A literal of a `LiteralType`. +data Literal + = NullLiteral -- ^ @null@ + | TrueLiteral -- ^ @true@ + | FalseLiteral -- ^ @false@ + | TextLiteral Text -- ^ @"abc"@ + deriving stock (Eq, Ord, Show, Read) + +-- Tokens -- + +{- | A token, of a `SyntaxKind` & 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 or a template's literal. +-} +data TsToken = TsToken + { tokenKind :: SyntaxKind + , tokenText :: Text + } deriving stock (Eq, Ord, Show, Read) + +instance Categorized TsToken where + type Categorize TsToken = SyntaxKind + categorize = tokenKind + +-- | The kinds of `TsToken`s, by the TypeScript compiler's names. +data SyntaxKind + = WhitespaceTrivia + | NewLineTrivia + | Identifier + | StringLiteral + | NoSubstitutionTemplateLiteral + | TemplateHead + | TemplateMiddle + | TemplateTail + | OpenBraceToken + | CloseBraceToken + | OpenParenToken + | CloseParenToken + | OpenBracketToken + | CloseBracketToken + | DotDotDotToken + | SemicolonToken + | CommaToken + | LessThanToken + | GreaterThanToken + | QuestionToken + | ColonToken + | EqualsToken + | BarToken + | AmpersandToken + | AnyKeyword + | AsKeyword + | BigIntKeyword + | BooleanKeyword + | ExportKeyword + | ExtendsKeyword + | FalseKeyword + | InKeyword + | KeyOfKeyword + | NeverKeyword + | NullKeyword + | NumberKeyword + | ObjectKeyword + | ReadonlyKeyword + | StringKeyword + | SymbolKeyword + | TrueKeyword + | TypeKeyword + | UndefinedKeyword + | UnknownKeyword + | VoidKeyword + deriving stock (Eq, Ord, Show, Read, Enum, Bounded) + +makeNestedPrisms ''TsDeclaration +makeNestedPrisms ''TypeNode +makeNestedPrisms ''TypeElement +makeNestedPrisms ''PropertyName +makeNestedPrisms ''Literal + +-- | The text of a punctuation or keyword `SyntaxKind`. +kindText :: SyntaxKind -> Maybe Text +kindText = flip lookup ((CloseBraceToken, "}") : punctuation <> keywords) + +punctuation :: [(SyntaxKind, Text)] +punctuation = + [ (OpenBraceToken, "{"), (OpenParenToken, "("), (CloseParenToken, ")") + , (OpenBracketToken, "["), (CloseBracketToken, "]") + , (DotDotDotToken, "..."), (SemicolonToken, ";"), (CommaToken, ",") + , (LessThanToken, "<"), (GreaterThanToken, ">"), (QuestionToken, "?") + , (ColonToken, ":"), (EqualsToken, "="), (BarToken, "|") + , (AmpersandToken, "&") + ] + +keywords :: [(SyntaxKind, Text)] +keywords = + [ (AnyKeyword, "any"), (AsKeyword, "as"), (BigIntKeyword, "bigint") + , (BooleanKeyword, "boolean"), (ExportKeyword, "export") + , (ExtendsKeyword, "extends"), (FalseKeyword, "false"), (InKeyword, "in") + , (KeyOfKeyword, "keyof"), (NeverKeyword, "never"), (NullKeyword, "null") + , (NumberKeyword, "number"), (ObjectKeyword, "object") + , (ReadonlyKeyword, "readonly"), (StringKeyword, "string") + , (SymbolKeyword, "symbol"), (TrueKeyword, "true"), (TypeKeyword, "type") + , (UndefinedKeyword, "undefined"), (UnknownKeyword, "unknown") + , (VoidKeyword, "void") + ] + +-- | The token of a punctuation or keyword `SyntaxKind`. +symbol :: SyntaxKind -> TsToken +symbol kind = TsToken kind (fromMaybe "" (kindText kind)) + +{- | A token, scanned from its characters. Its trivia are tokens, +as the scanner of the TypeScript compiler scans without skipping them, +so that @`manyP` tsTokenGrammar@ scans a file. + +Unlike the compiler's scanner, which rescans a @}@ as a template's +middle or tail, by the context of its parser, `tsTokenGrammar` is regular, +so that a @}@ followed by @\`@ or @${@ is a template's tail or middle, +of an empty literal, as it always is in a type. +-} +tsTokenGrammar :: RegGrammar Char TsToken +tsTokenGrammar = orP + [ kindOf WhitespaceTrivia >? someP (oneOf @Char (" \t" :: String)) + , kindOf NewLineTrivia >? orP + [only "\n" >? terminal "\n", only "\r\n" >? terminal "\r\n"] + , _Word >? identifierStart >:< manyP identifierPart + , kindOf StringLiteral >? terminal "\"" >* manyP stringChar *< terminal "\"" + , _Template >? terminal "`" >* manyP templateChar >*< orP + [ only NoSubstitutionTemplateLiteral >? terminal "`" + , only TemplateHead >? terminal "${" + ] + , _Closing >? terminal "}" >* orP + [ only TemplateTail >? terminal "`" + , only TemplateMiddle >? terminal "${" + , only CloseBraceToken >? oneP + ] + , orP + [ only (TsToken kind text) >? terminal (Text.unpack text) + | (kind, text) <- punctuation + ] + ] + where + identifierStart = orP + [ asIn @Char UppercaseLetter, asIn @Char LowercaseLetter + , asIn @Char TitlecaseLetter + , asIn @Char ModifierLetter, asIn @Char OtherLetter + , asIn @Char LetterNumber + , oneOf @Char ("_$" :: String) + ] + identifierPart = orP + [ identifierStart, asIn @Char DecimalNumber, asIn @Char NonSpacingMark + , asIn @Char SpacingCombiningMark, asIn @Char ConnectorPunctuation + ] + stringChar = orP + [ notOneOf @Char ('"' : '\\' : ['\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)) + ] + ] + hexDigits = "0123456789abcdefABCDEF" :: String + templateChar = orP + [ notOneOf @Char ("`$\\" :: String) + , terminal "\\" >* oneOf @Char ("`$\\" :: String) + ] + +-- | A token of a kind, by its text. +kindOf :: SyntaxKind -> Prism' TsToken String +kindOf kind = prism' + (TsToken kind . Text.pack) + (\(TsToken kind' text) -> + if kind == kind' then Just (Text.unpack text) else Nothing) + +-- | An identifier or keyword, by its text. +_Word :: Prism' TsToken String +_Word = prism' word $ \(TsToken kind text) -> + if kind == Identifier || kind `elem` map fst keywords + then Just (Text.unpack text) else Nothing + where + word chars = case lookup text [(t, k) | (k, t) <- keywords] of + Just kind -> TsToken kind text + Nothing -> TsToken Identifier text + where + text = Text.pack chars + +-- | A template without substitutions, or a template's head. +_Template :: Prism' TsToken (String, SyntaxKind) +_Template = prism' + (\(chars, kind) -> TsToken kind (Text.pack chars)) + (\(TsToken kind text) -> + if kind `elem` [NoSubstitutionTemplateLiteral, TemplateHead] + then Just (Text.unpack text, kind) else Nothing) + +-- | A @}@, or a template's middle or tail, of an empty literal. +_Closing :: Prism' TsToken SyntaxKind +_Closing = prism' + (\kind -> TsToken kind (if kind == CloseBraceToken then "}" else "")) + (\case + TsToken CloseBraceToken "}" -> Just CloseBraceToken + TsToken TemplateMiddle "" -> Just TemplateMiddle + TsToken TemplateTail "" -> Just TemplateTail + _ -> Nothing) + +-- | 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 -- + +{- | Type declarations, of tokens, by the TypeScript compiler's syntax. + +Trivia, whitespace & newlines, are parsed between tokens, & printed +conventionally. Each run of trivia is the trivia of exactly one token, +either before or after it, so that it parses only one way. +-} +tsGrammar :: Grammar TsToken [TsDeclaration] +tsGrammar = rule "declarations" $ + trivia [] >* manyP declaration + where + declaration = rule "declaration" $ _TypeAliasDeclaration + >? exported + >*< identifier + >*< tokenOf space EqualsToken space >* typeNode + *< tokenOf tight SemicolonToken newline + exported = orP + [ only True >? tokenOf oneP ExportKeyword space + >* tokenOf oneP TypeKeyword space + , only False >? tokenOf oneP TypeKeyword space + ] + typeNode = ruleRec "type" $ \ty -> _Conditional + >~ unionType ty >*< optionalP + ( tokenOf space ExtendsKeyword space >* unionType ty + >*< tokenOf space QuestionToken space >* ty + >*< tokenOf space ColonToken space >* ty + ) + unionType ty = rule "union" $ _Several _UnionType + >~ leading BarToken >* intersectionType ty >*< manyP + (tokenOf space BarToken space >* intersectionType ty) + intersectionType ty = rule "intersection" $ _Several _IntersectionType + >~ leading AmpersandToken >* postfixType ty >*< manyP + (tokenOf space AmpersandToken space >* postfixType ty) + -- A leading operator, which is parsed but not printed. + leading kind = dimap (const Nothing) (const ()) + (optionalP (tokenOf oneP kind space)) + postfixType ty = rule "postfix" $ _Arrays + >~ primaryType ty >*< manyP + ( tokenOf tight OpenBracketToken oneP + >* tokenOf tight CloseBracketToken oneP + ) + primaryType ty = rule "primary" $ orP + [ _KeywordType >? orP + [ only kind >? tokenOf oneP kind oneP + | kind <- + [ AnyKeyword, BigIntKeyword, BooleanKeyword, NeverKeyword + , NumberKeyword, ObjectKeyword, StringKeyword, SymbolKeyword + , UndefinedKeyword, UnknownKeyword, VoidKeyword + ] + ] + , _LiteralType >? orP + [ only NullLiteral >? tokenOf oneP NullKeyword oneP + , only TrueLiteral >? tokenOf oneP TrueKeyword oneP + , only FalseLiteral >? tokenOf oneP FalseKeyword oneP + , _TextLiteral >? textOf StringLiteral + ] + , _NoSubstitution >? textOf NoSubstitutionTemplateLiteral + , _TemplateLiteralType >? textOf TemplateHead *< trivia [] >*< + (_Snoc >? manyP (templateSpan TemplateMiddle (trivia [])) + >*< templateSpan TemplateTail oneP) + , _TypeReference >? identifier >*< orP + [ only [] >? oneP + , tokenOf tight LessThanToken tight + >* several1 (sepBy comma) ty + *< tokenOf tight GreaterThanToken oneP + ] + , _TupleType >? orP + [ only [] >? tokenOf oneP OpenBracketToken oneP + >* tokenOf tight CloseBracketToken oneP + , tokenOf oneP OpenBracketToken tight + >* several1 (sepBy comma) (tupleElement ty) + *< tokenOf tight CloseBracketToken oneP + ] + , _ParenthesizedType >? tokenOf oneP OpenParenToken tight + >* ty *< tokenOf tight CloseParenToken oneP + , _TypeLiteral >? orP + [ only [] >? tokenOf oneP OpenBraceToken oneP + >* tokenOf tight CloseBraceToken oneP + , tokenOf oneP OpenBraceToken space + >* several1 (sepBy semicolon) (member ty) + *< optionalSemicolon + *< tokenOf space CloseBraceToken oneP + ] + , _MappedType >? tokenOf oneP OpenBraceToken space + >* tokenOf oneP OpenBracketToken tight >* identifier + >*< tokenOf space InKeyword space >* ty + >*< optionalP (tokenOf space AsKeyword space >* ty) + >*< tokenOf tight CloseBracketToken oneP >* question + >*< tokenOf tight ColonToken space >* ty + *< tokenOf space CloseBraceToken oneP + ] + where + templateSpan kind after = + ty >*< trivia [] >* textOf kind *< after + tupleElement ty = rule "element" $ orP + [ _RestType >? tokenOf oneP DotDotDotToken tight >* ty + , _OptionalType >? ty *< tokenOf tight QuestionToken oneP + , ty + ] + member ty = rule "member" $ orP + [ _PropertySignature >? propertyName >*< question + >*< tokenOf tight ColonToken space >* ty + , _IndexSignature >? tokenOf oneP OpenBracketToken tight >* identifier + >*< tokenOf tight ColonToken space >* ty + >*< tokenOf tight CloseBracketToken oneP + >* tokenOf tight ColonToken space >* ty + ] + propertyName = orP + [ _PropertyIdentifier >? identifier + , _PropertyIdentifier >? orP + [only text >? tokenOf oneP kind oneP | (kind, text) <- keywords] + , _PropertyString >? textOf StringLiteral + ] + question = orP + [ only True >? tokenOf tight QuestionToken oneP + , only False >? oneP + ] + comma = tokenOf tight CommaToken space + semicolon = tokenOf tight SemicolonToken space + optionalSemicolon = dimap (const Nothing) (const ()) + (optionalP (tokenOf tight SemicolonToken oneP)) + identifier = textOf Identifier + space = trivia [TsToken WhitespaceTrivia " "] + newline = trivia [TsToken NewLineTrivia "\n"] + tight = trivia [] + +{- | Trivia, of any whitespace & newlines, printed as some trivia. -} +trivia + :: (Lexical TsToken p, Alternator p) + => [TsToken] -> p () () +trivia printed = dimap (const printed) (const ()) + (manyP (asIn @TsToken WhitespaceTrivia >|< asIn @TsToken NewLineTrivia)) + +-- | A punctuation or keyword token, between trivia, or `oneP`. +tokenOf + :: (Lexical TsToken p, Alternator p) + => p () () -> SyntaxKind -> p () () -> p () () +tokenOf before kind after = before >* terminal [symbol kind] *< after + +-- | The text of a token of a kind. +textOf :: (Lexical TsToken p, Alternator p) => SyntaxKind -> p Text Text +textOf kind = iso (TsToken kind) tokenText >~ asIn @TsToken kind + +-- | A list of at least two, or else its only one. +_Several + :: Prism' TypeNode [TypeNode] -> Iso' TypeNode (TypeNode, [TypeNode]) +_Several nodes = iso + (\node -> case node ^? nodes of + Just (first : others@(_ : _)) -> (first, others) + _ -> (node, [])) + (\case + (node, []) -> node + (first, others) -> review nodes (first : others)) + +-- | A type of any arrays of its element type. +_Arrays :: Iso' TypeNode (TypeNode, [()]) +_Arrays = iso arrays (uncurry (foldr (const ArrayType))) + where + arrays = \case + ArrayType node -> (() :) <$> arrays node + node -> (node, []) + +-- | A conditional type, or else its check type. +_Conditional + :: Iso' TypeNode (TypeNode, Maybe (TypeNode, (TypeNode, TypeNode))) +_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) + +-- | A template literal type without substitutions. +_NoSubstitution :: Prism' TypeNode Text +_NoSubstitution = prism' (`TemplateLiteralType` []) $ \case + TemplateLiteralType text [] -> Just text + _ -> Nothing + +-- Text -- + +{- | Print type declarations, by `tsGrammar` & `tsTokenGrammar`, +or `Nothing` for syntax that they don't print, like an unparenthesized +union type within an array type. +-} +tsPrint :: [TsDeclaration] -> Maybe String +tsPrint declarations = do + printed <- ($ []) <$> printG tsGrammar declarations + ($ "") <$> printG (manyP tsTokenGrammar) printed + +-- | Parse type declarations, by `tsTokenGrammar` & `tsGrammar`. +tsParse :: String -> Maybe [TsDeclaration] +tsParse source = do + let scanned = parsecG (manyP tsTokenGrammar) source + scannedTokens <- parsecResult scanned + if null (parsecStream scanned) + then listToMaybe + [parsed | (parsed, []) <- parseG tsGrammar scannedTokens] + else Nothing diff --git a/distributors-json/test/Main.hs b/distributors-json/test/Main.hs index c0bec4b6..03cec9f1 100644 --- a/distributors-json/test/Main.hs +++ b/distributors-json/test/Main.hs @@ -34,6 +34,7 @@ doctests = do let modulePaths = [ "src/Control/Lens/Grammar/Json.hs" + , "src/Control/Lens/Grammar/TypeScript.hs" ] packageEnvFlags = case ghcEnvironment of Just "-" -> [] diff --git a/distributors-json/test/Properties/Json.hs b/distributors-json/test/Properties/Json.hs index 2fab8769..f517238a 100644 --- a/distributors-json/test/Properties/Json.hs +++ b/distributors-json/test/Properties/Json.hs @@ -24,6 +24,9 @@ import Control.Lens.Grammar , (>*<), (>+<), (>?), (>|<), (>~) ) import Control.Lens.Grammar.Json +import Data.Kind (Type) +import Data.SOP (All) +import Control.Lens.Grammar.TypeScript (tsParse, tsPrint) import Data.Aeson ( FromJSON (..), Options (..), SumEncoding (..), ToJSON (..), Value (String) , camelTo2, decode, defaultOptions, genericToJSON @@ -286,8 +289,8 @@ jsonObjectSpec = describe "jsonObject" $ do 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 Exclude<\"no\" | \"yes\", \"yes\">]?: Int };" + , "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)])) @@ -510,12 +513,18 @@ jsonPrintSpec = describe "jsonErrorPrint" $ do printError (Dup (1, 2)) `shouldBe` Left "Error in $: cannot print key \"k\" twice" --- | TypeScript type declarations, one per line. +{- | TypeScript type declarations, one per line, +which parse as the declarations which print them. +-} declares :: forall a -> Json a => [Text] -> Expectation -declares a declarations = jsonTypes [a] `shouldBe` Text.unlines declarations +declares a declarations = do + tsTypes [a] `shouldBe` Text.unlines declarations + (tsPrint parsed >>= tsParse) `shouldBe` Just parsed + where + parsed = jsonTsDeclarations [a] jsonTypeSpec :: Spec -jsonTypeSpec = describe "jsonTypes" $ do +jsonTypeSpec = describe "jsonTsDeclarations" $ do let point = "{ px: number; py: number }" it "declares nothing for types without rules" $ do declares Bool [] @@ -593,7 +602,7 @@ jsonTypeSpec = describe "jsonTypes" $ do it "declares the rules of types without rules" $ declares (type (Vector Point)) ["export type Point = " <> point <> ";"] it "declares each type once" $ - length (Text.lines (jsonTypes [Twice16])) `shouldBe` 16 + length (Text.lines (tsTypes [Twice16])) `shouldBe` 16 it "names colliding declarations uniquely" $ declares (type Collide) [ "export type Collide = \ @@ -604,19 +613,18 @@ jsonTypeSpec = describe "jsonTypes" $ do it "names declarations by distinct TypeScript identifiers" $ do let pair = "Properties_Json_GHC_Types_Int_Data_Text_Internal_Text" declares (type Sanitized) - [ "export type Int = number;" - , "export type Int_Text = \ + [ "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 Properties_Json_Exclude = number;" - , "export type " <> pair <> " = [Int, string];" - , "export type Sanitized = \ - \[Int_Text, " <> pair <> ", Properties_Json_Exclude];" + , "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" $ - jsonTypes (type [Point, Box Point]) `shouldBe` Text.unlines + tsTypes (type [Point, Box Point]) `shouldBe` Text.unlines [ "export type Box_Point = Point;" , "export type Point = " <> point <> ";" ] @@ -658,7 +666,9 @@ instance Json Collide where <$> lmap named ("named" !: rule "Point" jsonNumber) <*> lmap typed ("typed" !: json) --- | Types named by the same identifier, @Int_Text@, & one named @Exclude@. +{- | 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 @@ -1159,3 +1169,7 @@ jsonOptionsSpec = describe "jsonGeneric" $ do 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 = maybe "" Text.pack (tsPrint (jsonTsDeclarations as)) From 9146b2395992224740c3d01f65961450d7ca7669 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Fri, 6 Nov 2026 01:17:00 -0800 Subject: [PATCH 016/130] Rename SyntaxKind to TsTokenCategory; pin CI's hpack to Stack's Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 4 +- .../src/Control/Lens/Grammar/TypeScript.hs | 38 +++++++++---------- 2 files changed, 21 insertions(+), 21 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8bf6ed8b..f99b2e4a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -31,13 +31,13 @@ jobs: - name: Check generated .cabal files match package.yaml run: | - curl -sSL https://github.com/sol/hpack/releases/download/0.38.1/hpack_linux.gz \ + 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-json; do (cd "$package" && ../hpack --force) done - git diff --exit-code -- '*.cabal' + git diff --exit-code -I 'by hpack version' -- '*.cabal' stack: runs-on: ubuntu-latest diff --git a/distributors-json/src/Control/Lens/Grammar/TypeScript.hs b/distributors-json/src/Control/Lens/Grammar/TypeScript.hs index 2d9d793f..21ac8f84 100644 --- a/distributors-json/src/Control/Lens/Grammar/TypeScript.hs +++ b/distributors-json/src/Control/Lens/Grammar/TypeScript.hs @@ -10,7 +10,7 @@ Stability : provisional Portability : non-portable The type declarations of TypeScript, like the TypeScript compiler, -in two layers: a `tsTokenGrammar` of its tokens, by their `SyntaxKind`s, +in two layers: a `tsTokenGrammar` of its tokens, by their `TsTokenCategory`s, & a `tsGrammar` of its syntax, of those tokens, by the compiler's names of its nodes, so that they parse & print together. @@ -33,7 +33,7 @@ module Control.Lens.Grammar.TypeScript , tsGrammar -- * Tokens , TsToken (..) - , SyntaxKind (..) + , TsTokenCategory (..) , tsTokenGrammar -- * Text , tsPrint @@ -56,7 +56,7 @@ data TsDeclaration = TypeAliasDeclaration Bool Text TypeNode -- | A type, by the TypeScript compiler's name of its node. data TypeNode - = KeywordType SyntaxKind -- ^ @number@, @string@, @never@, … + = KeywordType TsTokenCategory -- ^ @number@, @string@, @never@, … | LiteralType Literal -- ^ @null@, @true@ or @"abc"@ | TypeReference Text [TypeNode] -- ^ @T@ or @T\@ | ArrayType TypeNode -- ^ @T[]@ @@ -98,21 +98,21 @@ data Literal -- Tokens -- -{- | A token, of a `SyntaxKind` & its text, as the scanner of +{- | 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 or a template's literal. -} data TsToken = TsToken - { tokenKind :: SyntaxKind + { tokenCategory :: TsTokenCategory , tokenText :: Text } deriving stock (Eq, Ord, Show, Read) instance Categorized TsToken where - type Categorize TsToken = SyntaxKind - categorize = tokenKind + type Categorize TsToken = TsTokenCategory + categorize = tokenCategory -- | The kinds of `TsToken`s, by the TypeScript compiler's names. -data SyntaxKind +data TsTokenCategory = WhitespaceTrivia | NewLineTrivia | Identifier @@ -166,11 +166,11 @@ makeNestedPrisms ''TypeElement makeNestedPrisms ''PropertyName makeNestedPrisms ''Literal --- | The text of a punctuation or keyword `SyntaxKind`. -kindText :: SyntaxKind -> Maybe Text +-- | The text of a punctuation or keyword `TsTokenCategory`. +kindText :: TsTokenCategory -> Maybe Text kindText = flip lookup ((CloseBraceToken, "}") : punctuation <> keywords) -punctuation :: [(SyntaxKind, Text)] +punctuation :: [(TsTokenCategory, Text)] punctuation = [ (OpenBraceToken, "{"), (OpenParenToken, "("), (CloseParenToken, ")") , (OpenBracketToken, "["), (CloseBracketToken, "]") @@ -180,7 +180,7 @@ punctuation = , (AmpersandToken, "&") ] -keywords :: [(SyntaxKind, Text)] +keywords :: [(TsTokenCategory, Text)] keywords = [ (AnyKeyword, "any"), (AsKeyword, "as"), (BigIntKeyword, "bigint") , (BooleanKeyword, "boolean"), (ExportKeyword, "export") @@ -193,8 +193,8 @@ keywords = , (VoidKeyword, "void") ] --- | The token of a punctuation or keyword `SyntaxKind`. -symbol :: SyntaxKind -> TsToken +-- | The token of a punctuation or keyword `TsTokenCategory`. +symbol :: TsTokenCategory -> TsToken symbol kind = TsToken kind (fromMaybe "" (kindText kind)) {- | A token, scanned from its characters. Its trivia are tokens, @@ -256,7 +256,7 @@ tsTokenGrammar = orP ] -- | A token of a kind, by its text. -kindOf :: SyntaxKind -> Prism' TsToken String +kindOf :: TsTokenCategory -> Prism' TsToken String kindOf kind = prism' (TsToken kind . Text.pack) (\(TsToken kind' text) -> @@ -275,7 +275,7 @@ _Word = prism' word $ \(TsToken kind text) -> text = Text.pack chars -- | A template without substitutions, or a template's head. -_Template :: Prism' TsToken (String, SyntaxKind) +_Template :: Prism' TsToken (String, TsTokenCategory) _Template = prism' (\(chars, kind) -> TsToken kind (Text.pack chars)) (\(TsToken kind text) -> @@ -283,7 +283,7 @@ _Template = prism' then Just (Text.unpack text, kind) else Nothing) -- | A @}@, or a template's middle or tail, of an empty literal. -_Closing :: Prism' TsToken SyntaxKind +_Closing :: Prism' TsToken TsTokenCategory _Closing = prism' (\kind -> TsToken kind (if kind == CloseBraceToken then "}" else "")) (\case @@ -438,11 +438,11 @@ trivia printed = dimap (const printed) (const ()) -- | A punctuation or keyword token, between trivia, or `oneP`. tokenOf :: (Lexical TsToken p, Alternator p) - => p () () -> SyntaxKind -> p () () -> p () () + => p () () -> TsTokenCategory -> p () () -> p () () tokenOf before kind after = before >* terminal [symbol kind] *< after -- | The text of a token of a kind. -textOf :: (Lexical TsToken p, Alternator p) => SyntaxKind -> p Text Text +textOf :: (Lexical TsToken p, Alternator p) => TsTokenCategory -> p Text Text textOf kind = iso (TsToken kind) tokenText >~ asIn @TsToken kind -- | A list of at least two, or else its only one. From 86accd7faa3bd17e9102e1cb7baa02f4c8b50de5 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Fri, 6 Nov 2026 01:20:32 -0800 Subject: [PATCH 017/130] Add jsonTsPut, putting TypeScript declarations to a handle Co-Authored-By: Claude Opus 5.5 --- distributors-json/CHANGELOG.md | 3 ++- distributors-json/README.md | 2 +- .../src/Control/Lens/Grammar/Json.hs | 21 ++++++++++++++++--- 3 files changed, 21 insertions(+), 5 deletions(-) diff --git a/distributors-json/CHANGELOG.md b/distributors-json/CHANGELOG.md index 23da6732..98c44068 100644 --- a/distributors-json/CHANGELOG.md +++ b/distributors-json/CHANGELOG.md @@ -4,7 +4,8 @@ - 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, replacing `jsonTypes`. + `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. diff --git a/distributors-json/README.md b/distributors-json/README.md index 1e9cff1e..33e26162 100644 --- a/distributors-json/README.md +++ b/distributors-json/README.md @@ -13,7 +13,7 @@ data Person = Person {name :: Text, age :: Int, email :: Maybe Text} ```haskell >>> jsonDecode @Person "{\"name\":\"Ada\",\"age\":36}" Right (Person {name = "Ada", age = 36, email = Nothing}) ->>> mapM_ putStr (tsPrint (jsonTsDeclarations (type '[Person]))) +>>> jsonTsPut (type '[Person]) stdout export type Int = number; export type Person = { name: string; age: Int; email?: null | string }; ``` diff --git a/distributors-json/src/Control/Lens/Grammar/Json.hs b/distributors-json/src/Control/Lens/Grammar/Json.hs index 4f98a609..8926e94f 100644 --- a/distributors-json/src/Control/Lens/Grammar/Json.hs +++ b/distributors-json/src/Control/Lens/Grammar/Json.hs @@ -88,10 +88,11 @@ instance Json Shape where = Types -`jsonTsDeclarations` declares the TypeScript types of types' JSON, -which "Control.Lens.Grammar.TypeScript" prints, & `jsonType` types it. +`jsonTsPut` puts the TypeScript declarations of types' JSON, +which `jsonTsDeclarations` declares, by "Control.Lens.Grammar.TypeScript", +& `jsonType` types. ->>> mapM_ putStr (tsPrint (jsonTsDeclarations (type '[Person, Point, Shape]))) +>>> 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 }; @@ -121,6 +122,7 @@ module Control.Lens.Grammar.Json , JsonProperty (..) , jsonType , jsonTsDeclarations + , jsonTsPut -- * Errors , JsonError (..) , JsonErrorSort (..) @@ -240,6 +242,7 @@ 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 @@ -253,6 +256,7 @@ import Witherable qualified -- >>> 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 @@ -1651,6 +1655,17 @@ jsonTsDeclarations as = tsDeclarations $ hcollapse 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 tsPrint (jsonTsDeclarations as) of + Just declarations -> hPutStr handle declarations + Nothing -> ioError (userError "jsonTsPut: unprintable declarations") + {- | `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. From a7a40ecb6624e2fb60b9bf85571c0af2f67990fd Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Fri, 6 Nov 2026 01:34:07 -0800 Subject: [PATCH 018/130] Remove tsPrint & tsParse, interpreting the grammars where they're used jsonTsPut prints by Parsector, reporting the offset & expectation where it can't print, & the tests round-trip by Parsector & Parsor. Co-Authored-By: Claude Opus 5.5 --- distributors-json/bench/Main.hs | 10 ++++- .../src/Control/Lens/Grammar/Json.hs | 30 +++++++-------- .../src/Control/Lens/Grammar/TypeScript.hs | 38 +++++-------------- distributors-json/test/Properties/Json.hs | 21 +++++++--- 4 files changed, 49 insertions(+), 50 deletions(-) diff --git a/distributors-json/bench/Main.hs b/distributors-json/bench/Main.hs index 30ab1b85..49ededfd 100644 --- a/distributors-json/bench/Main.hs +++ b/distributors-json/bench/Main.hs @@ -11,7 +11,8 @@ import Control.DeepSeq (NFData) import Control.Lens.Grammar.Json import Data.Kind (Type) import Data.SOP (All) -import Control.Lens.Grammar.TypeScript (tsPrint) +import Control.Lens.Grammar (ParsecState (..), manyP, unparsecG) +import Control.Lens.Grammar.TypeScript import Data.Aeson ( FromJSON (..), ToJSON (..), Value (..), decode, defaultOptions, encode , genericToEncoding, object, (.=) @@ -294,4 +295,9 @@ main = defaultMain -- | The TypeScript declarations of types, as text. tsTypes :: forall (as :: [Type]) -> All Json as => Text.Text -tsTypes as = maybe "" Text.pack (tsPrint (jsonTsDeclarations as)) +tsTypes as = Text.pack (tsSource (jsonTsDeclarations as)) + +-- | Print declarations as tokens, & tokens as characters, by Parsector. +tsSource :: [TsDeclaration] -> String +tsSource declarations = parsecStream $ unparsecG (manyP tsTokenGrammar) + (parsecStream (unparsecG tsGrammar declarations [])) "" diff --git a/distributors-json/src/Control/Lens/Grammar/Json.hs b/distributors-json/src/Control/Lens/Grammar/Json.hs index 8926e94f..b773d2ed 100644 --- a/distributors-json/src/Control/Lens/Grammar/Json.hs +++ b/distributors-json/src/Control/Lens/Grammar/Json.hs @@ -1634,19 +1634,11 @@ jsonType a = Bnf start (Set.fromList (Map.toList rules)) (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. +of their types, named by its unqualified name, or else its qualified name, +which `jsonTsPut` puts. ->>> :set -XDeriveAnyClass -XDerivingStrategies ->>> import GHC.Generics (Generic) ->>> :{ -data Shape = Circle Double | Square {side :: Double} - deriving stock Generic - deriving anyclass Json -:} - ->>> mapM_ putStr (tsPrint (jsonTsDeclarations [Shape])) -export type Double = number | null | "+inf" | "-inf"; -export type Shape = { tag: "Circle"; contents: Double } | { tag: "Square"; side: Double }; +>>> jsonTsDeclarations (type '[Maybe Ordering]) +[TypeAliasDeclaration True "Ordering" (UnionType [LiteralType (TextLiteral "LT"),LiteralType (TextLiteral "EQ"),LiteralType (TextLiteral "GT")])] -} jsonTsDeclarations :: forall (as :: [Type]) -> All Json as => [TsDeclaration] jsonTsDeclarations as = tsDeclarations $ hcollapse @@ -1662,9 +1654,17 @@ like a @.ts@ file. export type Ordering = "LT" | "EQ" | "GT"; -} jsonTsPut :: forall (as :: [Type]) -> All Json as => Handle -> IO () -jsonTsPut as handle = case tsPrint (jsonTsDeclarations as) of - Just declarations -> hPutStr handle declarations - Nothing -> ioError (userError "jsonTsPut: unprintable declarations") +jsonTsPut as handle = case (parsecResult printed, parsecResult source) of + (Nothing, _) -> unprinted "tokens" printed + (_, Nothing) -> unprinted "characters" source + _ -> hPutStr handle (parsecStream source) + where + printed = unparsecG tsGrammar (jsonTsDeclarations as) [] + source = unparsecG (manyP tsTokenGrammar) (parsecStream printed) "" + unprinted layer stage = ioError $ userError $ + "jsonTsPut: cannot print " <> layer <> " at " + <> show (parsecOffset stage) <> ", expecting " + <> show (parsecExpect (parsecFailure stage)) {- | `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 diff --git a/distributors-json/src/Control/Lens/Grammar/TypeScript.hs b/distributors-json/src/Control/Lens/Grammar/TypeScript.hs index 21ac8f84..991d8a3b 100644 --- a/distributors-json/src/Control/Lens/Grammar/TypeScript.hs +++ b/distributors-json/src/Control/Lens/Grammar/TypeScript.hs @@ -14,13 +14,19 @@ in two layers: a `tsTokenGrammar` of its tokens, by their `TsTokenCategory`s, & a `tsGrammar` of its syntax, of those tokens, by the compiler's names of its nodes, so that they parse & print together. +Each layer interprets as any grammar does: here, the declarations print +as tokens, by `unparsecG`, which print as characters, & parse back, +by `parsecG` & `parseG`, since `tsTokenGrammar` is @LL(1)@ +but `tsGrammar` isn't. + >>> :set -XOverloadedStrings >>> let point = TypeLiteral [PropertySignature (PropertyIdentifier "x") False (KeywordType NumberKeyword)] ->>> mapM_ putStr (tsPrint [TypeAliasDeclaration True "Point" point]) +>>> let printed = unparsecG tsGrammar [TypeAliasDeclaration True "Point" point] ([] :: [TsToken]) +>>> let source = parsecStream (unparsecG (manyP tsTokenGrammar) (parsecStream printed) ("" :: String)) +>>> putStr source export type Point = { x: number }; - ->>> tsParse "type Pair = [string, number?];" -Just [TypeAliasDeclaration False "Pair" (TupleType [KeywordType StringKeyword,OptionalType (KeywordType NumberKeyword)])] +>>> [parsed | Just scanned <- [parsecResult (parsecG (manyP tsTokenGrammar) source)], (parsed, []) <- parseG tsGrammar scanned] +[[TypeAliasDeclaration True "Point" (TypeLiteral [PropertySignature (PropertyIdentifier "x") False (KeywordType NumberKeyword)])]] -} module Control.Lens.Grammar.TypeScript @@ -35,9 +41,6 @@ module Control.Lens.Grammar.TypeScript , TsToken (..) , TsTokenCategory (..) , tsTokenGrammar - -- * Text - , tsPrint - , tsParse ) where import Control.Lens @@ -482,24 +485,3 @@ _NoSubstitution :: Prism' TypeNode Text _NoSubstitution = prism' (`TemplateLiteralType` []) $ \case TemplateLiteralType text [] -> Just text _ -> Nothing - --- Text -- - -{- | Print type declarations, by `tsGrammar` & `tsTokenGrammar`, -or `Nothing` for syntax that they don't print, like an unparenthesized -union type within an array type. --} -tsPrint :: [TsDeclaration] -> Maybe String -tsPrint declarations = do - printed <- ($ []) <$> printG tsGrammar declarations - ($ "") <$> printG (manyP tsTokenGrammar) printed - --- | Parse type declarations, by `tsTokenGrammar` & `tsGrammar`. -tsParse :: String -> Maybe [TsDeclaration] -tsParse source = do - let scanned = parsecG (manyP tsTokenGrammar) source - scannedTokens <- parsecResult scanned - if null (parsecStream scanned) - then listToMaybe - [parsed | (parsed, []) <- parseG tsGrammar scannedTokens] - else Nothing diff --git a/distributors-json/test/Properties/Json.hs b/distributors-json/test/Properties/Json.hs index f517238a..fa4ab97b 100644 --- a/distributors-json/test/Properties/Json.hs +++ b/distributors-json/test/Properties/Json.hs @@ -20,13 +20,14 @@ module Properties.Json import Control.Lens (coerced, only, prism') import Control.Lens.Grammar - ( dimap, lmap, manyP, optionP, optionalP, rule, someP + ( ParsecState (..), dimap, lmap, manyP, optionP, optionalP, parseG + , parsecG, rule, someP, unparsecG , (>*<), (>+<), (>?), (>|<), (>~) ) import Control.Lens.Grammar.Json import Data.Kind (Type) import Data.SOP (All) -import Control.Lens.Grammar.TypeScript (tsParse, tsPrint) +import Control.Lens.Grammar.TypeScript import Data.Aeson ( FromJSON (..), Options (..), SumEncoding (..), ToJSON (..), Value (String) , camelTo2, decode, defaultOptions, genericToJSON @@ -519,9 +520,14 @@ 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 - (tsPrint parsed >>= tsParse) `shouldBe` Just parsed + take 1 + [ reparsed + | Just scanned <- [parsecResult (parsecG (manyP tsTokenGrammar) source)] + , (reparsed, []) <- parseG tsGrammar scanned + ] `shouldBe` [declared] where - parsed = jsonTsDeclarations [a] + declared = jsonTsDeclarations [a] + source = tsSource declared jsonTypeSpec :: Spec jsonTypeSpec = describe "jsonTsDeclarations" $ do @@ -1172,4 +1178,9 @@ jsonOptionsSpec = describe "jsonGeneric" $ do -- | The TypeScript declarations of types, as text. tsTypes :: forall (as :: [Type]) -> All Json as => Text.Text -tsTypes as = maybe "" Text.pack (tsPrint (jsonTsDeclarations as)) +tsTypes as = Text.pack (tsSource (jsonTsDeclarations as)) + +-- | Print declarations as tokens, & tokens as characters, by Parsector. +tsSource :: [TsDeclaration] -> String +tsSource declarations = parsecStream $ unparsecG (manyP tsTokenGrammar) + (parsecStream (unparsecG tsGrammar declarations [])) "" From 58a01046644cec698646c352e379e4d0552b28f4 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Fri, 6 Nov 2026 01:49:33 -0800 Subject: [PATCH 019/130] withOperators: Operator patterns are prisms A prism's constructor is total, so withOperators builds every operator it parses: no error for an infix pattern which doesn't build, & no prefix or postfix operator silently dropped. Co-Authored-By: Claude Opus 5.5 --- distributors-core/CHANGELOG.md | 8 +++++++ .../src/Data/Profunctor/Separator.hs | 24 ++++++++++--------- 2 files changed, 21 insertions(+), 11 deletions(-) diff --git a/distributors-core/CHANGELOG.md b/distributors-core/CHANGELOG.md index 83402d2c..a044c468 100644 --- a/distributors-core/CHANGELOG.md +++ b/distributors-core/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog for `distributors` +## Unreleased + +### Breaking Changes + +- `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. + ## 0.6.0.0 - 2026-04-24 ### New Module diff --git a/distributors-core/src/Data/Profunctor/Separator.hs b/distributors-core/src/Data/Profunctor/Separator.hs index daff3087..1621a3e6 100644 --- a/distributors-core/src/Data/Profunctor/Separator.hs +++ b/distributors-core/src/Data/Profunctor/Separator.hs @@ -31,7 +31,6 @@ module Data.Profunctor.Separator import Control.Lens import Control.Lens.PartialIso import Control.Lens.Grammar.Symbol -import Data.Maybe (fromMaybe) import Data.Monoid.Disjunctive (orP) import Data.Profunctor.Distributor import Data.Profunctor.Monoidal.Cocartesian @@ -139,15 +138,15 @@ intercalateP n (SepBy beg end comma) p = data Operator p a b where Infix :: Assoc -- ^ `NonAssoc`, `LeftAssoc`, `RightAssoc` - -> APartialIso a b (a,a) (b,b) -- ^ binary constructor pattern + -> APrism a b (a,a) (b,b) -- ^ binary constructor pattern -> p () () -- ^ operator symbol -> Operator p a b Prefix - :: APartialIso a b a b -- ^ unary endopattern + :: APrism a b a b -- ^ unary constructor pattern -> p () () -- ^ operator symbol -> Operator p a b Postfix - :: APartialIso a b a b -- ^ unary endopattern + :: APrism a b a b -- ^ unary constructor pattern -> p () () -- ^ operator symbol -> Operator p a b @@ -249,21 +248,21 @@ withOperators table p = foldl makeLevel p table withPreP ops inner = difoldr (partialIso fwd bwd) >? manyP (tagSepP (snd <$> ops)) >*< inner where - fns = [withPartialIso pat (,) | (pat, _) <- ops] + fns = [patternFns pat | (pat, _) <- ops] fwd x = orP [ (\y -> (i,y)) <$> f x | (i, (f,_)) <- zip [0 :: Int ..] fns ] bwd (i,y) = case drop i fns of - (_,g):_ -> g y + (_,g):_ -> Just (g y) [] -> Nothing withPostP ops inner = difoldl (partialIso fwd bwd) >? inner >*< manyP (tagSepP (snd <$> ops)) where - fns = [withPartialIso pat (,) | (pat, _) <- ops] + fns = [patternFns pat | (pat, _) <- ops] fwd x = orP [ (\y -> (y,i)) <$> f x | (i, (f,_)) <- zip [0 :: Int ..] fns ] bwd (y,i) = case drop i fns of - (_,g):_ -> g y + (_,g):_ -> Just (g y) [] -> Nothing {- | Parse one operand, then zero or more @(operator, operand)@ steps, @@ -288,11 +287,10 @@ withOperators table p = foldl makeLevel p table 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 (,)] + fns = [(assoc,f,g) | (assoc,pat,_) <- infixes, let (f,g) = patternFns 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)) + 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 @@ -315,3 +313,7 @@ withOperators table p = foldl makeLevel p table 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) From 90cc95f2c7c43fe92e6ffe2b70912a2f4ec756cc Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Fri, 6 Nov 2026 01:56:10 -0800 Subject: [PATCH 020/130] Parse TypeScript by Parsector, scanning without trivia tsTokensGrammar scans tokens without their trivia, as tsc's scanner skips them, & prints them with their trivia, so that tsGrammar, left-factored & guarding its printing alternatives by prisms, is LL(1): parsecG parses & unparsecG prints both layers, locating failures. Co-Authored-By: Claude Opus 5.5 --- distributors-json/CHANGELOG.md | 2 + distributors-json/bench/Main.hs | 4 +- .../src/Control/Lens/Grammar/Json.hs | 2 +- .../src/Control/Lens/Grammar/TypeScript.hs | 182 +++++++++++++----- distributors-json/test/Properties/Json.hs | 12 +- 5 files changed, 141 insertions(+), 61 deletions(-) diff --git a/distributors-json/CHANGELOG.md b/distributors-json/CHANGELOG.md index 98c44068..262dae38 100644 --- a/distributors-json/CHANGELOG.md +++ b/distributors-json/CHANGELOG.md @@ -9,6 +9,8 @@ - `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. diff --git a/distributors-json/bench/Main.hs b/distributors-json/bench/Main.hs index 49ededfd..a6939149 100644 --- a/distributors-json/bench/Main.hs +++ b/distributors-json/bench/Main.hs @@ -11,7 +11,7 @@ import Control.DeepSeq (NFData) import Control.Lens.Grammar.Json import Data.Kind (Type) import Data.SOP (All) -import Control.Lens.Grammar (ParsecState (..), manyP, unparsecG) +import Control.Lens.Grammar (ParsecState (..), unparsecG) import Control.Lens.Grammar.TypeScript import Data.Aeson ( FromJSON (..), ToJSON (..), Value (..), decode, defaultOptions, encode @@ -299,5 +299,5 @@ tsTypes as = Text.pack (tsSource (jsonTsDeclarations as)) -- | Print declarations as tokens, & tokens as characters, by Parsector. tsSource :: [TsDeclaration] -> String -tsSource declarations = parsecStream $ unparsecG (manyP tsTokenGrammar) +tsSource declarations = parsecStream $ unparsecG tsTokensGrammar (parsecStream (unparsecG tsGrammar declarations [])) "" diff --git a/distributors-json/src/Control/Lens/Grammar/Json.hs b/distributors-json/src/Control/Lens/Grammar/Json.hs index b773d2ed..b5598153 100644 --- a/distributors-json/src/Control/Lens/Grammar/Json.hs +++ b/distributors-json/src/Control/Lens/Grammar/Json.hs @@ -1660,7 +1660,7 @@ jsonTsPut as handle = case (parsecResult printed, parsecResult source) of _ -> hPutStr handle (parsecStream source) where printed = unparsecG tsGrammar (jsonTsDeclarations as) [] - source = unparsecG (manyP tsTokenGrammar) (parsecStream printed) "" + source = unparsecG tsTokensGrammar (parsecStream printed) "" unprinted layer stage = ioError $ userError $ "jsonTsPut: cannot print " <> layer <> " at " <> show (parsecOffset stage) <> ", expecting " diff --git a/distributors-json/src/Control/Lens/Grammar/TypeScript.hs b/distributors-json/src/Control/Lens/Grammar/TypeScript.hs index 991d8a3b..f24696f7 100644 --- a/distributors-json/src/Control/Lens/Grammar/TypeScript.hs +++ b/distributors-json/src/Control/Lens/Grammar/TypeScript.hs @@ -14,19 +14,22 @@ in two layers: a `tsTokenGrammar` of its tokens, by their `TsTokenCategory`s, & a `tsGrammar` of its syntax, of those tokens, by the compiler's names of its nodes, so that they parse & print together. -Each layer interprets as any grammar does: here, the declarations print -as tokens, by `unparsecG`, which print as characters, & parse back, -by `parsecG` & `parseG`, since `tsTokenGrammar` is @LL(1)@ -but `tsGrammar` isn't. +Both layers are @LL(1)@, since `tsTokensGrammar` scans tokens without +their trivia, so that `parsecG` parses & `unparsecG` prints each layer, +locating failures. Here, a declaration prints as tokens, & as characters, +& parses back. >>> :set -XOverloadedStrings >>> let point = TypeLiteral [PropertySignature (PropertyIdentifier "x") False (KeywordType NumberKeyword)] >>> let printed = unparsecG tsGrammar [TypeAliasDeclaration True "Point" point] ([] :: [TsToken]) ->>> let source = parsecStream (unparsecG (manyP tsTokenGrammar) (parsecStream printed) ("" :: String)) +>>> let source = parsecStream (unparsecG tsTokensGrammar (parsecStream printed) ("" :: String)) >>> putStr source export type Point = { x: number }; ->>> [parsed | Just scanned <- [parsecResult (parsecG (manyP tsTokenGrammar) source)], (parsed, []) <- parseG tsGrammar scanned] -[[TypeAliasDeclaration True "Point" (TypeLiteral [PropertySignature (PropertyIdentifier "x") False (KeywordType NumberKeyword)])]] +>>> parsecResult (parsecG tsGrammar (concat (parsecResult (parsecG tsTokensGrammar source)))) +Just [TypeAliasDeclaration True "Point" (TypeLiteral [PropertySignature (PropertyIdentifier "x") False (KeywordType NumberKeyword)])] +>>> let scanned = concat (parsecResult (parsecG tsTokensGrammar "type A = { a: number; b: };")) +>>> parsecOffset (parsecG tsGrammar scanned) +10 -} module Control.Lens.Grammar.TypeScript @@ -41,6 +44,7 @@ module Control.Lens.Grammar.TypeScript , TsToken (..) , TsTokenCategory (..) , tsTokenGrammar + , tsTokensGrammar ) where import Control.Lens @@ -202,7 +206,8 @@ symbol kind = TsToken kind (fromMaybe "" (kindText kind)) {- | A token, scanned from its characters. Its trivia are tokens, as the scanner of the TypeScript compiler scans without skipping them, -so that @`manyP` tsTokenGrammar@ scans a file. +so that @`manyP` tsTokenGrammar@ scans a file, or `tsTokensGrammar` +scans it without its trivia. Unlike the compiler's scanner, which rescans a @}@ as a template's middle or tail, by the context of its parser, `tsTokenGrammar` is regular, @@ -258,6 +263,17 @@ tsTokenGrammar = orP , 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 @LL(1)@. +-} +tsTokensGrammar :: RegGrammar Char [TsToken] +tsTokensGrammar = rmap + (\scanned -> [t | t <- scanned, tokenCategory t `notElem` trivial]) + (manyP tsTokenGrammar) + where + trivial = [WhitespaceTrivia, NewLineTrivia] + -- | A token of a kind, by its text. kindOf :: TsTokenCategory -> Prism' TsToken String kindOf kind = prism' @@ -308,9 +324,9 @@ _HexCode = prism' {- | Type declarations, of tokens, by the TypeScript compiler's syntax. -Trivia, whitespace & newlines, are parsed between tokens, & printed -conventionally. Each run of trivia is the trivia of exactly one token, -either before or after it, so that it parses only one way. +Trivia, whitespace & newlines, are printed conventionally, between tokens, +& parsed only by `parseG`, from tokens with trivia, since `parsecG` +parses tokens without them, which `tsTokensGrammar` scans. -} tsGrammar :: Grammar TsToken [TsDeclaration] tsGrammar = rule "declarations" $ @@ -362,56 +378,66 @@ tsGrammar = rule "declarations" $ , _TextLiteral >? textOf StringLiteral ] , _NoSubstitution >? textOf NoSubstitutionTemplateLiteral - , _TemplateLiteralType >? textOf TemplateHead *< trivia [] >*< - (_Snoc >? manyP (templateSpan TemplateMiddle (trivia [])) - >*< templateSpan TemplateTail oneP) + , _TemplateLiteralType >? textOf TemplateHead *< tight + >*< templateSpans ty , _TypeReference >? identifier >*< orP - [ only [] >? oneP - , tokenOf tight LessThanToken tight - >* several1 (sepBy comma) ty - *< tokenOf tight GreaterThanToken oneP + [ several1 (sepBy comma) + { beginBy = tokenOf tight LessThanToken tight + , endBy = tokenOf tight GreaterThanToken oneP + } ty + , only [] >? oneP ] - , _TupleType >? orP - [ only [] >? tokenOf oneP OpenBracketToken oneP - >* tokenOf tight CloseBracketToken oneP - , tokenOf oneP OpenBracketToken tight - >* several1 (sepBy comma) (tupleElement ty) + , _TupleType >? tokenOf oneP OpenBracketToken oneP >* orP + [ only [] >? tokenOf tight CloseBracketToken oneP + , tight >* several1 (sepBy comma) (tupleElement ty) *< tokenOf tight CloseBracketToken oneP ] , _ParenthesizedType >? tokenOf oneP OpenParenToken tight >* ty *< tokenOf tight CloseParenToken oneP - , _TypeLiteral >? orP - [ only [] >? tokenOf oneP OpenBraceToken oneP - >* tokenOf tight CloseBraceToken oneP - , tokenOf oneP OpenBraceToken space - >* several1 (sepBy semicolon) (member ty) - *< optionalSemicolon - *< tokenOf space CloseBraceToken oneP + , _Braced >? tokenOf oneP OpenBraceToken oneP >* orP + [ only (TypeLiteral []) >? tokenOf tight CloseBraceToken oneP + , _Bracketed >? tokenOf space OpenBracketToken tight >* identifier + >*< (mappedRest ty >+< indexRest ty) + , _PropertyFirst >? space >* property ty >*< members ty ] - , _MappedType >? tokenOf oneP OpenBraceToken space - >* tokenOf oneP OpenBracketToken tight >* identifier - >*< tokenOf space InKeyword space >* ty - >*< optionalP (tokenOf space AsKeyword space >* ty) - >*< tokenOf tight CloseBracketToken oneP >* question - >*< tokenOf tight ColonToken space >* ty - *< tokenOf space CloseBraceToken oneP ] - where - templateSpan kind after = - ty >*< trivia [] >* textOf kind *< after + -- The rest of a mapped type, after its type parameter's name. + mappedRest ty = tokenOf space InKeyword space >* ty + >*< optionalP (tokenOf space AsKeyword space >* ty) + >*< tokenOf tight CloseBracketToken oneP >* question + >*< tokenOf tight ColonToken space >* ty + *< tokenOf space CloseBraceToken oneP + -- The rest of a type literal, after its first index signature's name. + indexRest ty = tokenOf tight ColonToken space >* ty + >*< tokenOf tight CloseBracketToken oneP + >* tokenOf tight ColonToken space >* ty + >*< members ty + -- The members after a type literal's first, & its closing brace. + members ty = ruleRec "members" $ \rest -> orP + [ only [] >? tokenOf space CloseBraceToken oneP + , tokenOf tight SemicolonToken space >* orP + [ only [] >? tokenOf tight CloseBraceToken oneP + , member ty >:< rest + ] + ] + -- A template's spans, each a type & its middle's or tail's literal. + templateSpans ty = ruleRec "spans" $ \rest -> _Spans >? ty + >*< (tight >* textOf TemplateMiddle *< tight >*< rest + >+< tight >* textOf TemplateTail) tupleElement ty = rule "element" $ orP [ _RestType >? tokenOf oneP DotDotDotToken tight >* ty - , _OptionalType >? ty *< tokenOf tight QuestionToken oneP - , ty + , _Optional >~ ty >*< question ] member ty = rule "member" $ orP - [ _PropertySignature >? propertyName >*< question - >*< tokenOf tight ColonToken space >* ty + [ _PropertySignature >? property ty , _IndexSignature >? tokenOf oneP OpenBracketToken tight >* identifier - >*< tokenOf tight ColonToken space >* ty - >*< tokenOf tight CloseBracketToken oneP - >* tokenOf tight ColonToken space >* ty + >*< indexSignature ty ] + property ty = propertyName >*< question + >*< tokenOf tight ColonToken space >* ty + indexSignature ty = tokenOf tight ColonToken space >* ty + >*< tokenOf tight CloseBracketToken oneP + >* tokenOf tight ColonToken space >* ty propertyName = orP [ _PropertyIdentifier >? identifier , _PropertyIdentifier >? orP @@ -423,9 +449,6 @@ tsGrammar = rule "declarations" $ , only False >? oneP ] comma = tokenOf tight CommaToken space - semicolon = tokenOf tight SemicolonToken space - optionalSemicolon = dimap (const Nothing) (const ()) - (optionalP (tokenOf tight SemicolonToken oneP)) identifier = textOf Identifier space = trivia [TsToken WhitespaceTrivia " "] newline = trivia [TsToken NewLineTrivia "\n"] @@ -459,6 +482,65 @@ _Several nodes = iso (node, []) -> node (first, others) -> review nodes (first : others)) +-- | A type literal or a mapped type, which are braced. +_Braced :: Prism' TypeNode TypeNode +_Braced = prism' id $ \case + node@(TypeLiteral _) -> Just node + node@(MappedType {}) -> Just node + _ -> Nothing + +-- | A tuple's element, or else an optional element's type. +_Optional :: Iso' TypeNode (TypeNode, Bool) +_Optional = iso + (\case OptionalType node -> (node, True); node -> (node, False)) + (\case (node, True) -> OptionalType node; (node, False) -> node) + +{- | A mapped type, or a type literal whose first member is an index +signature, by its type parameter's or index's name, & the rest of it. +-} +_Bracketed :: Prism' TypeNode + ( Text + , Either + (TypeNode, (Maybe TypeNode, (Bool, TypeNode))) + (TypeNode, (TypeNode, [TypeElement])) + ) +_Bracketed = prism' bracketed $ \case + MappedType name constraint nameType optional node -> + Just (name, Left (constraint, (nameType, (optional, node)))) + TypeLiteral (IndexSignature name key node : others) -> + Just (name, Right (key, (node, others))) + _ -> Nothing + where + bracketed = \case + (name, Left (constraint, (nameType, (optional, node)))) -> + MappedType name constraint nameType optional node + (name, Right (key, (node, others))) -> + TypeLiteral (IndexSignature name key node : others) + +-- | A type literal whose first member is a property signature. +_PropertyFirst + :: Prism' TypeNode ((PropertyName, (Bool, TypeNode)), [TypeElement]) +_PropertyFirst = prism' + (\((name, (optional, node)), others) -> + TypeLiteral (PropertySignature name optional node : others)) + (\case + TypeLiteral (PropertySignature name optional node : others) -> + Just ((name, (optional, node)), others) + _ -> Nothing) + +-- | A template's spans, by the first's type & its middle or tail. +_Spans + :: Prism' [(TypeNode, Text)] + (TypeNode, Either (Text, [(TypeNode, 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 type of any arrays of its element type. _Arrays :: Iso' TypeNode (TypeNode, [()]) _Arrays = iso arrays (uncurry (foldr (const ArrayType))) diff --git a/distributors-json/test/Properties/Json.hs b/distributors-json/test/Properties/Json.hs index fa4ab97b..64d7c6de 100644 --- a/distributors-json/test/Properties/Json.hs +++ b/distributors-json/test/Properties/Json.hs @@ -20,7 +20,7 @@ module Properties.Json import Control.Lens (coerced, only, prism') import Control.Lens.Grammar - ( ParsecState (..), dimap, lmap, manyP, optionP, optionalP, parseG + ( ParsecState (..), dimap, lmap, manyP, optionP, optionalP , parsecG, rule, someP, unparsecG , (>*<), (>+<), (>?), (>|<), (>~) ) @@ -520,14 +520,10 @@ which parse as the declarations which print them. declares :: forall a -> Json a => [Text] -> Expectation declares a declarations = do tsTypes [a] `shouldBe` Text.unlines declarations - take 1 - [ reparsed - | Just scanned <- [parsecResult (parsecG (manyP tsTokenGrammar) source)] - , (reparsed, []) <- parseG tsGrammar scanned - ] `shouldBe` [declared] + parsecResult (parsecG tsGrammar scanned) `shouldBe` Just declared where declared = jsonTsDeclarations [a] - source = tsSource declared + scanned = concat (parsecResult (parsecG tsTokensGrammar (tsSource declared))) jsonTypeSpec :: Spec jsonTypeSpec = describe "jsonTsDeclarations" $ do @@ -1182,5 +1178,5 @@ tsTypes as = Text.pack (tsSource (jsonTsDeclarations as)) -- | Print declarations as tokens, & tokens as characters, by Parsector. tsSource :: [TsDeclaration] -> String -tsSource declarations = parsecStream $ unparsecG (manyP tsTokenGrammar) +tsSource declarations = parsecStream $ unparsecG tsTokensGrammar (parsecStream (unparsecG tsGrammar declarations [])) "" From fe5975392d60900bf817cd8c4bc3f4c877c72364 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Thu, 5 Nov 2026 12:19:26 -0800 Subject: [PATCH 021/130] Parsector: direct sequencing, choice & profunctor methods Its type is unchanged. tokenClass interprets its class & makes its failures once, rather than for each token; liftA2 sequences without a continuation; left' & right' choose without alternate; dimap, lmap & rmap map states directly; #. & .# coerce. Parsing Textual grammars is ~30-40% faster. Co-Authored-By: Claude Opus 5.5 --- .../src/Data/Profunctor/Grammar/Parsector.hs | 94 ++++++++++++++----- 1 file changed, 68 insertions(+), 26 deletions(-) diff --git a/distributors-core/src/Data/Profunctor/Grammar/Parsector.hs b/distributors-core/src/Data/Profunctor/Grammar/Parsector.hs index 7ee968df..a87be0a4 100644 --- a/distributors-core/src/Data/Profunctor/Grammar/Parsector.hs +++ b/distributors-core/src/Data/Profunctor/Grammar/Parsector.hs @@ -35,6 +35,7 @@ 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 @@ -187,33 +188,39 @@ 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 -> + -- 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. @@ -236,7 +243,15 @@ instance Functor (Parsector s a) where 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 @@ -245,21 +260,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 -> @@ -318,8 +344,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 -> @@ -335,9 +366,20 @@ 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 + 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) instance Categorized (Item s) => DisjunctiveMonoid (Parsector s a b) From 9e4539c99183de3ad79c30c8f33968b453c87884 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Thu, 5 Nov 2026 12:32:02 -0800 Subject: [PATCH 022/130] Parsector: terminal & manyP in loops terminal checks its tokens in one loop, and manyP runs its elements in one loop, both parsing & printing, rather than through isos, sums & sequencing for each token & element, with the same failures & hints as before. Parsing Textual grammars is now 1.1-3.8x read. Co-Authored-By: Claude Opus 5.5 --- .../src/Data/Profunctor/Grammar/Parsector.hs | 87 ++++++++++++++++++- 1 file changed, 85 insertions(+), 2 deletions(-) diff --git a/distributors-core/src/Data/Profunctor/Grammar/Parsector.hs b/distributors-core/src/Data/Profunctor/Grammar/Parsector.hs index a87be0a4..9f666e58 100644 --- a/distributors-core/src/Data/Profunctor/Grammar/Parsector.hs +++ b/distributors-core/src/Data/Profunctor/Grammar/Parsector.hs @@ -237,7 +237,40 @@ 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 + {- | 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 @@ -381,7 +414,57 @@ instance Categorized (Item s) => Choice (Parsector s) where 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) +instance Categorized (Item s) => Distributor (Parsector s) where + {- | Like @eotList >~ 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 $ From 56ba987380b6030bcee726493e629829ac0387a5 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Thu, 5 Nov 2026 12:39:29 -0800 Subject: [PATCH 023/130] Parsector: specialise stream instances to String TokenAlgebra & TerminalSymbol instances call uncons & snoc for each token through dictionaries; specialising them to String streams makes parsing Textual grammars ~5-15% faster. Specialising the other instances, inlining & -O2 made no measurable difference, since grammars are built by dictionary passing & run as already compiled closures. Co-Authored-By: Claude Opus 5.5 --- distributors-core/src/Data/Profunctor/Grammar/Parsector.hs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/distributors-core/src/Data/Profunctor/Grammar/Parsector.hs b/distributors-core/src/Data/Profunctor/Grammar/Parsector.hs index 9f666e58..96aa32b3 100644 --- a/distributors-core/src/Data/Profunctor/Grammar/Parsector.hs +++ b/distributors-core/src/Data/Profunctor/Grammar/Parsector.hs @@ -188,6 +188,7 @@ instance ( Categorized token, Item s ~ token , Cons s s token token, Snoc s s token token ) => TokenAlgebra token (Parsector s token token) where + {-# SPECIALISE instance TokenAlgebra Char (Parsector String Char Char) #-} -- The test & failures are made once, rather than for each token. tokenClass test = matches `seq` Parsector (\callback query -> let @@ -238,6 +239,7 @@ instance ( Categorized token, Item s ~ token , Cons s s token token, Snoc s s token token ) => TerminalSymbol token (Parsector s () ()) where + {-# SPECIALISE instance TerminalSymbol Char (Parsector String () ()) #-} {- | Like @only str ?< tokens str@, checking its tokens in one loop, failing without consuming at the first token, and committed after. -} From 8a868d13dec9268ff8dff576e518603e2994256b Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Thu, 5 Nov 2026 12:56:39 -0800 Subject: [PATCH 024/130] Printor: direct tokens, literals, repetition & maps; specialise tokenClass, token, oneOf & the rest test their tokens directly, rather than through satisfy; terminal prints its tokens together; manyP & optionalP traverse their elements; dimap, lmap & rmap map directly. Instances which print tokens are specialised to String & Maybe, and TerminalSymbol & IsString need only an Applicative. Printing Textual grammars is 2-4x faster. Co-Authored-By: Claude Opus 5.5 --- .../src/Data/Profunctor/Grammar.hs | 48 ++++++++++++++----- 1 file changed, 37 insertions(+), 11 deletions(-) diff --git a/distributors-core/src/Data/Profunctor/Grammar.hs b/distributors-core/src/Data/Profunctor/Grammar.hs index 6000b7ca..179a92a6 100644 --- a/distributors-core/src/Data/Profunctor/Grammar.hs +++ b/distributors-core/src/Data/Profunctor/Grammar.hs @@ -197,7 +197,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 -> @@ -219,7 +221,16 @@ 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 Applicative f => Distributor (Printor s f) +{- | `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 @@ -276,19 +287,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 From 4ca474e09cb3853edfeb8c5cac177111c3987d55 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Fri, 6 Nov 2026 05:48:24 -0800 Subject: [PATCH 025/130] HLint: Printor's strict pair matches are deliberate Co-Authored-By: Claude Opus 5.5 --- .hlint.yaml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.hlint.yaml b/.hlint.yaml index 2388c45e..c30aa497 100644 --- a/.hlint.yaml +++ b/.hlint.yaml @@ -93,3 +93,7 @@ # 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} From 48253ae14b45dfb76d74919070eb121a17808a9d Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Fri, 6 Nov 2026 06:13:21 -0800 Subject: [PATCH 026/130] Print enumerations by index jsonEnumWith, a JsonStr method, takes a table of strings & values, & each value's index in it, so that printers index rendered literals rather than walking a sum. Generic enumerations, whose constructors are all nullary, index by dataToTag#, which a type family over Rep requires only of them, since newtypes have no DataToTag. Encoding enumerations goes from 1.97x aeson to 1.37x, & printing them to Values from 0.84x to 0.41x. Co-Authored-By: Claude Opus 5.5 --- distributors-json/CHANGELOG.md | 2 + .../src/Control/Lens/Grammar/Json.hs | 106 +++++++++++++----- distributors-json/test/Properties/Json.hs | 4 +- 3 files changed, 83 insertions(+), 29 deletions(-) diff --git a/distributors-json/CHANGELOG.md b/distributors-json/CHANGELOG.md index 262dae38..cb5c9f57 100644 --- a/distributors-json/CHANGELOG.md +++ b/distributors-json/CHANGELOG.md @@ -14,3 +14,5 @@ - 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. +- `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/src/Control/Lens/Grammar/Json.hs b/distributors-json/src/Control/Lens/Grammar/Json.hs index b5598153..ea420936 100644 --- a/distributors-json/src/Control/Lens/Grammar/Json.hs +++ b/distributors-json/src/Control/Lens/Grammar/Json.hs @@ -174,6 +174,7 @@ 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) @@ -183,7 +184,7 @@ import Data.Maybe import Data.Monoid (Ap (..)) import Data.Monoid qualified as Monoid import Data.Ord (Down (..)) -import Data.Primitive.Array (Array) +import Data.Primitive.Array (Array, arrayFromList, indexArray) import Data.Primitive.PrimArray (PrimArray) import Data.Primitive.SmallArray (SmallArray) import Data.Primitive.Types (Prim) @@ -518,11 +519,15 @@ class 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"@. + 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 -> Text) -> [a] -> p a a - jsonEnumWith f as = - prism' f (\t -> lookup t [(f a, a) | a <- as]) ?< jsonText + jsonEnumWith :: (a -> Int) -> [(Text, a)] -> p a a + jsonEnumWith indexOf table = + prism' (indexArray names . indexOf) (`lookup` table) ?< jsonText + where + names = arrayFromList (map fst table) {- | Strings of numbers, like an integral map key's, like TypeScript's template literal type, @\`${number}\`@. -} @@ -813,6 +818,11 @@ instance JsonStr JsonParsor where jsonText = jsonParsor $ \case String t -> Right t v -> jsonMismatch "string" v + -- | Literal 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 () @@ -1066,6 +1076,10 @@ instance AesonStr key => JsonStr (KeyPrintor key) where 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 @@ -1287,6 +1301,10 @@ instance AesonStr val => JsonStr (JsonPrintor val) where 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] instance AesonVal val => JsonVal (JsonPrintor val) where jsonNull = primitive (const aesonNull) jsonBool = primitive aesonBool @@ -1733,7 +1751,8 @@ instance (x ~ (), y ~ ()) => IsString (JsonTypor x y) where fromString = typing . JsonStringLiteral . Text.pack instance JsonStr JsonTypor where jsonText = typing JsonString - jsonEnumWith f as = typing (jsonUnion [JsonStringLiteral (f a) | a <- as]) + jsonEnumWith _ table = + typing (jsonUnion [JsonStringLiteral literal | (literal, _) <- table]) jsonNumeric _ = typing JsonNumeric instance JsonVal JsonTypor where jsonNull = typing JsonNull @@ -2056,9 +2075,11 @@ tsTuples shapes = merged (nub (concatMap (expand False . mergeRests) shapes)) -- Json instance helpers --- | An enumeration of string literals, typed as their union. -jsonEnum :: (Eq a, JsonVal p) => (a -> Text) -> [a] -> p a a -jsonEnum f as = orP [only a >? fromString (Text.unpack (f a)) | a <- as] +-- | An enumeration of a bounded `Enum`, by the names of its values. +enumerated :: (Bounded a, Enum a, JsonStr p) => (a -> Text) -> p a a +enumerated name = jsonEnumWith + (\a -> fromEnum a - fromEnum (minBound `asTypeOf` a)) + [(name a, a) | a <- [minBound .. maxBound]] -- | An object of a single property, as @aeson@ requires of sums' tags. jsonTag :: JsonVal p => Text -> p a b -> p a b @@ -2152,10 +2173,9 @@ makePrisms ''These -- base instance Json Bool where json = jsonBool - jsonKey = - Just (jsonEnumWith (\b -> if b then "true" else "false") [False, True]) + jsonKey = Just (enumerated (\b -> if b then "true" else "false")) instance Json Ordering where - json = jsonTyped (jsonEnum (Text.pack . show) [LT, EQ, GT]) + json = jsonTyped (enumerated (Text.pack . show)) instance Json () where json = jsonTuple oneP jsonOmitField _ = True @@ -2654,22 +2674,23 @@ instance Json CalendarDiffDays where (jsonObject ("months" !: json >*< "days" !: json)) -- | Days of the week, named as @aeson@ names them. -weekdays :: ((DayOfWeek -> Text) -> [DayOfWeek] -> r) -> r -weekdays enumerate = enumerate (Text.toLower . Text.pack . show) - [Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday] +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 jsonEnum) - jsonKey = Just (jsonTyped (weekdays jsonEnumWith)) + json = jsonTyped weekdays + jsonKey = Just (jsonTyped weekdays) -- | Quarters of the year, named as @aeson@ names them. -quarters :: ((QuarterOfYear -> Text) -> [QuarterOfYear] -> r) -> r -quarters enumerate = - enumerate (Text.toLower . Text.pack . show) [Q1, Q2, Q3, Q4] +quarters :: JsonStr p => p QuarterOfYear QuarterOfYear +quarters = enumerated (Text.toLower . Text.pack . show) instance Json QuarterOfYear where - json = jsonTyped (quarters jsonEnum) - jsonKey = Just (jsonTyped (quarters jsonEnumWith)) + json = jsonTyped quarters + jsonKey = Just (jsonTyped quarters) -- uuid-types @@ -2742,8 +2763,10 @@ instance (Json a, Json b) => Json (Strict.Pair a b) where -- 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) - => Json (GHC.Generically a) where +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) @@ -2755,10 +2778,32 @@ definition. -} jsonGeneric :: forall a d f p - . (GHC.Generic a, GHC.Rep a ~ GHC.D1 d f, GSum f, Typeable a, JsonVal 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 (dimap (GHC.unM1 . GHC.from) (GHC.to . GHC.M1) (gsum opts)) +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) + +-- | 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 @@ -2784,6 +2829,8 @@ class GSum f where 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`. @@ -2798,6 +2845,9 @@ instance (GSum f, GSum g) => GSum (f GHC.:+: g) where 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 @@ -2822,6 +2872,8 @@ instance (GHC.Constructor c, GFields f, GContents f, GNullary f) | 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 diff --git a/distributors-json/test/Properties/Json.hs b/distributors-json/test/Properties/Json.hs index 64d7c6de..1fdca1a3 100644 --- a/distributors-json/test/Properties/Json.hs +++ b/distributors-json/test/Properties/Json.hs @@ -209,7 +209,7 @@ newtype Tally = Tally (Int, [(Bool, Int)]) instance Json Tally where json = jsonTyped $ dimap (\(Tally p) -> p) Tally $ jsonObject ( "total" !: json - >*< jsonDict (jsonEnumWith (\b -> if b then "yes" else "no") [False, True]) + >*< jsonDict (jsonEnumWith fromEnum [("no", False), ("yes", True)]) json ) @@ -219,7 +219,7 @@ newtype Votes = Votes (Int, [(Bool, Int)]) instance Json Votes where json = jsonTyped $ dimap (\(Votes p) -> p) Votes $ jsonObject ( "yes" !: json - >*< jsonDict (jsonEnumWith (\b -> if b then "yes" else "no") [False, True]) + >*< jsonDict (jsonEnumWith fromEnum [("no", False), ("yes", True)]) json ) From d141e6643a1613adadae77611d13de0219330593 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Fri, 6 Nov 2026 06:27:24 -0800 Subject: [PATCH 027/130] Rename the TypeScript syntax: TsType, TsProperty, TsPropertyName, TsLiteral TypeNode is TsType, TypeElement is TsProperty, PropertyName is TsPropertyName, Literal is TsLiteral, & TypeLiteral is ObjectType. Co-Authored-By: Claude Opus 5.5 --- .../src/Control/Lens/Grammar/Json.hs | 12 +-- .../src/Control/Lens/Grammar/TypeScript.hs | 98 +++++++++---------- 2 files changed, 55 insertions(+), 55 deletions(-) diff --git a/distributors-json/src/Control/Lens/Grammar/Json.hs b/distributors-json/src/Control/Lens/Grammar/Json.hs index ea420936..806f1cf5 100644 --- a/distributors-json/src/Control/Lens/Grammar/Json.hs +++ b/distributors-json/src/Control/Lens/Grammar/Json.hs @@ -818,7 +818,7 @@ instance JsonStr JsonParsor where jsonText = jsonParsor $ \case String t -> Right t v -> jsonMismatch "string" v - -- | Literal alternatives, dispatched by their string. + -- | 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 @@ -1886,7 +1886,7 @@ tsIdentifier name = case Text.uncons ident of {- | 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 -> TypeNode +tsType :: Map String JsonType -> Map String Text -> JsonType -> TsType tsType rules names = typeNode where typeNode = \case @@ -1917,10 +1917,10 @@ tsType rules names = typeNode -- 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 - ([], []) -> TypeLiteral [] + ([], []) -> ObjectType [] ([], [objectPart]) -> objectPart ([], objectParts) -> IntersectionType objectParts - (members, objectParts) -> case TypeLiteral members : objectParts of + (members, objectParts) -> case ObjectType members : objectParts of [objectPart] -> objectPart allObjectParts -> IntersectionType allObjectParts where @@ -1975,7 +1975,7 @@ tsType rules names = typeNode identifierChar c = isAlphaNum c || c == '_' || c == '$' -- | A union of types, flattened, or else its only type, or else @never@. -union :: [TypeNode] -> TypeNode +union :: [TsType] -> TsType union nodes = case nub (concatMap flatten nodes) of [] -> KeywordType NeverKeyword [node] -> node @@ -1990,7 +1990,7 @@ union nodes = case nub (concatMap flatten nodes) of node -> node -- | A type, parenthesized as an operand of an array or element type. -operand :: TypeNode -> TypeNode +operand :: TsType -> TsType operand = \case node@(UnionType _) -> ParenthesizedType node node@(IntersectionType _) -> ParenthesizedType node diff --git a/distributors-json/src/Control/Lens/Grammar/TypeScript.hs b/distributors-json/src/Control/Lens/Grammar/TypeScript.hs index f24696f7..7d6fce09 100644 --- a/distributors-json/src/Control/Lens/Grammar/TypeScript.hs +++ b/distributors-json/src/Control/Lens/Grammar/TypeScript.hs @@ -20,13 +20,13 @@ locating failures. Here, a declaration prints as tokens, & as characters, & parses back. >>> :set -XOverloadedStrings ->>> let point = TypeLiteral [PropertySignature (PropertyIdentifier "x") False (KeywordType NumberKeyword)] +>>> let point = ObjectType [PropertySignature (PropertyIdentifier "x") False (KeywordType NumberKeyword)] >>> let printed = unparsecG tsGrammar [TypeAliasDeclaration True "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 True "Point" (TypeLiteral [PropertySignature (PropertyIdentifier "x") False (KeywordType NumberKeyword)])] +Just [TypeAliasDeclaration True "Point" (ObjectType [PropertySignature (PropertyIdentifier "x") False (KeywordType NumberKeyword)])] >>> let scanned = concat (parsecResult (parsecG tsTokensGrammar "type A = { a: number; b: };")) >>> parsecOffset (parsecG tsGrammar scanned) 10 @@ -35,10 +35,10 @@ Just [TypeAliasDeclaration True "Point" (TypeLiteral [PropertySignature (Propert module Control.Lens.Grammar.TypeScript ( -- * Syntax TsDeclaration (..) - , TypeNode (..) - , TypeElement (..) - , PropertyName (..) - , Literal (..) + , TsType (..) + , TsProperty (..) + , TsPropertyName (..) + , TsLiteral (..) , tsGrammar -- * Tokens , TsToken (..) @@ -58,45 +58,45 @@ import Numeric (readHex, showHex) -- Syntax -- -- | A type alias, @export type T = U;@, exported or not. -data TsDeclaration = TypeAliasDeclaration Bool Text TypeNode +data TsDeclaration = TypeAliasDeclaration Bool Text TsType deriving stock (Eq, Ord, Show, Read) -- | A type, by the TypeScript compiler's name of its node. -data TypeNode +data TsType = KeywordType TsTokenCategory -- ^ @number@, @string@, @never@, … - | LiteralType Literal -- ^ @null@, @true@ or @"abc"@ - | TypeReference Text [TypeNode] -- ^ @T@ or @T\@ - | ArrayType TypeNode -- ^ @T[]@ - | TupleType [TypeNode] -- ^ @[T, U]@ - | OptionalType TypeNode -- ^ @T?@, an element of a tuple - | RestType TypeNode -- ^ @...T@, an element of a tuple - | UnionType [TypeNode] -- ^ @T | U@ - | IntersectionType [TypeNode] -- ^ @T & U@ - | ParenthesizedType TypeNode -- ^ @(T)@ - | TypeLiteral [TypeElement] -- ^ @{ x: T; y?: U }@ - | MappedType Text TypeNode (Maybe TypeNode) Bool TypeNode + | LiteralType TsLiteral -- ^ @null@, @true@ or @"abc"@ + | TypeReference Text [TsType] -- ^ @T@ or @T\@ + | ArrayType TsType -- ^ @T[]@ + | TupleType [TsType] -- ^ @[T, U]@ + | OptionalType TsType -- ^ @T?@, an element of a tuple + | RestType TsType -- ^ @...T@, an element of a tuple + | UnionType [TsType] -- ^ @T | U@ + | IntersectionType [TsType] -- ^ @T & U@ + | ParenthesizedType TsType -- ^ @(T)@ + | ObjectType [TsProperty] -- ^ @{ x: T; y?: U }@ + | MappedType Text TsType (Maybe TsType) Bool TsType -- ^ @{ [k in K as L]?: T }@, with a name type & an optional token or not - | ConditionalType TypeNode TypeNode TypeNode TypeNode + | ConditionalType TsType TsType TsType TsType -- ^ @T extends U ? V : W@ - | TemplateLiteralType Text [(TypeNode, Text)] + | TemplateLiteralType Text [(TsType, Text)] -- ^ @\`a${T}b\`@, by its head & its spans' types & literals deriving stock (Eq, Ord, Show, Read) --- | A member of a `TypeLiteral`. -data TypeElement - = PropertySignature PropertyName Bool TypeNode +-- | A member of an `ObjectType`. +data TsProperty + = PropertySignature TsPropertyName Bool TsType -- ^ @x: T@ or @x?: T@ - | IndexSignature Text TypeNode TypeNode -- ^ @[k: K]: T@ + | IndexSignature Text TsType TsType -- ^ @[k: K]: T@ deriving stock (Eq, Ord, Show, Read) -- | The name of a `PropertySignature`. -data PropertyName +data TsPropertyName = PropertyIdentifier Text -- ^ @x@ | PropertyString Text -- ^ @"x y"@ deriving stock (Eq, Ord, Show, Read) -- | A literal of a `LiteralType`. -data Literal +data TsLiteral = NullLiteral -- ^ @null@ | TrueLiteral -- ^ @true@ | FalseLiteral -- ^ @false@ @@ -168,10 +168,10 @@ data TsTokenCategory deriving stock (Eq, Ord, Show, Read, Enum, Bounded) makeNestedPrisms ''TsDeclaration -makeNestedPrisms ''TypeNode -makeNestedPrisms ''TypeElement -makeNestedPrisms ''PropertyName -makeNestedPrisms ''Literal +makeNestedPrisms ''TsType +makeNestedPrisms ''TsProperty +makeNestedPrisms ''TsPropertyName +makeNestedPrisms ''TsLiteral -- | The text of a punctuation or keyword `TsTokenCategory`. kindText :: TsTokenCategory -> Maybe Text @@ -395,7 +395,7 @@ tsGrammar = rule "declarations" $ , _ParenthesizedType >? tokenOf oneP OpenParenToken tight >* ty *< tokenOf tight CloseParenToken oneP , _Braced >? tokenOf oneP OpenBraceToken oneP >* orP - [ only (TypeLiteral []) >? tokenOf tight CloseBraceToken oneP + [ only (ObjectType []) >? tokenOf tight CloseBraceToken oneP , _Bracketed >? tokenOf space OpenBracketToken tight >* identifier >*< (mappedRest ty >+< indexRest ty) , _PropertyFirst >? space >* property ty >*< members ty @@ -473,7 +473,7 @@ textOf kind = iso (TsToken kind) tokenText >~ asIn @TsToken kind -- | A list of at least two, or else its only one. _Several - :: Prism' TypeNode [TypeNode] -> Iso' TypeNode (TypeNode, [TypeNode]) + :: Prism' TsType [TsType] -> Iso' TsType (TsType, [TsType]) _Several nodes = iso (\node -> case node ^? nodes of Just (first : others@(_ : _)) -> (first, others) @@ -483,14 +483,14 @@ _Several nodes = iso (first, others) -> review nodes (first : others)) -- | A type literal or a mapped type, which are braced. -_Braced :: Prism' TypeNode TypeNode +_Braced :: Prism' TsType TsType _Braced = prism' id $ \case - node@(TypeLiteral _) -> Just node + node@(ObjectType _) -> Just node node@(MappedType {}) -> Just node _ -> Nothing -- | A tuple's element, or else an optional element's type. -_Optional :: Iso' TypeNode (TypeNode, Bool) +_Optional :: Iso' TsType (TsType, Bool) _Optional = iso (\case OptionalType node -> (node, True); node -> (node, False)) (\case (node, True) -> OptionalType node; (node, False) -> node) @@ -498,16 +498,16 @@ _Optional = iso {- | A mapped type, or a type literal whose first member is an index signature, by its type parameter's or index's name, & the rest of it. -} -_Bracketed :: Prism' TypeNode +_Bracketed :: Prism' TsType ( Text , Either - (TypeNode, (Maybe TypeNode, (Bool, TypeNode))) - (TypeNode, (TypeNode, [TypeElement])) + (TsType, (Maybe TsType, (Bool, TsType))) + (TsType, (TsType, [TsProperty])) ) _Bracketed = prism' bracketed $ \case MappedType name constraint nameType optional node -> Just (name, Left (constraint, (nameType, (optional, node)))) - TypeLiteral (IndexSignature name key node : others) -> + ObjectType (IndexSignature name key node : others) -> Just (name, Right (key, (node, others))) _ -> Nothing where @@ -515,23 +515,23 @@ _Bracketed = prism' bracketed $ \case (name, Left (constraint, (nameType, (optional, node)))) -> MappedType name constraint nameType optional node (name, Right (key, (node, others))) -> - TypeLiteral (IndexSignature name key node : others) + ObjectType (IndexSignature name key node : others) -- | A type literal whose first member is a property signature. _PropertyFirst - :: Prism' TypeNode ((PropertyName, (Bool, TypeNode)), [TypeElement]) + :: Prism' TsType ((TsPropertyName, (Bool, TsType)), [TsProperty]) _PropertyFirst = prism' (\((name, (optional, node)), others) -> - TypeLiteral (PropertySignature name optional node : others)) + ObjectType (PropertySignature name optional node : others)) (\case - TypeLiteral (PropertySignature name optional node : others) -> + ObjectType (PropertySignature name optional node : others) -> Just ((name, (optional, node)), others) _ -> Nothing) -- | A template's spans, by the first's type & its middle or tail. _Spans - :: Prism' [(TypeNode, Text)] - (TypeNode, Either (Text, [(TypeNode, Text)]) Text) + :: Prism' [(TsType, Text)] + (TsType, Either (Text, [(TsType, Text)]) Text) _Spans = prism' (\case (node, Left (middle, others)) -> (node, middle) : others @@ -542,7 +542,7 @@ _Spans = prism' [] -> Nothing) -- | A type of any arrays of its element type. -_Arrays :: Iso' TypeNode (TypeNode, [()]) +_Arrays :: Iso' TsType (TsType, [()]) _Arrays = iso arrays (uncurry (foldr (const ArrayType))) where arrays = \case @@ -551,7 +551,7 @@ _Arrays = iso arrays (uncurry (foldr (const ArrayType))) -- | A conditional type, or else its check type. _Conditional - :: Iso' TypeNode (TypeNode, Maybe (TypeNode, (TypeNode, TypeNode))) + :: Iso' TsType (TsType, Maybe (TsType, (TsType, TsType))) _Conditional = iso (\case ConditionalType check extends true false -> @@ -563,7 +563,7 @@ _Conditional = iso ConditionalType check extends true false) -- | A template literal type without substitutions. -_NoSubstitution :: Prism' TypeNode Text +_NoSubstitution :: Prism' TsType Text _NoSubstitution = prism' (`TemplateLiteralType` []) $ \case TemplateLiteralType text [] -> Just text _ -> Nothing From e98b1a664ca5f6378669c3be09067f32d1e2b924 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Fri, 6 Nov 2026 18:12:19 -0800 Subject: [PATCH 028/130] Enumerable sums & Comonocles Enumerable functors are Homogeneous countable sums of single copies, sequenced by CocartesianMonoidal profunctors. Comonocles are the optic dual to Monocles by sums, with enumerated, enumBounded & Comonocular. WrappedPafb f p is CocartesianMonoidal for any Functor f. Co-Authored-By: Claude Opus 5.5 --- distributors-core/CHANGELOG.md | 10 +++ distributors-core/src/Control/Lens/Monocle.hs | 77 +++++++++++++++++++ .../Data/Profunctor/Monoidal/Cocartesian.hs | 4 +- .../src/Data/Traversable/Homogeneous.hs | 67 ++++++++++++++++ 4 files changed, 156 insertions(+), 2 deletions(-) diff --git a/distributors-core/CHANGELOG.md b/distributors-core/CHANGELOG.md index a044c468..fee10ddc 100644 --- a/distributors-core/CHANGELOG.md +++ b/distributors-core/CHANGELOG.md @@ -2,6 +2,16 @@ ## Unreleased +### New APIs + +- `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.Monocle`, dual to `Monocle`s by sums: + `Comonocle'`, `comonocle`, `enumerated`, `enumBounded`, & concrete + `Comonocular`s, with `runComonocular`. +- `WrappedPafb f p` is `CocartesianMonoidal` for any `Functor f`. + ### Breaking Changes - `Operator`'s `Infix`, `Prefix` & `Postfix` take `APrism`s, rather than diff --git a/distributors-core/src/Control/Lens/Monocle.hs b/distributors-core/src/Control/Lens/Monocle.hs index da093f78..586fbb76 100644 --- a/distributors-core/src/Control/Lens/Monocle.hs +++ b/distributors-core/src/Control/Lens/Monocle.hs @@ -25,12 +25,25 @@ module Control.Lens.Monocle , forevered -- * Monocular , Monocular (..), runMonocular + -- * Comonocle + , Comonocle + , Comonocle' + , comonocle + , enumerated + , enumBounded + -- * Comonocular + , Comonocular (..), runComonocular ) where import Control.Lens hiding (Traversing) import Control.Lens.Internal.Profunctor import Data.Distributive +import Data.List.NonEmpty (NonEmpty (..)) import Data.Profunctor.Monoidal +import Data.Profunctor.Monoidal.Cocartesian +import Data.Traversable.Homogeneous +import Data.Void (Void, absurd) +import GHC.Generics (V1, (:+:) (..)) {- | `Monocle`s are an optic that generalizes `Control.Lens.Traversal.Traversal`s & `Control.Lens.Grate.Grate`s. @@ -103,3 +116,67 @@ instance Applicative (Monocular a b s) where {- | 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 + +{- | `Comonocle`s are an optic dual to `Monocle`s, by sums, +which focus on the one copy that an `Enumerable` sum holds. + +Every `Control.Lens.Iso.Iso` is a `Comonocle`. + +`Comonocle`s are isomorphic to `Comonocular`s. +-} +type Comonocle s t a b = forall p f. + (CocartesianMonoidal p, Functor f) + => p a (f b) -> p s (f t) + +-- | A simple `Comonocle`. +type Comonocle' s a = Comonocle s s a a + +{- | Build a `Comonocle` from a concrete `Comonocular`. -} +comonocle :: Comonocular a b s t -> Comonocle s t a b +comonocle mon = unwrapPafb . runComonocular mon . WrapPafb + +{- | The `Comonocle` of an `Enumerable` sum's copy. + +>>> over enumerated (+ 1) (Identity 1) +Identity 2 +-} +enumerated :: Enumerable f => Comonocle (f a) (f b) a b +enumerated = unwrapPafb . enumerably . WrapPafb + +{- | The `Comonocle` of a bounded enumeration, as a sum of its values, +each of which holds nothing. +-} +enumBounded :: (Enum a, Bounded a) => Comonocle' a () +enumBounded p = values (minBound :| drop 1 [minBound .. maxBound]) + where + value a = dimap (const ()) (fmap (const a)) p + values = \case + a :| [] -> value a + a :| (b : others) -> dialt + (\x -> if fromEnum x == fromEnum a then Left x else Right x) + id + id + (value a) + (values (b :| others)) + +{- | `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 `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/Data/Profunctor/Monoidal/Cocartesian.hs b/distributors-core/src/Data/Profunctor/Monoidal/Cocartesian.hs index f041644f..125faa1b 100644 --- a/distributors-core/src/Data/Profunctor/Monoidal/Cocartesian.hs +++ b/distributors-core/src/Data/Profunctor/Monoidal/Cocartesian.hs @@ -96,9 +96,9 @@ instance Decidable f => CocartesianMonoidal (Clown f) where instance Alternative f => CocartesianMonoidal (Joker f) where zeroP = Joker empty Joker x >+< Joker y = Joker (Left <$> x <|> Right <$> y) -instance (CocartesianMonoidal p, Applicative f) +instance (CocartesianMonoidal p, Functor f) => CocartesianMonoidal (WrappedPafb f p) where - zeroP = WrapPafb (rmap pure zeroP) + 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 diff --git a/distributors-core/src/Data/Traversable/Homogeneous.hs b/distributors-core/src/Data/Traversable/Homogeneous.hs index 6b02f10e..45692f29 100644 --- a/distributors-core/src/Data/Traversable/Homogeneous.hs +++ b/distributors-core/src/Data/Traversable/Homogeneous.hs @@ -11,6 +11,8 @@ Portability : non-portable module Data.Traversable.Homogeneous ( -- * Homogeneous Homogeneous (..) + -- * Enumerable + , Enumerable (..) ) where import Control.Applicative @@ -141,3 +143,68 @@ 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 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 `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 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 From 3845566d490383a3a313f35659477cb485f8cc76 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Fri, 6 Nov 2026 18:13:39 -0800 Subject: [PATCH 029/130] Update Monoidal.hs --- distributors-core/src/Data/Profunctor/Monoidal.hs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/distributors-core/src/Data/Profunctor/Monoidal.hs b/distributors-core/src/Data/Profunctor/Monoidal.hs index ed9f78c4..9f040383 100644 --- a/distributors-core/src/Data/Profunctor/Monoidal.hs +++ b/distributors-core/src/Data/Profunctor/Monoidal.hs @@ -19,6 +19,8 @@ module Data.Profunctor.Monoidal , pureP, asEmpty, (>:<), snocP, replicateP, onlyOne -- * Monoidal & Strong , idP, arrP + -- * Monoidal, Strong & Costrong + , fixP -- * Monoidal, Choice & Strong , meander, traverseP, foldP -- * Deriving via Monoidal @@ -266,6 +268,9 @@ prop> arrP f = rmap f idP = lmap f idP arrP :: (Monoidal p, Strong p) => (a -> b) -> p a b arrP f = fmap f idP +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`, From 94dea9a6a834fd6ec134c41fe30ca8fe80af3ec4 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Fri, 6 Nov 2026 18:13:45 -0800 Subject: [PATCH 030/130] Update Json.hs --- .../src/Control/Lens/Grammar/Json.hs | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/distributors-json/src/Control/Lens/Grammar/Json.hs b/distributors-json/src/Control/Lens/Grammar/Json.hs index 806f1cf5..3b72e718 100644 --- a/distributors-json/src/Control/Lens/Grammar/Json.hs +++ b/distributors-json/src/Control/Lens/Grammar/Json.hs @@ -1656,7 +1656,7 @@ of their types, named by its unqualified name, or else its qualified name, which `jsonTsPut` puts. >>> jsonTsDeclarations (type '[Maybe Ordering]) -[TypeAliasDeclaration True "Ordering" (UnionType [LiteralType (TextLiteral "LT"),LiteralType (TextLiteral "EQ"),LiteralType (TextLiteral "GT")])] +[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 @@ -1847,7 +1847,7 @@ qualified names, as TypeScript identifiers, in order of their names. -} tsDeclarations :: [Bnf JsonType] -> [TsDeclaration] tsDeclarations bnfs = - [ TypeAliasDeclaration True identifier (tsType rules names ruleType) + [ TypeAliasDeclaration [ExportKeyword] identifier [] (tsType rules names ruleType) | (identifier, ruleType) <- sortOn fst [(names Map.! key, ruleType) | (key, ruleType) <- Map.toList rules] ] @@ -1890,7 +1890,7 @@ tsType :: Map String JsonType -> Map String Text -> JsonType -> TsType tsType rules names = typeNode where typeNode = \case - JsonRule key -> TypeReference (names Map.! key) [] + JsonRule key -> ReferenceType [names Map.! key] [] JsonNull -> LiteralType NullLiteral JsonBoolean -> KeywordType BooleanKeyword JsonNumber -> KeywordType NumberKeyword @@ -1925,14 +1925,14 @@ tsType rules names = typeNode allObjectParts -> IntersectionType allObjectParts where named = - [ PropertySignature (propertyName key) isOptional (typeNode t) + [ 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 /= mempty ] indexSignatures = - [ IndexSignature "key" (typeNode pattern) $ union + [ IndexSignature [] "key" (typeNode pattern) $ union (typeNode t : covered pattern) | (_, keyAlternatives, t) <- dicts , pattern <- take 1 @@ -1948,7 +1948,7 @@ tsType rules names = typeNode JsonNumeric -> isJust . readScientific _ -> const True mappedTypes = - [ MappedType "key" base exclusion True (typeNode t) + [ MappedType Nothing "key" base exclusion (Just QuestionToken) (typeNode t) | (keyType, keyAlternatives, t) <- dicts , let literalKeys = [l | JsonStringLiteral l <- keyAlternatives] @@ -1959,10 +1959,10 @@ tsType rules names = typeNode exclusion | null excluded = Nothing | otherwise = Just $ ConditionalType - (TypeReference "key" []) + (ReferenceType ["key"] []) (union (map (LiteralType . TextLiteral) excluded)) (KeywordType NeverKeyword) - (TypeReference "key" []) + (ReferenceType ["key"] []) , length excluded < length literalKeys ] propertyName key From 2dfd888649b468e4de6adbf84c8aeba4fef16971 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Fri, 6 Nov 2026 18:13:48 -0800 Subject: [PATCH 031/130] Update TypeScript.hs --- .../src/Control/Lens/Grammar/TypeScript.hs | 1500 +++++++++++++---- 1 file changed, 1185 insertions(+), 315 deletions(-) diff --git a/distributors-json/src/Control/Lens/Grammar/TypeScript.hs b/distributors-json/src/Control/Lens/Grammar/TypeScript.hs index 7d6fce09..74201ad4 100644 --- a/distributors-json/src/Control/Lens/Grammar/TypeScript.hs +++ b/distributors-json/src/Control/Lens/Grammar/TypeScript.hs @@ -2,43 +2,56 @@ {- | Module : Control.Lens.Grammar.TypeScript -Description : TypeScript type declarations, as a grammar +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 -The type declarations of TypeScript, like the TypeScript compiler, -in two layers: a `tsTokenGrammar` of its tokens, by their `TsTokenCategory`s, -& a `tsGrammar` of its syntax, of those tokens, by the compiler's -names of its nodes, so that they parse & print together. +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 are @LL(1)@, since `tsTokensGrammar` scans tokens without -their trivia, so that `parsecG` parses & `unparsecG` prints each layer, -locating failures. Here, a declaration prints as tokens, & as characters, -& parses back. +Both layers parse by `parsecG` & print by `unparsecG`, locating failures, +since `tsTokensGrammar` scans tokens without their trivia, as the compiler +does. Here, a declaration prints as tokens, & as characters, & parses back. >>> :set -XOverloadedStrings ->>> let point = ObjectType [PropertySignature (PropertyIdentifier "x") False (KeywordType NumberKeyword)] ->>> let printed = unparsecG tsGrammar [TypeAliasDeclaration True "Point" point] ([] :: [TsToken]) +>>> 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 True "Point" (ObjectType [PropertySignature (PropertyIdentifier "x") False (KeywordType NumberKeyword)])] ->>> let scanned = concat (parsecResult (parsecG tsTokensGrammar "type A = { a: number; b: };")) ->>> parsecOffset (parsecG tsGrammar scanned) -10 +>>> parsecResult (parsecG tsGrammar (concat (parsecResult (parsecG tsTokensGrammar source)))) == Just [TypeAliasDeclaration [ExportKeyword] "Point" [] point] +True -} module Control.Lens.Grammar.TypeScript - ( -- * Syntax + ( -- * Declarations TsDeclaration (..) + , TsModuleName (..) + , TsImportClause (..) + , TsNamedBindings (..) + , TsImportSpecifier (..) + , TsModuleReference (..) + , TsExportClause (..) + , TsVariableDeclaration (..) + , TsEnumMember (..) + , TsHeritage (..) + , TsEntityName + -- * Types , TsType (..) , TsProperty (..) , TsPropertyName (..) , TsLiteral (..) + , TsTypeParameter (..) + , TsSignature (..) + , TsParameter (..) + , TsBindingName (..) + , TsBindingElement (..) , tsGrammar -- * Tokens , TsToken (..) @@ -51,63 +64,210 @@ import Control.Lens import Control.Lens.Grammar import Data.Char (chr, ord) import Data.Maybe (fromMaybe, listToMaybe) +import Data.Profunctor.Monadic qualified as P import Data.Text (Text) import Data.Text qualified as Text import Numeric (readHex, showHex) --- Syntax -- +-- 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 type alias, @export type T = U;@, exported or not. -data TsDeclaration = TypeAliasDeclaration Bool Text TsType +-- | @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@, … - | LiteralType TsLiteral -- ^ @null@, @true@ or @"abc"@ - | TypeReference Text [TsType] -- ^ @T@ or @T\@ + | 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 Text TsType (Maybe TsType) Bool TsType - -- ^ @{ [k in K as L]?: T }@, with a name type & an optional token or not + | 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`. +{- | 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 TsPropertyName Bool TsType - -- ^ @x: T@ or @x?: T@ - | IndexSignature Text TsType TsType -- ^ @[k: K]: T@ + = 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 `PropertySignature`. +-- | 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`. +-- | 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 or a template's literal. +an identifier's name, a string's value, a number's spelling, +a template's literal, or a comment. -} data TsToken = TsToken { tokenCategory :: TsTokenCategory @@ -118,12 +278,17 @@ instance Categorized TsToken where type Categorize TsToken = TsTokenCategory categorize = tokenCategory --- | The kinds of `TsToken`s, by the TypeScript compiler's names. +-- | The categories of `TsToken`s, by the TypeScript compiler's names. data TsTokenCategory = WhitespaceTrivia | NewLineTrivia + | SingleLineCommentTrivia + | MultiLineCommentTrivia | Identifier + | PrivateIdentifier | StringLiteral + | NumericLiteral + | BigIntLiteral | NoSubstitutionTemplateLiteral | TemplateHead | TemplateMiddle @@ -134,6 +299,7 @@ data TsTokenCategory | CloseParenToken | OpenBracketToken | CloseBracketToken + | DotToken | DotDotDotToken | SemicolonToken | CommaToken @@ -142,175 +308,371 @@ data TsTokenCategory | QuestionToken | ColonToken | EqualsToken + | EqualsGreaterThanToken | BarToken | AmpersandToken - | AnyKeyword - | AsKeyword - | BigIntKeyword - | BooleanKeyword + | 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 - | NullKeyword | NumberKeyword | ObjectKeyword + | OutKeyword + | OverrideKeyword + | PrivateKeyword + | ProtectedKeyword + | PublicKeyword | ReadonlyKeyword + | RequireKeyword + | SetKeyword + | StaticKeyword | StringKeyword | SymbolKeyword - | TrueKeyword | TypeKeyword | UndefinedKeyword + | UniqueKeyword | UnknownKeyword - | VoidKeyword 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 - --- | The text of a punctuation or keyword `TsTokenCategory`. -kindText :: TsTokenCategory -> Maybe Text -kindText = flip lookup ((CloseBraceToken, "}") : punctuation <> keywords) +makeNestedPrisms ''TsTypeParameter +makeNestedPrisms ''TsSignature +makeNestedPrisms ''TsParameter +makeNestedPrisms ''TsBindingName +makeNestedPrisms ''TsBindingElement punctuation :: [(TsTokenCategory, Text)] punctuation = - [ (OpenBraceToken, "{"), (OpenParenToken, "("), (CloseParenToken, ")") + [ (OpenBraceToken, "{"), (CloseBraceToken, "}") + , (OpenParenToken, "("), (CloseParenToken, ")") , (OpenBracketToken, "["), (CloseBracketToken, "]") - , (DotDotDotToken, "..."), (SemicolonToken, ";"), (CommaToken, ",") - , (LessThanToken, "<"), (GreaterThanToken, ">"), (QuestionToken, "?") - , (ColonToken, ":"), (EqualsToken, "="), (BarToken, "|") - , (AmpersandToken, "&") + , (DotToken, "."), (DotDotDotToken, "..."), (SemicolonToken, ";") + , (CommaToken, ","), (LessThanToken, "<"), (GreaterThanToken, ">") + , (QuestionToken, "?"), (ColonToken, ":"), (EqualsToken, "=") + , (EqualsGreaterThanToken, "=>"), (BarToken, "|"), (AmpersandToken, "&") + , (MinusToken, "-"), (PlusToken, "+"), (AsteriskToken, "*") + , (ExclamationToken, "!") ] -keywords :: [(TsTokenCategory, Text)] -keywords = - [ (AnyKeyword, "any"), (AsKeyword, "as"), (BigIntKeyword, "bigint") - , (BooleanKeyword, "boolean"), (ExportKeyword, "export") - , (ExtendsKeyword, "extends"), (FalseKeyword, "false"), (InKeyword, "in") - , (KeyOfKeyword, "keyof"), (NeverKeyword, "never"), (NullKeyword, "null") - , (NumberKeyword, "number"), (ObjectKeyword, "object") - , (ReadonlyKeyword, "readonly"), (StringKeyword, "string") - , (SymbolKeyword, "symbol"), (TrueKeyword, "true"), (TypeKeyword, "type") - , (UndefinedKeyword, "undefined"), (UnknownKeyword, "unknown") - , (VoidKeyword, "void") +-- | 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") ] --- | The token of a punctuation or keyword `TsTokenCategory`. +-- | 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 kind = TsToken kind (fromMaybe "" (kindText kind)) +symbol category = + TsToken category (fromMaybe "" (lookup category (punctuation <> keywords))) -{- | A token, scanned from its characters. Its trivia are tokens, -as the scanner of the TypeScript compiler scans without skipping them, -so that @`manyP` tsTokenGrammar@ scans a file, or `tsTokensGrammar` -scans it without its trivia. +-- | 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 -Unlike the compiler's scanner, which rescans a @}@ as a template's -middle or tail, by the context of its parser, `tsTokenGrammar` is regular, -so that a @}@ followed by @\`@ or @${@ is a template's tail or middle, -of an empty literal, as it always is in a type. +{- | 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. -} tsTokenGrammar :: RegGrammar Char TsToken tsTokenGrammar = orP - [ kindOf WhitespaceTrivia >? someP (oneOf @Char (" \t" :: String)) + [ 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 StringLiteral >? terminal "\"" >* manyP stringChar *< terminal "\"" + , 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 "${" ] - , _Closing >? terminal "}" >* orP - [ only TemplateTail >? terminal "`" - , only TemplateMiddle >? terminal "${" - , only CloseBraceToken >? oneP - ] + , 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 kind text) >? terminal (Text.unpack text) - | (kind, text) <- punctuation + [ only (TsToken category text) >? terminal (Text.unpack text) + | (category, text) <- punctuation + , category `notElem` + [DotToken, DotDotDotToken, EqualsToken, EqualsGreaterThanToken] ] ] where - identifierStart = orP - [ asIn @Char UppercaseLetter, asIn @Char LowercaseLetter - , asIn @Char TitlecaseLetter - , asIn @Char ModifierLetter, asIn @Char OtherLetter - , asIn @Char LetterNumber - , oneOf @Char ("_$" :: String) - ] identifierPart = orP [ identifierStart, asIn @Char DecimalNumber, asIn @Char NonSpacingMark , asIn @Char SpacingCombiningMark, asIn @Char ConnectorPunctuation ] - stringChar = orP - [ notOneOf @Char ('"' : '\\' : ['\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)) - ] + numberPart = orP + [ asIn @Char DecimalNumber, asIn @Char UppercaseLetter + , asIn @Char LowercaseLetter, oneOf @Char ("_." :: String) ] - hexDigits = "0123456789abcdefABCDEF" :: String - templateChar = orP - [ notOneOf @Char ("`$\\" :: String) - , terminal "\\" >* 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 @LL(1)@. +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. -} -tsTokensGrammar :: RegGrammar Char [TsToken] +tsTokensGrammar :: CtxGrammar Char [TsToken] tsTokensGrammar = rmap (\scanned -> [t | t <- scanned, tokenCategory t `notElem` trivial]) - (manyP tsTokenGrammar) + (tokensWithin []) where - trivial = [WhitespaceTrivia, NewLineTrivia] + trivial = + [ WhitespaceTrivia, NewLineTrivia + , SingleLineCommentTrivia, MultiLineCommentTrivia + ] --- | A token of a kind, by its text. +{- | Tokens, within the substitutions of templates, by the depth of braces +within each, innermost first. +-} +tokensWithin + :: (Lexical Char p, Alternator p, Filtrator p, 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 kind = prism' - (TsToken kind . Text.pack) - (\(TsToken kind' text) -> - if kind == kind' then Just (Text.unpack text) else Nothing) +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 kind text) -> - if kind == Identifier || kind `elem` map fst keywords +_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 kind -> TsToken kind text + Just category -> TsToken category text Nothing -> TsToken Identifier text where text = Text.pack chars --- | A template without substitutions, or a template's head. -_Template :: Prism' TsToken (String, TsTokenCategory) -_Template = prism' - (\(chars, kind) -> TsToken kind (Text.pack chars)) - (\(TsToken kind text) -> - if kind `elem` [NoSubstitutionTemplateLiteral, TemplateHead] - then Just (Text.unpack text, kind) else Nothing) - --- | A @}@, or a template's middle or tail, of an empty literal. -_Closing :: Prism' TsToken TsTokenCategory -_Closing = prism' - (\kind -> TsToken kind (if kind == CloseBraceToken then "}" else "")) +-- | 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 CloseBraceToken "}" -> Just CloseBraceToken - TsToken TemplateMiddle "" -> Just TemplateMiddle - TsToken TemplateTail "" -> Just TemplateTail + 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' @@ -322,172 +684,675 @@ _HexCode = prism' -- Syntax -- -{- | Type declarations, of tokens, by the TypeScript compiler's syntax. +-- | The interpreters of TypeScript's syntax. +type TsGrammatical p = + (Lexical TsToken p, Alternator p, Filtrator p, P.MonadicTry p) -Trivia, whitespace & newlines, are printed conventionally, between tokens, -& parsed only by `parseG`, from tokens with trivia, since `parsecG` -parses tokens without them, which `tsTokensGrammar` scans. +{- | 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. -} -tsGrammar :: Grammar TsToken [TsDeclaration] -tsGrammar = rule "declarations" $ - trivia [] >* manyP declaration - where - declaration = rule "declaration" $ _TypeAliasDeclaration - >? exported - >*< identifier +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 - *< tokenOf tight SemicolonToken newline - exported = orP - [ only True >? tokenOf oneP ExportKeyword space - >* tokenOf oneP TypeKeyword space - , only False >? tokenOf oneP TypeKeyword space + *< 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] ] - typeNode = ruleRec "type" $ \ty -> _Conditional - >~ unionType ty >*< optionalP - ( tokenOf space ExtendsKeyword space >* unionType ty - >*< tokenOf space QuestionToken space >* ty - >*< tokenOf space ColonToken space >* ty - ) - unionType ty = rule "union" $ _Several _UnionType - >~ leading BarToken >* intersectionType ty >*< manyP - (tokenOf space BarToken space >* intersectionType ty) - intersectionType ty = rule "intersection" $ _Several _IntersectionType - >~ leading AmpersandToken >* postfixType ty >*< manyP - (tokenOf space AmpersandToken space >* postfixType ty) - -- A leading operator, which is parsed but not printed. - leading kind = dimap (const Nothing) (const ()) - (optionalP (tokenOf oneP kind space)) - postfixType ty = rule "postfix" $ _Arrays - >~ primaryType ty >*< manyP - ( tokenOf tight OpenBracketToken oneP - >* tokenOf tight CloseBracketToken oneP - ) - primaryType ty = rule "primary" $ orP - [ _KeywordType >? orP - [ only kind >? tokenOf oneP kind oneP - | kind <- - [ AnyKeyword, BigIntKeyword, BooleanKeyword, NeverKeyword - , NumberKeyword, ObjectKeyword, StringKeyword, SymbolKeyword - , UndefinedKeyword, UnknownKeyword, VoidKeyword - ] + >*< 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 ] - , _LiteralType >? orP - [ only NullLiteral >? tokenOf oneP NullKeyword oneP - , only TrueLiteral >? tokenOf oneP TrueKeyword oneP - , only FalseLiteral >? tokenOf oneP FalseKeyword oneP - , _TextLiteral >? textOf StringLiteral + *< 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 ] - , _NoSubstitution >? textOf NoSubstitutionTemplateLiteral - , _TemplateLiteralType >? textOf TemplateHead *< tight - >*< templateSpans ty - , _TypeReference >? identifier >*< orP - [ several1 (sepBy comma) - { beginBy = tokenOf tight LessThanToken tight - , endBy = tokenOf tight GreaterThanToken oneP - } ty - , only [] >? oneP + >*< 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 *< optionalToken CommaToken + *< 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 + [ several1 (sepBy comma) {beginBy = tokenOf space keyword space} 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 + ] ] - , _TupleType >? tokenOf oneP OpenBracketToken oneP >* orP - [ only [] >? tokenOf tight CloseBracketToken oneP - , tight >* several1 (sepBy comma) (tupleElement ty) - *< tokenOf tight CloseBracketToken oneP + >*< 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 *< optionalToken CommaToken + *< 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] ] - , _ParenthesizedType >? tokenOf oneP OpenParenToken tight - >* ty *< tokenOf tight CloseParenToken oneP - , _Braced >? tokenOf oneP OpenBraceToken oneP >* orP - [ only (ObjectType []) >? tokenOf tight CloseBraceToken oneP - , _Bracketed >? tokenOf space OpenBracketToken tight >* identifier - >*< (mappedRest ty >+< indexRest ty) - , _PropertyFirst >? space >* property ty >*< members ty + >*< 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 + [ several1 (sepBy comma) + { beginBy = tokenOf oneP LessThanToken oneP + , endBy = tokenOf oneP GreaterThanToken oneP + } item + , _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' (\(name, t) -> TypePredicate True name t) $ \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 ] - -- The rest of a mapped type, after its type parameter's name. - mappedRest ty = tokenOf space InKeyword space >* ty - >*< optionalP (tokenOf space AsKeyword space >* ty) - >*< tokenOf tight CloseBracketToken oneP >* question - >*< tokenOf tight ColonToken space >* ty - *< tokenOf space CloseBraceToken oneP - -- The rest of a type literal, after its first index signature's name. - indexRest ty = tokenOf tight ColonToken space >* ty - >*< tokenOf tight CloseBracketToken oneP - >* tokenOf tight ColonToken space >* ty - >*< members ty - -- The members after a type literal's first, & its closing brace. - members ty = ruleRec "members" $ \rest -> orP - [ only [] >? tokenOf space CloseBraceToken oneP - , tokenOf tight SemicolonToken space >* orP - [ only [] >? tokenOf tight CloseBraceToken oneP - , member ty >:< rest - ] + >*< 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 *< optionalToken CommaToken + *< tokenOf oneP CloseBracketToken oneP ] - -- A template's spans, each a type & its middle's or tail's literal. - templateSpans ty = ruleRec "spans" $ \rest -> _Spans >? ty - >*< (tight >* textOf TemplateMiddle *< tight >*< rest - >+< tight >* textOf TemplateTail) - tupleElement ty = rule "element" $ orP - [ _RestType >? tokenOf oneP DotDotDotToken tight >* ty + , _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 ] - member ty = rule "member" $ orP - [ _PropertySignature >? property ty - , _IndexSignature >? tokenOf oneP OpenBracketToken tight >* identifier - >*< indexSignature ty + 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 ] - property ty = propertyName >*< question - >*< tokenOf tight ColonToken space >* ty - indexSignature ty = tokenOf tight ColonToken space >* ty - >*< tokenOf tight CloseBracketToken oneP - >* tokenOf tight ColonToken space >* ty - propertyName = orP - [ _PropertyIdentifier >? identifier - , _PropertyIdentifier >? orP - [only text >? tokenOf oneP kind oneP | (kind, text) <- keywords] - , _PropertyString >? textOf StringLiteral + >*< 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 ] - question = orP - [ only True >? tokenOf tight QuestionToken oneP - , only False >? oneP + +-- | 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 ] - comma = tokenOf tight CommaToken space - identifier = textOf Identifier - space = trivia [TsToken WhitespaceTrivia " "] - newline = trivia [TsToken NewLineTrivia "\n"] - tight = trivia [] - -{- | Trivia, of any whitespace & newlines, printed as some trivia. -} -trivia - :: (Lexical TsToken p, Alternator p) - => [TsToken] -> p () () -trivia printed = dimap (const printed) (const ()) - (manyP (asIn @TsToken WhitespaceTrivia >|< asIn @TsToken NewLineTrivia)) --- | A punctuation or keyword token, between trivia, or `oneP`. -tokenOf - :: (Lexical TsToken p, Alternator p) - => p () () -> TsTokenCategory -> p () () -> p () () -tokenOf before kind after = before >* terminal [symbol kind] *< after +-- | A negative number, by its spelling without its sign. +_Negative :: Prism' Text Text +_Negative = prism' ("-" <>) (Text.stripPrefix "-") --- | The text of a token of a kind. -textOf :: (Lexical TsToken p, Alternator p) => TsTokenCategory -> p Text Text -textOf kind = iso (TsToken kind) tokenText >~ asIn @TsToken kind +-- | A qualified name. +entityName :: TsGrammatical p => p TsEntityName TsEntityName +entityName = + identifier >:< manyP (tokenOf oneP DotToken oneP >* identifierName) --- | 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)) +-- | Comma separated items. +commas :: TsGrammatical p => p a a -> p [a] [a] +commas = several (sepBy comma) --- | A type literal or a mapped type, which are braced. -_Braced :: Prism' TsType TsType -_Braced = prism' id $ \case - node@(ObjectType _) -> Just node - node@(MappedType {}) -> Just node - _ -> Nothing +-- | At least one comma separated item. +commas1 :: TsGrammatical p => p a a -> p [a] [a] +commas1 = several1 (sepBy comma) + +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) @@ -495,38 +1360,12 @@ _Optional = iso (\case OptionalType node -> (node, True); node -> (node, False)) (\case (node, True) -> OptionalType node; (node, False) -> node) -{- | A mapped type, or a type literal whose first member is an index -signature, by its type parameter's or index's name, & the rest of it. --} -_Bracketed :: Prism' TsType - ( Text - , Either - (TsType, (Maybe TsType, (Bool, TsType))) - (TsType, (TsType, [TsProperty])) - ) -_Bracketed = prism' bracketed $ \case - MappedType name constraint nameType optional node -> - Just (name, Left (constraint, (nameType, (optional, node)))) - ObjectType (IndexSignature name key node : others) -> - Just (name, Right (key, (node, others))) +-- | 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 - where - bracketed = \case - (name, Left (constraint, (nameType, (optional, node)))) -> - MappedType name constraint nameType optional node - (name, Right (key, (node, others))) -> - ObjectType (IndexSignature name key node : others) - --- | A type literal whose first member is a property signature. -_PropertyFirst - :: Prism' TsType ((TsPropertyName, (Bool, TsType)), [TsProperty]) -_PropertyFirst = prism' - (\((name, (optional, node)), others) -> - ObjectType (PropertySignature name optional node : others)) - (\case - ObjectType (PropertySignature name optional node : others) -> - Just ((name, (optional, node)), others) - _ -> Nothing) -- | A template's spans, by the first's type & its middle or tail. _Spans @@ -541,17 +1380,24 @@ _Spans = prism' (node, middle) : others@(_ : _) -> Just (node, Left (middle, others)) [] -> Nothing) --- | A type of any arrays of its element type. -_Arrays :: Iso' TsType (TsType, [()]) -_Arrays = iso arrays (uncurry (foldr (const ArrayType))) - where - arrays = \case - ArrayType node -> (() :) <$> arrays node - node -> (node, []) +-- | 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' TsType (TsType, Maybe (TsType, (TsType, TsType))) _Conditional = iso (\case ConditionalType check extends true false -> @@ -562,8 +1408,32 @@ _Conditional = iso (check, Just (extends, (true, false))) -> ConditionalType check extends true false) --- | A template literal type without substitutions. -_NoSubstitution :: Prism' TsType Text -_NoSubstitution = prism' (`TemplateLiteralType` []) $ \case - TemplateLiteralType text [] -> Just text - _ -> Nothing +-- 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 From d2a02b767b2dc1f59cff176716ebf9d008b04787 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Fri, 6 Nov 2026 19:05:25 -0800 Subject: [PATCH 032/130] TypeScript declaration files, after the compiler Control.Lens.Grammar.TypeScript models .d.ts files after the TypeScript compiler: declarations of types, interfaces, classes, functions, variables, enums, namespaces & modules, imports & exports, & every kind of type. tsTokensGrammar scans in the context of open templates, as the compiler rescans, & skips comments; tsGrammar parses by Parsector, with try where the compiler looks ahead. All 107 of TypeScript's lib.*.d.ts files, lib.dom.d.ts among them, parse, print & parse again as they parsed. A fixture of every kind of declaration tests that its canonical print is a fixed point. Co-Authored-By: Claude Opus 5.5 --- distributors-json/bench/Main.hs | 7 +- distributors-json/distributors-json.cabal | 3 + distributors-json/package.yaml | 1 + .../src/Control/Lens/Grammar/Json.hs | 8 +- .../src/Control/Lens/Grammar/TypeScript.hs | 29 +++++--- distributors-json/test/Main.hs | 2 + distributors-json/test/Properties/Json.hs | 7 +- .../test/Properties/TypeScript.hs | 38 ++++++++++ .../test/Properties/fixture.d.ts | 74 +++++++++++++++++++ .../test/Properties/fixture.golden.d.ts | 56 ++++++++++++++ 10 files changed, 207 insertions(+), 18 deletions(-) create mode 100644 distributors-json/test/Properties/TypeScript.hs create mode 100644 distributors-json/test/Properties/fixture.d.ts create mode 100644 distributors-json/test/Properties/fixture.golden.d.ts diff --git a/distributors-json/bench/Main.hs b/distributors-json/bench/Main.hs index a6939149..37f5d1c7 100644 --- a/distributors-json/bench/Main.hs +++ b/distributors-json/bench/Main.hs @@ -13,6 +13,8 @@ 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, (.=) @@ -299,5 +301,6 @@ tsTypes as = Text.pack (tsSource (jsonTsDeclarations as)) -- | Print declarations as tokens, & tokens as characters, by Parsector. tsSource :: [TsDeclaration] -> String -tsSource declarations = parsecStream $ unparsecG tsTokensGrammar - (parsecStream (unparsecG tsGrammar declarations [])) "" +tsSource declarations = toList $ parsecStream $ unparsecG tsTokensGrammar + (toList (parsecStream (unparsecG tsGrammar declarations (Seq.empty @TsToken)))) + (Seq.empty @Char) diff --git a/distributors-json/distributors-json.cabal b/distributors-json/distributors-json.cabal index f746a648..b4bba9d0 100644 --- a/distributors-json/distributors-json.cabal +++ b/distributors-json/distributors-json.cabal @@ -19,6 +19,8 @@ license-file: LICENSE build-type: Simple extra-source-files: README.md + test/Properties/fixture.d.ts + test/Properties/fixture.golden.d.ts extra-doc-files: CHANGELOG.md @@ -109,6 +111,7 @@ test-suite test main-is: Main.hs other-modules: Properties.Json + Properties.TypeScript Paths_distributors_json autogen-modules: Paths_distributors_json diff --git a/distributors-json/package.yaml b/distributors-json/package.yaml index 9d0d2697..b87452d4 100644 --- a/distributors-json/package.yaml +++ b/distributors-json/package.yaml @@ -8,6 +8,7 @@ copyright: "2026 Eitan Chatav" extra-source-files: - README.md +- test/Properties/*.d.ts extra-doc-files: - CHANGELOG.md diff --git a/distributors-json/src/Control/Lens/Grammar/Json.hs b/distributors-json/src/Control/Lens/Grammar/Json.hs index 3b72e718..1a41fc4f 100644 --- a/distributors-json/src/Control/Lens/Grammar/Json.hs +++ b/distributors-json/src/Control/Lens/Grammar/Json.hs @@ -1675,10 +1675,12 @@ 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 (parsecStream source) + _ -> hPutStr handle (toList (parsecStream source)) where - printed = unparsecG tsGrammar (jsonTsDeclarations as) [] - source = unparsecG tsTokensGrammar (parsecStream printed) "" + -- 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 " diff --git a/distributors-json/src/Control/Lens/Grammar/TypeScript.hs b/distributors-json/src/Control/Lens/Grammar/TypeScript.hs index 74201ad4..df73cd73 100644 --- a/distributors-json/src/Control/Lens/Grammar/TypeScript.hs +++ b/distributors-json/src/Control/Lens/Grammar/TypeScript.hs @@ -693,6 +693,10 @@ 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. + +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) @@ -876,7 +880,7 @@ specifier = _TsImportSpecifier >? typeOnly braced :: TsGrammatical p => p a a -> p [a] [a] braced item = tokenOf oneP OpenBraceToken oneP >* orP [ _Empty >? tokenOf oneP CloseBraceToken oneP - , space >* commas1 item *< optionalToken CommaToken + , space >* commas1 item *< tokenOf space CloseBraceToken oneP ] @@ -888,7 +892,8 @@ variable = _TsVariableDeclaration >? identifier -- | @extends@ or @implements@ & its heritage, or nothing for none. heritageClause :: TsGrammatical p => TsTokenCategory -> p [TsHeritage] [TsHeritage] heritageClause keyword = orP - [ several1 (sepBy comma) {beginBy = tokenOf space keyword space} heritage + [ _Cons >? tokenOf space keyword space >* heritage + >*< manyP (try (comma >* heritage)) , _Empty >? oneP ] @@ -996,7 +1001,7 @@ signature = _TsSignature >? typeParameters >*< parameters parameters :: TsGrammatical p => p [TsParameter] [TsParameter] parameters = tokenOf oneP OpenParenToken oneP - >* commas parameter *< optionalToken CommaToken + >* commas parameter *< tokenOf oneP CloseParenToken oneP parameter :: TsGrammatical p => p TsParameter TsParameter @@ -1056,10 +1061,10 @@ typeArguments = angled typeNode -- | @\@, or nothing for none. angled :: TsGrammatical p => p a a -> p [a] [a] angled item = orP - [ several1 (sepBy comma) - { beginBy = tokenOf oneP LessThanToken oneP - , endBy = tokenOf oneP GreaterThanToken oneP - } item + [ _Cons >? tokenOf oneP LessThanToken oneP >* item + >*< manyP (try (comma >* item)) + *< optionalToken CommaToken + *< tokenOf oneP GreaterThanToken oneP , _Empty >? oneP ] @@ -1077,7 +1082,7 @@ returnType = orP -- | An asserting type predicate. _AssertsPredicate :: Prism' TsType (Text, Maybe TsType) -_AssertsPredicate = prism' (\(name, t) -> TypePredicate True name t) $ \case +_AssertsPredicate = prism' (uncurry (TypePredicate True)) $ \case TypePredicate True name t -> Just (name, t) _ -> Nothing @@ -1192,7 +1197,7 @@ primaryType ty = rule "primary" $ orP , _ReferenceType >? entityName >*< typeArguments , _TupleType >? tokenOf oneP OpenBracketToken oneP >* orP [ _Empty >? tokenOf oneP CloseBracketToken oneP - , commas1 tupleElement *< optionalToken CommaToken + , commas1 tupleElement *< tokenOf oneP CloseBracketToken oneP ] , _ParenthesizedType >? tokenOf oneP OpenParenToken oneP @@ -1298,11 +1303,13 @@ entityName = -- | Comma separated items. commas :: TsGrammatical p => p a a -> p [a] [a] -commas = several (sepBy comma) +commas item = orP [commas1 item, _Empty >? oneP] -- | At least one comma separated item. +-- | At least one comma separated item, & a trailing comma, if it's there. commas1 :: TsGrammatical p => p a a -> p [a] [a] -commas1 = several1 (sepBy comma) +commas1 item = _Cons >? item >*< manyP (try (comma >* item)) + *< optionalToken CommaToken comma :: TsGrammatical p => p () () comma = tokenOf oneP CommaToken space diff --git a/distributors-json/test/Main.hs b/distributors-json/test/Main.hs index 03cec9f1..6487f30a 100644 --- a/distributors-json/test/Main.hs +++ b/distributors-json/test/Main.hs @@ -8,6 +8,7 @@ import Test.DocTest import Test.Hspec import Properties.Json +import Properties.TypeScript main :: IO () main = do @@ -26,6 +27,7 @@ main = do jsonOptionalSpec jsonCodecSpec jsonPrintSpec + typeScriptSpec doctests :: IO () doctests = do diff --git a/distributors-json/test/Properties/Json.hs b/distributors-json/test/Properties/Json.hs index 1fdca1a3..788a33c2 100644 --- a/distributors-json/test/Properties/Json.hs +++ b/distributors-json/test/Properties/Json.hs @@ -28,6 +28,8 @@ 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 (..), Value (String) , camelTo2, decode, defaultOptions, genericToJSON @@ -1178,5 +1180,6 @@ tsTypes as = Text.pack (tsSource (jsonTsDeclarations as)) -- | Print declarations as tokens, & tokens as characters, by Parsector. tsSource :: [TsDeclaration] -> String -tsSource declarations = parsecStream $ unparsecG tsTokensGrammar - (parsecStream (unparsecG tsGrammar declarations [])) "" +tsSource declarations = toList $ parsecStream $ unparsecG tsTokensGrammar + (toList (parsecStream (unparsecG tsGrammar declarations (Seq.empty @TsToken)))) + (Seq.empty @Char) 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 }; From 0fbbbab7b1ae21770df29022abfc9cf1da58b165 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sat, 7 Nov 2026 07:56:51 -0800 Subject: [PATCH 033/130] comonocles --- distributors-core/CHANGELOG.md | 16 +- distributors-core/src/Control/Lens/Grate.hs | 4 + distributors-core/src/Control/Lens/Monocle.hs | 165 +++++++++++++++--- .../src/Data/Traversable/Homogeneous.hs | 35 ++++ 4 files changed, 196 insertions(+), 24 deletions(-) diff --git a/distributors-core/CHANGELOG.md b/distributors-core/CHANGELOG.md index fee10ddc..15ec13a7 100644 --- a/distributors-core/CHANGELOG.md +++ b/distributors-core/CHANGELOG.md @@ -8,9 +8,23 @@ countable sums of single copies, sequenced `enumerably` by `CocartesianMonoidal`s, with generic defaults by `Generic1`. - `Comonocle`s, in `Control.Lens.Monocle`, dual to `Monocle`s by sums: - `Comonocle'`, `comonocle`, `enumerated`, `enumBounded`, & concrete + `comonocle`, `enumerated`, & concrete `Comonocular`s, with `runComonocular`. - `WrappedPafb f p` is `CocartesianMonoidal` for any `Functor f`. +- `AComonocle`, `withComonocle`, `cloneComonocle`, `mapComonocle`, + `altComonocle`, `crossComonocle`, `indexComonocle` & + `zipWithComonocle`; & `crossMonocle`. +- `Homogeneous` & `Enumerable` instances for `Down`, `Min`, `Max`, + `First`, `Last`, `Alt f`, `Ap f` & `IdentityT f`. +- `Bool1` & `Ordering1`, in `Data.Traversable.Homogeneous`, single copies + tagged by a `Bool` or an `Ordering`, which are `Enumerable` & + `Monad`s, combining tags by conjunction or lexicographically; + & `Bool1` is a `BooleanAlgebra`. + +### Bug Fixes + +- `Grating` is `Profunctor` & `Closed`, so every `Grate`, & so every + `Monocle`, is `AGrate`, for `withGrate`, `cotraverseOf` & co. ### Breaking Changes diff --git a/distributors-core/src/Control/Lens/Grate.hs b/distributors-core/src/Control/Lens/Grate.hs index 520065b8..56535014 100644 --- a/distributors-core/src/Control/Lens/Grate.hs +++ b/distributors-core/src/Control/Lens/Grate.hs @@ -103,6 +103,10 @@ collectOf grt f = distributeOf grt . fmap f 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 diff --git a/distributors-core/src/Control/Lens/Monocle.hs b/distributors-core/src/Control/Lens/Monocle.hs index 586fbb76..69557eb4 100644 --- a/distributors-core/src/Control/Lens/Monocle.hs +++ b/distributors-core/src/Control/Lens/Monocle.hs @@ -21,16 +21,23 @@ module Control.Lens.Monocle , cloneMonocle , imprism , mapMonocle + , crossMonocle , ditraversed , forevered -- * Monocular , Monocular (..), runMonocular -- * Comonocle , Comonocle - , Comonocle' + , AComonocle , comonocle + , withComonocle + , cloneComonocle + , mapComonocle + , altComonocle + , crossComonocle + , indexComonocle + , zipWithComonocle , enumerated - , enumBounded -- * Comonocular , Comonocular (..), runComonocular ) where @@ -38,12 +45,13 @@ module Control.Lens.Monocle import Control.Lens hiding (Traversing) import Control.Lens.Internal.Profunctor import Data.Distributive -import Data.List.NonEmpty (NonEmpty (..)) +import Data.Functor.Compose +import Data.Profunctor (Forget (..)) import Data.Profunctor.Monoidal import Data.Profunctor.Monoidal.Cocartesian import Data.Traversable.Homogeneous import Data.Void (Void, absurd) -import GHC.Generics (V1, (:+:) (..)) +import GHC.Generics (Par1 (..), V1, (:+:) (..)) {- | `Monocle`s are an optic that generalizes `Control.Lens.Traversal.Traversal`s & `Control.Lens.Grate.Grate`s. @@ -84,6 +92,20 @@ Just 1 imprism :: Monocle s t a b -> Prism s t a b imprism mon = clonePrism mon +{- | 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. @@ -120,7 +142,12 @@ runMonocular (Monocular k) p = k $ \f -> lmap f p {- | `Comonocle`s are an optic dual to `Monocle`s, by sums, which focus on the one copy that an `Enumerable` sum holds. -Every `Control.Lens.Iso.Iso` is a `Comonocle`. +Every `Control.Lens.Iso.Iso` is a `Comonocle`, +& every `Comonocle` is a `Control.Lens.Lens.Lens`, +whose residue is which copy is held. + +>>> view enumerated (Identity 'a') +'a' `Comonocle`s are isomorphic to `Comonocular`s. -} @@ -128,13 +155,93 @@ type Comonocle s t a b = forall p f. (CocartesianMonoidal p, Functor f) => p a (f b) -> p s (f t) --- | A simple `Comonocle`. -type Comonocle' s a = Comonocle s s a a +{- | `AComonocle` is monomorphically a `Comonocle`. -} +type AComonocle s t a b = + Comonocular a b a (Identity b) -> Comonocular a b s (Identity t) {- | Build a `Comonocle` from a concrete `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 + +{- | 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 enumerated) '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 (crossComonocle enumerated id) (\(a, c) -> (a + c, show c)) (Identity 1, 2) +(Identity 3,"2") +-} +crossComonocle + :: AComonocle s t a b + -> AComonocle u v c d + -> Comonocle (s,u) (t,v) (a,c) (b,d) +crossComonocle x y = + withComonocle x $ \e f -> + withComonocle y $ \g h -> + comonocle $ Comonocular + (\(s,u) -> Compose (fmap (\a -> fmap (a,) (g u)) (e s))) + (\(Compose bds) -> (f (fmap (fst . copied) bds), h (fmap snd (copied bds)))) + +{- | 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 Int s t a b +indexComonocle mon = withComonocle mon $ \split merge -> + ilens (\s -> let as = split s in (copyIndex as, copied as)) + (\s b -> merge (b <$ split s)) + +{- | Zip two sources of `AComonocle`, when they hold the same copy, +dual to `Control.Lens.Grate.cotraverseOf`, which zips every `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 = + runZipping (mapComonocle mon (Zipping (\a0 a1 -> Just (f a0 a1)))) + {- | The `Comonocle` of an `Enumerable` sum's copy. >>> over enumerated (+ 1) (Identity 1) @@ -143,22 +250,6 @@ Identity 2 enumerated :: Enumerable f => Comonocle (f a) (f b) a b enumerated = unwrapPafb . enumerably . WrapPafb -{- | The `Comonocle` of a bounded enumeration, as a sum of its values, -each of which holds nothing. --} -enumBounded :: (Enum a, Bounded a) => Comonocle' a () -enumBounded p = values (minBound :| drop 1 [minBound .. maxBound]) - where - value a = dimap (const ()) (fmap (const a)) p - values = \case - a :| [] -> value a - a :| (b : others) -> dialt - (\x -> if fromEnum x == fromEnum a then Left x else Right x) - id - id - (value a) - (values (b :| others)) - {- | `Comonocular` provides a concrete representation of `Comonocle`s, by an `Enumerable` sum of copies. -} @@ -180,3 +271,31 @@ instance CocartesianMonoidal (Comonocular a b) where runComonocular :: CocartesianMonoidal p => Comonocular a b s t -> p a b -> p s t runComonocular (Comonocular split merge) = dimap split merge . enumerably + +-- The copy which an `Enumerable` sum holds. +copied :: Enumerable f => f a -> a +copied = runForget (enumerably (Forget id)) + +-- Which copy an `Enumerable` sum holds, numbered from 0, left to right. +copyIndex :: Enumerable f => f a -> Int +copyIndex = case enumerably (Counting 1 (const 0)) of Counting _ which -> which + +-- How many copies, & which copy is held. +data Counting s t = Counting Int (s -> Int) +instance Profunctor Counting where + dimap f _ (Counting count which) = Counting count (which . f) +instance CocartesianMonoidal Counting where + zeroP = Counting 0 absurd + Counting count0 which0 >+< Counting count1 which1 = Counting + (count0 + count1) + (either which0 ((count0 +) . which1)) + +-- Zip two sources holding the same copy. +newtype Zipping s t = Zipping {runZipping :: s -> s -> Maybe t} +instance Profunctor Zipping where + dimap f g (Zipping z) = Zipping (\s0 s1 -> g <$> z (f s0) (f s1)) +instance CocartesianMonoidal Zipping where + zeroP = Zipping absurd + Zipping z0 >+< Zipping z1 = Zipping $ \case + Left s0 -> either (fmap Left . z0 s0) (const Nothing) + Right s1 -> either (const Nothing) (fmap Right . z1 s1) diff --git a/distributors-core/src/Data/Traversable/Homogeneous.hs b/distributors-core/src/Data/Traversable/Homogeneous.hs index 45692f29..4ca5816e 100644 --- a/distributors-core/src/Data/Traversable/Homogeneous.hs +++ b/distributors-core/src/Data/Traversable/Homogeneous.hs @@ -18,11 +18,14 @@ module Data.Traversable.Homogeneous 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 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.Profunctor.Monoidal import Data.Proxy import Data.Sequence (Seq) @@ -70,6 +73,22 @@ 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 @@ -176,6 +195,22 @@ 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 From adf53890438e58c1d311149348221cd7675eb0ec Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sat, 7 Nov 2026 08:25:52 -0800 Subject: [PATCH 034/130] Fix CI: haddock-project flags & an hlint suggestion cabal haddock-project rejects --haddock-hyperlink-source and --haddock-quickjump, which it does by default. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 3 +-- distributors-core/src/Data/Profunctor/Monoidal.hs | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f99b2e4a..5c27e09a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -155,8 +155,7 @@ jobs: - name: Build the documentation run: | - cabal haddock-project --hackage \ - --haddock-hyperlink-source --haddock-quickjump --output=docs + cabal haddock-project --hackage --output=docs - name: Upload the documentation uses: actions/upload-pages-artifact@v3 diff --git a/distributors-core/src/Data/Profunctor/Monoidal.hs b/distributors-core/src/Data/Profunctor/Monoidal.hs index 9f040383..864e8528 100644 --- a/distributors-core/src/Data/Profunctor/Monoidal.hs +++ b/distributors-core/src/Data/Profunctor/Monoidal.hs @@ -269,7 +269,7 @@ arrP :: (Monoidal p, Strong p) => (a -> b) -> p a b arrP f = fmap f idP fixP :: (Monoidal p, Strong p, Costrong p) => p (a -> a) a -fixP = let dup x = (x,x) in unfirst (arrP (uncurry ((.) dup))) +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`, From 32746078ce3a9e8ed1cf53de04127f2b1cfe96f9 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sat, 7 Nov 2026 08:34:23 -0800 Subject: [PATCH 035/130] elements --- .../src/Control/Lens/Grammar/Json.hs | 246 ++++++++++++------ distributors-json/test/Main.hs | 1 + distributors-json/test/Properties/Json.hs | 46 +++- 3 files changed, 212 insertions(+), 81 deletions(-) diff --git a/distributors-json/src/Control/Lens/Grammar/Json.hs b/distributors-json/src/Control/Lens/Grammar/Json.hs index 1a41fc4f..8b40d607 100644 --- a/distributors-json/src/Control/Lens/Grammar/Json.hs +++ b/distributors-json/src/Control/Lens/Grammar/Json.hs @@ -118,7 +118,7 @@ module Control.Lens.Grammar.Json , JsonStr (..) -- * Types , JsonType (..) - , JsonElement (..) + , JsonElements (..) , JsonProperty (..) , jsonType , jsonTsDeclarations @@ -1590,7 +1590,7 @@ printProperty key p a = {- | The type of JSON values, which a grammar describes, of rules by their names, in a `Bnf`, as `jsonType` describes them. -It's the union of its alternatives, so that `mempty` is the type of +It's the union of its alternatives, so that `falseP` is the type of no values. -} data JsonType @@ -1599,19 +1599,22 @@ data JsonType | JsonBoolean -- ^ @true@ or @false@ | JsonNumber -- ^ numbers | JsonString -- ^ strings - | JsonNumeric -- ^ strings of numbers + | JsonNumeric JsonType -- ^ the strings of a type, of numbers | JsonStringLiteral Text -- ^ a string - | JsonArray JsonType -- ^ arrays of a type - | JsonTuple [JsonElement] -- ^ arrays of elements, in order + | JsonSubtype JsonType -- ^ some values of a type + | JsonTuple JsonElements -- ^ arrays of elements | JsonObject [JsonProperty] -- ^ objects of properties | JsonUnion [JsonType] -- ^ values of any of some types deriving stock (Eq, Ord, Show, Read) --- | An element of a `JsonTuple`. -data JsonElement - = JsonRequired JsonType -- ^ an element - | JsonOptional JsonType -- ^ an element, or none - | JsonRest JsonType -- ^ any elements +-- | The elements of a `JsonTuple`, a regular expression of their types. +data JsonElements + = JsonElement JsonType -- ^ an element + | JsonElements JsonElements -- ^ elements, repeated any number of times + | JsonElements1 JsonElements -- ^ elements, repeated at least once + | JsonOptional JsonElements -- ^ elements, or none + | JsonSequence [JsonElements] -- ^ elements, in order + | JsonAlternate [JsonElements] -- ^ elements of any of some alternatives deriving stock (Eq, Ord, Show, Read) -- | A property of a `JsonObject`. @@ -1622,10 +1625,9 @@ data JsonProperty -- ^ the rest of the properties, by the types of their keys & values deriving stock (Eq, Ord, Show, Read) -instance Semigroup JsonType where - a <> b = jsonUnion [a, b] -instance Monoid JsonType where - mempty = JsonUnion [] +instance DisjunctiveMonoid JsonType where + falseP = JsonUnion [] + a >|< b = jsonUnion [a, b] -- | A union, of the alternatives of some types. jsonUnion :: [JsonType] -> JsonType @@ -1637,6 +1639,63 @@ jsonUnion types = case nub (concatMap flatten types) of JsonUnion ts -> ts t -> [t] +jsonSubtype :: JsonType -> JsonType +jsonSubtype = \case + JsonUnion [] -> falseP + t@(JsonSubtype _) -> t + t -> JsonSubtype t + +instance Semigroup JsonElements where + JsonAlternate [] <> _ = falseP + _ <> JsonAlternate [] = 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 -> JsonSequence els + _ -> falseP + where + -- Sequenced elements, or none, for no sequence of elements. + flatten = \case + JsonAlternate [] -> Nothing + JsonSequence els -> Just els + els -> Just [els] +instance Monoid JsonElements where + mempty = JsonSequence [] +instance DisjunctiveMonoid JsonElements where + falseP = JsonAlternate [] + a >|< b | a == b = a + JsonAlternate [] >|< b = b + a >|< JsonAlternate [] = a + JsonElements1 a >|< JsonSequence [] = starK a + JsonSequence [] >|< JsonElements1 b = starK b + a >|< JsonSequence [] = optK a + JsonSequence [] >|< b = optK b + a >|< b = case nub (flatten a <> flatten b) of + [els] -> els + alts -> JsonAlternate alts + where + flatten = \case + JsonAlternate alts -> alts + els -> [els] +instance KleeneStarAlgebra JsonElements where + starK = \case + JsonAlternate [] -> mempty + JsonSequence [] -> mempty + els -> JsonElements els + plusK = \case + JsonAlternate [] -> falseP + JsonSequence [] -> mempty + els -> JsonElements1 els + optK = \case + JsonAlternate [] -> mempty + JsonSequence [] -> mempty + JsonElements1 els -> starK els + els@(JsonElements _) -> els + els@(JsonOptional _) -> els + els -> JsonOptional els + {- | The type of the JSON of a type, by its rules, which are named by their qualified names. @@ -1692,9 +1751,9 @@ been unrolled, & updating the rules & their types. -} newtype JsonTypor a b = JsonTypor (Typing JsonType) --- | Alternative shapes of tuples, which `>*<` concatenates. +-- | The elements of tuples, which `>*<` sequences. newtype TupTypor a b = TupTypor - {runTupTypor :: Ap Typing (Ap [] [JsonElement])} + {runTupTypor :: Ap Typing JsonElements} -- | Alternative shapes of objects, which `>*<` concatenates. newtype ObjTypor a b = ObjTypor @@ -1703,21 +1762,21 @@ newtype ObjTypor a b = ObjTypor 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 `mempty`, while it's typed. +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 `mempty`, since JSON values are finite. +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 mempty + (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 mempty)) + lift (modify (Map.insert key falseP)) ruleType <- local (Map.insert key False) body lift (modify (Map.insert key ruleType)) pure (JsonRule key) @@ -1734,9 +1793,10 @@ 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 = coerce - unright = coerce + unleft (JsonTypor t) = JsonTypor (jsonSubtype <$> t) + unright (JsonTypor t) = JsonTypor (jsonSubtype <$> t) instance Witherable.Filterable (JsonTypor a) where mapMaybe = dimapMaybe Just instance Filtrator JsonTypor @@ -1744,8 +1804,8 @@ instance CocartesianMonoidal JsonTypor instance CocartesianChoice JsonTypor where alternate = either coerce coerce instance DisjunctiveMonoid (JsonTypor a b) where - falseP = typing mempty - JsonTypor t0 >|< JsonTypor t1 = JsonTypor (liftA2 (<>) t0 t1) + 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)) @@ -1755,29 +1815,34 @@ instance JsonStr JsonTypor where jsonText = typing JsonString jsonEnumWith _ table = typing (jsonUnion [JsonStringLiteral literal | (literal, _) <- table]) - jsonNumeric _ = typing JsonNumeric + jsonNumeric (JsonTypor t) = JsonTypor (numeric <$> t) + where + numeric = \case + JsonUnion [] -> falseP + ty -> JsonNumeric ty instance JsonVal JsonTypor where jsonNull = typing JsonNull jsonBool = typing JsonBoolean jsonNumber = typing JsonNumber - jsonArray (JsonTypor t) = JsonTypor (JsonArray <$> guarded t) - jsonTuple tup = JsonTypor (tuples <$> getAp (runTupTypor tup)) + jsonTuple tup = JsonTypor (tuple <$> getAp (runTupTypor tup)) where - tuples (Ap shapes) = jsonUnion (map JsonTuple shapes) + tuple = \case + JsonAlternate [] -> falseP + els -> JsonTuple 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 = mempty + | otherwise = falseP where keys = [key | JsonProperty key _ _ <- props] -deriving via Grammor (Ap Typing (Ap [] [JsonElement])) a +deriving via Grammor (Ap Typing JsonElements) a instance Functor (TupTypor a) -deriving via Grammor (Ap Typing (Ap [] [JsonElement])) a +deriving via Grammor (Ap Typing JsonElements) a instance Applicative (TupTypor a) -deriving via Grammor (Ap Typing (Ap [] [JsonElement])) +deriving via Grammor (Ap Typing JsonElements) instance Profunctor TupTypor instance CocartesianMonoidal TupTypor instance Choice TupTypor where @@ -1786,18 +1851,11 @@ instance Choice TupTypor where instance CocartesianChoice TupTypor where alternate = either coerce coerce instance DisjunctiveMonoid (TupTypor a b) where - falseP = TupTypor (pure (Ap [])) - TupTypor s0 >|< TupTypor s1 = TupTypor (liftA2 unite s0 s1) - where - unite (Ap shapes0) (Ap shapes1) = Ap (shapes0 <> shapes1) --- | `manyP` is a rest element, of the union of the elements of its shapes. + 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 (rest <$> s) - where - rest (Ap shapes) = Ap $ - case concatMap (map elementType) shapes of - [] -> [[]] - ts -> [[JsonRest (jsonUnion ts)]] + manyP (TupTypor s) = TupTypor (starK <$> s) instance Alternative (TupTypor a) where empty = falseP (<|>) = (>|<) @@ -1805,8 +1863,11 @@ instance Alternative (TupTypor a) where some = lmap repeat . someP instance Alternator TupTypor instance JsonTup JsonTypor TupTypor where - jsonElem (JsonTypor t) = - TupTypor (Ap ((\ty -> Ap [[JsonRequired ty]]) <$> guarded t)) + 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) @@ -1835,11 +1896,32 @@ instance JsonObj JsonTypor ObjTypor where typedProperty :: Typing JsonProperty -> ObjTypor a b typedProperty prop = ObjTypor (Ap ((\p -> Ap [[p]]) <$> prop)) -elementType :: JsonElement -> JsonType +-- | 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 - JsonRequired t -> t - JsonOptional t -> t - JsonRest t -> t + 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]] + JsonSequence els -> map concat (traverse tupleShapes els) + JsonAlternate 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) ] + JsonOptional els -> tupleShapes els <> [[]] -- TypeScript -- @@ -1897,23 +1979,33 @@ tsType rules names = typeNode JsonBoolean -> KeywordType BooleanKeyword JsonNumber -> KeywordType NumberKeyword JsonString -> KeywordType StringKeyword - JsonNumeric -> numeric + JsonNumeric t -> numeric t JsonStringLiteral text -> LiteralType (TextLiteral text) - JsonArray t -> ArrayType (operand (typeNode t)) + JsonSubtype t -> typeNode t t@(JsonTuple _) -> typeNode (JsonUnion [t]) JsonObject props -> object props JsonUnion ts -> union $ case break isTuple ts of (before, _ : _) -> map typeNode before - <> map tuple (tsTuples [els | JsonTuple els <- ts]) + <> map tuple + (tsTuples (concat [tupleShapes els | JsonTuple els <- ts])) <> [typeNode t | t <- drop (length before) ts, not (isTuple t)] _ -> map typeNode ts isTuple = \case JsonTuple _ -> True; _ -> False - numeric = TemplateLiteralType "" [(KeywordType NumberKeyword, "")] - tuple els = TupleType $ els <&> \case - JsonRequired t -> typeNode t - JsonOptional t -> OptionalType (operand (typeNode t)) - JsonRest t -> RestType (ArrayType (operand (typeNode t))) + numeric t + | JsonString `elem` alternatives = union + [ if alt == JsonString then numericString else typeNode alt + | alt <- alternatives ] + | otherwise = typeNode t + where + alternatives = typeAlternatives rules t + numericString = TemplateLiteralType "" [(KeywordType NumberKeyword, "")] + 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 signatures, of its string or numeric keys, & a mapped type -- of its literal keys, but those which are named, which TypeScript @@ -1932,13 +2024,13 @@ tsType rules names = typeNode keys = [key | JsonProperty key _ _ <- props] dicts = [ (keyType, typeAlternatives rules keyType, t) - | JsonDict keyType t <- props, t /= mempty ] + | JsonDict keyType t <- props, t /= falseP ] indexSignatures = [ IndexSignature [] "key" (typeNode pattern) $ union (typeNode t : covered pattern) | (_, keyAlternatives, t) <- dicts , pattern <- take 1 - [p | p <- [JsonString, JsonNumeric], p `elem` keyAlternatives] + [p | p <- [JsonString, JsonNumeric JsonString], p `elem` keyAlternatives] ] -- An index type also covers the named properties it matches, -- as TypeScript requires. @@ -1947,7 +2039,7 @@ tsType rules names = typeNode <> [ KeywordType UndefinedKeyword | or [o | JsonProperty key o _ <- props, matches pattern key] ] matches = \case - JsonNumeric -> isJust . readScientific + JsonNumeric _ -> isJust . readScientific _ -> const True mappedTypes = [ MappedType Nothing "key" base exclusion (Just QuestionToken) (typeNode t) @@ -1999,7 +2091,7 @@ operand = \case node@(ConditionalType {}) -> ParenthesizedType node node -> node --- | The alternatives of a type, resolving its rules. +-- | The alternatives of a type, resolving its rules & widening subtypes. typeAlternatives :: Map String JsonType -> JsonType -> [JsonType] typeAlternatives rules = go [] where @@ -2007,6 +2099,10 @@ typeAlternatives rules = go [] 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 + JsonNumeric t -> + [ if alt == JsonString then JsonNumeric JsonString else alt + | alt <- go seen t ] t -> [t] {- | Tuples of some shapes, as TypeScript types them. TypeScript requires @@ -2021,7 +2117,7 @@ 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 :: [[JsonElement]] -> [[JsonElement]] +tsTuples :: [[TupleElement]] -> [[TupleElement]] tsTuples shapes = merged (nub (concatMap (expand False . mergeRests) shapes)) where merged alts = @@ -2043,36 +2139,36 @@ tsTuples shapes = merged (nub (concatMap (expand False . mergeRests) shapes)) Just (map fst same <> [el] <> map fst others) _ -> Nothing unionedElement x y = case (x, y) of - (JsonRequired s, JsonRequired t) -> Just (JsonRequired (s <> t)) - (JsonOptional s, JsonOptional t) -> Just (JsonOptional (s <> t)) + (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 - [JsonRequired t] -> Just (a <> [JsonOptional t]) - [JsonOptional _] -> Just b - [JsonRest _] -> Just b - [JsonRequired t, JsonRest u] | t == u -> Just (a <> [JsonRest t]) + [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 JsonRest _ -> True; _ -> False + 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 <> [JsonRest (jsonUnion (map elementType middle))] <> after + before <> [RestElement (jsonUnion (map elementType middle))] <> after _ -> els expand _ [] = [[]] expand restBefore (el : els) = case el of - JsonOptional t | restBefore || not (optionalTail els) -> - expand restBefore els <> map (JsonRequired t :) (expand restBefore els) - JsonRest _ -> map (el :) (expand True els) + 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 - [JsonRest _] -> True - JsonOptional _ : els -> optionalTail els + [RestElement _] -> True + OptionalElement _ : els -> optionalTail els _ -> False -- Json instance helpers diff --git a/distributors-json/test/Main.hs b/distributors-json/test/Main.hs index 6487f30a..e5abcb15 100644 --- a/distributors-json/test/Main.hs +++ b/distributors-json/test/Main.hs @@ -27,6 +27,7 @@ main = do jsonOptionalSpec jsonCodecSpec jsonPrintSpec + jsonElementsSpec typeScriptSpec doctests :: IO () diff --git a/distributors-json/test/Properties/Json.hs b/distributors-json/test/Properties/Json.hs index 788a33c2..563383d3 100644 --- a/distributors-json/test/Properties/Json.hs +++ b/distributors-json/test/Properties/Json.hs @@ -16,12 +16,13 @@ module Properties.Json , jsonOptionalSpec , jsonCodecSpec , jsonPrintSpec + , jsonElementsSpec ) where import Control.Lens (coerced, only, prism') import Control.Lens.Grammar - ( ParsecState (..), dimap, lmap, manyP, optionP, optionalP - , parsecG, rule, someP, unparsecG + ( ParsecState (..), dimap, falseP, lmap, manyP, optK, optionP, optionalP + , parsecG, plusK, rule, someP, starK, unparsecG , (>*<), (>+<), (>?), (>|<), (>~) ) import Control.Lens.Grammar.Json @@ -354,7 +355,7 @@ instance Json Before where json = jsonTyped $ dimap (\(Before p) -> p) Before $ jsonTuple (optionalP (jsonElem json) >*< jsonElem json) --- | Two rests, @[...(number | string)[]]@. +-- | Two rests, @(number | string)[]@. newtype Rests = Rests ([Scientific], [Text]) deriving stock (Eq, Show) instance Json Rests where @@ -472,11 +473,11 @@ jsonTupleSpec = describe "variadic jsonTuple" $ do 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)[]];"] + 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[]];"] + ["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")) @@ -487,7 +488,7 @@ jsonTupleSpec = describe "variadic jsonTuple" $ do jsonParse @AlternativeRests (toJSON [toJSON (1 :: Int), "a"]) `shouldSatisfy` isLeft declares (type AlternativeRests) - ["export type AlternativeRests = [...number[]] | [...string[]];"] + ["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" @@ -1183,3 +1184,36 @@ 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)) + ] From d0c1cca75c1a8602990292aa8977b7024e30798a Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sat, 7 Nov 2026 08:39:13 -0800 Subject: [PATCH 036/130] number keys --- .../src/Control/Lens/Grammar/Json.hs | 35 ++++++++++--------- distributors-json/test/Properties/Json.hs | 2 +- 2 files changed, 19 insertions(+), 18 deletions(-) diff --git a/distributors-json/src/Control/Lens/Grammar/Json.hs b/distributors-json/src/Control/Lens/Grammar/Json.hs index 8b40d607..b501f8d5 100644 --- a/distributors-json/src/Control/Lens/Grammar/Json.hs +++ b/distributors-json/src/Control/Lens/Grammar/Json.hs @@ -531,8 +531,8 @@ class {- | Strings of numbers, like an integral map key's, like TypeScript's template literal type, @\`${number}\`@. -} - jsonNumeric :: p a a -> p a a - jsonNumeric = id + jsonNumberKey :: p a a -> p a a + jsonNumberKey = id {- | `JsonTup` grammars describe the elements of a JSON array. As `Alternator`s they have optional elements (`optionalP`, `optionP`), @@ -1599,7 +1599,7 @@ data JsonType | JsonBoolean -- ^ @true@ or @false@ | JsonNumber -- ^ numbers | JsonString -- ^ strings - | JsonNumeric JsonType -- ^ the strings of a type, of numbers + | JsonNumberKey JsonType -- ^ the strings of a type which are numbers, as keys | JsonStringLiteral Text -- ^ a string | JsonSubtype JsonType -- ^ some values of a type | JsonTuple JsonElements -- ^ arrays of elements @@ -1815,11 +1815,11 @@ instance JsonStr JsonTypor where jsonText = typing JsonString jsonEnumWith _ table = typing (jsonUnion [JsonStringLiteral literal | (literal, _) <- table]) - jsonNumeric (JsonTypor t) = JsonTypor (numeric <$> t) + jsonNumberKey (JsonTypor t) = JsonTypor (numberKey <$> t) where - numeric = \case + numberKey = \case JsonUnion [] -> falseP - ty -> JsonNumeric ty + ty -> JsonNumberKey ty instance JsonVal JsonTypor where jsonNull = typing JsonNull jsonBool = typing JsonBoolean @@ -1979,7 +1979,7 @@ tsType rules names = typeNode JsonBoolean -> KeywordType BooleanKeyword JsonNumber -> KeywordType NumberKeyword JsonString -> KeywordType StringKeyword - JsonNumeric t -> numeric t + JsonNumberKey t -> numberKey t JsonStringLiteral text -> LiteralType (TextLiteral text) JsonSubtype t -> typeNode t t@(JsonTuple _) -> typeNode (JsonUnion [t]) @@ -1992,14 +1992,14 @@ tsType rules names = typeNode <> [typeNode t | t <- drop (length before) ts, not (isTuple t)] _ -> map typeNode ts isTuple = \case JsonTuple _ -> True; _ -> False - numeric t + numberKey t | JsonString `elem` alternatives = union - [ if alt == JsonString then numericString else typeNode alt + [ if alt == JsonString then numberKeyString else typeNode alt | alt <- alternatives ] | otherwise = typeNode t where alternatives = typeAlternatives rules t - numericString = TemplateLiteralType "" [(KeywordType NumberKeyword, "")] + numberKeyString = TemplateLiteralType "" [(KeywordType NumberKeyword, "")] tuple = \case [RestElement t] -> ArrayType (operand (typeNode t)) els -> TupleType $ els <&> \case @@ -2007,7 +2007,7 @@ tsType rules names = typeNode OptionalElement t -> OptionalType (operand (typeNode t)) RestElement t -> RestType (ArrayType (operand (typeNode t))) -- The intersected parts of an object type: its named properties - -- & index signatures, of its string or numeric keys, & a mapped type + -- & index signatures, of its string or number 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 @@ -2030,7 +2030,8 @@ tsType rules names = typeNode (typeNode t : covered pattern) | (_, keyAlternatives, t) <- dicts , pattern <- take 1 - [p | p <- [JsonString, JsonNumeric JsonString], p `elem` keyAlternatives] + [ p | p <- [JsonString, JsonNumberKey JsonString] + , p `elem` keyAlternatives ] ] -- An index type also covers the named properties it matches, -- as TypeScript requires. @@ -2039,7 +2040,7 @@ tsType rules names = typeNode <> [ KeywordType UndefinedKeyword | or [o | JsonProperty key o _ <- props, matches pattern key] ] matches = \case - JsonNumeric _ -> isJust . readScientific + JsonNumberKey _ -> isJust . readScientific _ -> const True mappedTypes = [ MappedType Nothing "key" base exclusion (Just QuestionToken) (typeNode t) @@ -2100,8 +2101,8 @@ typeAlternatives rules = go [] go (key : seen) t JsonUnion ts -> concatMap (go seen) ts JsonSubtype t -> go seen t - JsonNumeric t -> - [ if alt == JsonString then JsonNumeric JsonString else alt + JsonNumberKey t -> + [ if alt == JsonString then JsonNumberKey JsonString else alt | alt <- go seen t ] t -> [t] @@ -2225,7 +2226,7 @@ readScientific t -- | `Scientific` map keys, as @aeson@ renders them. jsonScientificKey :: JsonStr p => p Scientific Scientific -jsonScientificKey = jsonNumeric (prism' render readScientific ?< jsonText) +jsonScientificKey = jsonNumberKey (prism' render readScientific ?< jsonText) where render s | e < 0 || e > 1024 = Text.pack (formatScientific Generic Nothing s) @@ -2235,7 +2236,7 @@ jsonScientificKey = jsonNumeric (prism' render readScientific ?< jsonText) -- | Integral map keys, as @aeson@ renders them. jsonIntKey :: (Show a, JsonStr p) => APrism' Scientific a -> p a a -jsonIntKey integral = jsonNumeric $ jsonEncodedText $ prism shown $ \t -> +jsonIntKey integral = jsonNumberKey $ jsonEncodedText $ prism shown $ \t -> maybe (Left (t, Encoding.text t)) Right (readScientific t >>= preview (clonePrism integral)) where diff --git a/distributors-json/test/Properties/Json.hs b/distributors-json/test/Properties/Json.hs index 563383d3..7594de3d 100644 --- a/distributors-json/test/Properties/Json.hs +++ b/distributors-json/test/Properties/Json.hs @@ -298,7 +298,7 @@ jsonObjectSpec = describe "jsonObject" $ do ] roundTrip (object ["yes" .= (2 :: Int), "no" .= (1 :: Int)]) (Votes (2, [(False, 1)])) - it "types numeric keys as template literals" $ do + it "types number keys as template literals" $ do declares (type (Box (Map Int Bool))) [ "export type Box_Map_Int_Bool = { [key: `${number}`]: boolean };" ] From 50645ba2ac18a27bd9f58e6587c51f0d0f574674 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sat, 7 Nov 2026 08:41:22 -0800 Subject: [PATCH 037/130] Update Json.hs --- distributors-json/src/Control/Lens/Grammar/Json.hs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/distributors-json/src/Control/Lens/Grammar/Json.hs b/distributors-json/src/Control/Lens/Grammar/Json.hs index b501f8d5..10387741 100644 --- a/distributors-json/src/Control/Lens/Grammar/Json.hs +++ b/distributors-json/src/Control/Lens/Grammar/Json.hs @@ -1602,12 +1602,12 @@ data JsonType | JsonNumberKey JsonType -- ^ the strings of a type which are numbers, as keys | JsonStringLiteral Text -- ^ a string | JsonSubtype JsonType -- ^ some values of a type - | JsonTuple JsonElements -- ^ arrays of elements + | 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 elements of a `JsonTuple`, a regular expression of their types. +-- | The elements of a `JsonArray`, a regular expression of their types. data JsonElements = JsonElement JsonType -- ^ an element | JsonElements JsonElements -- ^ elements, repeated any number of times @@ -1828,7 +1828,7 @@ instance JsonVal JsonTypor where where tuple = \case JsonAlternate [] -> falseP - els -> JsonTuple els + els -> JsonArray els jsonObject obj = JsonTypor (objects <$> getAp (runObjTypor obj)) where objects (Ap shapes) = jsonUnion (map object shapes) @@ -1982,16 +1982,16 @@ tsType rules names = typeNode JsonNumberKey t -> numberKey t JsonStringLiteral text -> LiteralType (TextLiteral text) JsonSubtype t -> typeNode t - t@(JsonTuple _) -> typeNode (JsonUnion [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 | JsonTuple els <- ts])) + (tsTuples (concat [tupleShapes els | JsonArray els <- ts])) <> [typeNode t | t <- drop (length before) ts, not (isTuple t)] _ -> map typeNode ts - isTuple = \case JsonTuple _ -> True; _ -> False + isTuple = \case JsonArray _ -> True; _ -> False numberKey t | JsonString `elem` alternatives = union [ if alt == JsonString then numberKeyString else typeNode alt From 6a0b60f76b05156fe4384d6abe3b6c9a7ae8b0e3 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sat, 7 Nov 2026 08:47:21 -0800 Subject: [PATCH 038/130] Update Monocle.hs --- distributors-core/src/Control/Lens/Monocle.hs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/distributors-core/src/Control/Lens/Monocle.hs b/distributors-core/src/Control/Lens/Monocle.hs index 69557eb4..c8827b3c 100644 --- a/distributors-core/src/Control/Lens/Monocle.hs +++ b/distributors-core/src/Control/Lens/Monocle.hs @@ -52,6 +52,7 @@ import Data.Profunctor.Monoidal.Cocartesian import Data.Traversable.Homogeneous import Data.Void (Void, absurd) import GHC.Generics (Par1 (..), V1, (:+:) (..)) +import Numeric.Natural (Natural) {- | `Monocle`s are an optic that generalizes `Control.Lens.Traversal.Traversal`s & `Control.Lens.Grate.Grate`s. @@ -224,7 +225,7 @@ 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 Int s t a b +indexComonocle :: AComonocle s t a b -> IndexedLens Natural s t a b indexComonocle mon = withComonocle mon $ \split merge -> ilens (\s -> let as = split s in (copyIndex as, copied as)) (\s b -> merge (b <$ split s)) @@ -277,11 +278,11 @@ copied :: Enumerable f => f a -> a copied = runForget (enumerably (Forget id)) -- Which copy an `Enumerable` sum holds, numbered from 0, left to right. -copyIndex :: Enumerable f => f a -> Int +copyIndex :: Enumerable f => f a -> Natural copyIndex = case enumerably (Counting 1 (const 0)) of Counting _ which -> which -- How many copies, & which copy is held. -data Counting s t = Counting Int (s -> Int) +data Counting s t = Counting Natural (s -> Natural) instance Profunctor Counting where dimap f _ (Counting count which) = Counting count (which . f) instance CocartesianMonoidal Counting where From cfc60315b58d61e555004c53c35bb9da76d79362 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sat, 7 Nov 2026 09:17:01 -0800 Subject: [PATCH 039/130] enumerable stuff --- distributors-core/src/Control/Lens/Monocle.hs | 40 ++----- .../src/Data/Traversable/Homogeneous.hs | 105 +++++++++++++++++- distributors-core/test/Main.hs | 2 + 3 files changed, 109 insertions(+), 38 deletions(-) diff --git a/distributors-core/src/Control/Lens/Monocle.hs b/distributors-core/src/Control/Lens/Monocle.hs index c8827b3c..3c4c23d5 100644 --- a/distributors-core/src/Control/Lens/Monocle.hs +++ b/distributors-core/src/Control/Lens/Monocle.hs @@ -46,7 +46,6 @@ import Control.Lens hiding (Traversing) import Control.Lens.Internal.Profunctor import Data.Distributive import Data.Functor.Compose -import Data.Profunctor (Forget (..)) import Data.Profunctor.Monoidal import Data.Profunctor.Monoidal.Cocartesian import Data.Traversable.Homogeneous @@ -54,6 +53,9 @@ import Data.Void (Void, absurd) import GHC.Generics (Par1 (..), V1, (:+:) (..)) import Numeric.Natural (Natural) +-- $setup +-- >>> import Data.Complex + {- | `Monocle`s are an optic that generalizes `Control.Lens.Traversal.Traversal`s & `Control.Lens.Grate.Grate`s. @@ -110,8 +112,8 @@ crossMonocle x y p = {- | Build a `Monocle` from a `Traversable` & `Distributive`, homogeneous, countable product. -prop> traverse = ditraversed -prop> cotraversed = ditraversed +@prop> traverse = ditraversed@ +@prop> cotraversed = ditraversed@ -} ditraversed :: (Traversable g, Distributive g) => Monocle (g a) (g b) a b ditraversed = unwrapPafb . ditraverse . WrapPafb @@ -216,7 +218,7 @@ crossComonocle x y = withComonocle y $ \g h -> comonocle $ Comonocular (\(s,u) -> Compose (fmap (\a -> fmap (a,) (g u)) (e s))) - (\(Compose bds) -> (f (fmap (fst . copied) bds), h (fmap snd (copied bds)))) + (\(Compose bds) -> (f (fmap (fst . extractEnumerable) bds), h (fmap snd (extractEnumerable bds)))) {- | The `Control.Lens.Indexed.IndexedLens` of `AComonocle`, indexed by which copy is held, numbered from 0, left to right. @@ -227,7 +229,7 @@ Numbering diverges past a summand of infinitely many copies. -} indexComonocle :: AComonocle s t a b -> IndexedLens Natural s t a b indexComonocle mon = withComonocle mon $ \split merge -> - ilens (\s -> let as = split s in (copyIndex as, copied as)) + ilens (\s -> let as = split s in (indexEnumerable as, extractEnumerable as)) (\s b -> merge (b <$ split s)) {- | Zip two sources of `AComonocle`, when they hold the same copy, @@ -272,31 +274,3 @@ instance CocartesianMonoidal (Comonocular a b) where runComonocular :: CocartesianMonoidal p => Comonocular a b s t -> p a b -> p s t runComonocular (Comonocular split merge) = dimap split merge . enumerably - --- The copy which an `Enumerable` sum holds. -copied :: Enumerable f => f a -> a -copied = runForget (enumerably (Forget id)) - --- Which copy an `Enumerable` sum holds, numbered from 0, left to right. -copyIndex :: Enumerable f => f a -> Natural -copyIndex = case enumerably (Counting 1 (const 0)) of Counting _ which -> which - --- How many copies, & which copy is held. -data Counting s t = Counting Natural (s -> Natural) -instance Profunctor Counting where - dimap f _ (Counting count which) = Counting count (which . f) -instance CocartesianMonoidal Counting where - zeroP = Counting 0 absurd - Counting count0 which0 >+< Counting count1 which1 = Counting - (count0 + count1) - (either which0 ((count0 +) . which1)) - --- Zip two sources holding the same copy. -newtype Zipping s t = Zipping {runZipping :: s -> s -> Maybe t} -instance Profunctor Zipping where - dimap f g (Zipping z) = Zipping (\s0 s1 -> g <$> z (f s0) (f s1)) -instance CocartesianMonoidal Zipping where - zeroP = Zipping absurd - Zipping z0 >+< Zipping z1 = Zipping $ \case - Left s0 -> either (fmap Left . z0 s0) (const Nothing) - Right s1 -> either (const Nothing) (fmap Right . z1 s1) diff --git a/distributors-core/src/Data/Traversable/Homogeneous.hs b/distributors-core/src/Data/Traversable/Homogeneous.hs index 4ca5816e..c952735e 100644 --- a/distributors-core/src/Data/Traversable/Homogeneous.hs +++ b/distributors-core/src/Data/Traversable/Homogeneous.hs @@ -11,8 +11,14 @@ Portability : non-portable module Data.Traversable.Homogeneous ( -- * Homogeneous Homogeneous (..) + , zipWithHomogeneous -- * Enumerable , Enumerable (..) + , extractEnumerable + , indexEnumerable + -- * Counting & Zipping + , Counting (..) + , Zipping (..) ) where import Control.Applicative @@ -26,6 +32,8 @@ 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 (..), Forget (..)) import Data.Profunctor.Monoidal import Data.Proxy import Data.Sequence (Seq) @@ -34,8 +42,11 @@ import Data.Tree (Tree (..)) import Data.Vector (Vector) import Data.Void import GHC.Generics +import Numeric.Natural (Natural) +import Witherable (Filterable (..)) import Data.Profunctor.Distributor +import Data.Profunctor.Filtrator import Data.Profunctor.Monoidal.Cocartesian {- | A class of `Homogeneous` @@ -44,14 +55,14 @@ countable sums of countable products. class Traversable t => Homogeneous t where {- | Sequences actions `homogeneously`. - prop> homogeneously @Maybe = optionalP - prop> homogeneously @[] = manyP + @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 + @prop> homogeneously = ditraverse@ And any user-defined homogeneous algebraic datatype has a default instance for `Homogeneous`, by deriving `Generic1`. @@ -166,12 +177,12 @@ instance Homogeneous Tree where {- | A class of `Enumerable` countable sums of single copies, which are `Homogeneous`, & sequenced by sums alone. -prop> enumerably @Identity = dimap runIdentity Identity +@prop> enumerably @Identity = dimap runIdentity Identity@ Every `Enumerable` is sequenced `enumerably` as it's sequenced `homogeneously`, by a `Distributor`. -prop> enumerably = homogeneously +@prop> enumerably = homogeneously@ And any user-defined enumerable algebraic datatype has a default instance for `Enumerable`, by deriving `Generic1`. @@ -243,3 +254,87 @@ 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 + +-- | The copy which an `Enumerable` sum holds. +extractEnumerable :: Enumerable f => f a -> a +extractEnumerable = runForget (enumerably (Forget id)) + +-- | Which copy an `Enumerable` sum holds, numbered from 0, left to right. +indexEnumerable :: Enumerable f => f a -> Natural +indexEnumerable = + case enumerably (Counting 1 (const 0)) of Counting _ which -> which + +{- | 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 = + runZipping (homogeneously (Zipping (\a0 a1 -> Just (f a0 a1)))) + +{- | `Counting` counts the index of an `Enumerable`. -} +data Counting s t = Counting Natural (s -> Natural) +instance Profunctor Counting where + dimap f _ (Counting count which) = Counting count (which . f) +instance Functor (Counting s) where + fmap _ (Counting count which) = Counting count which +instance Contravariant (Counting s) where + contramap _ (Counting count which) = Counting count which +instance Applicative (Counting s) where + pure _ = Counting 1 (const 0) + Counting count0 which0 <*> Counting count1 which1 = Counting + (count0 * count1) + (\s -> which0 s * count1 + which1 s) +instance CocartesianMonoidal Counting where + zeroP = Counting 0 absurd + Counting count0 which0 >+< Counting count1 which1 = Counting + (count0 + count1) + (either which0 ((count0 +) . which1)) +instance Cochoice Counting where + unleft (Counting count which) = Counting count (which . Left) + unright (Counting count which) = Counting count (which . Right) + +-- | `Zipping` zips two sources, when they have the same shape. +newtype Zipping s t = Zipping {runZipping :: s -> s -> Maybe t} +instance Profunctor Zipping where + dimap f g (Zipping z) = Zipping (\s0 s1 -> g <$> z (f s0) (f s1)) +instance Functor (Zipping s) where + fmap = rmap +instance Applicative (Zipping s) where + pure t = Zipping (\_ _ -> Just t) + Zipping zf <*> Zipping zx = Zipping (\s0 s1 -> zf s0 s1 <*> zx s0 s1) +instance Alternative (Zipping s) where + empty = Zipping (\_ _ -> Nothing) + Zipping z0 <|> Zipping z1 = Zipping (\s0 s1 -> z0 s0 s1 <|> z1 s0 s1) +instance Monad (Zipping s) where + Zipping z >>= f = Zipping (\s0 s1 -> z s0 s1 >>= \t -> runZipping (f t) s0 s1) +instance Filterable (Zipping s) where + mapMaybe f (Zipping z) = Zipping (\s0 s1 -> z s0 s1 >>= f) +instance DisjunctiveMonoid (Zipping s t) where + falseP = empty + (>|<) = (<|>) +instance Choice Zipping where + left' (Zipping z) = Zipping $ \s0 s1 -> case (s0, s1) of + (Left a0, Left a1) -> Left <$> z a0 a1 + _ -> Nothing + right' (Zipping z) = Zipping $ \s0 s1 -> case (s0, s1) of + (Right a0, Right a1) -> Right <$> z a0 a1 + _ -> Nothing +instance Cochoice Zipping where + unleft (Zipping z) = Zipping $ \a0 a1 -> + z (Left a0) (Left a1) >>= either Just (const Nothing) + unright (Zipping z) = Zipping $ \a0 a1 -> + z (Right a0) (Right a1) >>= either (const Nothing) Just +instance CocartesianMonoidal Zipping where + zeroP = Zipping absurd + Zipping z0 >+< Zipping z1 = Zipping $ \case + Left s0 -> either (fmap Left . z0 s0) (const Nothing) + Right s1 -> either (const Nothing) (fmap Right . z1 s1) +instance CocartesianChoice Zipping +instance Distributor Zipping +instance Alternator Zipping +instance Filtrator Zipping diff --git a/distributors-core/test/Main.hs b/distributors-core/test/Main.hs index 7477aa8e..44a00c78 100644 --- a/distributors-core/test/Main.hs +++ b/distributors-core/test/Main.hs @@ -95,6 +95,8 @@ doctests = do modulePaths = [ "src/Control/Lens/Grammar.hs" , "src/Data/Profunctor/Separator.hs" + , "src/Data/Traversable/Homogeneous.hs" + , "src/Control/Lens/Monocle.hs" ] sourceDirs = [ "-isrc" From 24ef65f6b68e42d8644b27ccef25dfc824b26d0a Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sat, 7 Nov 2026 10:58:14 -0800 Subject: [PATCH 040/130] enum stuff --- distributors-core/distributors.cabal | 1 + .../src/Data/Traversable/Homogeneous.hs | 99 ++++++- distributors-core/test/Main.hs | 2 + .../test/Properties/Homogeneous.hs | 243 ++++++++++++++++++ 4 files changed, 340 insertions(+), 5 deletions(-) create mode 100644 distributors-core/test/Properties/Homogeneous.hs diff --git a/distributors-core/distributors.cabal b/distributors-core/distributors.cabal index 421de401..519bd7d7 100644 --- a/distributors-core/distributors.cabal +++ b/distributors-core/distributors.cabal @@ -135,6 +135,7 @@ test-suite test Examples.RegString Examples.SemVer Examples.SExpr + Properties.Homogeneous Properties.Kleene Paths_distributors autogen-modules: diff --git a/distributors-core/src/Data/Traversable/Homogeneous.hs b/distributors-core/src/Data/Traversable/Homogeneous.hs index c952735e..16f302d3 100644 --- a/distributors-core/src/Data/Traversable/Homogeneous.hs +++ b/distributors-core/src/Data/Traversable/Homogeneous.hs @@ -12,19 +12,24 @@ module Data.Traversable.Homogeneous ( -- * Homogeneous Homogeneous (..) , zipWithHomogeneous + , zipWithHomogeneous3 -- * Enumerable , Enumerable (..) , extractEnumerable , indexEnumerable + , Bool1 (..), bool1 -- * Counting & Zipping , Counting (..) , Zipping (..) + , MultiZipping (..) ) where import Control.Applicative import Control.Lens hiding (chosen) import Control.Lens.PartialIso +import Control.Monad ((>=>)) import Control.Monad.Trans.Identity (IdentityT (..)) +import Data.Bool import Data.Complex import Data.Functor.Compose import qualified Data.Functor.Product as Functor @@ -46,7 +51,6 @@ import Numeric.Natural (Natural) import Witherable (Filterable (..)) import Data.Profunctor.Distributor -import Data.Profunctor.Filtrator import Data.Profunctor.Monoidal.Cocartesian {- | A class of `Homogeneous` @@ -254,6 +258,37 @@ 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 balanced tree, built lazily. + +>>> map indexEnumerable [(False, 'a'), (True, 'b')] +[0,1] +>>> map indexEnumerable [(LT, 'a'), (EQ, 'b'), (GT, 'c')] +[0,1,2] +>>> zipWithHomogeneous (+) (True, 1) (True, 2 :: Int) +Just (True,3) +>>> zipWithHomogeneous (+) (True, 1) (False, 2 :: Int) +Nothing + +Reaching a copy takes time logarithmic in the number of tags, +but counting them, as `indexEnumerable` 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) => Homogeneous ((,) e) where + homogeneously = enumerably +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 -- | The copy which an `Enumerable` sum holds. extractEnumerable :: Enumerable f => f a -> a @@ -276,6 +311,21 @@ zipWithHomogeneous zipWithHomogeneous f = runZipping (homogeneously (Zipping (\a0 a1 -> Just (f a0 a1)))) +{- | 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 = runMultiZipping + (homogeneously (MultiZipping + (\(Par1 a :*: Par1 b :*: Par1 c) -> Just (f a b c)))) + (Par1 x :*: Par1 y :*: Par1 z) + {- | `Counting` counts the index of an `Enumerable`. -} data Counting s t = Counting Natural (s -> Natural) instance Profunctor Counting where @@ -314,9 +364,7 @@ instance Monad (Zipping s) where Zipping z >>= f = Zipping (\s0 s1 -> z s0 s1 >>= \t -> runZipping (f t) s0 s1) instance Filterable (Zipping s) where mapMaybe f (Zipping z) = Zipping (\s0 s1 -> z s0 s1 >>= f) -instance DisjunctiveMonoid (Zipping s t) where - falseP = empty - (>|<) = (<|>) +instance DisjunctiveMonoid (Zipping s t) instance Choice Zipping where left' (Zipping z) = Zipping $ \s0 s1 -> case (s0, s1) of (Left a0, Left a1) -> Left <$> z a0 a1 @@ -337,4 +385,45 @@ instance CocartesianMonoidal Zipping where instance CocartesianChoice Zipping instance Distributor Zipping instance Alternator Zipping -instance Filtrator Zipping + +{- | `MultiZipping` zips sources in the positions of a `Traversable`, +like `Complex` of 2, when they have the same shape, as `Zipping` zips two. +With no sources, a sum is its first copy. +-} +newtype MultiZipping f s t = MultiZipping {runMultiZipping :: f s -> Maybe t} +instance Functor f => Profunctor (MultiZipping f) where + dimap f g (MultiZipping z) = MultiZipping (fmap g . z . fmap f) +instance Functor (MultiZipping f s) where + fmap g (MultiZipping z) = MultiZipping (fmap g . z) +instance Applicative (MultiZipping f s) where + pure t = MultiZipping (\_ -> Just t) + MultiZipping zf <*> MultiZipping zx = MultiZipping (\ss -> zf ss <*> zx ss) +instance Alternative (MultiZipping f s) where + empty = MultiZipping (\_ -> Nothing) + MultiZipping z0 <|> MultiZipping z1 = MultiZipping (\ss -> z0 ss <|> z1 ss) +instance Monad (MultiZipping f s) where + MultiZipping z >>= k = + MultiZipping (\ss -> z ss >>= \t -> runMultiZipping (k t) ss) +instance Filterable (MultiZipping f s) where + mapMaybe f (MultiZipping z) = MultiZipping (z >=> f) +instance DisjunctiveMonoid (MultiZipping f s t) where + falseP = empty + (>|<) = (<|>) +instance Traversable f => Choice (MultiZipping f) where + left' (MultiZipping z) = MultiZipping $ \ss -> + Left <$> (traverse (either Just (const Nothing)) ss >>= z) + right' (MultiZipping z) = MultiZipping $ \ss -> + Right <$> (traverse (either (const Nothing) Just) ss >>= z) +instance Functor f => Cochoice (MultiZipping f) where + unleft (MultiZipping z) = MultiZipping $ \ss -> + z (Left <$> ss) >>= either Just (const Nothing) + unright (MultiZipping z) = MultiZipping $ \ss -> + z (Right <$> ss) >>= either (const Nothing) Just +instance Traversable f => CocartesianMonoidal (MultiZipping f) where + zeroP = empty + MultiZipping z0 >+< MultiZipping z1 = MultiZipping $ \ss -> + Left <$> (traverse (either Just (const Nothing)) ss >>= z0) + <|> Right <$> (traverse (either (const Nothing) Just) ss >>= z1) +instance Traversable f => CocartesianChoice (MultiZipping f) +instance Traversable f => Distributor (MultiZipping f) +instance Traversable f => Alternator (MultiZipping f) diff --git a/distributors-core/test/Main.hs b/distributors-core/test/Main.hs index 44a00c78..a9c4c7b2 100644 --- a/distributors-core/test/Main.hs +++ b/distributors-core/test/Main.hs @@ -24,6 +24,7 @@ import Examples.LenVec import Examples.RegString import Examples.SemVer import Examples.SExpr +import Properties.Homogeneous import Properties.Kleene main :: IO () @@ -48,6 +49,7 @@ main = do describe "parseForest" parseForestTests describe "Parsector try rollback" tryRollbackTests describe "Kleene" kleeneProperties + describe "Homogeneous" homogeneousProperties describe "meander" meanderProperties parseForestTests :: Spec diff --git a/distributors-core/test/Properties/Homogeneous.hs b/distributors-core/test/Properties/Homogeneous.hs new file mode 100644 index 00000000..d189ce1b --- /dev/null +++ b/distributors-core/test/Properties/Homogeneous.hs @@ -0,0 +1,243 @@ +-- 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 Data.Foldable (toList) +import Data.Maybe (fromMaybe) +import Data.Monoid.Disjunctive +import Data.Profunctor +import Data.Profunctor.Monoidal.Cocartesian +import Data.Proxy (Proxy (..)) +import Data.Traversable.Homogeneous +import Data.Void +import Numeric.Natural (Natural) +import Test.Hspec +import Test.Hspec.QuickCheck (prop) +import Test.QuickCheck + +-- | 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 + +counting :: Finite s => Counting s t -> (Natural, [Natural]) +counting (Counting count which) = (count, map which universe) + +zipping :: Finite s => Zipping s t -> [Maybe t] +zipping (Zipping z) = [z s0 s1 | s0 <- universe, s1 <- universe] + +natural :: Gen Natural +natural = fromInteger . getNonNegative <$> arbitrary + +genCounting :: forall s t. Finite s => Gen (Counting s t) +genCounting = do + count <- natural + which <- vectorOf (length (universe :: [s])) natural + pure (Counting count (\s -> fromMaybe 0 (lookup s (zip universe which)))) + +genZipping :: Finite s => Gen t -> Gen (Zipping s t) +genZipping gen = do + let pairs = [(s0, s1) | s0 <- universe, s1 <- universe] + results <- vectorOf (length pairs) (liftArbitrary gen) + pure (Zipping (\s0 s1 -> fromMaybe Nothing (lookup (s0, s1) (zip pairs results)))) + +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 + +-- | Two & three sources, for `MultiZipping`. +data Two a = Two a a + deriving stock (Functor, Foldable, Traversable) +data Three a = Three a a a + deriving stock (Functor, Foldable, Traversable) + +multiZipping + :: (Traversable f, Finite s) => f () -> MultiZipping f s t -> [Maybe t] +multiZipping shape (MultiZipping z) = map z (traverse (const universe) shape) + +genMultiZipping + :: (Traversable f, Finite s) => f () -> Gen t -> Gen (MultiZipping f s t) +genMultiZipping shape gen = do + let inputs = map toList (traverse (const universe) shape) + results <- vectorOf (length inputs) (liftArbitrary gen) + pure (MultiZipping (\ss -> fromMaybe Nothing (lookup (toList ss) (zip inputs results)))) + +-- | The laws of `MultiZipping`, of the sources of a shape. +multiZippingLaws :: forall f. Traversable f => String -> f () -> Spec +multiZippingLaws name shape = describe ("MultiZipping " <> name) $ do + let + obs :: Finite s => MultiZipping f s t -> [Maybe t] + obs = multiZipping shape + z = genMultiZipping shape arbitrary :: Gen (MultiZipping f Bool Int) + zf = genMultiZipping shape (applyFun <$> arbitrary) + :: Gen (MultiZipping f Bool (Int -> Int)) + ze = genMultiZipping shape arbitrary + :: Gen (MultiZipping f (Either Bool ()) (Either Int ())) + 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 "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 "rmap Left = lmap Left . left'" $ forAllBlind z $ \p -> + obs (rmap Left p :: MultiZipping f Bool (Either Int ())) + === obs (lmap Left (left' p)) + prop "left' = dimap swapE swapE . right'" $ forAllBlind z $ \p -> + obs (left' p :: MultiZipping f (Either Bool ()) (Either Int ())) + === obs (dimap swapE swapE (right' p)) + prop "left' . left' = dimap assocE unassocE . left'" $ forAllBlind z $ \p -> + obs (left' (left' p) + :: MultiZipping f (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 "x >+< y = alternate (Left x) >|< alternate (Right y)" $ + forAllBlind z $ \x -> forAllBlind z $ \y -> + obs (x >+< y) === obs (alternate (Left x) >|< alternate (Right y)) + +type C = Counting Bool () +type Z = Zipping Bool Int + +homogeneousProperties :: Spec +homogeneousProperties = do + describe "Counting" $ do + let c = genCounting :: Gen C + prop "pure id <*> v = v" $ forAllBlind c $ \v -> + counting (pure id <*> v) === counting v + prop "pure (.) <*> u <*> v <*> w = u <*> (v <*> w)" $ + forAllBlind c $ \u -> forAllBlind c $ \v -> forAllBlind c $ \w -> + counting (pure (.) <*> (id <$ u) <*> (id <$ v) <*> w) + === counting ((id <$ u) <*> ((id <$ v) <*> w)) + prop "u <*> pure y = pure ($ y) <*> u" $ forAllBlind c $ \u -> + counting ((id <$ u) <*> pure ()) === counting (pure ($ ()) <*> (id <$ u)) + prop "zeroP >+< p = lunit p" $ forAllBlind c $ \p -> + counting (zeroP >+< p) === counting (lunit p) + prop "p >+< zeroP = runit p" $ forAllBlind c $ \p -> + counting (p >+< zeroP) === counting (runit p) + prop "p >+< q >+< r = assoc ((p >+< q) >+< r)" $ + forAllBlind c $ \p -> forAllBlind c $ \q -> forAllBlind c $ \r -> + counting (p >+< q >+< r) + === counting (dimap unassocE assocE ((p >+< q) >+< r)) + let ce = genCounting :: Gen (Counting (Either Bool ()) (Either () ())) + prop "unleft = unright . dimap swapE swapE" $ forAllBlind ce $ \p -> + counting (unleft p) === counting (unright (dimap swapE swapE p)) + prop "rmap (either id absurd) = unleft . lmap (either id absurd)" $ + forAllBlind (genCounting :: Gen (Counting Bool (Either () Void))) $ \p -> + counting (rmap (either id absurd) p) + === counting (unleft (lmap (either id absurd) p) :: C) + describe "Zipping" $ do + let z = genZipping arbitrary :: Gen Z + zf = genZipping (applyFun <$> arbitrary) + :: Gen (Zipping Bool (Int -> Int)) + prop "pure id <*> v = v" $ forAllBlind z $ \v -> + zipping (pure id <*> v) === zipping v + prop "pure (.) <*> u <*> v <*> w = u <*> (v <*> w)" $ + forAllBlind zf $ \u -> forAllBlind zf $ \v -> forAllBlind z $ \w -> + zipping (pure (.) <*> u <*> v <*> w) === zipping (u <*> (v <*> w)) + prop "pure f <*> pure x = pure (f x)" $ \(Fun _ f) (x :: Int) -> + zipping (pure f <*> pure x :: Z) === zipping (pure (f x) :: Z) + prop "u <*> pure y = pure ($ y) <*> u" $ forAllBlind zf $ \u (y :: Int) -> + zipping (u <*> pure y) === zipping (pure ($ y) <*> u) + prop "empty <|> x = x = x <|> empty" $ forAllBlind z $ \x -> + zipping (empty <|> x) === zipping x .&&. zipping (x <|> empty) === zipping x + prop "(x <|> y) <|> w = x <|> (y <|> w)" $ + forAllBlind z $ \x -> forAllBlind z $ \y -> forAllBlind z $ \w -> + zipping ((x <|> y) <|> w) === zipping (x <|> (y <|> w)) + let zb = genZipping arbitrary :: Gen (Zipping Bool Bool) + kleisli = (\f t -> if t then fst f else snd f) <$> ((,) <$> zb <*> zb) + prop "pure a >>= k = k a" $ forAllBlind kleisli $ \k a -> + zipping (pure a >>= k) === zipping (k a) + prop "m >>= pure = m" $ forAllBlind zb $ \m -> + zipping (m >>= pure) === zipping m + prop "(m >>= k) >>= h = m >>= (\\x -> k x >>= h)" $ + forAllBlind zb $ \m -> forAllBlind kleisli $ \k -> forAllBlind kleisli $ \h -> + zipping ((m >>= k) >>= h) === zipping (m >>= (\x -> k x >>= h)) + prop "zeroP >+< p = lunit p" $ forAllBlind z $ \p -> + zipping (zeroP >+< p) === zipping (lunit p) + prop "p >+< zeroP = runit p" $ forAllBlind z $ \p -> + zipping (p >+< zeroP) === zipping (runit p) + prop "p >+< q >+< r = assoc ((p >+< q) >+< r)" $ + forAllBlind z $ \p -> forAllBlind z $ \q -> forAllBlind z $ \r -> + zipping (p >+< q >+< r) + === zipping (dimap unassocE assocE ((p >+< q) >+< r)) + prop "rmap Left = lmap Left . left'" $ forAllBlind z $ \p -> + zipping (rmap Left p :: Zipping Bool (Either Int ())) + === zipping (lmap Left (left' p)) + prop "left' = dimap swapE swapE . right'" $ forAllBlind z $ \p -> + zipping (left' p :: Zipping (Either Bool ()) (Either Int ())) + === zipping (dimap swapE swapE (right' p)) + prop "left' . left' = dimap assocE unassocE . left'" $ forAllBlind z $ \p -> + zipping (left' (left' p) :: Zipping (Either (Either Bool ()) ()) (Either (Either Int ()) ())) + === zipping (dimap assocE unassocE (left' p)) + let ze = genZipping arbitrary + :: Gen (Zipping (Either Bool ()) (Either Int ())) + prop "unleft = unright . dimap swapE swapE" $ forAllBlind ze $ \p -> + zipping (unleft p) === zipping (unright (dimap swapE swapE p)) + prop "rmap (either id absurd) = unleft . lmap (either id absurd)" $ + forAllBlind (genZipping (Left <$> arbitrary) + :: Gen (Zipping Bool (Either Int Void))) $ \p -> + zipping (rmap (either id absurd) p) + === zipping (unleft (lmap (either id absurd) p) :: Z) + prop "left' = alternate . Left" $ forAllBlind z $ \p -> + zipping (left' p :: Zipping (Either Bool ()) (Either Int ())) + === zipping (alternate (Left p) :: Zipping (Either Bool ()) (Either Int ())) + prop "x >+< y = alternate (Left x) >|< alternate (Right y)" $ + forAllBlind z $ \x -> forAllBlind z $ \y -> + zipping (x >+< y) + === zipping (alternate (Left x) >|< alternate (Right y)) + multiZippingLaws "of no sources" Proxy + multiZippingLaws "of two sources" (Two () ()) + multiZippingLaws "of three sources" (Three () () ()) + describe "Enumerable & Homogeneous" $ do + it "numbers copies left to right" $ + map indexEnumerable [False1 (), True1 ()] `shouldBe` [0, 1] + 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 "MultiZipping of two is Zipping" $ + \(Fun _ f) (xs :: [Int]) (ys :: [Int]) -> + multiZipWith (\(Two x y) -> f (x, y) :: Int) (Two xs ys) + === zipWithHomogeneous (curry f) xs ys + 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" $ + multiZipWith (\Proxy -> 'a') (Proxy :: Proxy (Maybe Char)) + `shouldBe` Just (Just 'a') + where + multiZipWith + :: (Homogeneous t, Traversable f) => (f a -> b) -> f (t a) -> Maybe (t b) + multiZipWith f = runMultiZipping (homogeneously (MultiZipping (Just . f))) From d2f4b8386722b466de45f8601a3841e8d60a7dc8 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sat, 7 Nov 2026 11:47:38 -0800 Subject: [PATCH 041/130] homogeneous --- distributors-core/src/Control/Lens/Monocle.hs | 9 +- .../src/Data/Traversable/Homogeneous.hs | 320 +++++++++++------- .../test/Properties/Homogeneous.hs | 252 +++++++------- 3 files changed, 325 insertions(+), 256 deletions(-) diff --git a/distributors-core/src/Control/Lens/Monocle.hs b/distributors-core/src/Control/Lens/Monocle.hs index 3c4c23d5..8665d90d 100644 --- a/distributors-core/src/Control/Lens/Monocle.hs +++ b/distributors-core/src/Control/Lens/Monocle.hs @@ -50,7 +50,7 @@ import Data.Profunctor.Monoidal import Data.Profunctor.Monoidal.Cocartesian import Data.Traversable.Homogeneous import Data.Void (Void, absurd) -import GHC.Generics (Par1 (..), V1, (:+:) (..)) +import GHC.Generics (Par1 (..), V1, (:+:) (..), (:*:) (..)) import Numeric.Natural (Natural) -- $setup @@ -229,7 +229,7 @@ Numbering diverges past a summand of infinitely many copies. -} indexComonocle :: AComonocle s t a b -> IndexedLens Natural s t a b indexComonocle mon = withComonocle mon $ \split merge -> - ilens (\s -> let as = split s in (indexEnumerable as, extractEnumerable as)) + ilens (\s -> let as = split s in (fromEnumerable as, extractEnumerable as)) (\s b -> merge (b <$ split s)) {- | Zip two sources of `AComonocle`, when they hold the same copy, @@ -242,8 +242,9 @@ Nothing -} zipWithComonocle :: AComonocle s t a b -> (a -> a -> b) -> s -> s -> Maybe t -zipWithComonocle mon f = - runZipping (mapComonocle mon (Zipping (\a0 a1 -> Just (f a0 a1)))) +zipWithComonocle mon f s0 s1 = runZipporah + (mapComonocle mon (Zipporah (\(Par1 a0 :*: Par1 a1) -> Just (f a0 a1)))) + (Par1 s0 :*: Par1 s1) {- | The `Comonocle` of an `Enumerable` sum's copy. diff --git a/distributors-core/src/Data/Traversable/Homogeneous.hs b/distributors-core/src/Data/Traversable/Homogeneous.hs index 16f302d3..4a7f7dc2 100644 --- a/distributors-core/src/Data/Traversable/Homogeneous.hs +++ b/distributors-core/src/Data/Traversable/Homogeneous.hs @@ -11,17 +11,22 @@ Portability : non-portable module Data.Traversable.Homogeneous ( -- * Homogeneous Homogeneous (..) + , zipHomogeneous , zipWithHomogeneous , zipWithHomogeneous3 + , zipWithHomogeneousM + , transposeHomogeneous -- * Enumerable , Enumerable (..) , extractEnumerable - , indexEnumerable - , Bool1 (..), bool1 - -- * Counting & Zipping - , Counting (..) - , Zipping (..) - , MultiZipping (..) + , fromEnumerable + , toEnumerable + , succEnumerable + , predEnumerable + , enumerateFrom + -- * Indexing & Zipporah + , Indexing (..) + , Zipporah (..) ) where import Control.Applicative @@ -29,7 +34,6 @@ import Control.Lens hiding (chosen) import Control.Lens.PartialIso import Control.Monad ((>=>)) import Control.Monad.Trans.Identity (IdentityT (..)) -import Data.Bool import Data.Complex import Data.Functor.Compose import qualified Data.Functor.Product as Functor @@ -38,7 +42,7 @@ import qualified Data.Monoid as Monoid import Data.Ord (Down (..)) import qualified Data.Semigroup as Semigroup import Data.Monoid.Disjunctive -import Data.Profunctor (Cochoice (..), Forget (..)) +import Data.Profunctor (Cochoice (..), Forget (..), Star (..)) import Data.Profunctor.Monoidal import Data.Proxy import Data.Sequence (Seq) @@ -51,6 +55,7 @@ import Numeric.Natural (Natural) import Witherable (Filterable (..)) import Data.Profunctor.Distributor +import Data.Profunctor.Monadic (Monadic) import Data.Profunctor.Monoidal.Cocartesian {- | A class of `Homogeneous` @@ -262,9 +267,9 @@ instance Enumerable f => Enumerable (Rec1 f) where numbered by its tag's `fromEnum`, from `minBound`, & summed in a balanced tree, built lazily. ->>> map indexEnumerable [(False, 'a'), (True, 'b')] +>>> map fromEnumerable [(False, 'a'), (True, 'b')] [0,1] ->>> map indexEnumerable [(LT, 'a'), (EQ, 'b'), (GT, 'c')] +>>> map fromEnumerable [(LT, 'a'), (EQ, 'b'), (GT, 'c')] [0,1,2] >>> zipWithHomogeneous (+) (True, 1) (True, 2 :: Int) Just (True,3) @@ -272,7 +277,7 @@ Just (True,3) Nothing Reaching a copy takes time logarithmic in the number of tags, -but counting them, as `indexEnumerable` does, takes time linear in it, +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. -} @@ -294,10 +299,77 @@ instance (Enum e, Bounded e) => Enumerable ((,) e) where extractEnumerable :: Enumerable f => f a -> a extractEnumerable = runForget (enumerably (Forget id)) --- | Which copy an `Enumerable` sum holds, numbered from 0, left to right. -indexEnumerable :: Enumerable f => f a -> Natural -indexEnumerable = - case enumerably (Counting 1 (const 0)) of Counting _ which -> which +{- | Which copy an `Enumerable` sum holds, numbered from 0, left to right, +like `fromEnum`. + +>>> fromEnumerable (GT, 'x') +2 +-} +fromEnumerable :: Enumerable f => f a -> Natural +fromEnumerable = + case enumerably (pure ()) of Indexing _ which _ -> which + +{- | The copy of an `Enumerable` sum at an index, if there is one, +like `toEnum`, the inverse of `fromEnumerable`. + +>>> toEnumerable 'x' 1 :: Maybe (Ordering, Char) +Just (EQ,'x') +>>> toEnumerable 'x' 3 :: Maybe (Ordering, Char) +Nothing +-} +toEnumerable :: Enumerable f => a -> Natural -> Maybe (f a) +toEnumerable a copy = + case enumerably (pure a) of Indexing _ _ select -> select copy + +{- | The next copy of an `Enumerable` sum, if there is one, like `succ`. + +>>> succEnumerable (EQ, 'x') +Just (GT,'x') +>>> succEnumerable (GT, 'x') +Nothing +-} +succEnumerable :: Enumerable f => f a -> Maybe (f a) +succEnumerable x = case enumerably (pure (extractEnumerable x)) of + Indexing _ which select -> select (which x + 1) + +{- | The previous copy of an `Enumerable` sum, if there is one, like `pred`. + +>>> predEnumerable (EQ, 'x') +Just (LT,'x') +>>> predEnumerable (LT, 'x') +Nothing +-} +predEnumerable :: Enumerable f => f a -> Maybe (f a) +predEnumerable x = case enumerably (pure (extractEnumerable x)) of + Indexing _ which select -> case which x of + 0 -> Nothing + copy -> select (copy - 1) + +{- | 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 (extractEnumerable x)) of + Indexing _ which select -> + let go copy = maybe [] (: go (copy + 1)) (select copy) in go (which x) + +{- | 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. @@ -308,8 +380,8 @@ Nothing -} zipWithHomogeneous :: Homogeneous t => (a -> a -> b) -> t a -> t a -> Maybe (t b) -zipWithHomogeneous f = - runZipping (homogeneously (Zipping (\a0 a1 -> Just (f a0 a1)))) +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. @@ -321,109 +393,129 @@ Nothing zipWithHomogeneous3 :: Homogeneous t => (a -> a -> a -> b) -> t a -> t a -> t a -> Maybe (t b) -zipWithHomogeneous3 f x y z = runMultiZipping - (homogeneously (MultiZipping - (\(Par1 a :*: Par1 b :*: Par1 c) -> Just (f a b c)))) +zipWithHomogeneous3 f x y z = zipHomogeneous + (\(Par1 a :*: Par1 b :*: Par1 c) -> Just (f a b c)) (Par1 x :*: Par1 y :*: Par1 z) -{- | `Counting` counts the index of an `Enumerable`. -} -data Counting s t = Counting Natural (s -> Natural) -instance Profunctor Counting where - dimap f _ (Counting count which) = Counting count (which . f) -instance Functor (Counting s) where - fmap _ (Counting count which) = Counting count which -instance Contravariant (Counting s) where - contramap _ (Counting count which) = Counting count which -instance Applicative (Counting s) where - pure _ = Counting 1 (const 0) - Counting count0 which0 <*> Counting count1 which1 = Counting +{- | 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 + + +{- | `Indexing` 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 Indexing s t = Indexing Natural (s -> Natural) (Natural -> Maybe t) +instance Profunctor Indexing where + dimap f g (Indexing count which select) = + Indexing count (which . f) (fmap g . select) +instance Functor (Indexing s) where + fmap = rmap +instance Applicative (Indexing s) where + pure t = Indexing 1 (const 0) (\i -> if i == 0 then Just t else Nothing) + Indexing count0 which0 select0 <*> Indexing count1 which1 select1 = Indexing (count0 * count1) (\s -> which0 s * count1 + which1 s) -instance CocartesianMonoidal Counting where - zeroP = Counting 0 absurd - Counting count0 which0 >+< Counting count1 which1 = Counting + (\i -> if count1 == 0 then Nothing + else select0 (i `div` count1) <*> select1 (i `mod` count1)) +instance CocartesianMonoidal Indexing where + zeroP = Indexing 0 absurd (const Nothing) + Indexing count0 which0 select0 >+< Indexing count1 which1 select1 = Indexing (count0 + count1) (either which0 ((count0 +) . which1)) -instance Cochoice Counting where - unleft (Counting count which) = Counting count (which . Left) - unright (Counting count which) = Counting count (which . Right) - --- | `Zipping` zips two sources, when they have the same shape. -newtype Zipping s t = Zipping {runZipping :: s -> s -> Maybe t} -instance Profunctor Zipping where - dimap f g (Zipping z) = Zipping (\s0 s1 -> g <$> z (f s0) (f s1)) -instance Functor (Zipping s) where - fmap = rmap -instance Applicative (Zipping s) where - pure t = Zipping (\_ _ -> Just t) - Zipping zf <*> Zipping zx = Zipping (\s0 s1 -> zf s0 s1 <*> zx s0 s1) -instance Alternative (Zipping s) where - empty = Zipping (\_ _ -> Nothing) - Zipping z0 <|> Zipping z1 = Zipping (\s0 s1 -> z0 s0 s1 <|> z1 s0 s1) -instance Monad (Zipping s) where - Zipping z >>= f = Zipping (\s0 s1 -> z s0 s1 >>= \t -> runZipping (f t) s0 s1) -instance Filterable (Zipping s) where - mapMaybe f (Zipping z) = Zipping (\s0 s1 -> z s0 s1 >>= f) -instance DisjunctiveMonoid (Zipping s t) -instance Choice Zipping where - left' (Zipping z) = Zipping $ \s0 s1 -> case (s0, s1) of - (Left a0, Left a1) -> Left <$> z a0 a1 - _ -> Nothing - right' (Zipping z) = Zipping $ \s0 s1 -> case (s0, s1) of - (Right a0, Right a1) -> Right <$> z a0 a1 - _ -> Nothing -instance Cochoice Zipping where - unleft (Zipping z) = Zipping $ \a0 a1 -> - z (Left a0) (Left a1) >>= either Just (const Nothing) - unright (Zipping z) = Zipping $ \a0 a1 -> - z (Right a0) (Right a1) >>= either (const Nothing) Just -instance CocartesianMonoidal Zipping where - zeroP = Zipping absurd - Zipping z0 >+< Zipping z1 = Zipping $ \case - Left s0 -> either (fmap Left . z0 s0) (const Nothing) - Right s1 -> either (const Nothing) (fmap Right . z1 s1) -instance CocartesianChoice Zipping -instance Distributor Zipping -instance Alternator Zipping - -{- | `MultiZipping` zips sources in the positions of a `Traversable`, -like `Complex` of 2, when they have the same shape, as `Zipping` zips two. -With no sources, a sum is its first copy. + (\i -> if i < count0 then Left <$> select0 i + else Right <$> select1 (i - count0)) +instance Cochoice Indexing where + unleft (Indexing count which select) = Indexing count + (which . Left) (select >=> either Just (const Nothing)) + unright (Indexing count which select) = Indexing count + (which . Right) (select >=> either (const Nothing) Just) + + +{- | `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 MultiZipping f s t = MultiZipping {runMultiZipping :: f s -> Maybe t} -instance Functor f => Profunctor (MultiZipping f) where - dimap f g (MultiZipping z) = MultiZipping (fmap g . z . fmap f) -instance Functor (MultiZipping f s) where - fmap g (MultiZipping z) = MultiZipping (fmap g . z) -instance Applicative (MultiZipping f s) where - pure t = MultiZipping (\_ -> Just t) - MultiZipping zf <*> MultiZipping zx = MultiZipping (\ss -> zf ss <*> zx ss) -instance Alternative (MultiZipping f s) where - empty = MultiZipping (\_ -> Nothing) - MultiZipping z0 <|> MultiZipping z1 = MultiZipping (\ss -> z0 ss <|> z1 ss) -instance Monad (MultiZipping f s) where - MultiZipping z >>= k = - MultiZipping (\ss -> z ss >>= \t -> runMultiZipping (k t) ss) -instance Filterable (MultiZipping f s) where - mapMaybe f (MultiZipping z) = MultiZipping (z >=> f) -instance DisjunctiveMonoid (MultiZipping f s t) where +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 Traversable f => Choice (MultiZipping f) where - left' (MultiZipping z) = MultiZipping $ \ss -> - Left <$> (traverse (either Just (const Nothing)) ss >>= z) - right' (MultiZipping z) = MultiZipping $ \ss -> - Right <$> (traverse (either (const Nothing) Just) ss >>= z) -instance Functor f => Cochoice (MultiZipping f) where - unleft (MultiZipping z) = MultiZipping $ \ss -> - z (Left <$> ss) >>= either Just (const Nothing) - unright (MultiZipping z) = MultiZipping $ \ss -> - z (Right <$> ss) >>= either (const Nothing) Just -instance Traversable f => CocartesianMonoidal (MultiZipping f) where - zeroP = empty - MultiZipping z0 >+< MultiZipping z1 = MultiZipping $ \ss -> - Left <$> (traverse (either Just (const Nothing)) ss >>= z0) - <|> Right <$> (traverse (either (const Nothing) Just) ss >>= z1) -instance Traversable f => CocartesianChoice (MultiZipping f) -instance Traversable f => Distributor (MultiZipping f) -instance Traversable f => Alternator (MultiZipping f) +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/test/Properties/Homogeneous.hs b/distributors-core/test/Properties/Homogeneous.hs index d189ce1b..80bc188d 100644 --- a/distributors-core/test/Properties/Homogeneous.hs +++ b/distributors-core/test/Properties/Homogeneous.hs @@ -9,6 +9,8 @@ module Properties.Homogeneous (homogeneousProperties) where import Control.Applicative import Data.Foldable (toList) +import Data.List (transpose) +import Data.Int (Int8) import Data.Maybe (fromMaybe) import Data.Monoid.Disjunctive import Data.Profunctor @@ -16,6 +18,7 @@ import Data.Profunctor.Monoidal.Cocartesian import Data.Proxy (Proxy (..)) import Data.Traversable.Homogeneous import Data.Void +import GHC.Generics (Par1 (..), (:*:) (..)) import Numeric.Natural (Natural) import Test.Hspec import Test.Hspec.QuickCheck (prop) @@ -33,26 +36,22 @@ instance Finite Void where instance (Finite a, Finite b) => Finite (Either a b) where universe = map Left universe <> map Right universe -counting :: Finite s => Counting s t -> (Natural, [Natural]) -counting (Counting count which) = (count, map which universe) - -zipping :: Finite s => Zipping s t -> [Maybe t] -zipping (Zipping z) = [z s0 s1 | s0 <- universe, s1 <- universe] +-- | An `Indexing`'s count, indices of all sources, & selections, a little past. +indexing :: Finite s => Indexing s t -> (Natural, [Natural], [Maybe t]) +indexing (Indexing count which select) = + (count, map which universe, map select [0 .. count + 1]) natural :: Gen Natural natural = fromInteger . getNonNegative <$> arbitrary -genCounting :: forall s t. Finite s => Gen (Counting s t) -genCounting = do - count <- natural +genIndexing :: forall s t. Finite s => Gen t -> Gen (Indexing s t) +genIndexing gen = do + count <- (`mod` 5) <$> natural which <- vectorOf (length (universe :: [s])) natural - pure (Counting count (\s -> fromMaybe 0 (lookup s (zip universe which)))) - -genZipping :: Finite s => Gen t -> Gen (Zipping s t) -genZipping gen = do - let pairs = [(s0, s1) | s0 <- universe, s1 <- universe] - results <- vectorOf (length pairs) (liftArbitrary gen) - pure (Zipping (\s0 s1 -> fromMaybe Nothing (lookup (s0, s1) (zip pairs results)))) + selected <- vectorOf (fromIntegral count) gen + pure $ Indexing 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 @@ -69,37 +68,49 @@ unassocE = either (Left . Left) (either (Left . Right) Right) swapE :: Either a b -> Either b a swapE = either Right Left --- | Two & three sources, for `MultiZipping`. -data Two a = Two a a - deriving stock (Functor, Foldable, Traversable) -data Three a = Three a a a - deriving stock (Functor, Foldable, Traversable) +zipping + :: (Traversable f, Finite s) => f () -> Zipporah (->) f Maybe s t -> [Maybe t] +zipping shape (Zipporah z) = map z (traverse (const universe) shape) -multiZipping - :: (Traversable f, Finite s) => f () -> MultiZipping f s t -> [Maybe t] -multiZipping shape (MultiZipping z) = map z (traverse (const universe) shape) - -genMultiZipping - :: (Traversable f, Finite s) => f () -> Gen t -> Gen (MultiZipping f s t) -genMultiZipping shape gen = do +genZipping + :: (Traversable f, Finite s) => f () -> Gen t -> Gen (Zipporah (->) f Maybe s t) +genZipping shape gen = do let inputs = map toList (traverse (const universe) shape) results <- vectorOf (length inputs) (liftArbitrary gen) - pure (MultiZipping (\ss -> fromMaybe Nothing (lookup (toList ss) (zip inputs results)))) + pure (Zipporah (\ss -> fromMaybe Nothing (lookup (toList ss) (zip inputs results)))) --- | The laws of `MultiZipping`, of the sources of a shape. -multiZippingLaws :: forall f. Traversable f => String -> f () -> Spec -multiZippingLaws name shape = describe ("MultiZipping " <> name) $ do +-- | The laws of `Zipporah` of functions & `Maybe`, of the sources of a shape. +zippingLaws :: forall f. Traversable f => String -> f () -> Spec +zippingLaws name shape = describe ("Zipporah " <> name) $ do let - obs :: Finite s => MultiZipping f s t -> [Maybe t] - obs = multiZipping shape - z = genMultiZipping shape arbitrary :: Gen (MultiZipping f Bool Int) - zf = genMultiZipping shape (applyFun <$> arbitrary) - :: Gen (MultiZipping f Bool (Int -> Int)) - ze = genMultiZipping shape arbitrary - :: Gen (MultiZipping f (Either Bool ()) (Either Int ())) + obs :: Finite s => Zipporah (->) f Maybe s t -> [Maybe t] + obs = zipping shape + z = genZipping shape arbitrary :: Gen (Zipporah (->) f Maybe Bool Int) + zf = genZipping shape (applyFun <$> arbitrary) + :: Gen (Zipporah (->) f Maybe Bool (Int -> Int)) + ze = genZipping shape arbitrary + :: Gen (Zipporah (->) f Maybe (Either Bool ()) (Either Int ())) + zb = genZipping shape arbitrary :: Gen (Zipporah (->) f Maybe Bool Bool) + kleisli = (\(k0, k1) b -> if b then k0 else k1) <$> ((,) <$> zb <*> zb) + 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 "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 "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)) prop "zeroP >+< p = lunit p" $ forAllBlind z $ \p -> obs (zeroP >+< p) === obs (lunit p) prop "p >+< zeroP = runit p" $ forAllBlind z $ \p -> @@ -108,126 +119,84 @@ multiZippingLaws name shape = describe ("MultiZipping " <> name) $ do forAllBlind z $ \p -> forAllBlind z $ \q -> forAllBlind z $ \r -> obs (p >+< q >+< r) === obs (dimap unassocE assocE ((p >+< q) >+< r)) prop "rmap Left = lmap Left . left'" $ forAllBlind z $ \p -> - obs (rmap Left p :: MultiZipping f Bool (Either Int ())) + obs (rmap Left p :: Zipporah (->) f Maybe Bool (Either Int ())) === obs (lmap Left (left' p)) prop "left' = dimap swapE swapE . right'" $ forAllBlind z $ \p -> - obs (left' p :: MultiZipping f (Either Bool ()) (Either Int ())) + obs (left' p :: Zipporah (->) f Maybe (Either Bool ()) (Either Int ())) === obs (dimap swapE swapE (right' p)) prop "left' . left' = dimap assocE unassocE . left'" $ forAllBlind z $ \p -> obs (left' (left' p) - :: MultiZipping f (Either (Either Bool ()) ()) (Either (Either Int ()) ())) + :: Zipporah (->) f Maybe (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 (genZipping shape (Left <$> arbitrary) + :: Gen (Zipporah (->) f Maybe Bool (Either Int Void))) $ \p -> + obs (rmap (either id absurd) p) + === obs (unleft (lmap (either id absurd) p) :: Zipporah (->) f Maybe Bool 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)) -type C = Counting Bool () -type Z = Zipping Bool Int homogeneousProperties :: Spec homogeneousProperties = do - describe "Counting" $ do - let c = genCounting :: Gen C - prop "pure id <*> v = v" $ forAllBlind c $ \v -> - counting (pure id <*> v) === counting v - prop "pure (.) <*> u <*> v <*> w = u <*> (v <*> w)" $ - forAllBlind c $ \u -> forAllBlind c $ \v -> forAllBlind c $ \w -> - counting (pure (.) <*> (id <$ u) <*> (id <$ v) <*> w) - === counting ((id <$ u) <*> ((id <$ v) <*> w)) - prop "u <*> pure y = pure ($ y) <*> u" $ forAllBlind c $ \u -> - counting ((id <$ u) <*> pure ()) === counting (pure ($ ()) <*> (id <$ u)) - prop "zeroP >+< p = lunit p" $ forAllBlind c $ \p -> - counting (zeroP >+< p) === counting (lunit p) - prop "p >+< zeroP = runit p" $ forAllBlind c $ \p -> - counting (p >+< zeroP) === counting (runit p) - prop "p >+< q >+< r = assoc ((p >+< q) >+< r)" $ - forAllBlind c $ \p -> forAllBlind c $ \q -> forAllBlind c $ \r -> - counting (p >+< q >+< r) - === counting (dimap unassocE assocE ((p >+< q) >+< r)) - let ce = genCounting :: Gen (Counting (Either Bool ()) (Either () ())) - prop "unleft = unright . dimap swapE swapE" $ forAllBlind ce $ \p -> - counting (unleft p) === counting (unright (dimap swapE swapE p)) - prop "rmap (either id absurd) = unleft . lmap (either id absurd)" $ - forAllBlind (genCounting :: Gen (Counting Bool (Either () Void))) $ \p -> - counting (rmap (either id absurd) p) - === counting (unleft (lmap (either id absurd) p) :: C) - describe "Zipping" $ do - let z = genZipping arbitrary :: Gen Z - zf = genZipping (applyFun <$> arbitrary) - :: Gen (Zipping Bool (Int -> Int)) - prop "pure id <*> v = v" $ forAllBlind z $ \v -> - zipping (pure id <*> v) === zipping v + describe "Indexing" $ do + let ix = genIndexing arbitrary :: Gen (Indexing Bool Int) + ixf = genIndexing (applyFun <$> arbitrary) + :: Gen (Indexing Bool (Int -> Int)) + prop "pure id <*> v = v" $ forAllBlind ix $ \v -> + indexing (pure id <*> v) === indexing v prop "pure (.) <*> u <*> v <*> w = u <*> (v <*> w)" $ - forAllBlind zf $ \u -> forAllBlind zf $ \v -> forAllBlind z $ \w -> - zipping (pure (.) <*> u <*> v <*> w) === zipping (u <*> (v <*> w)) - prop "pure f <*> pure x = pure (f x)" $ \(Fun _ f) (x :: Int) -> - zipping (pure f <*> pure x :: Z) === zipping (pure (f x) :: Z) - prop "u <*> pure y = pure ($ y) <*> u" $ forAllBlind zf $ \u (y :: Int) -> - zipping (u <*> pure y) === zipping (pure ($ y) <*> u) - prop "empty <|> x = x = x <|> empty" $ forAllBlind z $ \x -> - zipping (empty <|> x) === zipping x .&&. zipping (x <|> empty) === zipping x - prop "(x <|> y) <|> w = x <|> (y <|> w)" $ - forAllBlind z $ \x -> forAllBlind z $ \y -> forAllBlind z $ \w -> - zipping ((x <|> y) <|> w) === zipping (x <|> (y <|> w)) - let zb = genZipping arbitrary :: Gen (Zipping Bool Bool) - kleisli = (\f t -> if t then fst f else snd f) <$> ((,) <$> zb <*> zb) - prop "pure a >>= k = k a" $ forAllBlind kleisli $ \k a -> - zipping (pure a >>= k) === zipping (k a) - prop "m >>= pure = m" $ forAllBlind zb $ \m -> - zipping (m >>= pure) === zipping m - prop "(m >>= k) >>= h = m >>= (\\x -> k x >>= h)" $ - forAllBlind zb $ \m -> forAllBlind kleisli $ \k -> forAllBlind kleisli $ \h -> - zipping ((m >>= k) >>= h) === zipping (m >>= (\x -> k x >>= h)) - prop "zeroP >+< p = lunit p" $ forAllBlind z $ \p -> - zipping (zeroP >+< p) === zipping (lunit p) - prop "p >+< zeroP = runit p" $ forAllBlind z $ \p -> - zipping (p >+< zeroP) === zipping (runit p) + forAllBlind ixf $ \u -> forAllBlind ixf $ \v -> forAllBlind ix $ \w -> + indexing (pure (.) <*> u <*> v <*> w) === indexing (u <*> (v <*> w)) + prop "u <*> pure y = pure ($ y) <*> u" $ forAllBlind ixf $ \u (y :: Int) -> + indexing (u <*> pure y) === indexing (pure ($ y) <*> u) + prop "zeroP >+< p = lunit p" $ forAllBlind ix $ \p -> + indexing (zeroP >+< p) === indexing (lunit p) + prop "p >+< zeroP = runit p" $ forAllBlind ix $ \p -> + indexing (p >+< zeroP) === indexing (runit p) prop "p >+< q >+< r = assoc ((p >+< q) >+< r)" $ - forAllBlind z $ \p -> forAllBlind z $ \q -> forAllBlind z $ \r -> - zipping (p >+< q >+< r) - === zipping (dimap unassocE assocE ((p >+< q) >+< r)) - prop "rmap Left = lmap Left . left'" $ forAllBlind z $ \p -> - zipping (rmap Left p :: Zipping Bool (Either Int ())) - === zipping (lmap Left (left' p)) - prop "left' = dimap swapE swapE . right'" $ forAllBlind z $ \p -> - zipping (left' p :: Zipping (Either Bool ()) (Either Int ())) - === zipping (dimap swapE swapE (right' p)) - prop "left' . left' = dimap assocE unassocE . left'" $ forAllBlind z $ \p -> - zipping (left' (left' p) :: Zipping (Either (Either Bool ()) ()) (Either (Either Int ()) ())) - === zipping (dimap assocE unassocE (left' p)) - let ze = genZipping arbitrary - :: Gen (Zipping (Either Bool ()) (Either Int ())) - prop "unleft = unright . dimap swapE swapE" $ forAllBlind ze $ \p -> - zipping (unleft p) === zipping (unright (dimap swapE swapE p)) + forAllBlind ix $ \p -> forAllBlind ix $ \q -> forAllBlind ix $ \r -> + indexing (p >+< q >+< r) + === indexing (dimap unassocE assocE ((p >+< q) >+< r)) + prop "unleft = unright . dimap swapE swapE" $ + forAllBlind (genIndexing arbitrary + :: Gen (Indexing (Either Bool ()) (Either Int ()))) $ \p -> + indexing (unleft p) === indexing (unright (dimap swapE swapE p)) prop "rmap (either id absurd) = unleft . lmap (either id absurd)" $ - forAllBlind (genZipping (Left <$> arbitrary) - :: Gen (Zipping Bool (Either Int Void))) $ \p -> - zipping (rmap (either id absurd) p) - === zipping (unleft (lmap (either id absurd) p) :: Z) - prop "left' = alternate . Left" $ forAllBlind z $ \p -> - zipping (left' p :: Zipping (Either Bool ()) (Either Int ())) - === zipping (alternate (Left p) :: Zipping (Either Bool ()) (Either Int ())) - prop "x >+< y = alternate (Left x) >|< alternate (Right y)" $ - forAllBlind z $ \x -> forAllBlind z $ \y -> - zipping (x >+< y) - === zipping (alternate (Left x) >|< alternate (Right y)) - multiZippingLaws "of no sources" Proxy - multiZippingLaws "of two sources" (Two () ()) - multiZippingLaws "of three sources" (Three () () ()) + forAllBlind (genIndexing (Left <$> arbitrary) + :: Gen (Indexing Bool (Either Int Void))) $ \p -> + indexing (rmap (either id absurd) p) + === indexing (unleft (lmap (either id absurd) p) :: Indexing Bool Int) + zippingLaws "of no sources" Proxy + zippingLaws "of two sources" (Par1 () :*: Par1 ()) + zippingLaws "of three sources" (Par1 () :*: Par1 () :*: Par1 ()) describe "Enumerable & Homogeneous" $ do it "numbers copies left to right" $ - map indexEnumerable [False1 (), True1 ()] `shouldBe` [0, 1] + map fromEnumerable [(LT, ()), (EQ, ()), (GT, ())] `shouldBe` [0, 1, 2] + prop "toEnumerable inverts fromEnumerable" $ \(c :: Char) -> + map (toEnumerable c) [0 .. 3] + === map Just [(LT, c), (EQ, c), (GT, c)] <> [Nothing :: Maybe (Ordering, Char)] + .&&. fmap fromEnumerable (toEnumerable c 2 :: Maybe (Ordering, Char)) + === Just 2 + prop "fromEnumerable is fromEnum, from minBound" $ \(e :: Int8) (c :: Char) -> + fromEnumerable (e, c) + === fromIntegral (fromEnum e - fromEnum (minBound :: Int8)) + prop "succEnumerable is succ, but at maxBound" $ \(e :: Ordering) (c :: Char) -> + succEnumerable (e, c) + === if e == maxBound then Nothing else Just (succ e, c) + prop "predEnumerable is pred, but at minBound" $ \(e :: Int8) (c :: Char) -> + predEnumerable (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 "MultiZipping of two is Zipping" $ - \(Fun _ f) (xs :: [Int]) (ys :: [Int]) -> - multiZipWith (\(Two x y) -> f (x, y) :: Int) (Two xs ys) - === zipWithHomogeneous (curry f) xs ys 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 @@ -235,9 +204,16 @@ homogeneousProperties = do 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" $ - multiZipWith (\Proxy -> 'a') (Proxy :: Proxy (Maybe Char)) + zipHomogeneous (\Proxy -> Just 'a') (Proxy :: Proxy (Maybe Char)) `shouldBe` Just (Just 'a') - where - multiZipWith - :: (Homogeneous t, Traversable f) => (f a -> b) -> f (t a) -> Maybe (t b) - multiZipWith f = runMultiZipping (homogeneously (MultiZipping (Just . f))) + 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 ) From 0d31de3da2dc13d49db670f4e55a27ef116a79a9 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sat, 7 Nov 2026 12:19:45 -0800 Subject: [PATCH 042/130] Drop jsonNumberKey: type number keys as strings jsonNumberKey was a JsonStr method whose only purpose was TypeScript: every runtime interpreter used its default, id, and only JsonTypor turned it into JsonNumberKey, rendered as `${number}`. That put a TypeScript concern into the JsonStr algebra. Now integral & scientific keys are just subtypes of strings, which the translation widens to `string`, like every other JsonSubtype. Parsing & printing are unchanged. Index signatures are only `[key: string]`, which cover every named member, so the numeric pattern & its readScientific coverage check are gone. Co-Authored-By: Claude Opus 5.5 --- .../src/Control/Lens/Grammar/Json.hs | 51 ++++--------------- distributors-json/test/Properties/Json.hs | 6 +-- 2 files changed, 13 insertions(+), 44 deletions(-) diff --git a/distributors-json/src/Control/Lens/Grammar/Json.hs b/distributors-json/src/Control/Lens/Grammar/Json.hs index 10387741..7f1eb632 100644 --- a/distributors-json/src/Control/Lens/Grammar/Json.hs +++ b/distributors-json/src/Control/Lens/Grammar/Json.hs @@ -528,11 +528,6 @@ class prism' (indexArray names . indexOf) (`lookup` table) ?< jsonText where names = arrayFromList (map fst table) - {- | Strings of numbers, like an integral map key's, - like TypeScript's template literal type, @\`${number}\`@. - -} - jsonNumberKey :: p a a -> p a a - jsonNumberKey = id {- | `JsonTup` grammars describe the elements of a JSON array. As `Alternator`s they have optional elements (`optionalP`, `optionP`), @@ -1599,7 +1594,6 @@ data JsonType | JsonBoolean -- ^ @true@ or @false@ | JsonNumber -- ^ numbers | JsonString -- ^ strings - | JsonNumberKey JsonType -- ^ the strings of a type which are numbers, as keys | JsonStringLiteral Text -- ^ a string | JsonSubtype JsonType -- ^ some values of a type | JsonArray JsonElements -- ^ arrays of elements @@ -1815,11 +1809,6 @@ instance JsonStr JsonTypor where jsonText = typing JsonString jsonEnumWith _ table = typing (jsonUnion [JsonStringLiteral literal | (literal, _) <- table]) - jsonNumberKey (JsonTypor t) = JsonTypor (numberKey <$> t) - where - numberKey = \case - JsonUnion [] -> falseP - ty -> JsonNumberKey ty instance JsonVal JsonTypor where jsonNull = typing JsonNull jsonBool = typing JsonBoolean @@ -1979,7 +1968,6 @@ tsType rules names = typeNode JsonBoolean -> KeywordType BooleanKeyword JsonNumber -> KeywordType NumberKeyword JsonString -> KeywordType StringKeyword - JsonNumberKey t -> numberKey t JsonStringLiteral text -> LiteralType (TextLiteral text) JsonSubtype t -> typeNode t t@(JsonArray _) -> typeNode (JsonUnion [t]) @@ -1992,14 +1980,6 @@ tsType rules names = typeNode <> [typeNode t | t <- drop (length before) ts, not (isTuple t)] _ -> map typeNode ts isTuple = \case JsonArray _ -> True; _ -> False - numberKey t - | JsonString `elem` alternatives = union - [ if alt == JsonString then numberKeyString else typeNode alt - | alt <- alternatives ] - | otherwise = typeNode t - where - alternatives = typeAlternatives rules t - numberKeyString = TemplateLiteralType "" [(KeywordType NumberKeyword, "")] tuple = \case [RestElement t] -> ArrayType (operand (typeNode t)) els -> TupleType $ els <&> \case @@ -2007,7 +1987,7 @@ tsType rules names = typeNode OptionalElement t -> OptionalType (operand (typeNode t)) RestElement t -> RestType (ArrayType (operand (typeNode t))) -- The intersected parts of an object type: its named properties - -- & index signatures, of its string or number keys, & a mapped type + -- & 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 @@ -2026,22 +2006,14 @@ tsType rules names = typeNode [ (keyType, typeAlternatives rules keyType, t) | JsonDict keyType t <- props, t /= falseP ] indexSignatures = - [ IndexSignature [] "key" (typeNode pattern) $ union - (typeNode t : covered pattern) - | (_, keyAlternatives, t) <- dicts - , pattern <- take 1 - [ p | p <- [JsonString, JsonNumberKey JsonString] - , p `elem` keyAlternatives ] - ] - -- An index type also covers the named properties it matches, + [ 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 pattern = - [typeNode t | JsonProperty key _ t <- props, matches pattern key] - <> [ KeywordType UndefinedKeyword - | or [o | JsonProperty key o _ <- props, matches pattern key] ] - matches = \case - JsonNumberKey _ -> isJust . readScientific - _ -> const True + 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 @@ -2101,9 +2073,6 @@ typeAlternatives rules = go [] go (key : seen) t JsonUnion ts -> concatMap (go seen) ts JsonSubtype t -> go seen t - JsonNumberKey t -> - [ if alt == JsonString then JsonNumberKey JsonString else alt - | alt <- go seen t ] t -> [t] {- | Tuples of some shapes, as TypeScript types them. TypeScript requires @@ -2226,7 +2195,7 @@ readScientific t -- | `Scientific` map keys, as @aeson@ renders them. jsonScientificKey :: JsonStr p => p Scientific Scientific -jsonScientificKey = jsonNumberKey (prism' render readScientific ?< jsonText) +jsonScientificKey = prism' render readScientific ?< jsonText where render s | e < 0 || e > 1024 = Text.pack (formatScientific Generic Nothing s) @@ -2236,7 +2205,7 @@ jsonScientificKey = jsonNumberKey (prism' render readScientific ?< jsonText) -- | Integral map keys, as @aeson@ renders them. jsonIntKey :: (Show a, JsonStr p) => APrism' Scientific a -> p a a -jsonIntKey integral = jsonNumberKey $ jsonEncodedText $ prism shown $ \t -> +jsonIntKey integral = jsonEncodedText $ prism shown $ \t -> maybe (Left (t, Encoding.text t)) Right (readScientific t >>= preview (clonePrism integral)) where diff --git a/distributors-json/test/Properties/Json.hs b/distributors-json/test/Properties/Json.hs index 7594de3d..6e9f2101 100644 --- a/distributors-json/test/Properties/Json.hs +++ b/distributors-json/test/Properties/Json.hs @@ -298,13 +298,13 @@ jsonObjectSpec = describe "jsonObject" $ do ] roundTrip (object ["yes" .= (2 :: Int), "no" .= (1 :: Int)]) (Votes (2, [(False, 1)])) - it "types number keys as template literals" $ do + it "types number keys as strings" $ do declares (type (Box (Map Int Bool))) - [ "export type Box_Map_Int_Bool = { [key: `${number}`]: boolean };" + [ "export type Box_Map_Int_Bool = { [key: string]: boolean };" ] declares (type Scores) [ "export type Scores = \ - \{ name: string; [key: `${number}`]: boolean };" + \{ name: string; [key: string]: boolean | string };" ] it "types the rest of an object as an index signature" $ do declares (type Extra) From 742899762ce49c7fa41feaddf99038e3b4af0ab8 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sat, 7 Nov 2026 12:19:54 -0800 Subject: [PATCH 043/130] Run doctests with doctest-parallel, under cabal & stack MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Each package has a doctests suite, whose Main is mainFromCabal, which finds every module & its extensions in the .cabal file. This replaces the doctest harness in each test Main: the DISTRIBUTORS_RUN_DOCTESTS switch, the STACK_EXE & GHC_ENVIRONMENT special cases, & the copied lists of modules & language extensions. cabal.project writes GHC environment files, which doctest-parallel needs to find the built packages, so CI's cabal jobs now run doctests too, not just the stack job. Every module's examples now run, not just six modules', which needed: - laws written as `@prop> …@`, which doctest skips, rather than bare `prop>` equations, which it can't run; - `$setup` blocks importing the names examples use, since doctest-parallel scopes a module by its exports, not its imports; - fixes to examples which hadn't run before. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 6 +- .gitignore | 1 + cabal.project | 3 + distributors-core/distributors.cabal | 75 +++++++++++- distributors-core/doctest/Doctests.hs | 7 ++ distributors-core/package.yaml | 8 +- distributors-core/src/Control/Lens/Diopter.hs | 4 +- distributors-core/src/Control/Lens/Grammar.hs | 4 + .../src/Control/Lens/Grammar/BackusNaur.hs | 10 +- .../src/Control/Lens/Grammar/RegEx.hs | 22 ++-- .../src/Control/Lens/Grammar/Token.hs | 4 +- distributors-core/src/Control/Lens/Monocle.hs | 5 + .../src/Control/Lens/PartialIso.hs | 10 +- distributors-core/src/Control/Lens/Wither.hs | 2 +- .../src/Control/Monad/Fail/Try.hs | 8 +- .../src/Data/Monoid/Disjunctive.hs | 18 +-- .../src/Data/Profunctor/Distributor.hs | 14 +-- .../src/Data/Profunctor/Filtrator.hs | 12 +- .../src/Data/Profunctor/Monadic.hs | 4 +- .../src/Data/Profunctor/Monoidal.hs | 31 ++--- .../Data/Profunctor/Monoidal/Cocartesian.hs | 24 ++-- .../src/Data/Traversable/Homogeneous.hs | 7 +- distributors-core/test/Main.hs | 109 +++--------------- distributors-json/distributors-json.cabal | 80 ++++++++++++- distributors-json/doctest/Doctests.hs | 7 ++ distributors-json/package.yaml | 8 +- .../src/Control/Lens/Grammar/Json.hs | 2 + .../src/Control/Lens/Grammar/TypeScript.hs | 3 + distributors-json/test/Main.hs | 95 +++------------ 29 files changed, 320 insertions(+), 263 deletions(-) create mode 100644 distributors-core/doctest/Doctests.hs create mode 100644 distributors-json/doctest/Doctests.hs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5c27e09a..98216286 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -69,9 +69,7 @@ jobs: - name: Build run: stack build --test --bench --no-run-tests --no-run-benchmarks - - name: Test, with doctests - env: - DISTRIBUTORS_RUN_DOCTESTS: "1" + - name: Test run: stack test cabal: @@ -108,8 +106,6 @@ jobs: - name: Build run: cabal build all - # Doctests run in the stack job, since doctest needs the package - # environment, which stack provides to test suites but cabal doesn't. - name: Test run: cabal test all --test-show-details=direct diff --git a/.gitignore b/.gitignore index 7b4c9fb4..f866aee4 100644 --- a/.gitignore +++ b/.gitignore @@ -25,3 +25,4 @@ tags .*.swp .qodo SCRATCH* +.ghc.environment.* diff --git a/cabal.project b/cabal.project index c70e7b0a..e33fe951 100644 --- a/cabal.project +++ b/cabal.project @@ -4,3 +4,6 @@ packages: 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/distributors.cabal b/distributors-core/distributors.cabal index 519bd7d7..d8902025 100644 --- a/distributors-core/distributors.cabal +++ b/distributors-core/distributors.cabal @@ -122,6 +122,80 @@ library , 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: + MemoTrie >=0.6 && <1 + , QuickCheck >=2.14 && <3 + , adjunctions >=4.4 && <5 + , base >=4.15 && <5 + , bifunctors >=5.5 && <6 + , bytestring >=0.11 && <1 + , containers >=0.6 && <1 + , contravariant >=1.5 && <2 + , distributive >=0.6 && <1 + , distributors + , 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 + , tagged >=0.8 && <1 + , template-haskell >=2.17 && <3 + , text ==2.* + , th-abstraction >=0.4 && <1 + , transformers >=0.5 && <1 + , vector >=0.12 && <1 + , witherable >=0.4 && <1 + default-language: Haskell2010 + test-suite test type: exitcode-stdio-1.0 main-is: Main.hs @@ -192,7 +266,6 @@ test-suite test , contravariant >=1.5 && <2 , distributive >=0.6 && <1 , distributors - , doctest >=0.18 && <1 , hspec >=2.7 && <3 , lens >=5.0 && <6 , megaparsec >=9.0 && <10 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/distributors-core/package.yaml b/distributors-core/package.yaml index 4319745c..ed7c9d18 100644 --- a/distributors-core/package.yaml +++ b/distributors-core/package.yaml @@ -94,12 +94,18 @@ 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/Diopter.hs b/distributors-core/src/Control/Lens/Diopter.hs index bea153d4..4e643ff4 100644 --- a/distributors-core/src/Control/Lens/Diopter.hs +++ b/distributors-core/src/Control/Lens/Diopter.hs @@ -80,8 +80,8 @@ manied = unwrapPafb . manyP . WrapPafb {- | Build a `Diopter` from a `Homogeneous` countable sum of countable products. -prop> traverse = homogenized -prop> homogenized = ditraversed +@prop> traverse = homogenized@ +@prop> homogenized = ditraversed@ -} homogenized :: Homogeneous t => Diopter (t a) (t b) a b homogenized = unwrapPafb . homogeneously . WrapPafb diff --git a/distributors-core/src/Control/Lens/Grammar.hs b/distributors-core/src/Control/Lens/Grammar.hs index 98d20b44..f9b162de 100644 --- a/distributors-core/src/Control/Lens/Grammar.hs +++ b/distributors-core/src/Control/Lens/Grammar.hs @@ -86,6 +86,10 @@ import Data.Profunctor.Monoidal as X import Data.Profunctor.Separator as X import Data.Traversable.Homogeneous as X +-- $setup +-- >>> import Data.String (fromString) +-- >>> import GHC.Exts (toList) + {- | A regular grammar may be constructed using `Lexical` and `Alternator` combinators. diff --git a/distributors-core/src/Control/Lens/Grammar/BackusNaur.hs b/distributors-core/src/Control/Lens/Grammar/BackusNaur.hs index 9a02b106..b4b86dab 100644 --- a/distributors-core/src/Control/Lens/Grammar/BackusNaur.hs +++ b/distributors-core/src/Control/Lens/Grammar/BackusNaur.hs @@ -39,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". @@ -52,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. @@ -81,7 +81,7 @@ and a set of named rules. When a `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 @@ -109,7 +109,7 @@ The [Brzozowski derivative] (https://dl.acm.org/doi/pdf/10.1145/321239.321249) of a `RegEx`tended `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. diff --git a/distributors-core/src/Control/Lens/Grammar/RegEx.hs b/distributors-core/src/Control/Lens/Grammar/RegEx.hs index 0f0ba61a..6ef1d95d 100644 --- a/distributors-core/src/Control/Lens/Grammar/RegEx.hs +++ b/distributors-core/src/Control/Lens/Grammar/RegEx.hs @@ -88,13 +88,13 @@ data CategoryTest token {- | `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 +@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@ `TokenClass` is the fixed point algebra of t`RegExam`. `TokenClass`es may be understood as normalizations of @@ -108,13 +108,13 @@ newtype TokenClass token = TokenClass (RegExam token (TokenClass token)) 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) +@prop> falseP = tokenClass falseP@ +@prop> tokenClass x >|< tokenClass y = tokenClass (x >|< y)@ Likewise, when a `TokenAlgebra` is `Alternative`, -prop> empty = tokenClass falseP -prop> tokenClass x <|> tokenClass y = tokenClass (x >|< y) +@prop> empty = tokenClass falseP@ +@prop> tokenClass x <|> tokenClass y = tokenClass (x >|< y)@ -} class Tokenized token p => TokenAlgebra token p where diff --git a/distributors-core/src/Control/Lens/Grammar/Token.hs b/distributors-core/src/Control/Lens/Grammar/Token.hs index 5ad21da5..b2e2675d 100644 --- a/distributors-core/src/Control/Lens/Grammar/Token.hs +++ b/distributors-core/src/Control/Lens/Grammar/Token.hs @@ -72,7 +72,7 @@ class Categorized token => Tokenized token p | p -> token where {- | A single token which is `oneOf` a set. - prop> token x = oneOf [x] + @prop> token x = oneOf [x]@ -} oneOf :: Foldable f => f token -> p @@ -83,7 +83,7 @@ class Categorized token => Tokenized token p | p -> token where {- | A single token which is `notOneOf` a set. - prop> anyToken = notOneOf [] + @prop> anyToken = notOneOf []@ -} notOneOf :: Foldable f => f token -> p diff --git a/distributors-core/src/Control/Lens/Monocle.hs b/distributors-core/src/Control/Lens/Monocle.hs index 8665d90d..77a6fb66 100644 --- a/distributors-core/src/Control/Lens/Monocle.hs +++ b/distributors-core/src/Control/Lens/Monocle.hs @@ -53,6 +53,11 @@ import Data.Void (Void, absurd) import GHC.Generics (Par1 (..), V1, (:+:) (..), (:*:) (..)) import Numeric.Natural (Natural) +-- $setup +-- >>> import Control.Lens +-- >>> import Data.Complex +-- >>> import Data.Functor.Identity + -- $setup -- >>> import Data.Complex diff --git a/distributors-core/src/Control/Lens/PartialIso.hs b/distributors-core/src/Control/Lens/PartialIso.hs index 7b609d3f..2e8ec43c 100644 --- a/distributors-core/src/Control/Lens/PartialIso.hs +++ b/distributors-core/src/Control/Lens/PartialIso.hs @@ -96,18 +96,18 @@ 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 +@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 +@prop> Just = f <=< g@ For an improper `PartialIso'`, @norm = g <=< f@ is an idempotent -prop> norm = norm <=< norm +@prop> norm = norm <=< norm@ and can be regarded as a normalization within some equivalence class of terms. @@ -242,7 +242,7 @@ missing exactly when it's the default, like `Data.Aeson.!=`, by the `non` isomorphism. -prop> optP != def = non def ~< optP +@prop> optP != def = non def ~< optP@ -} (!=) :: (Eq a, Profunctor q) diff --git a/distributors-core/src/Control/Lens/Wither.hs b/distributors-core/src/Control/Lens/Wither.hs index 7b5d7c59..37bf5b00 100644 --- a/distributors-core/src/Control/Lens/Wither.hs +++ b/distributors-core/src/Control/Lens/Wither.hs @@ -68,7 +68,7 @@ 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) diff --git a/distributors-core/src/Control/Monad/Fail/Try.hs b/distributors-core/src/Control/Monad/Fail/Try.hs index 48fa94a3..122f61a2 100644 --- a/distributors-core/src/Control/Monad/Fail/Try.hs +++ b/distributors-core/src/Control/Monad/Fail/Try.hs @@ -32,14 +32,14 @@ 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 diff --git a/distributors-core/src/Data/Monoid/Disjunctive.hs b/distributors-core/src/Data/Monoid/Disjunctive.hs index 3616103d..78428f4c 100644 --- a/distributors-core/src/Data/Monoid/Disjunctive.hs +++ b/distributors-core/src/Data/Monoid/Disjunctive.hs @@ -53,8 +53,8 @@ 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) +@prop> falseP >|< x = x = x >|< falseP@ +@prop> (x >|< y) >|< z = x >|< (y >|< z)@ -} class DisjunctiveMonoid a where @@ -114,24 +114,24 @@ 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 +@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 +@prop> optK x = mempty >|< x = x >|< mempty@ * `plusK`, one or more, -prop> plusK x = x <> starK x = starK x <> x +@prop> plusK x = x <> starK x = starK x <> x@ * and the eponymous `starK`, zero or more. -prop> starK x = optK (plusK x) +@prop> starK x = optK (plusK x)@ -} class (Monoid k, DisjunctiveMonoid k) => KleeneStarAlgebra k where diff --git a/distributors-core/src/Data/Profunctor/Distributor.hs b/distributors-core/src/Data/Profunctor/Distributor.hs index d4118279..d6260142 100644 --- a/distributors-core/src/Data/Profunctor/Distributor.hs +++ b/distributors-core/src/Data/Profunctor/Distributor.hs @@ -111,17 +111,17 @@ instance Distributor p => Distributor (Coyoneda p) where 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 +@prop> manyP p = optionP _Empty (someP p)@ +@prop> optionalP p = optionP _Nothing (_Just >? p)@ +@prop> someP p = p >:< manyP p@ 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 +@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`, diff --git a/distributors-core/src/Data/Profunctor/Filtrator.hs b/distributors-core/src/Data/Profunctor/Filtrator.hs index b2c122c9..a5e667d4 100644 --- a/distributors-core/src/Data/Profunctor/Filtrator.hs +++ b/distributors-core/src/Data/Profunctor/Filtrator.hs @@ -32,21 +32,21 @@ as well as `Filterable`, adding the `filtrate` method, which is an oplax monoidal structure morphism dual to `>+<`. -prop> filtrate . uncurry (>+<) = id -prop> uncurry (>+<) . filtrate = id +@prop> filtrate . uncurry (>+<) = id@ +@prop> uncurry (>+<) . filtrate = id@ -} 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 = lmap Left . mapMaybe (either Just (const Nothing))@ + @prop> unright = snd . filtrate = 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,7 +65,7 @@ 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` diff --git a/distributors-core/src/Data/Profunctor/Monadic.hs b/distributors-core/src/Data/Profunctor/Monadic.hs index 69e8b191..6ea0fb2a 100644 --- a/distributors-core/src/Data/Profunctor/Monadic.hs +++ b/distributors-core/src/Data/Profunctor/Monadic.hs @@ -44,7 +44,7 @@ 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,7 +61,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 diff --git a/distributors-core/src/Data/Profunctor/Monoidal.hs b/distributors-core/src/Data/Profunctor/Monoidal.hs index 864e8528..b6137ad4 100644 --- a/distributors-core/src/Data/Profunctor/Monoidal.hs +++ b/distributors-core/src/Data/Profunctor/Monoidal.hs @@ -40,6 +40,10 @@ 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` @@ -52,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)) @@ -72,7 +76,7 @@ infixr 5 >*< {- | `>*` sequences actions, discarding the value of the first argument; analagous to `*>`, extending it to `Monoidal`. -prop> oneP >* p = p +@prop> oneP >* p = p@ -} (>*) :: Monoidal p => p () c -> p a b -> p a b @@ -82,7 +86,7 @@ infixl 6 >* {- | `*<` sequences actions, discarding the value of the second argument; analagous to `<*`, extending it to `Monoidal`. -prop> p *< oneP = p +@prop> p *< oneP = p@ -} (*<) :: Monoidal p => p a b -> p () c -> p a b @@ -174,8 +178,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) @@ -203,7 +208,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))) @@ -253,9 +258,9 @@ 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 +@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) @@ -263,7 +268,7 @@ 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 +@prop> arrP f = rmap f idP = lmap f idP@ -} arrP :: (Monoidal p, Strong p) => (a -> b) -> p a b arrP f = fmap f idP diff --git a/distributors-core/src/Data/Profunctor/Monoidal/Cocartesian.hs b/distributors-core/src/Data/Profunctor/Monoidal/Cocartesian.hs index 125faa1b..efa41a94 100644 --- a/distributors-core/src/Data/Profunctor/Monoidal/Cocartesian.hs +++ b/distributors-core/src/Data/Profunctor/Monoidal/Cocartesian.hs @@ -37,6 +37,10 @@ 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` @@ -54,10 +58,10 @@ let assoc = dimap (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 +@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 @@ -65,7 +69,7 @@ class Profunctor p => CocartesianMonoidal p where `zeroP` has a default for `CocartesianChoice`s. - prop> zeroP = falseP + @prop> zeroP = falseP@ -} zeroP :: p Void Void default zeroP :: CocartesianChoice p => p Void Void @@ -75,7 +79,7 @@ class Profunctor p => CocartesianMonoidal p where `>+<` has a default for `CocartesianChoice`s. - prop> x >+< y = alternate (Left x) >|< alternate (Right y) + @prop> x >+< y = alternate (Left x) >|< alternate (Right y)@ -} (>+<) :: p a b -> p c d -> p (Either a c) (Either b d) default (>+<) @@ -154,10 +158,10 @@ like `Alternative` but without requiring 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) +@prop> left' = alternate . Left@ +@prop> right' = alternate . Right@ +@prop> zeroP = falseP@ +@prop> x >+< y = alternate (Left x) >|< alternate (Right y)@ For the case of `Functor`s, the analog of `alternate` can be defined without any other constraint, but the case of `Profunctor`s turns diff --git a/distributors-core/src/Data/Traversable/Homogeneous.hs b/distributors-core/src/Data/Traversable/Homogeneous.hs index 4a7f7dc2..00c33e2f 100644 --- a/distributors-core/src/Data/Traversable/Homogeneous.hs +++ b/distributors-core/src/Data/Traversable/Homogeneous.hs @@ -312,10 +312,9 @@ fromEnumerable = {- | The copy of an `Enumerable` sum at an index, if there is one, like `toEnum`, the inverse of `fromEnumerable`. ->>> toEnumerable 'x' 1 :: Maybe (Ordering, Char) -Just (EQ,'x') ->>> toEnumerable 'x' 3 :: Maybe (Ordering, Char) -Nothing +>>> [toEnumerable 'x' i | i <- [0..3]] :: [Maybe (Ordering, Char)] +[Just (LT,'x'),Just (EQ,'x'),Just (GT,'x'),Nothing] + -} toEnumerable :: Enumerable f => a -> Natural -> Maybe (f a) toEnumerable a copy = diff --git a/distributors-core/test/Main.hs b/distributors-core/test/Main.hs index a9c4c7b2..30054e05 100644 --- a/distributors-core/test/Main.hs +++ b/distributors-core/test/Main.hs @@ -6,11 +6,8 @@ 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 @@ -28,29 +25,24 @@ import Properties.Homogeneous import Properties.Kleene 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 "Homogeneous" homogeneousProperties - 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 "Homogeneous" homogeneousProperties + describe "meander" meanderProperties parseForestTests :: Spec parseForestTests = do @@ -89,71 +81,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" - , "src/Data/Traversable/Homogeneous.hs" - , "src/Control/Lens/Monocle.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 diff --git a/distributors-json/distributors-json.cabal b/distributors-json/distributors-json.cabal index b4bba9d0..8c9df8c1 100644 --- a/distributors-json/distributors-json.cabal +++ b/distributors-json/distributors-json.cabal @@ -106,6 +106,85 @@ library , 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.15 && <5 + , bytestring >=0.11 && <1 + , containers >=0.6 && <1 + , data-fix >=0.3 && <1 + , distributors ==0.6.* + , 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 @@ -166,7 +245,6 @@ test-suite test , distributors ==0.6.* , distributors-json , dlist >=1.0 && <2 - , doctest >=0.18 && <1 , hashable >=1.4 && <2 , hspec >=2.7 && <3 , lens >=5.0 && <6 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 index b87452d4..0a0f3381 100644 --- a/distributors-json/package.yaml +++ b/distributors-json/package.yaml @@ -101,12 +101,18 @@ default-extensions: - 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 - - doctest >= 0.18 && < 1 - hspec >= 2.7 && < 3 - QuickCheck >= 2.14 && < 3 - quickcheck-instances >= 0.3 && < 1 diff --git a/distributors-json/src/Control/Lens/Grammar/Json.hs b/distributors-json/src/Control/Lens/Grammar/Json.hs index 7f1eb632..2478f2eb 100644 --- a/distributors-json/src/Control/Lens/Grammar/Json.hs +++ b/distributors-json/src/Control/Lens/Grammar/Json.hs @@ -251,6 +251,8 @@ 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) diff --git a/distributors-json/src/Control/Lens/Grammar/TypeScript.hs b/distributors-json/src/Control/Lens/Grammar/TypeScript.hs index df73cd73..77b99ab8 100644 --- a/distributors-json/src/Control/Lens/Grammar/TypeScript.hs +++ b/distributors-json/src/Control/Lens/Grammar/TypeScript.hs @@ -69,6 +69,9 @@ 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 diff --git a/distributors-json/test/Main.hs b/distributors-json/test/Main.hs index e5abcb15..852a7c90 100644 --- a/distributors-json/test/Main.hs +++ b/distributors-json/test/Main.hs @@ -1,91 +1,22 @@ module Main (main) where -import Control.Monad (when) -import Data.Foldable (for_) -import Data.Maybe (isJust) -import System.Environment (lookupEnv) -import Test.DocTest import Test.Hspec import Properties.Json import Properties.TypeScript main :: IO () -main = do - shouldRunDoctests <- isJust <$> lookupEnv "DISTRIBUTORS_RUN_DOCTESTS" - hspec $ do - when shouldRunDoctests $ - describe "doctest" $ - it "should run haddock examples" doctests - jsonTypeSpec - aesonSpec - jsonErrorSpec - jsonObjectSpec - jsonOptionsSpec - jsonTupleSpec - jsonTupleChoiceSpec - jsonOptionalSpec - jsonCodecSpec - jsonPrintSpec - jsonElementsSpec - typeScriptSpec +main = hspec $ do + jsonTypeSpec + aesonSpec + jsonErrorSpec + jsonObjectSpec + jsonOptionsSpec + jsonTupleSpec + jsonTupleChoiceSpec + jsonOptionalSpec + jsonCodecSpec + jsonPrintSpec + jsonElementsSpec + typeScriptSpec -doctests :: IO () -doctests = do - stackExe <- lookupEnv "STACK_EXE" - ghcEnvironment <- lookupEnv "GHC_ENVIRONMENT" - let - modulePaths = - [ "src/Control/Lens/Grammar/Json.hs" - , "src/Control/Lens/Grammar/TypeScript.hs" - ] - packageEnvFlags = case ghcEnvironment of - Just "-" -> [] - Just path -> ["-package-env=" <> path] - Nothing -> [] - runnerFlags - | isJust stackExe = [] - | otherwise = "-isrc" : packageEnvFlags - languageExtensions = - [ "-XHaskell2010" - , "-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) From 6d66ce922a01dc057205cb762029f15d86724a81 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sat, 7 Nov 2026 12:19:54 -0800 Subject: [PATCH 044/130] Test Zipporah's laws for profunctors & functors besides (->) & Maybe The law suite takes a Zipper, which observes & generates Zipporahs of a profunctor & a functor, & runs at (->) & Maybe, (->) & [], and Star of a writer & Maybe, each of no, two & three sources. It covers the laws up to Alternator: Profunctor, Applicative, Alternative, Filterable, CocartesianMonoidal (units, associativity & naturality), Choice, Cochoice & CocartesianChoice, & Monad for Maybe. Distributor & Alternator are their classes' defaults. Co-Authored-By: Claude Opus 5.5 --- .../test/Properties/Homogeneous.hs | 168 ++++++++++++++---- 1 file changed, 131 insertions(+), 37 deletions(-) diff --git a/distributors-core/test/Properties/Homogeneous.hs b/distributors-core/test/Properties/Homogeneous.hs index 80bc188d..577e05e9 100644 --- a/distributors-core/test/Properties/Homogeneous.hs +++ b/distributors-core/test/Properties/Homogeneous.hs @@ -8,12 +8,17 @@ module Properties.Homogeneous (homogeneousProperties) where import Control.Applicative +import Control.Arrow ((+++)) +import Control.Monad ((<=<)) +import Data.Functor.Compose (Compose (..)) import Data.Foldable (toList) 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 @@ -23,6 +28,7 @@ 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 @@ -68,35 +74,75 @@ unassocE = either (Left . Left) (either (Left . Right) Right) swapE :: Either a b -> Either b a swapE = either Right Left -zipping - :: (Traversable f, Finite s) => f () -> Zipporah (->) f Maybe s t -> [Maybe t] -zipping shape (Zipporah z) = map z (traverse (const universe) shape) +-- | All the sources of a shape, of a finite type. +sources :: (Traversable f, Finite s) => f () -> [f s] +sources shape = traverse (const universe) shape -genZipping - :: (Traversable f, Finite s) => f () -> Gen t -> Gen (Zipporah (->) f Maybe s t) -genZipping shape gen = do - let inputs = map toList (traverse (const universe) shape) - results <- vectorOf (length inputs) (liftArbitrary gen) - pure (Zipporah (\ss -> fromMaybe Nothing (lookup (toList ss) (zip inputs results)))) +-- | 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)) --- | The laws of `Zipporah` of functions & `Maybe`, of the sources of a shape. -zippingLaws :: forall f. Traversable f => String -> f () -> Spec -zippingLaws name shape = describe ("Zipporah " <> name) $ do +-- | 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 (->) f Maybe s t -> [Maybe t] - obs = zipping shape - z = genZipping shape arbitrary :: Gen (Zipporah (->) f Maybe Bool Int) - zf = genZipping shape (applyFun <$> arbitrary) - :: Gen (Zipporah (->) f Maybe Bool (Int -> Int)) - ze = genZipping shape arbitrary - :: Gen (Zipporah (->) f Maybe (Either Bool ()) (Either Int ())) - zb = genZipping shape arbitrary :: Gen (Zipporah (->) f Maybe Bool Bool) - kleisli = (\(k0, k1) b -> if b then k0 else k1) <$> ((,) <$> zb <*> zb) + 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 -> @@ -104,13 +150,12 @@ zippingLaws name shape = describe ("Zipporah " <> name) $ do 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 "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)) + 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 -> @@ -118,27 +163,78 @@ zippingLaws name shape = describe ("Zipporah " <> name) $ do 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 (->) f Maybe Bool (Either Int ())) + 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 (->) f Maybe (Either Bool ()) (Either Int ())) + 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 (->) f Maybe (Either (Either Bool ()) ()) (Either (Either Int ()) ())) + :: 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 (genZipping shape (Left <$> arbitrary) - :: Gen (Zipporah (->) f Maybe Bool (Either Int Void))) $ \p -> + 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 (->) f Maybe Bool Int) + === 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 @@ -170,9 +266,7 @@ homogeneousProperties = do :: Gen (Indexing Bool (Either Int Void))) $ \p -> indexing (rmap (either id absurd) p) === indexing (unleft (lmap (either id absurd) p) :: Indexing Bool Int) - zippingLaws "of no sources" Proxy - zippingLaws "of two sources" (Par1 () :*: Par1 ()) - zippingLaws "of three sources" (Par1 () :*: Par1 () :*: Par1 ()) + zipporahLaws describe "Enumerable & Homogeneous" $ do it "numbers copies left to right" $ map fromEnumerable [(LT, ()), (EQ, ()), (GT, ())] `shouldBe` [0, 1, 2] From 9ccd6c331aa2956128c9da99b520fc9ae3bf178c Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sat, 7 Nov 2026 12:28:31 -0800 Subject: [PATCH 045/130] bird is the word --- distributors-core/src/Control/Lens/Diopter.hs | 4 +-- .../src/Control/Lens/Grammar/BackusNaur.hs | 10 +++---- .../src/Control/Lens/Grammar/RegEx.hs | 22 ++++++++-------- .../src/Control/Lens/Grammar/Token.hs | 4 +-- distributors-core/src/Control/Lens/Monocle.hs | 4 +-- .../src/Control/Lens/PartialIso.hs | 10 +++---- distributors-core/src/Control/Lens/Wither.hs | 2 +- .../src/Control/Monad/Fail/Try.hs | 8 +++--- .../src/Data/Monoid/Disjunctive.hs | 18 ++++++------- .../src/Data/Profunctor/Distributor.hs | 14 +++++----- .../src/Data/Profunctor/Filtrator.hs | 13 +++++----- .../src/Data/Profunctor/Monadic.hs | 4 +-- .../src/Data/Profunctor/Monoidal.hs | 26 +++++++++---------- .../Data/Profunctor/Monoidal/Cocartesian.hs | 20 +++++++------- .../src/Data/Profunctor/Separator.hs | 4 +-- .../src/Data/Traversable/Homogeneous.hs | 10 +++---- 16 files changed, 87 insertions(+), 86 deletions(-) diff --git a/distributors-core/src/Control/Lens/Diopter.hs b/distributors-core/src/Control/Lens/Diopter.hs index 4e643ff4..c0563a6a 100644 --- a/distributors-core/src/Control/Lens/Diopter.hs +++ b/distributors-core/src/Control/Lens/Diopter.hs @@ -80,8 +80,8 @@ manied = unwrapPafb . manyP . WrapPafb {- | Build a `Diopter` from a `Homogeneous` countable sum of countable products. -@prop> traverse = homogenized@ -@prop> homogenized = ditraversed@ +> prop> traverse = homogenized +> prop> homogenized = ditraversed -} homogenized :: Homogeneous t => Diopter (t a) (t b) a b homogenized = unwrapPafb . homogeneously . WrapPafb diff --git a/distributors-core/src/Control/Lens/Grammar/BackusNaur.hs b/distributors-core/src/Control/Lens/Grammar/BackusNaur.hs index b4b86dab..f20d01b8 100644 --- a/distributors-core/src/Control/Lens/Grammar/BackusNaur.hs +++ b/distributors-core/src/Control/Lens/Grammar/BackusNaur.hs @@ -39,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". @@ -52,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. @@ -81,7 +81,7 @@ and a set of named rules. When a `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 @@ -109,7 +109,7 @@ The [Brzozowski derivative] (https://dl.acm.org/doi/pdf/10.1145/321239.321249) of a `RegEx`tended `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. diff --git a/distributors-core/src/Control/Lens/Grammar/RegEx.hs b/distributors-core/src/Control/Lens/Grammar/RegEx.hs index 6ef1d95d..c06c064c 100644 --- a/distributors-core/src/Control/Lens/Grammar/RegEx.hs +++ b/distributors-core/src/Control/Lens/Grammar/RegEx.hs @@ -88,13 +88,13 @@ data CategoryTest token {- | `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@ +> 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 `TokenClass` is the fixed point algebra of t`RegExam`. `TokenClass`es may be understood as normalizations of @@ -108,13 +108,13 @@ newtype TokenClass token = TokenClass (RegExam token (TokenClass token)) 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)@ +> prop> falseP = tokenClass falseP +> prop> tokenClass x >|< tokenClass y = tokenClass (x >|< y) Likewise, when a `TokenAlgebra` is `Alternative`, -@prop> empty = tokenClass falseP@ -@prop> tokenClass x <|> tokenClass y = tokenClass (x >|< y)@ +> prop> empty = tokenClass falseP +> prop> tokenClass x <|> tokenClass y = tokenClass (x >|< y) -} class Tokenized token p => TokenAlgebra token p where diff --git a/distributors-core/src/Control/Lens/Grammar/Token.hs b/distributors-core/src/Control/Lens/Grammar/Token.hs index b2e2675d..a5c922a6 100644 --- a/distributors-core/src/Control/Lens/Grammar/Token.hs +++ b/distributors-core/src/Control/Lens/Grammar/Token.hs @@ -72,7 +72,7 @@ class Categorized token => Tokenized token p | p -> token where {- | A single token which is `oneOf` a set. - @prop> token x = oneOf [x]@ + > prop> token x = oneOf [x] -} oneOf :: Foldable f => f token -> p @@ -83,7 +83,7 @@ class Categorized token => Tokenized token p | p -> token where {- | A single token which is `notOneOf` a set. - @prop> anyToken = notOneOf []@ + > prop> anyToken = notOneOf [] -} notOneOf :: Foldable f => f token -> p diff --git a/distributors-core/src/Control/Lens/Monocle.hs b/distributors-core/src/Control/Lens/Monocle.hs index 77a6fb66..29333464 100644 --- a/distributors-core/src/Control/Lens/Monocle.hs +++ b/distributors-core/src/Control/Lens/Monocle.hs @@ -117,8 +117,8 @@ crossMonocle x y p = {- | Build a `Monocle` from a `Traversable` & `Distributive`, homogeneous, countable product. -@prop> traverse = ditraversed@ -@prop> cotraversed = ditraversed@ +> prop> traverse = ditraversed +> prop> cotraversed = ditraversed -} ditraversed :: (Traversable g, Distributive g) => Monocle (g a) (g b) a b ditraversed = unwrapPafb . ditraverse . WrapPafb diff --git a/distributors-core/src/Control/Lens/PartialIso.hs b/distributors-core/src/Control/Lens/PartialIso.hs index 2e8ec43c..3ab2f1bb 100644 --- a/distributors-core/src/Control/Lens/PartialIso.hs +++ b/distributors-core/src/Control/Lens/PartialIso.hs @@ -96,18 +96,18 @@ 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@ +> 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@ +> prop> Just = f <=< g For an improper `PartialIso'`, @norm = g <=< f@ is an idempotent -@prop> norm = norm <=< norm@ +> prop> norm = norm <=< norm and can be regarded as a normalization within some equivalence class of terms. @@ -242,7 +242,7 @@ missing exactly when it's the default, like `Data.Aeson.!=`, by the `non` isomorphism. -@prop> optP != def = non def ~< optP@ +> prop> optP != def = non def ~< optP -} (!=) :: (Eq a, Profunctor q) diff --git a/distributors-core/src/Control/Lens/Wither.hs b/distributors-core/src/Control/Lens/Wither.hs index 37bf5b00..67f14dc7 100644 --- a/distributors-core/src/Control/Lens/Wither.hs +++ b/distributors-core/src/Control/Lens/Wither.hs @@ -68,7 +68,7 @@ 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) diff --git a/distributors-core/src/Control/Monad/Fail/Try.hs b/distributors-core/src/Control/Monad/Fail/Try.hs index 122f61a2..6167a921 100644 --- a/distributors-core/src/Control/Monad/Fail/Try.hs +++ b/distributors-core/src/Control/Monad/Fail/Try.hs @@ -32,14 +32,14 @@ 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 diff --git a/distributors-core/src/Data/Monoid/Disjunctive.hs b/distributors-core/src/Data/Monoid/Disjunctive.hs index 78428f4c..e9dbab4b 100644 --- a/distributors-core/src/Data/Monoid/Disjunctive.hs +++ b/distributors-core/src/Data/Monoid/Disjunctive.hs @@ -53,8 +53,8 @@ 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)@ +> prop> falseP >|< x = x = x >|< falseP +> prop> (x >|< y) >|< z = x >|< (y >|< z) -} class DisjunctiveMonoid a where @@ -114,24 +114,24 @@ 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@ +> 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@ +> prop> optK x = mempty >|< x = x >|< mempty * `plusK`, one or more, -@prop> plusK x = x <> starK x = starK x <> x@ +> prop> plusK x = x <> starK x = starK x <> x * and the eponymous `starK`, zero or more. -@prop> starK x = optK (plusK x)@ +> prop> starK x = optK (plusK x) -} class (Monoid k, DisjunctiveMonoid k) => KleeneStarAlgebra k where diff --git a/distributors-core/src/Data/Profunctor/Distributor.hs b/distributors-core/src/Data/Profunctor/Distributor.hs index d6260142..d39b7daf 100644 --- a/distributors-core/src/Data/Profunctor/Distributor.hs +++ b/distributors-core/src/Data/Profunctor/Distributor.hs @@ -111,17 +111,17 @@ instance Distributor p => Distributor (Coyoneda p) where 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@ +> prop> manyP p = optionP _Empty (someP p) +> prop> optionalP p = optionP _Nothing (_Just >? p) +> prop> someP p = p >:< manyP p 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@ +> 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`, diff --git a/distributors-core/src/Data/Profunctor/Filtrator.hs b/distributors-core/src/Data/Profunctor/Filtrator.hs index a5e667d4..83b34231 100644 --- a/distributors-core/src/Data/Profunctor/Filtrator.hs +++ b/distributors-core/src/Data/Profunctor/Filtrator.hs @@ -32,21 +32,21 @@ as well as `Filterable`, adding the `filtrate` method, which is an oplax monoidal structure morphism dual to `>+<`. -@prop> filtrate . uncurry (>+<) = id@ -@prop> uncurry (>+<) . filtrate = id@ +> prop> filtrate . uncurry (>+<) = id +> prop> uncurry (>+<) . filtrate = id -} 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 = lmap Left . mapMaybe (either Just (const Nothing)) + > prop> unright = snd . filtrate = 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,7 +65,8 @@ 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` diff --git a/distributors-core/src/Data/Profunctor/Monadic.hs b/distributors-core/src/Data/Profunctor/Monadic.hs index 6ea0fb2a..beb78ee0 100644 --- a/distributors-core/src/Data/Profunctor/Monadic.hs +++ b/distributors-core/src/Data/Profunctor/Monadic.hs @@ -44,7 +44,7 @@ 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,7 +61,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 diff --git a/distributors-core/src/Data/Profunctor/Monoidal.hs b/distributors-core/src/Data/Profunctor/Monoidal.hs index b6137ad4..57d492c0 100644 --- a/distributors-core/src/Data/Profunctor/Monoidal.hs +++ b/distributors-core/src/Data/Profunctor/Monoidal.hs @@ -56,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)) @@ -76,7 +76,7 @@ infixr 5 >*< {- | `>*` sequences actions, discarding the value of the first argument; analagous to `*>`, extending it to `Monoidal`. -@prop> oneP >* p = p@ +> prop> oneP >* p = p -} (>*) :: Monoidal p => p () c -> p a b -> p a b @@ -86,7 +86,7 @@ infixl 6 >* {- | `*<` sequences actions, discarding the value of the second argument; analagous to `<*`, extending it to `Monoidal`. -@prop> p *< oneP = p@ +> prop> p *< oneP = p -} (*<) :: Monoidal p => p a b -> p () c -> p a b @@ -179,8 +179,8 @@ traversalP :: (forall p. (Monoidal p, Choice p, Strong p) => p a b -> p s t) -> 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) @@ -208,7 +208,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))) @@ -258,9 +258,9 @@ 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@ +> 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) @@ -268,7 +268,7 @@ 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@ +> prop> arrP f = rmap f idP = lmap f idP -} arrP :: (Monoidal p, Strong p) => (a -> b) -> p a b arrP f = fmap f idP diff --git a/distributors-core/src/Data/Profunctor/Monoidal/Cocartesian.hs b/distributors-core/src/Data/Profunctor/Monoidal/Cocartesian.hs index efa41a94..74487f9f 100644 --- a/distributors-core/src/Data/Profunctor/Monoidal/Cocartesian.hs +++ b/distributors-core/src/Data/Profunctor/Monoidal/Cocartesian.hs @@ -58,10 +58,10 @@ let assoc = dimap (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@ +> 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 @@ -69,7 +69,7 @@ class Profunctor p => CocartesianMonoidal p where `zeroP` has a default for `CocartesianChoice`s. - @prop> zeroP = falseP@ + > prop> zeroP = falseP -} zeroP :: p Void Void default zeroP :: CocartesianChoice p => p Void Void @@ -79,7 +79,7 @@ class Profunctor p => CocartesianMonoidal p where `>+<` has a default for `CocartesianChoice`s. - @prop> x >+< y = alternate (Left x) >|< alternate (Right y)@ + > prop> x >+< y = alternate (Left x) >|< alternate (Right y) -} (>+<) :: p a b -> p c d -> p (Either a c) (Either b d) default (>+<) @@ -158,10 +158,10 @@ like `Alternative` but without requiring 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)@ +> prop> left' = alternate . Left +> prop> right' = alternate . Right +> prop> zeroP = falseP +> prop> x >+< y = alternate (Left x) >|< alternate (Right y) For the case of `Functor`s, the analog of `alternate` can be defined without any other constraint, but the case of `Profunctor`s turns diff --git a/distributors-core/src/Data/Profunctor/Separator.hs b/distributors-core/src/Data/Profunctor/Separator.hs index 1621a3e6..6a7d1621 100644 --- a/distributors-core/src/Data/Profunctor/Separator.hs +++ b/distributors-core/src/Data/Profunctor/Separator.hs @@ -82,7 +82,7 @@ endWith :: TerminalSymbol c p => [c] -> SepBy p -> SepBy p endWith str separator = separator {endBy = terminal str} {- | -@prop> several noSep = manyP@ +> prop> several noSep = manyP -} several :: (IsList s, IsList t, Distributor p) @@ -91,7 +91,7 @@ several (SepBy beg end sep) p = iso toList fromList . eotList >~ beg >* (p >*< manyP (sep >* p) >+< oneP) *< end {- | -@prop> several1 noSep = someP@ +> prop> several1 noSep = someP -} several1 :: (IsList s, IsList t, Distributor p, Choice p) diff --git a/distributors-core/src/Data/Traversable/Homogeneous.hs b/distributors-core/src/Data/Traversable/Homogeneous.hs index 00c33e2f..85167297 100644 --- a/distributors-core/src/Data/Traversable/Homogeneous.hs +++ b/distributors-core/src/Data/Traversable/Homogeneous.hs @@ -64,14 +64,14 @@ countable sums of countable products. class Traversable t => Homogeneous t where {- | Sequences actions `homogeneously`. - @prop> homogeneously @Maybe = optionalP@ - @prop> homogeneously @[] = manyP@ + > 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@ + > prop> homogeneously = ditraverse And any user-defined homogeneous algebraic datatype has a default instance for `Homogeneous`, by deriving `Generic1`. @@ -186,12 +186,12 @@ instance Homogeneous Tree where {- | A class of `Enumerable` countable sums of single copies, which are `Homogeneous`, & sequenced by sums alone. -@prop> enumerably @Identity = dimap runIdentity Identity@ +> prop> enumerably @Identity = dimap runIdentity Identity Every `Enumerable` is sequenced `enumerably` as it's sequenced `homogeneously`, by a `Distributor`. -@prop> enumerably = homogeneously@ +> prop> enumerably = homogeneously And any user-defined enumerable algebraic datatype has a default instance for `Enumerable`, by deriving `Generic1`. From 48138d4e2043db60a3093e9d83aba7ba35a63cac Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sat, 7 Nov 2026 12:32:07 -0800 Subject: [PATCH 046/130] Fix the docs job: ignore GHC environment files when building haddocks cabal.project writes GHC environment files for doctest-parallel, but cabal haddock-project then loads one which names the in-place distributors-json library, which a documentation build never registers, failing with "cannot satisfy -package-id distributors-json-0.1.0.0-inplace". GHC_ENVIRONMENT=- makes haddock ignore it. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 98216286..a43fc0e9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -149,7 +149,12 @@ jobs: key: docs-${{ runner.os }}-${{ hashFiles('dist-newstyle/cache/plan.json') }} restore-keys: docs-${{ runner.os }}- + # Haddock mustn't load the GHC environment file which cabal.project + # writes for doctest-parallel, since it names packages which a + # documentation build doesn't register. - name: Build the documentation + env: + GHC_ENVIRONMENT: "-" run: | cabal haddock-project --hackage --output=docs From 729539188b3b50e0019d97ce2e44e50462fd824e Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sat, 7 Nov 2026 12:37:11 -0800 Subject: [PATCH 047/130] Drop CI's docs jobs, which main's Docs workflow replaces main's Docs workflow builds the documentation & publishes it to the gh-pages branch, for main & as a preview for each pull request, so CI's docs job & its deploy to GitHub Pages from an artifact are redundant. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 51 ---------------------------------------- 1 file changed, 51 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a43fc0e9..6bcf6639 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -126,54 +126,3 @@ jobs: - name: Build & check the flake run: nix flake check -L - - docs: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - - name: Set up GHC & Cabal - id: setup - uses: haskell-actions/setup@v2 - with: - ghc-version: "9.12.4" - cabal-update: true - - - name: Plan the build - run: cabal build all --dry-run - - - name: Cache the Cabal store - uses: actions/cache@v4 - with: - path: ${{ steps.setup.outputs.cabal-store }} - key: docs-${{ runner.os }}-${{ hashFiles('dist-newstyle/cache/plan.json') }} - restore-keys: docs-${{ runner.os }}- - - # Haddock mustn't load the GHC environment file which cabal.project - # writes for doctest-parallel, since it names packages which a - # documentation build doesn't register. - - name: Build the documentation - env: - GHC_ENVIRONMENT: "-" - run: | - cabal haddock-project --hackage --output=docs - - - name: Upload the documentation - uses: actions/upload-pages-artifact@v3 - with: - path: docs - - deploy-docs: - if: github.event_name == 'push' && github.ref == 'refs/heads/main' - needs: [docs, stack, cabal, nix, lint] - runs-on: ubuntu-latest - permissions: - pages: write - id-token: write - environment: - name: github-pages - url: ${{ steps.deployment.outputs.page_url }} - steps: - - name: Deploy the documentation to GitHub Pages - id: deployment - uses: actions/deploy-pages@v4 From a7e976c853669af3295ed267d1e12338be38653d Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sat, 7 Nov 2026 13:04:45 -0800 Subject: [PATCH 048/130] Update Monocle.hs --- distributors-core/src/Control/Lens/Monocle.hs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/distributors-core/src/Control/Lens/Monocle.hs b/distributors-core/src/Control/Lens/Monocle.hs index 29333464..d050a2e6 100644 --- a/distributors-core/src/Control/Lens/Monocle.hs +++ b/distributors-core/src/Control/Lens/Monocle.hs @@ -38,6 +38,7 @@ module Control.Lens.Monocle , indexComonocle , zipWithComonocle , enumerated + , enumed -- * Comonocular , Comonocular (..), runComonocular ) where @@ -259,6 +260,9 @@ Identity 2 enumerated :: Enumerable f => Comonocle (f a) (f b) a b enumerated = unwrapPafb . enumerably . WrapPafb +enumed :: (Enum a, Bounded a) => Comonocle a a () () +enumed = iso (\x -> (x,())) (\(x,()) -> x) . enumerated + {- | `Comonocular` provides a concrete representation of `Comonocle`s, by an `Enumerable` sum of copies. -} From 037d31293a85a81ef34762812043b3a012c34663 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sat, 7 Nov 2026 13:16:42 -0800 Subject: [PATCH 049/130] optics --- distributors-core/src/Control/Lens/Diopter.hs | 38 ++++++++ distributors-core/src/Control/Lens/Monocle.hs | 92 +++++++++++++++++-- .../test/Properties/Homogeneous.hs | 19 ++++ 3 files changed, 143 insertions(+), 6 deletions(-) diff --git a/distributors-core/src/Control/Lens/Diopter.hs b/distributors-core/src/Control/Lens/Diopter.hs index c0563a6a..88d3ef2d 100644 --- a/distributors-core/src/Control/Lens/Diopter.hs +++ b/distributors-core/src/Control/Lens/Diopter.hs @@ -20,10 +20,14 @@ module Control.Lens.Diopter , optioned , manied , homogenized + , zipDiopter + , zipWithDiopter + , transposeDiopter -- * Dioptrice , Dioptrice (..), runDioptrice ) where +import Control.Applicative (Alternative) import Control.Lens import Control.Lens.Internal.Profunctor import Data.Profunctor.Distributor @@ -86,6 +90,40 @@ countable sum of countable products. 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 `empty`. + +>>> zipDiopter manied (Just . sum) [[1, 2], [3, 4], [5, 6 :: Int]] +Just [9,12] +>>> zipDiopter manied (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 manied [[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 `Dioptrice` provides efficient access to some pair of functions that make up a `Diopter`. -} diff --git a/distributors-core/src/Control/Lens/Monocle.hs b/distributors-core/src/Control/Lens/Monocle.hs index d050a2e6..7cbf5036 100644 --- a/distributors-core/src/Control/Lens/Monocle.hs +++ b/distributors-core/src/Control/Lens/Monocle.hs @@ -36,6 +36,12 @@ module Control.Lens.Monocle , altComonocle , crossComonocle , indexComonocle + , countComonocle + , toEnumComonocle + , succComonocle + , predComonocle + , enumerateComonocle + , zipComonocle , zipWithComonocle , enumerated , enumed @@ -43,6 +49,7 @@ module Control.Lens.Monocle , Comonocular (..), runComonocular ) where +import Control.Applicative (Alternative) import Control.Lens hiding (Traversing) import Control.Lens.Internal.Profunctor import Data.Distributive @@ -59,9 +66,6 @@ import Numeric.Natural (Natural) -- >>> import Data.Complex -- >>> import Data.Functor.Identity --- $setup --- >>> import Data.Complex - {- | `Monocle`s are an optic that generalizes `Control.Lens.Traversal.Traversal`s & `Control.Lens.Grate.Grate`s. @@ -248,9 +252,79 @@ Nothing -} zipWithComonocle :: AComonocle s t a b -> (a -> a -> b) -> s -> s -> Maybe t -zipWithComonocle mon f s0 s1 = runZipporah - (mapComonocle mon (Zipporah (\(Par1 a0 :*: Par1 a1) -> Just (f a0 a1)))) - (Par1 s0 :*: Par1 s1) +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 `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 (enumed @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 () :: Indexing () ()) :: Indexing (f ()) (f ()) of + Indexing count _ _ -> count + +{- | The copy of `AComonocle` at an index, holding a focus, if there is one, +like `toEnum`, & inverse to `indexComonocle`. + +>>> toEnumComonocle enumed () 2 :: Maybe Ordering +Just GT +>>> toEnumComonocle enumed () 3 :: Maybe Ordering +Nothing +-} +toEnumComonocle :: AComonocle s t a b -> b -> Natural -> Maybe t +toEnumComonocle mon b copy = withComonocle mon $ \_ merge -> merge <$> toEnumerable b copy + +{- | The next copy of `AComonocle`, holding the same focus, +if there is one, like `succ`. + +>>> succComonocle enumed EQ +Just GT +>>> succComonocle enumed GT +Nothing +-} +succComonocle :: AComonocle s s a a -> s -> Maybe s +succComonocle mon s = withComonocle mon $ \split merge -> merge <$> succEnumerable (split s) + +{- | The previous copy of `AComonocle`, holding the same focus, +if there is one, like `pred`. + +>>> predComonocle enumed EQ +Just LT +>>> predComonocle enumed LT +Nothing +-} +predComonocle :: AComonocle s s a a -> s -> Maybe s +predComonocle mon s = withComonocle mon $ \split merge -> merge <$> predEnumerable (split s) + +{- | The copies of `AComonocle` from one onward, holding the same focus, +like `enumFrom`. + +>>> enumerateComonocle enumed 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 `Comonocle` of an `Enumerable` sum's copy. @@ -260,6 +334,12 @@ Identity 2 enumerated :: Enumerable f => Comonocle (f a) (f b) a b enumerated = unwrapPafb . enumerably . WrapPafb +{- | The `Comonocle` of a `Bounded` `Enum`, as copies of @()@, +numbered by `fromEnum` from `minBound`. + +>>> iview (indexComonocle enumed) True +(1,()) +-} enumed :: (Enum a, Bounded a) => Comonocle a a () () enumed = iso (\x -> (x,())) (\(x,()) -> x) . enumerated diff --git a/distributors-core/test/Properties/Homogeneous.hs b/distributors-core/test/Properties/Homogeneous.hs index 577e05e9..061583e8 100644 --- a/distributors-core/test/Properties/Homogeneous.hs +++ b/distributors-core/test/Properties/Homogeneous.hs @@ -9,6 +9,9 @@ module Properties.Homogeneous (homogeneousProperties) where import Control.Applicative import Control.Arrow ((+++)) +import Control.Lens (iview) +import Control.Lens.Diopter +import Control.Lens.Monocle import Control.Monad ((<=<)) import Data.Functor.Compose (Compose (..)) import Data.Foldable (toList) @@ -267,6 +270,22 @@ homogeneousProperties = do indexing (rmap (either id absurd) p) === indexing (unleft (lmap (either id absurd) p) :: Indexing Bool Int) zipporahLaws + describe "Comonocle & Diopter combinators" $ do + prop "countComonocle enumed is the number of values" $ + countComonocle (enumed @Int8) === 256 .&&. countComonocle (enumed @Bool) === 2 + prop "toEnumComonocle enumed inverts indexComonocle" $ \(e :: Int8) -> + toEnumComonocle enumed () (fst (iview (indexComonocle enumed) e)) === Just e + prop "succComonocle enumed is succ, but at maxBound" $ \(e :: Int8) -> + succComonocle enumed e === if e == maxBound then Nothing else Just (succ e) + prop "predComonocle enumed is pred, but at minBound" $ \(e :: Int8) -> + predComonocle enumed e === if e == minBound then Nothing else Just (pred e) + prop "enumerateComonocle enumed is enumFrom" $ \(e :: Ordering) -> + enumerateComonocle enumed e === [e ..] + prop "zipDiopter homogenized is zipHomogeneous" $ \(xss :: [[Int]]) -> + zipDiopter homogenized (Just . sum) ([1, 2] : xss) + === zipHomogeneous (Just . sum) ([1, 2 :: Int] : xss) + prop "zipWithDiopter manied is zipWithHomogeneous" $ \(xs :: [Int]) ys -> + zipWithDiopter manied (+) xs ys === zipWithHomogeneous (+) xs ys describe "Enumerable & Homogeneous" $ do it "numbers copies left to right" $ map fromEnumerable [(LT, ()), (EQ, ()), (GT, ())] `shouldBe` [0, 1, 2] From 9a71e1673d27d21425668b9b67ec2d8a27dae66b Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sat, 7 Nov 2026 16:16:09 -0800 Subject: [PATCH 050/130] Add jsonNullable: null or a value, without an Either for each MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Maybe's grammar, eotMaybe . swapped >~ jsonNull >+< json, cost every value an Either, a dimap & a dispatch to print, & a failed jsonNull, allocating an error, before each Just to parse. jsonNullable is a JsonVal method with that grammar as its default, which JsonPrintor & JsonParsor define directly, so Maybe & every record of an optional field print & parse as aeson does, with the same errors. Json ÷ aeson, before -> after: maybes encode 1.53x -> 0.96x toValue 1.65x -> 0.67x decode 1.16x -> 0.93x fromValue 1.46x -> 0.88x deep toValue 1.28x -> 1.09x decode 1.20x -> 1.10x fromValue 1.39x -> 1.02x Co-Authored-By: Claude Opus 5.5 --- .../src/Control/Lens/Grammar/Json.hs | 26 ++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/distributors-json/src/Control/Lens/Grammar/Json.hs b/distributors-json/src/Control/Lens/Grammar/Json.hs index 2478f2eb..388aac12 100644 --- a/distributors-json/src/Control/Lens/Grammar/Json.hs +++ b/distributors-json/src/Control/Lens/Grammar/Json.hs @@ -414,6 +414,13 @@ class -} 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 . swapped >~ jsonNull >+< p@ + -} + jsonNullable :: p a b -> p (Maybe a) (Maybe b) + jsonNullable p = eotMaybe . swapped >~ jsonNull >+< p {- | A `jsonDict` object of a `Map`, whose keys can't repeat, so that printing needn't check them. -} @@ -824,6 +831,14 @@ 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 = jsonParsor $ \case Bool b -> Right b v -> jsonMismatch "boolean" v @@ -1304,6 +1319,15 @@ instance AesonStr val => JsonStr (JsonPrintor val) where rendered = arrayFromList [aesonLiteral literal | (literal, _) <- table] 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 jsonNumber = primitive aesonNumber jsonInt = primitive (aesonIntegral Encoding.int) @@ -2270,7 +2294,7 @@ instance Json a => Json [a] where json = jsonList jsonKey = jsonKeyList @a instance Json a => Json (Maybe a) where - json = eotMaybe . swapped >~ jsonNull >+< json + json = jsonNullable json jsonOmitField = isNothing jsonOmittedField = Just Nothing instance (Json a, Json b) => Json (Either a b) where From 339b4ccaceefa21a19f5617949a0d404938d193b Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sat, 7 Nov 2026 16:16:09 -0800 Subject: [PATCH 051/130] Order eotMaybe & eotList's summands as their constructors MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit eotMaybe is now Maybe a ≅ Either () a, & eotList s ≅ Either () (a, s), empty first, as Nothing & [] come first, & as eotFunList already was. Call sites which try a value before the empty case, optionalP, manyP, the homogeneously of Vector & Seq, & several, now compose swapped; jsonNullable, which tries null first, no longer needs to. Behaviour is unchanged, so parsers try the same alternative first & copies keep their numbers. Co-Authored-By: Claude Opus 5.5 --- .../src/Control/Lens/PartialIso.hs | 20 +++++++++++-------- .../src/Data/Profunctor/Distributor.hs | 4 ++-- .../src/Data/Profunctor/Grammar/Parsector.hs | 2 +- .../src/Data/Profunctor/Separator.hs | 2 +- .../src/Data/Traversable/Homogeneous.hs | 4 ++-- .../src/Control/Lens/Grammar/Json.hs | 4 ++-- 6 files changed, 20 insertions(+), 16 deletions(-) diff --git a/distributors-core/src/Control/Lens/PartialIso.hs b/distributors-core/src/Control/Lens/PartialIso.hs index 3ab2f1bb..63b1a5eb 100644 --- a/distributors-core/src/Control/Lens/PartialIso.hs +++ b/distributors-core/src/Control/Lens/PartialIso.hs @@ -275,19 +275,23 @@ 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 ()) +{- | 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 (Right ()) Left) - (either Just (const Nothing)) + (maybe (Left ()) Right) + (either (const Nothing) Just) -{- | The either-of-tuples representation of list-like streams. -} +{- | 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) ()) + => Iso s t (Either () (a,s)) (Either () (b,t)) eotList = iso - (maybe (Right ()) Left . uncons) - (either (review _Cons) (const Empty)) + (maybe (Left ()) Right . uncons) + (either (const Empty) (review _Cons)) {- | Iterate the application of a partial isomorphism, useful for constructing fold/unfold isomorphisms. -} diff --git a/distributors-core/src/Data/Profunctor/Distributor.hs b/distributors-core/src/Data/Profunctor/Distributor.hs index d39b7daf..2a5c1e70 100644 --- a/distributors-core/src/Data/Profunctor/Distributor.hs +++ b/distributors-core/src/Data/Profunctor/Distributor.hs @@ -56,11 +56,11 @@ class (Monoidal p, CocartesianMonoidal p) => Distributor p where {- | One or none. -} optionalP :: p a b -> p (Maybe a) (Maybe b) - optionalP p = eotMaybe >~ p >+< oneP + optionalP p = eotMaybe . swapped >~ p >+< oneP {- | Zero or more. -} manyP :: p a b -> p [a] [b] - manyP p = eotList >~ p >*< manyP p >+< oneP + manyP p = eotList . swapped >~ p >*< manyP p >+< oneP instance Distributor (->) instance Monoid s => Distributor (Forget s) diff --git a/distributors-core/src/Data/Profunctor/Grammar/Parsector.hs b/distributors-core/src/Data/Profunctor/Grammar/Parsector.hs index 96aa32b3..a7c90a50 100644 --- a/distributors-core/src/Data/Profunctor/Grammar/Parsector.hs +++ b/distributors-core/src/Data/Profunctor/Grammar/Parsector.hs @@ -417,7 +417,7 @@ instance Categorized (Item s) => Choice (Parsector s) where query { parsecResult = either (const Nothing) Just =<< result } instance Categorized (Item s) => CocartesianMonoidal (Parsector s) instance Categorized (Item s) => Distributor (Parsector s) where - {- | Like @eotList >~ p >*< manyP p >+< oneP@, in one loop, + {- | 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. -} diff --git a/distributors-core/src/Data/Profunctor/Separator.hs b/distributors-core/src/Data/Profunctor/Separator.hs index 6a7d1621..4941faaa 100644 --- a/distributors-core/src/Data/Profunctor/Separator.hs +++ b/distributors-core/src/Data/Profunctor/Separator.hs @@ -87,7 +87,7 @@ endWith str separator = separator {endBy = terminal str} 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 >~ +several (SepBy beg end sep) p = iso toList fromList . eotList . swapped >~ beg >* (p >*< manyP (sep >* p) >+< oneP) *< end {- | diff --git a/distributors-core/src/Data/Traversable/Homogeneous.hs b/distributors-core/src/Data/Traversable/Homogeneous.hs index 85167297..d5aaa234 100644 --- a/distributors-core/src/Data/Traversable/Homogeneous.hs +++ b/distributors-core/src/Data/Traversable/Homogeneous.hs @@ -175,9 +175,9 @@ instance Homogeneous Maybe where instance Homogeneous [] where homogeneously = manyP instance Homogeneous Vector where - homogeneously p = eotList >~ p >*< homogeneously p >+< oneP + homogeneously p = eotList . swapped >~ p >*< homogeneously p >+< oneP instance Homogeneous Seq where - homogeneously p = eotList >~ p >*< homogeneously p >+< oneP + homogeneously p = eotList . swapped >~ p >*< homogeneously p >+< oneP instance Homogeneous Complex where homogeneously p = dimap2 realPart imagPart (:+) p p instance Homogeneous Tree where diff --git a/distributors-json/src/Control/Lens/Grammar/Json.hs b/distributors-json/src/Control/Lens/Grammar/Json.hs index 388aac12..bd1f4606 100644 --- a/distributors-json/src/Control/Lens/Grammar/Json.hs +++ b/distributors-json/src/Control/Lens/Grammar/Json.hs @@ -417,10 +417,10 @@ class {- | @null@ or a value, like @aeson@'s `Maybe`, though interpreters may define it more efficiently. - @jsonNullable p = eotMaybe . swapped >~ jsonNull >+< p@ + @jsonNullable p = eotMaybe >~ jsonNull >+< p@ -} jsonNullable :: p a b -> p (Maybe a) (Maybe b) - jsonNullable p = eotMaybe . swapped >~ jsonNull >+< p + jsonNullable p = eotMaybe >~ jsonNull >+< p {- | A `jsonDict` object of a `Map`, whose keys can't repeat, so that printing needn't check them. -} From ba53826b5448265d5680e777138f5341cf004aea Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sat, 7 Nov 2026 16:27:25 -0800 Subject: [PATCH 052/130] Add jsonInteger & jsonNatural, printed as aeson prints them MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Integer & Natural printed through _Integer ?< jsonNumber, costing every value an Either & several closures, like the bounded integers before they had their own JsonVal methods. jsonInteger & jsonNatural join jsonInt … jsonWord64, defaulting to the same grammars, which JsonPrintor defines as primitives by aeson's Encoding.integer. Parsing & the TypeScript types are unchanged. Json ÷ aeson for integers: encode 1.25x -> 1.00x, toValue ~1.8x -> 0.87x. Co-Authored-By: Claude Opus 5.5 --- .../src/Control/Lens/Grammar/Json.hs | 26 ++++++++++++------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/distributors-json/src/Control/Lens/Grammar/Json.hs b/distributors-json/src/Control/Lens/Grammar/Json.hs index bd1f4606..97614fbd 100644 --- a/distributors-json/src/Control/Lens/Grammar/Json.hs +++ b/distributors-json/src/Control/Lens/Grammar/Json.hs @@ -405,6 +405,10 @@ class 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 @@ -1340,6 +1344,8 @@ instance AesonVal val => JsonVal (JsonPrintor val) where 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 @@ -2188,6 +2194,15 @@ _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 @@ -2344,18 +2359,11 @@ instance Json Word32 where instance Json Word64 where json = jsonTyped jsonWord64 jsonKey = Just (jsonIntKey _BoundedInteger) -_Integer :: Prism' Scientific Integer -_Integer = prism' fromInteger $ - boundedScientific >=> either (const Nothing) Just . floatingOrInteger @Double instance Json Integer where - json = jsonTyped (_Integer ?< jsonNumber) + json = jsonTyped jsonInteger jsonKey = Just (jsonIntKey _Integer) -_Natural :: Prism' Scientific Natural -_Natural = prism' fromIntegral $ \s -> do - i <- preview _Integer s - fromInteger i <$ guard (i >= 0) instance Json Natural where - json = jsonTyped (_Natural ?< jsonNumber) + json = jsonTyped jsonNatural jsonKey = Just (jsonIntKey _Natural) instance Json CTime where json = coerced >~ json @Int64 From c89344f0af56da77585846ef698c21227e72e4fa Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sat, 7 Nov 2026 17:18:15 -0800 Subject: [PATCH 053/130] Encode object keys once, when building a printer, not per value MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Encoding a property escaped & quoted its key every time, by Encoding.pair, though an object's named keys are known when its printer is built. AesonVal now has an associated key & properties type: for Encoding, a key rendered once to its quoted bytes, & a Series built by Encoding.pair'; for Value, the Key & [(Key, Value)] as before. Only the rendering path changes; the try & check paths, which find duplicate keys, keep [(Key, val)]. Json ÷ aeson, encode: deep 1.53x -> 1.29x, variants 1.42x -> 1.27x, eithers 1.34x -> 1.19x, sums 1.22x -> 1.12x, wide 1.08x -> 1.01x. Co-Authored-By: Claude Opus 5.5 --- .../src/Control/Lens/Grammar/Json.hs | 64 ++++++++++++++----- 1 file changed, 49 insertions(+), 15 deletions(-) diff --git a/distributors-json/src/Control/Lens/Grammar/Json.hs b/distributors-json/src/Control/Lens/Grammar/Json.hs index 97614fbd..3cfed9d1 100644 --- a/distributors-json/src/Control/Lens/Grammar/Json.hs +++ b/distributors-json/src/Control/Lens/Grammar/Json.hs @@ -1112,6 +1112,14 @@ class AesonStr val => AesonVal val where -> (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 instance AesonVal Value where aesonNull = Null @@ -1132,7 +1140,14 @@ instance AesonVal Value 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 + +-- | Keys are rendered once, as their quoted strings, & properties as a series. instance AesonVal Encoding where aesonNull = Encoding.null_ aesonBool = Encoding.bool @@ -1148,6 +1163,12 @@ instance AesonVal Encoding where 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 {- | `JsonPrintor` `printorTry`s to print a value, or else `printorCheck`s it to locate the failure. A `printorTotal` printor prints every value, @@ -1240,7 +1261,7 @@ data ObjPrintor val a b = ObjPrintor , objPrintorRest :: !Bool , objPrintorTotal :: !(Set String -> Bool) , objPrintorTry :: !(a -> Maybe (DList (Key, val))) - , objPrintorRender :: !(a -> [(Key, val)] -> [(Key, val)]) + , objPrintorRender :: !(a -> AesonProps val -> AesonProps val) , objPrintorCheck :: !(a -> Either JsonError [(Key, val)]) } @@ -1384,7 +1405,7 @@ instance AesonVal val => JsonVal (JsonPrintor val) where | otherwise -> JsonPrintor (\rules -> objPrintorTotal printor rules) (fmap (aesonObject . toList) . objPrintorTry printor) - (\a -> aesonObject (objPrintorRender printor a [])) + (\a -> aesonProps (objPrintorRender printor a (aesonPropsEmpty @val))) (fmap aesonObject . objPrintorCheck printor) Nothing where @@ -1511,7 +1532,7 @@ instance Profunctor (ObjPrintor val) where (check . f) _ #. p = coerce p p .# _ = coerce p -instance Choice (ObjPrintor val) where +instance AesonVal val => Choice (ObjPrintor val) where left' = alternate . Left right' = alternate . Right instance CocartesianMonoidal (ObjPrintor val) where @@ -1525,7 +1546,7 @@ instance CocartesianMonoidal (ObjPrintor val) where Left a -> objPrintorRender p a props Right b -> objPrintorRender q b props) (either (objPrintorCheck p) (objPrintorCheck q)) -instance CocartesianChoice (ObjPrintor val) where +instance AesonVal val => CocartesianChoice (ObjPrintor val) where alternate = \case Left p -> objTrying p (either (objPrintorTry p) (const Nothing)) @@ -1533,7 +1554,7 @@ instance CocartesianChoice (ObjPrintor val) where Right p -> objTrying p (either (const Nothing) (objPrintorTry p)) (either (\_ -> jsonUnexpected Nothing) (objPrintorCheck p)) -instance DisjunctiveMonoid (ObjPrintor val a b) where +instance AesonVal val => DisjunctiveMonoid (ObjPrintor val a b) where falseP = ObjPrintor [] False (const False) (const Nothing) (\_ props -> props) (\_ -> jsonUnexpected Nothing) p >|< q = ObjPrintor @@ -1542,27 +1563,36 @@ instance DisjunctiveMonoid (ObjPrintor val a b) where (\rules -> objPrintorTotal p rules || objPrintorTotal q rules) (\a -> objPrintorTry p a <|> objPrintorTry q a) (\a props -> maybe - (objPrintorRender q a props) (`DList.apply` props) (objPrintorTry p a)) + (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 `ObjPrintor` of another's shapes, rendering what it tries. objTrying - :: ObjPrintor val x y + :: 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 -> DList.apply (fromMaybe mempty (attempt a)) props) + (\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 (keyOf a) p c props) rest entries) + (\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 @@ -1570,18 +1600,20 @@ instance AesonVal val => JsonObj (JsonPrintor val) (ObjPrintor val) where k !: p = ObjPrintor [[key]] False (\rules -> printorTotal p rules) (fmap property . printorTry p) - (renderProperty key 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 key p a rest) ma) + (\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) -- | Print the properties of a map, whose keys are distinct, as an object. @@ -1604,9 +1636,11 @@ printDistinct fold key p = JsonPrintor k = keyOf a renderProperty - :: Key -> JsonPrintor val a b -> a -> [(Key, val)] -> [(Key, val)] + :: 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` (key, printed) : rest + let printed = printorRender p a in printed `seq` aesonProp key printed rest printProperty :: Key -> JsonPrintor val a b -> a -> Either JsonError [(Key, val)] From b37c24f69fba8fad07d81b5c745b2dc13380a17a Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sat, 7 Nov 2026 18:13:56 -0800 Subject: [PATCH 054/130] Compile grammars at their types: break the JsonTup/JsonObj superclass cycle, & inline the printer MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A grammar was interpreted at runtime: the printer of a type was built by calling its instance with dictionaries, & printed through opaque closures. Marking the path INLINE wasn't enough, since jsonTuple was a loop breaker, never inlined: JsonTup & JsonObj had JsonVal p as a superclass, so the tuple dictionary which jsonTuple builds contained the dictionary containing jsonTuple. Grammars get JsonVal p from their own context, so JsonTup & JsonObj no longer have it as a superclass, which a few signatures now state, & there's no cycle. The printer's combinators, the tuple, object & generic machinery, & the primitive instances are INLINE, & jsonTuple's body is printTuple, so GHC compiles a grammar at its use site to direct code, as it does aeson's. A type's json, by default & by Generically, is INLINABLE rather than INLINE, so a recursive type's printer is built once, not at every node. Json ÷ aeson, encode: maybes 0.98x -> 0.14x, tuples 0.90x -> 0.58x, enums 1.57x -> 1.39x, ints 0.96x -> 0.77x; other datasets unchanged, but tuples toValue 1.36x -> 1.46x. Co-Authored-By: Claude Opus 5.5 --- .../src/Control/Lens/Grammar/Json.hs | 185 ++++++++++++++++-- 1 file changed, 168 insertions(+), 17 deletions(-) diff --git a/distributors-json/src/Control/Lens/Grammar/Json.hs b/distributors-json/src/Control/Lens/Grammar/Json.hs index 3cfed9d1..4298664e 100644 --- a/distributors-json/src/Control/Lens/Grammar/Json.hs +++ b/distributors-json/src/Control/Lens/Grammar/Json.hs @@ -277,6 +277,7 @@ class Json a where json :: JsonVal p => p a a default json :: (Json (GHC.Generically a), JsonVal p) => p a a json = iso GHC.Generically coerce >~ json + {-# INLINABLE json #-} {- | `Data.Aeson.toJSONList`, an array of values by default. `Char` overrides it, so that a `String` is a JSON string, @@ -284,6 +285,7 @@ class Json a where -} jsonList :: JsonVal p => p [a] [a] jsonList = jsonArray json + {-# INLINE jsonList #-} {- | `Data.Aeson.toJSONKey`, as the text keys of objects, or else `Nothing` for the keys of arrays of pairs. @@ -339,10 +341,12 @@ 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 `JsonError`, by its message. @@ -472,6 +476,7 @@ 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 @@ -548,7 +553,7 @@ 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 (JsonVal p, Alternator q) => JsonTup p q | q -> p where +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. @@ -559,8 +564,7 @@ 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 (JsonVal p, Monoidal q, CocartesianChoice q) - => JsonObj p q | q -> p where +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 `?:`, @@ -1050,6 +1054,8 @@ class AesonStr val where instance AesonStr Value where aesonText = String aesonString = String . Text.pack + {-# INLINE aesonText #-} + {-# INLINE aesonString #-} instance AesonStr Key where aesonText = Key.fromText @@ -1064,6 +1070,10 @@ instance AesonStr (Encoding.Encoding' a) where 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 @@ -1146,6 +1156,19 @@ instance AesonVal Value where aesonProp key value rest = (key, value) : rest aesonPropsEmpty = [] aesonProps = Object . KeyMap.fromList + {-# INLINE aesonNull #-} + {-# INLINE aesonBool #-} + {-# INLINE aesonNumber #-} + {-# INLINE aesonIntegral #-} + {-# INLINE aesonDouble #-} + {-# INLINE aesonList #-} + {-# 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 @@ -1169,6 +1192,19 @@ instance AesonVal Encoding where aesonProp key value rest = Encoding.pair' key value <> rest aesonPropsEmpty = mempty aesonProps = Encoding.pairs + {-# INLINE aesonNull #-} + {-# INLINE aesonBool #-} + {-# INLINE aesonNumber #-} + {-# INLINE aesonIntegral #-} + {-# INLINE aesonDouble #-} + {-# INLINE aesonList #-} + {-# INLINE aesonObject #-} + {-# INLINE aesonMap #-} + {-# INLINE aesonValue #-} + {-# INLINE aesonKey #-} + {-# INLINE aesonProp #-} + {-# INLINE aesonPropsEmpty #-} + {-# INLINE aesonProps #-} {- | `JsonPrintor` `printorTry`s to print a value, or else `printorCheck`s it to locate the failure. A `printorTotal` printor prints every value, @@ -1190,11 +1226,13 @@ 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 `JsonPrintor`. printing :: (a -> val) -> JsonPrintor val a b printing render = JsonPrintor (const True) (Just . render) render (Right . render) Nothing +{-# INLINE printing #-} -- | A total `JsonPrintor` of a primitive. primitive :: AesonStr val => (a -> val) -> JsonPrintor val a b @@ -1237,6 +1275,7 @@ data TupPrintor val a b = TupPrintor renderElement :: (a -> val) -> a -> [val] -> [val] renderElement render a rest = let printed = render a in printed `seq` printed : rest +{-# INLINE renderElement #-} -- | Printed elements, counted to locate a failure of a later element. newtype Elements val = Elements (Either JsonError (Int, DList val)) @@ -1271,6 +1310,7 @@ 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. @@ -1284,6 +1324,9 @@ instance Profunctor (JsonPrintor val) where (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) @@ -1291,6 +1334,8 @@ instance Cochoice (JsonPrintor val) where 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 @@ -1299,6 +1344,8 @@ instance CocartesianMonoidal (JsonPrintor val) where (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)) @@ -1306,6 +1353,8 @@ instance AesonVal val => Choice (JsonPrintor val) where 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) @@ -1328,6 +1377,7 @@ instance BackusNaurForm (JsonPrintor val a b) where , 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) @@ -1335,6 +1385,7 @@ instance (AesonStr val, x ~ (), y ~ ()) => IsString (JsonPrintor val x y) 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) @@ -1342,6 +1393,9 @@ instance AesonStr val => JsonStr (JsonPrintor val) where 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. @@ -1354,8 +1408,10 @@ instance AesonVal val => JsonVal (JsonPrintor val) where 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) @@ -1380,15 +1436,11 @@ instance AesonVal val => JsonVal (JsonPrintor val) where Nothing where render = fromMaybe (aesonList (printorRender p)) (printorRenderArray p) + {-# INLINE jsonArray #-} jsonMap key = printDistinct Map.foldrWithKey key jsonHashMap key = printDistinct HashMap.foldrWithKey key - jsonTuple tup = JsonPrintor - (\rules -> tupPrintorTotal tup rules) - (fmap (aesonList id . toList) . tupPrintorTry tup) - (\a -> aesonList id (tupPrintorRender tup a [])) - (\a -> case tupPrintorCheck tup a of - Elements printed -> aesonList id . toList . snd <$> printed) - Nothing + jsonTuple = printTuple + {-# INLINE jsonTuple #-} jsonObject obj = case foldr ((<|>) . duplicateKey) Nothing (objPrintorShapes printor) of Just key -> trying (const Nothing) (\_ -> printDuplicate key) @@ -1412,10 +1464,31 @@ instance AesonVal val => JsonVal (JsonPrintor val) 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 @@ -1425,6 +1498,8 @@ instance Applicative (TupPrintor val a) where (\a rest -> tupPrintorRender p a $! tupPrintorRender q a rest) (tupPrintorCheck p <> tupPrintorCheck q) Nothing + {-# INLINE pure #-} + {-# INLINE (<*>) #-} instance Profunctor (TupPrintor val) where dimap f _ p = case tupPrintorElement p of Just single -> @@ -1434,6 +1509,9 @@ instance Profunctor (TupPrintor val) where (\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 CocartesianMonoidal (TupPrintor val) where @@ -1502,7 +1580,7 @@ instance DisjunctiveMonoid (TupPrintor val a b) where (printed, _) -> printed) Nothing -instance AesonVal val => JsonTup (JsonPrintor val) (TupPrintor val) where +instance JsonTup (JsonPrintor val) (TupPrintor val) where jsonElem p = TupPrintor (\rules -> printorTotal p rules) (fmap DList.singleton . printorTry p) @@ -1510,10 +1588,12 @@ instance AesonVal val => JsonTup (JsonPrintor val) (TupPrintor val) where (\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 []) @@ -1525,6 +1605,7 @@ instance Applicative (ObjPrintor val a) where (\a -> (<>) <$> try0 a <*> try1 a) (\a rest -> render0 a $! render1 a rest) (\a -> (<>) <$> check0 a <*> check1 a) + {-# INLINE pure #-} instance Profunctor (ObjPrintor val) where dimap f _ (ObjPrintor keys rest total attempt render check) = ObjPrintor keys rest total @@ -1532,9 +1613,14 @@ instance Profunctor (ObjPrintor val) where (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 @@ -1546,6 +1632,8 @@ instance CocartesianMonoidal (ObjPrintor val) where 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 @@ -1554,6 +1642,7 @@ instance AesonVal val => CocartesianChoice (ObjPrintor val) where 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) @@ -1615,6 +1704,25 @@ instance AesonVal val => JsonObj (JsonPrintor val) (ObjPrintor val) 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 + :: AesonVal val + => (forall q. JsonTup (JsonPrintor val) q => q a b) -> JsonPrintor val a b +printTuple tup = JsonPrintor + (\rules -> tupPrintorTotal tup rules) + (fmap (aesonList id . toList) . tupPrintorTry tup) + (\a -> aesonList id (tupPrintorRender tup a [])) + (\a -> case tupPrintorCheck tup 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 @@ -1641,6 +1749,7 @@ renderProperty -> 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)] @@ -2316,6 +2425,7 @@ makePrisms ''These -- base instance Json Bool where json = jsonBool + {-# INLINE json #-} jsonKey = Just (enumerated (\b -> if b then "true" else "false")) instance Json Ordering where json = jsonTyped (enumerated (Text.pack . show)) @@ -2341,6 +2451,7 @@ instance Json Char where 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 @@ -2365,6 +2476,7 @@ instance HasResolution a => Json (Fixed a) where 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 @@ -2475,16 +2587,23 @@ instance Json (Proxy a) where jsonOmittedField = Just Proxy -- tuples -- | An element of a tuple, by its projection. -projectElem :: (Json a, JsonTup p q) => (s -> a) -> q s a +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 = jsonTuple (jsonElem json >*< jsonElem 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) @@ -2653,6 +2772,7 @@ instance -- text instance Json Text where json = jsonText + {-# INLINE json #-} jsonKey = Just jsonText instance Json LText.Text where json = iso LText.toStrict LText.fromStrict >~ jsonText @@ -2905,6 +3025,7 @@ instance ) => 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, @@ -2923,6 +3044,7 @@ jsonGeneric opts = jsonTyped $ case (enumIndex @(AllNullary f) @a, gtable @f opt , 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 @@ -2951,6 +3073,7 @@ gsum opts Aeson.UntaggedValue -> guntagged opts Aeson.ObjectWithSingleField -> gsingleField opts Aeson.TwoElemArray -> gtwoElements opts +{-# INLINE gsum #-} -- | An object, rejecting other properties by `Aeson.rejectUnknownFields`. gobject @@ -2958,6 +3081,7 @@ gobject gobject opts obj | Aeson.rejectUnknownFields opts = jsonObjectStrict obj | otherwise = jsonObject obj +{-# INLINE gobject #-} class GSum f where gconCount :: Int @@ -2990,6 +3114,14 @@ instance (GSum f, GSum g) => GSum (f GHC.:+: g) where 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 @@ -3013,9 +3145,9 @@ instance (GHC.Constructor c, GFields f, GContents f, GNullary f) gtagged opts tagField contentsField = GHC.M1 #. gobject opts (tag >* contents) .# GHC.unM1 where - tag :: JsonObj p q => q () () + tag :: (JsonVal p, JsonObj p q) => q () () tag = tagField !: fromString (gconTag @c opts) - contents :: JsonObj p q => q (f x) (f x) + 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 @@ -3030,6 +3162,14 @@ instance (GHC.Constructor c, GFields f, GContents f, GNullary f) ( lmap (const ()) (jsonElem (fromString (gconTag @c opts))) *> jsonElem (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 @@ -3046,7 +3186,7 @@ gselName = GHC.selName (GHC.M1 GHC.U1 :: GHC.S1 s GHC.U1 ()) class GFields f where -- | A record's fields, by `Aeson.fieldLabelModifier`. - gfields :: JsonObj p q => Aeson.Options -> q (f x) (f x) + 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 @@ -3054,7 +3194,7 @@ instance (GHC.Selector s, Json a) => GFields (GHC.S1 s (GHC.K1 i a)) where where key = Text.pack (Aeson.fieldLabelModifier opts (gselName @s)) -- An omittable field, by `jsonOmitField` & `jsonOmittedField`. - property :: JsonObj p q => q a a + property :: (JsonVal p, JsonObj p q) => q a a property = case jsonOmittedField @a of Just omitted | Aeson.allowOmittedFields opts || Aeson.omitNothingFields opts -> @@ -3064,21 +3204,27 @@ instance (GHC.Selector s, Json a) => GFields (GHC.S1 s (GHC.K1 i a)) where | Aeson.omitNothingFields opts && jsonOmitField a = Nothing | otherwise = Just a 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 :: JsonTup p q => q (f x) (f x) + gelements :: (JsonVal p, JsonTup p q) => q (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 + {-# INLINE gelements #-} instance (GElements f, GElements g) => GElements (f GHC.:*: g) where gelements = dimap2 (\(a GHC.:*: _) -> a) (\(_ GHC.:*: b) -> b) (GHC.:*:) gelements gelements + {-# INLINE gelements #-} instance GElements GHC.U1 where gelements = dimap (const ()) (const GHC.U1) oneP @@ -3088,13 +3234,16 @@ gtuple => 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 #-} instance (GElements f, GElements g) => GContents (f GHC.:*: g) where gcontents = jsonTuple gelements + {-# INLINE gcontents #-} instance GContents GHC.U1 where gcontents = jsonTuple gelements @@ -3104,5 +3253,7 @@ 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 #-} From bb65054b5e625763321fcd9ad00c8fa298c995c2 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sat, 7 Nov 2026 18:51:24 -0800 Subject: [PATCH 055/130] Encode an array's elements as they're rendered, without a list MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Rendering a tuple collected its elements in a list, which the printer then turned into an array. AesonVal now has associated elements: for Encoding, the elements so far, separated by commas & bracketed at the end, so that an inlined tuple encodes straight into its builder; for Value, still a list, made an array once. The tuple printor's JsonTup & Profunctor instances are specialized to Value & Encoding, so that code which isn't inlined renders elements without an AesonVal dictionary. Json ÷ aeson, A/B against the previous commit: encode tuples 0.55x -> 0.21x, pairMap 1.20x -> 1.10x, rose 1.57x -> 1.52x; toValue tuples & pairMap unchanged, rose 1.52x -> 1.62x. Co-Authored-By: Claude Opus 5.5 --- .../src/Control/Lens/Grammar/Json.hs | 78 ++++++++++++++----- 1 file changed, 60 insertions(+), 18 deletions(-) diff --git a/distributors-json/src/Control/Lens/Grammar/Json.hs b/distributors-json/src/Control/Lens/Grammar/Json.hs index 4298664e..7847cfb7 100644 --- a/distributors-json/src/Control/Lens/Grammar/Json.hs +++ b/distributors-json/src/Control/Lens/Grammar/Json.hs @@ -139,6 +139,7 @@ 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) @@ -1130,6 +1131,14 @@ class AesonStr val => AesonVal val where aesonProp :: AesonKey val -> val -> AesonProps val -> AesonProps val aesonPropsEmpty :: AesonProps val aesonProps :: AesonProps 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 @@ -1156,6 +1165,13 @@ instance AesonVal Value where aesonProp key value rest = (key, value) : rest aesonPropsEmpty = [] aesonProps = Object . KeyMap.fromList + type AesonElems Value = [Value] + aesonElem = (:) + aesonElemsEmpty = [] + aesonElems = aesonList id + {-# INLINE aesonElem #-} + {-# INLINE aesonElemsEmpty #-} + {-# INLINE aesonElems #-} {-# INLINE aesonNull #-} {-# INLINE aesonBool #-} {-# INLINE aesonNumber #-} @@ -1192,6 +1208,21 @@ instance AesonVal Encoding where aesonProp key value rest = Encoding.pair' key value <> rest aesonPropsEmpty = mempty aesonProps = Encoding.pairs + 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 #-} @@ -1266,15 +1297,16 @@ 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 -> [val] -> [val]) + , tupPrintorRender :: !(a -> AesonElems val -> AesonElems val) , tupPrintorCheck :: !(a -> Elements val) , tupPrintorElement :: !(Maybe (a -> val)) } -- | Render a single element, before the rest. -renderElement :: (a -> val) -> a -> [val] -> [val] +renderElement + :: AesonVal val => (a -> val) -> a -> AesonElems val -> AesonElems val renderElement render a rest = - let printed = render a in printed `seq` printed : rest + let printed = render a in printed `seq` aesonElem printed rest {-# INLINE renderElement #-} -- | Printed elements, counted to locate a failure of a later element. @@ -1500,7 +1532,9 @@ instance Applicative (TupPrintor val a) where Nothing {-# INLINE pure #-} {-# INLINE (<*>) #-} -instance Profunctor (TupPrintor val) where +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 @@ -1514,7 +1548,7 @@ instance Profunctor (TupPrintor val) where {-# INLINE lmap #-} _ #. p = coerce p p .# _ = coerce p -instance CocartesianMonoidal (TupPrintor val) where +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) @@ -1524,11 +1558,11 @@ instance CocartesianMonoidal (TupPrintor val) where Right b -> tupPrintorRender q b rest) (either (tupPrintorCheck p) (tupPrintorCheck q)) Nothing -instance Distributor (TupPrintor val) where +instance AesonVal val => Distributor (TupPrintor val) where manyP p = TupPrintor (\rules -> tupPrintorTotal p rules) (fmap mconcat . tryAll (tupPrintorTotal p) (tupPrintorTry p) - (\a -> DList.fromList (tupPrintorRender p a []))) + (\a -> fromMaybe mempty (tupPrintorTry p a))) (\as rest -> foldr (\a printed -> tupPrintorRender p a $! printed) rest as) (foldMap (tupPrintorCheck p)) Nothing @@ -1539,14 +1573,14 @@ instance Distributor (TupPrintor val) where (foldMap (tupPrintorCheck p)) Nothing -- | `optionP` omits its default. -instance Alternative (TupPrintor val a) where +instance AesonVal val => Alternative (TupPrintor val a) where empty = falseP (<|>) = (>|<) many = lmap repeat . manyP some = lmap repeat . someP -instance Alternator (TupPrintor val) where +instance AesonVal val => Alternator (TupPrintor val) where optionP def p = pureP def >|< p -instance Choice (TupPrintor val) where +instance AesonVal val => Choice (TupPrintor val) where left' = alternate . Left right' = alternate . Right unprintable :: Elements val @@ -1554,11 +1588,16 @@ unprintable = Elements (jsonUnexpected Nothing) -- | A partial `TupPrintor`, rendering what it tries, or else nothing. tupTrying - :: (a -> Maybe (DList val)) -> (a -> Elements val) -> TupPrintor val a b + :: AesonVal val + => (a -> Maybe (DList val)) -> (a -> Elements val) -> TupPrintor val a b tupTrying attempt check = TupPrintor (const False) attempt - (\a -> DList.apply (fromMaybe mempty (attempt a))) check Nothing + (\a -> prependElems (fromMaybe mempty (attempt a))) check Nothing -instance CocartesianChoice (TupPrintor val) where +-- | 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)) @@ -1566,13 +1605,13 @@ instance CocartesianChoice (TupPrintor val) where Right p -> tupTrying (either (const Nothing) (tupPrintorTry p)) (either (\_ -> unprintable) (tupPrintorCheck p)) -instance DisjunctiveMonoid (TupPrintor val a b) where +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) (`DList.apply` rest) (tupPrintorTry p a)) + (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)) @@ -1580,7 +1619,10 @@ instance DisjunctiveMonoid (TupPrintor val a b) where (printed, _) -> printed) Nothing -instance JsonTup (JsonPrintor val) (TupPrintor val) where +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) @@ -1713,12 +1755,12 @@ the instance's specializations needn't break their recursion through `jsonTuple` itself, which would stop it from inlining. -} printTuple - :: AesonVal val + :: forall val a b. AesonVal val => (forall q. JsonTup (JsonPrintor val) q => q a b) -> JsonPrintor val a b printTuple tup = JsonPrintor (\rules -> tupPrintorTotal tup rules) (fmap (aesonList id . toList) . tupPrintorTry tup) - (\a -> aesonList id (tupPrintorRender tup a [])) + (\a -> aesonElems (tupPrintorRender tup a (aesonElemsEmpty @val))) (\a -> case tupPrintorCheck tup a of Elements printed -> aesonList id . toList . snd <$> printed) Nothing From 6d74a60d90fbe2a00656ff06e2a8b785bb0f4ebe Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sat, 7 Nov 2026 19:17:01 -0800 Subject: [PATCH 056/130] Write a Value array's elements evaluated, not as thunks MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit aesonList wrote each element into its array lazily, allocating a thunk per element which forcing the Value later evaluated & updated. Writing it evaluated skips that. Json ÷ aeson toValue, A/B against the previous commit: geometric mean 0.875x -> 0.797x; ints 0.88x -> 0.67x, texts 0.86x -> 0.62x, maybes 0.71x -> 0.55x, nested 0.80x -> 0.63x, tuples 1.43x -> 1.30x, eithers 1.34x -> 1.16x; but recursive rose 1.50x -> 1.72x & deep 1.07x -> 1.15x. Co-Authored-By: Claude Opus 5.5 --- distributors-json/src/Control/Lens/Grammar/Json.hs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/distributors-json/src/Control/Lens/Grammar/Json.hs b/distributors-json/src/Control/Lens/Grammar/Json.hs index 7847cfb7..855e819d 100644 --- a/distributors-json/src/Control/Lens/Grammar/Json.hs +++ b/distributors-json/src/Control/Lens/Grammar/Json.hs @@ -1151,7 +1151,7 @@ instance AesonVal Value where let write _ [] = pure array write i (a : rest) = - MVector.unsafeWrite array i (f a) >> write (i + 1) rest + (MVector.unsafeWrite array i $! f a) >> write (i + 1) rest write 0 as aesonObject = Object . KeyMap.fromList aesonMap key fold render = Object . KeyMap.fromList . fold property [] From d247c9528b9dee2b3cb9732a504b533aaf221cad Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sun, 8 Nov 2026 06:02:03 -0800 Subject: [PATCH 057/130] Compile derived Json instances: default json to jsonGeneric directly The class default went through the Json (Generically a) instance, whose grammar GHC specialized at a type's representation but left polymorphic in the interpreter p: printers were built at runtime from dictionaries. Defaulting json to jsonGeneric directly lets a derived instance compile to a printer & parser at its type. (makePrisms ''These moves up, so the generic classes are in scope at the class declaration.) printTuple now instantiates its rank-2 grammar once. At -O2, each field's instantiation was specialized to a function of a void argument, so a tuple's printor was rebuilt per value (rose encode 2.9x aeson). Json/aeson: deep encode 1.26x -> 0.99x, deep fromValue 0.94x -> 0.76x, enums encode 1.38x -> 1.18x, enums toValue 0.34x -> 0.20x, rose encode 1.42x -> 1.32x, rose toValue ~1.6x -> ~1.45x; sums & variants fromValue ~5-10% slower (~0.72x). Co-Authored-By: Claude Opus 5.5 --- .../src/Control/Lens/Grammar/Json.hs | 27 +++++++++++-------- 1 file changed, 16 insertions(+), 11 deletions(-) diff --git a/distributors-json/src/Control/Lens/Grammar/Json.hs b/distributors-json/src/Control/Lens/Grammar/Json.hs index 855e819d..bc00be32 100644 --- a/distributors-json/src/Control/Lens/Grammar/Json.hs +++ b/distributors-json/src/Control/Lens/Grammar/Json.hs @@ -264,6 +264,7 @@ import Witherable qualified -- >>> let explain err = formatError (jsonErrorPath err) (jsonErrorMessage err) makePrisms ''Value +makePrisms ''These -- Json grammars -- @@ -276,8 +277,12 @@ class Json a where -- | `Aeson.toJSON` & `Aeson.parseJSON`, as one grammar. json :: JsonVal p => p a a - default json :: (Json (GHC.Generically a), JsonVal p) => p a a - json = iso GHC.Generically coerce >~ json + 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`, an array of values by default. @@ -1757,13 +1762,15 @@ the instance's specializations needn't break their recursion through printTuple :: forall val a b. AesonVal val => (forall q. JsonTup (JsonPrintor val) q => q a b) -> JsonPrintor val a b -printTuple tup = JsonPrintor - (\rules -> tupPrintorTotal tup rules) - (fmap (aesonList id . toList) . tupPrintorTry tup) - (\a -> aesonElems (tupPrintorRender tup a (aesonElemsEmpty @val))) - (\a -> case tupPrintorCheck tup a of - Elements printed -> aesonList id . toList . snd <$> printed) - Nothing +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. @@ -2462,8 +2469,6 @@ overKey f = \case -- Json instances -makePrisms ''These - -- base instance Json Bool where json = jsonBool From 6f81f756a1ca2f97e3f1f84d3a47c548a17e23e1 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sun, 8 Nov 2026 06:18:07 -0800 Subject: [PATCH 058/130] Update Json.hs --- .../src/Control/Lens/Grammar/Json.hs | 67 ++++++++++--------- 1 file changed, 34 insertions(+), 33 deletions(-) diff --git a/distributors-json/src/Control/Lens/Grammar/Json.hs b/distributors-json/src/Control/Lens/Grammar/Json.hs index bc00be32..2e8dc5a2 100644 --- a/distributors-json/src/Control/Lens/Grammar/Json.hs +++ b/distributors-json/src/Control/Lens/Grammar/Json.hs @@ -117,12 +117,12 @@ module Control.Lens.Grammar.Json , JsonTup (..) , JsonStr (..) -- * Types - , JsonType (..) - , JsonElements (..) - , JsonProperty (..) , jsonType , jsonTsDeclarations , jsonTsPut + , JsonType (..) + , JsonElements (..) + , JsonProperty (..) -- * Errors , JsonError (..) , JsonErrorSort (..) @@ -1830,9 +1830,9 @@ data JsonElements = JsonElement JsonType -- ^ an element | JsonElements JsonElements -- ^ elements, repeated any number of times | JsonElements1 JsonElements -- ^ elements, repeated at least once - | JsonOptional JsonElements -- ^ elements, or none - | JsonSequence [JsonElements] -- ^ elements, in order - | JsonAlternate [JsonElements] -- ^ elements of any of some alternatives + | JsonElementsOpt JsonElements -- ^ elements, or none + | JsonElementsTup [JsonElements] -- ^ elements, in order + | JsonElementsAlt [JsonElements] -- ^ elements of any of some alternatives deriving stock (Eq, Ord, Show, Read) -- | A property of a `JsonObject`. @@ -1864,55 +1864,55 @@ jsonSubtype = \case t -> JsonSubtype t instance Semigroup JsonElements where - JsonAlternate [] <> _ = falseP - _ <> JsonAlternate [] = falseP + 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 -> JsonSequence els + els -> JsonElementsTup els _ -> falseP where -- Sequenced elements, or none, for no sequence of elements. flatten = \case - JsonAlternate [] -> Nothing - JsonSequence els -> Just els + JsonElementsAlt [] -> Nothing + JsonElementsTup els -> Just els els -> Just [els] instance Monoid JsonElements where - mempty = JsonSequence [] + mempty = JsonElementsTup [] instance DisjunctiveMonoid JsonElements where - falseP = JsonAlternate [] + falseP = JsonElementsAlt [] a >|< b | a == b = a - JsonAlternate [] >|< b = b - a >|< JsonAlternate [] = a - JsonElements1 a >|< JsonSequence [] = starK a - JsonSequence [] >|< JsonElements1 b = starK b - a >|< JsonSequence [] = optK a - JsonSequence [] >|< b = optK b + 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 -> JsonAlternate alts + alts -> JsonElementsAlt alts where flatten = \case - JsonAlternate alts -> alts + JsonElementsAlt alts -> alts els -> [els] instance KleeneStarAlgebra JsonElements where starK = \case - JsonAlternate [] -> mempty - JsonSequence [] -> mempty + JsonElementsAlt [] -> mempty + JsonElementsTup [] -> mempty els -> JsonElements els plusK = \case - JsonAlternate [] -> falseP - JsonSequence [] -> mempty + JsonElementsAlt [] -> falseP + JsonElementsTup [] -> mempty els -> JsonElements1 els optK = \case - JsonAlternate [] -> mempty - JsonSequence [] -> mempty + JsonElementsAlt [] -> mempty + JsonElementsTup [] -> mempty JsonElements1 els -> starK els els@(JsonElements _) -> els - els@(JsonOptional _) -> els - els -> JsonOptional 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. @@ -2040,7 +2040,7 @@ instance JsonVal JsonTypor where jsonTuple tup = JsonTypor (tuple <$> getAp (runTupTypor tup)) where tuple = \case - JsonAlternate [] -> falseP + JsonElementsAlt [] -> falseP els -> JsonArray els jsonObject obj = JsonTypor (objects <$> getAp (runObjTypor obj)) where @@ -2126,15 +2126,15 @@ elementType = \case tupleShapes :: JsonElements -> [[TupleElement]] tupleShapes = \case JsonElement t -> [[RequiredElement t]] - JsonSequence els -> map concat (traverse tupleShapes els) - JsonAlternate alts -> concatMap tupleShapes alts + 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) ] - JsonOptional els -> tupleShapes els <> [[]] + JsonElementsOpt els -> tupleShapes els <> [[]] -- TypeScript -- @@ -2846,6 +2846,7 @@ 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 + {-# INLINABLE json #-} instance (Typeable a, Json a) => Json (Tree a) where json = jsonTyped gtuple From 323f094179e7e382e8820d51f084821709479706 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sun, 8 Nov 2026 06:49:54 -0800 Subject: [PATCH 059/130] Add jsonEnum, an enumeration by a Comonocle's copies & their names jsonEnum enumed name tables an enumeration once, by jsonEnumWith, numbering each value by fromEnumerable. jsonEnumWith stays the method, the fast primitive that generic enums use with dataToTag#. Also drop INLINABLE on Map's json: it didn't help (pairMap toValue 1.61x -> 1.69x aeson, the rest flat). Co-Authored-By: Claude Opus 5.5 --- .../src/Control/Lens/Grammar/Json.hs | 25 +++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/distributors-json/src/Control/Lens/Grammar/Json.hs b/distributors-json/src/Control/Lens/Grammar/Json.hs index 2e8dc5a2..5ca89726 100644 --- a/distributors-json/src/Control/Lens/Grammar/Json.hs +++ b/distributors-json/src/Control/Lens/Grammar/Json.hs @@ -115,7 +115,7 @@ module Control.Lens.Grammar.Json , JsonVal (..), jsonTyped , JsonObj (..), (!=) , JsonTup (..) - , JsonStr (..) + , JsonStr (..), jsonEnum -- * Types , jsonType , jsonTsDeclarations @@ -132,6 +132,7 @@ module Control.Lens.Grammar.Json import Control.Applicative import Control.Lens import Control.Lens.Grammar +import Control.Lens.Monocle (AComonocle, withComonocle) import Control.Monad import Control.Monad.Trans.Class (lift) import Control.Monad.Trans.Reader (ReaderT, ask, local, runReaderT) @@ -553,6 +554,27 @@ class 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.Monocle (enumed) +>>> 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 enumed 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 (toEnumerable () 0) + in jsonEnumWith (fromIntegral . 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 (`>+<`, `>|<`), @@ -2846,7 +2868,6 @@ 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 - {-# INLINABLE json #-} instance (Typeable a, Json a) => Json (Tree a) where json = jsonTyped gtuple From 31912b6267dc59d0ddcbf73dc301ae9d3c9d8d14 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sun, 8 Nov 2026 07:10:04 -0800 Subject: [PATCH 060/130] Unify jsonOmitField & jsonOmittedField as a prism, jsonOmitted jsonOmitted :: Maybe (APrism' a ()), like lens's nearly: it matches the value a record omits, by omitNothingFields, & reviews the value of an omitted field, by allowOmittedFields. As a prism, what's omitted when printing is what's restored when parsing, so omitted fields round-trip. Co-Authored-By: Claude Opus 5.5 --- .../src/Control/Lens/Grammar/Json.hs | 52 ++++++++----------- 1 file changed, 22 insertions(+), 30 deletions(-) diff --git a/distributors-json/src/Control/Lens/Grammar/Json.hs b/distributors-json/src/Control/Lens/Grammar/Json.hs index 5ca89726..9a3463b5 100644 --- a/distributors-json/src/Control/Lens/Grammar/Json.hs +++ b/distributors-json/src/Control/Lens/Grammar/Json.hs @@ -306,17 +306,13 @@ class Json a where jsonKeyList :: Maybe (forall k. JsonStr k => k [a] [a]) jsonKeyList = Nothing - {- | `Data.Aeson.omitField`, whether a record's field of the value - may be omitted, by `Aeson.omitNothingFields`. + {- | `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 `Aeson.omitNothingFields`, + & reviews the value of a field omitted by `Aeson.allowOmittedFields`. -} - jsonOmitField :: a -> Bool - jsonOmitField _ = False - - {- | `Data.Aeson.omittedField`, the value of a record's field which is - omitted, by `Aeson.allowOmittedFields`. - -} - jsonOmittedField :: Maybe a - jsonOmittedField = Nothing + jsonOmit :: Maybe (APrism' a ()) + jsonOmit = Nothing -- Running Json grammars -- @@ -2500,8 +2496,7 @@ instance Json Ordering where json = jsonTyped (enumerated (Text.pack . show)) instance Json () where json = jsonTuple oneP - jsonOmitField _ = True - jsonOmittedField = Just () + jsonOmit = Just (only ()) instance Json Void where json = zeroP jsonKey = Just (prism' absurd (const Nothing) ?< jsonText) @@ -2524,8 +2519,7 @@ instance Json a => Json [a] where jsonKey = jsonKeyList @a instance Json a => Json (Maybe a) where json = jsonNullable json - jsonOmitField = isNothing - jsonOmittedField = Just Nothing + jsonOmit = Just _Nothing instance (Json a, Json b) => Json (Either a b) where json = jsonTag "Left" json >+< jsonTag "Right" json instance Json Double where @@ -2600,15 +2594,13 @@ instance Json a => Json (Solo a) where jsonKeyList = overKey (iso (map getSolo) (map MkSolo) >~) (jsonKeyList @a) instance Json a => Json (Identity a) where json = coerced >~ json @a - jsonOmitField = coerce (jsonOmitField @a) - jsonOmittedField = coerce (jsonOmittedField @a) + jsonOmit = (coerced .) <$> jsonOmit @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 = coerce (jsonOmitField @a) - jsonOmittedField = coerce (jsonOmittedField @a) + jsonOmit = (coerced .) <$> jsonOmit @a jsonKey = overKey (coerced >~) (jsonKey @a) instance Json (f (g a)) => Json (Compose f g a) where json = coerced >~ json @(f (g a)) @@ -2652,8 +2644,7 @@ 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 _ = True - jsonOmittedField = Just Proxy + jsonOmit = 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 @@ -3049,8 +3040,7 @@ instance (Functor f, Typeable f, Json (f (Fix f))) => Json (Nu f) where -- jsonTag instance Json b => Json (Tagged a b) where json = coerced >~ json @b - jsonOmitField = coerce (jsonOmitField @b) - jsonOmittedField = coerce (jsonOmittedField @b) + jsonOmit = (coerced .) <$> jsonOmit @b jsonKey = overKey (coerced >~) (jsonKey @b) jsonKeyList = overKey (coerced >~) (jsonKeyList @b) @@ -3076,8 +3066,7 @@ instance (Json (f a), Json (g a)) => Json (These1 f g a) where -- strict instance Json a => Json (Strict.Maybe a) where json = iso Strict.toLazy Strict.toStrict >~ json @(Maybe a) - jsonOmitField = Strict.isNothing - jsonOmittedField = Just Strict.Nothing + jsonOmit = 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 @@ -3262,16 +3251,19 @@ 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` & `jsonOmittedField`. + -- An omittable field, by `jsonOmit`. property :: (JsonVal p, JsonObj p q) => q a a - property = case jsonOmittedField @a of + property = case jsonOmit @a of Just omitted | Aeson.allowOmittedFields opts || Aeson.omitNothingFields opts -> - dimap present (fromMaybe omitted) (key ?: json) + 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 - present a - | Aeson.omitNothingFields opts && jsonOmitField a = Nothing - | otherwise = Just a gfield = Just ((GHC.M1 . GHC.K1) #. json .# GHC.unK1 . GHC.unM1) {-# INLINE gfields #-} {-# INLINE gfield #-} From 1ac0dfab7e6e3f6171362b635c549e03d64906c1 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sun, 8 Nov 2026 07:20:56 -0800 Subject: [PATCH 061/130] Rename enumerated & enumed to _Enumerable & _BoundedEnum Co-Authored-By: Claude Opus 5.5 --- distributors-core/CHANGELOG.md | 2 +- distributors-core/src/Control/Lens/Monocle.hs | 38 +++++++++---------- .../test/Properties/Homogeneous.hs | 20 +++++----- .../src/Control/Lens/Grammar/Json.hs | 14 +++---- 4 files changed, 37 insertions(+), 37 deletions(-) diff --git a/distributors-core/CHANGELOG.md b/distributors-core/CHANGELOG.md index 15ec13a7..f7365d4d 100644 --- a/distributors-core/CHANGELOG.md +++ b/distributors-core/CHANGELOG.md @@ -8,7 +8,7 @@ countable sums of single copies, sequenced `enumerably` by `CocartesianMonoidal`s, with generic defaults by `Generic1`. - `Comonocle`s, in `Control.Lens.Monocle`, dual to `Monocle`s by sums: - `comonocle`, `enumerated`, & concrete + `comonocle`, `_Enumerable`, `_BoundedEnum`, & concrete `Comonocular`s, with `runComonocular`. - `WrappedPafb f p` is `CocartesianMonoidal` for any `Functor f`. - `AComonocle`, `withComonocle`, `cloneComonocle`, `mapComonocle`, diff --git a/distributors-core/src/Control/Lens/Monocle.hs b/distributors-core/src/Control/Lens/Monocle.hs index 7cbf5036..bacd36b5 100644 --- a/distributors-core/src/Control/Lens/Monocle.hs +++ b/distributors-core/src/Control/Lens/Monocle.hs @@ -43,8 +43,8 @@ module Control.Lens.Monocle , enumerateComonocle , zipComonocle , zipWithComonocle - , enumerated - , enumed + , _Enumerable + , _BoundedEnum -- * Comonocular , Comonocular (..), runComonocular ) where @@ -159,7 +159,7 @@ Every `Control.Lens.Iso.Iso` is a `Comonocle`, & every `Comonocle` is a `Control.Lens.Lens.Lens`, whose residue is which copy is held. ->>> view enumerated (Identity 'a') +>>> view _Enumerable (Identity 'a') 'a' `Comonocle`s are isomorphic to `Comonocular`s. @@ -202,7 +202,7 @@ mapComonocle mon = withComonocle mon $ \split merge -> 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 enumerated) 'x' (Right (Identity 'y')) +>>> set (altComonocle id _Enumerable) 'x' (Right (Identity 'y')) Right (Identity 'x') -} altComonocle @@ -216,7 +216,7 @@ altComonocle x y p = rmap (either (fmap Left) (fmap Right)) since products of sums of copies distribute, \(m a \times n c = (m n) (a \times c)\). ->>> over (crossComonocle enumerated id) (\(a, c) -> (a + c, show c)) (Identity 1, 2) +>>> over (crossComonocle _Enumerable id) (\(a, c) -> (a + c, show c)) (Identity 1, 2) (Identity 3,"2") -} crossComonocle @@ -271,7 +271,7 @@ 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 (enumed @Ordering) +>>> countComonocle (_BoundedEnum @Ordering) 3 -} countComonocle :: AComonocle s t a b -> Natural @@ -284,9 +284,9 @@ countComonocle mon = withComonocle mon $ \split _ -> copies split {- | The copy of `AComonocle` at an index, holding a focus, if there is one, like `toEnum`, & inverse to `indexComonocle`. ->>> toEnumComonocle enumed () 2 :: Maybe Ordering +>>> toEnumComonocle _BoundedEnum () 2 :: Maybe Ordering Just GT ->>> toEnumComonocle enumed () 3 :: Maybe Ordering +>>> toEnumComonocle _BoundedEnum () 3 :: Maybe Ordering Nothing -} toEnumComonocle :: AComonocle s t a b -> b -> Natural -> Maybe t @@ -295,9 +295,9 @@ toEnumComonocle mon b copy = withComonocle mon $ \_ merge -> merge <$> toEnumera {- | The next copy of `AComonocle`, holding the same focus, if there is one, like `succ`. ->>> succComonocle enumed EQ +>>> succComonocle _BoundedEnum EQ Just GT ->>> succComonocle enumed GT +>>> succComonocle _BoundedEnum GT Nothing -} succComonocle :: AComonocle s s a a -> s -> Maybe s @@ -306,9 +306,9 @@ succComonocle mon s = withComonocle mon $ \split merge -> merge <$> succEnumerab {- | The previous copy of `AComonocle`, holding the same focus, if there is one, like `pred`. ->>> predComonocle enumed EQ +>>> predComonocle _BoundedEnum EQ Just LT ->>> predComonocle enumed LT +>>> predComonocle _BoundedEnum LT Nothing -} predComonocle :: AComonocle s s a a -> s -> Maybe s @@ -317,7 +317,7 @@ predComonocle mon s = withComonocle mon $ \split merge -> merge <$> predEnumerab {- | The copies of `AComonocle` from one onward, holding the same focus, like `enumFrom`. ->>> enumerateComonocle enumed False +>>> enumerateComonocle _BoundedEnum False [False,True] >>> enumerateComonocle (altComonocle id id) (Left 'x' :: Either Char Char) [Left 'x',Right 'x'] @@ -328,20 +328,20 @@ enumerateComonocle mon s = {- | The `Comonocle` of an `Enumerable` sum's copy. ->>> over enumerated (+ 1) (Identity 1) +>>> over _Enumerable (+ 1) (Identity 1) Identity 2 -} -enumerated :: Enumerable f => Comonocle (f a) (f b) a b -enumerated = unwrapPafb . enumerably . WrapPafb +_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 enumed) True +>>> iview (indexComonocle _BoundedEnum) True (1,()) -} -enumed :: (Enum a, Bounded a) => Comonocle a a () () -enumed = iso (\x -> (x,())) (\(x,()) -> x) . enumerated +_BoundedEnum :: (Bounded a, Enum a) => Comonocle a a () () +_BoundedEnum = iso (\x -> (x,())) (\(x,()) -> x) . _Enumerable {- | `Comonocular` provides a concrete representation of `Comonocle`s, by an `Enumerable` sum of copies. diff --git a/distributors-core/test/Properties/Homogeneous.hs b/distributors-core/test/Properties/Homogeneous.hs index 061583e8..52606c31 100644 --- a/distributors-core/test/Properties/Homogeneous.hs +++ b/distributors-core/test/Properties/Homogeneous.hs @@ -271,16 +271,16 @@ homogeneousProperties = do === indexing (unleft (lmap (either id absurd) p) :: Indexing Bool Int) zipporahLaws describe "Comonocle & Diopter combinators" $ do - prop "countComonocle enumed is the number of values" $ - countComonocle (enumed @Int8) === 256 .&&. countComonocle (enumed @Bool) === 2 - prop "toEnumComonocle enumed inverts indexComonocle" $ \(e :: Int8) -> - toEnumComonocle enumed () (fst (iview (indexComonocle enumed) e)) === Just e - prop "succComonocle enumed is succ, but at maxBound" $ \(e :: Int8) -> - succComonocle enumed e === if e == maxBound then Nothing else Just (succ e) - prop "predComonocle enumed is pred, but at minBound" $ \(e :: Int8) -> - predComonocle enumed e === if e == minBound then Nothing else Just (pred e) - prop "enumerateComonocle enumed is enumFrom" $ \(e :: Ordering) -> - enumerateComonocle enumed e === [e ..] + prop "countComonocle _BoundedEnum is the number of values" $ + countComonocle (_BoundedEnum @Int8) === 256 .&&. countComonocle (_BoundedEnum @Bool) === 2 + prop "toEnumComonocle _BoundedEnum inverts indexComonocle" $ \(e :: Int8) -> + toEnumComonocle _BoundedEnum () (fst (iview (indexComonocle _BoundedEnum) e)) === Just e + prop "succComonocle _BoundedEnum is succ, but at maxBound" $ \(e :: Int8) -> + succComonocle _BoundedEnum e === if e == maxBound then Nothing else Just (succ e) + prop "predComonocle _BoundedEnum is pred, but at minBound" $ \(e :: Int8) -> + predComonocle _BoundedEnum e === if e == minBound then Nothing else Just (pred e) + prop "enumerateComonocle _BoundedEnum is enumFrom" $ \(e :: Ordering) -> + enumerateComonocle _BoundedEnum e === [e ..] prop "zipDiopter homogenized is zipHomogeneous" $ \(xss :: [[Int]]) -> zipDiopter homogenized (Just . sum) ([1, 2] : xss) === zipHomogeneous (Just . sum) ([1, 2 :: Int] : xss) diff --git a/distributors-json/src/Control/Lens/Grammar/Json.hs b/distributors-json/src/Control/Lens/Grammar/Json.hs index 9a3463b5..e703966f 100644 --- a/distributors-json/src/Control/Lens/Grammar/Json.hs +++ b/distributors-json/src/Control/Lens/Grammar/Json.hs @@ -554,11 +554,11 @@ class which `jsonEnumWith` tables once, numbered as `fromEnumerable` numbers them. >>> import Control.Lens (coerced) ->>> import Control.Lens.Monocle (enumed) +>>> import Control.Lens.Monocle (_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 enumed name +>>> instance Json Order where json = coerced >~ jsonEnum _BoundedEnum name >>> jsonPrint (Order GT) String "gt" >>> jsonParse @Order (Aeson.String "lt") @@ -2386,8 +2386,8 @@ tsTuples shapes = merged (nub (concatMap (expand False . mergeRests) shapes)) -- Json instance helpers -- | An enumeration of a bounded `Enum`, by the names of its values. -enumerated :: (Bounded a, Enum a, JsonStr p) => (a -> Text) -> p a a -enumerated name = jsonEnumWith +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]] @@ -2491,9 +2491,9 @@ overKey f = \case instance Json Bool where json = jsonBool {-# INLINE json #-} - jsonKey = Just (enumerated (\b -> if b then "true" else "false")) + jsonKey = Just (jsonEnumerated (\b -> if b then "true" else "false")) instance Json Ordering where - json = jsonTyped (enumerated (Text.pack . show)) + json = jsonTyped (jsonEnumerated (Text.pack . show)) instance Json () where json = jsonTuple oneP jsonOmit = Just (only ()) @@ -3002,7 +3002,7 @@ instance Json DayOfWeek where -- | Quarters of the year, named as @aeson@ names them. quarters :: JsonStr p => p QuarterOfYear QuarterOfYear -quarters = enumerated (Text.toLower . Text.pack . show) +quarters = jsonEnumerated (Text.toLower . Text.pack . show) instance Json QuarterOfYear where json = jsonTyped quarters From 3e33c261dc22bb42bd3f423b0682b364d2bd6886 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sun, 8 Nov 2026 07:30:26 -0800 Subject: [PATCH 062/130] Untangle core from grammars: MonadicTry & terminal separators move up MonadicTry moves to Control.Monad.Fail.Try, so Data.Profunctor.Monadic no longer imports it, & sepWith, beginWith & endWith move to Control.Lens.Grammar.Symbol, beside terminal, so Data.Profunctor.Separator no longer imports grammar symbols. No module outside the grammars now imports one, which a split of them into their own package needs. Co-Authored-By: Claude Opus 5.5 --- distributors-core/CHANGELOG.md | 6 +++++ .../src/Control/Lens/Grammar/Symbol.hs | 24 +++++++++++++++++++ .../src/Control/Monad/Fail/Try.hs | 5 ++++ .../src/Data/Profunctor/Monadic.hs | 7 ------ .../src/Data/Profunctor/Separator.hs | 23 ------------------ .../src/Control/Lens/Grammar/TypeScript.hs | 4 ++-- 6 files changed, 37 insertions(+), 32 deletions(-) diff --git a/distributors-core/CHANGELOG.md b/distributors-core/CHANGELOG.md index f7365d4d..d81bc84c 100644 --- a/distributors-core/CHANGELOG.md +++ b/distributors-core/CHANGELOG.md @@ -31,6 +31,12 @@ - `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. +- `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`, `beginWith` & `endWith` move from `Data.Profunctor.Separator` + to `Control.Lens.Grammar.Symbol`, beside `terminal`, so that + `Data.Profunctor.Separator` needn't import grammar symbols. ## 0.6.0.0 - 2026-04-24 diff --git a/distributors-core/src/Control/Lens/Grammar/Symbol.hs b/distributors-core/src/Control/Lens/Grammar/Symbol.hs index a36ec396..2bdcbdcf 100644 --- a/distributors-core/src/Control/Lens/Grammar/Symbol.hs +++ b/distributors-core/src/Control/Lens/Grammar/Symbol.hs @@ -12,6 +12,10 @@ module Control.Lens.Grammar.Symbol ( -- * Symbol TerminalSymbol (..) , NonTerminalSymbol (..) + -- * Separators + , sepWith + , beginWith + , endWith ) where import Control.Lens @@ -20,6 +24,7 @@ import Control.Lens.Grammar.Token import Data.Bifunctor.Joker import Data.Profunctor import Data.Profunctor.Monoidal +import Data.Profunctor.Separator (SepBy (..), sepBy) import Text.ParserCombinators.ReadP (ReadP, string) -- | A `terminal` symbol in a grammar. @@ -34,6 +39,25 @@ class TerminalSymbol token s | s -> token where class NonTerminalSymbol s where nonTerminal :: String -> s +{- | 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} + -- instances instance TerminalSymbol token (f ()) => TerminalSymbol token (Joker f () ()) where diff --git a/distributors-core/src/Control/Monad/Fail/Try.hs b/distributors-core/src/Control/Monad/Fail/Try.hs index 6167a921..3c1e7677 100644 --- a/distributors-core/src/Control/Monad/Fail/Try.hs +++ b/distributors-core/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,6 +27,7 @@ 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 @@ -55,6 +57,9 @@ class default try :: m a -> m a try = id +{- | A `Profunctor` which is also a `MonadTry`. -} +type MonadicTry p = (Profunctor p, forall x. MonadTry (p x)) + instance MonadTry m => MonadTry (Joker m a) where try = Joker . try . runJoker instance MonadTry ReadP diff --git a/distributors-core/src/Data/Profunctor/Monadic.hs b/distributors-core/src/Data/Profunctor/Monadic.hs index beb78ee0..ba2a0713 100644 --- a/distributors-core/src/Data/Profunctor/Monadic.hs +++ b/distributors-core/src/Data/Profunctor/Monadic.hs @@ -26,15 +26,11 @@ module Data.Profunctor.Monadic , (>>=) , (>>) , return - -- * MonadicTry - , MonadicTry - , try , fail ) where import Control.Lens import Control.Monad hiding ((>>=), (>>), return) -import Control.Monad.Fail.Try import Data.Profunctor.Monoidal import Prelude hiding ((>>=), (>>), return) @@ -65,6 +61,3 @@ version of `pureP`. -} 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/distributors-core/src/Data/Profunctor/Separator.hs b/distributors-core/src/Data/Profunctor/Separator.hs index 4941faaa..04c8b00a 100644 --- a/distributors-core/src/Data/Profunctor/Separator.hs +++ b/distributors-core/src/Data/Profunctor/Separator.hs @@ -13,9 +13,6 @@ module Data.Profunctor.Separator SepBy (..) , sepBy , noSep - , sepWith - , beginWith - , endWith -- * SepBy Combinators , several , several1 @@ -30,7 +27,6 @@ module Data.Profunctor.Separator import Control.Lens import Control.Lens.PartialIso -import Control.Lens.Grammar.Symbol import Data.Monoid.Disjunctive (orP) import Data.Profunctor.Distributor import Data.Profunctor.Monoidal.Cocartesian @@ -62,25 +58,6 @@ 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 -} diff --git a/distributors-json/src/Control/Lens/Grammar/TypeScript.hs b/distributors-json/src/Control/Lens/Grammar/TypeScript.hs index 77b99ab8..d3e214c6 100644 --- a/distributors-json/src/Control/Lens/Grammar/TypeScript.hs +++ b/distributors-json/src/Control/Lens/Grammar/TypeScript.hs @@ -568,7 +568,7 @@ tsTokensGrammar = rmap within each, innermost first. -} tokensWithin - :: (Lexical Char p, Alternator p, Filtrator p, P.MonadicTry p) + :: (Lexical Char p, Alternator p, Filtrator p, MonadicTry p) => [Int] -> p [TsToken] [TsToken] tokensWithin depths = orP [ _Cons >? (tokenWithin P.>>= tokensWithin . within depths) @@ -689,7 +689,7 @@ _HexCode = prism' -- | The interpreters of TypeScript's syntax. type TsGrammatical p = - (Lexical TsToken p, Alternator p, Filtrator p, P.MonadicTry 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 From 8587e2825b74bdf592a79b1be5ee3f873c469232 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sun, 8 Nov 2026 07:35:38 -0800 Subject: [PATCH 063/130] Split the grammars into their own package, distributors-grammar distributors keeps the profunctor algebra & optics; distributors-grammar takes Control.Lens.Grammar & its modules, Control.Monad.Fail.Try, Data.Profunctor.Grammar & Parsector, with their tests & doctests. withOperators' example moves to Control.Lens.Grammar, & the internal modules become Control.Lens.Internal.*. distributors drops QuickCheck, random, MemoTrie, monad-loops & mtl (& unused bytestring & text). stack, cabal, the nix flake & CI build the three packages. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 7 +- cabal.project | 1 + distributors-core/CHANGELOG.md | 7 + distributors-core/distributors.cabal | 56 +--- distributors-core/package.yaml | 11 +- .../{Grammar => }/Internal/NestedPrismTH.hs | 4 +- .../Lens/{Grammar => }/Internal/Orphanage.hs | 4 +- .../src/Control/Lens/PartialIso.hs | 4 +- .../src/Data/Profunctor/Separator.hs | 62 +---- distributors-core/test/Main.hs | 146 +---------- distributors-grammar/CHANGELOG.md | 8 + distributors-grammar/LICENSE | 30 +++ distributors-grammar/README.md | 10 + distributors-grammar/Setup.hs | 2 + .../distributors-grammar.cabal | 239 ++++++++++++++++++ distributors-grammar/doctest/Doctests.hs | 7 + distributors-grammar/package.yaml | 104 ++++++++ .../src/Control/Lens/Grammar.hs | 60 +++++ .../src/Control/Lens/Grammar/BackusNaur.hs | 0 .../src/Control/Lens/Grammar/Machine.hs | 0 .../src/Control/Lens/Grammar/RegEx.hs | 0 .../src/Control/Lens/Grammar/Symbol.hs | 0 .../src/Control/Lens/Grammar/Token.hs | 0 .../src/Control/Monad/Fail/Try.hs | 0 .../src/Data/Profunctor/Grammar.hs | 0 .../src/Data/Profunctor/Grammar/Parsector.hs | 0 .../test/Examples/Arithmetic.hs | 0 .../test/Examples/Chain.hs | 0 .../test/Examples/Expression.hs | 0 .../test/Examples/Json.hs | 0 .../test/Examples/Lambda.hs | 0 .../test/Examples/LenVec.hs | 0 .../test/Examples/RegString.hs | 0 .../test/Examples/SExpr.hs | 0 .../test/Examples/SemVer.hs | 0 distributors-grammar/test/Main.hs | 152 +++++++++++ .../test/Properties/Kleene.hs | 0 distributors-json/distributors-json.cabal | 6 +- distributors-json/package.yaml | 1 + flake.nix | 10 +- stack.yaml | 1 + 41 files changed, 658 insertions(+), 274 deletions(-) rename distributors-core/src/Control/Lens/{Grammar => }/Internal/NestedPrismTH.hs (99%) rename distributors-core/src/Control/Lens/{Grammar => }/Internal/Orphanage.hs (97%) create mode 100644 distributors-grammar/CHANGELOG.md create mode 100644 distributors-grammar/LICENSE create mode 100644 distributors-grammar/README.md create mode 100644 distributors-grammar/Setup.hs create mode 100644 distributors-grammar/distributors-grammar.cabal create mode 100644 distributors-grammar/doctest/Doctests.hs create mode 100644 distributors-grammar/package.yaml rename {distributors-core => distributors-grammar}/src/Control/Lens/Grammar.hs (94%) rename {distributors-core => distributors-grammar}/src/Control/Lens/Grammar/BackusNaur.hs (100%) rename {distributors-core => distributors-grammar}/src/Control/Lens/Grammar/Machine.hs (100%) rename {distributors-core => distributors-grammar}/src/Control/Lens/Grammar/RegEx.hs (100%) rename {distributors-core => distributors-grammar}/src/Control/Lens/Grammar/Symbol.hs (100%) rename {distributors-core => distributors-grammar}/src/Control/Lens/Grammar/Token.hs (100%) rename {distributors-core => distributors-grammar}/src/Control/Monad/Fail/Try.hs (100%) rename {distributors-core => distributors-grammar}/src/Data/Profunctor/Grammar.hs (100%) rename {distributors-core => distributors-grammar}/src/Data/Profunctor/Grammar/Parsector.hs (100%) rename {distributors-core => distributors-grammar}/test/Examples/Arithmetic.hs (100%) rename {distributors-core => distributors-grammar}/test/Examples/Chain.hs (100%) rename {distributors-core => distributors-grammar}/test/Examples/Expression.hs (100%) rename {distributors-core => distributors-grammar}/test/Examples/Json.hs (100%) rename {distributors-core => distributors-grammar}/test/Examples/Lambda.hs (100%) rename {distributors-core => distributors-grammar}/test/Examples/LenVec.hs (100%) rename {distributors-core => distributors-grammar}/test/Examples/RegString.hs (100%) rename {distributors-core => distributors-grammar}/test/Examples/SExpr.hs (100%) rename {distributors-core => distributors-grammar}/test/Examples/SemVer.hs (100%) create mode 100644 distributors-grammar/test/Main.hs rename {distributors-core => distributors-grammar}/test/Properties/Kleene.hs (100%) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6bcf6639..9aec33cd 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -26,7 +26,7 @@ jobs: - name: Run HLint uses: haskell-actions/hlint-run@v2 with: - path: '["distributors-core/", "distributors-json/"]' + path: '["distributors-core/", "distributors-grammar/", "distributors-json/"]' fail-on: suggestion - name: Check generated .cabal files match package.yaml @@ -34,7 +34,7 @@ jobs: 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-json; do + for package in distributors-core distributors-grammar distributors-json; do (cd "$package" && ../hpack --force) done git diff --exit-code -I 'by hpack version' -- '*.cabal' @@ -57,6 +57,7 @@ jobs: ~/.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: | @@ -111,7 +112,7 @@ jobs: - name: Check packages run: | - for package in distributors-core distributors-json; do + for package in distributors-core distributors-grammar distributors-json; do (cd "$package" && cabal check) done diff --git a/cabal.project b/cabal.project index e33fe951..3e190f1e 100644 --- a/cabal.project +++ b/cabal.project @@ -1,5 +1,6 @@ packages: distributors-core + distributors-grammar distributors-json tests: True diff --git a/distributors-core/CHANGELOG.md b/distributors-core/CHANGELOG.md index d81bc84c..44506b6a 100644 --- a/distributors-core/CHANGELOG.md +++ b/distributors-core/CHANGELOG.md @@ -28,6 +28,13 @@ ### Breaking Changes +- 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.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. diff --git a/distributors-core/distributors.cabal b/distributors-core/distributors.cabal index d8902025..97ad188a 100644 --- a/distributors-core/distributors.cabal +++ b/distributors-core/distributors.cabal @@ -1,13 +1,13 @@ cabal-version: 2.2 --- This file has been generated from package.yaml by hpack version 0.39.1. +-- This file has been generated from package.yaml by hpack version 0.39.6. -- -- 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. +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 @@ -30,24 +30,15 @@ library exposed-modules: Control.Lens.Bifocal Control.Lens.Diopter - Control.Lens.Grammar - Control.Lens.Grammar.BackusNaur - Control.Lens.Grammar.Internal.NestedPrismTH - Control.Lens.Grammar.Internal.Orphanage - Control.Lens.Grammar.Machine - Control.Lens.Grammar.RegEx - Control.Lens.Grammar.Symbol - Control.Lens.Grammar.Token Control.Lens.Grate + Control.Lens.Internal.NestedPrismTH + Control.Lens.Internal.Orphanage Control.Lens.Monocle Control.Lens.PartialIso 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.Monoidal Data.Profunctor.Monoidal.Cocartesian @@ -99,23 +90,16 @@ 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 + adjunctions >=4.4 && <5 , base >=4.15 && <5 , bifunctors >=5.5 && <6 - , bytestring >=0.11 && <1 , containers >=0.6 && <1 , contravariant >=1.5 && <2 , distributive >=0.6 && <1 , 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 @@ -171,25 +155,18 @@ test-suite doctests 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 - , adjunctions >=4.4 && <5 + adjunctions >=4.4 && <5 , base >=4.15 && <5 , bifunctors >=5.5 && <6 - , bytestring >=0.11 && <1 , containers >=0.6 && <1 , contravariant >=1.5 && <2 , distributive >=0.6 && <1 , distributors , 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 , tagged >=0.8 && <1 , template-haskell >=2.17 && <3 - , text ==2.* , th-abstraction >=0.4 && <1 , transformers >=0.5 && <1 , vector >=0.12 && <1 @@ -200,17 +177,7 @@ 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.Homogeneous - Properties.Kleene Paths_distributors autogen-modules: Paths_distributors @@ -256,26 +223,19 @@ 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 , bifunctors >=5.5 && <6 - , bytestring >=0.11 && <1 , containers >=0.6 && <1 , contravariant >=1.5 && <2 , distributive >=0.6 && <1 , distributors , 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/package.yaml b/distributors-core/package.yaml index ed7c9d18..f99dd818 100644 --- a/distributors-core/package.yaml +++ b/distributors-core/package.yaml @@ -12,30 +12,24 @@ 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 - adjunctions >= 4.4 && < 5 - bifunctors >= 5.5 && < 6 -- bytestring >= 0.11 && < 1 - containers >= 0.6 && < 1 - contravariant >= 1.5 && < 2 - distributive >= 0.6 && < 1 - 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 @@ -107,5 +101,4 @@ tests: dependencies: - distributors - hspec >= 2.7 && < 3 - - megaparsec >= 9.0 && < 10 - QuickCheck >= 2.14 && < 3 diff --git a/distributors-core/src/Control/Lens/Grammar/Internal/NestedPrismTH.hs b/distributors-core/src/Control/Lens/Internal/NestedPrismTH.hs similarity index 99% rename from distributors-core/src/Control/Lens/Grammar/Internal/NestedPrismTH.hs rename to distributors-core/src/Control/Lens/Internal/NestedPrismTH.hs index 773da1b8..f444db3f 100644 --- a/distributors-core/src/Control/Lens/Grammar/Internal/NestedPrismTH.hs +++ b/distributors-core/src/Control/Lens/Internal/NestedPrismTH.hs @@ -1,5 +1,5 @@ {- | -Module : Control.Lens.Grammar.Internal.NestedPrismTH +Module : Control.Lens.Internal.NestedPrismTH Description : nested pair prisms Copyright : (C) 2026 - Eitan Chatav License : BSD-style (see the file LICENSE) @@ -11,7 +11,7 @@ Code is duplicated from `Control.Lens.Internal.PrismTH`, with small tweaks to support nested pairs. -} -module Control.Lens.Grammar.Internal.NestedPrismTH +module Control.Lens.Internal.NestedPrismTH ( -- * Nested prisms makeNestedPrisms ) where diff --git a/distributors-core/src/Control/Lens/Grammar/Internal/Orphanage.hs b/distributors-core/src/Control/Lens/Internal/Orphanage.hs similarity index 97% rename from distributors-core/src/Control/Lens/Grammar/Internal/Orphanage.hs rename to distributors-core/src/Control/Lens/Internal/Orphanage.hs index bccd3001..370d43de 100644 --- a/distributors-core/src/Control/Lens/Grammar/Internal/Orphanage.hs +++ b/distributors-core/src/Control/Lens/Internal/Orphanage.hs @@ -1,7 +1,7 @@ {-# OPTIONS_GHC -Wno-orphans #-} {- | -Module : Control.Lens.Grammar.Internal.Orphanage +Module : Control.Lens.Internal.Orphanage Description : orphanage Copyright : (C) 2026 - Eitan Chatav License : BSD-style (see the file LICENSE) @@ -12,7 +12,7 @@ Portability : non-portable An orphanage for instances without a home. -} -module Control.Lens.Grammar.Internal.Orphanage () where +module Control.Lens.Internal.Orphanage () where import Control.Applicative hiding (WrappedArrow) import Control.Applicative qualified as Ap (WrappedArrow) diff --git a/distributors-core/src/Control/Lens/PartialIso.hs b/distributors-core/src/Control/Lens/PartialIso.hs index 63b1a5eb..af342cb4 100644 --- a/distributors-core/src/Control/Lens/PartialIso.hs +++ b/distributors-core/src/Control/Lens/PartialIso.hs @@ -54,8 +54,8 @@ module Control.Lens.PartialIso ) where import Control.Lens -import Control.Lens.Grammar.Internal.Orphanage () -import Control.Lens.Grammar.Internal.NestedPrismTH +import Control.Lens.Internal.Orphanage () +import Control.Lens.Internal.NestedPrismTH import Control.Lens.Internal.Profunctor import Control.Lens.Iso import Control.Lens.Prism diff --git a/distributors-core/src/Data/Profunctor/Separator.hs b/distributors-core/src/Data/Profunctor/Separator.hs index 04c8b00a..b80b3013 100644 --- a/distributors-core/src/Data/Profunctor/Separator.hs +++ b/distributors-core/src/Data/Profunctor/Separator.hs @@ -140,66 +140,8 @@ 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!" +For an example, see the expression grammar in "Control.Lens.Grammar", +of natural numbers with postfix, right-associative & left-associative operators. -} withOperators :: Alternator p diff --git a/distributors-core/test/Main.hs b/distributors-core/test/Main.hs index 30054e05..c44794fc 100644 --- a/distributors-core/test/Main.hs +++ b/distributors-core/test/Main.hs @@ -1,86 +1,17 @@ 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.Profunctor.Monoidal (meander) import Data.Profunctor.Types (Star (..)) -import Data.Tree (Tree (..)) import Test.Hspec -import Test.QuickCheck (generate) -import qualified Text.Megaparsec as M -import Examples.Arithmetic -import Examples.Chain -import Examples.Expression -import Examples.Json -import Examples.Lambda -import Examples.LenVec -import Examples.RegString -import Examples.SemVer -import Examples.SExpr import Properties.Homogeneous -import Properties.Kleene main :: IO () 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 "Homogeneous" homogeneousProperties describe "meander" meanderProperties -parseForestTests :: Spec -parseForestTests = do - it "returns the nested rule forest for a full parse" $ do - let (actualForest, actualRest) = parseForest (transducerG arithGrammar) "2*3+4;;;" - actualForest `shouldBe` - [ Node ("arith", 0, 5, "2*3+4") - [ Node ("sum", 0, 5, "2*3+4") - [ Node ("product", 0, 3, "2*3") - [ Node ("factor", 0, 1, "2") - [Node ("number", 0, 1, "2") []] - , Node ("factor", 2, 3, "3") - [Node ("number", 2, 3, "3") []] - ] - , Node ("product", 4, 5, "4") - [ Node ("factor", 4, 5, "4") - [Node ("number", 4, 5, "4") []] - ] - ] - ] - ] - actualRest `shouldBe` ";;;" - -tryRollbackTests :: Spec -tryRollbackTests = do - it "rolls back parse stream/offset on failed try" $ do - let actual = parsecG (try (tokens "ab")) "ax" - parsecLooked actual `shouldBe` False - parsecOffset actual `shouldBe` 0 - parsecStream actual `shouldBe` "ax" - parsecResult actual `shouldBe` (Nothing :: Maybe String) - it "rolls back unparse stream/offset on failed try" $ do - let actual = unparsecG (try (tokens "ab")) "ax" "" - parsecLooked actual `shouldBe` False - parsecOffset actual `shouldBe` 0 - parsecStream actual `shouldBe` "" - parsecResult actual `shouldBe` (Nothing :: Maybe String) - meanderProperties :: Spec meanderProperties = it "preserves left-to-right traversal effects" $ do @@ -91,78 +22,3 @@ meanderProperties = 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 - testCtxGrammar isLL1 grammar (expectedSyntax, expectedString) - it ("should match " <> expectedString <> " correctly") $ do - let actualMatch = expectedString =~ regbnfG grammar - actualMatch `shouldBe` True - describe "transducerG" $ do - it "should generate the hundred shorted valid words in a language" $ do - generated <- generate (take 100 <$> languageSample (transducerG grammar)) - for_ generated $ \word -> do - let fullParses = [() | (_, "") <- parseG grammar word] - fullParses `shouldBe` [()] - -testCsg :: (Show a, Eq a) => Bool -> [(a, String)] -> CtxGrammar Char a -> Spec -testCsg isLL1 examples grammar = - describe "examples" $ for_ examples $ testCtxGrammar isLL1 grammar - -testCtxGrammar :: (Show a, Eq a) => Bool -> CtxGrammar Char a -> (a, String) -> Spec -testCtxGrammar isLL1 grammar (expectedSyntax, expectedString) = do - it ("should parseG from " <> expectedString <> " correctly") $ do - let actualSyntax = [parsed | (parsed, "") <- parseG grammar expectedString] - actualSyntax `shouldBe` [expectedSyntax] - it ("should unparseG to " <> expectedString <> " correctly") $ do - let actualString = unparseG grammar expectedSyntax "" - actualString `shouldBe` Just expectedString - it ("should printG to " <> expectedString <> " correctly") $ do - let actualString = ($ "") <$> printG grammar expectedSyntax - actualString `shouldBe` Just expectedString - when isLL1 $ do - it ("should parsecG from " <> expectedString <> " correctly") $ do - let actualSyntax = parsecG grammar expectedString - let expectedLength = genericLength expectedString - let actualLooked = parsecLooked actualSyntax - let actualFailure = parsecFailure actualSyntax - actualSyntax `shouldBe` - (ParsecState actualLooked expectedLength "" actualFailure (Just expectedSyntax)) - it ("should unparsecG to " <> expectedString <> " correctly") $ do - let actualString = unparsecG grammar expectedSyntax "" - let expectedLength = genericLength expectedString - let actualLooked = parsecLooked actualString - let actualFailure = parsecFailure actualString - actualString `shouldBe` - (ParsecState actualLooked expectedLength expectedString actualFailure (Just expectedSyntax)) - it ("should parse with megaparsec to " <> expectedString <> " correctly") $ do - let megaparsec = unwrapMega (monadG grammar) - let actualSyntax = M.parse megaparsec "" expectedString - actualSyntax `shouldBe` Right expectedSyntax - -newtype WrapMega a = WrapMega {unwrapMega :: M.Parsec String String a} - deriving newtype - ( Functor, Applicative, Alternative - , Monad, MonadPlus, MonadFail - ) -instance TerminalSymbol Char (WrapMega ()) where - terminal str = WrapMega (M.chunk str *> pure ()) -instance TokenAlgebra Char (WrapMega Char) where - tokenClass exam = WrapMega $ M.label (show exam) (M.satisfy (tokenClass exam)) -instance Tokenized Char (WrapMega Char) where - anyToken = WrapMega M.anySingle - token = WrapMega . M.single - oneOf = WrapMega . M.oneOf - notOneOf = WrapMega . M.noneOf - asIn cat = WrapMega $ M.label ("in category " ++ show cat) - (M.satisfy (tokenClass (asIn cat))) - notAsIn cat = WrapMega $ M.label ("not in category " ++ show cat) - (M.satisfy (tokenClass (notAsIn cat))) -instance BackusNaurForm (WrapMega a) where - rule lbl (WrapMega p) = WrapMega (M.label lbl p) - ruleRec lbl = rule lbl . fix -instance Filterable WrapMega where - catMaybes m = m >>= maybe (fail "unrestricted filtration") pure -instance MonadTry WrapMega where - try (WrapMega p) = WrapMega (M.try p) diff --git a/distributors-grammar/CHANGELOG.md b/distributors-grammar/CHANGELOG.md new file mode 100644 index 00000000..e496f310 --- /dev/null +++ b/distributors-grammar/CHANGELOG.md @@ -0,0 +1,8 @@ +# Changelog for `distributors-grammar` + +## Unreleased + +- 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`. 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/distributors-grammar.cabal b/distributors-grammar/distributors-grammar.cabal new file mode 100644 index 00000000..69f9b5ad --- /dev/null +++ b/distributors-grammar/distributors-grammar.cabal @@ -0,0 +1,239 @@ +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.15 && <5 + , bifunctors >=5.5 && <6 + , containers >=0.6 && <1 + , distributors ==0.6.* + , 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.15 && <5 + , bifunctors >=5.5 && <6 + , containers >=0.6 && <1 + , distributors ==0.6.* + , 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.Json + Examples.Lambda + Examples.LenVec + Examples.RegString + Examples.SemVer + Examples.SExpr + Properties.Kleene + 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.15 && <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 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..18d9e4c1 --- /dev/null +++ b/distributors-grammar/package.yaml @@ -0,0 +1,104 @@ +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.15 && < 5 +- bifunctors >= 5.5 && < 6 +- containers >= 0.6 && < 1 +- distributors >= 0.6 && < 0.7 +- 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 diff --git a/distributors-core/src/Control/Lens/Grammar.hs b/distributors-grammar/src/Control/Lens/Grammar.hs similarity index 94% rename from distributors-core/src/Control/Lens/Grammar.hs rename to distributors-grammar/src/Control/Lens/Grammar.hs index f9b162de..3c8f1a3f 100644 --- a/distributors-core/src/Control/Lens/Grammar.hs +++ b/distributors-grammar/src/Control/Lens/Grammar.hs @@ -280,6 +280,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 diff --git a/distributors-core/src/Control/Lens/Grammar/BackusNaur.hs b/distributors-grammar/src/Control/Lens/Grammar/BackusNaur.hs similarity index 100% rename from distributors-core/src/Control/Lens/Grammar/BackusNaur.hs rename to distributors-grammar/src/Control/Lens/Grammar/BackusNaur.hs diff --git a/distributors-core/src/Control/Lens/Grammar/Machine.hs b/distributors-grammar/src/Control/Lens/Grammar/Machine.hs similarity index 100% rename from distributors-core/src/Control/Lens/Grammar/Machine.hs rename to distributors-grammar/src/Control/Lens/Grammar/Machine.hs diff --git a/distributors-core/src/Control/Lens/Grammar/RegEx.hs b/distributors-grammar/src/Control/Lens/Grammar/RegEx.hs similarity index 100% rename from distributors-core/src/Control/Lens/Grammar/RegEx.hs rename to distributors-grammar/src/Control/Lens/Grammar/RegEx.hs diff --git a/distributors-core/src/Control/Lens/Grammar/Symbol.hs b/distributors-grammar/src/Control/Lens/Grammar/Symbol.hs similarity index 100% rename from distributors-core/src/Control/Lens/Grammar/Symbol.hs rename to distributors-grammar/src/Control/Lens/Grammar/Symbol.hs diff --git a/distributors-core/src/Control/Lens/Grammar/Token.hs b/distributors-grammar/src/Control/Lens/Grammar/Token.hs similarity index 100% rename from distributors-core/src/Control/Lens/Grammar/Token.hs rename to distributors-grammar/src/Control/Lens/Grammar/Token.hs diff --git a/distributors-core/src/Control/Monad/Fail/Try.hs b/distributors-grammar/src/Control/Monad/Fail/Try.hs similarity index 100% rename from distributors-core/src/Control/Monad/Fail/Try.hs rename to distributors-grammar/src/Control/Monad/Fail/Try.hs diff --git a/distributors-core/src/Data/Profunctor/Grammar.hs b/distributors-grammar/src/Data/Profunctor/Grammar.hs similarity index 100% rename from distributors-core/src/Data/Profunctor/Grammar.hs rename to distributors-grammar/src/Data/Profunctor/Grammar.hs diff --git a/distributors-core/src/Data/Profunctor/Grammar/Parsector.hs b/distributors-grammar/src/Data/Profunctor/Grammar/Parsector.hs similarity index 100% rename from distributors-core/src/Data/Profunctor/Grammar/Parsector.hs rename to distributors-grammar/src/Data/Profunctor/Grammar/Parsector.hs diff --git a/distributors-core/test/Examples/Arithmetic.hs b/distributors-grammar/test/Examples/Arithmetic.hs similarity index 100% rename from distributors-core/test/Examples/Arithmetic.hs rename to distributors-grammar/test/Examples/Arithmetic.hs diff --git a/distributors-core/test/Examples/Chain.hs b/distributors-grammar/test/Examples/Chain.hs similarity index 100% rename from distributors-core/test/Examples/Chain.hs rename to distributors-grammar/test/Examples/Chain.hs diff --git a/distributors-core/test/Examples/Expression.hs b/distributors-grammar/test/Examples/Expression.hs similarity index 100% rename from distributors-core/test/Examples/Expression.hs rename to distributors-grammar/test/Examples/Expression.hs diff --git a/distributors-core/test/Examples/Json.hs b/distributors-grammar/test/Examples/Json.hs similarity index 100% rename from distributors-core/test/Examples/Json.hs rename to distributors-grammar/test/Examples/Json.hs diff --git a/distributors-core/test/Examples/Lambda.hs b/distributors-grammar/test/Examples/Lambda.hs similarity index 100% rename from distributors-core/test/Examples/Lambda.hs rename to distributors-grammar/test/Examples/Lambda.hs diff --git a/distributors-core/test/Examples/LenVec.hs b/distributors-grammar/test/Examples/LenVec.hs similarity index 100% rename from distributors-core/test/Examples/LenVec.hs rename to distributors-grammar/test/Examples/LenVec.hs diff --git a/distributors-core/test/Examples/RegString.hs b/distributors-grammar/test/Examples/RegString.hs similarity index 100% rename from distributors-core/test/Examples/RegString.hs rename to distributors-grammar/test/Examples/RegString.hs diff --git a/distributors-core/test/Examples/SExpr.hs b/distributors-grammar/test/Examples/SExpr.hs similarity index 100% rename from distributors-core/test/Examples/SExpr.hs rename to distributors-grammar/test/Examples/SExpr.hs diff --git a/distributors-core/test/Examples/SemVer.hs b/distributors-grammar/test/Examples/SemVer.hs similarity index 100% rename from distributors-core/test/Examples/SemVer.hs rename to distributors-grammar/test/Examples/SemVer.hs diff --git a/distributors-grammar/test/Main.hs b/distributors-grammar/test/Main.hs new file mode 100644 index 00000000..d2a995a5 --- /dev/null +++ b/distributors-grammar/test/Main.hs @@ -0,0 +1,152 @@ +module Main (main) where + +import Data.Foldable hiding (toList) +import Control.Lens.Grammar +import Control.Monad (when) +import Data.Function (fix) +import Data.List (genericLength) +import Data.Tree (Tree (..)) +import Test.Hspec +import Test.QuickCheck (generate) +import qualified Text.Megaparsec as M + +import Examples.Arithmetic +import Examples.Chain +import Examples.Expression +import Examples.Json +import Examples.Lambda +import Examples.LenVec +import Examples.RegString +import Examples.SemVer +import Examples.SExpr +import Properties.Kleene + +main :: IO () +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 + +parseForestTests :: Spec +parseForestTests = do + it "returns the nested rule forest for a full parse" $ do + let (actualForest, actualRest) = parseForest (transducerG arithGrammar) "2*3+4;;;" + actualForest `shouldBe` + [ Node ("arith", 0, 5, "2*3+4") + [ Node ("sum", 0, 5, "2*3+4") + [ Node ("product", 0, 3, "2*3") + [ Node ("factor", 0, 1, "2") + [Node ("number", 0, 1, "2") []] + , Node ("factor", 2, 3, "3") + [Node ("number", 2, 3, "3") []] + ] + , Node ("product", 4, 5, "4") + [ Node ("factor", 4, 5, "4") + [Node ("number", 4, 5, "4") []] + ] + ] + ] + ] + actualRest `shouldBe` ";;;" + +tryRollbackTests :: Spec +tryRollbackTests = do + it "rolls back parse stream/offset on failed try" $ do + let actual = parsecG (try (tokens "ab")) "ax" + parsecLooked actual `shouldBe` False + parsecOffset actual `shouldBe` 0 + parsecStream actual `shouldBe` "ax" + parsecResult actual `shouldBe` (Nothing :: Maybe String) + it "rolls back unparse stream/offset on failed try" $ do + let actual = unparsecG (try (tokens "ab")) "ax" "" + parsecLooked actual `shouldBe` False + parsecOffset actual `shouldBe` 0 + parsecStream actual `shouldBe` "" + parsecResult actual `shouldBe` (Nothing :: Maybe String) + +testCfg :: (Show a, Eq a) => Bool -> [(a, String)] -> Grammar Char a -> Spec +testCfg isLL1 examples grammar = do + describe "examples" $ for_ examples $ \(expectedSyntax, expectedString) -> do + testCtxGrammar isLL1 grammar (expectedSyntax, expectedString) + it ("should match " <> expectedString <> " correctly") $ do + let actualMatch = expectedString =~ regbnfG grammar + actualMatch `shouldBe` True + describe "transducerG" $ do + it "should generate the hundred shorted valid words in a language" $ do + generated <- generate (take 100 <$> languageSample (transducerG grammar)) + for_ generated $ \word -> do + let fullParses = [() | (_, "") <- parseG grammar word] + fullParses `shouldBe` [()] + +testCsg :: (Show a, Eq a) => Bool -> [(a, String)] -> CtxGrammar Char a -> Spec +testCsg isLL1 examples grammar = + describe "examples" $ for_ examples $ testCtxGrammar isLL1 grammar + +testCtxGrammar :: (Show a, Eq a) => Bool -> CtxGrammar Char a -> (a, String) -> Spec +testCtxGrammar isLL1 grammar (expectedSyntax, expectedString) = do + it ("should parseG from " <> expectedString <> " correctly") $ do + let actualSyntax = [parsed | (parsed, "") <- parseG grammar expectedString] + actualSyntax `shouldBe` [expectedSyntax] + it ("should unparseG to " <> expectedString <> " correctly") $ do + let actualString = unparseG grammar expectedSyntax "" + actualString `shouldBe` Just expectedString + it ("should printG to " <> expectedString <> " correctly") $ do + let actualString = ($ "") <$> printG grammar expectedSyntax + actualString `shouldBe` Just expectedString + when isLL1 $ do + it ("should parsecG from " <> expectedString <> " correctly") $ do + let actualSyntax = parsecG grammar expectedString + let expectedLength = genericLength expectedString + let actualLooked = parsecLooked actualSyntax + let actualFailure = parsecFailure actualSyntax + actualSyntax `shouldBe` + (ParsecState actualLooked expectedLength "" actualFailure (Just expectedSyntax)) + it ("should unparsecG to " <> expectedString <> " correctly") $ do + let actualString = unparsecG grammar expectedSyntax "" + let expectedLength = genericLength expectedString + let actualLooked = parsecLooked actualString + let actualFailure = parsecFailure actualString + actualString `shouldBe` + (ParsecState actualLooked expectedLength expectedString actualFailure (Just expectedSyntax)) + it ("should parse with megaparsec to " <> expectedString <> " correctly") $ do + let megaparsec = unwrapMega (monadG grammar) + let actualSyntax = M.parse megaparsec "" expectedString + actualSyntax `shouldBe` Right expectedSyntax + +newtype WrapMega a = WrapMega {unwrapMega :: M.Parsec String String a} + deriving newtype + ( Functor, Applicative, Alternative + , Monad, MonadPlus, MonadFail + ) +instance TerminalSymbol Char (WrapMega ()) where + terminal str = WrapMega (M.chunk str *> pure ()) +instance TokenAlgebra Char (WrapMega Char) where + tokenClass exam = WrapMega $ M.label (show exam) (M.satisfy (tokenClass exam)) +instance Tokenized Char (WrapMega Char) where + anyToken = WrapMega M.anySingle + token = WrapMega . M.single + oneOf = WrapMega . M.oneOf + notOneOf = WrapMega . M.noneOf + asIn cat = WrapMega $ M.label ("in category " ++ show cat) + (M.satisfy (tokenClass (asIn cat))) + notAsIn cat = WrapMega $ M.label ("not in category " ++ show cat) + (M.satisfy (tokenClass (notAsIn cat))) +instance BackusNaurForm (WrapMega a) where + rule lbl (WrapMega p) = WrapMega (M.label lbl p) + ruleRec lbl = rule lbl . fix +instance Filterable WrapMega where + catMaybes m = m >>= maybe (fail "unrestricted filtration") pure +instance MonadTry WrapMega where + try (WrapMega p) = WrapMega (M.try p) diff --git a/distributors-core/test/Properties/Kleene.hs b/distributors-grammar/test/Properties/Kleene.hs similarity index 100% rename from distributors-core/test/Properties/Kleene.hs rename to distributors-grammar/test/Properties/Kleene.hs diff --git a/distributors-json/distributors-json.cabal b/distributors-json/distributors-json.cabal index 8c9df8c1..a07275ad 100644 --- a/distributors-json/distributors-json.cabal +++ b/distributors-json/distributors-json.cabal @@ -1,6 +1,6 @@ cabal-version: 2.2 --- This file has been generated from package.yaml by hpack version 0.39.1. +-- This file has been generated from package.yaml by hpack version 0.39.6. -- -- see: https://github.com/sol/hpack @@ -84,6 +84,7 @@ library , containers >=0.6 && <1 , data-fix >=0.3 && <1 , distributors ==0.6.* + , distributors-grammar ==0.1.* , dlist >=1.0 && <2 , hashable >=1.4 && <2 , lens >=5.0 && <6 @@ -161,6 +162,7 @@ test-suite doctests , containers >=0.6 && <1 , data-fix >=0.3 && <1 , distributors ==0.6.* + , distributors-grammar ==0.1.* , distributors-json , dlist >=1.0 && <2 , doctest-parallel >=0.3 && <1 @@ -243,6 +245,7 @@ test-suite test , containers >=0.6 && <1 , data-fix >=0.3 && <1 , distributors ==0.6.* + , distributors-grammar ==0.1.* , distributors-json , dlist >=1.0 && <2 , hashable >=1.4 && <2 @@ -324,6 +327,7 @@ benchmark json , data-fix >=0.3 && <1 , deepseq >=1.4 && <2 , distributors ==0.6.* + , distributors-grammar ==0.1.* , distributors-json , dlist >=1.0 && <2 , hashable >=1.4 && <2 diff --git a/distributors-json/package.yaml b/distributors-json/package.yaml index 0a0f3381..1566abfc 100644 --- a/distributors-json/package.yaml +++ b/distributors-json/package.yaml @@ -26,6 +26,7 @@ dependencies: - containers >= 0.6 && < 1 - data-fix >= 0.3 && < 1 - distributors >= 0.6 && < 0.7 +- distributors-grammar >= 0.1 && < 0.2 - dlist >= 1.0 && < 2 - hashable >= 1.4 && < 2 - lens >= 5.0 && < 6 diff --git a/flake.nix b/flake.nix index 7912ebe4..3d2e1bb2 100644 --- a/flake.nix +++ b/flake.nix @@ -1,5 +1,5 @@ { - description = "distributors & distributors-json"; + description = "distributors, distributors-grammar & distributors-json"; inputs = { nixpkgs.url = "github:NixOS/nixpkgs/nixpkgs-unstable"; @@ -16,6 +16,8 @@ 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 { }; }; @@ -24,17 +26,21 @@ { 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-json ]; + packages = p: + [ p.distributors p.distributors-grammar p.distributors-json ]; withHoogle = false; nativeBuildInputs = [ pkgs.cabal-install diff --git a/stack.yaml b/stack.yaml index ad8feb13..a8eb8e3b 100644 --- a/stack.yaml +++ b/stack.yaml @@ -1,4 +1,5 @@ resolver: nightly-2026-09-27 packages: - distributors-core +- distributors-grammar - distributors-json From c00deeff3b7e553f903b3f490aca017837af4eb6 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sun, 8 Nov 2026 08:10:44 -0800 Subject: [PATCH 064/130] Bump distributors to 0.7.0.0, for the grammars' split Co-Authored-By: Claude Opus 5.5 --- distributors-core/distributors.cabal | 2 +- distributors-core/package.yaml | 2 +- distributors-grammar/distributors-grammar.cabal | 4 ++-- distributors-grammar/package.yaml | 2 +- distributors-json/distributors-json.cabal | 8 ++++---- distributors-json/package.yaml | 2 +- 6 files changed, 10 insertions(+), 10 deletions(-) diff --git a/distributors-core/distributors.cabal b/distributors-core/distributors.cabal index 97ad188a..a51e96a9 100644 --- a/distributors-core/distributors.cabal +++ b/distributors-core/distributors.cabal @@ -5,7 +5,7 @@ cabal-version: 2.2 -- see: https://github.com/sol/hpack name: distributors -version: 0.6.0.0 +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 diff --git a/distributors-core/package.yaml b/distributors-core/package.yaml index f99dd818..0db3f36b 100644 --- a/distributors-core/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" diff --git a/distributors-grammar/distributors-grammar.cabal b/distributors-grammar/distributors-grammar.cabal index 69f9b5ad..70d8a657 100644 --- a/distributors-grammar/distributors-grammar.cabal +++ b/distributors-grammar/distributors-grammar.cabal @@ -88,7 +88,7 @@ library , base >=4.15 && <5 , bifunctors >=5.5 && <6 , containers >=0.6 && <1 - , distributors ==0.6.* + , distributors ==0.7.* , lens >=5.0 && <6 , monad-loops >=0.4.3 && <1 , mtl >=2.2 && <3 @@ -151,7 +151,7 @@ test-suite doctests , base >=4.15 && <5 , bifunctors >=5.5 && <6 , containers >=0.6 && <1 - , distributors ==0.6.* + , distributors ==0.7.* , distributors-grammar , doctest-parallel >=0.3 && <1 , lens >=5.0 && <6 diff --git a/distributors-grammar/package.yaml b/distributors-grammar/package.yaml index 18d9e4c1..f43d791a 100644 --- a/distributors-grammar/package.yaml +++ b/distributors-grammar/package.yaml @@ -22,7 +22,7 @@ dependencies: - base >= 4.15 && < 5 - bifunctors >= 5.5 && < 6 - containers >= 0.6 && < 1 -- distributors >= 0.6 && < 0.7 +- distributors >= 0.7 && < 0.8 - lens >= 5.0 && < 6 - MemoTrie >= 0.6 && < 1 - monad-loops >= 0.4.3 && < 1 diff --git a/distributors-json/distributors-json.cabal b/distributors-json/distributors-json.cabal index a07275ad..38fe56eb 100644 --- a/distributors-json/distributors-json.cabal +++ b/distributors-json/distributors-json.cabal @@ -83,7 +83,7 @@ library , bytestring >=0.11 && <1 , containers >=0.6 && <1 , data-fix >=0.3 && <1 - , distributors ==0.6.* + , distributors ==0.7.* , distributors-grammar ==0.1.* , dlist >=1.0 && <2 , hashable >=1.4 && <2 @@ -161,7 +161,7 @@ test-suite doctests , bytestring >=0.11 && <1 , containers >=0.6 && <1 , data-fix >=0.3 && <1 - , distributors ==0.6.* + , distributors ==0.7.* , distributors-grammar ==0.1.* , distributors-json , dlist >=1.0 && <2 @@ -244,7 +244,7 @@ test-suite test , bytestring >=0.11 && <1 , containers >=0.6 && <1 , data-fix >=0.3 && <1 - , distributors ==0.6.* + , distributors ==0.7.* , distributors-grammar ==0.1.* , distributors-json , dlist >=1.0 && <2 @@ -326,7 +326,7 @@ benchmark json , containers >=0.6 && <1 , data-fix >=0.3 && <1 , deepseq >=1.4 && <2 - , distributors ==0.6.* + , distributors ==0.7.* , distributors-grammar ==0.1.* , distributors-json , dlist >=1.0 && <2 diff --git a/distributors-json/package.yaml b/distributors-json/package.yaml index 1566abfc..55e2038c 100644 --- a/distributors-json/package.yaml +++ b/distributors-json/package.yaml @@ -25,7 +25,7 @@ dependencies: - bytestring >= 0.11 && < 1 - containers >= 0.6 && < 1 - data-fix >= 0.3 && < 1 -- distributors >= 0.6 && < 0.7 +- distributors >= 0.7 && < 0.8 - distributors-grammar >= 0.1 && < 0.2 - dlist >= 1.0 && < 2 - hashable >= 1.4 && < 2 From 514a5d0d90b1e0540becd264c47175c4ea8de00c Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sun, 8 Nov 2026 08:18:33 -0800 Subject: [PATCH 065/130] Move the internal modules to Control.Lens.Internal.Distributors Co-Authored-By: Claude Opus 5.5 --- distributors-core/CHANGELOG.md | 2 +- distributors-core/distributors.cabal | 4 ++-- .../Control/Lens/Internal/{ => Distributors}/NestedPrismTH.hs | 4 ++-- .../src/Control/Lens/Internal/{ => Distributors}/Orphanage.hs | 4 ++-- distributors-core/src/Control/Lens/PartialIso.hs | 4 ++-- 5 files changed, 9 insertions(+), 9 deletions(-) rename distributors-core/src/Control/Lens/Internal/{ => Distributors}/NestedPrismTH.hs (98%) rename distributors-core/src/Control/Lens/Internal/{ => Distributors}/Orphanage.hs (97%) diff --git a/distributors-core/CHANGELOG.md b/distributors-core/CHANGELOG.md index 44506b6a..f8c0fc8d 100644 --- a/distributors-core/CHANGELOG.md +++ b/distributors-core/CHANGELOG.md @@ -34,7 +34,7 @@ & `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.NestedPrismTH` & `.Orphanage`. + `Control.Lens.Internal.Distributors.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. diff --git a/distributors-core/distributors.cabal b/distributors-core/distributors.cabal index a51e96a9..b48c92cf 100644 --- a/distributors-core/distributors.cabal +++ b/distributors-core/distributors.cabal @@ -31,8 +31,8 @@ library Control.Lens.Bifocal Control.Lens.Diopter Control.Lens.Grate - Control.Lens.Internal.NestedPrismTH - Control.Lens.Internal.Orphanage + Control.Lens.Internal.Distributors.NestedPrismTH + Control.Lens.Internal.Distributors.Orphanage Control.Lens.Monocle Control.Lens.PartialIso Control.Lens.Wither diff --git a/distributors-core/src/Control/Lens/Internal/NestedPrismTH.hs b/distributors-core/src/Control/Lens/Internal/Distributors/NestedPrismTH.hs similarity index 98% rename from distributors-core/src/Control/Lens/Internal/NestedPrismTH.hs rename to distributors-core/src/Control/Lens/Internal/Distributors/NestedPrismTH.hs index f444db3f..13c767d1 100644 --- a/distributors-core/src/Control/Lens/Internal/NestedPrismTH.hs +++ b/distributors-core/src/Control/Lens/Internal/Distributors/NestedPrismTH.hs @@ -1,5 +1,5 @@ {- | -Module : Control.Lens.Internal.NestedPrismTH +Module : Control.Lens.Internal.Distributors.NestedPrismTH Description : nested pair prisms Copyright : (C) 2026 - Eitan Chatav License : BSD-style (see the file LICENSE) @@ -11,7 +11,7 @@ Code is duplicated from `Control.Lens.Internal.PrismTH`, with small tweaks to support nested pairs. -} -module Control.Lens.Internal.NestedPrismTH +module Control.Lens.Internal.Distributors.NestedPrismTH ( -- * Nested prisms makeNestedPrisms ) where diff --git a/distributors-core/src/Control/Lens/Internal/Orphanage.hs b/distributors-core/src/Control/Lens/Internal/Distributors/Orphanage.hs similarity index 97% rename from distributors-core/src/Control/Lens/Internal/Orphanage.hs rename to distributors-core/src/Control/Lens/Internal/Distributors/Orphanage.hs index 370d43de..a496ce22 100644 --- a/distributors-core/src/Control/Lens/Internal/Orphanage.hs +++ b/distributors-core/src/Control/Lens/Internal/Distributors/Orphanage.hs @@ -1,7 +1,7 @@ {-# OPTIONS_GHC -Wno-orphans #-} {- | -Module : Control.Lens.Internal.Orphanage +Module : Control.Lens.Internal.Distributors.Orphanage Description : orphanage Copyright : (C) 2026 - Eitan Chatav License : BSD-style (see the file LICENSE) @@ -12,7 +12,7 @@ Portability : non-portable An orphanage for instances without a home. -} -module Control.Lens.Internal.Orphanage () where +module Control.Lens.Internal.Distributors.Orphanage () where import Control.Applicative hiding (WrappedArrow) import Control.Applicative qualified as Ap (WrappedArrow) diff --git a/distributors-core/src/Control/Lens/PartialIso.hs b/distributors-core/src/Control/Lens/PartialIso.hs index af342cb4..625157bc 100644 --- a/distributors-core/src/Control/Lens/PartialIso.hs +++ b/distributors-core/src/Control/Lens/PartialIso.hs @@ -54,8 +54,8 @@ module Control.Lens.PartialIso ) where import Control.Lens -import Control.Lens.Internal.Orphanage () -import Control.Lens.Internal.NestedPrismTH +import Control.Lens.Internal.Distributors.Orphanage () +import Control.Lens.Internal.Distributors.NestedPrismTH import Control.Lens.Internal.Profunctor import Control.Lens.Iso import Control.Lens.Prism From a68f588c6d63e6499627c2105feac2199b5a8f72 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sun, 8 Nov 2026 08:57:15 -0800 Subject: [PATCH 066/130] Update Json.hs --- .../src/Control/Lens/Grammar/Json.hs | 22 +++++++++---------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/distributors-json/src/Control/Lens/Grammar/Json.hs b/distributors-json/src/Control/Lens/Grammar/Json.hs index e703966f..abc01007 100644 --- a/distributors-json/src/Control/Lens/Grammar/Json.hs +++ b/distributors-json/src/Control/Lens/Grammar/Json.hs @@ -311,8 +311,8 @@ class Json a where it matches the value omitted by `Aeson.omitNothingFields`, & reviews the value of a field omitted by `Aeson.allowOmittedFields`. -} - jsonOmit :: Maybe (APrism' a ()) - jsonOmit = Nothing + jsonOmitField :: Maybe (APrism' a ()) + jsonOmitField = Nothing -- Running Json grammars -- @@ -2496,7 +2496,7 @@ instance Json Ordering where json = jsonTyped (jsonEnumerated (Text.pack . show)) instance Json () where json = jsonTuple oneP - jsonOmit = Just (only ()) + jsonOmitField = Just (only ()) instance Json Void where json = zeroP jsonKey = Just (prism' absurd (const Nothing) ?< jsonText) @@ -2519,7 +2519,7 @@ instance Json a => Json [a] where jsonKey = jsonKeyList @a instance Json a => Json (Maybe a) where json = jsonNullable json - jsonOmit = Just _Nothing + jsonOmitField = Just _Nothing instance (Json a, Json b) => Json (Either a b) where json = jsonTag "Left" json >+< jsonTag "Right" json instance Json Double where @@ -2594,13 +2594,13 @@ instance Json a => Json (Solo a) where jsonKeyList = overKey (iso (map getSolo) (map MkSolo) >~) (jsonKeyList @a) instance Json a => Json (Identity a) where json = coerced >~ json @a - jsonOmit = (coerced .) <$> jsonOmit @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 - jsonOmit = (coerced .) <$> jsonOmit @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)) @@ -2644,7 +2644,7 @@ 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 - jsonOmit = Just (only Proxy) + 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 @@ -3040,7 +3040,7 @@ instance (Functor f, Typeable f, Json (f (Fix f))) => Json (Nu f) where -- jsonTag instance Json b => Json (Tagged a b) where json = coerced >~ json @b - jsonOmit = (coerced .) <$> jsonOmit @b + jsonOmitField = (coerced .) <$> jsonOmitField @b jsonKey = overKey (coerced >~) (jsonKey @b) jsonKeyList = overKey (coerced >~) (jsonKeyList @b) @@ -3066,7 +3066,7 @@ instance (Json (f a), Json (g a)) => Json (These1 f g a) where -- strict instance Json a => Json (Strict.Maybe a) where json = iso Strict.toLazy Strict.toStrict >~ json @(Maybe a) - jsonOmit = Just (nearly Strict.Nothing Strict.isNothing) + 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 @@ -3251,9 +3251,9 @@ 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 `jsonOmit`. + -- An omittable field, by `jsonOmitField`. property :: (JsonVal p, JsonObj p q) => q a a - property = case jsonOmit @a of + property = case jsonOmitField @a of Just omitted | Aeson.allowOmittedFields opts || Aeson.omitNothingFields opts -> withPrism omitted $ \omit match -> From baa5b1a813438d588dba9b3a4af83b53b458b59e Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sun, 8 Nov 2026 08:59:06 -0800 Subject: [PATCH 067/130] Rename Control.Lens.Internal.Distributors to the singular Distributor Co-Authored-By: Claude Opus 5.5 --- distributors-core/CHANGELOG.md | 2 +- distributors-core/distributors.cabal | 4 ++-- .../Internal/{Distributors => Distributor}/NestedPrismTH.hs | 4 ++-- .../Lens/Internal/{Distributors => Distributor}/Orphanage.hs | 4 ++-- distributors-core/src/Control/Lens/PartialIso.hs | 4 ++-- 5 files changed, 9 insertions(+), 9 deletions(-) rename distributors-core/src/Control/Lens/Internal/{Distributors => Distributor}/NestedPrismTH.hs (98%) rename distributors-core/src/Control/Lens/Internal/{Distributors => Distributor}/Orphanage.hs (97%) diff --git a/distributors-core/CHANGELOG.md b/distributors-core/CHANGELOG.md index f8c0fc8d..4e4cd664 100644 --- a/distributors-core/CHANGELOG.md +++ b/distributors-core/CHANGELOG.md @@ -34,7 +34,7 @@ & `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.Distributors.NestedPrismTH` & `.Orphanage`. + `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. diff --git a/distributors-core/distributors.cabal b/distributors-core/distributors.cabal index b48c92cf..d14e5fb0 100644 --- a/distributors-core/distributors.cabal +++ b/distributors-core/distributors.cabal @@ -31,8 +31,8 @@ library Control.Lens.Bifocal Control.Lens.Diopter Control.Lens.Grate - Control.Lens.Internal.Distributors.NestedPrismTH - Control.Lens.Internal.Distributors.Orphanage + Control.Lens.Internal.Distributor.NestedPrismTH + Control.Lens.Internal.Distributor.Orphanage Control.Lens.Monocle Control.Lens.PartialIso Control.Lens.Wither diff --git a/distributors-core/src/Control/Lens/Internal/Distributors/NestedPrismTH.hs b/distributors-core/src/Control/Lens/Internal/Distributor/NestedPrismTH.hs similarity index 98% rename from distributors-core/src/Control/Lens/Internal/Distributors/NestedPrismTH.hs rename to distributors-core/src/Control/Lens/Internal/Distributor/NestedPrismTH.hs index 13c767d1..a8a68e23 100644 --- a/distributors-core/src/Control/Lens/Internal/Distributors/NestedPrismTH.hs +++ b/distributors-core/src/Control/Lens/Internal/Distributor/NestedPrismTH.hs @@ -1,5 +1,5 @@ {- | -Module : Control.Lens.Internal.Distributors.NestedPrismTH +Module : Control.Lens.Internal.Distributor.NestedPrismTH Description : nested pair prisms Copyright : (C) 2026 - Eitan Chatav License : BSD-style (see the file LICENSE) @@ -11,7 +11,7 @@ Code is duplicated from `Control.Lens.Internal.PrismTH`, with small tweaks to support nested pairs. -} -module Control.Lens.Internal.Distributors.NestedPrismTH +module Control.Lens.Internal.Distributor.NestedPrismTH ( -- * Nested prisms makeNestedPrisms ) where diff --git a/distributors-core/src/Control/Lens/Internal/Distributors/Orphanage.hs b/distributors-core/src/Control/Lens/Internal/Distributor/Orphanage.hs similarity index 97% rename from distributors-core/src/Control/Lens/Internal/Distributors/Orphanage.hs rename to distributors-core/src/Control/Lens/Internal/Distributor/Orphanage.hs index a496ce22..9d5ac240 100644 --- a/distributors-core/src/Control/Lens/Internal/Distributors/Orphanage.hs +++ b/distributors-core/src/Control/Lens/Internal/Distributor/Orphanage.hs @@ -1,7 +1,7 @@ {-# OPTIONS_GHC -Wno-orphans #-} {- | -Module : Control.Lens.Internal.Distributors.Orphanage +Module : Control.Lens.Internal.Distributor.Orphanage Description : orphanage Copyright : (C) 2026 - Eitan Chatav License : BSD-style (see the file LICENSE) @@ -12,7 +12,7 @@ Portability : non-portable An orphanage for instances without a home. -} -module Control.Lens.Internal.Distributors.Orphanage () where +module Control.Lens.Internal.Distributor.Orphanage () where import Control.Applicative hiding (WrappedArrow) import Control.Applicative qualified as Ap (WrappedArrow) diff --git a/distributors-core/src/Control/Lens/PartialIso.hs b/distributors-core/src/Control/Lens/PartialIso.hs index 625157bc..6a0742cc 100644 --- a/distributors-core/src/Control/Lens/PartialIso.hs +++ b/distributors-core/src/Control/Lens/PartialIso.hs @@ -54,8 +54,8 @@ module Control.Lens.PartialIso ) where import Control.Lens -import Control.Lens.Internal.Distributors.Orphanage () -import Control.Lens.Internal.Distributors.NestedPrismTH +import Control.Lens.Internal.Distributor.Orphanage () +import Control.Lens.Internal.Distributor.NestedPrismTH import Control.Lens.Internal.Profunctor import Control.Lens.Iso import Control.Lens.Prism From c30bc4c00db1b22aeac6529375287b01aa384809 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sun, 8 Nov 2026 09:29:17 -0800 Subject: [PATCH 068/130] Read RegString & RegBnf as String reads, so that read . show = id show prints them as string literals, but read took all of its input as their text, quotes included, so read . show wasn't id, & they couldn't be read within a list or a Maybe. read now reads a string literal, by String's readsPrec at its precision, leaving the rest, & its text by the grammar, failing for text which doesn't parse. Co-Authored-By: Claude Opus 5.5 --- .../src/Control/Lens/Grammar.hs | 14 +++++++++-- .../test/Properties/Kleene.hs | 23 ++++++++++++++++++- 2 files changed, 34 insertions(+), 3 deletions(-) diff --git a/distributors-grammar/src/Control/Lens/Grammar.hs b/distributors-grammar/src/Control/Lens/Grammar.hs index 3c8f1a3f..0d463b9f 100644 --- a/distributors-grammar/src/Control/Lens/Grammar.hs +++ b/distributors-grammar/src/Control/Lens/Grammar.hs @@ -1104,7 +1104,7 @@ 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 @@ -1123,4 +1123,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/distributors-grammar/test/Properties/Kleene.hs b/distributors-grammar/test/Properties/Kleene.hs index 9cb4253a..4e43bac6 100644 --- a/distributors-grammar/test/Properties/Kleene.hs +++ b/distributors-grammar/test/Properties/Kleene.hs @@ -4,8 +4,10 @@ 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 (prop) +import Test.Hspec.QuickCheck (modifyMaxSize, prop) import Test.QuickCheck #if !MIN_VERSION_QuickCheck(2,17,0) @@ -54,6 +56,20 @@ instance Arbitrary (RegEx Char) where 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) @@ -145,3 +161,8 @@ kleeneProperties = do (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 + From 5dce657c203558660ae3016974ca139e9f0ab279 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sun, 8 Nov 2026 09:29:17 -0800 Subject: [PATCH 069/130] Document why each TypeScript grammar is regular or contextual tsGrammar isn't LL(1), as the docs said: it's a CtxGrammar by try, which backtracks where TypeScript's syntax needs more lookahead, while tsTokensGrammar is one by monadic bonding, of templates' brace depths. Co-Authored-By: Claude Opus 5.5 --- .../src/Control/Lens/Grammar/TypeScript.hs | 31 ++++++++++++++----- 1 file changed, 24 insertions(+), 7 deletions(-) diff --git a/distributors-json/src/Control/Lens/Grammar/TypeScript.hs b/distributors-json/src/Control/Lens/Grammar/TypeScript.hs index d3e214c6..bebf2d16 100644 --- a/distributors-json/src/Control/Lens/Grammar/TypeScript.hs +++ b/distributors-json/src/Control/Lens/Grammar/TypeScript.hs @@ -17,7 +17,9 @@ together. Both layers parse by `parsecG` & print by `unparsecG`, locating failures, since `tsTokensGrammar` scans tokens without their trivia, as the compiler -does. Here, a declaration prints as tokens, & as characters, & parses back. +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))] @@ -30,8 +32,12 @@ True -} module Control.Lens.Grammar.TypeScript - ( -- * Declarations - TsDeclaration (..) + ( -- * Grammar + tsGrammar + , tsTokenGrammar + , tsTokensGrammar + -- * Declarations + , TsDeclaration (..) , TsModuleName (..) , TsImportClause (..) , TsNamedBindings (..) @@ -52,12 +58,9 @@ module Control.Lens.Grammar.TypeScript , TsParameter (..) , TsBindingName (..) , TsBindingElement (..) - , tsGrammar -- * Tokens , TsToken (..) , TsTokenCategory (..) - , tsTokenGrammar - , tsTokensGrammar ) where import Control.Lens @@ -466,6 +469,8 @@ 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 @@ -549,10 +554,14 @@ templateChar = orP {- | 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 @LL(1)@. +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.>>=`, the depths that a @}@ is scanned by. -} tsTokensGrammar :: CtxGrammar Char [TsToken] tsTokensGrammar = rmap @@ -697,6 +706,14 @@ 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. From d7e650ca93ec406686fa3e022e2c288f5027a88b Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sun, 8 Nov 2026 10:25:15 -0800 Subject: [PATCH 070/130] Complete ViaJson's aeson instances: omitted fields & keys ViaJson derives omitField & omittedField, by jsonOmitField, & ToJSONKey & FromJSONKey, by jsonKey & jsonKeyList, or else as values in arrays of pairs, as aeson's defaults do; & it's Eq, Ord & Show. Tested against aeson's own instances: maps of Int, Text, (Int, Int) & String keys, & omitted Maybe fields. Co-Authored-By: Claude Opus 5.5 --- distributors-json/CHANGELOG.md | 4 ++ .../src/Control/Lens/Grammar/Json.hs | 57 ++++++++++++++++--- distributors-json/test/Properties/Json.hs | 26 ++++++++- 3 files changed, 76 insertions(+), 11 deletions(-) diff --git a/distributors-json/CHANGELOG.md b/distributors-json/CHANGELOG.md index cb5c9f57..32ef2594 100644 --- a/distributors-json/CHANGELOG.md +++ b/distributors-json/CHANGELOG.md @@ -14,5 +14,9 @@ - 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. +- `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/src/Control/Lens/Grammar/Json.hs b/distributors-json/src/Control/Lens/Grammar/Json.hs index abc01007..c8942b8a 100644 --- a/distributors-json/src/Control/Lens/Grammar/Json.hs +++ b/distributors-json/src/Control/Lens/Grammar/Json.hs @@ -286,30 +286,32 @@ class Json a where json = jsonGeneric Aeson.defaultOptions {-# INLINABLE json #-} - {- | `Data.Aeson.toJSONList`, an array of values by default. - `Char` overrides it, so that a `String` is a JSON string, - as do types wrapping a `Char`, by forwarding it. + {- | `Data.Aeson.toJSONList` & `Data.Aeson.parseJSONList`, + as one grammar, an array of values by default. + `Char` and wrappers override it, so that a `String` is a JSON string. -} jsonList :: JsonVal p => p [a] [a] jsonList = jsonArray json {-# INLINE jsonList #-} - {- | `Data.Aeson.toJSONKey`, as the text keys of objects, + {- | `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`, keys of lists, like `jsonList`. - `Char` overrides it, so that a `String` is a key. + {- | `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 `Aeson.omitNothingFields`, - & reviews the value of a field omitted by `Aeson.allowOmittedFields`. + 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 @@ -352,7 +354,10 @@ jsonErrorEncode = runJsonPrintor json {-# INLINE jsonErrorEncode #-} {- | @aeson@'s instances, derived from a `Json` instance, failing to parse -at the path of a `JsonError`, by its message. +at the path of a `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 @@ -360,6 +365,7 @@ at the path of a `JsonError`, by its message. > 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 @@ -368,10 +374,43 @@ instance Json a => Aeson.ToJSON (ViaJson a) where (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 `JsonError`, by its message. parseFailure :: JsonError -> Aeson.Parser x diff --git a/distributors-json/test/Properties/Json.hs b/distributors-json/test/Properties/Json.hs index 6e9f2101..2b7720b2 100644 --- a/distributors-json/test/Properties/Json.hs +++ b/distributors-json/test/Properties/Json.hs @@ -32,8 +32,8 @@ import Control.Lens.Grammar.TypeScript import Data.Foldable (toList) import Data.Sequence qualified as Seq import Data.Aeson - ( FromJSON (..), Options (..), SumEncoding (..), ToJSON (..), Value (String) - , camelTo2, decode, defaultOptions, genericToJSON + ( FromJSON (..), Options (..), SumEncoding (..), ToJSON (..), ToJSONKey + , Value (String), camelTo2, decode, defaultOptions, encode, genericToJSON , object, (.=) ) import Data.Aeson.Encoding (encodingToLazyByteString) @@ -727,6 +727,28 @@ jsonCodecSpec = describe "jsonEncode" $ do 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 -> From 45a413c55bd333e683ce9f829efd3254074f85de Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sun, 8 Nov 2026 10:36:25 -0800 Subject: [PATCH 071/130] Update Json.hs --- distributors-json/src/Control/Lens/Grammar/Json.hs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/distributors-json/src/Control/Lens/Grammar/Json.hs b/distributors-json/src/Control/Lens/Grammar/Json.hs index c8942b8a..ef361d81 100644 --- a/distributors-json/src/Control/Lens/Grammar/Json.hs +++ b/distributors-json/src/Control/Lens/Grammar/Json.hs @@ -103,13 +103,13 @@ export type Shape = { kind: "circle"; radius: Double } | { kind: "rectangle"; si module Control.Lens.Grammar.Json ( -- * Json Json (..) + , jsonGeneric , jsonParse , jsonDecode , jsonPrint , jsonErrorPrint , jsonEncode , jsonErrorEncode - , jsonGeneric , ViaJson (..) -- * Grammar , JsonVal (..), jsonTyped From af0281602f28d1e229c886b15084d3d47d3c3437 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sun, 8 Nov 2026 11:08:06 -0800 Subject: [PATCH 072/130] Fix haddock links: out-of-scope & ambiguous identifiers, fixP's doc Qualify references Haddock can't see: Control.Lens.Grammar's docs above its Template Haskell splices can't see names defined below them, & a few modules mention >+<, empty & Alternative without importing them. Mark types sharing a name with their constructor as types, t'Name', which Haddock links them to anyway, & document fixP. Co-Authored-By: Claude Opus 5.5 --- distributors-core/src/Control/Lens/Bifocal.hs | 8 +-- distributors-core/src/Control/Lens/Diopter.hs | 8 +-- distributors-core/src/Control/Lens/Grate.hs | 4 +- distributors-core/src/Control/Lens/Monocle.hs | 18 ++--- .../src/Control/Lens/PartialIso.hs | 4 +- .../src/Data/Profunctor/Filtrator.hs | 2 +- .../src/Data/Profunctor/Monoidal.hs | 3 + .../src/Data/Profunctor/Separator.hs | 6 +- .../src/Data/Traversable/Homogeneous.hs | 4 +- .../src/Control/Lens/Grammar.hs | 72 ++++++++++--------- .../src/Control/Lens/Grammar/BackusNaur.hs | 12 ++-- .../src/Control/Lens/Grammar/Machine.hs | 12 ++-- .../src/Control/Lens/Grammar/RegEx.hs | 12 ++-- .../src/Control/Lens/Grammar/Symbol.hs | 6 +- .../src/Control/Monad/Fail/Try.hs | 2 +- .../src/Data/Profunctor/Grammar.hs | 6 +- .../src/Data/Profunctor/Grammar/Parsector.hs | 22 +++--- .../src/Control/Lens/Grammar/Json.hs | 46 ++++++------ .../src/Control/Lens/Grammar/TypeScript.hs | 2 +- 19 files changed, 129 insertions(+), 120 deletions(-) diff --git a/distributors-core/src/Control/Lens/Bifocal.hs b/distributors-core/src/Control/Lens/Bifocal.hs index 5bef52f9..cc4ee6de 100644 --- a/distributors-core/src/Control/Lens/Bifocal.hs +++ b/distributors-core/src/Control/Lens/Bifocal.hs @@ -55,7 +55,7 @@ Every one of the following is a `Bifocal`. * `Control.Lens.Diopter.Diopter` * `Prismoid` & `Filtroid` -`Bifocal`s are isomorphic to `Binocular`s. +`Bifocal`s are isomorphic to t'Binocular's. -} type Bifocal s t a b = forall p f. (Alternator p, Filtrator p, Alternative f, Filterable f) @@ -76,7 +76,7 @@ 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`. -} +{- | 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 @@ -145,7 +145,7 @@ withBifocal => ABifocal s t a b -> ((s -> Maybe a) -> f b) -> f t withBifocal bif = unBinocular (catMaybes (bif (Just <$> Binocular ($ Just)))) -{- | `Binocular` provides an efficient +{- | t'Binocular' provides an efficient concrete representation of `Bifocal`s. -} newtype Binocular a b s t = Binocular { unBinocular @@ -189,7 +189,7 @@ instance CocartesianChoice (Binocular a b) instance Alternator (Binocular a b) instance Filtrator (Binocular a b) -{- | Run a `Binocular` on a partial `Distributor`. -} +{- | Run a t'Binocular' on a partial `Distributor`. -} runBinocular :: (Alternator p, Filtrator p) => Binocular a b s t diff --git a/distributors-core/src/Control/Lens/Diopter.hs b/distributors-core/src/Control/Lens/Diopter.hs index 88d3ef2d..14f93ac3 100644 --- a/distributors-core/src/Control/Lens/Diopter.hs +++ b/distributors-core/src/Control/Lens/Diopter.hs @@ -41,7 +41,7 @@ import GHC.Generics Every `Control.Lens.Iso.Iso` and `Control.Lens.Monocle` is a `Diopter`. -`Diopter`s are isomorphic to `Dioptrice`s. +`Diopter`s are isomorphic to t'Dioptrice's. -} type Diopter s t a b = forall p f. (Distributor p, Applicative f) @@ -91,7 +91,7 @@ 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 `empty`. +when they have the same shape, or else `Control.Applicative.empty`. >>> zipDiopter manied (Just . sum) [[1, 2], [3, 4], [5, 6 :: Int]] Just [9,12] @@ -124,7 +124,7 @@ 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 `Dioptrice` provides efficient access +{- | A t'Dioptrice' provides efficient access to some pair of functions that make up a `Diopter`. -} data Dioptrice a b s t where @@ -157,7 +157,7 @@ instance Distributor (Dioptrice a b) where (Comp1 . fmap f) (fmap g . unComp1) -{- | Run a `Dioptrice` on a `Distributor`. -} +{- | Run a t'Dioptrice' on a `Distributor`. -} runDioptrice :: Distributor p => Dioptrice a b s t diff --git a/distributors-core/src/Control/Lens/Grate.hs b/distributors-core/src/Control/Lens/Grate.hs index 56535014..a096c32f 100644 --- a/distributors-core/src/Control/Lens/Grate.hs +++ b/distributors-core/src/Control/Lens/Grate.hs @@ -42,7 +42,7 @@ import Data.Profunctor.Monoidal Every `Control.Lens.Monocle.Monocle` is a `Grate`. -`Grate`s are isomorphic to `Grating`s. +`Grate`s are isomorphic to t'Grating's. -} type Grate s t a b = forall p f. (Closed p, Monoidal p, Distributive f, Applicative f) @@ -99,7 +99,7 @@ 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} diff --git a/distributors-core/src/Control/Lens/Monocle.hs b/distributors-core/src/Control/Lens/Monocle.hs index bacd36b5..fa1fda4d 100644 --- a/distributors-core/src/Control/Lens/Monocle.hs +++ b/distributors-core/src/Control/Lens/Monocle.hs @@ -71,7 +71,7 @@ import Numeric.Natural (Natural) Every `Control.Lens.Iso.Iso` is a `Monocle`. -`Monocle`s are isomorphic to `Monocular`s. +`Monocle`s are isomorphic to t'Monocular's. -} type Monocle s t a b = forall p f. (Monoidal p, Applicative f) @@ -81,7 +81,7 @@ type Monocle s t a b = forall p f. 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`. -} +{- | 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 @@ -136,7 +136,7 @@ forevered = unwrapPafb . foreverP . WrapPafb 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 +{- | 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} @@ -148,7 +148,7 @@ 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`. -} +{- | 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 @@ -162,7 +162,7 @@ whose residue is which copy is held. >>> view _Enumerable (Identity 'a') 'a' -`Comonocle`s are isomorphic to `Comonocular`s. +`Comonocle`s are isomorphic to t'Comonocular's. -} type Comonocle s t a b = forall p f. (CocartesianMonoidal p, Functor f) @@ -172,7 +172,7 @@ type Comonocle s t a b = forall p f. type AComonocle s t a b = Comonocular a b a (Identity b) -> Comonocular a b s (Identity t) -{- | Build a `Comonocle` from a concrete `Comonocular`. -} +{- | 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 @@ -256,7 +256,7 @@ 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 `empty`. +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) @@ -343,7 +343,7 @@ numbered by `fromEnum` from `minBound`. _BoundedEnum :: (Bounded a, Enum a) => Comonocle a a () () _BoundedEnum = iso (\x -> (x,())) (\(x,()) -> x) . _Enumerable -{- | `Comonocular` provides a concrete representation of `Comonocle`s, +{- | t'Comonocular' provides a concrete representation of `Comonocle`s, by an `Enumerable` sum of copies. -} data Comonocular a b s t where @@ -360,7 +360,7 @@ instance CocartesianMonoidal (Comonocular a b) where (either (L1 . split0) (R1 . split1)) (\case L1 x -> Left (merge0 x); R1 y -> Right (merge1 y)) -{- | Run a `Comonocular` on a `CocartesianMonoidal` `Profunctor`. -} +{- | 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/PartialIso.hs b/distributors-core/src/Control/Lens/PartialIso.hs index 6a0742cc..b3a90631 100644 --- a/distributors-core/src/Control/Lens/PartialIso.hs +++ b/distributors-core/src/Control/Lens/PartialIso.hs @@ -84,7 +84,7 @@ 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. +`PartialIso`s are isomorphic to t'PartialExchange's. -} type PartialIso s t a b = forall p f. (Choice p, Cochoice p, Applicative f, Filterable f) @@ -118,7 +118,7 @@ type PartialIso' s a = PartialIso s s a a type APartialIso s t a b = PartialExchange a b a (Maybe b) -> PartialExchange a b s (Maybe t) -{- | A `PartialExchange` provides efficient access +{- | A t'PartialExchange' provides efficient access to the two functions that make up a `PartialIso`. -} data PartialExchange a b s t = diff --git a/distributors-core/src/Data/Profunctor/Filtrator.hs b/distributors-core/src/Data/Profunctor/Filtrator.hs index 83b34231..0b11bb21 100644 --- a/distributors-core/src/Data/Profunctor/Filtrator.hs +++ b/distributors-core/src/Data/Profunctor/Filtrator.hs @@ -30,7 +30,7 @@ import Witherable {- | The `Filtrator` class extends `Cochoice`, as well as `Filterable`, adding the `filtrate` method, which is an oplax monoidal structure morphism dual to -`>+<`. +`Data.Profunctor.Monoidal.Cocartesian.>+<`. > prop> filtrate . uncurry (>+<) = id > prop> uncurry (>+<) . filtrate = id diff --git a/distributors-core/src/Data/Profunctor/Monoidal.hs b/distributors-core/src/Data/Profunctor/Monoidal.hs index 57d492c0..9681ccaa 100644 --- a/distributors-core/src/Data/Profunctor/Monoidal.hs +++ b/distributors-core/src/Data/Profunctor/Monoidal.hs @@ -273,6 +273,9 @@ like `Control.Arrow.arr`. 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 .))) diff --git a/distributors-core/src/Data/Profunctor/Separator.hs b/distributors-core/src/Data/Profunctor/Separator.hs index b80b3013..986f3dae 100644 --- a/distributors-core/src/Data/Profunctor/Separator.hs +++ b/distributors-core/src/Data/Profunctor/Separator.hs @@ -46,14 +46,14 @@ data SepBy p = SepBy , Eq, Ord, Show, Read ) -{- | A `SepBy` smart constructor, +{- | A t'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, +{- | A t'SepBy' smart constructor for no separator, beginning or ending delimiters. -} noSep :: Applicative p => SepBy (p ()) noSep = sepBy (pure ()) @@ -99,7 +99,7 @@ chain1 association pat (SepBy beg end sep) = leftOrRight chainl1 chainr1 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`. -} +{- | Add a t'SepBy' to `replicateP` using `intercalateP`. -} intercalateP :: (Monoidal p, Choice p, AsEmpty s, Cons s s a a) => Int {- ^ number of repetitions -} diff --git a/distributors-core/src/Data/Traversable/Homogeneous.hs b/distributors-core/src/Data/Traversable/Homogeneous.hs index d5aaa234..23358050 100644 --- a/distributors-core/src/Data/Traversable/Homogeneous.hs +++ b/distributors-core/src/Data/Traversable/Homogeneous.hs @@ -427,7 +427,7 @@ transposeHomogeneous transposeHomogeneous = zipHomogeneous Just -{- | `Indexing` numbers the copies of a sum of products, from 0, +{- | t'Indexing' 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. -} @@ -458,7 +458,7 @@ instance Cochoice Indexing where (which . Right) (select >=> either (const Nothing) Just) -{- | `Zipporah` is a profunctor @p@ between functors, like `Data.Bifunctor.Biff`, +{- | 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. -} diff --git a/distributors-grammar/src/Control/Lens/Grammar.hs b/distributors-grammar/src/Control/Lens/Grammar.hs index 0d463b9f..8bcb6cbc 100644 --- a/distributors-grammar/src/Control/Lens/Grammar.hs +++ b/distributors-grammar/src/Control/Lens/Grammar.hs @@ -175,7 +175,7 @@ because @_SemVer@ is an `Control.Lens.Iso.Iso`. +------------+---------------+ | `<|>` | `>|<` | +------------+---------------+ -| `choice` | `orP` | +| @choice@ | `orP` | +------------+---------------+ | `many` | `manyP` | +------------+---------------+ @@ -184,7 +184,8 @@ because @_SemVer@ is an `Control.Lens.Iso.Iso`. | `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}|-)+)*))?))) @@ -219,7 +220,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. @@ -398,7 +400,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. @@ -434,17 +436,19 @@ unrestricted filtration of grammars by computable predicates, which can recognize the larger class of recursively enumerable languages. 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 effects `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. 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" @@ -473,7 +477,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. @@ -484,17 +488,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") "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")))) -`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`. @@ -505,16 +510,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 @@ -524,7 +529,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 @@ -551,7 +556,7 @@ 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 @@ -565,7 +570,7 @@ using `BooleanAlgebra` combinators. >>> tokenClass (notP (oneOf "xyz")) :: RegString "[^xyz]" -Ill-formed `RegString`s normalize to failure. +Ill-formed t'RegString's normalize to failure. >>> fromString ")(" :: RegString "[]" @@ -579,17 +584,17 @@ newtype RegString = RegString {runRegString :: RegEx Char} , 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 @@ -599,12 +604,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. @@ -634,8 +640,8 @@ 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. +{- | `regexGrammar` is a context-free `Grammar` for t'RegString's. +It can't be a `RegGrammar`, since t'RegString's include parenthesization. But [balanced parentheses](https://en.wikipedia.org/wiki/Dyck_language) are a context-free language. @@ -817,7 +823,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) @@ -844,14 +850,14 @@ regbnfGrammar = rule "regbnf" $ _RegBnf . _Bnf >~ (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`. @@ -859,7 +865,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 @@ -1081,7 +1087,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 diff --git a/distributors-grammar/src/Control/Lens/Grammar/BackusNaur.hs b/distributors-grammar/src/Control/Lens/Grammar/BackusNaur.hs index f20d01b8..7bde099f 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/BackusNaur.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/BackusNaur.hs @@ -76,8 +76,8 @@ 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 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. @@ -89,15 +89,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 @@ -107,7 +107,7 @@ 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 diff --git a/distributors-grammar/src/Control/Lens/Grammar/Machine.hs b/distributors-grammar/src/Control/Lens/Grammar/Machine.hs index 63b15e08..45ee2ebd 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/Machine.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/Machine.hs @@ -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] @@ -364,7 +364,7 @@ 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 `falseP` result means the current chart has no scanner transitions, i.e. the prefix is a dead end for recognition. @@ -404,7 +404,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 index c06c064c..3814eac6 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/RegEx.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/RegEx.hs @@ -56,8 +56,8 @@ data 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`. +{- | Both `RegEx`pressions and t'TokenClass'es are algebras over the t`RegExam` endo-`Functor`. +t'TokenClass' is the fixed point of t`RegExam`. -} data RegExam token alg = OneOf (Set token) @@ -85,7 +85,7 @@ data CategoryTest token = AndAsIn (Categorize token) | AndNotAsIn (Set (Categorize token)) -{- | `TokenClass` forms a `Tokenized` `BooleanAlgebra`, +{- | t'TokenClass' forms a `Tokenized` `BooleanAlgebra`, such that the following invariants hold. > prop> trueP = anyToken @@ -96,8 +96,8 @@ such that the following invariants hold. > prop> notP . asIn = notAsIn > prop> notP . notAsIn = asIn -`TokenClass` is the fixed point algebra of t`RegExam`. -`TokenClass`es may be understood as normalizations of +t'TokenClass' is the fixed point algebra of t`RegExam`. +t'TokenClass'es may be understood as normalizations of `BooleanAlgebra` expressions generated by `Tokenized` expressions. -} @@ -111,7 +111,7 @@ 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 `Alternative`, +Likewise, when a `TokenAlgebra` is `Control.Applicative.Alternative`, > prop> empty = tokenClass falseP > prop> tokenClass x <|> tokenClass y = tokenClass (x >|< y) diff --git a/distributors-grammar/src/Control/Lens/Grammar/Symbol.hs b/distributors-grammar/src/Control/Lens/Grammar/Symbol.hs index 2bdcbdcf..6f2f7f04 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/Symbol.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/Symbol.hs @@ -39,7 +39,7 @@ class TerminalSymbol token s | s -> token where class NonTerminalSymbol s where nonTerminal :: String -> s -{- | A `SepBy` smart constructor like `sepBy`, +{- | A t'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`. -} @@ -48,12 +48,12 @@ sepWith => [c] -> SepBy (p ()) sepWith = sepBy . terminal -{- | A `SepBy` smart modifier like `beginBy`, +{- | A t'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`, +{- | A t'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} diff --git a/distributors-grammar/src/Control/Monad/Fail/Try.hs b/distributors-grammar/src/Control/Monad/Fail/Try.hs index 3c1e7677..e2bbb273 100644 --- a/distributors-grammar/src/Control/Monad/Fail/Try.hs +++ b/distributors-grammar/src/Control/Monad/Fail/Try.hs @@ -51,7 +51,7 @@ 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 diff --git a/distributors-grammar/src/Data/Profunctor/Grammar.hs b/distributors-grammar/src/Data/Profunctor/Grammar.hs index 179a92a6..bfd47625 100644 --- a/distributors-grammar/src/Data/Profunctor/Grammar.hs +++ b/distributors-grammar/src/Data/Profunctor/Grammar.hs @@ -44,7 +44,7 @@ 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 @@ -53,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, @@ -68,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 diff --git a/distributors-grammar/src/Data/Profunctor/Grammar/Parsector.hs b/distributors-grammar/src/Data/Profunctor/Grammar/Parsector.hs index a7c90a50..e55ea627 100644 --- a/distributors-grammar/src/Data/Profunctor/Grammar/Parsector.hs +++ b/distributors-grammar/src/Data/Profunctor/Grammar/Parsector.hs @@ -44,15 +44,15 @@ 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) @@ -61,9 +61,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 @@ -74,13 +74,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 @@ -93,7 +93,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 @@ -112,9 +112,9 @@ 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 diff --git a/distributors-json/src/Control/Lens/Grammar/Json.hs b/distributors-json/src/Control/Lens/Grammar/Json.hs index ef361d81..02b26d65 100644 --- a/distributors-json/src/Control/Lens/Grammar/Json.hs +++ b/distributors-json/src/Control/Lens/Grammar/Json.hs @@ -34,7 +34,7 @@ Failures are located, & name what they expected. = @aeson@ -`ViaJson` derives @aeson@'s instances, & `jsonGeneric` takes +t'ViaJson' derives @aeson@'s instances, & `jsonGeneric` takes @aeson@'s `Aeson.Options`. >>> :{ @@ -288,7 +288,7 @@ class Json a where {- | `Data.Aeson.toJSONList` & `Data.Aeson.parseJSONList`, as one grammar, an array of values by default. - `Char` and wrappers override it, so that a `String` is a JSON string. + `Char` and wrappers override it, so that a t'String' is a JSON string. -} jsonList :: JsonVal p => p [a] [a] jsonList = jsonArray json @@ -354,7 +354,7 @@ jsonErrorEncode = runJsonPrintor json {-# INLINE jsonErrorEncode #-} {- | @aeson@'s instances, derived from a `Json` instance, failing to parse -at the path of a `JsonError`, by its message: `Aeson.ToJSON` & +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. @@ -412,7 +412,7 @@ keyParser keyParser key = Aeson.FromJSONKeyTextParser (either parseFailure pure . runJsonParsor key . String) --- | Fail to parse at the path of a `JsonError`, by its message. +-- | 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) @@ -672,7 +672,7 @@ data JsonError = JsonError , jsonErrorRules :: Forest String } deriving stock (Eq, Show) --- | How a `JsonError` failed, so that alternatives report the closest. +-- | How a t'JsonError' failed, so that alternatives report the closest. data JsonErrorSort = JsonLiteral -- ^ a string literal mismatch; the alternative doesn't apply @@ -682,7 +682,7 @@ data JsonErrorSort -- ^ the value was rejected for what it contains, lacks or repeats deriving stock (Eq, Ord, Show) -{- | A `JsonError`'s message, without its path, as @aeson@ words it. +{- | 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\"" @@ -769,7 +769,7 @@ jsonOrElse err1 err2 -- Parsing interpreters -- -{- | `JsonParsor` parses a `Value`. It may also have a `Dispatch`, +{- | 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. @@ -824,7 +824,7 @@ orElse p q v = case p v of Left err1 -> onFailure (jsonOrElse err1) (q v) success -> success -{- | `TupParsor` parses the elements of a JSON array from a position, +{- | 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. -} @@ -833,7 +833,7 @@ data TupParsor a b = TupParsor , runTupParsor :: Vector Value -> Int -> [Either JsonError (b, Int)] } -{- | `ObjParsor` reads keys of an `Object`, ignoring other keys, +{- | 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, @@ -947,7 +947,7 @@ instance JsonVal JsonParsor where jsonObject obj = objectParsor False obj jsonObjectStrict obj = objectParsor True obj -{- | Parse an `Object` by its properties, and, if it's rejecting, +{- | 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. -} @@ -1100,7 +1100,7 @@ showKey = show . Key.toText -- Printing interpreters -- --- | @aeson@'s representations of JSON strings, `Value`, `Encoding` & `Key`. +-- | @aeson@'s representations of JSON strings, `Value`, `Encoding` & t'Key'. class AesonStr val where aesonText :: Text -> val aesonString :: String -> val @@ -1142,8 +1142,8 @@ instance AesonStr (Encoding.Encoding' a) where retagEncoding :: Encoding.Encoding' a -> Encoding.Encoding' b retagEncoding = Encoding.unsafeToEncoding . Encoding.fromEncoding -{- | `KeyPrintor` prints the key of an `Object`, which is total, -as a `Key` or as its `Encoding.Encoding'`. +{- | 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} @@ -1299,7 +1299,7 @@ instance AesonVal Encoding where {-# INLINE aesonPropsEmpty #-} {-# INLINE aesonProps #-} -{- | `JsonPrintor` `printorTry`s to print a value, or else `printorCheck`s it +{- | 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. @@ -1321,19 +1321,19 @@ runJsonPrintor p | otherwise = \a -> maybe (printorCheck p a) Right (printorTry p a) {-# INLINE runJsonPrintor #-} --- | A total `JsonPrintor`. +-- | 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 `JsonPrintor` of a primitive. +-- | 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 `JsonPrintor`, rendering what it tries, +{- | A partial t'JsonPrintor', rendering what it tries, or else null, as `jsonPrint` does. -} trying @@ -1352,7 +1352,7 @@ tryAll total attempt render = \as -> if isTotal where isTotal = total Set.empty -{- | `TupPrintor` prints the elements of a JSON array, +{- | 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. -} @@ -1385,7 +1385,7 @@ instance Semigroup (Elements val) where instance Monoid (Elements val) where mempty = Elements (Right (0, mempty)) -{- | `ObjPrintor` writes keys of an `Object`. +{- | 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. -} @@ -1648,7 +1648,7 @@ instance AesonVal val => Choice (TupPrintor val) where unprintable :: Elements val unprintable = Elements (jsonUnexpected Nothing) --- | A partial `TupPrintor`, rendering what it tries, or else 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 @@ -1761,7 +1761,7 @@ instance AesonVal val => DisjunctiveMonoid (ObjPrintor val a b) where Left err -> onFailure (jsonOrElse err) (objPrintorCheck q a) success -> success) --- | A partial `ObjPrintor` of another's shapes, rendering what it tries. +-- | A partial t'ObjPrintor' of another's shapes, rendering what it tries. objTrying :: AesonVal val => ObjPrintor val x y @@ -1865,7 +1865,7 @@ printProperty key p a = -- Types of JSON -- {- | The type of JSON values, which a grammar describes, -of rules by their names, in a `Bnf`, as `jsonType` describes them. +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. -} @@ -2020,7 +2020,7 @@ jsonTsPut as handle = case (parsecResult printed, parsecResult source) of <> show (parsecOffset stage) <> ", expecting " <> show (parsecExpect (parsecFailure stage)) -{- | `JsonTypor` types the JSON of a grammar, reading the rules being typed +{- | 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. -} diff --git a/distributors-json/src/Control/Lens/Grammar/TypeScript.hs b/distributors-json/src/Control/Lens/Grammar/TypeScript.hs index bebf2d16..5a1e4432 100644 --- a/distributors-json/src/Control/Lens/Grammar/TypeScript.hs +++ b/distributors-json/src/Control/Lens/Grammar/TypeScript.hs @@ -284,7 +284,7 @@ instance Categorized TsToken where type Categorize TsToken = TsTokenCategory categorize = tokenCategory --- | The categories of `TsToken`s, by the TypeScript compiler's names. +-- | The categories of t'TsToken's, by the TypeScript compiler's names. data TsTokenCategory = WhitespaceTrivia | NewLineTrivia From e50c603a972208ca275a24835b8a6db70f004371 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sun, 8 Nov 2026 11:08:52 -0800 Subject: [PATCH 073/130] Update Monoidal.hs --- distributors-core/src/Data/Profunctor/Monoidal.hs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/distributors-core/src/Data/Profunctor/Monoidal.hs b/distributors-core/src/Data/Profunctor/Monoidal.hs index 9681ccaa..0ffb92de 100644 --- a/distributors-core/src/Data/Profunctor/Monoidal.hs +++ b/distributors-core/src/Data/Profunctor/Monoidal.hs @@ -23,7 +23,7 @@ module Data.Profunctor.Monoidal , fixP -- * Monoidal, Choice & Strong , meander, traverseP, foldP - -- * Deriving via Monoidal + -- * Deriving via Monoidally , Monoidally (..) ) where From a1ca4f484dc81856c1f754fe5ab9cd6646724800 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sun, 8 Nov 2026 11:43:06 -0800 Subject: [PATCH 074/130] Print pairs directly, by a jsonPair method Pairs & generic constructors of two positional fields printed by the general tuple printor: each element consed in a list by a chain of closures, the list measured, & an array allocated by the runtime at that length. jsonPair, defaulting to that tuple, prints an array of two elements directly, by AesonVal's aesonPair, whose constant size GHC allocates inline. Json/aeson: pairMap toValue 1.66x -> 0.83x & encode 1.05x -> 0.84x, rose toValue 1.48x -> 0.93x & encode 0.75x -> 0.60x, eithers toValue 1.31x -> 1.16x; the others are unchanged. Also: jsonType's required type argument has a kind, Type. Co-Authored-By: Claude Opus 5.5 --- distributors-json/CHANGELOG.md | 3 + .../src/Control/Lens/Grammar/Json.hs | 59 +++++++++++++++++-- 2 files changed, 56 insertions(+), 6 deletions(-) diff --git a/distributors-json/CHANGELOG.md b/distributors-json/CHANGELOG.md index 32ef2594..3337da82 100644 --- a/distributors-json/CHANGELOG.md +++ b/distributors-json/CHANGELOG.md @@ -14,6 +14,9 @@ - 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. - `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 diff --git a/distributors-json/src/Control/Lens/Grammar/Json.hs b/distributors-json/src/Control/Lens/Grammar/Json.hs index 02b26d65..bbaec65f 100644 --- a/distributors-json/src/Control/Lens/Grammar/Json.hs +++ b/distributors-json/src/Control/Lens/Grammar/Json.hs @@ -471,6 +471,13 @@ class -} 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) {- | A `jsonDict` object of a `Map`, whose keys can't repeat, so that printing needn't check them. -} @@ -1178,6 +1185,8 @@ class AesonStr val => AesonVal val where 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 @@ -1215,6 +1224,11 @@ instance AesonVal Value where 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 @@ -1240,6 +1254,7 @@ instance AesonVal Value where {-# INLINE aesonIntegral #-} {-# INLINE aesonDouble #-} {-# INLINE aesonList #-} + {-# INLINE aesonPair #-} {-# INLINE aesonObject #-} {-# INLINE aesonMap #-} {-# INLINE aesonValue #-} @@ -1256,6 +1271,9 @@ instance AesonVal Encoding where 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 @@ -1291,6 +1309,7 @@ instance AesonVal Encoding where {-# INLINE aesonIntegral #-} {-# INLINE aesonDouble #-} {-# INLINE aesonList #-} + {-# INLINE aesonPair #-} {-# INLINE aesonObject #-} {-# INLINE aesonMap #-} {-# INLINE aesonValue #-} @@ -1531,6 +1550,20 @@ instance AesonVal val => JsonVal (JsonPrintor val) where 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 #-} jsonMap key = printDistinct Map.foldrWithKey key jsonHashMap key = printDistinct HashMap.foldrWithKey key jsonTuple = printTuple @@ -1882,14 +1915,14 @@ data JsonType | JsonUnion [JsonType] -- ^ values of any of some types deriving stock (Eq, Ord, Show, Read) --- | The elements of a `JsonArray`, a regular expression of their types. +-- | 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 order - | JsonElementsAlt [JsonElements] -- ^ elements of any of some alternatives + | JsonElementsTup [JsonElements] -- ^ elements, in sequence + | JsonElementsAlt [JsonElements] -- ^ elements, any of some alternatives deriving stock (Eq, Ord, Show, Read) -- | A property of a `JsonObject`. @@ -1979,7 +2012,7 @@ Bnf {startBnf = JsonBoolean, rulesBnf = fromList []} >>> jsonType (Maybe Ordering) Bnf {startBnf = JsonUnion [JsonNull,JsonRule "GHC.Types.Ordering"], rulesBnf = fromList [("GHC.Types.Ordering",JsonUnion [JsonStringLiteral "LT",JsonStringLiteral "EQ",JsonStringLiteral "GT"])]} -} -jsonType :: forall a -> Json a => Bnf JsonType +jsonType :: forall (a :: Type) -> Json a => Bnf JsonType jsonType a = Bnf start (Set.fromList (Map.toList rules)) where JsonTypor typed = json @a @JsonTypor @@ -2691,7 +2724,7 @@ projectElem f = lmap f (jsonElem json) {-# INLINE projectElem #-} instance (Json a, Json b) => Json (a, b) where - json = jsonTuple (jsonElem json >*< jsonElem json) + json = jsonPair json json {-# INLINE json #-} jsonList = jsonArray json {-# INLINE jsonList #-} @@ -3318,15 +3351,22 @@ instance GFields GHC.U1 where 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 @@ -3341,8 +3381,15 @@ class GContents f where 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 = jsonTuple gelements + 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)) (\(x, y) -> x GHC.:*: y) (jsonPair a b) + Nothing -> jsonTuple gelements + Nothing -> jsonTuple gelements {-# INLINE gcontents #-} instance GContents GHC.U1 where gcontents = jsonTuple gelements From 27a45b33f2d46ad8848ed9d3beb3cc794b24397b Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sun, 8 Nov 2026 11:50:42 -0800 Subject: [PATCH 075/130] Use uncurry in the generic pair, as HLint suggests Co-Authored-By: Claude Opus 5.5 --- distributors-json/src/Control/Lens/Grammar/Json.hs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/distributors-json/src/Control/Lens/Grammar/Json.hs b/distributors-json/src/Control/Lens/Grammar/Json.hs index bbaec65f..103a09a3 100644 --- a/distributors-json/src/Control/Lens/Grammar/Json.hs +++ b/distributors-json/src/Control/Lens/Grammar/Json.hs @@ -3387,7 +3387,7 @@ instance (GElements f, GElements g) => GContents (f GHC.:*: g) where gcontents = case gelement @f @x of Just a -> case gelement @g @x of Just b -> dimap - (\(x GHC.:*: y) -> (x, y)) (\(x, y) -> x GHC.:*: y) (jsonPair a b) + (\(x GHC.:*: y) -> (x, y)) (uncurry (GHC.:*:)) (jsonPair a b) Nothing -> jsonTuple gelements Nothing -> jsonTuple gelements {-# INLINE gcontents #-} From 36bed178b2a5c7123d16169e8474352029270d45 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sun, 8 Nov 2026 12:33:36 -0800 Subject: [PATCH 076/130] Print single-property objects & small arrays directly jsonTag, an object of one property, as Either, Functor.Sum, These & sums by ObjectWithSingleField print, is a JsonVal method, which printing renders without an object's printor, by AesonVal's aesonTag: a singleton KeyMap, or a single pair. Sums by TwoElemArray print by jsonPair. And a Value array of up to four elements is allocated at its literal size, inline, rather than measured & allocated by the runtime. Json/aeson: eithers encode 1.30x -> 0.88x & toValue 1.18x -> 0.77x, tuples toValue 1.36x -> 1.11x; the others are unchanged. Co-Authored-By: Claude Opus 5.5 --- distributors-json/CHANGELOG.md | 3 ++ .../src/Control/Lens/Grammar/Json.hs | 53 +++++++++++++++---- 2 files changed, 47 insertions(+), 9 deletions(-) diff --git a/distributors-json/CHANGELOG.md b/distributors-json/CHANGELOG.md index 3337da82..12750ac0 100644 --- a/distributors-json/CHANGELOG.md +++ b/distributors-json/CHANGELOG.md @@ -17,6 +17,9 @@ - `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 diff --git a/distributors-json/src/Control/Lens/Grammar/Json.hs b/distributors-json/src/Control/Lens/Grammar/Json.hs index 103a09a3..2678adbd 100644 --- a/distributors-json/src/Control/Lens/Grammar/Json.hs +++ b/distributors-json/src/Control/Lens/Grammar/Json.hs @@ -478,6 +478,13 @@ class -} 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. -} @@ -738,6 +745,7 @@ 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 @@ -1202,6 +1210,8 @@ class AesonStr val => AesonVal val where 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 @@ -1241,10 +1251,29 @@ instance AesonVal Value where 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 = [] - aesonElems = aesonList id + -- 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 #-} @@ -1288,6 +1317,7 @@ instance AesonVal Encoding where 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 @@ -1564,6 +1594,17 @@ instance AesonVal val => JsonVal (JsonPrintor val) where 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 @@ -2463,10 +2504,6 @@ jsonEnumerated name = jsonEnumWith (\a -> fromEnum a - fromEnum (minBound `asTypeOf` a)) [(name a, a) | a <- [minBound .. maxBound]] --- | An object of a single property, as @aeson@ requires of sums' tags. -jsonTag :: JsonVal p => Text -> p a b -> p a b -jsonTag k p = jsonObjectStrict (k !: p) - boundedScientific :: Scientific -> Maybe Scientific boundedScientific s = s <$ guard (abs (base10Exponent s) <= 1024) @@ -3288,10 +3325,8 @@ instance (GHC.Constructor c, GFields f, GContents f, GNullary f) _ -> gcons opts gsingleField opts = jsonTag (Text.pack (gconTag @c opts)) (gcons @(GHC.C1 c f) opts) - gtwoElements opts = jsonTuple - ( lmap (const ()) (jsonElem (fromString (gconTag @c opts))) - *> jsonElem (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 #-} From 439e015ced79949a4ec887d58475b0b8379bd3ef Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sun, 8 Nov 2026 12:41:29 -0800 Subject: [PATCH 077/130] Parse an array of a primitive at once A t'JsonParsor' of a primitive, text, a boolean or a number, also parses an array of its values at once, when they all match: checking each, then listing them, without an Either for each element. Otherwise, the array parses element by element, failing as before. Json/aeson: longTexts fromValue 1.36x -> 0.87x, texts fromValue 1.05x -> 0.60x, bools fromValue 1.07x -> 0.46x; the others are unchanged. Co-Authored-By: Claude Opus 5.5 --- .../src/Control/Lens/Grammar/Json.hs | 42 +++++++++++++------ 1 file changed, 29 insertions(+), 13 deletions(-) diff --git a/distributors-json/src/Control/Lens/Grammar/Json.hs b/distributors-json/src/Control/Lens/Grammar/Json.hs index 2678adbd..609b11ab 100644 --- a/distributors-json/src/Control/Lens/Grammar/Json.hs +++ b/distributors-json/src/Control/Lens/Grammar/Json.hs @@ -792,6 +792,8 @@ 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]) } {- | Parsers by the string literal which they accept, @@ -803,7 +805,19 @@ data Dispatch b = Dispatch } jsonParsor :: (Value -> Either JsonError b) -> JsonParsor a b -jsonParsor = JsonParsor Nothing +jsonParsor parse = JsonParsor Nothing parse Nothing + +-- | A primitive t'JsonParsor', matching its values. +primitiveParsor + :: String -> (Value -> Maybe b) -> JsonParsor a b +primitiveParsor expected match = JsonParsor Nothing parse (Just array) + 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 @@ -812,6 +826,7 @@ mapParsing mapParsing f parsor = JsonParsor { jsonParsorDispatch = retable <$> jsonParsorDispatch parsor , runJsonParsor = f (runJsonParsor parsor) + , jsonParsorArray = Nothing } where retable dispatch = dispatch {dispatchTable = f <$> dispatchTable dispatch} @@ -891,23 +906,23 @@ instance DisjunctiveMonoid (JsonParsor a b) where dispatch = Dispatch (dispatchKey dispatch0) $ Map.unionWith orElse (dispatchTable dispatch0) (dispatchTable dispatch1) in - JsonParsor (Just dispatch) (dispatching dispatch) + JsonParsor (Just dispatch) (dispatching dispatch) Nothing _ -> jsonParsor (orElse (runJsonParsor p) (runJsonParsor q)) instance BackusNaurForm (JsonParsor a b) where rule name = mapParsing (onFailure (jsonRelabel (unqualified name)) .) 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 + (Just (Dispatch Nothing (Map.singleton literal parse))) parse Nothing where literal = Text.pack s parse = \case String t | t == literal -> Right () v -> Left (JsonError [] [show s] (Just (Right v)) JsonLiteral []) instance JsonStr JsonParsor where - jsonText = jsonParsor $ \case - String t -> Right t - v -> jsonMismatch "string" v + jsonText = primitiveParsor "string" $ \case + String t -> Just t + _ -> Nothing -- | TsLiteral alternatives, dispatched by their string. jsonEnumWith indexOf table = orP [ dimap indexOf (const a) (only i >? fromString (Text.unpack literal)) @@ -925,14 +940,15 @@ instance JsonVal JsonParsor where Left err -> Left (jsonOrElse nullError err) where nullError = JsonError [] ["null"] (Just (Right v)) JsonMismatch [] - jsonBool = jsonParsor $ \case - Bool b -> Right b - v -> jsonMismatch "boolean" v - jsonNumber = jsonParsor $ \case - Number n -> Right n - v -> jsonMismatch "number" v + jsonBool = primitiveParsor "boolean" $ \case + Bool b -> Just b + _ -> Nothing + jsonNumber = primitiveParsor "number" $ \case + Number n -> Just n + _ -> Nothing jsonValue = jsonParsor Right 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 @@ -967,7 +983,7 @@ 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 +objectParsor rejecting obj = JsonParsor dispatch parse Nothing where overlap = foldr ((<|>) . duplicateKey) Nothing (objParsorShapes obj) parse = \case From ad5aeb4ad2ac49e997d516e2baf2fa3f2f7d45f6 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sun, 8 Nov 2026 12:49:25 -0800 Subject: [PATCH 078/130] Keep parsing arrays at once through parsors' combinators A parsor's array of matching values parses at once through fmap & dimap, mapping its values, Cochoice's unleft & unright, & so prisms by ?<, failing over to element by element if any value doesn't match, rules, & alternatives, by the first's. So integers, by their prisms, & numbers' isos parse their arrays at once. Json/aeson: ints fromValue 1.05x -> 0.96x, int8s 1.05x -> 0.95x, integers 0.99x -> 0.93x, word64s 1.02x -> 0.99x; the others unchanged. Co-Authored-By: Claude Opus 5.5 --- .../src/Control/Lens/Grammar/Json.hs | 30 +++++++++++++------ 1 file changed, 21 insertions(+), 9 deletions(-) diff --git a/distributors-json/src/Control/Lens/Grammar/Json.hs b/distributors-json/src/Control/Lens/Grammar/Json.hs index 609b11ab..f849cab9 100644 --- a/distributors-json/src/Control/Lens/Grammar/Json.hs +++ b/distributors-json/src/Control/Lens/Grammar/Json.hs @@ -877,22 +877,30 @@ data ObjParsor a b = ObjParsor } instance Functor (JsonParsor a) where - fmap f = mapParsing (fmap (onSuccess f)) + 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 = mapParsing (fmap (onSuccess g)) + 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 = mapParsing $ \p v -> - p v >>= either pure (\_ -> jsonUnexpected (Just v)) - unright = mapParsing $ \p v -> - p v >>= either (\_ -> jsonUnexpected (Just v)) pure + 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) @@ -906,10 +914,14 @@ instance DisjunctiveMonoid (JsonParsor a b) where dispatch = Dispatch (dispatchKey dispatch0) $ Map.unionWith orElse (dispatchTable dispatch0) (dispatchTable dispatch1) in - JsonParsor (Just dispatch) (dispatching dispatch) Nothing - _ -> jsonParsor (orElse (runJsonParsor p) (runJsonParsor q)) + JsonParsor (Just dispatch) (dispatching dispatch) array + _ -> JsonParsor Nothing (orElse (runJsonParsor p) (runJsonParsor q)) array + where + -- An array which the first alternative parses, element by element. + array = jsonParsorArray p instance BackusNaurForm (JsonParsor a b) where - rule name = mapParsing (onFailure (jsonRelabel (unqualified name)) .) + rule name p = (mapParsing (onFailure (jsonRelabel (unqualified name)) .) p) + {jsonParsorArray = jsonParsorArray p} ruleRec name f = fix (rule name . f) instance (x ~ (), y ~ ()) => IsString (JsonParsor x y) where fromString s = JsonParsor From cad6b9b0ff2fc5474ae7df4ef807f9ea7a35ba8c Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sun, 8 Nov 2026 12:57:29 -0800 Subject: [PATCH 079/130] Parse maps of text keys by mapping their keys A t'JsonParsor' of strings which is a function of their text keeping its order, as jsonText is, marks it, & jsonMap parses a map of such keys by mapping them, in order, from an Object's ascending keys, to build its Map without comparing keys, rather than parsing each key & building it from a list. Failures are located at their keys, as before. Json/aeson: textMap fromValue 1.25x -> 1.00x, decode 1.05x -> 1.00x; the other maps are unchanged. Co-Authored-By: Claude Opus 5.5 --- .../src/Control/Lens/Grammar/Json.hs | 35 ++++++++++++++----- distributors-json/test/Properties/Json.hs | 4 +++ 2 files changed, 31 insertions(+), 8 deletions(-) diff --git a/distributors-json/src/Control/Lens/Grammar/Json.hs b/distributors-json/src/Control/Lens/Grammar/Json.hs index f849cab9..7cf2233c 100644 --- a/distributors-json/src/Control/Lens/Grammar/Json.hs +++ b/distributors-json/src/Control/Lens/Grammar/Json.hs @@ -794,6 +794,10 @@ data JsonParsor a b = JsonParsor , 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, @@ -805,12 +809,12 @@ data Dispatch b = Dispatch } jsonParsor :: (Value -> Either JsonError b) -> JsonParsor a b -jsonParsor parse = JsonParsor Nothing parse Nothing +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) +primitiveParsor expected match = JsonParsor Nothing parse (Just array) Nothing where parse v = maybe (jsonMismatch expected v) Right (match v) array arr @@ -827,6 +831,7 @@ mapParsing f parsor = JsonParsor { jsonParsorDispatch = retable <$> jsonParsorDispatch parsor , runJsonParsor = f (runJsonParsor parsor) , jsonParsorArray = Nothing + , jsonParsorText = Nothing } where retable dispatch = dispatch {dispatchTable = f <$> dispatchTable dispatch} @@ -914,27 +919,29 @@ instance DisjunctiveMonoid (JsonParsor a b) where dispatch = Dispatch (dispatchKey dispatch0) $ Map.unionWith orElse (dispatchTable dispatch0) (dispatchTable dispatch1) in - JsonParsor (Just dispatch) (dispatching dispatch) array - _ -> JsonParsor Nothing (orElse (runJsonParsor p) (runJsonParsor q)) array + 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} + {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)) JsonLiteral []) instance JsonStr JsonParsor where - jsonText = primitiveParsor "string" $ \case + jsonText = (primitiveParsor "string" $ \case String t -> Just t - _ -> Nothing + _ -> Nothing) {jsonParsorText = Just id} -- | TsLiteral alternatives, dispatched by their string. jsonEnumWith indexOf table = orP [ dimap indexOf (const a) (only i >? fromString (Text.unpack literal)) @@ -959,6 +966,18 @@ instance JsonVal JsonParsor where 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 @@ -995,7 +1014,7 @@ 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 +objectParsor rejecting obj = JsonParsor dispatch parse Nothing Nothing where overlap = foldr ((<|>) . duplicateKey) Nothing (objParsorShapes obj) parse = \case diff --git a/distributors-json/test/Properties/Json.hs b/distributors-json/test/Properties/Json.hs index 2b7720b2..93d84ee0 100644 --- a/distributors-json/test/Properties/Json.hs +++ b/distributors-json/test/Properties/Json.hs @@ -827,6 +827,10 @@ jsonErrorSpec = describe "jsonParse errors" $ do "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)]) From ce67c001c016abf45b5a63e1c862af9b445be272 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sun, 8 Nov 2026 13:50:19 -0800 Subject: [PATCH 080/130] Inline Monoidal's product combinators & the printors' Applicative methods oneP, >*<, >*, *< & dimap2 are INLINE, as are ObjPrintor's & TupPrintor's <*>, *>, <* & liftA2, which defaulted to out-of-line class methods, so that a generic record's printor compiles to its properties' renderings, rather than being combined at runtime by Applicative workers. Json/aeson: deep encode 0.88x -> 0.84x; the others are unchanged. Co-Authored-By: Claude Opus 5.5 --- distributors-core/src/Data/Profunctor/Monoidal.hs | 5 +++++ distributors-json/src/Control/Lens/Grammar/Json.hs | 13 +++++++++++++ 2 files changed, 18 insertions(+) diff --git a/distributors-core/src/Data/Profunctor/Monoidal.hs b/distributors-core/src/Data/Profunctor/Monoidal.hs index 0ffb92de..a94b6d7f 100644 --- a/distributors-core/src/Data/Profunctor/Monoidal.hs +++ b/distributors-core/src/Data/Profunctor/Monoidal.hs @@ -67,10 +67,12 @@ 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; @@ -81,6 +83,7 @@ analagous to `*>`, extending it to `Monoidal`. -} (>*) :: 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; @@ -91,6 +94,7 @@ analagous to `<*`, extending it to `Monoidal`. -} (*<) :: 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 `>*<`, @@ -102,6 +106,7 @@ 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`. -} diff --git a/distributors-json/src/Control/Lens/Grammar/Json.hs b/distributors-json/src/Control/Lens/Grammar/Json.hs index 7cf2233c..c4d3b841 100644 --- a/distributors-json/src/Control/Lens/Grammar/Json.hs +++ b/distributors-json/src/Control/Lens/Grammar/Json.hs @@ -1713,8 +1713,14 @@ instance Applicative (TupPrintor val a) where (\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) #-} @@ -1830,7 +1836,14 @@ instance Applicative (ObjPrintor val a) where (\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 From 356f41cf194282b51874865c870c53be1238cb3a Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sun, 8 Nov 2026 13:53:39 -0800 Subject: [PATCH 081/130] Rename RegExam to TokenExam, & move token classes to Token TokenExam, the type, moves with TokenClass, its fixed point, TokenAlgebra & CategoryTest to Control.Lens.Grammar.Token, beside Tokenized, leaving Control.Lens.Grammar.RegEx with RegEx, whose RegExam constructor embeds a TokenExam of regular expressions, & keeps its name. foldTokenClass folds a TokenClass by an algebra of its TokenExams, so that each TokenAlgebra instance is one step of its fold, & RegEx's is foldTokenClass RegExam. Co-Authored-By: Claude Opus 5.5 --- distributors-grammar/CHANGELOG.md | 4 + .../src/Control/Lens/Grammar.hs | 2 +- .../src/Control/Lens/Grammar/RegEx.hs | 249 +----------------- .../src/Control/Lens/Grammar/Token.hs | 226 ++++++++++++++++ .../src/Data/Profunctor/Grammar.hs | 1 - .../src/Data/Profunctor/Grammar/Parsector.hs | 1 - 6 files changed, 244 insertions(+), 239 deletions(-) diff --git a/distributors-grammar/CHANGELOG.md b/distributors-grammar/CHANGELOG.md index e496f310..45455551 100644 --- a/distributors-grammar/CHANGELOG.md +++ b/distributors-grammar/CHANGELOG.md @@ -6,3 +6,7 @@ `Control.Lens.Grammar` & its `BackusNaur`, `Machine`, `RegEx`, `Symbol` & `Token` modules, `Control.Monad.Fail.Try`, `Data.Profunctor.Grammar` & `Data.Profunctor.Grammar.Parsector`. +- `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. diff --git a/distributors-grammar/src/Control/Lens/Grammar.hs b/distributors-grammar/src/Control/Lens/Grammar.hs index 8bcb6cbc..a579c1b0 100644 --- a/distributors-grammar/src/Control/Lens/Grammar.hs +++ b/distributors-grammar/src/Control/Lens/Grammar.hs @@ -634,7 +634,7 @@ instance Matching String RegBnf where makeNestedPrisms ''Bnf makeNestedPrisms ''RegEx -makeNestedPrisms ''RegExam +makeNestedPrisms ''TokenExam makeNestedPrisms ''CategoryTest makeNestedPrisms ''GeneralCategory makeNestedPrisms ''RegString diff --git a/distributors-grammar/src/Control/Lens/Grammar/RegEx.hs b/distributors-grammar/src/Control/Lens/Grammar/RegEx.hs index 3814eac6..c912700e 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/RegEx.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/RegEx.hs @@ -1,6 +1,6 @@ {- | Module : Control.Lens.Grammar.RegEx -Description : regular expressions & token classes +Description : regular expressions Copyright : (C) 2026 - Eitan Chatav License : BSD-style (see the file LICENSE) Maintainer : Eitan Chatav @@ -13,34 +13,18 @@ Regular expressions form a Kleene star algebra. See Kleene, -} module Control.Lens.Grammar.RegEx - ( -- * TokenAlgebra - TokenAlgebra (..) - -- * RegEx & TokenClass - , RegEx (..) - , TokenClass (..) - , RegExam (..) - , CategoryTest (..) + ( -- * RegEx + RegEx (..) ) where 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.Disjunctive 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 {- | The `RegEx`pression type forms the prototypical `KleeneStarAlgebra`. It is also a `TokenAlgebra` and `tokenClass` acts homomorphically on disjunction. @@ -54,88 +38,11 @@ data RegEx token | KleeneStar (RegEx token) | KleeneOpt (RegEx token) | KleenePlus (RegEx token) - | RegExam (RegExam token (RegEx token)) + | RegExam (TokenExam token (RegEx token)) -{- | Both `RegEx`pressions and t'TokenClass'es are algebras over the t`RegExam` endo-`Functor`. -t'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)) - -{- | 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`RegExam`. -t'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 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 - 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 >&< allP notAsIn cats) - Alternate exam1 exam2 -> tokenClass exam1 >|< tokenClass exam2 --instances 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 @@ -144,75 +51,20 @@ deriving stock instance 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 - => 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 (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 + 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 (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 + tokenClass = foldTokenClass RegExam instance Categorized token => Monoid (RegEx token) where mempty = SeqEmpty instance Categorized token => Semigroup (RegEx token) where @@ -224,7 +76,7 @@ instance Categorized token => Semigroup (RegEx token) where rex0 <> KleeneStar rex1 | rex0 == rex1 = plusK rex1 rex0 <> rex1 = Sequence rex0 rex1 instance Categorized token => DisjunctiveMonoid (RegEx token) where - falseP = RegExam failExam + falseP = RegExam (OneOf Set.empty) rex0 >|< rex1 | rex0 == rex1 = rex0 KleenePlus rex >|< SeqEmpty = starK rex SeqEmpty >|< KleenePlus rex = starK rex @@ -250,87 +102,6 @@ instance Categorized token => KleeneStarAlgebra (RegEx token) where plusK (RegExam exam) | isFailExam exam = falseP plusK SeqEmpty = mempty plusK rex = KleenePlus rex -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 - => DisjunctiveMonoid (RegExam token (TokenClass token)) where - falseP = failExam - 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) -instance Categorized token - => BooleanAlgebra (RegExam token (TokenClass token)) where - trueP = passExam - notP exam | isFailExam exam = passExam - notP exam | isPassExam exam = failExam - notP (Alternate (TokenClass x) (TokenClass y)) = notP x >&< notP y - 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 (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) -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 @@ -386,3 +157,9 @@ testNotOneOf 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 diff --git a/distributors-grammar/src/Control/Lens/Grammar/Token.hs b/distributors-grammar/src/Control/Lens/Grammar/Token.hs index a5c922a6..c6d42874 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/Token.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/Token.hs @@ -16,6 +16,12 @@ module Control.Lens.Grammar.Token -- * Categorized , Categorized (..) , GeneralCategory (..) + -- * TokenAlgebra + , TokenAlgebra (..) + , TokenClass (..) + , foldTokenClass + , TokenExam (..) + , CategoryTest (..) ) where import Control.Lens @@ -25,7 +31,12 @@ import Data.Bifunctor.Joker import Data.Char import Data.Foldable 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) @@ -162,3 +173,218 @@ instance (RandomGen g, Monad m, Categorized token, Random token) notOneOf xs = iterateUntil (`notElem` xs) anyToken asIn cat = iterateUntil ((== cat) . categorize) anyToken notAsIn cat = iterateUntil ((/= cat) . categorize) anyToken + +{- | 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) + | Alternate 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 + +{- | `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 + tokenClass = foldTokenClass $ \case + OneOf chars -> oneOf chars + NotOneOf chars (AndAsIn cat) -> + satisfy (notOneOf chars >&< asIn cat) + NotOneOf chars (AndNotAsIn cats) -> + satisfy (notOneOf chars >&< allP notAsIn cats) + Alternate p q -> p >|< q + +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 $ \case + OneOf xs -> \x -> Set.member x xs + NotOneOf xs (AndAsIn y) -> \x -> + Set.notMember x xs && categorize x == y + NotOneOf xs (AndNotAsIn ys) -> \x -> + Set.notMember x xs && Set.notMember (categorize x) ys + Alternate p q -> \x -> p x || q x +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 -> Gen.oneof [p, q] +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 -> do + b <- state random + if (b :: Bool) then p else q +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 | 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) +instance Categorized token + => BooleanAlgebra (TokenExam token (TokenClass token)) where + trueP = passExam + notP exam | isFailExam exam = passExam + notP exam | isPassExam exam = failExam + notP (Alternate (TokenClass x) (TokenClass y)) = notP x >&< notP y + 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 (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) +deriving stock instance + (Categorized token, Read token, Read alg, Read (Categorize token)) + => Read (TokenExam token alg) +deriving stock instance + (Categorized token, Show token, Show alg, Show (Categorize token)) + => Show (TokenExam token alg) +deriving stock instance Functor (TokenExam token) +deriving stock instance Foldable (TokenExam token) +deriving stock instance Traversable (TokenExam token) +deriving stock instance (Categorized token, Eq alg) => Eq (TokenExam token alg) +deriving stock instance (Categorized token, Ord alg) => Ord (TokenExam token alg) +deriving stock instance Categorized token => Eq (CategoryTest token) +deriving stock instance Categorized token => Ord (CategoryTest token) +deriving stock instance + (Categorized token, Read token, Read (Categorize token)) + => Read (CategoryTest token) +deriving stock instance + (Categorized token, Show token, Show (Categorize token)) + => Show (CategoryTest token) diff --git a/distributors-grammar/src/Data/Profunctor/Grammar.hs b/distributors-grammar/src/Data/Profunctor/Grammar.hs index bfd47625..d6e0315a 100644 --- a/distributors-grammar/src/Data/Profunctor/Grammar.hs +++ b/distributors-grammar/src/Data/Profunctor/Grammar.hs @@ -27,7 +27,6 @@ import Control.Lens import Control.Lens.Extras import Control.Lens.Grammar.BackusNaur import Control.Lens.Grammar.Machine -import Control.Lens.Grammar.RegEx import Control.Lens.Grammar.Symbol import Control.Lens.Grammar.Token import Control.Monad diff --git a/distributors-grammar/src/Data/Profunctor/Grammar/Parsector.hs b/distributors-grammar/src/Data/Profunctor/Grammar/Parsector.hs index e55ea627..2f6cf602 100644 --- a/distributors-grammar/src/Data/Profunctor/Grammar/Parsector.hs +++ b/distributors-grammar/src/Data/Profunctor/Grammar/Parsector.hs @@ -27,7 +27,6 @@ import Control.Category import Data.Function (fix) import Control.Lens import Control.Lens.Grammar.BackusNaur -import Control.Lens.Grammar.RegEx import Control.Lens.Grammar.Symbol import Control.Lens.Grammar.Token import Control.Lens.PartialIso From 0cfcc7ea5201aa283633d584fc93deb13aca6e11 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sun, 8 Nov 2026 13:56:12 -0800 Subject: [PATCH 082/130] Update Token.hs --- distributors-grammar/src/Control/Lens/Grammar/Token.hs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/distributors-grammar/src/Control/Lens/Grammar/Token.hs b/distributors-grammar/src/Control/Lens/Grammar/Token.hs index c6d42874..23282769 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/Token.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/Token.hs @@ -276,13 +276,13 @@ instance Categorized token => TokenAlgebra token (TokenExam token (TokenClass token)) where tokenClass (TokenClass exam) = exam instance Categorized token => TokenAlgebra token (token -> Bool) where - tokenClass = foldTokenClass $ \case - OneOf xs -> \x -> Set.member x xs - NotOneOf xs (AndAsIn y) -> \x -> + 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) -> \x -> + NotOneOf xs (AndNotAsIn ys) -> Set.notMember x xs && Set.notMember (categorize x) ys - Alternate p q -> \x -> p x || q x + Alternate p q -> p x || q x instance TokenAlgebra token (f token) => TokenAlgebra token (Joker f token token) where tokenClass = Joker . tokenClass From 8a11ccdd0e2015bd2703d3382a497ff6a4f9cc0f Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sun, 8 Nov 2026 15:44:51 -0800 Subject: [PATCH 083/130] Make RegEx's & TokenClass's monoids associative, by lists RegEx's Sequence & TokenExam's Alternate take lists of two or more items, none of them sequences, or alternatives, which <> & >|< normalize as functions of their flattened items, so that they're associative up to ==, as QuickCheck now tests, with the identity & Kleene laws. Runs of a repeated item are rewritten, b* B & B b* to b+ & so on, until none apply; alternatives of tokens are one TokenClass, & the empty word makes alternatives optional. Regular expressions print with fewer parentheses. Co-Authored-By: Claude Opus 5.5 --- distributors-grammar/CHANGELOG.md | 4 + .../src/Control/Lens/Grammar.hs | 30 ++-- .../src/Control/Lens/Grammar/BackusNaur.hs | 10 +- .../src/Control/Lens/Grammar/Machine.hs | 18 ++- .../src/Control/Lens/Grammar/RegEx.hs | 149 ++++++++++++++---- .../src/Control/Lens/Grammar/Token.hs | 65 ++++++-- .../test/Properties/Kleene.hs | 7 + 7 files changed, 216 insertions(+), 67 deletions(-) diff --git a/distributors-grammar/CHANGELOG.md b/distributors-grammar/CHANGELOG.md index 45455551..ab0f3541 100644 --- a/distributors-grammar/CHANGELOG.md +++ b/distributors-grammar/CHANGELOG.md @@ -10,3 +10,7 @@ `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 lists, 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/src/Control/Lens/Grammar.hs b/distributors-grammar/src/Control/Lens/Grammar.hs index a579c1b0..3dc39eaf 100644 --- a/distributors-grammar/src/Control/Lens/Grammar.hs +++ b/distributors-grammar/src/Control/Lens/Grammar.hs @@ -188,7 +188,7 @@ 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. @@ -455,7 +455,7 @@ diverge if the `CtxGrammar` they're run on is left-recursive. 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} @@ -497,7 +497,7 @@ with `Control.Lens.Grammar.regstringG`. 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"))]) 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 @@ -654,8 +654,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}*\} @@ -666,10 +666,20 @@ 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) + >~ several1 (sepWith "|") (seqG rex) seqG rex = rule "sequence" $ - chain Left _Sequence _SeqEmpty noSep (exprG rex) + iso itemsOf mconcat >~ manyP (exprG rex) + + alternativesOf = \case + RegExam (Alternate rexes) -> rexes + rex -> [rex] + + itemsOf = \case + SeqEmpty -> [] + Sequence rexes -> rexes + rex -> [rex] exprG rex = rule "expression" $ orP [ _KleeneOpt >? atomG rex *< terminal "?" @@ -835,12 +845,12 @@ 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}* -} diff --git a/distributors-grammar/src/Control/Lens/Grammar/BackusNaur.hs b/distributors-grammar/src/Control/Lens/Grammar/BackusNaur.hs index 7bde099f..5ea22b33 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/BackusNaur.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/BackusNaur.hs @@ -126,9 +126,11 @@ diffB prefix (Bnf start rules) = diff1B = memo2 $ \x -> \case SeqEmpty -> falseP NonTerminal nameY -> anyP (diff1B x) (rulesNamed nameY rules) - Sequence y1 y2 -> + Sequence [] -> falseP + Sequence (y1 : ys) -> if δ (Bnf y1 rules) then y1'y2 >|< y1y2' else y1'y2 where + y2 = mconcat ys y1'y2 = diff1B x y1 <> y2 y1y2' = y1 <> diff1B x y2 KleeneStar y -> diff1B x y <> starK y @@ -142,7 +144,7 @@ diffB prefix (Bnf start rules) = RegExam (NotOneOf chars (AndNotAsIn cats)) -> if elem x chars || elem (categorize x) cats then falseP else mempty - RegExam (Alternate y1 y2) -> diff1B x y1 >|< diff1B x y2 + RegExam (Alternate ys) -> anyP (diff1B x) ys -- | Does a pattern match the empty word? δ :: (Categorized token, HasTrie token) @@ -153,8 +155,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 ys -> all ν ys + RegExam (Alternate ys) -> any ν ys NonTerminal nameY -> any ν (rulesNamed nameY rules) _ -> False diff --git a/distributors-grammar/src/Control/Lens/Grammar/Machine.hs b/distributors-grammar/src/Control/Lens/Grammar/Machine.hs index 45ee2ebd..c2c8d125 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/Machine.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/Machine.hs @@ -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 xs -> all (rexNullable nm) xs KleeneStar _ -> True KleeneOpt _ -> True KleenePlus x -> rexNullable nm x - RegExam (Alternate x y) -> rexNullable nm x || rexNullable nm y + RegExam (Alternate xs) -> any (rexNullable nm) xs 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 [] -> thompson SeqEmpty nextId dests + Sequence [rex0] -> thompson rex0 nextId dests + Sequence (rex0 : rexes) -> let - (firsts1, states1, nextId1, bypass1) = thompson rex1 nextId dests + (firsts1, states1, nextId1, bypass1) = + thompson (Sequence rexes) 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 []) -> (IntSet.empty, [], nextId, False) + RegExam (Alternate [rex0]) -> thompson rex0 nextId dests + RegExam (Alternate (rex0 : rexes)) -> let - (firsts1, states1, nextId1, bypass1) = thompson rex1 nextId dests + (firsts1, states1, nextId1, bypass1) = + thompson (RegExam (Alternate rexes)) nextId dests (firsts0, states0, nextId0, bypass0) = thompson rex0 nextId1 dests in ( firsts0 <> firsts1 diff --git a/distributors-grammar/src/Control/Lens/Grammar/RegEx.hs b/distributors-grammar/src/Control/Lens/Grammar/RegEx.hs index c912700e..a2ed4587 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/RegEx.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/RegEx.hs @@ -20,6 +20,7 @@ module Control.Lens.Grammar.RegEx 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 @@ -33,7 +34,8 @@ It is also a `TokenAlgebra` and `tokenClass` acts homomorphically on disjunction -} data RegEx token = SeqEmpty - | Sequence (RegEx token) (RegEx token) + -- | Two or more items, none of them sequences or empty. + | Sequence [RegEx token] | NonTerminal String | KleeneStar (RegEx token) | KleeneOpt (RegEx token) @@ -67,34 +69,19 @@ 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 - SeqEmpty <> rex = rex - rex <> SeqEmpty = rex - RegExam exam <> _ | isFailExam exam = falseP - _ <> RegExam exam | isFailExam exam = falseP - KleeneStar rex0 <> rex1 | rex0 == rex1 = plusK rex0 - rex0 <> KleeneStar rex1 | rex0 == rex1 = plusK rex1 - rex0 <> rex1 = Sequence rex0 rex1 + 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 | 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) + 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 @@ -107,8 +94,8 @@ instance (Categorized token, HasTrie token) data (RegEx token :->: b) = RegExTrie { seqEmptyTrie :: b , nonTerminalTrie :: String :->: b - , sequenceTrie :: (RegEx token, RegEx token) :->: b - , alternateTrie :: (RegEx token, RegEx token) :->: b + , sequenceTrie :: [RegEx token] :->: b + , alternateTrie :: [RegEx token] :->: b , kleeneStarTrie :: RegEx token :->: b , kleeneOptTrie :: RegEx token :->: b , kleenePlusTrie :: RegEx token :->: b @@ -118,8 +105,8 @@ instance (Categorized token, HasTrie token) trie f = RegExTrie { seqEmptyTrie = f mempty , nonTerminalTrie = trie (f . nonTerminal) - , sequenceTrie = trie (f . uncurry (<>)) - , alternateTrie = trie (f . uncurry (>|<)) + , sequenceTrie = trie (f . mconcat) + , alternateTrie = trie (f . foldr (>|<) falseP) , kleeneStarTrie = trie (f . starK) , kleeneOptTrie = trie (f . optK) , kleenePlusTrie = trie (f . plusK) @@ -129,7 +116,7 @@ instance (Categorized token, HasTrie token) untrie rex = \case SeqEmpty -> seqEmptyTrie rex NonTerminal name -> untrie (nonTerminalTrie rex) name - Sequence x1 x2 -> untrie (sequenceTrie rex) (x1,x2) + Sequence xs -> untrie (sequenceTrie rex) xs KleeneStar x -> untrie (kleeneStarTrie rex) x KleenePlus x -> untrie (kleenePlusTrie rex) x KleeneOpt x -> untrie (kleeneOptTrie rex) x @@ -139,12 +126,12 @@ instance (Categorized token, HasTrie token) 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) + RegExam (Alternate xs) -> untrie (alternateTrie rex) xs 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' Sequence <$> enumerate (sequenceTrie rex) + , first' (RegExam . Alternate) <$> enumerate (alternateTrie rex) , first' KleeneStar <$> enumerate (kleeneStarTrie rex) , first' KleeneOpt <$> enumerate (kleeneOptTrie rex) , first' KleenePlus <$> enumerate (kleenePlusTrie rex) @@ -163,3 +150,105 @@ 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 rexes -> 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 + rexes' -> Sequence 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 rexes) -> 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 + rexes' -> RegExam (Alternate 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/distributors-grammar/src/Control/Lens/Grammar/Token.hs b/distributors-grammar/src/Control/Lens/Grammar/Token.hs index 23282769..6142e9a6 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/Token.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/Token.hs @@ -30,6 +30,7 @@ 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 @@ -181,7 +182,10 @@ of an algebra, whose fixed point is t'TokenClass'. Both t'TokenClass'es & data TokenExam token alg = OneOf (Set token) | NotOneOf (Set token) (CategoryTest token) - | Alternate alg alg + {- | Two or more alternatives, none of them alternatives, + in the order they're written. + -} + | Alternate [alg] failExam :: TokenExam token alg failExam = OneOf Set.empty @@ -197,6 +201,39 @@ 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 xs -> [x | TokenClass x <- xs] + 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 + exams' -> Alternate (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. -} @@ -251,7 +288,7 @@ class Tokenized token p => TokenAlgebra token p where satisfy (notOneOf chars >&< asIn cat) NotOneOf chars (AndNotAsIn cats) -> satisfy (notOneOf chars >&< allP notAsIn cats) - Alternate p q -> p >|< q + Alternate ps -> foldr1 (>|<) ps deriving stock instance Generic (TokenExam token alg) deriving stock instance Generic1 (TokenExam token) @@ -282,7 +319,7 @@ instance Categorized token => TokenAlgebra token (token -> Bool) where Set.notMember x xs && categorize x == y NotOneOf xs (AndNotAsIn ys) -> Set.notMember x xs && Set.notMember (categorize x) ys - Alternate p q -> p x || q x + Alternate ps -> any ($ x) ps instance TokenAlgebra token (f token) => TokenAlgebra token (Joker f token token) where tokenClass = Joker . tokenClass @@ -295,7 +332,7 @@ instance (Categorized token, Arbitrary token) => TokenAlgebra token (Gen token) (\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 -> Gen.oneof [p, q] + Alternate ps -> Gen.oneof ps instance (RandomGen g, Monad m, Categorized token, Random token) => TokenAlgebra token (StateT g m token) where tokenClass = foldTokenClass $ \case @@ -304,9 +341,9 @@ instance (RandomGen g, Monad m, Categorized token, Random token) 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 -> do - b <- state random - if (b :: Bool) then p else q + Alternate ps -> do + i <- state (randomR (0, length ps - 1)) + ps !! i instance Categorized token => Tokenized token (TokenExam token alg) where anyToken = passExam token a = OneOf (Set.singleton a) @@ -320,19 +357,13 @@ instance Categorized token => Tokenized token (TokenExam token alg) where instance Categorized token => DisjunctiveMonoid (TokenExam token (TokenClass token)) where falseP = failExam - 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) + 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 (TokenClass x) (TokenClass y)) = notP x >&< notP y + notP (Alternate xs) = foldr1 (>&<) [notP x | TokenClass x <- xs] notP (OneOf xs) = notOneOf xs notP (NotOneOf xs (AndAsIn y)) = oneOf xs >|< notAsIn y notP (NotOneOf xs (AndNotAsIn ys)) = oneOf xs >|< anyP asIn ys @@ -341,8 +372,8 @@ instance Categorized token 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) + x >&< Alternate ys = foldr1 (>|<) [x >&< y | TokenClass y <- ys] + Alternate xs >&< z = foldr1 (>|<) [x >&< z | TokenClass x <- xs] 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)) diff --git a/distributors-grammar/test/Properties/Kleene.hs b/distributors-grammar/test/Properties/Kleene.hs index 4e43bac6..1f7d055d 100644 --- a/distributors-grammar/test/Properties/Kleene.hs +++ b/distributors-grammar/test/Properties/Kleene.hs @@ -93,6 +93,13 @@ kleeneProperties = do (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 "TokenAlgebra" $ do it "falseP = tokenClass falseP" $ (falseP :: RegEx Char) `shouldBe` tokenClass falseP From 685c1f8bb49b7388e22b8409934d364a1d95f9b3 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sun, 8 Nov 2026 15:52:24 -0800 Subject: [PATCH 084/130] Encode two or more items in Sequence's & Alternate's types Sequence & Alternate take two items & a list of more, rather than a list, so that empty & single sequences & alternatives are unrepresentable, & folding, indexing & choosing among them is total. Co-Authored-By: Claude Opus 5.5 --- distributors-grammar/CHANGELOG.md | 3 +- .../src/Control/Lens/Grammar.hs | 8 +++--- .../src/Control/Lens/Grammar/BackusNaur.hs | 11 ++++---- .../src/Control/Lens/Grammar/Machine.hs | 24 ++++++++-------- .../src/Control/Lens/Grammar/RegEx.hs | 18 ++++++------ .../src/Control/Lens/Grammar/Token.hs | 28 +++++++++++-------- 6 files changed, 48 insertions(+), 44 deletions(-) diff --git a/distributors-grammar/CHANGELOG.md b/distributors-grammar/CHANGELOG.md index ab0f3541..311b2300 100644 --- a/distributors-grammar/CHANGELOG.md +++ b/distributors-grammar/CHANGELOG.md @@ -10,7 +10,8 @@ `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 lists, normalized, +- `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/src/Control/Lens/Grammar.hs b/distributors-grammar/src/Control/Lens/Grammar.hs index 3dc39eaf..11221686 100644 --- a/distributors-grammar/src/Control/Lens/Grammar.hs +++ b/distributors-grammar/src/Control/Lens/Grammar.hs @@ -455,7 +455,7 @@ diverge if the `CtxGrammar` they're run on is left-recursive. 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} @@ -497,7 +497,7 @@ with `Control.Lens.Grammar.regstringG`. 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"))) []) 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 @@ -673,12 +673,12 @@ regexGrammar = _RegString >~ ruleRec "regex" altG iso itemsOf mconcat >~ manyP (exprG rex) alternativesOf = \case - RegExam (Alternate rexes) -> rexes + RegExam (Alternate rex0 rex1 rexes) -> rex0 : rex1 : rexes rex -> [rex] itemsOf = \case SeqEmpty -> [] - Sequence rexes -> rexes + Sequence rex0 rex1 rexes -> rex0 : rex1 : rexes rex -> [rex] exprG rex = rule "expression" $ orP diff --git a/distributors-grammar/src/Control/Lens/Grammar/BackusNaur.hs b/distributors-grammar/src/Control/Lens/Grammar/BackusNaur.hs index 5ea22b33..f1503a09 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/BackusNaur.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/BackusNaur.hs @@ -126,11 +126,10 @@ diffB prefix (Bnf start rules) = diff1B = memo2 $ \x -> \case SeqEmpty -> falseP NonTerminal nameY -> anyP (diff1B x) (rulesNamed nameY rules) - Sequence [] -> falseP - Sequence (y1 : ys) -> + Sequence y1 y ys -> if δ (Bnf y1 rules) then y1'y2 >|< y1y2' else y1'y2 where - y2 = mconcat ys + y2 = mconcat (y : ys) y1'y2 = diff1B x y1 <> y2 y1y2' = y1 <> diff1B x y2 KleeneStar y -> diff1B x y <> starK y @@ -144,7 +143,7 @@ diffB prefix (Bnf start rules) = RegExam (NotOneOf chars (AndNotAsIn cats)) -> if elem x chars || elem (categorize x) cats then falseP else mempty - RegExam (Alternate ys) -> anyP (diff1B x) ys + RegExam (Alternate y1 y2 ys) -> anyP (diff1B x) (y1 : y2 : ys) -- | Does a pattern match the empty word? δ :: (Categorized token, HasTrie token) @@ -155,8 +154,8 @@ diffB prefix (Bnf start rules) = KleeneStar _ -> True KleeneOpt _ -> True KleenePlus y -> ν y - Sequence ys -> all ν ys - RegExam (Alternate ys) -> any ν ys + Sequence y1 y2 ys -> all ν (y1 : y2 : ys) + RegExam (Alternate y1 y2 ys) -> any ν (y1 : y2 : ys) NonTerminal nameY -> any ν (rulesNamed nameY rules) _ -> False diff --git a/distributors-grammar/src/Control/Lens/Grammar/Machine.hs b/distributors-grammar/src/Control/Lens/Grammar/Machine.hs index c2c8d125..d2f702bb 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/Machine.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/Machine.hs @@ -120,11 +120,11 @@ transducer (Bnf start rules) = Transducer rexNullable nm = \case SeqEmpty -> True NonTerminal n -> Set.member n nm - Sequence xs -> all (rexNullable nm) xs + Sequence x y zs -> all (rexNullable nm) (x : y : zs) KleeneStar _ -> True KleeneOpt _ -> True KleenePlus x -> rexNullable nm x - RegExam (Alternate xs) -> any (rexNullable nm) xs + RegExam (Alternate x y zs) -> any (rexNullable nm) (x : y : zs) RegExam (OneOf _) -> False RegExam (NotOneOf _ _) -> False @@ -180,12 +180,12 @@ transducer (Bnf start rules) = Transducer , nextId + 1 , Set.member name nullSet ) - Sequence [] -> thompson SeqEmpty nextId dests - Sequence [rex0] -> thompson rex0 nextId dests - Sequence (rex0 : rexes) -> + Sequence rex0 rex1 rexes -> let - (firsts1, states1, nextId1, bypass1) = - thompson (Sequence rexes) 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 @@ -223,12 +223,12 @@ transducer (Bnf start rules) = Transducer , nextId + 1 , False ) - RegExam (Alternate []) -> (IntSet.empty, [], nextId, False) - RegExam (Alternate [rex0]) -> thompson rex0 nextId dests - RegExam (Alternate (rex0 : rexes)) -> + RegExam (Alternate rex0 rex1 rexes) -> let - (firsts1, states1, nextId1, bypass1) = - thompson (RegExam (Alternate rexes)) 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 diff --git a/distributors-grammar/src/Control/Lens/Grammar/RegEx.hs b/distributors-grammar/src/Control/Lens/Grammar/RegEx.hs index a2ed4587..1246cd55 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/RegEx.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/RegEx.hs @@ -35,7 +35,7 @@ It is also a `TokenAlgebra` and `tokenClass` acts homomorphically on disjunction data RegEx token = SeqEmpty -- | Two or more items, none of them sequences or empty. - | Sequence [RegEx token] + | Sequence (RegEx token) (RegEx token) [RegEx token] | NonTerminal String | KleeneStar (RegEx token) | KleeneOpt (RegEx token) @@ -116,7 +116,7 @@ instance (Categorized token, HasTrie token) untrie rex = \case SeqEmpty -> seqEmptyTrie rex NonTerminal name -> untrie (nonTerminalTrie rex) name - Sequence xs -> untrie (sequenceTrie rex) xs + 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 @@ -126,12 +126,12 @@ instance (Categorized token, HasTrie token) RegExam (NotOneOf chars (AndNotAsIn cats)) -> untrie (notOneOfTrie rex) (Set.toList chars, Right (Set.toList (Set.map fromEnum cats))) - RegExam (Alternate xs) -> untrie (alternateTrie rex) xs + RegExam (Alternate x y zs) -> untrie (alternateTrie rex) (x : y : zs) enumerate rex = mconcat [ [(SeqEmpty, seqEmptyTrie rex)] , first' NonTerminal <$> enumerate (nonTerminalTrie rex) - , first' Sequence <$> enumerate (sequenceTrie rex) - , first' (RegExam . Alternate) <$> enumerate (alternateTrie 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) @@ -155,7 +155,7 @@ isFailExam = \case items :: RegEx token -> [RegEx token] items = \case SeqEmpty -> [] - Sequence rexes -> rexes + Sequence rex0 rex1 rexes -> rex0 : rex1 : rexes rex -> [rex] {- | Items, normalized: any which fails fails, & runs of a repeated item, @@ -173,7 +173,7 @@ sequenced rexes | otherwise = case rewrite rexes of [] -> SeqEmpty [rex] -> rex - rexes' -> Sequence rexes' + rex0 : rex1 : rexes' -> Sequence rex0 rex1 rexes' where isFail = \case RegExam exam -> isFailExam exam @@ -219,7 +219,7 @@ sequenced rexes alternatives :: RegEx token -> [RegEx token] alternatives = \case RegExam (OneOf tokens') | Set.null tokens' -> [] - RegExam (Alternate rexes) -> rexes + RegExam (Alternate rex0 rex1 rexes) -> rex0 : rex1 : rexes KleeneOpt rex -> alternatives rex <> [SeqEmpty] KleeneStar rex -> [KleenePlus rex, SeqEmpty] rex -> [rex] @@ -235,7 +235,7 @@ alternated rexes = case nub (unionTokens [rex | rex <- rexes, rex /= SeqEmpty]) of [] -> falseP [rex] -> rex - rexes' -> RegExam (Alternate rexes') + rex0 : rex1 : rexes' -> RegExam (Alternate rex0 rex1 rexes') where unionTokens xs = case [cls | x <- xs, Just cls <- [tokenOf x]] of [] -> xs diff --git a/distributors-grammar/src/Control/Lens/Grammar/Token.hs b/distributors-grammar/src/Control/Lens/Grammar/Token.hs index 6142e9a6..694606fb 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/Token.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/Token.hs @@ -185,7 +185,7 @@ data TokenExam token alg {- | Two or more alternatives, none of them alternatives, in the order they're written. -} - | Alternate [alg] + | Alternate alg alg [alg] failExam :: TokenExam token alg failExam = OneOf Set.empty @@ -205,7 +205,7 @@ isPassExam _ = False examAlternatives :: TokenExam token (TokenClass token) -> [TokenExam token (TokenClass token)] examAlternatives = \case - Alternate xs -> [x | TokenClass x <- xs] + Alternate x y zs -> [exam | TokenClass exam <- x : y : zs] exam -> [exam] {- | Alternatives, normalized: any which passes every token passes, @@ -221,7 +221,8 @@ alternatives exams | otherwise = case nub (unionOneOfs (filter (not . isFailExam) exams)) of [] -> failExam [exam] -> exam - exams' -> Alternate (map TokenClass exams') + exam0 : exam1 : exams' -> + Alternate (TokenClass exam0) (TokenClass exam1) (map TokenClass exams') where unionOneOfs xs = case [tokens' | OneOf tokens' <- xs] of [] -> xs @@ -288,7 +289,7 @@ class Tokenized token p => TokenAlgebra token p where satisfy (notOneOf chars >&< asIn cat) NotOneOf chars (AndNotAsIn cats) -> satisfy (notOneOf chars >&< allP notAsIn cats) - Alternate ps -> foldr1 (>|<) ps + Alternate p q ps -> foldr1 (>|<) (p : q : ps) deriving stock instance Generic (TokenExam token alg) deriving stock instance Generic1 (TokenExam token) @@ -319,7 +320,7 @@ instance Categorized token => TokenAlgebra token (token -> Bool) where Set.notMember x xs && categorize x == y NotOneOf xs (AndNotAsIn ys) -> Set.notMember x xs && Set.notMember (categorize x) ys - Alternate ps -> any ($ x) ps + Alternate p q ps -> any ($ x) (p : q : ps) instance TokenAlgebra token (f token) => TokenAlgebra token (Joker f token token) where tokenClass = Joker . tokenClass @@ -332,7 +333,7 @@ instance (Categorized token, Arbitrary token) => TokenAlgebra token (Gen token) (\x -> x `notElem` xs && categorize x == cat) NotOneOf xs (AndNotAsIn cats) -> arbitrary `Gen.suchThat` (\x -> x `notElem` xs && categorize x `notElem` cats) - Alternate ps -> Gen.oneof ps + 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 @@ -341,9 +342,9 @@ instance (RandomGen g, Monad m, Categorized token, Random token) iterateUntil (\x -> x `notElem` xs && categorize x == cat) anyToken NotOneOf xs (AndNotAsIn cats) -> iterateUntil (\x -> x `notElem` xs && categorize x `notElem` cats) anyToken - Alternate ps -> do - i <- state (randomR (0, length ps - 1)) - ps !! i + 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) @@ -363,7 +364,8 @@ instance Categorized token trueP = passExam notP exam | isFailExam exam = passExam notP exam | isPassExam exam = failExam - notP (Alternate xs) = foldr1 (>&<) [notP x | TokenClass x <- xs] + 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 @@ -372,8 +374,10 @@ instance Categorized token exam >&< _ | isFailExam exam = failExam x >&< exam | isPassExam exam = x exam >&< z | isPassExam exam = z - x >&< Alternate ys = foldr1 (>|<) [x >&< y | TokenClass y <- ys] - Alternate xs >&< z = foldr1 (>|<) [x >&< z | TokenClass x <- xs] + 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)) From 1e89f18fc1cd67575856501aeb5b002021f0ace6 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Sun, 8 Nov 2026 18:49:38 -0800 Subject: [PATCH 085/130] Split Comonocle into its own module & merge Separator into Distributor Comonocles & their combinators move from Control.Lens.Monocle to Control.Lens.Comonocle, & Data.Profunctor.Separator's separators & operator expressions merge into Data.Profunctor.Distributor, which they build on. Co-Authored-By: Claude Opus 5.5 --- distributors-core/CHANGELOG.md | 6 +- distributors-core/distributors.cabal | 2 +- distributors-core/src/Control/Lens/Bifocal.hs | 1 - .../src/Control/Lens/Comonocle.hs | 261 ++++++++++++++++++ distributors-core/src/Control/Lens/Monocle.hs | 241 ---------------- .../src/Data/Profunctor/Distributor.hs | 221 +++++++++++++++ .../src/Data/Profunctor/Separator.hs | 238 ---------------- .../test/Properties/Homogeneous.hs | 2 +- .../src/Control/Lens/Grammar.hs | 2 - .../src/Control/Lens/Grammar/Symbol.hs | 2 +- .../src/Control/Lens/Grammar/Json.hs | 4 +- 11 files changed, 492 insertions(+), 488 deletions(-) create mode 100644 distributors-core/src/Control/Lens/Comonocle.hs delete mode 100644 distributors-core/src/Data/Profunctor/Separator.hs diff --git a/distributors-core/CHANGELOG.md b/distributors-core/CHANGELOG.md index 4e4cd664..c02e546d 100644 --- a/distributors-core/CHANGELOG.md +++ b/distributors-core/CHANGELOG.md @@ -7,7 +7,7 @@ - `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.Monocle`, dual to `Monocle`s by sums: +- `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`. @@ -28,6 +28,10 @@ ### Breaking Changes +- `Comonocle`s & their combinators move from `Control.Lens.Monocle` to + their own module, `Control.Lens.Comonocle`. +- `Data.Profunctor.Separator` merges into `Data.Profunctor.Distributor`: + `SepBy`, `several`, `chain`, `intercalateP`, `withOperators` & so on. - 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` diff --git a/distributors-core/distributors.cabal b/distributors-core/distributors.cabal index d14e5fb0..6f25002e 100644 --- a/distributors-core/distributors.cabal +++ b/distributors-core/distributors.cabal @@ -29,6 +29,7 @@ source-repository head library exposed-modules: Control.Lens.Bifocal + Control.Lens.Comonocle Control.Lens.Diopter Control.Lens.Grate Control.Lens.Internal.Distributor.NestedPrismTH @@ -42,7 +43,6 @@ library Data.Profunctor.Monadic Data.Profunctor.Monoidal Data.Profunctor.Monoidal.Cocartesian - Data.Profunctor.Separator Data.Traversable.Homogeneous other-modules: Paths_distributors diff --git a/distributors-core/src/Control/Lens/Bifocal.hs b/distributors-core/src/Control/Lens/Bifocal.hs index cc4ee6de..1c33cd6f 100644 --- a/distributors-core/src/Control/Lens/Bifocal.hs +++ b/distributors-core/src/Control/Lens/Bifocal.hs @@ -42,7 +42,6 @@ import Data.Profunctor import Data.Profunctor.Distributor import Data.Profunctor.Monoidal.Cocartesian import Data.Profunctor.Filtrator -import Data.Profunctor.Separator import Witherable {- | `Bifocal`s are bidirectional parser optics. diff --git a/distributors-core/src/Control/Lens/Comonocle.hs b/distributors-core/src/Control/Lens/Comonocle.hs new file mode 100644 index 00000000..aced9638 --- /dev/null +++ b/distributors-core/src/Control/Lens/Comonocle.hs @@ -0,0 +1,261 @@ +{- | +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 + -- * Combinators + , comonocle + , withComonocle + , cloneComonocle + , mapComonocle + , altComonocle + , crossComonocle + , indexComonocle + , countComonocle + , toEnumComonocle + , succComonocle + , predComonocle + , enumerateComonocle + , zipComonocle + , zipWithComonocle + , _Enumerable + , _BoundedEnum + -- * Comonocular + , Comonocular (..), runComonocular + ) where + +import Control.Applicative (Alternative) +import Control.Lens hiding (Traversing) +import Control.Lens.Internal.Profunctor +import Data.Functor.Compose +import Data.Profunctor.Monoidal.Cocartesian +import Data.Traversable.Homogeneous +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. + +Every `Control.Lens.Iso.Iso` is a `Comonocle`, +& every `Comonocle` is 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. +-} +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`. -} +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 + +{- | 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 (crossComonocle _Enumerable id) (\(a, c) -> (a + c, show c)) (Identity 1, 2) +(Identity 3,"2") +-} +crossComonocle + :: AComonocle s t a b + -> AComonocle u v c d + -> Comonocle (s,u) (t,v) (a,c) (b,d) +crossComonocle x y = + withComonocle x $ \e f -> + withComonocle y $ \g h -> + comonocle $ Comonocular + (\(s,u) -> Compose (fmap (\a -> fmap (a,) (g u)) (e s))) + (\(Compose bds) -> (f (fmap (fst . extractEnumerable) bds), h (fmap snd (extractEnumerable bds)))) + +{- | 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 (\s -> let as = split s in (fromEnumerable as, extractEnumerable as)) + (\s b -> merge (b <$ split s)) + +{- | Zip two sources of `AComonocle`, when they hold the same copy, +dual to `Control.Lens.Grate.cotraverseOf`, which zips every `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 () :: Indexing () ()) :: Indexing (f ()) (f ()) of + Indexing count _ _ -> count + +{- | The copy of `AComonocle` at an index, holding a focus, if there is one, +like `toEnum`, & inverse to `indexComonocle`. + +>>> toEnumComonocle _BoundedEnum () 2 :: Maybe Ordering +Just GT +>>> toEnumComonocle _BoundedEnum () 3 :: Maybe Ordering +Nothing +-} +toEnumComonocle :: AComonocle s t a b -> b -> Natural -> Maybe t +toEnumComonocle mon b copy = withComonocle mon $ \_ merge -> merge <$> toEnumerable b copy + +{- | The next copy of `AComonocle`, holding the same focus, +if there is one, like `succ`. + +>>> succComonocle _BoundedEnum EQ +Just GT +>>> succComonocle _BoundedEnum GT +Nothing +-} +succComonocle :: AComonocle s s a a -> s -> Maybe s +succComonocle mon s = withComonocle mon $ \split merge -> merge <$> succEnumerable (split s) + +{- | The previous copy of `AComonocle`, holding the same focus, +if there is one, like `pred`. + +>>> predComonocle _BoundedEnum EQ +Just LT +>>> predComonocle _BoundedEnum LT +Nothing +-} +predComonocle :: AComonocle s s a a -> s -> Maybe s +predComonocle mon s = withComonocle mon $ \split merge -> merge <$> predEnumerable (split s) + +{- | 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 `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/Monocle.hs b/distributors-core/src/Control/Lens/Monocle.hs index fa1fda4d..95166575 100644 --- a/distributors-core/src/Control/Lens/Monocle.hs +++ b/distributors-core/src/Control/Lens/Monocle.hs @@ -26,40 +26,12 @@ module Control.Lens.Monocle , forevered -- * Monocular , Monocular (..), runMonocular - -- * Comonocle - , Comonocle - , AComonocle - , comonocle - , withComonocle - , cloneComonocle - , mapComonocle - , altComonocle - , crossComonocle - , indexComonocle - , countComonocle - , toEnumComonocle - , succComonocle - , predComonocle - , enumerateComonocle - , zipComonocle - , zipWithComonocle - , _Enumerable - , _BoundedEnum - -- * Comonocular - , Comonocular (..), runComonocular ) where -import Control.Applicative (Alternative) import Control.Lens hiding (Traversing) import Control.Lens.Internal.Profunctor import Data.Distributive -import Data.Functor.Compose import Data.Profunctor.Monoidal -import Data.Profunctor.Monoidal.Cocartesian -import Data.Traversable.Homogeneous -import Data.Void (Void, absurd) -import GHC.Generics (Par1 (..), V1, (:+:) (..), (:*:) (..)) -import Numeric.Natural (Natural) -- $setup -- >>> import Control.Lens @@ -151,216 +123,3 @@ instance Applicative (Monocular a b s) where {- | 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 - -{- | `Comonocle`s are an optic dual to `Monocle`s, by sums, -which focus on the one copy that an `Enumerable` sum holds. - -Every `Control.Lens.Iso.Iso` is a `Comonocle`, -& every `Comonocle` is 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. --} -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`. -} -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 - -{- | 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 (crossComonocle _Enumerable id) (\(a, c) -> (a + c, show c)) (Identity 1, 2) -(Identity 3,"2") --} -crossComonocle - :: AComonocle s t a b - -> AComonocle u v c d - -> Comonocle (s,u) (t,v) (a,c) (b,d) -crossComonocle x y = - withComonocle x $ \e f -> - withComonocle y $ \g h -> - comonocle $ Comonocular - (\(s,u) -> Compose (fmap (\a -> fmap (a,) (g u)) (e s))) - (\(Compose bds) -> (f (fmap (fst . extractEnumerable) bds), h (fmap snd (extractEnumerable bds)))) - -{- | 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 (\s -> let as = split s in (fromEnumerable as, extractEnumerable as)) - (\s b -> merge (b <$ split s)) - -{- | Zip two sources of `AComonocle`, when they hold the same copy, -dual to `Control.Lens.Grate.cotraverseOf`, which zips every `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 () :: Indexing () ()) :: Indexing (f ()) (f ()) of - Indexing count _ _ -> count - -{- | The copy of `AComonocle` at an index, holding a focus, if there is one, -like `toEnum`, & inverse to `indexComonocle`. - ->>> toEnumComonocle _BoundedEnum () 2 :: Maybe Ordering -Just GT ->>> toEnumComonocle _BoundedEnum () 3 :: Maybe Ordering -Nothing --} -toEnumComonocle :: AComonocle s t a b -> b -> Natural -> Maybe t -toEnumComonocle mon b copy = withComonocle mon $ \_ merge -> merge <$> toEnumerable b copy - -{- | The next copy of `AComonocle`, holding the same focus, -if there is one, like `succ`. - ->>> succComonocle _BoundedEnum EQ -Just GT ->>> succComonocle _BoundedEnum GT -Nothing --} -succComonocle :: AComonocle s s a a -> s -> Maybe s -succComonocle mon s = withComonocle mon $ \split merge -> merge <$> succEnumerable (split s) - -{- | The previous copy of `AComonocle`, holding the same focus, -if there is one, like `pred`. - ->>> predComonocle _BoundedEnum EQ -Just LT ->>> predComonocle _BoundedEnum LT -Nothing --} -predComonocle :: AComonocle s s a a -> s -> Maybe s -predComonocle mon s = withComonocle mon $ \split merge -> merge <$> predEnumerable (split s) - -{- | 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 `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/Data/Profunctor/Distributor.hs b/distributors-core/src/Data/Profunctor/Distributor.hs index 2a5c1e70..14c22998 100644 --- a/distributors-core/src/Data/Profunctor/Distributor.hs +++ b/distributors-core/src/Data/Profunctor/Distributor.hs @@ -13,6 +13,20 @@ module Data.Profunctor.Distributor Distributor (..) -- * Alternator , Alternator (..) + -- * SepBy + , SepBy (..) + , sepBy + , noSep + -- * SepBy Combinators + , several + , several1 + , chain + , chain1 + , intercalateP + -- * Operator Expressions + , Operator (..) + , Assoc (..) + , withOperators ) where import Control.Applicative hiding (WrappedArrow) @@ -35,6 +49,7 @@ import Data.Profunctor.Monad import Data.Profunctor.Monoidal import Data.Profunctor.Yoneda import Data.Profunctor.Monoidal.Cocartesian +import GHC.Exts (IsList (..)) -- Distributor -- @@ -154,3 +169,209 @@ instance Alternative f => Alternator (Joker f) where someP (Joker x) = Joker (some x) optionP def (Joker x) = Joker (x <|> withPrism def (\f _ -> pure (f ()))) + +-- Separators -- + +{- | 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 t'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 t'SepBy' smart constructor for no separator, +beginning or ending delimiters. -} +noSep :: Applicative p => SepBy (p ()) +noSep = sepBy (pure ()) + +{- | +> 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 . swapped >~ + 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 t'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` + -> 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`, 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 an 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 (partialIso fwd bwd) >? manyP (tagSepP (snd <$> ops)) >*< inner + where + fns = [patternFns pat | (pat, _) <- ops] + fwd x = orP + [ (\y -> (i,y)) <$> f x | (i, (f,_)) <- zip [0 :: Int ..] fns ] + bwd (i,y) = case drop i fns of + (_,g):_ -> Just (g y) + [] -> Nothing + + withPostP ops inner = + difoldl (partialIso fwd bwd) >? inner >*< manyP (tagSepP (snd <$> ops)) + where + fns = [patternFns pat | (pat, _) <- ops] + fwd x = orP + [ (\y -> (y,i)) <$> f x | (i, (f,_)) <- zip [0 :: Int ..] fns ] + bwd (y,i) = case drop i fns of + (_,g):_ -> Just (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 = [(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 = 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 = 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/Data/Profunctor/Separator.hs b/distributors-core/src/Data/Profunctor/Separator.hs deleted file mode 100644 index 986f3dae..00000000 --- a/distributors-core/src/Data/Profunctor/Separator.hs +++ /dev/null @@ -1,238 +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 - -- * SepBy Combinators - , several - , several1 - , chain - , chain1 - , intercalateP - -- * Operator Expressions - , Operator (..) - , Assoc (..) - , withOperators - ) where - -import Control.Lens -import Control.Lens.PartialIso -import Data.Monoid.Disjunctive (orP) -import Data.Profunctor.Distributor -import Data.Profunctor.Monoidal.Cocartesian -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 t'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 t'SepBy' smart constructor for no separator, -beginning or ending delimiters. -} -noSep :: Applicative p => SepBy (p ()) -noSep = sepBy (pure ()) - -{- | -> 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 . swapped >~ - 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 t'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` - -> 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`, 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 an 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 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 = orP [only i >? sym | (i, sym) <- zip [0 :: Int ..] syms] - - withPreP ops inner = - difoldr (partialIso fwd bwd) >? manyP (tagSepP (snd <$> ops)) >*< inner - where - fns = [patternFns pat | (pat, _) <- ops] - fwd x = orP - [ (\y -> (i,y)) <$> f x | (i, (f,_)) <- zip [0 :: Int ..] fns ] - bwd (i,y) = case drop i fns of - (_,g):_ -> Just (g y) - [] -> Nothing - - withPostP ops inner = - difoldl (partialIso fwd bwd) >? inner >*< manyP (tagSepP (snd <$> ops)) - where - fns = [patternFns pat | (pat, _) <- ops] - fwd x = orP - [ (\y -> (y,i)) <$> f x | (i, (f,_)) <- zip [0 :: Int ..] fns ] - bwd (y,i) = case drop i fns of - (_,g):_ -> Just (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) = patternFns pat] - - assocOf i = let (assoc,_,_) = fns !! i in assoc - 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 = 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 = 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/test/Properties/Homogeneous.hs b/distributors-core/test/Properties/Homogeneous.hs index 52606c31..9caceb27 100644 --- a/distributors-core/test/Properties/Homogeneous.hs +++ b/distributors-core/test/Properties/Homogeneous.hs @@ -11,7 +11,7 @@ import Control.Applicative import Control.Arrow ((+++)) import Control.Lens (iview) import Control.Lens.Diopter -import Control.Lens.Monocle +import Control.Lens.Comonocle import Control.Monad ((<=<)) import Data.Functor.Compose (Compose (..)) import Data.Foldable (toList) diff --git a/distributors-grammar/src/Control/Lens/Grammar.hs b/distributors-grammar/src/Control/Lens/Grammar.hs index 11221686..ef3cdcfd 100644 --- a/distributors-grammar/src/Control/Lens/Grammar.hs +++ b/distributors-grammar/src/Control/Lens/Grammar.hs @@ -59,7 +59,6 @@ import Data.Profunctor.Monadic 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) @@ -83,7 +82,6 @@ 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 -- $setup diff --git a/distributors-grammar/src/Control/Lens/Grammar/Symbol.hs b/distributors-grammar/src/Control/Lens/Grammar/Symbol.hs index 6f2f7f04..18af1e00 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/Symbol.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/Symbol.hs @@ -24,7 +24,7 @@ import Control.Lens.Grammar.Token import Data.Bifunctor.Joker import Data.Profunctor import Data.Profunctor.Monoidal -import Data.Profunctor.Separator (SepBy (..), sepBy) +import Data.Profunctor.Distributor (SepBy (..), sepBy) import Text.ParserCombinators.ReadP (ReadP, string) -- | A `terminal` symbol in a grammar. diff --git a/distributors-json/src/Control/Lens/Grammar/Json.hs b/distributors-json/src/Control/Lens/Grammar/Json.hs index c4d3b841..b6627b2e 100644 --- a/distributors-json/src/Control/Lens/Grammar/Json.hs +++ b/distributors-json/src/Control/Lens/Grammar/Json.hs @@ -132,7 +132,7 @@ module Control.Lens.Grammar.Json import Control.Applicative import Control.Lens import Control.Lens.Grammar -import Control.Lens.Monocle (AComonocle, withComonocle) +import Control.Lens.Comonocle (AComonocle, withComonocle) import Control.Monad import Control.Monad.Trans.Class (lift) import Control.Monad.Trans.Reader (ReaderT, ask, local, runReaderT) @@ -607,7 +607,7 @@ class which `jsonEnumWith` tables once, numbered as `fromEnumerable` numbers them. >>> import Control.Lens (coerced) ->>> import Control.Lens.Monocle (_BoundedEnum) +>>> 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 From 319009e573c2689a15bfb2dc57b9799a7e8fe211 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Mon, 9 Nov 2026 04:50:05 -0800 Subject: [PATCH 086/130] Benchmark real-world documents, from aeson's benchmarks Twitter search results, of 10 & 100 stories & of Japanese text, GitHub issues, a GeoJSON polygon & generated records of people, copied from aeson's benchmarks with attribution, typed by records whose Json & aeson instances are derived generically by the same options, & embedded. Co-Authored-By: Claude Opus 5.5 --- distributors-json/bench/Documents.hs | 296 ++ distributors-json/bench/Main.hs | 8 + distributors-json/bench/data/README.md | 14 + .../bench/data/buffer-builder.json | 4322 +++++++++++++++++ distributors-json/bench/data/geometry.json | 1 + .../bench/data/github-issues.json | 1540 ++++++ distributors-json/bench/data/jp100.json | 1 + distributors-json/bench/data/twitter10.json | 1 + distributors-json/bench/data/twitter100.json | 1 + distributors-json/distributors-json.cabal | 9 + distributors-json/package.yaml | 3 + 11 files changed, 6196 insertions(+) create mode 100644 distributors-json/bench/Documents.hs create mode 100644 distributors-json/bench/data/README.md create mode 100644 distributors-json/bench/data/buffer-builder.json create mode 100644 distributors-json/bench/data/geometry.json create mode 100644 distributors-json/bench/data/github-issues.json create mode 100644 distributors-json/bench/data/jp100.json create mode 100644 distributors-json/bench/data/twitter10.json create mode 100644 distributors-json/bench/data/twitter100.json 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 index 37f5d1c7..db0d5f49 100644 --- a/distributors-json/bench/Main.hs +++ b/distributors-json/bench/Main.hs @@ -36,6 +36,8 @@ import Data.Word (Word64) import GHC.Generics (Generic) import Test.Tasty.Bench +import Documents qualified as Doc + data Person = Person { name :: Text , age :: Int @@ -286,6 +288,12 @@ main = defaultMain , 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]) ()) 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 index 38fe56eb..24f3fbd2 100644 --- a/distributors-json/distributors-json.cabal +++ b/distributors-json/distributors-json.cabal @@ -21,6 +21,13 @@ 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 @@ -275,6 +282,7 @@ benchmark json type: exitcode-stdio-1.0 main-is: Main.hs other-modules: + Documents Paths_distributors_json autogen-modules: Paths_distributors_json @@ -330,6 +338,7 @@ benchmark json , 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 diff --git a/distributors-json/package.yaml b/distributors-json/package.yaml index 55e2038c..0611a8cc 100644 --- a/distributors-json/package.yaml +++ b/distributors-json/package.yaml @@ -9,6 +9,8 @@ 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 @@ -128,4 +130,5 @@ benchmarks: dependencies: - deepseq >= 1.4 && < 2 - distributors-json + - file-embed >= 0.0.15 && < 1 - tasty-bench >= 0.3 && < 1 From 24f165160d32202726f61b0624858cfc6b31b55f Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Mon, 9 Nov 2026 04:53:53 -0800 Subject: [PATCH 087/130] Split Enumerable into its own module, & rename Indexing to Enumerator Enumerable, its functions, & Indexing, renamed Enumerator, which numbers an enumerable sum's copies, move to Data.Traversable.Homogeneous.Enumerable. The (,) e Homogeneous instance stays with its class, sequencing its tags itself, & Control.Lens.Grammar re-exports the new module, as it did them. Co-Authored-By: Claude Opus 5.5 --- distributors-core/CHANGELOG.md | 2 + distributors-core/distributors.cabal | 1 + .../src/Control/Lens/Comonocle.hs | 5 +- .../src/Data/Traversable/Homogeneous.hs | 201 +-------------- .../Traversable/Homogeneous/Enumerable.hs | 235 ++++++++++++++++++ .../test/Properties/Homogeneous.hs | 49 ++-- .../src/Control/Lens/Grammar.hs | 1 + 7 files changed, 271 insertions(+), 223 deletions(-) create mode 100644 distributors-core/src/Data/Traversable/Homogeneous/Enumerable.hs diff --git a/distributors-core/CHANGELOG.md b/distributors-core/CHANGELOG.md index c02e546d..4d9f6f07 100644 --- a/distributors-core/CHANGELOG.md +++ b/distributors-core/CHANGELOG.md @@ -28,6 +28,8 @@ ### Breaking Changes +- `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 `Data.Profunctor.Distributor`: diff --git a/distributors-core/distributors.cabal b/distributors-core/distributors.cabal index 6f25002e..ac3a8d46 100644 --- a/distributors-core/distributors.cabal +++ b/distributors-core/distributors.cabal @@ -44,6 +44,7 @@ library Data.Profunctor.Monoidal Data.Profunctor.Monoidal.Cocartesian Data.Traversable.Homogeneous + Data.Traversable.Homogeneous.Enumerable other-modules: Paths_distributors autogen-modules: diff --git a/distributors-core/src/Control/Lens/Comonocle.hs b/distributors-core/src/Control/Lens/Comonocle.hs index aced9638..60cf5d35 100644 --- a/distributors-core/src/Control/Lens/Comonocle.hs +++ b/distributors-core/src/Control/Lens/Comonocle.hs @@ -39,6 +39,7 @@ import Control.Lens.Internal.Profunctor import Data.Functor.Compose 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) @@ -173,8 +174,8 @@ 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 () :: Indexing () ()) :: Indexing (f ()) (f ()) of - Indexing count _ _ -> count + copies _ = case enumerably (pure () :: Enumerator () ()) :: Enumerator (f ()) (f ()) of + Enumerator count _ _ -> count {- | The copy of `AComonocle` at an index, holding a focus, if there is one, like `toEnum`, & inverse to `indexComonocle`. diff --git a/distributors-core/src/Data/Traversable/Homogeneous.hs b/distributors-core/src/Data/Traversable/Homogeneous.hs index 23358050..5a174d7f 100644 --- a/distributors-core/src/Data/Traversable/Homogeneous.hs +++ b/distributors-core/src/Data/Traversable/Homogeneous.hs @@ -16,23 +16,13 @@ module Data.Traversable.Homogeneous , zipWithHomogeneous3 , zipWithHomogeneousM , transposeHomogeneous - -- * Enumerable - , Enumerable (..) - , extractEnumerable - , fromEnumerable - , toEnumerable - , succEnumerable - , predEnumerable - , enumerateFrom - -- * Indexing & Zipporah - , Indexing (..) + -- * Zipporah , Zipporah (..) ) where import Control.Applicative import Control.Lens hiding (chosen) import Control.Lens.PartialIso -import Control.Monad ((>=>)) import Control.Monad.Trans.Identity (IdentityT (..)) import Data.Complex import Data.Functor.Compose @@ -42,7 +32,7 @@ import qualified Data.Monoid as Monoid import Data.Ord (Down (..)) import qualified Data.Semigroup as Semigroup import Data.Monoid.Disjunctive -import Data.Profunctor (Cochoice (..), Forget (..), Star (..)) +import Data.Profunctor (Cochoice (..), Star (..)) import Data.Profunctor.Monoidal import Data.Proxy import Data.Sequence (Seq) @@ -51,7 +41,6 @@ import Data.Tree (Tree (..)) import Data.Vector (Vector) import Data.Void import GHC.Generics -import Numeric.Natural (Natural) import Witherable (Filterable (..)) import Data.Profunctor.Distributor @@ -183,108 +172,16 @@ instance Homogeneous Complex where instance Homogeneous Tree where homogeneously p = dimap2 rootLabel subForest Node p (manyP (homogeneously p)) -{- | 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 `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 balanced tree, built lazily. +summed in a balanced tree, built lazily. ->>> map fromEnumerable [(False, 'a'), (True, 'b')] -[0,1] ->>> map fromEnumerable [(LT, 'a'), (EQ, 'b'), (GT, 'c')] -[0,1,2] >>> zipWithHomogeneous (+) (True, 1) (True, 2 :: Int) Just (True,3) >>> zipWithHomogeneous (+) (True, 1) (False, 2 :: Int) Nothing - -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) => Homogeneous ((,) e) where - homogeneously = enumerably -instance (Enum e, Bounded e) => Enumerable ((,) e) where - enumerably p = go (tag (minBound :: e)) (tag (maxBound :: e)) + homogeneously p = go (tag (minBound :: e)) (tag (maxBound :: e)) where tag = toInteger . fromEnum go lo hi @@ -295,65 +192,6 @@ instance (Enum e, Bounded e) => Enumerable ((,) e) where where mid = (lo + hi) `div` 2 --- | The copy which an `Enumerable` sum holds. -extractEnumerable :: Enumerable f => f a -> a -extractEnumerable = runForget (enumerably (Forget id)) - -{- | Which copy an `Enumerable` sum holds, numbered from 0, left to right, -like `fromEnum`. - ->>> fromEnumerable (GT, 'x') -2 --} -fromEnumerable :: Enumerable f => f a -> Natural -fromEnumerable = - case enumerably (pure ()) of Indexing _ which _ -> which - -{- | The copy of an `Enumerable` sum at an index, if there is one, -like `toEnum`, the inverse of `fromEnumerable`. - ->>> [toEnumerable 'x' i | i <- [0..3]] :: [Maybe (Ordering, Char)] -[Just (LT,'x'),Just (EQ,'x'),Just (GT,'x'),Nothing] - --} -toEnumerable :: Enumerable f => a -> Natural -> Maybe (f a) -toEnumerable a copy = - case enumerably (pure a) of Indexing _ _ select -> select copy - -{- | The next copy of an `Enumerable` sum, if there is one, like `succ`. - ->>> succEnumerable (EQ, 'x') -Just (GT,'x') ->>> succEnumerable (GT, 'x') -Nothing --} -succEnumerable :: Enumerable f => f a -> Maybe (f a) -succEnumerable x = case enumerably (pure (extractEnumerable x)) of - Indexing _ which select -> select (which x + 1) - -{- | The previous copy of an `Enumerable` sum, if there is one, like `pred`. - ->>> predEnumerable (EQ, 'x') -Just (LT,'x') ->>> predEnumerable (LT, 'x') -Nothing --} -predEnumerable :: Enumerable f => f a -> Maybe (f a) -predEnumerable x = case enumerably (pure (extractEnumerable x)) of - Indexing _ which select -> case which x of - 0 -> Nothing - copy -> select (copy - 1) - -{- | 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 (extractEnumerable x)) of - Indexing _ which select -> - let go copy = maybe [] (: go (copy + 1)) (select copy) in go (which x) - {- | 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`. @@ -427,37 +265,6 @@ transposeHomogeneous transposeHomogeneous = zipHomogeneous Just -{- | t'Indexing' 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 Indexing s t = Indexing Natural (s -> Natural) (Natural -> Maybe t) -instance Profunctor Indexing where - dimap f g (Indexing count which select) = - Indexing count (which . f) (fmap g . select) -instance Functor (Indexing s) where - fmap = rmap -instance Applicative (Indexing s) where - pure t = Indexing 1 (const 0) (\i -> if i == 0 then Just t else Nothing) - Indexing count0 which0 select0 <*> Indexing count1 which1 select1 = Indexing - (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 Indexing where - zeroP = Indexing 0 absurd (const Nothing) - Indexing count0 which0 select0 >+< Indexing count1 which1 select1 = Indexing - (count0 + count1) - (either which0 ((count0 +) . which1)) - (\i -> if i < count0 then Left <$> select0 i - else Right <$> select1 (i - count0)) -instance Cochoice Indexing where - unleft (Indexing count which select) = Indexing count - (which . Left) (select >=> either Just (const Nothing)) - unright (Indexing count which select) = Indexing count - (which . Right) (select >=> either (const Nothing) 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. 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..bddc3f3e --- /dev/null +++ b/distributors-core/src/Data/Traversable/Homogeneous/Enumerable.hs @@ -0,0 +1,235 @@ +{-| +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 (..) + , extractEnumerable + , fromEnumerable + , toEnumerable + , succEnumerable + , predEnumerable + , enumerateFrom + -- * Enumerator + , Enumerator (..) + ) where + +import Control.Applicative +import Control.Lens hiding (chosen) +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 + +{- | 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 `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 balanced tree, built lazily. + +>>> map fromEnumerable [(False, 'a'), (True, 'b')] +[0,1] +>>> map fromEnumerable [(LT, 'a'), (EQ, 'b'), (GT, 'c')] +[0,1,2] + +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 + +-- | The copy which an `Enumerable` sum holds. +extractEnumerable :: Enumerable f => f a -> a +extractEnumerable = runForget (enumerably (Forget id)) + +{- | Which copy an `Enumerable` sum holds, numbered from 0, left to right, +like `fromEnum`. + +>>> fromEnumerable (GT, 'x') +2 +-} +fromEnumerable :: Enumerable f => f a -> Natural +fromEnumerable = + case enumerably (pure ()) of Enumerator _ which _ -> which + +{- | The copy of an `Enumerable` sum at an index, if there is one, +like `toEnum`, the inverse of `fromEnumerable`. + +>>> [toEnumerable 'x' i | i <- [0..3]] :: [Maybe (Ordering, Char)] +[Just (LT,'x'),Just (EQ,'x'),Just (GT,'x'),Nothing] + +-} +toEnumerable :: Enumerable f => a -> Natural -> Maybe (f a) +toEnumerable a copy = + case enumerably (pure a) of Enumerator _ _ select -> select copy + +{- | The next copy of an `Enumerable` sum, if there is one, like `succ`. + +>>> succEnumerable (EQ, 'x') +Just (GT,'x') +>>> succEnumerable (GT, 'x') +Nothing +-} +succEnumerable :: Enumerable f => f a -> Maybe (f a) +succEnumerable x = case enumerably (pure (extractEnumerable x)) of + Enumerator _ which select -> select (which x + 1) + +{- | The previous copy of an `Enumerable` sum, if there is one, like `pred`. + +>>> predEnumerable (EQ, 'x') +Just (LT,'x') +>>> predEnumerable (LT, 'x') +Nothing +-} +predEnumerable :: Enumerable f => f a -> Maybe (f a) +predEnumerable x = case enumerably (pure (extractEnumerable x)) of + Enumerator _ which select -> case which x of + 0 -> Nothing + copy -> select (copy - 1) + +{- | 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 (extractEnumerable x)) of + Enumerator _ which select -> + let go copy = maybe [] (: go (copy + 1)) (select copy) in go (which x) + +{- | 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/Properties/Homogeneous.hs b/distributors-core/test/Properties/Homogeneous.hs index 9caceb27..572fc284 100644 --- a/distributors-core/test/Properties/Homogeneous.hs +++ b/distributors-core/test/Properties/Homogeneous.hs @@ -25,6 +25,7 @@ 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) @@ -45,20 +46,20 @@ instance Finite Void where instance (Finite a, Finite b) => Finite (Either a b) where universe = map Left universe <> map Right universe --- | An `Indexing`'s count, indices of all sources, & selections, a little past. -indexing :: Finite s => Indexing s t -> (Natural, [Natural], [Maybe t]) -indexing (Indexing count which select) = +-- | 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 -genIndexing :: forall s t. Finite s => Gen t -> Gen (Indexing s t) -genIndexing gen = do +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 $ Indexing count + pure $ Enumerator count (\s -> fromMaybe 0 (lookup s (zip universe which))) (\i -> lookup i (zip [0 ..] selected)) @@ -241,34 +242,34 @@ zipporahLaws = do homogeneousProperties :: Spec homogeneousProperties = do - describe "Indexing" $ do - let ix = genIndexing arbitrary :: Gen (Indexing Bool Int) - ixf = genIndexing (applyFun <$> arbitrary) - :: Gen (Indexing Bool (Int -> Int)) + 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 -> - indexing (pure id <*> v) === indexing v + enumerator (pure id <*> v) === enumerator v prop "pure (.) <*> u <*> v <*> w = u <*> (v <*> w)" $ forAllBlind ixf $ \u -> forAllBlind ixf $ \v -> forAllBlind ix $ \w -> - indexing (pure (.) <*> u <*> v <*> w) === indexing (u <*> (v <*> w)) + enumerator (pure (.) <*> u <*> v <*> w) === enumerator (u <*> (v <*> w)) prop "u <*> pure y = pure ($ y) <*> u" $ forAllBlind ixf $ \u (y :: Int) -> - indexing (u <*> pure y) === indexing (pure ($ y) <*> u) + enumerator (u <*> pure y) === enumerator (pure ($ y) <*> u) prop "zeroP >+< p = lunit p" $ forAllBlind ix $ \p -> - indexing (zeroP >+< p) === indexing (lunit p) + enumerator (zeroP >+< p) === enumerator (lunit p) prop "p >+< zeroP = runit p" $ forAllBlind ix $ \p -> - indexing (p >+< zeroP) === indexing (runit p) + enumerator (p >+< zeroP) === enumerator (runit p) prop "p >+< q >+< r = assoc ((p >+< q) >+< r)" $ forAllBlind ix $ \p -> forAllBlind ix $ \q -> forAllBlind ix $ \r -> - indexing (p >+< q >+< r) - === indexing (dimap unassocE assocE ((p >+< q) >+< r)) + enumerator (p >+< q >+< r) + === enumerator (dimap unassocE assocE ((p >+< q) >+< r)) prop "unleft = unright . dimap swapE swapE" $ - forAllBlind (genIndexing arbitrary - :: Gen (Indexing (Either Bool ()) (Either Int ()))) $ \p -> - indexing (unleft p) === indexing (unright (dimap swapE swapE p)) + 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 (genIndexing (Left <$> arbitrary) - :: Gen (Indexing Bool (Either Int Void))) $ \p -> - indexing (rmap (either id absurd) p) - === indexing (unleft (lmap (either id absurd) p) :: Indexing Bool Int) + 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" $ diff --git a/distributors-grammar/src/Control/Lens/Grammar.hs b/distributors-grammar/src/Control/Lens/Grammar.hs index ef3cdcfd..fd66474b 100644 --- a/distributors-grammar/src/Control/Lens/Grammar.hs +++ b/distributors-grammar/src/Control/Lens/Grammar.hs @@ -83,6 +83,7 @@ import Data.Profunctor.Grammar as X import Data.Profunctor.Grammar.Parsector as X import Data.Profunctor.Monoidal as X import Data.Traversable.Homogeneous as X +import Data.Traversable.Homogeneous.Enumerable as X -- $setup -- >>> import Data.String (fromString) From bec6b5b7a85808b28807d4be6b8ec879fc62a7fa Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Mon, 9 Nov 2026 04:57:17 -0800 Subject: [PATCH 088/130] Add Data.Traversable.Homogeneous.Vectorial Vectorial containers are Homogeneous & Distributive, of a fixed shape, like Identity, Complex & their products & compositions, so they're sequenced vectorially, by ditraverse, by Monoidal profunctors alone, & zip & transpose totally. Their API: shapes, by replicating, positions & dimensions; total & strict zipping, unzipping & transposing; positions, from lists, indexing & adjusting; & strict vector space operations. Co-Authored-By: Claude Opus 5.5 --- distributors-core/CHANGELOG.md | 4 + distributors-core/distributors.cabal | 1 + .../Data/Traversable/Homogeneous/Vectorial.hs | 223 ++++++++++++++++++ .../test/Properties/Homogeneous.hs | 18 ++ 4 files changed, 246 insertions(+) create mode 100644 distributors-core/src/Data/Traversable/Homogeneous/Vectorial.hs diff --git a/distributors-core/CHANGELOG.md b/distributors-core/CHANGELOG.md index 4d9f6f07..aad71b95 100644 --- a/distributors-core/CHANGELOG.md +++ b/distributors-core/CHANGELOG.md @@ -4,6 +4,10 @@ ### New APIs +- `Data.Traversable.Homogeneous.Vectorial`: `Vectorial` containers, + `Homogeneous` & `Distributive`, of fixed shapes, sequenced `vectorially` + by `Monoidal` profunctors, with total & strict zipping, transposing, + positions & vector space operations. - `Enumerable`, in `Data.Traversable.Homogeneous`, of `Homogeneous` countable sums of single copies, sequenced `enumerably` by `CocartesianMonoidal`s, with generic defaults by `Generic1`. diff --git a/distributors-core/distributors.cabal b/distributors-core/distributors.cabal index ac3a8d46..7eb8971d 100644 --- a/distributors-core/distributors.cabal +++ b/distributors-core/distributors.cabal @@ -45,6 +45,7 @@ library Data.Profunctor.Monoidal.Cocartesian Data.Traversable.Homogeneous Data.Traversable.Homogeneous.Enumerable + Data.Traversable.Homogeneous.Vectorial other-modules: Paths_distributors autogen-modules: diff --git a/distributors-core/src/Data/Traversable/Homogeneous/Vectorial.hs b/distributors-core/src/Data/Traversable/Homogeneous/Vectorial.hs new file mode 100644 index 00000000..6a7ce844 --- /dev/null +++ b/distributors-core/src/Data/Traversable/Homogeneous/Vectorial.hs @@ -0,0 +1,223 @@ +{-| +Module : Data.Traversable.Homogeneous.Vectorial +Description : vectorial +Copyright : (C) 2026 - Eitan Chatav +License : BSD-style (see the file LICENSE) +Maintainer : Eitan Chatav +Stability : provisional +Portability : non-portable +-} + +module Data.Traversable.Homogeneous.Vectorial + ( -- * Vectorial + Vectorial + , vectorially + -- * Shape + , replicateVectorial + , positionsVectorial + , dimensionVectorial + -- * Zipping + , zipVectorial + , zipWithVectorial + , zipWithVectorial' + , zipWith3Vectorial + , zipWith3Vectorial' + , unzipVectorial + , transposeVectorial + -- * Positions + , fromListVectorial + , indexVectorial + , adjustVectorial + -- * Vector space + , zeroVectorial + , (^+^) + , (^-^) + , negateVectorial + , (*^) + , dotVectorial + ) where + +import Data.Distributive (Distributive (..), cotraverse) +import Data.Foldable (toList) +import Data.Functor.Const (Const (..)) +import Data.List (genericDrop, genericLength) +import Data.Maybe (listToMaybe) +import Data.Profunctor.Monoidal (Monoidal, ditraverse) +import Data.Traversable (mapAccumL) +import Data.Traversable.Homogeneous +import GHC.Generics (Par1 (..), (:*:) (..)) +import Numeric.Natural (Natural) + +-- $setup +-- >>> import Data.Complex +-- >>> import Data.Functor.Identity +-- >>> import Numeric.Natural (Natural) + +{- | `Vectorial` containers are `Homogeneous` & `Data.Distributive.Distributive`, +so every value has the same shape, a fixed number of positions, +like `Data.Functor.Identity.Identity`, `Data.Complex.Complex`, +& their products & compositions. So they zip totally, as +`Homogeneous` structures of different shapes can't, +& they're sequenced by `Monoidal` `Data.Profunctor.Profunctor`s alone, +`vectorially`, which `homogeneously` specializes. + +> prop> homogeneously = vectorially +-} +type Vectorial f = (Homogeneous f, Distributive f) + +-- | Sequences an action in every position, by `ditraverse`. +vectorially :: (Vectorial f, Monoidal p) => p a b -> p (f a) (f b) +vectorially = ditraverse + +-- | The same value in every position, like `pure`. +-- +-- >>> replicateVectorial 'x' :: Complex Char +-- 'x' :+ 'x' +replicateVectorial :: forall f a. Vectorial f => a -> f a +replicateVectorial a = getConst <$> distribute (Const a :: Const a (f ())) + +-- | Positions, numbered from 0, left to right. +-- +-- >>> positionsVectorial :: Complex Natural +-- 0 :+ 1 +positionsVectorial :: forall f. Vectorial f => f Natural +positionsVectorial = + snd (mapAccumL (\i () -> (i + 1, i)) 0 (replicateVectorial @f ())) + +-- | The number of positions. +-- +-- >>> dimensionVectorial @Complex +-- 2 +dimensionVectorial :: forall f. Vectorial f => Natural +dimensionVectorial = genericLength (toList (replicateVectorial @f ())) + +-- | Zip two structures, position by position. +-- +-- >>> zipVectorial (1 :+ 2) ('a' :+ 'b') +-- (1,'a') :+ (2,'b') +zipVectorial :: Vectorial f => f a -> f b -> f (a, b) +zipVectorial = zipWithVectorial (,) + +{- | Zip two structures by a function, position by position, +which, as their shapes are the same, never fails. + +>>> zipWithVectorial (+) (1 :+ 2) (10 :+ 20) +11 :+ 22 +-} +zipWithVectorial :: Vectorial f => (a -> b -> c) -> f a -> f b -> f c +zipWithVectorial f as bs = + cotraverse zipped (Par1 (Left <$> as) :*: Par1 (Right <$> bs)) + where + -- positions agree, as shapes do + zipped = \case + Par1 (Left a) :*: Par1 (Right b) -> f a b + _ -> error "zipWithVectorial: positions disagree" + +-- | `zipWithVectorial`, evaluating every result, left to right. +zipWithVectorial' :: Vectorial f => (a -> b -> c) -> f a -> f b -> f c +zipWithVectorial' f as bs = forced (zipWithVectorial f as bs) + +-- | Zip three structures by a function, position by position. +-- +-- >>> zipWith3Vectorial (\a b c -> a + b * c) (1 :+ 2) (3 :+ 4) (5 :+ 6) +-- 16 :+ 26 +zipWith3Vectorial + :: Vectorial f => (a -> b -> c -> d) -> f a -> f b -> f c -> f d +zipWith3Vectorial f as bs cs = cotraverse zipped + (Par1 (Left <$> as) :*: Par1 (Right . Left <$> bs) + :*: Par1 (Right . Right <$> cs)) + where + -- positions agree, as shapes do + zipped = \case + Par1 (Left a) :*: Par1 (Right (Left b)) :*: Par1 (Right (Right c)) -> + f a b c + _ -> error "zipWith3Vectorial: positions disagree" + +-- | `zipWith3Vectorial`, evaluating every result, left to right. +zipWith3Vectorial' + :: Vectorial f => (a -> b -> c -> d) -> f a -> f b -> f c -> f d +zipWith3Vectorial' f as bs cs = forced (zipWith3Vectorial f as bs cs) + +-- | Unzip a structure of pairs. +-- +-- >>> unzipVectorial ((1,'a') :+ (2,'b')) +-- (1 :+ 2,'a' :+ 'b') +unzipVectorial :: Vectorial f => f (a, b) -> (f a, f b) +unzipVectorial abs' = (fst <$> abs', snd <$> abs') + +{- | Transpose nested structures, which, as their shapes are the same, +never fails. + +>>> transposeVectorial ((1 :+ 2) :+ (3 :+ 4)) +(1 :+ 3) :+ (2 :+ 4) +-} +transposeVectorial :: (Vectorial f, Vectorial g) => f (g a) -> g (f a) +transposeVectorial = distribute + +{- | A structure of a list's values, when it has exactly as many as +the structure has positions. + +>>> fromListVectorial "ab" :: Maybe (Complex Char) +Just ('a' :+ 'b') +>>> fromListVectorial "abc" :: Maybe (Complex Char) +Nothing +-} +fromListVectorial :: forall f a. Vectorial f => [a] -> Maybe (f a) +fromListVectorial as = case mapAccumL fill as (replicateVectorial @f ()) of + ([], filled) -> sequenceA filled + _ -> Nothing + where + fill (x : xs) () = (xs, Just x) + fill [] () = ([], Nothing) + +-- | The value at a position, if there is one. +-- +-- >>> indexVectorial 1 ('a' :+ 'b') +-- Just 'b' +indexVectorial :: Vectorial f => Natural -> f a -> Maybe a +indexVectorial i = listToMaybe . genericDrop i . toList + +-- | Adjust the value at a position. +-- +-- >>> adjustVectorial 0 negate (1 :+ 2) +-- (-1) :+ 2 +adjustVectorial :: Vectorial f => Natural -> (a -> a) -> f a -> f a +adjustVectorial i f = zipWithVectorial + (\j a -> if i == j then f a else a) positionsVectorial + +-- | The zero vector. +zeroVectorial :: (Vectorial f, Num a) => f a +zeroVectorial = replicateVectorial 0 + +-- | Add vectors, strictly. +(^+^) :: (Vectorial f, Num a) => f a -> f a -> f a +(^+^) = zipWithVectorial' (+) +infixl 6 ^+^ + +-- | Subtract vectors, strictly. +(^-^) :: (Vectorial f, Num a) => f a -> f a -> f a +(^-^) = zipWithVectorial' (-) +infixl 6 ^-^ + +-- | Negate a vector, strictly. +negateVectorial :: (Vectorial f, Num a) => f a -> f a +negateVectorial = forced . fmap negate + +-- | Scale a vector, strictly. +-- +-- >>> 2 *^ (1 :+ 2) +-- 2 :+ 4 +(*^) :: (Vectorial f, Num a) => a -> f a -> f a +s *^ v = forced (fmap (s *) v) +infixl 7 *^ + +-- | The dot product of vectors, summed strictly. +-- +-- >>> dotVectorial (1 :+ 2) (3 :+ 4) +-- 11 +dotVectorial :: (Vectorial f, Num a) => f a -> f a -> a +dotVectorial u v = foldl' (+) 0 (zipWithVectorial (*) u v) + +-- | A structure, with every value evaluated, left to right. +forced :: Foldable f => f a -> f a +forced xs = foldr seq xs xs diff --git a/distributors-core/test/Properties/Homogeneous.hs b/distributors-core/test/Properties/Homogeneous.hs index 572fc284..2495acae 100644 --- a/distributors-core/test/Properties/Homogeneous.hs +++ b/distributors-core/test/Properties/Homogeneous.hs @@ -13,6 +13,7 @@ import Control.Lens (iview) import Control.Lens.Diopter import Control.Lens.Comonocle import Control.Monad ((<=<)) +import Data.Complex (Complex (..), imagPart, realPart) import Data.Functor.Compose (Compose (..)) import Data.Foldable (toList) import Data.List (transpose) @@ -26,6 +27,7 @@ import Data.Profunctor.Monoidal.Cocartesian import Data.Proxy (Proxy (..)) import Data.Traversable.Homogeneous import Data.Traversable.Homogeneous.Enumerable +import Data.Traversable.Homogeneous.Vectorial import Data.Void import GHC.Generics (Par1 (..), (:*:) (..)) import Numeric.Natural (Natural) @@ -242,6 +244,22 @@ zipporahLaws = do homogeneousProperties :: Spec homogeneousProperties = do + describe "Vectorial" $ do + prop "zipWithVectorial zips position by position" $ + \(a :: Complex Int) (b :: Complex Int) -> + zipWithVectorial (-) a b + === (realPart a - realPart b) :+ (imagPart a - imagPart b) + prop "zipWithVectorial' agrees with zipWithVectorial" $ + \(a :: Complex Int) (b :: Complex Int) -> + zipWithVectorial' (*) a b === zipWithVectorial (*) a b + prop "fromListVectorial . toList = Just" $ \(a :: Complex Int) -> + fromListVectorial (toList a) === Just a + prop "transposeVectorial . transposeVectorial = id" $ + \(a :: Complex (Complex Int)) -> + transposeVectorial (transposeVectorial a) === a + prop "dotVectorial is the sum of products" $ + \(a :: Complex Int) (b :: Complex Int) -> + dotVectorial a b === sum (zipWithVectorial (*) a b) describe "Enumerator" $ do let ix = genEnumerator arbitrary :: Gen (Enumerator Bool Int) ixf = genEnumerator (applyFun <$> arbitrary) From e67f7493f572696614cbbddc5a90bec6c0e8f572 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Mon, 9 Nov 2026 05:03:06 -0800 Subject: [PATCH 089/130] Base Vectorial on Representable, with a basis Comonocle, _Basis Vectorial containers are Homogeneous & Representable: Representable gives them a basis, which Homogeneous's Foldable order enumerates, so that it's countable, by the law toList v = map (index v) basisVectorial. Zipping & transposing are by tabulate & index, total, without tagging, & _Basis is the basis's Comonocle, of a copy of () per basis element, which the Comonocle combinators count, number & navigate. The API adds coordinates, ordinals, unit vectors & matrices. Co-Authored-By: Claude Opus 5.5 --- distributors-core/CHANGELOG.md | 7 +- .../Data/Traversable/Homogeneous/Vectorial.hs | 246 +++++++++++------- .../test/Properties/Homogeneous.hs | 17 ++ 3 files changed, 176 insertions(+), 94 deletions(-) diff --git a/distributors-core/CHANGELOG.md b/distributors-core/CHANGELOG.md index aad71b95..c1ec60f8 100644 --- a/distributors-core/CHANGELOG.md +++ b/distributors-core/CHANGELOG.md @@ -5,9 +5,10 @@ ### New APIs - `Data.Traversable.Homogeneous.Vectorial`: `Vectorial` containers, - `Homogeneous` & `Distributive`, of fixed shapes, sequenced `vectorially` - by `Monoidal` profunctors, with total & strict zipping, transposing, - positions & vector space operations. + `Homogeneous` & `Representable`, whose `Foldable` order enumerates their + basis, which `_Basis` is a `Comonocle` of; sequenced `vectorially` by + `Monoidal` profunctors, with coordinates, total & strict zipping, + transposing, & vector space & matrix operations. - `Enumerable`, in `Data.Traversable.Homogeneous`, of `Homogeneous` countable sums of single copies, sequenced `enumerably` by `CocartesianMonoidal`s, with generic defaults by `Generic1`. diff --git a/distributors-core/src/Data/Traversable/Homogeneous/Vectorial.hs b/distributors-core/src/Data/Traversable/Homogeneous/Vectorial.hs index 6a7ce844..b8844db6 100644 --- a/distributors-core/src/Data/Traversable/Homogeneous/Vectorial.hs +++ b/distributors-core/src/Data/Traversable/Homogeneous/Vectorial.hs @@ -12,10 +12,13 @@ module Data.Traversable.Homogeneous.Vectorial ( -- * Vectorial Vectorial , vectorially - -- * Shape - , replicateVectorial - , positionsVectorial + -- * Basis + , _Basis + , basisVectorial + , ordinalVectorial + , fromOrdinalVectorial , dimensionVectorial + , coordinate -- * Zipping , zipVectorial , zipWithVectorial @@ -24,116 +27,152 @@ module Data.Traversable.Homogeneous.Vectorial , zipWith3Vectorial' , unzipVectorial , transposeVectorial - -- * Positions , fromListVectorial - , indexVectorial - , adjustVectorial -- * Vector space , zeroVectorial + , unitVectorial , (^+^) , (^-^) , negateVectorial , (*^) , dotVectorial + -- * Matrices + , identityVectorial + , outerVectorial + , (!*) + , (!*!) ) where -import Data.Distributive (Distributive (..), cotraverse) +import Control.Lens (Lens', dimap, lens) +import Control.Lens.Comonocle (Comonocle) import Data.Foldable (toList) -import Data.Functor.Const (Const (..)) -import Data.List (genericDrop, genericLength) +import Data.Functor.Rep (Representable (..)) +import Data.List (elemIndex, genericDrop, genericLength) import Data.Maybe (listToMaybe) import Data.Profunctor.Monoidal (Monoidal, ditraverse) +import Data.Profunctor.Monoidal.Cocartesian (CocartesianMonoidal (..), dialt) +import Data.Void (absurd) import Data.Traversable (mapAccumL) import Data.Traversable.Homogeneous -import GHC.Generics (Par1 (..), (:*:) (..)) import Numeric.Natural (Natural) -- $setup +-- >>> import Control.Lens (over, view) -- >>> import Data.Complex --- >>> import Data.Functor.Identity --- >>> import Numeric.Natural (Natural) -{- | `Vectorial` containers are `Homogeneous` & `Data.Distributive.Distributive`, -so every value has the same shape, a fixed number of positions, -like `Data.Functor.Identity.Identity`, `Data.Complex.Complex`, -& their products & compositions. So they zip totally, as -`Homogeneous` structures of different shapes can't, -& they're sequenced by `Monoidal` `Data.Profunctor.Profunctor`s alone, -`vectorially`, which `homogeneously` specializes. +{- | `Vectorial` containers are `Homogeneous` & `Representable`: +`Representable` gives them a basis, `Rep` @f@, of the positions +of their every value, & `Homogeneous`, by its `Foldable` order, +enumerates that basis, so that it's countable, as `basisVectorial`. + +> prop> toList v = map (index v) basisVectorial + +So they zip & transpose totally, as `Homogeneous` structures of +different shapes can't, & they're sequenced by `Monoidal` +`Data.Profunctor.Profunctor`s alone, `vectorially`, +which `homogeneously` specializes. > prop> homogeneously = vectorially -} -type Vectorial f = (Homogeneous f, Distributive f) +type Vectorial f = (Homogeneous f, Representable f) -- | Sequences an action in every position, by `ditraverse`. vectorially :: (Vectorial f, Monoidal p) => p a b -> p (f a) (f b) vectorially = ditraverse --- | The same value in every position, like `pure`. +{- | The `Comonocle` of the basis, as a sum of copies of @()@, +one for each basis element, in `Foldable` order, so that +the `Comonocle` combinators navigate it. + +>>> import Control.Lens.Comonocle +>>> countComonocle (_Basis @Complex) +2 +>>> toEnumComonocle (_Basis @Complex) () 1 +Just True +>>> enumerateComonocle (_Basis @Complex) False +[False,True] +-} +_Basis :: forall f. (Vectorial f, Eq (Rep f)) => Comonocle (Rep f) (Rep f) () () +_Basis p = case basisVectorial @f of + -- an empty basis has no elements, by the law of `Vectorial` + [] -> dimap (\_ -> error "_Basis: no basis elements") absurd zeroP + r : rs -> copies r rs + where + copies r = \case + [] -> dimap (const ()) (fmap (const r)) p + r' : rs -> + dialt (\s -> if s == r then Left () else Right s) + (fmap (const r)) id p (copies r' rs) + +-- | The basis, in `Foldable` order. -- --- >>> replicateVectorial 'x' :: Complex Char --- 'x' :+ 'x' -replicateVectorial :: forall f a. Vectorial f => a -> f a -replicateVectorial a = getConst <$> distribute (Const a :: Const a (f ())) +-- >>> basisVectorial @Complex +-- [False,True] +basisVectorial :: forall f. Vectorial f => [Rep f] +basisVectorial = toList (tabulate @f id) --- | Positions, numbered from 0, left to right. +-- | The ordinal of a basis element, in `basisVectorial`, numbered from 0. -- --- >>> positionsVectorial :: Complex Natural --- 0 :+ 1 -positionsVectorial :: forall f. Vectorial f => f Natural -positionsVectorial = - snd (mapAccumL (\i () -> (i + 1, i)) 0 (replicateVectorial @f ())) +-- >>> ordinalVectorial @Complex True +-- Just 1 +ordinalVectorial + :: forall f. (Vectorial f, Eq (Rep f)) => Rep f -> Maybe Natural +ordinalVectorial i = fromIntegral <$> elemIndex i (basisVectorial @f) + +-- | The basis element of an ordinal, if there is one. +-- +-- >>> fromOrdinalVectorial @Complex 1 +-- Just True +-- >>> fromOrdinalVectorial @Complex 2 +-- Nothing +fromOrdinalVectorial :: forall f. Vectorial f => Natural -> Maybe (Rep f) +fromOrdinalVectorial n = listToMaybe (genericDrop n (basisVectorial @f)) --- | The number of positions. +-- | The number of basis elements, which diverges for an infinite basis. -- -- >>> dimensionVectorial @Complex -- 2 dimensionVectorial :: forall f. Vectorial f => Natural -dimensionVectorial = genericLength (toList (replicateVectorial @f ())) +dimensionVectorial = genericLength (basisVectorial @f) --- | Zip two structures, position by position. +-- | The coordinate at a basis element. +-- +-- >>> view (coordinate True) (1 :+ 2) +-- 2 +-- >>> over (coordinate False) negate (1 :+ 2) +-- (-1) :+ 2 +coordinate :: (Representable f, Eq (Rep f)) => Rep f -> Lens' (f a) a +coordinate i = lens (`index` i) $ \v a -> + tabulate (\j -> if j == i then a else index v j) + +-- | Zip two structures, coordinate by coordinate. -- -- >>> zipVectorial (1 :+ 2) ('a' :+ 'b') -- (1,'a') :+ (2,'b') -zipVectorial :: Vectorial f => f a -> f b -> f (a, b) +zipVectorial :: Representable f => f a -> f b -> f (a, b) zipVectorial = zipWithVectorial (,) -{- | Zip two structures by a function, position by position, -which, as their shapes are the same, never fails. - ->>> zipWithVectorial (+) (1 :+ 2) (10 :+ 20) -11 :+ 22 --} -zipWithVectorial :: Vectorial f => (a -> b -> c) -> f a -> f b -> f c -zipWithVectorial f as bs = - cotraverse zipped (Par1 (Left <$> as) :*: Par1 (Right <$> bs)) - where - -- positions agree, as shapes do - zipped = \case - Par1 (Left a) :*: Par1 (Right b) -> f a b - _ -> error "zipWithVectorial: positions disagree" +-- | Zip two structures by a function, coordinate by coordinate. +-- +-- >>> zipWithVectorial (+) (1 :+ 2) (10 :+ 20) +-- 11 :+ 22 +zipWithVectorial :: Representable f => (a -> b -> c) -> f a -> f b -> f c +zipWithVectorial f as bs = tabulate (\i -> f (index as i) (index bs i)) --- | `zipWithVectorial`, evaluating every result, left to right. +-- | `zipWithVectorial`, evaluating every coordinate, in `Foldable` order. zipWithVectorial' :: Vectorial f => (a -> b -> c) -> f a -> f b -> f c zipWithVectorial' f as bs = forced (zipWithVectorial f as bs) --- | Zip three structures by a function, position by position. +-- | Zip three structures by a function, coordinate by coordinate. -- -- >>> zipWith3Vectorial (\a b c -> a + b * c) (1 :+ 2) (3 :+ 4) (5 :+ 6) -- 16 :+ 26 zipWith3Vectorial - :: Vectorial f => (a -> b -> c -> d) -> f a -> f b -> f c -> f d -zipWith3Vectorial f as bs cs = cotraverse zipped - (Par1 (Left <$> as) :*: Par1 (Right . Left <$> bs) - :*: Par1 (Right . Right <$> cs)) - where - -- positions agree, as shapes do - zipped = \case - Par1 (Left a) :*: Par1 (Right (Left b)) :*: Par1 (Right (Right c)) -> - f a b c - _ -> error "zipWith3Vectorial: positions disagree" + :: Representable f => (a -> b -> c -> d) -> f a -> f b -> f c -> f d +zipWith3Vectorial f as bs cs = + tabulate (\i -> f (index as i) (index bs i) (index cs i)) --- | `zipWith3Vectorial`, evaluating every result, left to right. +-- | `zipWith3Vectorial`, evaluating every coordinate, in `Foldable` order. zipWith3Vectorial' :: Vectorial f => (a -> b -> c -> d) -> f a -> f b -> f c -> f d zipWith3Vectorial' f as bs cs = forced (zipWith3Vectorial f as bs cs) @@ -142,20 +181,20 @@ zipWith3Vectorial' f as bs cs = forced (zipWith3Vectorial f as bs cs) -- -- >>> unzipVectorial ((1,'a') :+ (2,'b')) -- (1 :+ 2,'a' :+ 'b') -unzipVectorial :: Vectorial f => f (a, b) -> (f a, f b) +unzipVectorial :: Functor f => f (a, b) -> (f a, f b) unzipVectorial abs' = (fst <$> abs', snd <$> abs') -{- | Transpose nested structures, which, as their shapes are the same, -never fails. - ->>> transposeVectorial ((1 :+ 2) :+ (3 :+ 4)) -(1 :+ 3) :+ (2 :+ 4) --} -transposeVectorial :: (Vectorial f, Vectorial g) => f (g a) -> g (f a) -transposeVectorial = distribute +-- | Transpose nested structures. +-- +-- >>> transposeVectorial ((1 :+ 2) :+ (3 :+ 4)) +-- (1 :+ 3) :+ (2 :+ 4) +transposeVectorial + :: (Representable f, Representable g) => f (g a) -> g (f a) +transposeVectorial xss = + tabulate (\j -> tabulate (\i -> index (index xss i) j)) -{- | A structure of a list's values, when it has exactly as many as -the structure has positions. +{- | A structure of a list's values, in `Foldable` order, when it has +exactly as many as the basis. >>> fromListVectorial "ab" :: Maybe (Complex Char) Just ('a' :+ 'b') @@ -163,31 +202,23 @@ Just ('a' :+ 'b') Nothing -} fromListVectorial :: forall f a. Vectorial f => [a] -> Maybe (f a) -fromListVectorial as = case mapAccumL fill as (replicateVectorial @f ()) of +fromListVectorial as = case mapAccumL fill as (tabulate @f (const ())) of ([], filled) -> sequenceA filled _ -> Nothing where fill (x : xs) () = (xs, Just x) fill [] () = ([], Nothing) --- | The value at a position, if there is one. --- --- >>> indexVectorial 1 ('a' :+ 'b') --- Just 'b' -indexVectorial :: Vectorial f => Natural -> f a -> Maybe a -indexVectorial i = listToMaybe . genericDrop i . toList +-- | The zero vector. +zeroVectorial :: (Representable f, Num a) => f a +zeroVectorial = tabulate (const 0) --- | Adjust the value at a position. +-- | The unit vector of a basis element. -- --- >>> adjustVectorial 0 negate (1 :+ 2) --- (-1) :+ 2 -adjustVectorial :: Vectorial f => Natural -> (a -> a) -> f a -> f a -adjustVectorial i f = zipWithVectorial - (\j a -> if i == j then f a else a) positionsVectorial - --- | The zero vector. -zeroVectorial :: (Vectorial f, Num a) => f a -zeroVectorial = replicateVectorial 0 +-- >>> unitVectorial True :: Complex Int +-- 0 :+ 1 +unitVectorial :: (Representable f, Eq (Rep f), Num a) => Rep f -> f a +unitVectorial i = tabulate (\j -> if i == j then 1 else 0) -- | Add vectors, strictly. (^+^) :: (Vectorial f, Num a) => f a -> f a -> f a @@ -218,6 +249,39 @@ infixl 7 *^ dotVectorial :: (Vectorial f, Num a) => f a -> f a -> a dotVectorial u v = foldl' (+) 0 (zipWithVectorial (*) u v) --- | A structure, with every value evaluated, left to right. +-- | The identity matrix, of rows of unit vectors. +-- +-- >>> identityVectorial :: Complex (Complex Int) +-- (1 :+ 0) :+ (0 :+ 1) +identityVectorial :: (Representable f, Eq (Rep f), Num a) => f (f a) +identityVectorial = tabulate unitVectorial + +-- | The outer product of vectors, a matrix of rows. +-- +-- >>> outerVectorial (1 :+ 2) (3 :+ 4) +-- (3 :+ 4) :+ (6 :+ 8) +outerVectorial + :: (Representable f, Representable g, Num a) => f a -> g a -> f (g a) +outerVectorial u v = fmap (\a -> fmap (a *) v) u + +-- | Multiply a matrix, of rows, by a vector. +-- +-- >>> ((1 :+ 2) :+ (3 :+ 4)) !* (1 :+ 1) +-- 3 :+ 7 +(!*) :: (Vectorial f, Vectorial g, Num a) => f (g a) -> g a -> f a +m !* v = forced (fmap (`dotVectorial` v) m) +infixl 7 !* + +-- | Multiply matrices, of rows. +-- +-- >>> ((1 :+ 2) :+ (3 :+ 4)) !*! ((0 :+ 1) :+ (1 :+ 0)) +-- (2 :+ 1) :+ (4 :+ 3) +(!*!) + :: (Vectorial f, Vectorial g, Vectorial h, Num a) + => f (g a) -> g (h a) -> f (h a) +m !*! n = fmap (transposeVectorial n !*) m +infixl 7 !*! + +-- | A structure, with every value evaluated, in `Foldable` order. forced :: Foldable f => f a -> f a forced xs = foldr seq xs xs diff --git a/distributors-core/test/Properties/Homogeneous.hs b/distributors-core/test/Properties/Homogeneous.hs index 2495acae..925de69a 100644 --- a/distributors-core/test/Properties/Homogeneous.hs +++ b/distributors-core/test/Properties/Homogeneous.hs @@ -15,6 +15,7 @@ import Control.Lens.Comonocle import Control.Monad ((<=<)) import Data.Complex (Complex (..), imagPart, realPart) import Data.Functor.Compose (Compose (..)) +import Data.Functor.Rep (Representable (..)) import Data.Foldable (toList) import Data.List (transpose) import Data.Int (Int8) @@ -257,6 +258,22 @@ homogeneousProperties = do prop "transposeVectorial . transposeVectorial = id" $ \(a :: Complex (Complex Int)) -> transposeVectorial (transposeVectorial a) === a + prop "toList v = map (index v) basisVectorial" $ \(v :: Complex Int) -> + toList v === map (index v) (basisVectorial @Complex) + prop "toList v = map (index v) basisVectorial, composed" $ + \(v :: Complex (Complex Int)) -> + let w = Compose v + in toList w === map (index w) (basisVectorial @(Compose Complex Complex)) + it "_Basis numbers basis elements as their ordinals" $ + map (fst . iview (indexComonocle (_Basis @Complex))) + (basisVectorial @Complex) + `shouldBe` [0, 1] + it "ordinals invert basis elements" $ + map (ordinalVectorial @Complex) (basisVectorial @Complex) + `shouldBe` map Just [0, 1] + prop "transposeVectorial . outerVectorial u = outerVectorial u . flip" $ + \(u :: Complex Int) (v :: Complex Int) -> + transposeVectorial (outerVectorial u v) === outerVectorial v u prop "dotVectorial is the sum of products" $ \(a :: Complex Int) (b :: Complex Int) -> dotVectorial a b === sum (zipWithVectorial (*) a b) From d911d483ac315cbc4cff8ffd4ddde1c095fbb4db Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Mon, 9 Nov 2026 05:04:42 -0800 Subject: [PATCH 090/130] Remove Data.Traversable.Homogeneous.Vectorial It derived nothing from Homogeneous & Representable that their laws give: its basis Comonocle rested on equality tests & an unreachable error, rather than a structural sum. Co-Authored-By: Claude Opus 5.5 --- distributors-core/CHANGELOG.md | 5 - distributors-core/distributors.cabal | 1 - .../Data/Traversable/Homogeneous/Vectorial.hs | 287 ------------------ .../test/Properties/Homogeneous.hs | 35 --- 4 files changed, 328 deletions(-) delete mode 100644 distributors-core/src/Data/Traversable/Homogeneous/Vectorial.hs diff --git a/distributors-core/CHANGELOG.md b/distributors-core/CHANGELOG.md index c1ec60f8..4d9f6f07 100644 --- a/distributors-core/CHANGELOG.md +++ b/distributors-core/CHANGELOG.md @@ -4,11 +4,6 @@ ### New APIs -- `Data.Traversable.Homogeneous.Vectorial`: `Vectorial` containers, - `Homogeneous` & `Representable`, whose `Foldable` order enumerates their - basis, which `_Basis` is a `Comonocle` of; sequenced `vectorially` by - `Monoidal` profunctors, with coordinates, total & strict zipping, - transposing, & vector space & matrix operations. - `Enumerable`, in `Data.Traversable.Homogeneous`, of `Homogeneous` countable sums of single copies, sequenced `enumerably` by `CocartesianMonoidal`s, with generic defaults by `Generic1`. diff --git a/distributors-core/distributors.cabal b/distributors-core/distributors.cabal index 7eb8971d..ac3a8d46 100644 --- a/distributors-core/distributors.cabal +++ b/distributors-core/distributors.cabal @@ -45,7 +45,6 @@ library Data.Profunctor.Monoidal.Cocartesian Data.Traversable.Homogeneous Data.Traversable.Homogeneous.Enumerable - Data.Traversable.Homogeneous.Vectorial other-modules: Paths_distributors autogen-modules: diff --git a/distributors-core/src/Data/Traversable/Homogeneous/Vectorial.hs b/distributors-core/src/Data/Traversable/Homogeneous/Vectorial.hs deleted file mode 100644 index b8844db6..00000000 --- a/distributors-core/src/Data/Traversable/Homogeneous/Vectorial.hs +++ /dev/null @@ -1,287 +0,0 @@ -{-| -Module : Data.Traversable.Homogeneous.Vectorial -Description : vectorial -Copyright : (C) 2026 - Eitan Chatav -License : BSD-style (see the file LICENSE) -Maintainer : Eitan Chatav -Stability : provisional -Portability : non-portable --} - -module Data.Traversable.Homogeneous.Vectorial - ( -- * Vectorial - Vectorial - , vectorially - -- * Basis - , _Basis - , basisVectorial - , ordinalVectorial - , fromOrdinalVectorial - , dimensionVectorial - , coordinate - -- * Zipping - , zipVectorial - , zipWithVectorial - , zipWithVectorial' - , zipWith3Vectorial - , zipWith3Vectorial' - , unzipVectorial - , transposeVectorial - , fromListVectorial - -- * Vector space - , zeroVectorial - , unitVectorial - , (^+^) - , (^-^) - , negateVectorial - , (*^) - , dotVectorial - -- * Matrices - , identityVectorial - , outerVectorial - , (!*) - , (!*!) - ) where - -import Control.Lens (Lens', dimap, lens) -import Control.Lens.Comonocle (Comonocle) -import Data.Foldable (toList) -import Data.Functor.Rep (Representable (..)) -import Data.List (elemIndex, genericDrop, genericLength) -import Data.Maybe (listToMaybe) -import Data.Profunctor.Monoidal (Monoidal, ditraverse) -import Data.Profunctor.Monoidal.Cocartesian (CocartesianMonoidal (..), dialt) -import Data.Void (absurd) -import Data.Traversable (mapAccumL) -import Data.Traversable.Homogeneous -import Numeric.Natural (Natural) - --- $setup --- >>> import Control.Lens (over, view) --- >>> import Data.Complex - -{- | `Vectorial` containers are `Homogeneous` & `Representable`: -`Representable` gives them a basis, `Rep` @f@, of the positions -of their every value, & `Homogeneous`, by its `Foldable` order, -enumerates that basis, so that it's countable, as `basisVectorial`. - -> prop> toList v = map (index v) basisVectorial - -So they zip & transpose totally, as `Homogeneous` structures of -different shapes can't, & they're sequenced by `Monoidal` -`Data.Profunctor.Profunctor`s alone, `vectorially`, -which `homogeneously` specializes. - -> prop> homogeneously = vectorially --} -type Vectorial f = (Homogeneous f, Representable f) - --- | Sequences an action in every position, by `ditraverse`. -vectorially :: (Vectorial f, Monoidal p) => p a b -> p (f a) (f b) -vectorially = ditraverse - -{- | The `Comonocle` of the basis, as a sum of copies of @()@, -one for each basis element, in `Foldable` order, so that -the `Comonocle` combinators navigate it. - ->>> import Control.Lens.Comonocle ->>> countComonocle (_Basis @Complex) -2 ->>> toEnumComonocle (_Basis @Complex) () 1 -Just True ->>> enumerateComonocle (_Basis @Complex) False -[False,True] --} -_Basis :: forall f. (Vectorial f, Eq (Rep f)) => Comonocle (Rep f) (Rep f) () () -_Basis p = case basisVectorial @f of - -- an empty basis has no elements, by the law of `Vectorial` - [] -> dimap (\_ -> error "_Basis: no basis elements") absurd zeroP - r : rs -> copies r rs - where - copies r = \case - [] -> dimap (const ()) (fmap (const r)) p - r' : rs -> - dialt (\s -> if s == r then Left () else Right s) - (fmap (const r)) id p (copies r' rs) - --- | The basis, in `Foldable` order. --- --- >>> basisVectorial @Complex --- [False,True] -basisVectorial :: forall f. Vectorial f => [Rep f] -basisVectorial = toList (tabulate @f id) - --- | The ordinal of a basis element, in `basisVectorial`, numbered from 0. --- --- >>> ordinalVectorial @Complex True --- Just 1 -ordinalVectorial - :: forall f. (Vectorial f, Eq (Rep f)) => Rep f -> Maybe Natural -ordinalVectorial i = fromIntegral <$> elemIndex i (basisVectorial @f) - --- | The basis element of an ordinal, if there is one. --- --- >>> fromOrdinalVectorial @Complex 1 --- Just True --- >>> fromOrdinalVectorial @Complex 2 --- Nothing -fromOrdinalVectorial :: forall f. Vectorial f => Natural -> Maybe (Rep f) -fromOrdinalVectorial n = listToMaybe (genericDrop n (basisVectorial @f)) - --- | The number of basis elements, which diverges for an infinite basis. --- --- >>> dimensionVectorial @Complex --- 2 -dimensionVectorial :: forall f. Vectorial f => Natural -dimensionVectorial = genericLength (basisVectorial @f) - --- | The coordinate at a basis element. --- --- >>> view (coordinate True) (1 :+ 2) --- 2 --- >>> over (coordinate False) negate (1 :+ 2) --- (-1) :+ 2 -coordinate :: (Representable f, Eq (Rep f)) => Rep f -> Lens' (f a) a -coordinate i = lens (`index` i) $ \v a -> - tabulate (\j -> if j == i then a else index v j) - --- | Zip two structures, coordinate by coordinate. --- --- >>> zipVectorial (1 :+ 2) ('a' :+ 'b') --- (1,'a') :+ (2,'b') -zipVectorial :: Representable f => f a -> f b -> f (a, b) -zipVectorial = zipWithVectorial (,) - --- | Zip two structures by a function, coordinate by coordinate. --- --- >>> zipWithVectorial (+) (1 :+ 2) (10 :+ 20) --- 11 :+ 22 -zipWithVectorial :: Representable f => (a -> b -> c) -> f a -> f b -> f c -zipWithVectorial f as bs = tabulate (\i -> f (index as i) (index bs i)) - --- | `zipWithVectorial`, evaluating every coordinate, in `Foldable` order. -zipWithVectorial' :: Vectorial f => (a -> b -> c) -> f a -> f b -> f c -zipWithVectorial' f as bs = forced (zipWithVectorial f as bs) - --- | Zip three structures by a function, coordinate by coordinate. --- --- >>> zipWith3Vectorial (\a b c -> a + b * c) (1 :+ 2) (3 :+ 4) (5 :+ 6) --- 16 :+ 26 -zipWith3Vectorial - :: Representable f => (a -> b -> c -> d) -> f a -> f b -> f c -> f d -zipWith3Vectorial f as bs cs = - tabulate (\i -> f (index as i) (index bs i) (index cs i)) - --- | `zipWith3Vectorial`, evaluating every coordinate, in `Foldable` order. -zipWith3Vectorial' - :: Vectorial f => (a -> b -> c -> d) -> f a -> f b -> f c -> f d -zipWith3Vectorial' f as bs cs = forced (zipWith3Vectorial f as bs cs) - --- | Unzip a structure of pairs. --- --- >>> unzipVectorial ((1,'a') :+ (2,'b')) --- (1 :+ 2,'a' :+ 'b') -unzipVectorial :: Functor f => f (a, b) -> (f a, f b) -unzipVectorial abs' = (fst <$> abs', snd <$> abs') - --- | Transpose nested structures. --- --- >>> transposeVectorial ((1 :+ 2) :+ (3 :+ 4)) --- (1 :+ 3) :+ (2 :+ 4) -transposeVectorial - :: (Representable f, Representable g) => f (g a) -> g (f a) -transposeVectorial xss = - tabulate (\j -> tabulate (\i -> index (index xss i) j)) - -{- | A structure of a list's values, in `Foldable` order, when it has -exactly as many as the basis. - ->>> fromListVectorial "ab" :: Maybe (Complex Char) -Just ('a' :+ 'b') ->>> fromListVectorial "abc" :: Maybe (Complex Char) -Nothing --} -fromListVectorial :: forall f a. Vectorial f => [a] -> Maybe (f a) -fromListVectorial as = case mapAccumL fill as (tabulate @f (const ())) of - ([], filled) -> sequenceA filled - _ -> Nothing - where - fill (x : xs) () = (xs, Just x) - fill [] () = ([], Nothing) - --- | The zero vector. -zeroVectorial :: (Representable f, Num a) => f a -zeroVectorial = tabulate (const 0) - --- | The unit vector of a basis element. --- --- >>> unitVectorial True :: Complex Int --- 0 :+ 1 -unitVectorial :: (Representable f, Eq (Rep f), Num a) => Rep f -> f a -unitVectorial i = tabulate (\j -> if i == j then 1 else 0) - --- | Add vectors, strictly. -(^+^) :: (Vectorial f, Num a) => f a -> f a -> f a -(^+^) = zipWithVectorial' (+) -infixl 6 ^+^ - --- | Subtract vectors, strictly. -(^-^) :: (Vectorial f, Num a) => f a -> f a -> f a -(^-^) = zipWithVectorial' (-) -infixl 6 ^-^ - --- | Negate a vector, strictly. -negateVectorial :: (Vectorial f, Num a) => f a -> f a -negateVectorial = forced . fmap negate - --- | Scale a vector, strictly. --- --- >>> 2 *^ (1 :+ 2) --- 2 :+ 4 -(*^) :: (Vectorial f, Num a) => a -> f a -> f a -s *^ v = forced (fmap (s *) v) -infixl 7 *^ - --- | The dot product of vectors, summed strictly. --- --- >>> dotVectorial (1 :+ 2) (3 :+ 4) --- 11 -dotVectorial :: (Vectorial f, Num a) => f a -> f a -> a -dotVectorial u v = foldl' (+) 0 (zipWithVectorial (*) u v) - --- | The identity matrix, of rows of unit vectors. --- --- >>> identityVectorial :: Complex (Complex Int) --- (1 :+ 0) :+ (0 :+ 1) -identityVectorial :: (Representable f, Eq (Rep f), Num a) => f (f a) -identityVectorial = tabulate unitVectorial - --- | The outer product of vectors, a matrix of rows. --- --- >>> outerVectorial (1 :+ 2) (3 :+ 4) --- (3 :+ 4) :+ (6 :+ 8) -outerVectorial - :: (Representable f, Representable g, Num a) => f a -> g a -> f (g a) -outerVectorial u v = fmap (\a -> fmap (a *) v) u - --- | Multiply a matrix, of rows, by a vector. --- --- >>> ((1 :+ 2) :+ (3 :+ 4)) !* (1 :+ 1) --- 3 :+ 7 -(!*) :: (Vectorial f, Vectorial g, Num a) => f (g a) -> g a -> f a -m !* v = forced (fmap (`dotVectorial` v) m) -infixl 7 !* - --- | Multiply matrices, of rows. --- --- >>> ((1 :+ 2) :+ (3 :+ 4)) !*! ((0 :+ 1) :+ (1 :+ 0)) --- (2 :+ 1) :+ (4 :+ 3) -(!*!) - :: (Vectorial f, Vectorial g, Vectorial h, Num a) - => f (g a) -> g (h a) -> f (h a) -m !*! n = fmap (transposeVectorial n !*) m -infixl 7 !*! - --- | A structure, with every value evaluated, in `Foldable` order. -forced :: Foldable f => f a -> f a -forced xs = foldr seq xs xs diff --git a/distributors-core/test/Properties/Homogeneous.hs b/distributors-core/test/Properties/Homogeneous.hs index 925de69a..572fc284 100644 --- a/distributors-core/test/Properties/Homogeneous.hs +++ b/distributors-core/test/Properties/Homogeneous.hs @@ -13,9 +13,7 @@ import Control.Lens (iview) import Control.Lens.Diopter import Control.Lens.Comonocle import Control.Monad ((<=<)) -import Data.Complex (Complex (..), imagPart, realPart) import Data.Functor.Compose (Compose (..)) -import Data.Functor.Rep (Representable (..)) import Data.Foldable (toList) import Data.List (transpose) import Data.Int (Int8) @@ -28,7 +26,6 @@ import Data.Profunctor.Monoidal.Cocartesian import Data.Proxy (Proxy (..)) import Data.Traversable.Homogeneous import Data.Traversable.Homogeneous.Enumerable -import Data.Traversable.Homogeneous.Vectorial import Data.Void import GHC.Generics (Par1 (..), (:*:) (..)) import Numeric.Natural (Natural) @@ -245,38 +242,6 @@ zipporahLaws = do homogeneousProperties :: Spec homogeneousProperties = do - describe "Vectorial" $ do - prop "zipWithVectorial zips position by position" $ - \(a :: Complex Int) (b :: Complex Int) -> - zipWithVectorial (-) a b - === (realPart a - realPart b) :+ (imagPart a - imagPart b) - prop "zipWithVectorial' agrees with zipWithVectorial" $ - \(a :: Complex Int) (b :: Complex Int) -> - zipWithVectorial' (*) a b === zipWithVectorial (*) a b - prop "fromListVectorial . toList = Just" $ \(a :: Complex Int) -> - fromListVectorial (toList a) === Just a - prop "transposeVectorial . transposeVectorial = id" $ - \(a :: Complex (Complex Int)) -> - transposeVectorial (transposeVectorial a) === a - prop "toList v = map (index v) basisVectorial" $ \(v :: Complex Int) -> - toList v === map (index v) (basisVectorial @Complex) - prop "toList v = map (index v) basisVectorial, composed" $ - \(v :: Complex (Complex Int)) -> - let w = Compose v - in toList w === map (index w) (basisVectorial @(Compose Complex Complex)) - it "_Basis numbers basis elements as their ordinals" $ - map (fst . iview (indexComonocle (_Basis @Complex))) - (basisVectorial @Complex) - `shouldBe` [0, 1] - it "ordinals invert basis elements" $ - map (ordinalVectorial @Complex) (basisVectorial @Complex) - `shouldBe` map Just [0, 1] - prop "transposeVectorial . outerVectorial u = outerVectorial u . flip" $ - \(u :: Complex Int) (v :: Complex Int) -> - transposeVectorial (outerVectorial u v) === outerVectorial v u - prop "dotVectorial is the sum of products" $ - \(a :: Complex Int) (b :: Complex Int) -> - dotVectorial a b === sum (zipWithVectorial (*) a b) describe "Enumerator" $ do let ix = genEnumerator arbitrary :: Gen (Enumerator Bool Int) ixf = genEnumerator (applyFun <$> arbitrary) From 364a02b925cd2019ac92f19ab131a66b3025dda5 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Mon, 9 Nov 2026 05:19:17 -0800 Subject: [PATCH 091/130] Add enumerateFromThen, enumerateFromTo & enumerateFromThenTo Enum-like progressions of an Enumerable sum's copies, & their Comonocle counterparts, walking Integer progressions of copy indices until an index has no copy, holding the first argument's focus. Tested against Prelude's enumFromThen, enumFromTo & enumFromThenTo on Int8. Co-Authored-By: Claude Opus 5.5 --- distributors-core/CHANGELOG.md | 6 +++ .../src/Control/Lens/Comonocle.hs | 33 ++++++++++++ .../Traversable/Homogeneous/Enumerable.hs | 51 +++++++++++++++++++ .../test/Properties/Homogeneous.hs | 21 ++++++++ 4 files changed, 111 insertions(+) diff --git a/distributors-core/CHANGELOG.md b/distributors-core/CHANGELOG.md index 4d9f6f07..1d6295e7 100644 --- a/distributors-core/CHANGELOG.md +++ b/distributors-core/CHANGELOG.md @@ -14,6 +14,12 @@ - `AComonocle`, `withComonocle`, `cloneComonocle`, `mapComonocle`, `altComonocle`, `crossComonocle`, `indexComonocle` & `zipWithComonocle`; & `crossMonocle`. +- Enum-like functions of `Enumerable`s, `fromEnumerable`, `toEnumerable`, + `succEnumerable`, `predEnumerable`, `enumerateFrom`, `enumerateFromThen`, + `enumerateFromTo` & `enumerateFromThenTo`, & of `Comonocle`s, + `toEnumComonocle`, `succComonocle`, `predComonocle`, `enumerateComonocle`, + `enumerateFromThenComonocle`, `enumerateFromToComonocle` & + `enumerateFromThenToComonocle`. - `Homogeneous` & `Enumerable` instances for `Down`, `Min`, `Max`, `First`, `Last`, `Alt f`, `Ap f` & `IdentityT f`. - `Bool1` & `Ordering1`, in `Data.Traversable.Homogeneous`, single copies diff --git a/distributors-core/src/Control/Lens/Comonocle.hs b/distributors-core/src/Control/Lens/Comonocle.hs index 60cf5d35..56ef3ee4 100644 --- a/distributors-core/src/Control/Lens/Comonocle.hs +++ b/distributors-core/src/Control/Lens/Comonocle.hs @@ -25,6 +25,9 @@ module Control.Lens.Comonocle , succComonocle , predComonocle , enumerateComonocle + , enumerateFromThenComonocle + , enumerateFromToComonocle + , enumerateFromThenToComonocle , zipComonocle , zipWithComonocle , _Enumerable @@ -222,6 +225,36 @@ 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) diff --git a/distributors-core/src/Data/Traversable/Homogeneous/Enumerable.hs b/distributors-core/src/Data/Traversable/Homogeneous/Enumerable.hs index bddc3f3e..232b8649 100644 --- a/distributors-core/src/Data/Traversable/Homogeneous/Enumerable.hs +++ b/distributors-core/src/Data/Traversable/Homogeneous/Enumerable.hs @@ -17,6 +17,9 @@ module Data.Traversable.Homogeneous.Enumerable , succEnumerable , predEnumerable , enumerateFrom + , enumerateFromThen + , enumerateFromTo + , enumerateFromThenTo -- * Enumerator , Enumerator (..) ) where @@ -204,6 +207,54 @@ enumerateFrom x = case enumerably (pure (extractEnumerable x)) of Enumerator _ which select -> let go copy = maybe [] (: go (copy + 1)) (select copy) in 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 [from, fromEnumerable' y ..] + where + from = fromEnumerable' x + +{- | 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 . 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 indices = case enumerably (pure (extractEnumerable x)) of + Enumerator _ _ select -> + let + go = \case + i : is | i >= 0, Just copy <- select (fromInteger i) -> copy : go is + _ -> [] + in go indices + {- | 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. diff --git a/distributors-core/test/Properties/Homogeneous.hs b/distributors-core/test/Properties/Homogeneous.hs index 572fc284..09a029c5 100644 --- a/distributors-core/test/Properties/Homogeneous.hs +++ b/distributors-core/test/Properties/Homogeneous.hs @@ -282,12 +282,33 @@ homogeneousProperties = do predComonocle _BoundedEnum 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 "zipDiopter homogenized is zipHomogeneous" $ \(xss :: [[Int]]) -> zipDiopter homogenized (Just . sum) ([1, 2] : xss) === zipHomogeneous (Just . sum) ([1, 2 :: Int] : xss) prop "zipWithDiopter manied is zipWithHomogeneous" $ \(xs :: [Int]) ys -> zipWithDiopter manied (+) 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 fromEnumerable [(LT, ()), (EQ, ()), (GT, ())] `shouldBe` [0, 1, 2] prop "toEnumerable inverts fromEnumerable" $ \(c :: Char) -> From 9a5d7523da88eb4437fa8242caed1b6259453e88 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Mon, 9 Nov 2026 05:47:30 -0800 Subject: [PATCH 092/130] Fix Haddock links & typos, and cite parsec for infixP Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WcUfd5Fh5FyQ5nF9vxu83Z --- distributors-core/src/Control/Lens/Diopter.hs | 2 +- .../src/Data/Profunctor/Distributor.hs | 25 ++++--------------- .../src/Data/Profunctor/Monoidal.hs | 10 ++++---- .../Data/Profunctor/Monoidal/Cocartesian.hs | 2 +- .../src/Control/Lens/Grammar.hs | 10 ++++---- .../src/Control/Lens/Grammar/Symbol.hs | 2 +- .../src/Control/Lens/Grammar/Token.hs | 4 +-- .../src/Control/Lens/Grammar/TypeScript.hs | 1 - 8 files changed, 20 insertions(+), 36 deletions(-) diff --git a/distributors-core/src/Control/Lens/Diopter.hs b/distributors-core/src/Control/Lens/Diopter.hs index 14f93ac3..7e0ce97c 100644 --- a/distributors-core/src/Control/Lens/Diopter.hs +++ b/distributors-core/src/Control/Lens/Diopter.hs @@ -39,7 +39,7 @@ 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`. +Every `Control.Lens.Iso.Iso` and `Control.Lens.Monocle.Monocle` is a `Diopter`. `Diopter`s are isomorphic to t'Dioptrice's. -} diff --git a/distributors-core/src/Data/Profunctor/Distributor.hs b/distributors-core/src/Data/Profunctor/Distributor.hs index 14c22998..f5ae39c3 100644 --- a/distributors-core/src/Data/Profunctor/Distributor.hs +++ b/distributors-core/src/Data/Profunctor/Distributor.hs @@ -187,7 +187,7 @@ data SepBy p = SepBy {- | A t'SepBy' smart constructor, setting the `separateBy` field. -Beginning and ending delimitors will be no-ops, +Beginning and ending delimiters will be no-ops, except by modifier record updates `beginBy` or `endBy`. -} sepBy :: Applicative p => p () -> SepBy (p ()) sepBy = SepBy (pure ()) (pure ()) @@ -271,7 +271,7 @@ 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 +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. @@ -323,24 +323,9 @@ withOperators table p = foldl makeLevel p table (_,g):_ -> Just (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. - -} + -- 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 diff --git a/distributors-core/src/Data/Profunctor/Monoidal.hs b/distributors-core/src/Data/Profunctor/Monoidal.hs index a94b6d7f..8c6ed532 100644 --- a/distributors-core/src/Data/Profunctor/Monoidal.hs +++ b/distributors-core/src/Data/Profunctor/Monoidal.hs @@ -76,7 +76,7 @@ oneP = pure () 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 @@ -87,7 +87,7 @@ x >* y = lmap (const ()) x *> y 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 @@ -98,7 +98,7 @@ x *< y = x <* lmap (const ()) y 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` @@ -109,7 +109,7 @@ 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' @@ -162,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`. -} diff --git a/distributors-core/src/Data/Profunctor/Monoidal/Cocartesian.hs b/distributors-core/src/Data/Profunctor/Monoidal/Cocartesian.hs index 74487f9f..7e084f19 100644 --- a/distributors-core/src/Data/Profunctor/Monoidal/Cocartesian.hs +++ b/distributors-core/src/Data/Profunctor/Monoidal/Cocartesian.hs @@ -165,7 +165,7 @@ on sums, with these laws relating them. 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 `CocartesianChoice`. +out to be slightly more complex, necessitating `CocartesianChoice`. >>> :{ alternateF :: Functor f => Either (f a) (f b) -> f (Either a b) diff --git a/distributors-grammar/src/Control/Lens/Grammar.hs b/distributors-grammar/src/Control/Lens/Grammar.hs index fd66474b..b6850bb9 100644 --- a/distributors-grammar/src/Control/Lens/Grammar.hs +++ b/distributors-grammar/src/Control/Lens/Grammar.hs @@ -116,7 +116,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`. @@ -390,8 +390,8 @@ 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, @@ -437,11 +437,11 @@ which can recognize the larger class of recursively enumerable languages. Finally, `CtxGrammar`s support failure reporting and backtracking. This has no effect on `Control.Lens.Grammar.printG`, `Control.Lens.Grammar.parseG` or `Control.Lens.Grammar.unparseG`; -but it effects `Control.Lens.Grammar.parsecG` +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. t'Parsor' is an @LL(∞)@ parser. t'Parsector' is an @LL(1)@ parser. diff --git a/distributors-grammar/src/Control/Lens/Grammar/Symbol.hs b/distributors-grammar/src/Control/Lens/Grammar/Symbol.hs index 18af1e00..b0337cf8 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/Symbol.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/Symbol.hs @@ -41,7 +41,7 @@ class NonTerminalSymbol s where {- | A t'SepBy' smart constructor like `sepBy`, with a `terminal` argument. -Beginning and ending delimitors will be no-ops, +Beginning and ending delimiters will be no-ops, except by applying smart modifiers `beginWith` or `endWith`. -} sepWith :: (Applicative p, TerminalSymbol c (p ())) diff --git a/distributors-grammar/src/Control/Lens/Grammar/Token.hs b/distributors-grammar/src/Control/Lens/Grammar/Token.hs index 694606fb..22c0a786 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/Token.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/Token.hs @@ -253,14 +253,14 @@ such that the following invariants hold. > prop> notP . asIn = notAsIn > prop> notP . notAsIn = asIn -t'TokenClass' is the fixed point algebra of t`TokenExam`. +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. +-- | 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) diff --git a/distributors-json/src/Control/Lens/Grammar/TypeScript.hs b/distributors-json/src/Control/Lens/Grammar/TypeScript.hs index 5a1e4432..50862fb4 100644 --- a/distributors-json/src/Control/Lens/Grammar/TypeScript.hs +++ b/distributors-json/src/Control/Lens/Grammar/TypeScript.hs @@ -1325,7 +1325,6 @@ entityName = commas :: TsGrammatical p => p a a -> p [a] [a] commas item = orP [commas1 item, _Empty >? oneP] --- | At least one comma separated item. -- | 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)) From b12eef3d82e57b1423941cd057e3c01b461de3a5 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Mon, 9 Nov 2026 05:47:54 -0800 Subject: [PATCH 093/130] List distributors-grammar in the README; drop removed Bool1 & Ordering1 from the changelog Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WcUfd5Fh5FyQ5nF9vxu83Z --- README.md | 7 +++++-- distributors-core/CHANGELOG.md | 6 ++---- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 26bceb0a..a80c5892 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,12 @@ # distributors -Unifying parsers, printers & grammars, in two packages: +Unifying parsers, printers & grammars, in three packages: - [`distributors-core`](distributors-core): the `distributors` package, - of profunctor grammars, which parse, print & generate together. + 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. diff --git a/distributors-core/CHANGELOG.md b/distributors-core/CHANGELOG.md index 1d6295e7..e7cf96c4 100644 --- a/distributors-core/CHANGELOG.md +++ b/distributors-core/CHANGELOG.md @@ -22,10 +22,8 @@ `enumerateFromThenToComonocle`. - `Homogeneous` & `Enumerable` instances for `Down`, `Min`, `Max`, `First`, `Last`, `Alt f`, `Ap f` & `IdentityT f`. -- `Bool1` & `Ordering1`, in `Data.Traversable.Homogeneous`, single copies - tagged by a `Bool` or an `Ordering`, which are `Enumerable` & - `Monad`s, combining tags by conjunction or lexicographically; - & `Bool1` is a `BooleanAlgebra`. +- `Homogeneous` & `Enumerable` instances for `(,) e`, a copy for each tag + of a `Bounded` `Enum`, summed in a balanced tree. ### Bug Fixes From 5217e818d165c0ac5ab2ec33296d827557113196 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Mon, 9 Nov 2026 06:11:18 -0800 Subject: [PATCH 094/130] monocle combinators --- distributors-core/src/Control/Lens/Monocle.hs | 48 +++++++++++++++++++ .../test/Properties/Homogeneous.hs | 23 ++++++++- 2 files changed, 70 insertions(+), 1 deletion(-) diff --git a/distributors-core/src/Control/Lens/Monocle.hs b/distributors-core/src/Control/Lens/Monocle.hs index 95166575..6e907003 100644 --- a/distributors-core/src/Control/Lens/Monocle.hs +++ b/distributors-core/src/Control/Lens/Monocle.hs @@ -24,14 +24,20 @@ module Control.Lens.Monocle , crossMonocle , ditraversed , forevered + , zipMonocle + , zipWithMonocle + , replicateMonocle + , tabulateMonocle -- * Monocular , Monocular (..), runMonocular ) 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 Numeric.Natural (Natural) -- $setup -- >>> import Control.Lens @@ -104,6 +110,48 @@ ditraversed = unwrapPafb . ditraverse . WrapPafb 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 `Identity` @f@, +& `Control.Lens.Grate.cotraverseOf`, at `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 + {- | 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))) diff --git a/distributors-core/test/Properties/Homogeneous.hs b/distributors-core/test/Properties/Homogeneous.hs index 09a029c5..9c7aabc6 100644 --- a/distributors-core/test/Properties/Homogeneous.hs +++ b/distributors-core/test/Properties/Homogeneous.hs @@ -9,12 +9,16 @@ module Properties.Homogeneous (homogeneousProperties) where import Control.Applicative import Control.Arrow ((+++)) -import Control.Lens (iview) +import Control.Lens (iview, toListOf, traverseOf) import Control.Lens.Diopter import Control.Lens.Comonocle +import Control.Lens.Grate (cotraverseOf) +import Control.Lens.Monocle 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) @@ -291,6 +295,23 @@ homogeneousProperties = do \(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] + it "tabulateMonocle numbers foci left to right" $ + toListOf ditraversed (tabulateMonocle ditraversed id :: Complex Natural) + `shouldBe` [0, 1] prop "zipDiopter homogenized is zipHomogeneous" $ \(xss :: [[Int]]) -> zipDiopter homogenized (Just . sum) ([1, 2] : xss) === zipHomogeneous (Just . sum) ([1, 2 :: Int] : xss) From 7390735bed80eb66c3cde3cd8fd58bc64b10104f Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Mon, 9 Nov 2026 20:51:26 -0800 Subject: [PATCH 095/130] prismComonocle --- distributors-core/src/Control/Lens/Comonocle.hs | 12 +++++++++--- .../src/Data/Traversable/Homogeneous/Enumerable.hs | 14 +++++++++----- 2 files changed, 18 insertions(+), 8 deletions(-) diff --git a/distributors-core/src/Control/Lens/Comonocle.hs b/distributors-core/src/Control/Lens/Comonocle.hs index 56ef3ee4..dd5bf73c 100644 --- a/distributors-core/src/Control/Lens/Comonocle.hs +++ b/distributors-core/src/Control/Lens/Comonocle.hs @@ -22,6 +22,7 @@ module Control.Lens.Comonocle , indexComonocle , countComonocle , toEnumComonocle + , prismComonocle , succComonocle , predComonocle , enumerateComonocle @@ -137,9 +138,14 @@ Numbering diverges past a summand of infinitely many copies. (1,'a') -} indexComonocle :: AComonocle s t a b -> IndexedLens Natural s t a b -indexComonocle mon = withComonocle mon $ \split merge -> - ilens (\s -> let as = split s in (fromEnumerable as, extractEnumerable as)) - (\s b -> merge (b <$ split s)) +indexComonocle mon = withComonocle mon $ \split merge -> ilens + (((,) <$> fromEnumerable <*> extractEnumerable) . split) + (\s b -> merge (b <$ split s)) + +prismComonocle :: AComonocle s s a a -> Prism' (Natural, a) s +prismComonocle mon = withComonocle mon $ \split merge -> prism' + (((,) <$> fromEnumerable <*> extractEnumerable) . split) + (\(n,a) -> merge <$> toEnumerable a n) {- | Zip two sources of `AComonocle`, when they hold the same copy, dual to `Control.Lens.Grate.cotraverseOf`, which zips every `Monocle`. diff --git a/distributors-core/src/Data/Traversable/Homogeneous/Enumerable.hs b/distributors-core/src/Data/Traversable/Homogeneous/Enumerable.hs index 232b8649..73e43a5d 100644 --- a/distributors-core/src/Data/Traversable/Homogeneous/Enumerable.hs +++ b/distributors-core/src/Data/Traversable/Homogeneous/Enumerable.hs @@ -14,6 +14,7 @@ module Data.Traversable.Homogeneous.Enumerable , extractEnumerable , fromEnumerable , toEnumerable + , prismEnumerable , succEnumerable , predEnumerable , enumerateFrom @@ -162,6 +163,11 @@ fromEnumerable :: Enumerable f => f a -> Natural fromEnumerable = case enumerably (pure ()) of Enumerator _ which _ -> which +prismEnumerable :: Enumerable f => Prism' (Natural, a) (f a) +prismEnumerable = prism' + (liftA2 (,) fromEnumerable extractEnumerable) + (\(n,a) -> toEnumerable a n) + {- | The copy of an `Enumerable` sum at an index, if there is one, like `toEnum`, the inverse of `fromEnumerable`. @@ -216,9 +222,7 @@ stepping by the copy of another, like `enumFromThen`. [(GT,'x'),(EQ,'x'),(LT,'x')] -} enumerateFromThen :: Enumerable f => f a -> f b -> [f a] -enumerateFromThen x y = copiesAt x [from, fromEnumerable' y ..] - where - from = fromEnumerable' x +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`. @@ -247,13 +251,13 @@ fromEnumerable' = toInteger . fromEnumerable until an index has none. -} copiesAt :: Enumerable f => f a -> [Integer] -> [f a] -copiesAt x indices = case enumerably (pure (extractEnumerable x)) of +copiesAt x ixes = case enumerably (pure (extractEnumerable x)) of Enumerator _ _ select -> let go = \case i : is | i >= 0, Just copy <- select (fromInteger i) -> copy : go is _ -> [] - in go indices + in go ixes {- | t'Enumerator' numbers the copies of a sum of products, from 0, left to right, & products row by row, both ways: From c7326d0f3f11a91723bdc288dc6a728937e95378 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Tue, 10 Nov 2026 05:32:07 -0800 Subject: [PATCH 096/130] enumerable --- .../src/Control/Lens/Comonocle.hs | 58 +++++++------- .../Traversable/Homogeneous/Enumerable.hs | 77 ++++++++----------- .../src/Control/Lens/Grammar/Json.hs | 4 +- 3 files changed, 67 insertions(+), 72 deletions(-) diff --git a/distributors-core/src/Control/Lens/Comonocle.hs b/distributors-core/src/Control/Lens/Comonocle.hs index dd5bf73c..3ed48563 100644 --- a/distributors-core/src/Control/Lens/Comonocle.hs +++ b/distributors-core/src/Control/Lens/Comonocle.hs @@ -21,10 +21,8 @@ module Control.Lens.Comonocle , crossComonocle , indexComonocle , countComonocle - , toEnumComonocle - , prismComonocle + , fromComonocle , succComonocle - , predComonocle , enumerateComonocle , enumerateFromThenComonocle , enumerateFromToComonocle @@ -39,8 +37,10 @@ module Control.Lens.Comonocle 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 @@ -128,7 +128,14 @@ crossComonocle x y = withComonocle y $ \g h -> comonocle $ Comonocular (\(s,u) -> Compose (fmap (\a -> fmap (a,) (g u)) (e s))) - (\(Compose bds) -> (f (fmap (fst . extractEnumerable) bds), h (fmap snd (extractEnumerable bds)))) + (\(Compose x) -> f >*< h $ + let + (_, y) = review fromEnumerable x + z = fmap (review fromEnumerable) x + in + (fmap (fst . snd) z, fmap snd y) + ) + -- (\(Compose bds) -> (f (fmap (fst . extractEnumerable) bds), h (fmap snd (extractEnumerable bds)))) {- | The `Control.Lens.Indexed.IndexedLens` of `AComonocle`, indexed by which copy is held, numbered from 0, left to right. @@ -139,13 +146,21 @@ Numbering diverges past a summand of infinitely many copies. -} indexComonocle :: AComonocle s t a b -> IndexedLens Natural s t a b indexComonocle mon = withComonocle mon $ \split merge -> ilens - (((,) <$> fromEnumerable <*> extractEnumerable) . split) + (review fromEnumerable . split) (\s b -> merge (b <$ split s)) -prismComonocle :: AComonocle s s a a -> Prism' (Natural, a) s -prismComonocle mon = withComonocle mon $ \split merge -> prism' - (((,) <$> fromEnumerable <*> extractEnumerable) . split) - (\(n,a) -> merge <$> toEnumerable a n) +{- | The copy of `AComonocle` at an index, holding a focus, if there is one, +like `toEnum`, & inverse to `indexComonocle`. + +>>> toEnumComonocle _BoundedEnum () 2 :: Maybe Ordering +Just GT +>>> toEnumComonocle _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 `Monocle`. @@ -186,17 +201,6 @@ countComonocle mon = withComonocle mon $ \split _ -> copies split copies _ = case enumerably (pure () :: Enumerator () ()) :: Enumerator (f ()) (f ()) of Enumerator count _ _ -> count -{- | The copy of `AComonocle` at an index, holding a focus, if there is one, -like `toEnum`, & inverse to `indexComonocle`. - ->>> toEnumComonocle _BoundedEnum () 2 :: Maybe Ordering -Just GT ->>> toEnumComonocle _BoundedEnum () 3 :: Maybe Ordering -Nothing --} -toEnumComonocle :: AComonocle s t a b -> b -> Natural -> Maybe t -toEnumComonocle mon b copy = withComonocle mon $ \_ merge -> merge <$> toEnumerable b copy - {- | The next copy of `AComonocle`, holding the same focus, if there is one, like `succ`. @@ -204,11 +208,8 @@ if there is one, like `succ`. Just GT >>> succComonocle _BoundedEnum GT Nothing --} -succComonocle :: AComonocle s s a a -> s -> Maybe s -succComonocle mon s = withComonocle mon $ \split merge -> merge <$> succEnumerable (split s) -{- | The previous copy of `AComonocle`, holding the same focus, +The previous copy of `AComonocle`, holding the same focus, if there is one, like `pred`. >>> predComonocle _BoundedEnum EQ @@ -216,8 +217,13 @@ Just LT >>> predComonocle _BoundedEnum LT Nothing -} -predComonocle :: AComonocle s s a a -> s -> Maybe s -predComonocle mon s = withComonocle mon $ \split merge -> merge <$> predEnumerable (split s) +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 copies of `AComonocle` from one onward, holding the same focus, like `enumFrom`. diff --git a/distributors-core/src/Data/Traversable/Homogeneous/Enumerable.hs b/distributors-core/src/Data/Traversable/Homogeneous/Enumerable.hs index 73e43a5d..90292ef6 100644 --- a/distributors-core/src/Data/Traversable/Homogeneous/Enumerable.hs +++ b/distributors-core/src/Data/Traversable/Homogeneous/Enumerable.hs @@ -11,12 +11,8 @@ Portability : non-portable module Data.Traversable.Homogeneous.Enumerable ( -- * Enumerable Enumerable (..) - , extractEnumerable , fromEnumerable - , toEnumerable - , prismEnumerable , succEnumerable - , predEnumerable , enumerateFrom , enumerateFromThen , enumerateFromTo @@ -27,6 +23,7 @@ module Data.Traversable.Homogeneous.Enumerable 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 @@ -149,59 +146,51 @@ instance (Enum e, Bounded e) => Enumerable ((,) e) where where mid = (lo + hi) `div` 2 --- | The copy which an `Enumerable` sum holds. -extractEnumerable :: Enumerable f => f a -> a -extractEnumerable = runForget (enumerably (Forget id)) - {- | Which copy an `Enumerable` sum holds, numbered from 0, left to right, like `fromEnum`. ->>> fromEnumerable (GT, 'x') -2 --} -fromEnumerable :: Enumerable f => f a -> Natural -fromEnumerable = - case enumerably (pure ()) of Enumerator _ which _ -> which - -prismEnumerable :: Enumerable f => Prism' (Natural, a) (f a) -prismEnumerable = prism' - (liftA2 (,) fromEnumerable extractEnumerable) - (\(n,a) -> toEnumerable a n) +>>> view fromEnumerable (GT, 'x') +(2, 'x') -{- | The copy of an `Enumerable` sum at an index, if there is one, -like `toEnum`, the inverse of `fromEnumerable`. +Also, the copy of an `Enumerable` sum at an index, if there is one, +like `toEnum`. ->>> [toEnumerable 'x' i | i <- [0..3]] :: [Maybe (Ordering, Char)] +>>> [review fromEnumerable (i,'x') | i <- [0..3]] :: [Maybe (Ordering, Char)] [Just (LT,'x'),Just (EQ,'x'),Just (GT,'x'),Nothing] -} -toEnumerable :: Enumerable f => a -> Natural -> Maybe (f a) -toEnumerable a copy = - case enumerably (pure a) of Enumerator _ _ select -> select copy +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`. ->>> succEnumerable (EQ, 'x') +>>> view succEnumerable (EQ, 'x') Just (GT,'x') ->>> succEnumerable (GT, 'x') +>>> view succEnumerable (GT, 'x') Nothing --} -succEnumerable :: Enumerable f => f a -> Maybe (f a) -succEnumerable x = case enumerably (pure (extractEnumerable x)) of - Enumerator _ which select -> select (which x + 1) - -{- | The previous copy of an `Enumerable` sum, if there is one, like `pred`. ->>> predEnumerable (EQ, 'x') +>>> review succEnumerable (EQ, 'x') Just (LT,'x') ->>> predEnumerable (LT, 'x') +>>> review succEnumerable (LT, 'x') Nothing -} -predEnumerable :: Enumerable f => f a -> Maybe (f a) -predEnumerable x = case enumerably (pure (extractEnumerable x)) of - Enumerator _ which select -> case which x of - 0 -> Nothing - copy -> select (copy - 1) +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 copies of an `Enumerable` sum from one onward, like `enumFrom`. @@ -209,9 +198,9 @@ predEnumerable x = case enumerably (pure (extractEnumerable x)) of [(EQ,'x'),(GT,'x')] -} enumerateFrom :: Enumerable f => f a -> [f a] -enumerateFrom x = case enumerably (pure (extractEnumerable x)) of +enumerateFrom x = case enumerably (pure (review fromEnumerable x)) of Enumerator _ which select -> - let go copy = maybe [] (: go (copy + 1)) (select copy) in go (which x) + 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`. @@ -245,13 +234,13 @@ enumerateFromThenTo x y z = -- | The index of an `Enumerable` sum's copy, as an `Integer`. fromEnumerable' :: Enumerable f => f a -> Integer -fromEnumerable' = toInteger . fromEnumerable +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 (extractEnumerable x)) of +copiesAt x ixes = case enumerably (pure (snd (review fromEnumerable x))) of Enumerator _ _ select -> let go = \case diff --git a/distributors-json/src/Control/Lens/Grammar/Json.hs b/distributors-json/src/Control/Lens/Grammar/Json.hs index b6627b2e..7d567463 100644 --- a/distributors-json/src/Control/Lens/Grammar/Json.hs +++ b/distributors-json/src/Control/Lens/Grammar/Json.hs @@ -619,8 +619,8 @@ 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 (toEnumerable () 0) - in jsonEnumWith (fromIntegral . fromEnumerable . split) + let copies = maybe [] enumerateFrom (preview fromEnumerable (0,())) + in jsonEnumWith (fromIntegral . fst . review fromEnumerable . split) [(name a, a) | a <- map merge copies] {-# INLINE jsonEnum #-} From d4078ef53925092cd2a602437ae70800624ae5ea Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Tue, 10 Nov 2026 05:33:51 -0800 Subject: [PATCH 097/130] failBnf --- distributors-grammar/src/Control/Lens/Grammar/BackusNaur.hs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/distributors-grammar/src/Control/Lens/Grammar/BackusNaur.hs b/distributors-grammar/src/Control/Lens/Grammar/BackusNaur.hs index f1503a09..8b4146bc 100644 --- a/distributors-grammar/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 @@ -76,6 +76,10 @@ class BackusNaurForm bnf where ruleRec :: String -> (bnf -> bnf) -> bnf ruleRec _ = fix +-- | A nonterminal symbol to indicate a failure. +failBnf :: (BackusNaurForm bnf, DisjunctiveMonoid bnf) => String -> bnf +failBnf msg = rule msg falseP + {- | A t'Bnf' consists of a distinguished starting rule and a set of named rules. When a t'Bnf' supports `NonTerminalSymbol`s, then it supports the `BackusNaurForm` interface From 5e9765ad61853164735781946b6fd2571e86b589 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Tue, 10 Nov 2026 11:55:12 -0800 Subject: [PATCH 098/130] Update Comonocle.hs --- distributors-core/src/Control/Lens/Comonocle.hs | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/distributors-core/src/Control/Lens/Comonocle.hs b/distributors-core/src/Control/Lens/Comonocle.hs index 3ed48563..c1d083d2 100644 --- a/distributors-core/src/Control/Lens/Comonocle.hs +++ b/distributors-core/src/Control/Lens/Comonocle.hs @@ -128,14 +128,13 @@ crossComonocle x y = withComonocle y $ \g h -> comonocle $ Comonocular (\(s,u) -> Compose (fmap (\a -> fmap (a,) (g u)) (e s))) - (\(Compose x) -> f >*< h $ + (\(Compose i) -> f >*< h $ let - (_, y) = review fromEnumerable x - z = fmap (review fromEnumerable) x + (_, j) = review fromEnumerable i + k = fmap (review fromEnumerable) i in - (fmap (fst . snd) z, fmap snd y) + (fmap (fst . snd) k, fmap snd j) ) - -- (\(Compose bds) -> (f (fmap (fst . extractEnumerable) bds), h (fmap snd (extractEnumerable bds)))) {- | The `Control.Lens.Indexed.IndexedLens` of `AComonocle`, indexed by which copy is held, numbered from 0, left to right. From 8139bc1ed2749068920801728a0880df11fdaa01 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Thu, 12 Nov 2026 09:05:00 -0800 Subject: [PATCH 099/130] Fix the build: tests & docs of Enumerable & Comonocle optics The test suite & doctests still used toEnumComonocle, predComonocle, toEnumerable & predEnumerable, & applied fromEnumerable as a function, since they became the prisms fromEnumerable & fromComonocle & the partial isos succEnumerable & succComonocle. predEnumerable & predComonocle return, as their coPartialIsos. Examples run partial isos by withPartialIso, since view & review can't, & preview diverges on failure by Cochoice (->). Co-Authored-By: Claude Opus 5.5 --- distributors-core/CHANGELOG.md | 9 ++-- .../src/Control/Lens/Comonocle.hs | 31 ++++++++------ .../Traversable/Homogeneous/Enumerable.hs | 42 ++++++++++++------- .../test/Properties/Homogeneous.hs | 34 ++++++++------- 4 files changed, 70 insertions(+), 46 deletions(-) diff --git a/distributors-core/CHANGELOG.md b/distributors-core/CHANGELOG.md index e7cf96c4..2986c0f8 100644 --- a/distributors-core/CHANGELOG.md +++ b/distributors-core/CHANGELOG.md @@ -14,10 +14,11 @@ - `AComonocle`, `withComonocle`, `cloneComonocle`, `mapComonocle`, `altComonocle`, `crossComonocle`, `indexComonocle` & `zipWithComonocle`; & `crossMonocle`. -- Enum-like functions of `Enumerable`s, `fromEnumerable`, `toEnumerable`, - `succEnumerable`, `predEnumerable`, `enumerateFrom`, `enumerateFromThen`, - `enumerateFromTo` & `enumerateFromThenTo`, & of `Comonocle`s, - `toEnumComonocle`, `succComonocle`, `predComonocle`, `enumerateComonocle`, +- 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`, diff --git a/distributors-core/src/Control/Lens/Comonocle.hs b/distributors-core/src/Control/Lens/Comonocle.hs index c1d083d2..4fa45efe 100644 --- a/distributors-core/src/Control/Lens/Comonocle.hs +++ b/distributors-core/src/Control/Lens/Comonocle.hs @@ -23,6 +23,7 @@ module Control.Lens.Comonocle , countComonocle , fromComonocle , succComonocle + , predComonocle , enumerateComonocle , enumerateFromThenComonocle , enumerateFromToComonocle @@ -50,6 +51,7 @@ import Numeric.Natural (Natural) -- $setup -- >>> import Control.Lens +-- >>> import Control.Lens.PartialIso (withPartialIso) -- >>> import Data.Functor.Identity {- | `Comonocle`s are an optic dual to `Control.Lens.Monocle.Monocle`s, by sums, @@ -151,9 +153,9 @@ indexComonocle mon = withComonocle mon $ \split merge -> ilens {- | The copy of `AComonocle` at an index, holding a focus, if there is one, like `toEnum`, & inverse to `indexComonocle`. ->>> toEnumComonocle _BoundedEnum () 2 :: Maybe Ordering +>>> preview (fromComonocle _BoundedEnum) (2, ()) :: Maybe Ordering Just GT ->>> toEnumComonocle _BoundedEnum () 3 :: Maybe Ordering +>>> preview (fromComonocle _BoundedEnum) (3, ()) :: Maybe Ordering Nothing -} fromComonocle :: AComonocle s s a a -> Prism' (Natural, a) s @@ -201,19 +203,11 @@ countComonocle mon = withComonocle mon $ \split _ -> copies split Enumerator count _ _ -> count {- | The next copy of `AComonocle`, holding the same focus, -if there is one, like `succ`. +if there is one, like `succ`, & conversely, the previous copy, like `pred`. ->>> succComonocle _BoundedEnum EQ +>>> withPartialIso (succComonocle _BoundedEnum) const EQ Just GT ->>> succComonocle _BoundedEnum GT -Nothing - -The previous copy of `AComonocle`, holding the same focus, -if there is one, like `pred`. - ->>> predComonocle _BoundedEnum EQ -Just LT ->>> predComonocle _BoundedEnum LT +>>> withPartialIso (succComonocle _BoundedEnum) const GT Nothing -} succComonocle :: AComonocle s s a a -> PartialIso' s s @@ -224,6 +218,17 @@ succComonocle mon = (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`. + +>>> withPartialIso (predComonocle _BoundedEnum) const EQ +Just LT +>>> withPartialIso (predComonocle _BoundedEnum) const 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`. diff --git a/distributors-core/src/Data/Traversable/Homogeneous/Enumerable.hs b/distributors-core/src/Data/Traversable/Homogeneous/Enumerable.hs index 90292ef6..dda84589 100644 --- a/distributors-core/src/Data/Traversable/Homogeneous/Enumerable.hs +++ b/distributors-core/src/Data/Traversable/Homogeneous/Enumerable.hs @@ -13,6 +13,7 @@ module Data.Traversable.Homogeneous.Enumerable Enumerable (..) , fromEnumerable , succEnumerable + , predEnumerable , enumerateFrom , enumerateFromThen , enumerateFromTo @@ -40,6 +41,10 @@ import Numeric.Natural (Natural) import Data.Profunctor.Monoidal.Cocartesian import Data.Traversable.Homogeneous +-- $setup +-- >>> import Control.Lens (preview, review) +-- >>> import Control.Lens.PartialIso (withPartialIso) + {- | A class of `Enumerable` countable sums of single copies, which are `Homogeneous`, & sequenced by sums alone. @@ -124,10 +129,10 @@ instance Enumerable f => Enumerable (Rec1 f) where numbered by its tag's `fromEnum`, from `minBound`, & summed in a balanced tree, built lazily. ->>> map fromEnumerable [(False, 'a'), (True, 'b')] -[0,1] ->>> map fromEnumerable [(LT, 'a'), (EQ, 'b'), (GT, 'c')] -[0,1,2] +>>> 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, @@ -149,13 +154,13 @@ instance (Enum e, Bounded e) => Enumerable ((,) e) where {- | Which copy an `Enumerable` sum holds, numbered from 0, left to right, like `fromEnum`. ->>> view fromEnumerable (GT, 'x') -(2, 'x') +>>> review fromEnumerable (GT, 'x') +(2,'x') Also, the copy of an `Enumerable` sum at an index, if there is one, like `toEnum`. ->>> [review fromEnumerable (i,'x') | i <- [0..3]] :: [Maybe (Ordering, Char)] +>>> [preview fromEnumerable (i,'x') | i <- [0..3]] :: [Maybe (Ordering, Char)] [Just (LT,'x'),Just (EQ,'x'),Just (GT,'x'),Nothing] -} @@ -168,16 +173,12 @@ fromEnumerable = prism' (liftA2 (,) from' extract') to' 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`. +{- | The next copy of an `Enumerable` sum, if there is one, like `succ`, +& conversely, the previous copy, like `pred`. ->>> view succEnumerable (EQ, 'x') +>>> withPartialIso succEnumerable const (EQ, 'x') Just (GT,'x') ->>> view succEnumerable (GT, 'x') -Nothing - ->>> review succEnumerable (EQ, 'x') -Just (LT,'x') ->>> review succEnumerable (LT, 'x') +>>> withPartialIso succEnumerable const (GT, 'x') Nothing -} succEnumerable :: Enumerable f => PartialIso' (f a) (f a) @@ -192,6 +193,17 @@ succEnumerable = partialIso succ' pred' 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`. + +>>> withPartialIso predEnumerable const (EQ, 'x') +Just (LT,'x') +>>> withPartialIso predEnumerable const (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') diff --git a/distributors-core/test/Properties/Homogeneous.hs b/distributors-core/test/Properties/Homogeneous.hs index 9c7aabc6..0fb2550d 100644 --- a/distributors-core/test/Properties/Homogeneous.hs +++ b/distributors-core/test/Properties/Homogeneous.hs @@ -9,11 +9,12 @@ module Properties.Homogeneous (homogeneousProperties) where import Control.Applicative import Control.Arrow ((+++)) -import Control.Lens (iview, toListOf, traverseOf) +import Control.Lens (iview, preview, review, toListOf, traverseOf) import Control.Lens.Diopter import Control.Lens.Comonocle import Control.Lens.Grate (cotraverseOf) import Control.Lens.Monocle +import Control.Lens.PartialIso (withPartialIso) import Control.Monad ((<=<)) import Data.Functor.Compose (Compose (..)) import Data.Complex (Complex (..)) @@ -278,12 +279,15 @@ homogeneousProperties = do describe "Comonocle & Diopter combinators" $ do prop "countComonocle _BoundedEnum is the number of values" $ countComonocle (_BoundedEnum @Int8) === 256 .&&. countComonocle (_BoundedEnum @Bool) === 2 - prop "toEnumComonocle _BoundedEnum inverts indexComonocle" $ \(e :: Int8) -> - toEnumComonocle _BoundedEnum () (fst (iview (indexComonocle _BoundedEnum) e)) === Just e + 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) -> - succComonocle _BoundedEnum e === if e == maxBound then Nothing else Just (succ e) + withPartialIso (succComonocle _BoundedEnum) const e + === if e == maxBound then Nothing else Just (succ e) prop "predComonocle _BoundedEnum is pred, but at minBound" $ \(e :: Int8) -> - predComonocle _BoundedEnum e === if e == minBound then Nothing else Just (pred e) + 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" $ @@ -331,20 +335,22 @@ homogeneousProperties = do all ((== c) . snd) (take 600 (enumerateFromThenTo (e, c) (e', ()) (maxBound, ()))) it "numbers copies left to right" $ - map fromEnumerable [(LT, ()), (EQ, ()), (GT, ())] `shouldBe` [0, 1, 2] - prop "toEnumerable inverts fromEnumerable" $ \(c :: Char) -> - map (toEnumerable c) [0 .. 3] + 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 fromEnumerable (toEnumerable c 2 :: Maybe (Ordering, Char)) - === Just 2 + .&&. fmap (review fromEnumerable) + (preview fromEnumerable (2, c) :: Maybe (Ordering, Char)) + === Just (2, c) prop "fromEnumerable is fromEnum, from minBound" $ \(e :: Int8) (c :: Char) -> - fromEnumerable (e, c) - === fromIntegral (fromEnum e - fromEnum (minBound :: Int8)) + review fromEnumerable (e, c) + === (fromIntegral (fromEnum e - fromEnum (minBound :: Int8)), c) prop "succEnumerable is succ, but at maxBound" $ \(e :: Ordering) (c :: Char) -> - succEnumerable (e, c) + 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) -> - predEnumerable (e, c) + 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 ..]] From 540cf484b401de8c5018fc63fbeadf473a3d1ec6 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Thu, 12 Nov 2026 09:40:05 -0800 Subject: [PATCH 100/130] Ditraversal: Monocles by homogeneous products A Ditraversal a b s t splits a source into a Traversable & Distributive shape of foci, & merges a target from one; ditraversal builds a Monocle of it by ditraversed, & withDitraversal converts AMonocle to its split & merge. Ditraversal a b is Monoidal, multiplying shapes by GHC.Generics' :*: with unit U1, from Par1, as Dioptrice does, so withDitraversal runs the Monocular on it, needing no counting or reflection; it diverges for infinitely many foci. Co-Authored-By: Claude Opus 5.5 --- distributors-core/CHANGELOG.md | 3 + distributors-core/src/Control/Lens/Monocle.hs | 58 +++++++++++++++++++ .../test/Properties/Homogeneous.hs | 18 +++++- 3 files changed, 78 insertions(+), 1 deletion(-) diff --git a/distributors-core/CHANGELOG.md b/distributors-core/CHANGELOG.md index 2986c0f8..bfa4dffd 100644 --- a/distributors-core/CHANGELOG.md +++ b/distributors-core/CHANGELOG.md @@ -14,6 +14,9 @@ - `AComonocle`, `withComonocle`, `cloneComonocle`, `mapComonocle`, `altComonocle`, `crossComonocle`, `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` & diff --git a/distributors-core/src/Control/Lens/Monocle.hs b/distributors-core/src/Control/Lens/Monocle.hs index 6e907003..28d38b46 100644 --- a/distributors-core/src/Control/Lens/Monocle.hs +++ b/distributors-core/src/Control/Lens/Monocle.hs @@ -30,6 +30,8 @@ module Control.Lens.Monocle , tabulateMonocle -- * Monocular , Monocular (..), runMonocular + -- * Ditraversal + , Ditraversal (..), ditraversal, withDitraversal ) where import Control.Lens hiding (Traversing) @@ -37,11 +39,13 @@ 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 that generalizes @@ -171,3 +175,57 @@ instance Applicative (Monocular a b s) where {- | 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 `:*:`, with unit `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/test/Properties/Homogeneous.hs b/distributors-core/test/Properties/Homogeneous.hs index 0fb2550d..e84275c4 100644 --- a/distributors-core/test/Properties/Homogeneous.hs +++ b/distributors-core/test/Properties/Homogeneous.hs @@ -9,7 +9,7 @@ module Properties.Homogeneous (homogeneousProperties) where import Control.Applicative import Control.Arrow ((+++)) -import Control.Lens (iview, preview, review, toListOf, traverseOf) +import Control.Lens (iview, over, preview, review, toListOf, traverseOf) import Control.Lens.Diopter import Control.Lens.Comonocle import Control.Lens.Grate (cotraverseOf) @@ -313,6 +313,22 @@ homogeneousProperties = do 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] From 91cfb0713508bedb3c54ecfa5b4b46a6910713fa Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Thu, 12 Nov 2026 09:52:44 -0800 Subject: [PATCH 101/130] PartialIso fails by Filterable, without Cochoice PartialIso drops its Cochoice constraint: it chooses whether its pattern matches by Choice, & fails in either direction by Filterable, emptying with catMaybes (pure Nothing) & filtering with mapMaybe. partialIso is the action dimapMaybe on p a (f b), as WrappedPafb is Choice & Cochoice, like coPrism is the action ?<. So preview, ^?, has & toListOf terminate on a PartialIso which fails, rather than looping in Cochoice (->), & preview of coPartialIso runs one backwards; >?< is unchanged. PartialIso's haddock shows, by tested examples, which combinators run a PartialIso, & why review, over, set & view don't; & corrects its claim of an isomorphism with PartialExchange, which is a retract instead: withPartialIso is a retraction with section partialIso, so clonePartialIso is idempotent, but not the identity, since a Prism passes a mismatch through, where its cloned partial functions fail. Properties test that preview, coPartialIso, traverseOf & clonePartialIso agree with withPartialIso, terminating, for partialIso, satisfied, nulled, notNulled, a Prism & a coPrism. Enumerable's & Comonocle's succ & pred examples run by preview again. Ditraversal's haddock names the types :*: & U1 unambiguously. Co-Authored-By: Claude Opus 5.5 --- distributors-core/CHANGELOG.md | 5 + distributors-core/distributors.cabal | 1 + .../src/Control/Lens/Comonocle.hs | 9 +- distributors-core/src/Control/Lens/Monocle.hs | 2 +- .../src/Control/Lens/PartialIso.hs | 102 ++++++++++++++++-- .../Traversable/Homogeneous/Enumerable.hs | 9 +- distributors-core/test/Main.hs | 2 + .../test/Properties/PartialIso.hs | 63 +++++++++++ 8 files changed, 175 insertions(+), 18 deletions(-) create mode 100644 distributors-core/test/Properties/PartialIso.hs diff --git a/distributors-core/CHANGELOG.md b/distributors-core/CHANGELOG.md index bfa4dffd..1db08db7 100644 --- a/distributors-core/CHANGELOG.md +++ b/distributors-core/CHANGELOG.md @@ -36,6 +36,11 @@ ### Breaking Changes +- `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)@, like `coPrism`. + Its action `>?<` on `Choice` & `Cochoice` profunctors is unchanged. - `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 diff --git a/distributors-core/distributors.cabal b/distributors-core/distributors.cabal index ac3a8d46..243496c8 100644 --- a/distributors-core/distributors.cabal +++ b/distributors-core/distributors.cabal @@ -179,6 +179,7 @@ test-suite test main-is: Main.hs other-modules: Properties.Homogeneous + Properties.PartialIso Paths_distributors autogen-modules: Paths_distributors diff --git a/distributors-core/src/Control/Lens/Comonocle.hs b/distributors-core/src/Control/Lens/Comonocle.hs index 4fa45efe..569aa35e 100644 --- a/distributors-core/src/Control/Lens/Comonocle.hs +++ b/distributors-core/src/Control/Lens/Comonocle.hs @@ -51,7 +51,6 @@ import Numeric.Natural (Natural) -- $setup -- >>> import Control.Lens --- >>> import Control.Lens.PartialIso (withPartialIso) -- >>> import Data.Functor.Identity {- | `Comonocle`s are an optic dual to `Control.Lens.Monocle.Monocle`s, by sums, @@ -205,9 +204,9 @@ countComonocle mon = withComonocle mon $ \split _ -> copies split {- | The next copy of `AComonocle`, holding the same focus, if there is one, like `succ`, & conversely, the previous copy, like `pred`. ->>> withPartialIso (succComonocle _BoundedEnum) const EQ +>>> preview (succComonocle _BoundedEnum) EQ Just GT ->>> withPartialIso (succComonocle _BoundedEnum) const GT +>>> preview (succComonocle _BoundedEnum) GT Nothing -} succComonocle :: AComonocle s s a a -> PartialIso' s s @@ -221,9 +220,9 @@ succComonocle mon = {- | The previous copy of `AComonocle`, holding the same focus, if there is one, like `pred`, & conversely, the next copy, like `succ`. ->>> withPartialIso (predComonocle _BoundedEnum) const EQ +>>> preview (predComonocle _BoundedEnum) EQ Just LT ->>> withPartialIso (predComonocle _BoundedEnum) const LT +>>> preview (predComonocle _BoundedEnum) LT Nothing -} predComonocle :: AComonocle s s a a -> PartialIso' s s diff --git a/distributors-core/src/Control/Lens/Monocle.hs b/distributors-core/src/Control/Lens/Monocle.hs index 28d38b46..d102bf80 100644 --- a/distributors-core/src/Control/Lens/Monocle.hs +++ b/distributors-core/src/Control/Lens/Monocle.hs @@ -190,7 +190,7 @@ data Ditraversal a b s t where 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 `:*:`, with unit `U1`, +{- | 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 diff --git a/distributors-core/src/Control/Lens/PartialIso.hs b/distributors-core/src/Control/Lens/PartialIso.hs index b3a90631..14ff5af7 100644 --- a/distributors-core/src/Control/Lens/PartialIso.hs +++ b/distributors-core/src/Control/Lens/PartialIso.hs @@ -63,6 +63,9 @@ import Control.Monad import Data.Profunctor import Witherable +-- $setup +-- >>> import Control.Lens + {- | The `dimapMaybe` function endows `Choice` & `Cochoice` "partial profunctors" with an action `>?<` of `PartialIso`s. @@ -82,12 +85,94 @@ dimapMaybe f g = 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 t'PartialExchange's. +Every `Control.Lens.Iso.Iso`, `Control.Lens.Prism.Prism` & `coPrism` +is a `PartialIso`. + +__N.B.__ t'PartialExchange' is a retract of `PartialIso`: +`withPartialIso` is a retraction, with `partialIso` its section, +recovering the partial functions which build a `PartialIso`. + +> prop> withPartialIso (partialIso f g) PartialExchange = PartialExchange f g + +But they aren't isomorphic, since a `PartialIso` may be more than +its partial functions, as a `Control.Lens.Prism.Prism` is, below. +Rebuilding a `PartialIso` from its partial functions, +by `clonePartialIso`, is idempotent, but not the identity. + +> prop> clonePartialIso pattern = withPartialIso pattern partialIso +> prop> clonePartialIso (clonePartialIso pattern) = clonePartialIso pattern + +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, where its partial functions, +cloned by `clonePartialIso`, fail; so it isn't its own clone. + +>>> traverseOf _Just (Just . succ) Nothing +Just Nothing +>>> traverseOf (clonePartialIso _Just) (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 & `coPrism`s. + +>>> preview (halve . halve) 12 +Just 3 +>>> preview (_Just . halve) (Just 4) +Just 2 +>>> preview (halve . coPrism _Just) 6 +Just (Just 3) -} type PartialIso s t a b = forall p f. - (Choice p, Cochoice p, Applicative f, Filterable f) + (Choice p, Applicative f, Filterable f) => p a (f b) -> p s (f t) {- | @@ -140,10 +225,13 @@ instance Cochoice (PartialExchange a b) where unright (PartialExchange f g) = PartialExchange (f . Right) (either (pure Nothing) Just <=< g) -{- | Build a `PartialIso`. -} +{- | Build a `PartialIso` from its partial functions, +matching forwards & building backwards, +as the action `dimapMaybe` on @p a (f b)@, +like `coPrism` is the action `?<`. +-} partialIso :: (s -> Maybe a) -> (b -> Maybe t) -> PartialIso s t a b -partialIso f g = - unright . iso (maybe (Left ()) Right . f =<<) (mapMaybe g) . right' +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. -} diff --git a/distributors-core/src/Data/Traversable/Homogeneous/Enumerable.hs b/distributors-core/src/Data/Traversable/Homogeneous/Enumerable.hs index dda84589..e0e1d671 100644 --- a/distributors-core/src/Data/Traversable/Homogeneous/Enumerable.hs +++ b/distributors-core/src/Data/Traversable/Homogeneous/Enumerable.hs @@ -43,7 +43,6 @@ import Data.Traversable.Homogeneous -- $setup -- >>> import Control.Lens (preview, review) --- >>> import Control.Lens.PartialIso (withPartialIso) {- | A class of `Enumerable` countable sums of single copies, which are `Homogeneous`, & sequenced by sums alone. @@ -176,9 +175,9 @@ fromEnumerable = prism' (liftA2 (,) from' extract') to' {- | The next copy of an `Enumerable` sum, if there is one, like `succ`, & conversely, the previous copy, like `pred`. ->>> withPartialIso succEnumerable const (EQ, 'x') +>>> preview succEnumerable (EQ, 'x') Just (GT,'x') ->>> withPartialIso succEnumerable const (GT, 'x') +>>> preview succEnumerable (GT, 'x') Nothing -} succEnumerable :: Enumerable f => PartialIso' (f a) (f a) @@ -196,9 +195,9 @@ succEnumerable = partialIso succ' pred' {- | The previous copy of an `Enumerable` sum, if there is one, like `pred`, & conversely, the next copy, like `succ`. ->>> withPartialIso predEnumerable const (EQ, 'x') +>>> preview predEnumerable (EQ, 'x') Just (LT,'x') ->>> withPartialIso predEnumerable const (LT, 'x') +>>> preview predEnumerable (LT, 'x') Nothing -} predEnumerable :: Enumerable f => PartialIso' (f a) (f a) diff --git a/distributors-core/test/Main.hs b/distributors-core/test/Main.hs index c44794fc..30147e52 100644 --- a/distributors-core/test/Main.hs +++ b/distributors-core/test/Main.hs @@ -6,10 +6,12 @@ import Data.Profunctor.Types (Star (..)) import Test.Hspec import Properties.Homogeneous +import Properties.PartialIso main :: IO () main = hspec $ do describe "Homogeneous" homogeneousProperties + describe "PartialIso" partialIsoProperties describe "meander" meanderProperties meanderProperties :: Spec diff --git a/distributors-core/test/Properties/PartialIso.hs b/distributors-core/test/Properties/PartialIso.hs new file mode 100644 index 00000000..879c33e2 --- /dev/null +++ b/distributors-core/test/Properties/PartialIso.hs @@ -0,0 +1,63 @@ +module Properties.PartialIso (partialIsoProperties) where + +import Control.Lens (preview, traverseOf) +import Control.Lens.PartialIso +import Test.Hspec +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 "a coPrism" (coPrism _Just :: PartialIso' Int (Maybe Int)) + checkTraverse "a coPrism" (coPrism _Just :: PartialIso' Int (Maybe Int)) + checkPartialIso "a Prism" (_Just :: PartialIso' (Maybe Int) Int) + describe "a Prism" $ + prop "traverseOf passes a mismatch through, unlike its clone" $ + \(Fun _ f :: Fun Int (Maybe Int)) -> within second $ + traverseOf _Just f Nothing === Just Nothing + .&&. traverseOf (clonePartialIso _Just) f Nothing === Nothing + +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 From 487c14e2039be83a530a793e046417dd97efce03 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Thu, 12 Nov 2026 10:27:44 -0800 Subject: [PATCH 102/130] core alg fixes --- distributors-core/CHANGELOG.md | 8 +++++ distributors-core/src/Control/Lens/Bifocal.hs | 9 +++-- .../src/Control/Lens/Comonocle.hs | 2 +- distributors-core/src/Control/Lens/Monocle.hs | 4 +-- distributors-core/src/Control/Lens/Wither.hs | 6 ++-- .../src/Data/Monoid/Disjunctive.hs | 2 -- .../src/Data/Profunctor/Filtrator.hs | 36 +++++++++++++------ .../Data/Profunctor/Monoidal/Cocartesian.hs | 8 +++++ .../Traversable/Homogeneous/Enumerable.hs | 2 +- 9 files changed, 54 insertions(+), 23 deletions(-) diff --git a/distributors-core/CHANGELOG.md b/distributors-core/CHANGELOG.md index 1db08db7..70ea27a7 100644 --- a/distributors-core/CHANGELOG.md +++ b/distributors-core/CHANGELOG.md @@ -41,6 +41,14 @@ `PartialIso` which fails to match, rather than looping in `Cochoice (->)`. `partialIso` is the action `dimapMaybe` on @p a (f b)@, like `coPrism`. 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 diff --git a/distributors-core/src/Control/Lens/Bifocal.hs b/distributors-core/src/Control/Lens/Bifocal.hs index 1c33cd6f..e287e8e2 100644 --- a/distributors-core/src/Control/Lens/Bifocal.hs +++ b/distributors-core/src/Control/Lens/Bifocal.hs @@ -50,6 +50,7 @@ Every one of the following is a `Bifocal`. * `Control.Lens.Iso.Iso` * `Control.Lens.Prism.Prism` +* `Control.Lens.PartialIso.PartialIso` & `Control.Lens.PartialIso.coPrism` * `Control.Lens.Monocle.Monocle` * `Control.Lens.Diopter.Diopter` * `Prismoid` & `Filtroid` @@ -64,13 +65,15 @@ type Bifocal s t a b = forall p f. 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. -} +{- | `Prismoid`s generalize `Control.Lens.Prism.Prism`s +& `Control.Lens.Diopter.Diopter`s, combining them, +& every `Prismoid` is a `Bifocal`. -} 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. -} +{- | An optic for `Filtrator`s, `Filtroid`s generalize +`Control.Lens.PartialIso.coPrism`s, & every `Filtroid` is a `Bifocal`. -} type Filtroid s t a b = forall p f. (Filtrator p, Filterable f) => p a (f b) -> p s (f t) diff --git a/distributors-core/src/Control/Lens/Comonocle.hs b/distributors-core/src/Control/Lens/Comonocle.hs index 569aa35e..6b5ae2d9 100644 --- a/distributors-core/src/Control/Lens/Comonocle.hs +++ b/distributors-core/src/Control/Lens/Comonocle.hs @@ -163,7 +163,7 @@ fromComonocle mon = withComonocle mon $ \split merge -> prism' (fmap merge . preview fromEnumerable) {- | Zip two sources of `AComonocle`, when they hold the same copy, -dual to `Control.Lens.Grate.cotraverseOf`, which zips every `Monocle`. +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) diff --git a/distributors-core/src/Control/Lens/Monocle.hs b/distributors-core/src/Control/Lens/Monocle.hs index d102bf80..847f1c6c 100644 --- a/distributors-core/src/Control/Lens/Monocle.hs +++ b/distributors-core/src/Control/Lens/Monocle.hs @@ -116,8 +116,8 @@ 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 `Identity` @f@, -& `Control.Lens.Grate.cotraverseOf`, at `Identity` @g@. +`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] diff --git a/distributors-core/src/Control/Lens/Wither.hs b/distributors-core/src/Control/Lens/Wither.hs index 67f14dc7..c33cd3bc 100644 --- a/distributors-core/src/Control/Lens/Wither.hs +++ b/distributors-core/src/Control/Lens/Wither.hs @@ -35,7 +35,7 @@ import Data.Profunctor.Sieve import Prelude hiding (filter) import Witherable -{- | `Wither`s extends `Control.Lens.Traversal.Traversal`s by filtering. +{- | `Wither`s extend `Control.Lens.Traversal.Traversal`s by filtering. Every one of the following is a `Wither`. @@ -50,8 +50,8 @@ 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 -{- | `Witheroid`s generalize `Wither`s. -Every `Control.Lens.Prism.Prism` is a `Witheroid`. +{- | `Witheroid`s generalize `Control.Lens.Prism.Prism`s, +& every `Witheroid` is a `Wither`, at the `Choice` @(->)@. -} type Witheroid s t a b = forall p f. (Choice p, Alternative f) diff --git a/distributors-core/src/Data/Monoid/Disjunctive.hs b/distributors-core/src/Data/Monoid/Disjunctive.hs index e9dbab4b..8f0406da 100644 --- a/distributors-core/src/Data/Monoid/Disjunctive.hs +++ b/distributors-core/src/Data/Monoid/Disjunctive.hs @@ -251,8 +251,6 @@ instance DisjunctiveMonoid (f a) => DisjunctiveMonoid (Alt f a) where instance DisjunctiveMonoid (f a) => DisjunctiveMonoid (Ap f a) where falseP = Ap falseP Ap x >|< Ap y = Ap (x >|< y) -instance (Applicative f, DisjunctiveMonoid (f k), Monoid k) - => KleeneStarAlgebra (Ap f k) instance DisjunctiveMonoid (f (g a)) => DisjunctiveMonoid (Compose f g a) where falseP = Compose falseP Compose x >|< Compose y = Compose (x >|< y) diff --git a/distributors-core/src/Data/Profunctor/Filtrator.hs b/distributors-core/src/Data/Profunctor/Filtrator.hs index 0b11bb21..4806ca10 100644 --- a/distributors-core/src/Data/Profunctor/Filtrator.hs +++ b/distributors-core/src/Data/Profunctor/Filtrator.hs @@ -29,18 +29,37 @@ import Witherable {- | The `Filtrator` class extends `Cochoice`, as well as `Filterable`, adding the `filtrate` method, -which is an oplax monoidal structure morphism dual to -`Data.Profunctor.Monoidal.Cocartesian.>+<`. +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` @@ -92,11 +111,6 @@ 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) diff --git a/distributors-core/src/Data/Profunctor/Monoidal/Cocartesian.hs b/distributors-core/src/Data/Profunctor/Monoidal/Cocartesian.hs index 7e084f19..606e7185 100644 --- a/distributors-core/src/Data/Profunctor/Monoidal/Cocartesian.hs +++ b/distributors-core/src/Data/Profunctor/Monoidal/Cocartesian.hs @@ -163,6 +163,14 @@ on sums, with these laws relating them. > 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`. diff --git a/distributors-core/src/Data/Traversable/Homogeneous/Enumerable.hs b/distributors-core/src/Data/Traversable/Homogeneous/Enumerable.hs index e0e1d671..3b4e603b 100644 --- a/distributors-core/src/Data/Traversable/Homogeneous/Enumerable.hs +++ b/distributors-core/src/Data/Traversable/Homogeneous/Enumerable.hs @@ -50,7 +50,7 @@ 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 `Distributor`. +`homogeneously`, by a `Data.Profunctor.Distributor.Distributor`. > prop> enumerably = homogeneously From 536570a90be42881a1dbc71e5888b42f00456ac5 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Thu, 12 Nov 2026 13:17:03 -0800 Subject: [PATCH 103/130] optics big update Prismoids and more --- distributors-core/CHANGELOG.md | 37 ++- distributors-core/distributors.cabal | 1 + distributors-core/src/Control/Lens/Bifocal.hs | 94 +------ .../src/Control/Lens/Comonocle.hs | 49 +++- distributors-core/src/Control/Lens/Diopter.hs | 19 +- distributors-core/src/Control/Lens/Grate.hs | 7 +- distributors-core/src/Control/Lens/Monocle.hs | 44 ++- .../src/Control/Lens/PartialIso.hs | 79 +++++- .../src/Control/Lens/Prismoid.hs | 266 ++++++++++++++++++ distributors-core/src/Control/Lens/Wither.hs | 64 +++-- .../src/Data/Profunctor/Distributor.hs | 40 ++- .../src/Data/Traversable/Homogeneous.hs | 25 ++ .../test/Properties/Homogeneous.hs | 48 +++- .../test/Properties/PartialIso.hs | 32 ++- 14 files changed, 636 insertions(+), 169 deletions(-) create mode 100644 distributors-core/src/Control/Lens/Prismoid.hs diff --git a/distributors-core/CHANGELOG.md b/distributors-core/CHANGELOG.md index 70ea27a7..63b12b9b 100644 --- a/distributors-core/CHANGELOG.md +++ b/distributors-core/CHANGELOG.md @@ -28,6 +28,23 @@ `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 balanced 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`, with + `somed`, `opted`, `lefted`, `righted`, `chained1` & `chained`. +- `Plasmoid`s, families of optics separated by a `SepBy`, which are + `Prismoid`s by `noSep`: `chained1` & `chained` are `Plasmoid`s, taking a + `SepBy`; & new `severaled`, `severaled1` & `intercalated`, separated like + `several`, `several1` & `intercalateP`; & `operated`, an expression of + an operator table, like `withOperators`. +- `Prismatoid`, the concrete form of `Prismoid`s, a partial `Dioptrice`, + with `APrismoid`, `prismoid`, `withPrismoid`, `mapPrismoid`, + `clonePrismoid` & `runPrismatoid`. +- `PartialExchange` is a `DisjunctiveMonoid`, choosing by first success + in either direction, of which `satisfied` is a homomorphism; + `withOperators` tries its unary operators by it. ### Bug Fixes @@ -36,10 +53,28 @@ ### Breaking Changes +- `Bifocal`s need `(Alternator p, Applicative f, Filterable f)`, dropping + `Filtrator p` & `Alternative f`, which `Filterable f` provides, as it + does `PartialIso`'s `Cochoice`. +- `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. + +- `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)@, like `coPrism`. + `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 & diff --git a/distributors-core/distributors.cabal b/distributors-core/distributors.cabal index 243496c8..25dcc855 100644 --- a/distributors-core/distributors.cabal +++ b/distributors-core/distributors.cabal @@ -36,6 +36,7 @@ library Control.Lens.Internal.Distributor.Orphanage Control.Lens.Monocle Control.Lens.PartialIso + Control.Lens.Prismoid Control.Lens.Wither Data.Monoid.Disjunctive Data.Profunctor.Distributor diff --git a/distributors-core/src/Control/Lens/Bifocal.hs b/distributors-core/src/Control/Lens/Bifocal.hs index e287e8e2..a60e22bb 100644 --- a/distributors-core/src/Control/Lens/Bifocal.hs +++ b/distributors-core/src/Control/Lens/Bifocal.hs @@ -12,25 +12,12 @@ module Control.Lens.Bifocal ( -- * Bifocal Bifocal , ABifocal + , Binocular (..), runBinocular -- * Combinators , bifocal - , mapBifocal - , cloneBifocal , withBifocal - -- * Binocular - , Binocular (..), runBinocular - -- * Prismoid - , Prismoid - , somed - , opted - , lefted - , righted - , chained1 - , chained - -- * Filtroid - , Filtroid - , unlefted - , unrighted + , cloneBifocal + , mapBifocal ) where import Control.Applicative @@ -45,39 +32,25 @@ import Data.Profunctor.Filtrator import Witherable {- | `Bifocal`s are bidirectional parser optics. +Writing ⊂ for "every one is a", -Every one of the following is a `Bifocal`. +`Control.Lens.Prismoid.Prismoid` ∪ `Control.Lens.PartialIso.PartialIso` ⊂ `Bifocal`, -* `Control.Lens.Iso.Iso` -* `Control.Lens.Prism.Prism` -* `Control.Lens.PartialIso.PartialIso` & `Control.Lens.PartialIso.coPrism` -* `Control.Lens.Monocle.Monocle` -* `Control.Lens.Diopter.Diopter` -* `Prismoid` & `Filtroid` +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'Binocular's. -} type Bifocal s t a b = forall p f. - (Alternator p, Filtrator p, Alternative f, Filterable f) + (Alternator p, Applicative 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 `Control.Lens.Prism.Prism`s -& `Control.Lens.Diopter.Diopter`s, combining them, -& every `Prismoid` is a `Bifocal`. -} -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 -`Control.Lens.PartialIso.coPrism`s, & every `Filtroid` is a `Bifocal`. -} -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 t'Binocular'. -} bifocal :: Binocular a b s t -> Bifocal s t a b bifocal bif = unwrapPafb . runBinocular bif . WrapPafb @@ -94,53 +67,6 @@ 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) diff --git a/distributors-core/src/Control/Lens/Comonocle.hs b/distributors-core/src/Control/Lens/Comonocle.hs index 6b5ae2d9..a5b17826 100644 --- a/distributors-core/src/Control/Lens/Comonocle.hs +++ b/distributors-core/src/Control/Lens/Comonocle.hs @@ -12,6 +12,7 @@ module Control.Lens.Comonocle ( -- * Comonocle Comonocle , AComonocle + , Comonocular (..), runComonocular -- * Combinators , comonocle , withComonocle @@ -21,6 +22,7 @@ module Control.Lens.Comonocle , crossComonocle , indexComonocle , countComonocle + , copiesComonocle , fromComonocle , succComonocle , predComonocle @@ -32,8 +34,6 @@ module Control.Lens.Comonocle , zipWithComonocle , _Enumerable , _BoundedEnum - -- * Comonocular - , Comonocular (..), runComonocular ) where import Control.Applicative (Alternative) @@ -56,14 +56,19 @@ import Numeric.Natural (Natural) {- | `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. -Every `Control.Lens.Iso.Iso` is a `Comonocle`, -& every `Comonocle` is a `Control.Lens.Lens.Lens`, +Writing ⊂ for "every one is a", + +`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. +`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) @@ -201,6 +206,40 @@ countComonocle mon = withComonocle mon $ \split _ -> copies split 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`. diff --git a/distributors-core/src/Control/Lens/Diopter.hs b/distributors-core/src/Control/Lens/Diopter.hs index 7e0ce97c..21b5b0d7 100644 --- a/distributors-core/src/Control/Lens/Diopter.hs +++ b/distributors-core/src/Control/Lens/Diopter.hs @@ -12,6 +12,7 @@ module Control.Lens.Diopter ( -- * Diopter Diopter , ADiopter + , Dioptrice (..), runDioptrice -- * Combinators , diopter , withDiopter @@ -23,8 +24,6 @@ module Control.Lens.Diopter , zipDiopter , zipWithDiopter , transposeDiopter - -- * Dioptrice - , Dioptrice (..), runDioptrice ) where import Control.Applicative (Alternative) @@ -37,11 +36,21 @@ import Data.Void import GHC.Generics {- | `Diopter`s are an optic that generalizes -`Control.Lens.Bifocal.Bifocal`s and `Control.Lens.Traversal.Traversal`s. +`Control.Lens.Monocle.Monocle`s, of products, +& `Control.Lens.Comonocle.Comonocle`s, of sums, +to countable sums of countable products. +Writing ⊂ for "every one is a", + +`Control.Lens.Monocle.Monocle` ∪ `Control.Lens.Comonocle.Comonocle` +⊂ `Diopter` ⊂ +`Control.Lens.Traversal.Traversal` ∩ `Control.Lens.Prismoid.Prismoid`. -Every `Control.Lens.Iso.Iso` and `Control.Lens.Monocle.Monocle` is a `Diopter`. +`Diopter`s are isomorphic to t'Dioptrice's, whose shapes are `Homogeneous`, +so these inclusions mirror those of the optics' shapes, -`Diopter`s are isomorphic to t'Dioptrice's. +(`Traversable` ∩ `Data.Distributive.Distributive`) +∪ `Data.Traversable.Homogeneous.Enumerable.Enumerable` +⊂ `Homogeneous`. -} type Diopter s t a b = forall p f. (Distributor p, Applicative f) diff --git a/distributors-core/src/Control/Lens/Grate.hs b/distributors-core/src/Control/Lens/Grate.hs index a096c32f..a191f0ca 100644 --- a/distributors-core/src/Control/Lens/Grate.hs +++ b/distributors-core/src/Control/Lens/Grate.hs @@ -15,6 +15,7 @@ module Control.Lens.Grate ( -- * Grate Grate , AGrate + , Grating (..) -- * Combinators , grate , withGrate @@ -26,8 +27,6 @@ module Control.Lens.Grate , distributeOf , collectOf , distributing - -- * Grating - , Grating (..) ) where import Data.Distributive @@ -40,7 +39,9 @@ import Data.Profunctor.Monoidal {- | `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`. +Writing ⊂ for "every one is a", + +`Control.Lens.Iso.Iso` ⊂ `Control.Lens.Monocle.Monocle` ⊂ `Grate`. `Grate`s are isomorphic to t'Grating's. -} diff --git a/distributors-core/src/Control/Lens/Monocle.hs b/distributors-core/src/Control/Lens/Monocle.hs index 847f1c6c..82ea4f22 100644 --- a/distributors-core/src/Control/Lens/Monocle.hs +++ b/distributors-core/src/Control/Lens/Monocle.hs @@ -15,12 +15,14 @@ module Control.Lens.Monocle ( -- * Monocle Monocle , AMonocle + , Monocular (..), runMonocular + , Ditraversal (..), ditraversal, withDitraversal -- * Combinators , monocle , withMonocle , cloneMonocle - , imprism , mapMonocle + , imprism , crossMonocle , ditraversed , forevered @@ -28,10 +30,7 @@ module Control.Lens.Monocle , zipWithMonocle , replicateMonocle , tabulateMonocle - -- * Monocular - , Monocular (..), runMonocular - -- * Ditraversal - , Ditraversal (..), ditraversal, withDitraversal + , fociMonocle ) where import Control.Lens hiding (Traversing) @@ -48,12 +47,18 @@ import Numeric.Natural (Natural) -- >>> import Data.Foldable (toList) -- >>> import Data.Functor.Identity -{- | `Monocle`s are an optic that generalizes -`Control.Lens.Traversal.Traversal`s & `Control.Lens.Grate.Grate`s. +{- | `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. +Writing ⊂ for "every one is a", -Every `Control.Lens.Iso.Iso` is a `Monocle`. +`Control.Lens.Iso.Iso` ⊂ `Monocle` ⊂ +`Control.Lens.Traversal.Traversal` ∩ `Control.Lens.Grate.Grate`. -`Monocle`s are isomorphic to t'Monocular's. +`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) @@ -156,6 +161,27 @@ 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))) diff --git a/distributors-core/src/Control/Lens/PartialIso.hs b/distributors-core/src/Control/Lens/PartialIso.hs index 14ff5af7..794b2f58 100644 --- a/distributors-core/src/Control/Lens/PartialIso.hs +++ b/distributors-core/src/Control/Lens/PartialIso.hs @@ -13,8 +13,7 @@ See Rendel & Ostermann, module Control.Lens.PartialIso ( -- * PartialIso - dimapMaybe - , PartialIso + PartialIso , PartialIso' , APartialIso , PartialExchange (PartialExchange) @@ -27,13 +26,14 @@ module Control.Lens.PartialIso , crossPartialIso , altPartialIso -- * Applicators + , dimapMaybe , (>?) , (?<) , (>?<) , (>~) , (~<) , (!=) - , coPrism + , filterPrism -- * Patterns , satisfied , nulled @@ -60,6 +60,7 @@ import Control.Lens.Internal.Profunctor import Control.Lens.Iso import Control.Lens.Prism import Control.Monad +import Data.Monoid.Disjunctive import Data.Profunctor import Witherable @@ -83,10 +84,13 @@ dimapMaybe f g = {- | `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. +by combining `Control.Lens.Prism.Prism`s, constructor patterns, +with `filterPrism`s, filter patterns. -Every `Control.Lens.Iso.Iso`, `Control.Lens.Prism.Prism` & `coPrism` -is a `PartialIso`. +Writing ⊂ for "every one is a", + +`Control.Lens.Iso.Iso` ∪ `Control.Lens.Prism.Prism` ∪ `filterPrism` +⊂ `PartialIso` ⊂ `Control.Lens.Bifocal.Bifocal`. __N.B.__ t'PartialExchange' is a retract of `PartialIso`: `withPartialIso` is a retraction, with `partialIso` its section, @@ -162,13 +166,13 @@ since t'Data.Functor.Identity.Identity' can't fail, so isn't `Filterable`; `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 & `coPrism`s. +& 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 . coPrism _Just) 6 +>>> preview (halve . filterPrism _Just) 6 Just (Just 3) -} type PartialIso s t a b = forall p f. @@ -224,11 +228,27 @@ instance Cochoice (PartialExchange a b) where PartialExchange (f . Left) (either Just (pure Nothing) <=< g) unright (PartialExchange f g) = PartialExchange (f . Right) (either (pure Nothing) Just <=< g) +{- | t'PartialExchange's choose by first success, in either direction, +& `falseP` fails in both, so `Data.Monoid.Disjunctive.orP` tries +the partial functions of `PartialIso`s in turn. + +`satisfied` is a homomorphism of `Data.Monoid.Disjunctive.BooleanAlgebra`s +of predicates, from `>|<` to `>|<`, & from `>&<` to composition. + +> prop> withPartialIso (satisfied (p >|< q)) PartialExchange = withPartialIso (satisfied p) PartialExchange >|< withPartialIso (satisfied q) PartialExchange +> prop> withPartialIso (satisfied falseP) PartialExchange = falseP +> prop> satisfied (p >&< q) = satisfied p . satisfied q +> prop> satisfied trueP = id +-} +instance DisjunctiveMonoid (PartialExchange a b s t) where + falseP = PartialExchange falseP falseP + PartialExchange f g >|< PartialExchange f' g' = + PartialExchange (f >|< f') (g >|< g') {- | Build a `PartialIso` from its partial functions, matching forwards & building backwards, as the action `dimapMaybe` on @p a (f b)@, -like `coPrism` is the action `?<`. +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 @@ -297,7 +317,14 @@ altPartialIso x y = (>?) pat = withPrism pat $ \f g -> dimap g (either id f) . right' infixl 4 >? -{- | Action of a coPrism on `Cochoice` `Profunctor`s. -} +{- | 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 @@ -340,11 +367,35 @@ by the `non` isomorphism. prop != def = non def ~< prop infix 6 != -{- | Action of a `coPrism` -on the composition of a `Profunctor` and `Filterable`. +{- | 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))@. -} -coPrism :: (Profunctor p, Filterable f) => APrism b a t s -> p a (f b) -> p s (f t) -coPrism p = unwrapPafb . (?<) p . WrapPafb +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. -} diff --git a/distributors-core/src/Control/Lens/Prismoid.hs b/distributors-core/src/Control/Lens/Prismoid.hs new file mode 100644 index 00000000..18bb6586 --- /dev/null +++ b/distributors-core/src/Control/Lens/Prismoid.hs @@ -0,0 +1,266 @@ +{- | +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 + -- * Combinators + , prismoid + , withPrismoid + , clonePrismoid + , mapPrismoid + , somed + , opted + , lefted + , righted + -- * Plasmoid + , Plasmoid + , chained1 + , chained + , severaled + , severaled1 + , intercalated + , operated + ) where + +import Control.Applicative +import Control.Lens +import Control.Lens.Internal.Profunctor +import Control.Lens.PartialIso +import Data.Monoid.Disjunctive (DisjunctiveMonoid (..)) +import Data.Profunctor.Distributor +import Data.Profunctor.Monoidal.Cocartesian +import Data.Traversable.Homogeneous +import Data.Void +import GHC.Exts (IsList (..)) +import GHC.Generics (Par1 (..), U1 (..), V1, (:*:) (..), (:+:) (..), (:.:) (..)) + +-- $setup +-- >>> import Control.Lens (Prism', prism') +-- >>> import Data.Bifunctor.Joker +-- >>> import Data.Char (digitToInt, isDigit) +-- >>> import Data.Functor.Identity (Identity (..)) +-- >>> import Data.Profunctor.Distributor (Assoc (..), Operator (..), noSep, sepBy) +-- >>> 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. Writing ⊂ for "every one is a", + +`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 `Control.Lens.PartialIso.clonePartialIso` 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. +-} +type Prismoid s t a b = forall p f. + (Alternator p, Applicative f) + => p a (f b) -> p s (f t) + +{- | A `Plasmoid` is a family of optics, separated by a t'SepBy', +which is an optic at the `Alternator` @p@ of its separators. + +Its separators are data-free, @p () ()@, so they place effects +between its foci, but never change what its source or target holds. +So without separators, by `noSep`, which is polymorphic in @p@, +a `Plasmoid` is a `Prismoid`, & its data is that `Prismoid`'s; +for any @plasmoid :: Plasmoid s t a b@, +@plasmoid noSep :: Prismoid s t a b@. + +>>> withPrismoid (severaled1 noSep :: Prismoid String String Char Char) $ \f _ -> fmap length (f "abc") +Just 3 +-} +type Plasmoid s t a b = forall p f. + (Alternator p, Applicative f) + => SepBy (p () ()) -> p a (f b) -> p s (f t) + +{- | `APrismoid` is monomorphically a `Prismoid`. -} +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 `APrismoid` on `Alternator`s. -} +mapPrismoid :: Alternator p => APrismoid s t a b -> p a b -> p s t +mapPrismoid pat = withPrismoid pat $ \f g -> runPrismatoid (Prismatoid f g) + +{- | 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 + +{- | Convert `APrismoid` to the pair of functions that characterize it. + +>>> withPrismoid somed $ \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 + +{- | One or more, like `someP`. -} +somed :: Prismoid [a] [b] a b +somed = unwrapPafb . someP . WrapPafb + +{- | Zero or more, separated by a t'SepBy', like `several`. -} +severaled :: (IsList s, IsList t) => Plasmoid s t (Item s) (Item t) +severaled sep = unwrapPafb . several (fmap (WrapPafb . rmap pure) sep) . WrapPafb + +{- | One or more, separated by a t'SepBy', like `several1`. + +>>> let digits = runJoker (severaled1 (sepBy (Joker (() <$ char ','))) (Joker (Identity <$> satisfy isDigit)) :: Joker ReadP String (Identity String)) +>>> [ds | (Identity ds, "") <- readP_to_S digits "1,2,3"] +["123"] +-} +severaled1 :: (IsList s, IsList t) => Plasmoid s t (Item s) (Item t) +severaled1 sep = unwrapPafb . several1 (fmap (WrapPafb . rmap pure) sep) . WrapPafb + +{- | Exactly some number of times, separated by a t'SepBy', +like `intercalateP`, or without separators, by `noSep`, like +`Data.Profunctor.Monoidal.replicateP`. -} +intercalated :: (AsEmpty s, Cons s s a a) => Int -> Plasmoid s s a a +intercalated n sep = + unwrapPafb . intercalateP n (fmap (WrapPafb . rmap pure) sep) . WrapPafb + +{- | An expression of `Operator`s, from a table of them, ordered from +highest to lowest precedence, like `withOperators`. An operator table, +like a t'SepBy', is of an `Alternator` @p@, its symbols data-free. + +>>> :{ +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 (Identity . Digit . digitToInt <$> satisfy isDigit) +>>> [e | (Identity e, "") <- readP_to_S (runJoker (operated [[plus]] digit)) "1+2+3"] +[Plus (Plus (Digit 1) (Digit 2)) (Digit 3)] +-} +operated + :: (Alternator p, Applicative f) + => [[Operator p a b]] -> p a (f b) -> p a (f b) +operated table = + unwrapPafb . withOperators (map (map wrapping) table) . WrapPafb + where + wrapping = \case + Infix assoc pat sym -> Infix assoc pat (WrapPafb (rmap pure sym)) + Prefix pat sym -> Prefix pat (WrapPafb (rmap pure sym)) + Postfix pat sym -> Postfix pat (WrapPafb (rmap pure sym)) + +{- | 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. +-} +chained1 + :: (forall x. x -> Either x x) + -> APartialIso a b (a,a) (b,b) + -> Plasmoid a b a b +chained1 assoc binPat sep = + unwrapPafb . chain1 assoc binPat (fmap (WrapPafb . rmap pure) sep) . 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 () () + -> Plasmoid a b a b +chained assoc binPat nilPat sep = + unwrapPafb . chain assoc binPat nilPat (fmap (WrapPafb . rmap pure) sep) . WrapPafb + +{- | 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) diff --git a/distributors-core/src/Control/Lens/Wither.hs b/distributors-core/src/Control/Lens/Wither.hs index c33cd3bc..2f07b016 100644 --- a/distributors-core/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,35 +31,55 @@ import Data.Profunctor.Sieve import Prelude hiding (filter) import Witherable +-- $setup +-- >>> import Control.Applicative (Alternative (..)) +-- >>> import Control.Lens +-- >>> import Control.Lens.PartialIso (clonePartialIso) + {- | `Wither`s extend `Control.Lens.Traversal.Traversal`s by filtering. +Writing ⊂ for "every one is a", -Every one of the following is a `Wither`. +`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 -{- | `Witheroid`s generalize `Control.Lens.Prism.Prism`s, -& every `Witheroid` is a `Wither`, at the `Choice` @(->)@. --} -type Witheroid s t a b = forall p f. - (Choice p, Alternative f) - => p a (f b) -> p s (f t) - {- | Clone `AWither` so that you can reuse the same 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`, +@witherPrism@ is `Control.Lens.PartialIso.clonePartialIso`, +a `Control.Lens.PartialIso.PartialIso`, for a `Filterable` @f@. + +>>> (withered . clonePartialIso _Just) (\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) @@ -80,16 +96,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/Profunctor/Distributor.hs b/distributors-core/src/Data/Profunctor/Distributor.hs index f5ae39c3..7c110822 100644 --- a/distributors-core/src/Data/Profunctor/Distributor.hs +++ b/distributors-core/src/Data/Profunctor/Distributor.hs @@ -130,6 +130,13 @@ with these laws relating them. > 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`. @@ -304,24 +311,27 @@ withOperators table p = foldl makeLevel p table tagSepP syms = orP [only i >? sym | (i, sym) <- zip [0 :: Int ..] syms] withPreP ops inner = - difoldr (partialIso fwd bwd) >? manyP (tagSepP (snd <$> ops)) >*< inner - where - fns = [patternFns pat | (pat, _) <- ops] - fwd x = orP - [ (\y -> (i,y)) <$> f x | (i, (f,_)) <- zip [0 :: Int ..] fns ] - bwd (i,y) = case drop i fns of - (_,g):_ -> Just (g y) - [] -> Nothing + difoldr (taggedP (,) id (fst <$> ops)) + >? manyP (tagSepP (snd <$> ops)) >*< inner withPostP ops inner = - difoldl (partialIso fwd bwd) >? inner >*< manyP (tagSepP (snd <$> ops)) + 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 = + case orP (zipWith exchange [0 ..] pats) of + PartialExchange fwd bwd -> partialIso fwd bwd where - fns = [patternFns pat | (pat, _) <- ops] - fwd x = orP - [ (\y -> (y,i)) <$> f x | (i, (f,_)) <- zip [0 :: Int ..] fns ] - bwd (y,i) = case drop i fns of - (_,g):_ -> Just (g y) - [] -> Nothing + exchange i pat = let (match, build) = patternFns pat in + PartialExchange (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@: diff --git a/distributors-core/src/Data/Traversable/Homogeneous.hs b/distributors-core/src/Data/Traversable/Homogeneous.hs index 5a174d7f..ec0c435c 100644 --- a/distributors-core/src/Data/Traversable/Homogeneous.hs +++ b/distributors-core/src/Data/Traversable/Homogeneous.hs @@ -26,6 +26,7 @@ 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 @@ -47,8 +48,26 @@ 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`. @@ -163,6 +182,12 @@ 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 diff --git a/distributors-core/test/Properties/Homogeneous.hs b/distributors-core/test/Properties/Homogeneous.hs index e84275c4..e261b997 100644 --- a/distributors-core/test/Properties/Homogeneous.hs +++ b/distributors-core/test/Properties/Homogeneous.hs @@ -9,8 +9,9 @@ module Properties.Homogeneous (homogeneousProperties) where import Control.Applicative import Control.Arrow ((+++)) -import Control.Lens (iview, over, preview, review, toListOf, traverseOf) +import Control.Lens (ReifiedLens (..), ReifiedPrism (..), _Just, iview, over, preview, review, set, toListOf, traverseOf, view) import Control.Lens.Diopter +import Control.Lens.Prismoid (APrismoid, clonePrismoid, lefted, severaled, severaled1, somed, withPrismoid) import Control.Lens.Comonocle import Control.Lens.Grate (cotraverseOf) import Control.Lens.Monocle @@ -25,6 +26,7 @@ import Data.Int (Int8) import Data.Maybe (fromMaybe) import Data.Monoid.Disjunctive import Data.Profunctor +import Data.Profunctor.Distributor (noSep) import Data.Profunctor.Monadic (Monadic) import Data.Profunctor.Monoidal (Monoidal) import Data.Profunctor.Monoidal.Cocartesian @@ -332,6 +334,50 @@ homogeneousProperties = do 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 somed) xs === roundTrip somed xs + .&&. roundTrip (clonePrismoid lefted) e === roundTrip lefted e + .&&. roundTrip (clonePrismoid _Just) m === roundTrip _Just m + .&&. roundTrip (clonePrismoid manied) xs === roundTrip manied 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 "severaled1 noSep is somed, & severaled noSep is manied" $ \(xs :: [Int]) -> + withPrismoid (severaled1 noSep :: APrismoid [Int] [Int] Int Int) (\match _ -> toList <$> match xs) + === withPrismoid somed (\match _ -> toList <$> match xs) + .&&. withPrismoid (severaled noSep :: APrismoid [Int] [Int] Int Int) (\match _ -> toList <$> match xs) + === withPrismoid manied (\match _ -> toList <$> match xs) + prop "somed matches one or more" $ \(xs :: [Int]) -> + withPrismoid somed (\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) diff --git a/distributors-core/test/Properties/PartialIso.hs b/distributors-core/test/Properties/PartialIso.hs index 879c33e2..67ea2151 100644 --- a/distributors-core/test/Properties/PartialIso.hs +++ b/distributors-core/test/Properties/PartialIso.hs @@ -1,7 +1,8 @@ module Properties.PartialIso (partialIsoProperties) where -import Control.Lens (preview, traverseOf) +import Control.Lens (preview, review, traverseOf, view) import Control.Lens.PartialIso +import Data.Monoid.Disjunctive import Test.Hspec import Test.Hspec.QuickCheck (prop) import Test.QuickCheck @@ -18,14 +19,39 @@ partialIsoProperties = do checkTraverse "nulled" (nulled :: PartialIso' [Int] ()) checkPartialIso "notNulled" (notNulled :: PartialIso' [Int] [Int]) checkTraverse "notNulled" (notNulled :: PartialIso' [Int] [Int]) - checkPartialIso "a coPrism" (coPrism _Just :: PartialIso' Int (Maybe Int)) - checkTraverse "a coPrism" (coPrism _Just :: PartialIso' Int (Maybe 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, unlike its clone" $ \(Fun _ f :: Fun Int (Maybe Int)) -> within second $ traverseOf _Just f Nothing === Just Nothing .&&. traverseOf (clonePartialIso _Just) f Nothing === Nothing + describe "satisfied, a homomorphism of predicates" $ do + prop "from >|< to >|< of PartialExchanges" $ + \(Fun _ p :: Fun Int Bool) (Fun _ q) x y -> + exchanged (satisfied (p >|< q)) x y + === exchanging + ( withPartialIso (satisfied p) PartialExchange + >|< withPartialIso (satisfied q) PartialExchange ) 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 + exchanged :: APartialIso s t a b -> s -> b -> (Maybe a, Maybe t) + exchanged pattern = exchanging (withPartialIso pattern PartialExchange) + exchanging :: PartialExchange a b s t -> s -> b -> (Maybe a, Maybe t) + exchanging (PartialExchange match build) s b = (match s, build b) halve :: PartialIso' Int Int halve = partialIso From 1512375604f3d43cb0768d9fd6454bfb13465bc0 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Thu, 12 Nov 2026 20:09:46 -0800 Subject: [PATCH 104/130] PartialMarket, separated, Spectacle-based ABifocal & optic docs - PartialIso: PartialMarket is its concrete form, isomorphic to it (Prisms & filterPrisms, passing through or failing); APartialIso by PartialMarket, so clonePartialIso is the identity; PartialExchange removed; Cochoice, Filtrator & DisjunctiveMonoid for PartialMarket; orPartialIso & emptyPartialIso; altPartialIso, crossPartialIso & >?< keep passing through; corrected PartialIso' laws & docs. - Prismoid: Plasmoid removed; separated runs any APrismoid with a SepBy; chained1, chained & intercalated are Prismoids; operated = withOperators. - ABifocal is by Spectacle shapes, fixing divergence of repeating Bifocals; Cotraversal renamed Diffraction. - Inclusion props for A-types; base >= 4.20 (GHC 9.10). Co-Authored-By: Claude Opus 5.5 --- distributors-core/CHANGELOG.md | 41 +- distributors-core/README.md | 44 ++ distributors-core/distributors.cabal | 7 +- distributors-core/package.yaml | 2 +- distributors-core/src/Control/Lens/Bifocal.hs | 116 +++++- .../src/Control/Lens/Comonocle.hs | 7 +- distributors-core/src/Control/Lens/Diopter.hs | 7 +- distributors-core/src/Control/Lens/Grate.hs | 52 ++- distributors-core/src/Control/Lens/Monocle.hs | 7 +- .../src/Control/Lens/PartialIso.hs | 385 ++++++++++++++---- .../src/Control/Lens/Prismoid.hs | 210 +++++++--- distributors-core/src/Control/Lens/Wither.hs | 18 +- .../src/Data/Profunctor/Distributor.hs | 7 +- .../src/Data/Profunctor/Filtrator.hs | 6 +- distributors-core/test/Main.hs | 2 + .../test/Properties/Homogeneous.hs | 61 ++- distributors-core/test/Properties/Parsing.hs | 75 ++++ .../test/Properties/PartialIso.hs | 142 ++++++- .../distributors-grammar.cabal | 6 +- distributors-grammar/package.yaml | 2 +- distributors-json/distributors-json.cabal | 8 +- distributors-json/package.yaml | 2 +- 22 files changed, 980 insertions(+), 227 deletions(-) create mode 100644 distributors-core/test/Properties/Parsing.hs diff --git a/distributors-core/CHANGELOG.md b/distributors-core/CHANGELOG.md index 63b12b9b..81dd7507 100644 --- a/distributors-core/CHANGELOG.md +++ b/distributors-core/CHANGELOG.md @@ -33,18 +33,28 @@ 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`, with - `somed`, `opted`, `lefted`, `righted`, `chained1` & `chained`. -- `Plasmoid`s, families of optics separated by a `SepBy`, which are - `Prismoid`s by `noSep`: `chained1` & `chained` are `Plasmoid`s, taking a - `SepBy`; & new `severaled`, `severaled1` & `intercalated`, separated like - `several`, `several1` & `intercalateP`; & `operated`, an expression of - an operator table, like `withOperators`. + `somed`, `opted`, `lefted`, `righted`, `chained1` & `chained`; & new + `intercalated`, like `replicateP`, & `operated`, an expression of an + operator table, like `withOperators`. +- `separated`, running any `APrismoid` with a `SepBy`, its separator + between consecutive foci, & its delimiters around them, so + `separated somed = several1`, `separated manied = several`, + `separated (intercalated n) = intercalateP n` & + `separated (chained1 assoc pat) = chain1 assoc pat`. - `Prismatoid`, the concrete form of `Prismoid`s, a partial `Dioptrice`, with `APrismoid`, `prismoid`, `withPrismoid`, `mapPrismoid`, `clonePrismoid` & `runPrismatoid`. -- `PartialExchange` is a `DisjunctiveMonoid`, choosing by first success - in either direction, of which `satisfied` is a homomorphism; - `withOperators` tries its unary operators by it. +- 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. ### Bug Fixes @@ -53,9 +63,22 @@ ### Breaking Changes +- `altPartialIso` & `crossPartialIso` 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 `somed` 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`. diff --git a/distributors-core/README.md b/distributors-core/README.md index 18cfd50a..9e3c9b7d 100644 --- a/distributors-core/README.md +++ b/distributors-core/README.md @@ -42,3 +42,47 @@ Some optics in this library are [grates, a new kind of optic](https://r6research ## 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/distributors-core/distributors.cabal b/distributors-core/distributors.cabal index 25dcc855..aa474cab 100644 --- a/distributors-core/distributors.cabal +++ b/distributors-core/distributors.cabal @@ -93,7 +93,7 @@ library ghc-options: -Wall -Wcompat -Widentities -Wincomplete-record-updates -Wincomplete-uni-patterns -Wmissing-export-lists -Wmissing-home-modules -Wpartial-fields -Wredundant-constraints build-depends: adjunctions >=4.4 && <5 - , base >=4.15 && <5 + , base >=4.20 && <5 , bifunctors >=5.5 && <6 , containers >=0.6 && <1 , contravariant >=1.5 && <2 @@ -158,7 +158,7 @@ test-suite doctests 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.15 && <5 + , base >=4.20 && <5 , bifunctors >=5.5 && <6 , containers >=0.6 && <1 , contravariant >=1.5 && <2 @@ -180,6 +180,7 @@ test-suite test main-is: Main.hs other-modules: Properties.Homogeneous + Properties.Parsing Properties.PartialIso Paths_distributors autogen-modules: @@ -228,7 +229,7 @@ test-suite test build-depends: QuickCheck >=2.14 && <3 , adjunctions >=4.4 && <5 - , base >=4.15 && <5 + , base >=4.20 && <5 , bifunctors >=5.5 && <6 , containers >=0.6 && <1 , contravariant >=1.5 && <2 diff --git a/distributors-core/package.yaml b/distributors-core/package.yaml index 0db3f36b..4e1f822f 100644 --- a/distributors-core/package.yaml +++ b/distributors-core/package.yaml @@ -19,7 +19,7 @@ description: Its grammars are in @distributors-grammar@. dependencies: -- base >= 4.15 && < 5 +- base >= 4.20 && < 5 - adjunctions >= 4.4 && < 5 - bifunctors >= 5.5 && < 6 - containers >= 0.6 && < 1 diff --git a/distributors-core/src/Control/Lens/Bifocal.hs b/distributors-core/src/Control/Lens/Bifocal.hs index a60e22bb..49779ae3 100644 --- a/distributors-core/src/Control/Lens/Bifocal.hs +++ b/distributors-core/src/Control/Lens/Bifocal.hs @@ -12,6 +12,7 @@ module Control.Lens.Bifocal ( -- * Bifocal Bifocal , ABifocal + , Spectacle (..), runSpectacle, spectacle, withSpectacle , Binocular (..), runBinocular -- * Combinators , bifocal @@ -24,16 +25,22 @@ import Control.Applicative import Control.Lens import Control.Lens.Internal.Profunctor import Control.Lens.PartialIso -import Data.Monoid.Disjunctive (DisjunctiveMonoid) +import Control.Monad ((>=>)) +import Data.Monoid.Disjunctive (DisjunctiveMonoid (..)) import Data.Profunctor import Data.Profunctor.Distributor import Data.Profunctor.Monoidal.Cocartesian import Data.Profunctor.Filtrator +import Data.Traversable.Homogeneous +import Data.Void +import GHC.Generics (Par1 (..), U1 (..), V1, (:*:) (..), (:+:) (..), (:.:) (..)) import Witherable -{- | `Bifocal`s are bidirectional parser optics. -Writing ⊂ for "every one is a", +-- $setup +-- >>> import Control.Lens (_Just) +-- >>> import Control.Lens.PartialIso (clonePartialIso) +{- | `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`, @@ -41,15 +48,19 @@ so every `Control.Lens.Iso.Iso`, `Control.Lens.Prism.Prism`, `Control.Lens.Comonocle.Comonocle` & `Control.Lens.Diopter.Diopter` is a `Bifocal` too. -`Bifocal`s are isomorphic to t'Binocular's. +`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`. -} +{- | `ABifocal` is monomorphically a `Bifocal`. + +> prop> Bifocal s t a b ⊂ ABifocal s t a b +-} type ABifocal s t a b = - Binocular a b a (Maybe b) -> Binocular a b s (Maybe t) + 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 @@ -59,7 +70,7 @@ bifocal bif = unwrapPafb . runBinocular bif . WrapPafb 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 +mapBifocal bif = runSpectacle (catMaybes (bif (Just <$> Spectacle (Just . Par1) (Just . unPar1)))) {- | Clone `ABifocal` so that you can reuse the same monomorphically typed `Bifocal` for different purposes. @@ -67,14 +78,15 @@ monomorphically typed `Bifocal` for different purposes. cloneBifocal :: ABifocal s t a b -> Bifocal s t a b cloneBifocal bif = unwrapPafb . mapBifocal bif . WrapPafb -{- | Run `ABifocal` over an `Alternative` & `Filterable`. -} +{- | 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 (catMaybes (bif (Just <$> Binocular ($ Just)))) +withBifocal bif = unBinocular (mapBifocal bif (Binocular ($ Just))) -{- | t'Binocular' provides an efficient -concrete representation of `Bifocal`s. -} +{- | 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) @@ -123,3 +135,85 @@ runBinocular => 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 index a5b17826..afefbe42 100644 --- a/distributors-core/src/Control/Lens/Comonocle.hs +++ b/distributors-core/src/Control/Lens/Comonocle.hs @@ -56,8 +56,6 @@ import Numeric.Natural (Natural) {- | `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. -Writing ⊂ for "every one is a", - `Control.Lens.Iso.Iso` ⊂ `Comonocle` ⊂ `Control.Lens.Lens.Lens` ∩ `Control.Lens.Diopter.Diopter`, @@ -74,7 +72,10 @@ 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`. -} +{- | `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) diff --git a/distributors-core/src/Control/Lens/Diopter.hs b/distributors-core/src/Control/Lens/Diopter.hs index 21b5b0d7..b7aac991 100644 --- a/distributors-core/src/Control/Lens/Diopter.hs +++ b/distributors-core/src/Control/Lens/Diopter.hs @@ -39,8 +39,6 @@ import GHC.Generics `Control.Lens.Monocle.Monocle`s, of products, & `Control.Lens.Comonocle.Comonocle`s, of sums, to countable sums of countable products. -Writing ⊂ for "every one is a", - `Control.Lens.Monocle.Monocle` ∪ `Control.Lens.Comonocle.Comonocle` ⊂ `Diopter` ⊂ `Control.Lens.Traversal.Traversal` ∩ `Control.Lens.Prismoid.Prismoid`. @@ -56,7 +54,10 @@ 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`. -} +{- | `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) diff --git a/distributors-core/src/Control/Lens/Grate.hs b/distributors-core/src/Control/Lens/Grate.hs index a191f0ca..7c52e93c 100644 --- a/distributors-core/src/Control/Lens/Grate.hs +++ b/distributors-core/src/Control/Lens/Grate.hs @@ -16,6 +16,7 @@ module Control.Lens.Grate Grate , AGrate , Grating (..) + , Diffraction (..), diffraction, withDiffraction -- * Combinators , grate , withGrate @@ -36,20 +37,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`. -Writing ⊂ for "every one is a", - `Control.Lens.Iso.Iso` ⊂ `Control.Lens.Monocle.Monocle` ⊂ `Grate`. -`Grate`s are isomorphic to t'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) @@ -119,3 +126,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/distributors-core/src/Control/Lens/Monocle.hs b/distributors-core/src/Control/Lens/Monocle.hs index 82ea4f22..0b5ac893 100644 --- a/distributors-core/src/Control/Lens/Monocle.hs +++ b/distributors-core/src/Control/Lens/Monocle.hs @@ -50,8 +50,6 @@ import Numeric.Natural (Natural) {- | `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. -Writing ⊂ for "every one is a", - `Control.Lens.Iso.Iso` ⊂ `Monocle` ⊂ `Control.Lens.Traversal.Traversal` ∩ `Control.Lens.Grate.Grate`. @@ -64,7 +62,10 @@ 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`. -} +{- | `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) diff --git a/distributors-core/src/Control/Lens/PartialIso.hs b/distributors-core/src/Control/Lens/PartialIso.hs index 794b2f58..d0ee1281 100644 --- a/distributors-core/src/Control/Lens/PartialIso.hs +++ b/distributors-core/src/Control/Lens/PartialIso.hs @@ -16,7 +16,7 @@ module Control.Lens.PartialIso PartialIso , PartialIso' , APartialIso - , PartialExchange (PartialExchange) + , PartialMarket (..), partialMarket, withPartialMarket -- * Combinators , partialIso , partialInvoluted @@ -25,6 +25,8 @@ module Control.Lens.PartialIso , coPartialIso , crossPartialIso , altPartialIso + , orPartialIso + , emptyPartialIso -- * Applicators , dimapMaybe , (>?) @@ -33,8 +35,8 @@ module Control.Lens.PartialIso , (>~) , (~<) , (!=) - , filterPrism -- * Patterns + , filterPrism , satisfied , nulled , notNulled @@ -59,6 +61,7 @@ import Control.Lens.Internal.Distributor.NestedPrismTH 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 @@ -66,6 +69,7 @@ import Witherable -- $setup -- >>> import Control.Lens +-- >>> import Data.Monoid.Disjunctive ((>|<)) {- | The `dimapMaybe` function endows `Choice` & `Cochoice` "partial profunctors" @@ -87,24 +91,42 @@ 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. -Writing ⊂ for "every one is a", - `Control.Lens.Iso.Iso` ∪ `Control.Lens.Prism.Prism` ∪ `filterPrism` ⊂ `PartialIso` ⊂ `Control.Lens.Bifocal.Bifocal`. -__N.B.__ t'PartialExchange' is a retract of `PartialIso`: -`withPartialIso` is a retraction, with `partialIso` its section, -recovering the partial functions which build a `PartialIso`. +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. -> prop> withPartialIso (partialIso f g) PartialExchange = PartialExchange f g +`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`, -But they aren't isomorphic, since a `PartialIso` may be more than -its partial functions, as a `Control.Lens.Prism.Prism` is, below. -Rebuilding a `PartialIso` from its partial functions, -by `clonePartialIso`, is idempotent, but not the identity. +> prop> partialMarket build match = filterPrism _Just . prism build (maybe (Left Nothing) match) -> prop> clonePartialIso pattern = withPartialIso pattern partialIso -> prop> clonePartialIso (clonePartialIso pattern) = clonePartialIso pattern +& 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`, @@ -152,12 +174,14 @@ Just 8 Nothing A `Control.Lens.Prism.Prism` is exhaustive though, -passing a mismatched source through, where its partial functions, -cloned by `clonePartialIso`, fail; so it isn't its own clone. +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`, @@ -183,18 +207,18 @@ type PartialIso s t a b = forall p f. 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: +A proper `PartialIso'`, with partial functions @match@ & @build@, +by `withPartialIso`, inverts what it matches & what it builds. -> prop> Just = f <=< g -> prop> Just = g <=< f +> prop> match s = Just a ==> build a = Just s +> prop> build a = Just s ==> match s = Just a -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. +However, sometimes an improper `PartialIso'` will be useful, +matching what it builds, but not necessarily rebuilding what it matches. -> prop> Just = f <=< g +> prop> build a = Just s ==> match s = Just a -For an improper `PartialIso'`, @norm = g <=< f@ is an idempotent +For an improper `PartialIso'`, @norm = build <=< match@ is an idempotent > prop> norm = norm <=< norm @@ -203,47 +227,120 @@ some equivalence class of terms. -} type PartialIso' s a = PartialIso s s a a -{- | `APartialIso` is monomorphically a `PartialIso`. -} +{- | `APartialIso` is monomorphically a `PartialIso`. + +> prop> PartialIso s t a b ⊂ APartialIso s t a b +-} type APartialIso s t a b = - PartialExchange a b a (Maybe b) -> PartialExchange a b s (Maybe t) + 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. -{- | A t'PartialExchange' provides efficient access -to the two functions that make up a `PartialIso`. +> 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 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) -{- | t'PartialExchange's choose by first success, in either direction, -& `falseP` fails in both, so `Data.Monoid.Disjunctive.orP` tries -the partial functions of `PartialIso`s in turn. - -`satisfied` is a homomorphism of `Data.Monoid.Disjunctive.BooleanAlgebra`s -of predicates, from `>|<` to `>|<`, & from `>&<` to composition. - -> prop> withPartialIso (satisfied (p >|< q)) PartialExchange = withPartialIso (satisfied p) PartialExchange >|< withPartialIso (satisfied q) PartialExchange -> prop> withPartialIso (satisfied falseP) PartialExchange = falseP -> prop> satisfied (p >&< q) = satisfied p . satisfied q -> prop> satisfied trueP = id +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 -} -instance DisjunctiveMonoid (PartialExchange a b s t) where - falseP = PartialExchange falseP falseP - PartialExchange f g >|< PartialExchange f' g' = - PartialExchange (f >|< f') (g >|< g') +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, @@ -258,43 +355,94 @@ 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. -} +{- | 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 = - case pattern (PartialExchange Just (Just . Just)) of - PartialExchange f g -> k f (join . g) +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 = withPartialIso pattern $ \f g -> partialIso f g - -{- | Clone and invert `APartialIso`. -} +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. -} +{- | Construct a `PartialIso` on pairs from components, +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 (crossPartialIso _Just _Just) (\(x, y) -> Just (x + y, x * y)) (Just 2, Just 3 :: Maybe Int) +Just (Just 5,Just 6) +>>> traverseOf (crossPartialIso _Just _Just) (Just . id) (Nothing, Nothing :: Maybe Int) +Just (Nothing,Nothing) +>>> traverseOf (crossPartialIso _Just _Just) (Just . id) (Just 2, Nothing :: Maybe Int) +Nothing +-} 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. -} + 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, +passing a mismatch through from either. + +>>> traverseOf (altPartialIso _Just _Just) (Just . either (Left . succ) (Right . pred)) (Left (Just 1) :: Either (Maybe Int) (Maybe Int)) +Just (Left (Just 2)) +>>> traverseOf (altPartialIso _Just _Just) (Just . either (Left . succ) (Right . pred)) (Left Nothing :: Either (Maybe Int) (Maybe Int)) +Just (Left Nothing) +-} altPartialIso :: APartialIso s t a b -> APartialIso u v c d @@ -302,11 +450,51 @@ altPartialIso (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)) + 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 emptyPartialIso pattern = clonePartialIso pattern +> prop> orPartialIso pattern emptyPartialIso = clonePartialIso pattern +> prop> satisfied (const False) = emptyPartialIso + +>>> preview emptyPartialIso 'x' :: Maybe Char +Nothing +-} +emptyPartialIso :: PartialIso s t a b +emptyPartialIso = partialMarket (const Nothing) (const (Left Nothing)) {- | Action of `APrism` on `Choice` `Profunctor`s. -} (>?) @@ -333,13 +521,31 @@ whose `Cochoice` by a `Filterable` @f@ filters the residual out. (?<) pat = withPrism pat $ \f g -> unright . dimap (either id f) g infixl 4 ?< -{- | Action of `APartialIso` on `Choice` & `Cochoice` partial profunctors. -} +{- | 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 = withPartialIso pat dimapMaybe +(>?<) 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. -} @@ -398,7 +604,18 @@ filterPrism filterPrism p = unwrapPafb . (?<) p . WrapPafb {- | `satisfied` is the prototypical proper partial isomorphism, -identifying a subset which satisfies a predicate. -} +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 diff --git a/distributors-core/src/Control/Lens/Prismoid.hs b/distributors-core/src/Control/Lens/Prismoid.hs index 18bb6586..159170cf 100644 --- a/distributors-core/src/Control/Lens/Prismoid.hs +++ b/distributors-core/src/Control/Lens/Prismoid.hs @@ -13,6 +13,7 @@ module Control.Lens.Prismoid Prismoid , APrismoid , Prismatoid (..), runPrismatoid + , Prismocular (..), runPrismocular, prismocular, withPrismocular -- * Combinators , prismoid , withPrismoid @@ -22,14 +23,11 @@ module Control.Lens.Prismoid , opted , lefted , righted - -- * Plasmoid - , Plasmoid , chained1 , chained - , severaled - , severaled1 , intercalated , operated + , separated ) where import Control.Applicative @@ -38,13 +36,14 @@ import Control.Lens.Internal.Profunctor import Control.Lens.PartialIso import Data.Monoid.Disjunctive (DisjunctiveMonoid (..)) import Data.Profunctor.Distributor +import Data.Profunctor.Monoidal ((>*), (*<), replicateP) import Data.Profunctor.Monoidal.Cocartesian import Data.Traversable.Homogeneous import Data.Void -import GHC.Exts (IsList (..)) 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) @@ -55,7 +54,7 @@ import GHC.Generics (Par1 (..), U1 (..), V1, (:*:) (..), (:+:) (..), (:.:) (..)) {- | `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. Writing ⊂ for "every one is a", +& building totally backwards. `Control.Lens.Prism.Prism` ∪ `Control.Lens.Diopter.Diopter` ⊂ `Prismoid` ⊂ `Control.Lens.Bifocal.Bifocal`. @@ -64,33 +63,22 @@ 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 `Control.Lens.PartialIso.clonePartialIso` makes it do in any `Choice`. +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. +`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) -{- | A `Plasmoid` is a family of optics, separated by a t'SepBy', -which is an optic at the `Alternator` @p@ of its separators. +{- | `APrismoid` is monomorphically a `Prismoid`. -Its separators are data-free, @p () ()@, so they place effects -between its foci, but never change what its source or target holds. -So without separators, by `noSep`, which is polymorphic in @p@, -a `Plasmoid` is a `Prismoid`, & its data is that `Prismoid`'s; -for any @plasmoid :: Plasmoid s t a b@, -@plasmoid noSep :: Prismoid s t a b@. - ->>> withPrismoid (severaled1 noSep :: Prismoid String String Char Char) $ \f _ -> fmap length (f "abc") -Just 3 +> prop> Prismoid s t a b ⊂ APrismoid s t a b -} -type Plasmoid s t a b = forall p f. - (Alternator p, Applicative f) - => SepBy (p () ()) -> p a (f b) -> p s (f t) - -{- | `APrismoid` is monomorphically a `Prismoid`. -} type APrismoid s t a b = Prismatoid a b a (Identity b) -> Prismatoid a b s (Identity t) @@ -132,25 +120,11 @@ withPrismoid pat k = somed :: Prismoid [a] [b] a b somed = unwrapPafb . someP . WrapPafb -{- | Zero or more, separated by a t'SepBy', like `several`. -} -severaled :: (IsList s, IsList t) => Plasmoid s t (Item s) (Item t) -severaled sep = unwrapPafb . several (fmap (WrapPafb . rmap pure) sep) . WrapPafb - -{- | One or more, separated by a t'SepBy', like `several1`. - ->>> let digits = runJoker (severaled1 (sepBy (Joker (() <$ char ','))) (Joker (Identity <$> satisfy isDigit)) :: Joker ReadP String (Identity String)) ->>> [ds | (Identity ds, "") <- readP_to_S digits "1,2,3"] -["123"] --} -severaled1 :: (IsList s, IsList t) => Plasmoid s t (Item s) (Item t) -severaled1 sep = unwrapPafb . several1 (fmap (WrapPafb . rmap pure) sep) . WrapPafb - -{- | Exactly some number of times, separated by a t'SepBy', -like `intercalateP`, or without separators, by `noSep`, like -`Data.Profunctor.Monoidal.replicateP`. -} -intercalated :: (AsEmpty s, Cons s s a a) => Int -> Plasmoid s s a a -intercalated n sep = - unwrapPafb . intercalateP n (fmap (WrapPafb . rmap pure) sep) . WrapPafb +{- | Exactly some number of times, like +`Data.Profunctor.Monoidal.replicateP`, +or, `separated` by a t'SepBy', like `intercalateP`. -} +intercalated :: (AsEmpty s, Cons s s a a) => Int -> Prismoid s s a a +intercalated n = unwrapPafb . replicateP n . WrapPafb {- | An expression of `Operator`s, from a table of them, ordered from highest to lowest precedence, like `withOperators`. An operator table, @@ -163,20 +137,12 @@ _Plus = prism' (uncurry Plus) (\case Plus x y -> Just (x, y); _ -> Nothing) :} >>> let plus = Infix LeftAssoc _Plus (Joker (() <$ char '+')) ->>> let digit = Joker (Identity . Digit . digitToInt <$> satisfy isDigit) ->>> [e | (Identity e, "") <- readP_to_S (runJoker (operated [[plus]] digit)) "1+2+3"] +>>> let digit = Joker (Digit . digitToInt <$> satisfy isDigit) +>>> [e | (e, "") <- readP_to_S (runJoker (operated [[plus]] digit)) "1+2+3"] [Plus (Plus (Digit 1) (Digit 2)) (Digit 3)] -} -operated - :: (Alternator p, Applicative f) - => [[Operator p a b]] -> p a (f b) -> p a (f b) -operated table = - unwrapPafb . withOperators (map (map wrapping) table) . WrapPafb - where - wrapping = \case - Infix assoc pat sym -> Infix assoc pat (WrapPafb (rmap pure sym)) - Prefix pat sym -> Prefix pat (WrapPafb (rmap pure sym)) - Postfix pat sym -> Postfix pat (WrapPafb (rmap pure sym)) +operated :: Alternator p => [[Operator p a b]] -> p a b -> p a b +operated = withOperators {- | One or zero with default. -} opted :: APrism a b () () -> Prismoid a b a b @@ -194,26 +160,28 @@ 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. +Associate a binary constructor pattern to sequence one or more times, +like `chain1`, or, `separated` by a t'SepBy', with separators. -} chained1 :: (forall x. x -> Either x x) -> APartialIso a b (a,a) (b,b) - -> Plasmoid a b a b -chained1 assoc binPat sep = - unwrapPafb . chain1 assoc binPat (fmap (WrapPafb . rmap pure) sep) . WrapPafb + -> 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. +or use a nilary constructor pattern to sequence zero times, +like `chain`, or, `separated` by a t'SepBy', with separators. -} chained :: (forall x. x -> Either x x) -> APartialIso a b (a,a) (b,b) -> APrism a b () () - -> Plasmoid a b a b -chained assoc binPat nilPat sep = - unwrapPafb . chain assoc binPat nilPat (fmap (WrapPafb . rmap pure) sep) . WrapPafb + -> Prismoid a b a b +chained assoc binPat nilPat = + unwrapPafb . chain assoc binPat nilPat noSep . WrapPafb {- | A t'Prismatoid' provides efficient access to the pair of functions that make up a `Prismoid`, @@ -264,3 +232,119 @@ 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 somed (\probe -> maybe empty pure (probe "")) :: Maybe String +Nothing +>>> withPrismocular somed (\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 (mapPrismoid pat (Prismocular ($ Just))) + +{- | Action of `APrismoid` on `Alternator`s, like `mapPrismoid`, +with a t'SepBy', its separator +between consecutive foci, & its delimiters around them all. +A shape of @n@ foci gets @n - 1@ separators, like `Data.List.intersperse`. + +> prop> separated pat noSep = clonePrismoid pat +> prop> separated pat (SepBy beg end sep) p = beg >* separated pat (sepBy sep) p *< end +> prop> separated somed = several1 +> prop> separated manied = several +> prop> separated (intercalated n) = intercalateP n +> prop> separated (chained1 assoc pat) = chain1 assoc pat + +>>> let digits = runJoker (separated somed (sepBy (Joker (() <$ char ','))) (Joker (satisfy isDigit)) :: Joker ReadP String String) +>>> [ds | (ds, "") <- readP_to_S digits "1,2,3"] +["123"] +-} +separated + :: Alternator p + => APrismoid s t a b -> SepBy (p () ()) -> p a b -> p s t +separated pat (SepBy beg end sep) p = + case mapPrismoid pat (Interspersing empty p (sep >* p)) of + Interspersing noFoci firstFoci _ -> beg >* (noFoci <|> firstFoci) *< end + +{- | An `Alternator` which separates the foci it sequences, +from either of two states: before any focus, or after one. +Before any focus, an action either sequences no focus, +or some, its first unseparated; after one, it separates every focus. +Those are its three fields, in order. +-} +data Interspersing p a b = Interspersing (p a b) (p a b) (p a b) +instance Profunctor p => Profunctor (Interspersing p) where + dimap f g ~(Interspersing n x y) = Interspersing (dimap f g n) (dimap f g x) (dimap f g y) +instance Alternator p => Functor (Interspersing p a) where fmap = rmap +instance Alternator p => Applicative (Interspersing p a) where + pure b = Interspersing (pure b) empty (pure b) + liftA2 h ~(Interspersing xn xf xl) ~(Interspersing yn yf yl) = Interspersing + (liftA2 h xn yn) + (liftA2 h xn yf <|> liftA2 h xf yl) + (liftA2 h xl yl) +instance Alternator p => Alternative (Interspersing p a) where + empty = Interspersing empty empty empty + ~(Interspersing xn xf xl) <|> ~(Interspersing yn yf yl) = + Interspersing (xn <|> yn) (xf <|> yf) (xl <|> yl) +instance Alternator p => DisjunctiveMonoid (Interspersing p a b) +instance Alternator p => Choice (Interspersing p) where + left' = alternate . Left + right' = alternate . Right +instance Alternator p => CocartesianMonoidal (Interspersing p) where + zeroP = Interspersing zeroP zeroP zeroP + ~(Interspersing xn xf xl) >+< ~(Interspersing yn yf yl) = + Interspersing (xn >+< yn) (xf >+< yf) (xl >+< yl) +instance Alternator p => CocartesianChoice (Interspersing p) where + alternate = \case + Left ~(Interspersing n x y) -> + Interspersing (alternate (Left n)) (alternate (Left x)) (alternate (Left y)) + Right ~(Interspersing n x y) -> + Interspersing (alternate (Right n)) (alternate (Right x)) (alternate (Right y)) +instance Alternator p => Distributor (Interspersing p) +instance Alternator p => Alternator (Interspersing p) diff --git a/distributors-core/src/Control/Lens/Wither.hs b/distributors-core/src/Control/Lens/Wither.hs index 2f07b016..88cd6370 100644 --- a/distributors-core/src/Control/Lens/Wither.hs +++ b/distributors-core/src/Control/Lens/Wither.hs @@ -34,11 +34,9 @@ import Witherable -- $setup -- >>> import Control.Applicative (Alternative (..)) -- >>> import Control.Lens --- >>> import Control.Lens.PartialIso (clonePartialIso) +-- >>> import Control.Lens.PartialIso (partialIso, withPartialIso) {- | `Wither`s extend `Control.Lens.Traversal.Traversal`s by filtering. -Writing ⊂ for "every one is a", - `Control.Lens.Traversal.Traversal` ⊂ `Wither`, so every `Control.Lens.Iso.Iso`, `Control.Lens.Lens.Lens` @@ -46,7 +44,10 @@ so every `Control.Lens.Iso.Iso`, `Control.Lens.Lens.Lens` -} type Wither s t a b = forall f. Alternative f => (a -> f b) -> s -> f t -{- | `AWither` is monomorphically a `Wither`. -} +{- | `AWither` is monomorphically a `Wither`. + +> prop> Wither s t a b ⊂ AWither s t a b +-} 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 @@ -73,11 +74,12 @@ witherPrism prsm = withPrism prsm $ \embed match -> >>> (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`, -@witherPrism@ is `Control.Lens.PartialIso.clonePartialIso`, -a `Control.Lens.PartialIso.PartialIso`, for a `Filterable` @f@. +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 . clonePartialIso _Just) (\x -> Just (x + 1)) [Just 1, Nothing, Just 2] +>>> (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 diff --git a/distributors-core/src/Data/Profunctor/Distributor.hs b/distributors-core/src/Data/Profunctor/Distributor.hs index 7c110822..27964ab0 100644 --- a/distributors-core/src/Data/Profunctor/Distributor.hs +++ b/distributors-core/src/Data/Profunctor/Distributor.hs @@ -325,13 +325,12 @@ withOperators table p = foldl makeLevel p table -> (d -> (Int, y)) -- ^ untag a build -> [APrism x y x y] -> PartialIso x y c d taggedP tag untag pats = - case orP (zipWith exchange [0 ..] pats) of - PartialExchange fwd bwd -> partialIso fwd bwd + let (fwd, bwd) = orP (zipWith exchange [0 ..] pats) in partialIso fwd bwd where exchange i pat = let (match, build) = patternFns pat in - PartialExchange (fmap (tag i) . match) $ \d -> case untag d of + (fmap (tag i) . match, \d -> case untag d of (j, y) | j == i -> Just (build y) - _ -> Nothing + _ -> Nothing) -- An operand, then @(operator, operand)@ steps, folded by each -- operator's associativity, like parsec's @buildExpressionParser@: diff --git a/distributors-core/src/Data/Profunctor/Filtrator.hs b/distributors-core/src/Data/Profunctor/Filtrator.hs index 4806ca10..bbdf27ff 100644 --- a/distributors-core/src/Data/Profunctor/Filtrator.hs +++ b/distributors-core/src/Data/Profunctor/Filtrator.hs @@ -111,11 +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 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/test/Main.hs b/distributors-core/test/Main.hs index 30147e52..7a0c7b47 100644 --- a/distributors-core/test/Main.hs +++ b/distributors-core/test/Main.hs @@ -7,11 +7,13 @@ import Test.Hspec import Properties.Homogeneous import Properties.PartialIso +import Properties.Parsing main :: IO () main = hspec $ do describe "Homogeneous" homogeneousProperties describe "PartialIso" partialIsoProperties + describe "Parsing" parsingProperties describe "meander" meanderProperties meanderProperties :: Spec diff --git a/distributors-core/test/Properties/Homogeneous.hs b/distributors-core/test/Properties/Homogeneous.hs index e261b997..69eb63a0 100644 --- a/distributors-core/test/Properties/Homogeneous.hs +++ b/distributors-core/test/Properties/Homogeneous.hs @@ -11,9 +11,11 @@ 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, clonePrismoid, lefted, severaled, severaled1, somed, withPrismoid) +import Control.Lens.Prismoid (APrismoid, Prismocular (..), clonePrismoid, lefted, mapPrismoid, prismocular, somed, 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 (cotraverseOf) +import Control.Lens.Grate (Diffraction (..), diffraction, cotraversed, cotraverseOf, withDiffraction) import Control.Lens.Monocle import Control.Lens.PartialIso (withPartialIso) import Control.Monad ((<=<)) @@ -26,7 +28,6 @@ import Data.Int (Int8) import Data.Maybe (fromMaybe) import Data.Monoid.Disjunctive import Data.Profunctor -import Data.Profunctor.Distributor (noSep) import Data.Profunctor.Monadic (Monadic) import Data.Profunctor.Monoidal (Monoidal) import Data.Profunctor.Monoidal.Cocartesian @@ -370,11 +371,55 @@ homogeneousProperties = do withPrismoid (_Just :: APrismoid (Maybe Int) (Maybe Int) Int Int) (\match _ -> toList <$> match m) === fmap pure m - prop "severaled1 noSep is somed, & severaled noSep is manied" $ \(xs :: [Int]) -> - withPrismoid (severaled1 noSep :: APrismoid [Int] [Int] Int Int) (\match _ -> toList <$> match xs) - === withPrismoid somed (\match _ -> toList <$> match xs) - .&&. withPrismoid (severaled noSep :: APrismoid [Int] [Int] Int Int) (\match _ -> toList <$> match xs) - === withPrismoid manied (\match _ -> toList <$> match xs) + 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 somed xs === shaping somed xs + .&&. probing lefted e === shaping lefted e + .&&. probing _Just m === shaping _Just m + .&&. probing manied xs === shaping manied 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 (mapPrismoid 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 somed xs === shaping somed xs + .&&. probing manied xs === shaping manied xs + prop "cloneBifocal somed matches one or more" $ \(xs :: [Int]) -> + withSpectacle (cloneBifocal somed) (\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 "somed matches one or more" $ \(xs :: [Int]) -> withPrismoid somed (\match _ -> toList <$> match xs) === if null xs then Nothing else Just xs diff --git a/distributors-core/test/Properties/Parsing.hs b/distributors-core/test/Properties/Parsing.hs new file mode 100644 index 00000000..2a5943d4 --- /dev/null +++ b/distributors-core/test/Properties/Parsing.hs @@ -0,0 +1,75 @@ +module Properties.Parsing (parsingProperties) where + +import Control.Lens.Diopter (manied) +import Control.Lens.Prismoid +import Data.Bifunctor.Joker (Joker (..)) +import Data.Char (isDigit) +import Data.Functor.Identity (Identity (..)) +import Data.List (intercalate) +import Control.Lens (Prism', prism') +import Data.Profunctor (rmap) +import Data.Profunctor.Distributor (SepBy (..), chain1, intercalateP, sepBy, several, several1) +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 "separated" $ do + prop "separated somed = several1" $ \(Digits ds) -> + let str = bracketed ds + in parses (rmap Identity (separated somed brackets plainDigit)) str + === parses (rmap Identity (several1 brackets plainDigit :: Joker ReadP String String)) str + prop "separated manied = several" $ \(Digits ds) -> + let str = bracketed ds + in parses (rmap Identity (separated manied brackets plainDigit)) str + === parses (rmap Identity (several brackets plainDigit :: Joker ReadP String String)) str + prop "separated (intercalated n) = intercalateP n" $ + \(Digits ds) -> let str = bracketed ds; n = length ds in + parses (rmap Identity (separated (intercalated n) brackets plainDigit :: Joker ReadP String String)) str + === parses (rmap Identity (intercalateP n brackets plainDigit)) str + prop "separated (chained1 assoc pat) = chain1 assoc pat" $ + \(Digits ds) -> let str = bracketed ds in + parses (rmap Identity (separated (chained1 Left _Node) brackets plainLeaf)) str + === parses (rmap Identity (chain1 Left _Node brackets plainLeaf)) str + .&&. parses (rmap Identity (separated (chained1 Right _Node) brackets plainLeaf)) str + === parses (rmap Identity (chain1 Right _Node brackets plainLeaf)) str + prop "separated somed parses only separated digits" $ + \(Digits ds) -> parses (rmap Identity (separated somed brackets plainDigit)) (bracketed ds) + === [ds | not (null ds)] + prop "separated is ambiguous only where its Prismoid is" $ + \(Digits ds0) -> let ds = take 8 ds0 in + length (parses (rmap Identity (separated (somed . somed) (sepBy comma) plainDigit)) (intercalate "," (map pure ds))) + === length (parses ((somed . somed) 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) ++ "]" + +brackets :: SepBy (Joker ReadP () ()) +brackets = SepBy (sym '[') (sym ']') (sym ',') + where sym c = Joker (() <$ char c) + +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) + +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 index 67ea2151..39daa911 100644 --- a/distributors-core/test/Properties/PartialIso.hs +++ b/distributors-core/test/Properties/PartialIso.hs @@ -1,9 +1,12 @@ module Properties.PartialIso (partialIsoProperties) where -import Control.Lens (preview, review, traverseOf, view) +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 @@ -29,17 +32,128 @@ partialIsoProperties = do 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, unlike its clone" $ + 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 === 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 "altPartialIso of Prisms is their sum" $ + \(Fun _ f :: Fun Int (Maybe Int)) (e :: Either (Maybe Int) (Maybe Int)) -> within second $ + traverseOf (altPartialIso _Just _Just) (either (fmap Left . f) (fmap Right . f)) e + === either (fmap Left . traverseOf _Just f) (fmap Right . traverseOf _Just f) e + prop "crossPartialIso of Prisms passes through where both do" $ + \(Fun _ f :: Fun (Int, Int) (Maybe (Int, Int))) (m :: Maybe Int) (n :: Maybe Int) -> within second $ + traverseOf (crossPartialIso _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 "emptyPartialIso is orPartialIso's identity" $ + \(Fun _ f :: Fun Int (Maybe Int)) (m :: Maybe Int) -> within second $ + traverseOf (orPartialIso emptyPartialIso _Just) f m === traverseOf _Just f m + .&&. traverseOf (orPartialIso _Just emptyPartialIso) 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 PartialExchanges" $ + 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) PartialExchange - >|< withPartialIso (satisfied q) PartialExchange ) x y + ( 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 @@ -48,10 +162,20 @@ partialIsoProperties = do 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 PartialExchange) - exchanging :: PartialExchange a b s t -> s -> b -> (Maybe a, Maybe t) - exchanging (PartialExchange match build) s b = (match s, build b) + 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 diff --git a/distributors-grammar/distributors-grammar.cabal b/distributors-grammar/distributors-grammar.cabal index 70d8a657..947755cb 100644 --- a/distributors-grammar/distributors-grammar.cabal +++ b/distributors-grammar/distributors-grammar.cabal @@ -85,7 +85,7 @@ library build-depends: MemoTrie >=0.6 && <1 , QuickCheck >=2.14 && <3 - , base >=4.15 && <5 + , base >=4.20 && <5 , bifunctors >=5.5 && <6 , containers >=0.6 && <1 , distributors ==0.7.* @@ -148,7 +148,7 @@ test-suite doctests build-depends: MemoTrie >=0.6 && <1 , QuickCheck >=2.14 && <3 - , base >=4.15 && <5 + , base >=4.20 && <5 , bifunctors >=5.5 && <6 , containers >=0.6 && <1 , distributors ==0.7.* @@ -223,7 +223,7 @@ test-suite test build-depends: MemoTrie >=0.6 && <1 , QuickCheck >=2.14 && <3 - , base >=4.15 && <5 + , base >=4.20 && <5 , bifunctors >=5.5 && <6 , containers >=0.6 && <1 , distributors diff --git a/distributors-grammar/package.yaml b/distributors-grammar/package.yaml index f43d791a..c1c40393 100644 --- a/distributors-grammar/package.yaml +++ b/distributors-grammar/package.yaml @@ -19,7 +19,7 @@ description: as regular expressions & Backus-Naur forms. dependencies: -- base >= 4.15 && < 5 +- base >= 4.20 && < 5 - bifunctors >= 5.5 && < 6 - containers >= 0.6 && < 1 - distributors >= 0.7 && < 0.8 diff --git a/distributors-json/distributors-json.cabal b/distributors-json/distributors-json.cabal index 24f3fbd2..fa6ef42d 100644 --- a/distributors-json/distributors-json.cabal +++ b/distributors-json/distributors-json.cabal @@ -86,7 +86,7 @@ library 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.15 && <5 + , base >=4.20 && <5 , bytestring >=0.11 && <1 , containers >=0.6 && <1 , data-fix >=0.3 && <1 @@ -164,7 +164,7 @@ test-suite doctests 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.15 && <5 + , base >=4.20 && <5 , bytestring >=0.11 && <1 , containers >=0.6 && <1 , data-fix >=0.3 && <1 @@ -247,7 +247,7 @@ test-suite test build-depends: QuickCheck >=2.14 && <3 , aeson >=2.2 && <3 - , base >=4.15 && <5 + , base >=4.20 && <5 , bytestring >=0.11 && <1 , containers >=0.6 && <1 , data-fix >=0.3 && <1 @@ -329,7 +329,7 @@ benchmark json 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.15 && <5 + , base >=4.20 && <5 , bytestring >=0.11 && <1 , containers >=0.6 && <1 , data-fix >=0.3 && <1 diff --git a/distributors-json/package.yaml b/distributors-json/package.yaml index 0611a8cc..106aad11 100644 --- a/distributors-json/package.yaml +++ b/distributors-json/package.yaml @@ -22,7 +22,7 @@ description: See "Control.Lens.Grammar.Json". dependencies: -- base >= 4.15 && < 5 +- base >= 4.20 && < 5 - aeson >= 2.2 && < 3 - bytestring >= 0.11 && < 1 - containers >= 0.6 && < 1 From ad1b48ca5e399495526739b4ea3935e0bd8bc306 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Fri, 13 Nov 2026 00:48:05 -0800 Subject: [PATCH 105/130] Prismoid applicators: >?*, sepBy & counted Prismoids Prismoids apply directly at an Alternator, so the target's own methods act, & separators, repetition & delimiters compose from small parts. - >?* applies a polymorphic Prismoid at an Alternator, without a concrete form, keeping the target's someP & optionP (e.g. Grammor's plusK exactly). mapPrismoid is removed: clonePrismoid pat >?*. - sepBy :: p () () -> Prismoid s t a b -> p a b -> p s t separates consecutive foci by an internal upper triangular matrix of actions, preferring foci greedily; delimiters compose by >* & *<. It replaces SepBy, noSep, sepWith, beginWith & endWith, & the SepBy combinators. - manyTillP, an Alternator method, p* q trying q first; Grammor defines it as starK p <> q, so sepBy is finite at static Alternators. - Optics renamed or new: manied -> several, somed -> atLeast 1, chained1/chained -> chain1/chain; exactly, atLeast, atMost & inRange, unified on one worker (finite lower bound, optional upper bound). - skipManyP & skipOptionalP, & their Diopters skippedMany & skippedOptional: actions a parser accepts & a printer omits. - SepBy's module merges into Control.Lens.Prismoid, which, with Control.Lens.Diopter, Control.Lens.Grammar re-exports. - Fixed: a deterministic parser's separated many parsed nothing. Co-Authored-By: Claude Opus 5.5 --- distributors-core/CHANGELOG.md | 57 ++- distributors-core/src/Control/Lens/Diopter.hs | 38 +- .../src/Control/Lens/Prismoid.hs | 452 ++++++++++++++---- .../src/Data/Profunctor/Distributor.hs | 256 ++-------- .../test/Properties/Homogeneous.hs | 28 +- distributors-core/test/Properties/Parsing.hs | 115 +++-- distributors-grammar/CHANGELOG.md | 8 + .../src/Control/Lens/Grammar.hs | 25 +- .../src/Control/Lens/Grammar/Symbol.hs | 24 - .../src/Data/Profunctor/Grammar.hs | 1 + .../test/Examples/Arithmetic.hs | 4 +- distributors-grammar/test/Examples/Chain.hs | 2 +- .../test/Examples/Expression.hs | 2 +- distributors-grammar/test/Examples/Json.hs | 6 +- distributors-grammar/test/Examples/Lambda.hs | 2 +- distributors-grammar/test/Examples/LenVec.hs | 2 +- distributors-grammar/test/Examples/SExpr.hs | 2 +- distributors-grammar/test/Examples/SemVer.hs | 4 +- .../test/Properties/Kleene.hs | 47 ++ 19 files changed, 650 insertions(+), 425 deletions(-) diff --git a/distributors-core/CHANGELOG.md b/distributors-core/CHANGELOG.md index 81dd7507..d6bf3b2f 100644 --- a/distributors-core/CHANGELOG.md +++ b/distributors-core/CHANGELOG.md @@ -32,18 +32,30 @@ - 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`, with - `somed`, `opted`, `lefted`, `righted`, `chained1` & `chained`; & new - `intercalated`, like `replicateP`, & `operated`, an expression of an - operator table, like `withOperators`. -- `separated`, running any `APrismoid` with a `SepBy`, its separator - between consecutive foci, & its delimiters around them, so - `separated somed = several1`, `separated manied = several`, - `separated (intercalated n) = intercalateP n` & - `separated (chained1 assoc pat) = chain1 assoc pat`. +- `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. +- `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`. +- `atLeast`, `atMost` & `inRange`, `Prismoid`s of at least, at most, & + between, some numbers of times, like a regular expression's @{n,}@, + @{0,n}@ & @{lo,hi}@. +- `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`, `mapPrismoid`, - `clonePrismoid` & `runPrismatoid`. + 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` @@ -77,7 +89,7 @@ - `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 `somed` diverged at static `Profunctor`s. + `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 @@ -111,8 +123,20 @@ `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 `Data.Profunctor.Distributor`: - `SepBy`, `several`, `chain`, `intercalateP`, `withOperators` & so on. +- `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, & + `iso toList fromList >~ 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` @@ -126,9 +150,8 @@ - `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`, `beginWith` & `endWith` move from `Data.Profunctor.Separator` - to `Control.Lens.Grammar.Symbol`, beside `terminal`, so that - `Data.Profunctor.Separator` needn't import grammar symbols. +- `sepWith`, `beginWith` & `endWith` are removed: a separator is a + `terminal`, & delimiters compose around `sepBy` by `>*` & `*<`. ## 0.6.0.0 - 2026-04-24 diff --git a/distributors-core/src/Control/Lens/Diopter.hs b/distributors-core/src/Control/Lens/Diopter.hs index b7aac991..d0cc2ae3 100644 --- a/distributors-core/src/Control/Lens/Diopter.hs +++ b/distributors-core/src/Control/Lens/Diopter.hs @@ -19,7 +19,9 @@ module Control.Lens.Diopter , cloneDiopter , mapDiopter , optioned - , manied + , several + , skippedMany + , skippedOptional , homogenized , zipDiopter , zipWithDiopter @@ -35,6 +37,12 @@ import Data.Traversable.Homogeneous import Data.Void import GHC.Generics +-- $setup +-- >>> 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, @@ -88,8 +96,26 @@ 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 +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. @@ -103,9 +129,9 @@ 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 manied (Just . sum) [[1, 2], [3, 4], [5, 6 :: Int]] +>>> zipDiopter several (Just . sum) [[1, 2], [3, 4], [5, 6 :: Int]] Just [9,12] ->>> zipDiopter manied (Just . sum) [[1, 2], [3 :: Int]] +>>> zipDiopter several (Just . sum) [[1, 2], [3 :: Int]] Nothing -} zipDiopter @@ -128,7 +154,7 @@ zipWithDiopter dio f s0 s1 = {- | Transpose sources of `ADiopter` in the positions of a `Traversable`, when they have the same shape. ->>> transposeDiopter manied [[1, 2, 3], [4, 5, 6 :: Int]] +>>> 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 diff --git a/distributors-core/src/Control/Lens/Prismoid.hs b/distributors-core/src/Control/Lens/Prismoid.hs index 159170cf..f4d7dfe3 100644 --- a/distributors-core/src/Control/Lens/Prismoid.hs +++ b/distributors-core/src/Control/Lens/Prismoid.hs @@ -14,30 +14,39 @@ module Control.Lens.Prismoid , APrismoid , Prismatoid (..), runPrismatoid , Prismocular (..), runPrismocular, prismocular, withPrismocular + -- * Applicators + , (>?*) + , sepBy + , withOperators -- * Combinators , prismoid , withPrismoid , clonePrismoid - , mapPrismoid - , somed , opted , lefted , righted - , chained1 - , chained - , intercalated - , operated - , separated + , chain1 + , chain + , exactly + , atLeast + , atMost + , inRange + -- * Operator Expressions + , Operator (..) + , Assoc (..) ) where import Control.Applicative +import Control.Monad (void) +import Data.Maybe (fromMaybe, isJust) import Control.Lens import Control.Lens.Internal.Profunctor import Control.Lens.PartialIso -import Data.Monoid.Disjunctive (DisjunctiveMonoid (..)) +import Data.Monoid.Disjunctive (DisjunctiveMonoid (..), orP) import Data.Profunctor.Distributor -import Data.Profunctor.Monoidal ((>*), (*<), replicateP) +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, (:*:) (..), (:+:) (..), (:.:) (..)) @@ -47,8 +56,9 @@ import GHC.Generics (Par1 (..), U1 (..), V1, (:*:) (..), (:+:) (..), (:.:) (..)) -- >>> 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.Profunctor.Distributor (Assoc (..), Operator (..), noSep, sepBy) +-- >>> import Data.Functor.Product (Product (..)) -- >>> import Text.ParserCombinators.ReadP (ReadP, char, readP_to_S, satisfy) {- | `Prismoid`s generalize `Control.Lens.Prism.Prism`s @@ -93,9 +103,28 @@ prismoid => (s -> Maybe (h a)) -> (h b -> t) -> Prismoid s t a b prismoid f g = unwrapPafb . runPrismatoid (Prismatoid f g) . WrapPafb -{- | Action of `APrismoid` on `Alternator`s. -} -mapPrismoid :: Alternator p => APrismoid s t a b -> p a b -> p s t -mapPrismoid pat = withPrismoid pat $ \f g -> runPrismatoid (Prismatoid f g) +{- | 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. @@ -105,7 +134,7 @@ clonePrismoid pat = withPrismoid pat prismoid {- | Convert `APrismoid` to the pair of functions that characterize it. ->>> withPrismoid somed $ \f _ -> (fmap length (f ""), fmap length (f "ab")) +>>> withPrismoid (atLeast 1) $ \f _ -> (fmap length (f ""), fmap length (f "ab")) (Nothing,Just 2) -} withPrismoid @@ -116,33 +145,70 @@ withPrismoid pat k = case runIdentity <$> pat (Identity <$> Prismatoid (Just . Par1) unPar1) of Prismatoid f g -> k f g -{- | One or more, like `someP`. -} -somed :: Prismoid [a] [b] a b -somed = unwrapPafb . someP . WrapPafb +{- | Exactly some number of times, or separated by `sepBy`. -{- | Exactly some number of times, like -`Data.Profunctor.Monoidal.replicateP`, -or, `separated` by a t'SepBy', like `intercalateP`. -} -intercalated :: (AsEmpty s, Cons s s a a) => Int -> Prismoid s s a a -intercalated n = unwrapPafb . replicateP n . WrapPafb +> prop> exactly n = inRange n n +> prop> exactly n >?* p = replicateP n p +-} +exactly :: Int -> Prismoid [a] [b] a b +exactly n = inRange n n -{- | An expression of `Operator`s, from a table of them, ordered from -highest to lowest precedence, like `withOperators`. An operator table, -like a t'SepBy', is of an `Alternator` @p@, its symbols data-free. +{- | 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`. ->>> :{ -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) -:} +> prop> atLeast 0 = several +> prop> atLeast 1 >?* p = someP p ->>> let plus = Infix LeftAssoc _Plus (Joker (() <$ char '+')) ->>> let digit = Joker (Digit . digitToInt <$> satisfy isDigit) ->>> [e | (e, "") <- readP_to_S (runJoker (operated [[plus]] digit)) "1+2+3"] -[Plus (Plus (Digit 1) (Digit 2)) (Digit 3)] +>>> 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"] +[] -} -operated :: Alternator p => [[Operator p a b]] -> p a b -> p a b -operated = withOperators +atLeast :: Int -> Prismoid [a] [b] a b +atLeast n = unwrapPafb . repetitions n Nothing . WrapPafb + +{- | At most some number of times, trying more first, +or separated by `sepBy`. + +> prop> atMost n = inRange 0 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 = inRange 0 + +{- | Between some numbers of times, inclusive, trying more first, +like a regular expression's @{lo,hi}@, or separated by `sepBy`. +It never matches where @lo > hi@. + +>>> let digits lo hi = runJoker (inRange lo hi >?* Joker (satisfy isDigit)) :: ReadP String +>>> [ds | (ds, "") <- readP_to_S (digits 2 3) "123"] +["123"] +>>> [ds | n <- [1 .. 4], (ds, "") <- readP_to_S (digits 2 3) (take n "1234")] +["12","123"] +-} +inRange :: Int -> Int -> Prismoid [a] [b] a b +inRange lo hi = unwrapPafb . repetitions lo (Just hi) . WrapPafb + +-- At least @l@ times, & at most @h@, if bounded: the mandatory copies, +-- then, unbounded, the `Alternator`'s own `someP` or `manyP`, +-- or, bounded, optional copies, trying more first. +repetitions :: Alternator p => Int -> Maybe Int -> p a b -> p [a] [b] +repetitions l h p + | maybe False (l >) h = empty + | l > 1 || (l == 1 && isJust h) = p >:< repetitions (l - 1) (subtract 1 <$> h) p + | l == 1 = someP p + | otherwise = case h of + Nothing -> manyP p + Just m + | m <= 0 -> eotList . swapped >~ empty >+< oneP + | otherwise -> eotList . swapped >~ p >*< repetitions 0 (Just (m - 1)) p >+< oneP {- | One or zero with default. -} opted :: APrism a b () () -> Prismoid a b a b @@ -161,27 +227,32 @@ righted = unwrapPafb . alternate . Right . WrapPafb {- | Associate a binary constructor pattern to sequence one or more times, -like `chain1`, or, `separated` by a t'SepBy', with separators. +`Left` or `Right` associated, folding & unfolding it by +`Control.Lens.PartialIso.difoldl` or `Control.Lens.PartialIso.difoldr`, +or separated by `sepBy`. -} -chained1 - :: (forall x. x -> Either x x) - -> APartialIso a b (a,a) (b,b) +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 -chained1 assoc binPat = - unwrapPafb . chain1 assoc binPat noSep . WrapPafb +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 `chain`, or, `separated` by a t'SepBy', with separators. +like `chain1` & `opted`, +or separated by `sepBy`. -} -chained - :: (forall x. x -> Either x x) - -> APartialIso a b (a,a) (b,b) - -> APrism a b () () +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 -chained assoc binPat nilPat = - unwrapPafb . chain assoc binPat nilPat noSep . WrapPafb +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`, @@ -279,72 +350,247 @@ prismocular pm = unwrapPafb . runPrismocular pm . WrapPafb {- | Run `APrismoid` by partial probes in an `Alternative`. ->>> withPrismocular somed (\probe -> maybe empty pure (probe "")) :: Maybe String +>>> withPrismocular (atLeast 1) (\probe -> maybe empty pure (probe "")) :: Maybe String Nothing ->>> withPrismocular somed (\probe -> maybe empty pure (probe "ab")) :: Maybe String +>>> 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 (mapPrismoid pat (Prismocular ($ Just))) - -{- | Action of `APrismoid` on `Alternator`s, like `mapPrismoid`, -with a t'SepBy', its separator -between consecutive foci, & its delimiters around them all. -A shape of @n@ foci gets @n - 1@ separators, like `Data.List.intersperse`. - -> prop> separated pat noSep = clonePrismoid pat -> prop> separated pat (SepBy beg end sep) p = beg >* separated pat (sepBy sep) p *< end -> prop> separated somed = several1 -> prop> separated manied = several -> prop> separated (intercalated n) = intercalateP n -> prop> separated (chained1 assoc pat) = chain1 assoc pat - ->>> let digits = runJoker (separated somed (sepBy (Joker (() <$ char ','))) (Joker (satisfy isDigit)) :: Joker ReadP String String) +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 are lists by @`iso` `toList` `fromList`@. + +>>> 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')] -} -separated +sepBy :: Alternator p - => APrismoid s t a b -> SepBy (p () ()) -> p a b -> p s t -separated pat (SepBy beg end sep) p = - case mapPrismoid pat (Interspersing empty p (sep >* p)) of - Interspersing noFoci firstFoci _ -> beg >* (noFoci <|> firstFoci) *< end - -{- | An `Alternator` which separates the foci it sequences, -from either of two states: before any focus, or after one. -Before any focus, an action either sequences no focus, -or some, its first unseparated; after one, it separates every focus. -Those are its three fields, in order. + => 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 Interspersing p a b = Interspersing (p a b) (p a b) (p a b) -instance Profunctor p => Profunctor (Interspersing p) where - dimap f g ~(Interspersing n x y) = Interspersing (dimap f g n) (dimap f g x) (dimap f g y) -instance Alternator p => Functor (Interspersing p a) where fmap = rmap -instance Alternator p => Applicative (Interspersing p a) where - pure b = Interspersing (pure b) empty (pure b) - liftA2 h ~(Interspersing xn xf xl) ~(Interspersing yn yf yl) = Interspersing - (liftA2 h xn yn) - (liftA2 h xn yf <|> liftA2 h xf yl) +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 (Interspersing p a) where - empty = Interspersing empty empty empty - ~(Interspersing xn xf xl) <|> ~(Interspersing yn yf yl) = - Interspersing (xn <|> yn) (xf <|> yf) (xl <|> yl) -instance Alternator p => DisjunctiveMonoid (Interspersing p a b) -instance Alternator p => Choice (Interspersing p) where +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 (Interspersing p) where - zeroP = Interspersing zeroP zeroP zeroP - ~(Interspersing xn xf xl) >+< ~(Interspersing yn yf yl) = - Interspersing (xn >+< yn) (xf >+< yf) (xl >+< yl) -instance Alternator p => CocartesianChoice (Interspersing p) where +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 ~(Interspersing n x y) -> - Interspersing (alternate (Left n)) (alternate (Left x)) (alternate (Left y)) - Right ~(Interspersing n x y) -> - Interspersing (alternate (Right n)) (alternate (Right x)) (alternate (Right y)) -instance Alternator p => Distributor (Interspersing p) -instance Alternator p => Alternator (Interspersing p) + 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 = 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 = 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/Data/Profunctor/Distributor.hs b/distributors-core/src/Data/Profunctor/Distributor.hs index 27964ab0..11e9c4b8 100644 --- a/distributors-core/src/Data/Profunctor/Distributor.hs +++ b/distributors-core/src/Data/Profunctor/Distributor.hs @@ -11,22 +11,10 @@ Portability : non-portable module Data.Profunctor.Distributor ( -- * Distributor Distributor (..) + , skipManyP + , skipOptionalP -- * Alternator , Alternator (..) - -- * SepBy - , SepBy (..) - , sepBy - , noSep - -- * SepBy Combinators - , several - , several1 - , chain - , chain1 - , intercalateP - -- * Operator Expressions - , Operator (..) - , Assoc (..) - , withOperators ) where import Control.Applicative hiding (WrappedArrow) @@ -49,7 +37,11 @@ import Data.Profunctor.Monad import Data.Profunctor.Monoidal import Data.Profunctor.Yoneda import Data.Profunctor.Monoidal.Cocartesian -import GHC.Exts (IsList (..)) + +-- $setup +-- >>> import Data.Bifunctor.Joker (Joker (..)) +-- >>> import Data.Profunctor.Monoidal ((*<)) +-- >>> import Text.ParserCombinators.ReadP (char, readP_to_S) -- Distributor -- @@ -120,6 +112,28 @@ 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`, @@ -162,6 +176,23 @@ class (Distributor p, CocartesianChoice p, forall x. Alternative (p x)) 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 + instance (Alternator p, Applicative f) => Alternator (WrappedPafb f p) where someP (WrapPafb x) = WrapPafb (rmap sequenceA (someP x)) @@ -169,203 +200,12 @@ instance (Alternator p, Applicative f) 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)) 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)) instance Alternative f => Alternator (Joker f) where someP (Joker x) = Joker (some x) optionP def (Joker x) = Joker (x <|> withPrism def (\f _ -> pure (f ()))) - --- Separators -- - -{- | 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 t'SepBy' smart constructor, -setting the `separateBy` field. -Beginning and ending delimiters will be no-ops, -except by modifier record updates `beginBy` or `endBy`. -} -sepBy :: Applicative p => p () -> SepBy (p ()) -sepBy = SepBy (pure ()) (pure ()) - -{- | A t'SepBy' smart constructor for no separator, -beginning or ending delimiters. -} -noSep :: Applicative p => SepBy (p ()) -noSep = sepBy (pure ()) - -{- | -> 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 . swapped >~ - 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 t'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` - -> 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. - -For an 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 = 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 = 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/test/Properties/Homogeneous.hs b/distributors-core/test/Properties/Homogeneous.hs index 69eb63a0..880adb00 100644 --- a/distributors-core/test/Properties/Homogeneous.hs +++ b/distributors-core/test/Properties/Homogeneous.hs @@ -11,7 +11,7 @@ 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, mapPrismoid, prismocular, somed, withPrismocular, withPrismoid) +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 @@ -363,10 +363,10 @@ homogeneousProperties = do roundTrip :: APrismoid s s Int Int -> s -> Maybe s roundTrip o s = withPrismoid o $ \match build -> build . fmap k <$> match s in - roundTrip (clonePrismoid somed) xs === roundTrip somed xs + 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 manied) xs === roundTrip manied xs + .&&. 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) @@ -388,14 +388,14 @@ homogeneousProperties = do shaping :: APrismoid s s Int Int -> s -> Maybe s shaping o s = withPrismoid o $ \match build -> build . fmap f <$> match s in - probing somed xs === shaping somed xs + probing (atLeast 1) xs === shaping (atLeast 1) xs .&&. probing lefted e === shaping lefted e .&&. probing _Just m === shaping _Just m - .&&. probing manied xs === shaping manied xs + .&&. 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 (mapPrismoid l (Prismocular ($ Just)))) + 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" $ @@ -409,10 +409,10 @@ homogeneousProperties = do 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 somed xs === shaping somed xs - .&&. probing manied xs === shaping manied xs - prop "cloneBifocal somed matches one or more" $ \(xs :: [Int]) -> - withSpectacle (cloneBifocal somed) (\match _ -> toList <$> match 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) -> @@ -420,14 +420,14 @@ homogeneousProperties = do (\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 "somed matches one or more" $ \(xs :: [Int]) -> - withPrismoid somed (\match _ -> toList <$> match xs) + 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 manied is zipWithHomogeneous" $ \(xs :: [Int]) ys -> - zipWithDiopter manied (+) xs ys === zipWithHomogeneous (+) xs ys + 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 -> diff --git a/distributors-core/test/Properties/Parsing.hs b/distributors-core/test/Properties/Parsing.hs index 2a5943d4..c762deb7 100644 --- a/distributors-core/test/Properties/Parsing.hs +++ b/distributors-core/test/Properties/Parsing.hs @@ -1,14 +1,18 @@ module Properties.Parsing (parsingProperties) where -import Control.Lens.Diopter (manied) +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 (SepBy (..), chain1, intercalateP, sepBy, several, several1) +import Data.Profunctor.Distributor (Alternator (..)) +import Data.Profunctor.Monoidal ((>*), (*<), replicateP) import Test.Hspec import Test.Hspec.QuickCheck (prop) import Test.QuickCheck @@ -16,32 +20,74 @@ import Text.ParserCombinators.ReadP (ReadP, char, readP_to_S, satisfy) parsingProperties :: Spec parsingProperties = do - describe "separated" $ do - prop "separated somed = several1" $ \(Digits ds) -> - let str = bracketed ds - in parses (rmap Identity (separated somed brackets plainDigit)) str - === parses (rmap Identity (several1 brackets plainDigit :: Joker ReadP String String)) str - prop "separated manied = several" $ \(Digits ds) -> - let str = bracketed ds - in parses (rmap Identity (separated manied brackets plainDigit)) str - === parses (rmap Identity (several brackets plainDigit :: Joker ReadP String String)) str - prop "separated (intercalated n) = intercalateP n" $ - \(Digits ds) -> let str = bracketed ds; n = length ds in - parses (rmap Identity (separated (intercalated n) brackets plainDigit :: Joker ReadP String String)) str - === parses (rmap Identity (intercalateP n brackets plainDigit)) str - prop "separated (chained1 assoc pat) = chain1 assoc pat" $ - \(Digits ds) -> let str = bracketed ds in - parses (rmap Identity (separated (chained1 Left _Node) brackets plainLeaf)) str - === parses (rmap Identity (chain1 Left _Node brackets plainLeaf)) str - .&&. parses (rmap Identity (separated (chained1 Right _Node) brackets plainLeaf)) str - === parses (rmap Identity (chain1 Right _Node brackets plainLeaf)) str - prop "separated somed parses only separated digits" $ - \(Digits ds) -> parses (rmap Identity (separated somed brackets plainDigit)) (bracketed ds) + 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 "separated is ambiguous only where its Prismoid is" $ + 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 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 (separated (somed . somed) (sepBy comma) plainDigit)) (intercalate "," (map pure ds))) - === length (parses ((somed . somed) digit) ds) + 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 @@ -50,9 +96,8 @@ instance Arbitrary Digits where bracketed :: String -> String bracketed ds = "[" ++ intercalate "," (map pure ds) ++ "]" -brackets :: SepBy (Joker ReadP () ()) -brackets = SepBy (sym '[') (sym ']') (sym ',') - where sym c = Joker (() <$ char c) +inBrackets :: Joker ReadP a b -> Joker ReadP a b +inBrackets p = Joker (() <$ char '[') >* p *< Joker (() <$ char ']') comma :: Joker ReadP () () comma = Joker (() <$ char ',') @@ -71,5 +116,17 @@ _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-grammar/CHANGELOG.md b/distributors-grammar/CHANGELOG.md index 311b2300..a217d188 100644 --- a/distributors-grammar/CHANGELOG.md +++ b/distributors-grammar/CHANGELOG.md @@ -6,6 +6,14 @@ `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`, with a `terminal` + separator, delimiters composing around a `sepBy` grammar by `>*` & + `*<`. +- `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 diff --git a/distributors-grammar/src/Control/Lens/Grammar.hs b/distributors-grammar/src/Control/Lens/Grammar.hs index b6850bb9..d3eb35a7 100644 --- a/distributors-grammar/src/Control/Lens/Grammar.hs +++ b/distributors-grammar/src/Control/Lens/Grammar.hs @@ -74,6 +74,8 @@ 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.Diopter as X +import Control.Lens.Prismoid as X import Control.Monad.Fail.Try as X import Data.Monoid.Disjunctive as X import Data.Profunctor.Distributor as X @@ -143,7 +145,7 @@ semverGrammar = _SemVer >*< optionP _Empty (terminal "+" >* identifiersG) where numberG = iso show read >~ someP (asIn @Char DecimalNumber) - identifiersG = several1 (sepWith ".") (someP charG) + identifiersG = sepBy (terminal ".") (atLeast 1) (someP charG) charG = asIn LowercaseLetter >|< asIn UppercaseLetter >|< asIn DecimalNumber @@ -256,9 +258,9 @@ arithGrammar :: Grammar Char Arith arithGrammar = ruleRec "arith" sumG where sumG arith = rule "sum" $ - chain1 Left _Add (sepWith "+") (prodG arith) + sepBy (terminal "+") (chain1 Left _Add) (prodG arith) prodG arith = rule "product" $ - chain1 Left _Mul (sepWith "*") (factorG arith) + sepBy (terminal "*") (chain1 Left _Mul) (factorG arith) factorG arith = rule "factor" $ numberG >|< terminal "(" >* arith *< terminal ")" numberG = rule "number" $ @@ -378,7 +380,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 = sepBy (terminal ",") (exactly n) numberG len <- numberG -- bonds to _LenVec terminal ";" -- doesn't bond vectorG (fromIntegral len) -- bonds to _LenVec @@ -666,7 +668,7 @@ regexGrammar = _RegString >~ ruleRec "regex" altG where altG rex = rule "alternate" $ iso alternativesOf (foldr1 (>|<) :: [RegEx Char] -> RegEx Char) - >~ several1 (sepWith "|") (seqG rex) + >~ sepBy (terminal "|") (atLeast 1) (seqG rex) seqG rex = rule "sequence" $ iso itemsOf mconcat >~ manyP (exprG rex) @@ -733,19 +735,18 @@ regexGrammar = _RegString >~ ruleRec "regex" altG classCatG = rule "class-category" $ orP [ _AndAsIn >? terminal "\\p{" >* categoryG *< terminal "}" - , _AndNotAsIn >? several1 - (sepWith "|" & beginWith "\\P{" & endWith "}") - categoryG + , _AndNotAsIn . iso toList fromList >? + terminal "\\P{" >* sepBy (terminal "|") (atLeast 1) categoryG *< terminal "}" ] classOneOfG = rule "class-one-of" $ orP [ onlyOne charG - , terminal "[" >* several noSep charG *< terminal "]" + , terminal "[" >* (iso toList fromList >~ manyP charG) *< terminal "]" ] classNotOneOfG = rule "class-not-one-of" $ orP [ asEmpty >*< classCatG - , terminal "[^" >* several noSep charG >*< + , terminal "[^" >* (iso toList fromList >~ manyP charG) >*< optionP (_AndNotAsIn . _Empty) classCatG *< terminal "]" ] @@ -855,8 +856,8 @@ That means that it can generate a self-hosted definition. -} regbnfGrammar :: Grammar Char RegBnf regbnfGrammar = rule "regbnf" $ _RegBnf . _Bnf >~ - terminal "{start} = " >* regexGrammar >*< several noSep - (terminal "\n" >* nonterminalG *< terminal " = " >*< regexGrammar) + terminal "{start} = " >* regexGrammar >*< (iso toList fromList >~ manyP + (terminal "\n" >* nonterminalG *< terminal " = " >*< regexGrammar)) {- | `regstringG` generates a t'RegString' from a regular grammar. diff --git a/distributors-grammar/src/Control/Lens/Grammar/Symbol.hs b/distributors-grammar/src/Control/Lens/Grammar/Symbol.hs index b0337cf8..a36ec396 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/Symbol.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/Symbol.hs @@ -12,10 +12,6 @@ module Control.Lens.Grammar.Symbol ( -- * Symbol TerminalSymbol (..) , NonTerminalSymbol (..) - -- * Separators - , sepWith - , beginWith - , endWith ) where import Control.Lens @@ -24,7 +20,6 @@ import Control.Lens.Grammar.Token import Data.Bifunctor.Joker import Data.Profunctor import Data.Profunctor.Monoidal -import Data.Profunctor.Distributor (SepBy (..), sepBy) import Text.ParserCombinators.ReadP (ReadP, string) -- | A `terminal` symbol in a grammar. @@ -39,25 +34,6 @@ class TerminalSymbol token s | s -> token where class NonTerminalSymbol s where nonTerminal :: String -> s -{- | A t'SepBy' smart constructor like `sepBy`, -with a `terminal` argument. -Beginning and ending delimiters 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 t'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 t'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} - -- instances instance TerminalSymbol token (f ()) => TerminalSymbol token (Joker f () ()) where diff --git a/distributors-grammar/src/Data/Profunctor/Grammar.hs b/distributors-grammar/src/Data/Profunctor/Grammar.hs index d6e0315a..522ca1b6 100644 --- a/distributors-grammar/src/Data/Profunctor/Grammar.hs +++ b/distributors-grammar/src/Data/Profunctor/Grammar.hs @@ -354,6 +354,7 @@ instance KleeneStarAlgebra k => Distributor (Grammor k) where instance KleeneStarAlgebra k => Alternator (Grammor k) where someP (Grammor rex) = Grammor (plusK rex) optionP _ (Grammor rex) = Grammor (optK rex) + manyTillP (Grammor rex) (Grammor rest) = Grammor (starK rex <> rest) instance Tokenized token k => Tokenized token (Grammor k a b) where anyToken = Grammor anyToken token = Grammor . token diff --git a/distributors-grammar/test/Examples/Arithmetic.hs b/distributors-grammar/test/Examples/Arithmetic.hs index 9bb1fa7d..3c876e88 100644 --- a/distributors-grammar/test/Examples/Arithmetic.hs +++ b/distributors-grammar/test/Examples/Arithmetic.hs @@ -20,9 +20,9 @@ arithGrammar :: Grammar Char Arith arithGrammar = ruleRec "arith" sumG where sumG arith = rule "sum" $ - chain1 Left _Add (sepWith "+") (prodG arith) + sepBy (terminal "+") (chain1 Left _Add) (prodG arith) prodG arith = rule "product" $ - chain1 Left _Mul (sepWith "*") (factorG arith) + sepBy (terminal "*") (chain1 Left _Mul) (factorG arith) factorG arith = rule "factor" $ number >|< terminal "(" >* arith *< terminal ")" number = rule "number" $ diff --git a/distributors-grammar/test/Examples/Chain.hs b/distributors-grammar/test/Examples/Chain.hs index c806557e..8c397264 100644 --- a/distributors-grammar/test/Examples/Chain.hs +++ b/distributors-grammar/test/Examples/Chain.hs @@ -19,7 +19,7 @@ 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 ")" charG = notOneOf "()\\" diff --git a/distributors-grammar/test/Examples/Expression.hs b/distributors-grammar/test/Examples/Expression.hs index 65184077..4a7f3aa9 100644 --- a/distributors-grammar/test/Examples/Expression.hs +++ b/distributors-grammar/test/Examples/Expression.hs @@ -75,7 +75,7 @@ powGrammar = ruleRec "pow" $ \e -> nat >|< terminal "(" >* e *< terminal ")" nat = rule "nat" $ _Nat . iso show read >? someP (asIn @Char DecimalNumber) - in chain1 (\x -> Right x) _Exp (sepWith "^") atom + in sepBy (terminal "^") (chain1 Right _Exp) atom powExamples :: [(Expr, String)] powExamples = diff --git a/distributors-grammar/test/Examples/Json.hs b/distributors-grammar/test/Examples/Json.hs index e7cdeaf7..ed8169be 100644 --- a/distributors-grammar/test/Examples/Json.hs +++ b/distributors-grammar/test/Examples/Json.hs @@ -57,7 +57,7 @@ jsonGrammar = rule "json" elementG -- members = member | member ',' members membersG json = rule "members" $ - several1 (sepWith ",") (memberG json) + sepBy (terminal ",") (atLeast 1) (memberG json) -- member = ws string ws ':' element memberG json = rule "member" $ @@ -71,7 +71,7 @@ jsonGrammar = rule "json" elementG -- elements = element | element ',' elements elementsG json = rule "elements" $ - several1 (sepWith ",") json + sepBy (terminal ",") (atLeast 1) json -- string = '"' characters '"' stringG = rule "string" $ @@ -100,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/distributors-grammar/test/Examples/Lambda.hs b/distributors-grammar/test/Examples/Lambda.hs index 1c13c972..7c5207aa 100644 --- a/distributors-grammar/test/Examples/Lambda.hs +++ b/distributors-grammar/test/Examples/Lambda.hs @@ -34,7 +34,7 @@ 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) + sepBy (terminal " ") (chain1 Left _App) (atomG term) -- Atomic term: variable or parenthesized term atomG term = rule "atom" $ orP diff --git a/distributors-grammar/test/Examples/LenVec.hs b/distributors-grammar/test/Examples/LenVec.hs index 13483dc3..b1f0210b 100644 --- a/distributors-grammar/test/Examples/LenVec.hs +++ b/distributors-grammar/test/Examples/LenVec.hs @@ -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 = sepBy (terminal ",") (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/SExpr.hs b/distributors-grammar/test/Examples/SExpr.hs index 5fad88ab..715fe3cf 100644 --- a/distributors-grammar/test/Examples/SExpr.hs +++ b/distributors-grammar/test/Examples/SExpr.hs @@ -29,7 +29,7 @@ sexprGrammar = ruleRec "sexpr" $ \sexpr -> orP -- List: parenthesized sequence of S-expressions -- Elements are separated by whitespace listG sexpr = rule "list" $ - terminal "(" >* several (sepWith " ") sexpr *< terminal ")" + terminal "(" >* sepBy (terminal " ") several sexpr *< terminal ")" -- Characters allowed in atoms: letters, digits, and symbols atomChars = diff --git a/distributors-grammar/test/Examples/SemVer.hs b/distributors-grammar/test/Examples/SemVer.hs index a204b856..e9c99a2f 100644 --- a/distributors-grammar/test/Examples/SemVer.hs +++ b/distributors-grammar/test/Examples/SemVer.hs @@ -41,7 +41,7 @@ semverGrammar = _SemVer >*< optionP _Empty (terminal "+" >* identifiersG) where numberG = iso show read >~ someP (asIn @Char DecimalNumber) - identifiersG = several1 (sepWith ".") (someP charG) + identifiersG = sepBy (terminal ".") (atLeast 1) (someP charG) charG = asIn LowercaseLetter >|< asIn UppercaseLetter >|< asIn DecimalNumber @@ -52,7 +52,7 @@ semverCtxGrammar :: CtxGrammar Char SemVer semverCtxGrammar = _SemVer >? P.do let numberG = iso show read >~ someP (asIn @Char DecimalNumber) - identifiersG = several1 (sepWith ".") (someP charG) + identifiersG = sepBy (terminal ".") (atLeast 1) (someP charG) charG = asIn LowercaseLetter >|< asIn UppercaseLetter >|< asIn DecimalNumber diff --git a/distributors-grammar/test/Properties/Kleene.hs b/distributors-grammar/test/Properties/Kleene.hs index 1f7d055d..998daae7 100644 --- a/distributors-grammar/test/Properties/Kleene.hs +++ b/distributors-grammar/test/Properties/Kleene.hs @@ -100,6 +100,52 @@ kleeneProperties = do 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 hi) s === (if bounded lo hi s then Just s else Nothing) + .&&. (if bounded lo hi s then parsed (inRange lo 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 @@ -173,3 +219,4 @@ kleeneProperties = do reparsed :: RegString -> RegString reparsed = fromList . toList + From 0723d02e67f3fac3c05eb80949a69afece13f4ea Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Fri, 13 Nov 2026 00:52:52 -0800 Subject: [PATCH 106/130] inRange generalization --- distributors-core/CHANGELOG.md | 6 +-- .../src/Control/Lens/Prismoid.hs | 54 ++++++++++--------- distributors-core/test/Properties/Parsing.hs | 2 +- .../test/Properties/Kleene.hs | 4 +- 4 files changed, 34 insertions(+), 32 deletions(-) diff --git a/distributors-core/CHANGELOG.md b/distributors-core/CHANGELOG.md index d6bf3b2f..af69a8e3 100644 --- a/distributors-core/CHANGELOG.md +++ b/distributors-core/CHANGELOG.md @@ -45,9 +45,9 @@ sequencing actions forwards & none backwards, like whitespace or a trailing separator, which a parser accepts & a printer omits; & their `Diopter`s, `skippedMany` & `skippedOptional`. -- `atLeast`, `atMost` & `inRange`, `Prismoid`s of at least, at most, & - between, some numbers of times, like a regular expression's @{n,}@, - @{0,n}@ & @{lo,hi}@. +- `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`. - `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@. diff --git a/distributors-core/src/Control/Lens/Prismoid.hs b/distributors-core/src/Control/Lens/Prismoid.hs index f4d7dfe3..f38b3d77 100644 --- a/distributors-core/src/Control/Lens/Prismoid.hs +++ b/distributors-core/src/Control/Lens/Prismoid.hs @@ -147,16 +147,17 @@ withPrismoid pat k = {- | Exactly some number of times, or separated by `sepBy`. -> prop> exactly n = inRange n n +> prop> exactly n = inRange n (Just n) > prop> exactly n >?* p = replicateP n p -} exactly :: Int -> Prismoid [a] [b] a b -exactly n = inRange n n +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 @@ -167,12 +168,12 @@ its own `manyP`. [] -} atLeast :: Int -> Prismoid [a] [b] a b -atLeast n = unwrapPafb . repetitions n Nothing . WrapPafb +atLeast n = inRange n Nothing {- | At most some number of times, trying more first, or separated by `sepBy`. -> prop> atMost n = inRange 0 n +> 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"] @@ -181,34 +182,35 @@ or separated by `sepBy`. [] -} atMost :: Int -> Prismoid [a] [b] a b -atMost = inRange 0 - -{- | Between some numbers of times, inclusive, trying more first, -like a regular expression's @{lo,hi}@, or separated by `sepBy`. +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@. >>> let digits lo hi = runJoker (inRange lo hi >?* Joker (satisfy isDigit)) :: ReadP String ->>> [ds | (ds, "") <- readP_to_S (digits 2 3) "123"] +>>> [ds | (ds, "") <- readP_to_S (digits 2 (Just 3)) "123"] ["123"] ->>> [ds | n <- [1 .. 4], (ds, "") <- readP_to_S (digits 2 3) (take n "1234")] +>>> [ds | n <- [1 .. 4], (ds, "") <- readP_to_S (digits 2 (Just 3)) (take n "1234")] ["12","123"] -} -inRange :: Int -> Int -> Prismoid [a] [b] a b -inRange lo hi = unwrapPafb . repetitions lo (Just hi) . WrapPafb - --- At least @l@ times, & at most @h@, if bounded: the mandatory copies, --- then, unbounded, the `Alternator`'s own `someP` or `manyP`, --- or, bounded, optional copies, trying more first. -repetitions :: Alternator p => Int -> Maybe Int -> p a b -> p [a] [b] -repetitions l h p - | maybe False (l >) h = empty - | l > 1 || (l == 1 && isJust h) = p >:< repetitions (l - 1) (subtract 1 <$> h) p - | l == 1 = someP p - | otherwise = case h of - Nothing -> manyP p - Just m - | m <= 0 -> eotList . swapped >~ empty >+< oneP - | otherwise -> eotList . swapped >~ p >*< repetitions 0 (Just (m - 1)) p >+< oneP +inRange :: Int -> Maybe Int -> Prismoid [a] [b] a b +inRange lo hi = unwrapPafb . go lo hi . WrapPafb + where + go :: Alternator p => Int -> Maybe Int -> p a b -> p [a] [b] + go l h p + | maybe False (l >) h = empty + | l > 1 || (l == 1 && isJust h) = p >:< go (l - 1) (subtract 1 <$> h) p + | l == 1 = someP p + | otherwise = case h of + Nothing -> manyP p + Just m + | m <= 0 -> eotList . swapped >~ empty >+< oneP + | otherwise -> eotList . swapped >~ p >*< go 0 (Just (m - 1)) p >+< oneP {- | One or zero with default. -} opted :: APrism a b () () -> Prismoid a b a b diff --git a/distributors-core/test/Properties/Parsing.hs b/distributors-core/test/Properties/Parsing.hs index c762deb7..0fe8ab21 100644 --- a/distributors-core/test/Properties/Parsing.hs +++ b/distributors-core/test/Properties/Parsing.hs @@ -72,7 +72,7 @@ parsingProperties = do === 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 hi >?* plainDigit)) ds + 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 diff --git a/distributors-grammar/test/Properties/Kleene.hs b/distributors-grammar/test/Properties/Kleene.hs index 998daae7..fddc561a 100644 --- a/distributors-grammar/test/Properties/Kleene.hs +++ b/distributors-grammar/test/Properties/Kleene.hs @@ -129,8 +129,8 @@ kleeneProperties = do 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 hi) s === (if bounded lo hi s then Just s else Nothing) - .&&. (if bounded lo hi s then parsed (inRange lo hi) s === Just (s, "") else property True) + 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) From 9bf9269c6f31e80afb861e1bb648a1e71b8ca598 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Fri, 13 Nov 2026 01:06:56 -0800 Subject: [PATCH 107/130] sepWith: sepBy of a terminal separator, in Control.Lens.Grammar.Symbol sepWith :: (Alternator p, TerminalSymbol c (p () ())) => [c] -> Prismoid s t a b -> p a b -> p s t sepWith = sepBy . terminal Every grammar separator is a terminal, so grammars read sepWith "," (atLeast 1) json; 0.6's several1 (sepWith ",") p is sepWith "," (atLeast 1) p. Co-Authored-By: Claude Opus 5.5 --- distributors-core/CHANGELOG.md | 6 ++++-- distributors-grammar/CHANGELOG.md | 6 +++--- distributors-grammar/src/Control/Lens/Grammar.hs | 12 ++++++------ .../src/Control/Lens/Grammar/Symbol.hs | 14 ++++++++++++++ distributors-grammar/test/Examples/Arithmetic.hs | 4 ++-- distributors-grammar/test/Examples/Expression.hs | 2 +- distributors-grammar/test/Examples/Json.hs | 4 ++-- distributors-grammar/test/Examples/Lambda.hs | 2 +- distributors-grammar/test/Examples/LenVec.hs | 2 +- distributors-grammar/test/Examples/SExpr.hs | 2 +- distributors-grammar/test/Examples/SemVer.hs | 4 ++-- 11 files changed, 37 insertions(+), 21 deletions(-) diff --git a/distributors-core/CHANGELOG.md b/distributors-core/CHANGELOG.md index af69a8e3..800e01f5 100644 --- a/distributors-core/CHANGELOG.md +++ b/distributors-core/CHANGELOG.md @@ -150,8 +150,10 @@ - `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`, `beginWith` & `endWith` are removed: a separator is a - `terminal`, & delimiters compose around `sepBy` by `>*` & `*<`. +- `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 diff --git a/distributors-grammar/CHANGELOG.md b/distributors-grammar/CHANGELOG.md index a217d188..85d86cfe 100644 --- a/distributors-grammar/CHANGELOG.md +++ b/distributors-grammar/CHANGELOG.md @@ -8,9 +8,9 @@ & `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`, with a `terminal` - separator, delimiters composing around a `sepBy` grammar by `>*` & - `*<`. + `several`, `atLeast`, `chain1` & `exactly`, & `Control.Lens.Grammar.Symbol` + exports `sepWith`, `sepBy` of a `terminal` separator, delimiters + composing around a separated grammar by `>*` & `*<`. - `Grammor` defines `manyTillP` as @starK p <> q@, without recursing, so `sepBy` grammars, even of shapes without foci, have finite regular expressions & `Bnf`s. diff --git a/distributors-grammar/src/Control/Lens/Grammar.hs b/distributors-grammar/src/Control/Lens/Grammar.hs index d3eb35a7..4409091f 100644 --- a/distributors-grammar/src/Control/Lens/Grammar.hs +++ b/distributors-grammar/src/Control/Lens/Grammar.hs @@ -145,7 +145,7 @@ semverGrammar = _SemVer >*< optionP _Empty (terminal "+" >* identifiersG) where numberG = iso show read >~ someP (asIn @Char DecimalNumber) - identifiersG = sepBy (terminal ".") (atLeast 1) (someP charG) + identifiersG = sepWith "." (atLeast 1) (someP charG) charG = asIn LowercaseLetter >|< asIn UppercaseLetter >|< asIn DecimalNumber @@ -258,9 +258,9 @@ arithGrammar :: Grammar Char Arith arithGrammar = ruleRec "arith" sumG where sumG arith = rule "sum" $ - sepBy (terminal "+") (chain1 Left _Add) (prodG arith) + sepWith "+" (chain1 Left _Add) (prodG arith) prodG arith = rule "product" $ - sepBy (terminal "*") (chain1 Left _Mul) (factorG arith) + sepWith "*" (chain1 Left _Mul) (factorG arith) factorG arith = rule "factor" $ numberG >|< terminal "(" >* arith *< terminal ")" numberG = rule "number" $ @@ -380,7 +380,7 @@ lenvecGrammar :: CtxGrammar Char LenVec lenvecGrammar = _LenVec >? P.do let numberG = iso show read >~ someP (asIn @Char DecimalNumber) - vectorG n = sepBy (terminal ",") (exactly n) numberG + vectorG n = sepWith "," (exactly n) numberG len <- numberG -- bonds to _LenVec terminal ";" -- doesn't bond vectorG (fromIntegral len) -- bonds to _LenVec @@ -668,7 +668,7 @@ regexGrammar = _RegString >~ ruleRec "regex" altG where altG rex = rule "alternate" $ iso alternativesOf (foldr1 (>|<) :: [RegEx Char] -> RegEx Char) - >~ sepBy (terminal "|") (atLeast 1) (seqG rex) + >~ sepWith "|" (atLeast 1) (seqG rex) seqG rex = rule "sequence" $ iso itemsOf mconcat >~ manyP (exprG rex) @@ -736,7 +736,7 @@ regexGrammar = _RegString >~ ruleRec "regex" altG classCatG = rule "class-category" $ orP [ _AndAsIn >? terminal "\\p{" >* categoryG *< terminal "}" , _AndNotAsIn . iso toList fromList >? - terminal "\\P{" >* sepBy (terminal "|") (atLeast 1) categoryG *< terminal "}" + terminal "\\P{" >* sepWith "|" (atLeast 1) categoryG *< terminal "}" ] classOneOfG = rule "class-one-of" $ orP diff --git a/distributors-grammar/src/Control/Lens/Grammar/Symbol.hs b/distributors-grammar/src/Control/Lens/Grammar/Symbol.hs index a36ec396..e19789d8 100644 --- a/distributors-grammar/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/test/Examples/Arithmetic.hs b/distributors-grammar/test/Examples/Arithmetic.hs index 3c876e88..27046118 100644 --- a/distributors-grammar/test/Examples/Arithmetic.hs +++ b/distributors-grammar/test/Examples/Arithmetic.hs @@ -20,9 +20,9 @@ arithGrammar :: Grammar Char Arith arithGrammar = ruleRec "arith" sumG where sumG arith = rule "sum" $ - sepBy (terminal "+") (chain1 Left _Add) (prodG arith) + sepWith "+" (chain1 Left _Add) (prodG arith) prodG arith = rule "product" $ - sepBy (terminal "*") (chain1 Left _Mul) (factorG arith) + sepWith "*" (chain1 Left _Mul) (factorG arith) factorG arith = rule "factor" $ number >|< terminal "(" >* arith *< terminal ")" number = rule "number" $ diff --git a/distributors-grammar/test/Examples/Expression.hs b/distributors-grammar/test/Examples/Expression.hs index 4a7f3aa9..0f626c10 100644 --- a/distributors-grammar/test/Examples/Expression.hs +++ b/distributors-grammar/test/Examples/Expression.hs @@ -75,7 +75,7 @@ powGrammar = ruleRec "pow" $ \e -> nat >|< terminal "(" >* e *< terminal ")" nat = rule "nat" $ _Nat . iso show read >? someP (asIn @Char DecimalNumber) - in sepBy (terminal "^") (chain1 Right _Exp) atom + in sepWith "^" (chain1 Right _Exp) atom powExamples :: [(Expr, String)] powExamples = diff --git a/distributors-grammar/test/Examples/Json.hs b/distributors-grammar/test/Examples/Json.hs index ed8169be..f912bba6 100644 --- a/distributors-grammar/test/Examples/Json.hs +++ b/distributors-grammar/test/Examples/Json.hs @@ -57,7 +57,7 @@ jsonGrammar = rule "json" elementG -- members = member | member ',' members membersG json = rule "members" $ - sepBy (terminal ",") (atLeast 1) (memberG json) + sepWith "," (atLeast 1) (memberG json) -- member = ws string ws ':' element memberG json = rule "member" $ @@ -71,7 +71,7 @@ jsonGrammar = rule "json" elementG -- elements = element | element ',' elements elementsG json = rule "elements" $ - sepBy (terminal ",") (atLeast 1) json + sepWith "," (atLeast 1) json -- string = '"' characters '"' stringG = rule "string" $ diff --git a/distributors-grammar/test/Examples/Lambda.hs b/distributors-grammar/test/Examples/Lambda.hs index 7c5207aa..82d0c3c4 100644 --- a/distributors-grammar/test/Examples/Lambda.hs +++ b/distributors-grammar/test/Examples/Lambda.hs @@ -34,7 +34,7 @@ lambdaGrammar = ruleRec "lambda" termG -- Application: left-associative chain of atoms -- e.g., "f x y" parses as "(f x) y" appG term = rule "application" $ - sepBy (terminal " ") (chain1 Left _App) (atomG term) + sepWith " " (chain1 Left _App) (atomG term) -- Atomic term: variable or parenthesized term atomG term = rule "atom" $ orP diff --git a/distributors-grammar/test/Examples/LenVec.hs b/distributors-grammar/test/Examples/LenVec.hs index b1f0210b..1357172f 100644 --- a/distributors-grammar/test/Examples/LenVec.hs +++ b/distributors-grammar/test/Examples/LenVec.hs @@ -17,7 +17,7 @@ lenvecGrammar :: CtxGrammar Char LenVec lenvecGrammar = _LenVec >? P.do let numberG = iso show read >~ someP (asIn @Char DecimalNumber) - vectorG n = sepBy (terminal ",") (exactly n) 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/SExpr.hs b/distributors-grammar/test/Examples/SExpr.hs index 715fe3cf..6fdc9bde 100644 --- a/distributors-grammar/test/Examples/SExpr.hs +++ b/distributors-grammar/test/Examples/SExpr.hs @@ -29,7 +29,7 @@ sexprGrammar = ruleRec "sexpr" $ \sexpr -> orP -- List: parenthesized sequence of S-expressions -- Elements are separated by whitespace listG sexpr = rule "list" $ - terminal "(" >* sepBy (terminal " ") several sexpr *< terminal ")" + terminal "(" >* sepWith " " several sexpr *< terminal ")" -- Characters allowed in atoms: letters, digits, and symbols atomChars = diff --git a/distributors-grammar/test/Examples/SemVer.hs b/distributors-grammar/test/Examples/SemVer.hs index e9c99a2f..17c71c67 100644 --- a/distributors-grammar/test/Examples/SemVer.hs +++ b/distributors-grammar/test/Examples/SemVer.hs @@ -41,7 +41,7 @@ semverGrammar = _SemVer >*< optionP _Empty (terminal "+" >* identifiersG) where numberG = iso show read >~ someP (asIn @Char DecimalNumber) - identifiersG = sepBy (terminal ".") (atLeast 1) (someP charG) + identifiersG = sepWith "." (atLeast 1) (someP charG) charG = asIn LowercaseLetter >|< asIn UppercaseLetter >|< asIn DecimalNumber @@ -52,7 +52,7 @@ semverCtxGrammar :: CtxGrammar Char SemVer semverCtxGrammar = _SemVer >? P.do let numberG = iso show read >~ someP (asIn @Char DecimalNumber) - identifiersG = sepBy (terminal ".") (atLeast 1) (someP charG) + identifiersG = sepWith "." (atLeast 1) (someP charG) charG = asIn LowercaseLetter >|< asIn UppercaseLetter >|< asIn DecimalNumber From bb0659a123cdba90603a63e0530d8c28a92c7c12 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Fri, 13 Nov 2026 07:15:00 -0800 Subject: [PATCH 108/130] listed :: (IsList s, IsList t) => Iso [Item s] [Item t] s t A list of items as an IsList, like lens's List pattern, as an optic: act on an IsList as on lists by listed ~< p, or into its items by from listed. It replaces iso toList fromList in the grammars. Co-Authored-By: Claude Opus 5.5 --- distributors-core/CHANGELOG.md | 4 +++- distributors-core/src/Control/Lens/PartialIso.hs | 14 ++++++++++++++ distributors-core/src/Control/Lens/Prismoid.hs | 2 +- distributors-grammar/src/Control/Lens/Grammar.hs | 8 ++++---- 4 files changed, 22 insertions(+), 6 deletions(-) diff --git a/distributors-core/CHANGELOG.md b/distributors-core/CHANGELOG.md index 800e01f5..4828f0c5 100644 --- a/distributors-core/CHANGELOG.md +++ b/distributors-core/CHANGELOG.md @@ -48,6 +48,8 @@ - `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@. @@ -129,7 +131,7 @@ `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, & - `iso toList fromList >~ sepBy sep several p` of other `IsList`s; + `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`. diff --git a/distributors-core/src/Control/Lens/PartialIso.hs b/distributors-core/src/Control/Lens/PartialIso.hs index d0ee1281..b98ae1a8 100644 --- a/distributors-core/src/Control/Lens/PartialIso.hs +++ b/distributors-core/src/Control/Lens/PartialIso.hs @@ -42,6 +42,7 @@ module Control.Lens.PartialIso , notNulled , eotMaybe , eotList + , listed -- * Iterators , iterating , difoldl1 @@ -66,10 +67,13 @@ 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" @@ -649,6 +653,16 @@ 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 diff --git a/distributors-core/src/Control/Lens/Prismoid.hs b/distributors-core/src/Control/Lens/Prismoid.hs index f38b3d77..3b18f4ed 100644 --- a/distributors-core/src/Control/Lens/Prismoid.hs +++ b/distributors-core/src/Control/Lens/Prismoid.hs @@ -382,7 +382,7 @@ Separating `Control.Lens.Diopter.several`, `atLeast`, `atMost`, `inRange`, 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 are lists by @`iso` `toList` `fromList`@. +Other `IsList`s act as lists by @`Control.Lens.PartialIso.listed` ~<@. >>> let comma = Joker (() <$ char ',') >>> let digit = Joker (satisfy isDigit) diff --git a/distributors-grammar/src/Control/Lens/Grammar.hs b/distributors-grammar/src/Control/Lens/Grammar.hs index 4409091f..6bdc6482 100644 --- a/distributors-grammar/src/Control/Lens/Grammar.hs +++ b/distributors-grammar/src/Control/Lens/Grammar.hs @@ -735,18 +735,18 @@ regexGrammar = _RegString >~ ruleRec "regex" altG classCatG = rule "class-category" $ orP [ _AndAsIn >? terminal "\\p{" >* categoryG *< terminal "}" - , _AndNotAsIn . iso toList fromList >? + , _AndNotAsIn . from listed >? terminal "\\P{" >* sepWith "|" (atLeast 1) categoryG *< terminal "}" ] classOneOfG = rule "class-one-of" $ orP [ onlyOne charG - , terminal "[" >* (iso toList fromList >~ manyP charG) *< terminal "]" + , terminal "[" >* (listed ~< manyP charG) *< terminal "]" ] classNotOneOfG = rule "class-not-one-of" $ orP [ asEmpty >*< classCatG - , terminal "[^" >* (iso toList fromList >~ manyP charG) >*< + , terminal "[^" >* (listed ~< manyP charG) >*< optionP (_AndNotAsIn . _Empty) classCatG *< terminal "]" ] @@ -856,7 +856,7 @@ That means that it can generate a self-hosted definition. -} regbnfGrammar :: Grammar Char RegBnf regbnfGrammar = rule "regbnf" $ _RegBnf . _Bnf >~ - terminal "{start} = " >* regexGrammar >*< (iso toList fromList >~ manyP + terminal "{start} = " >* regexGrammar >*< (listed ~< manyP (terminal "\n" >* nonterminalG *< terminal " = " >*< regexGrammar)) From b732759fee7fa3d29298540fb452bde834c6fb07 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Fri, 13 Nov 2026 07:15:00 -0800 Subject: [PATCH 109/130] Rename JsonLiteral to JsonIlliteral & JsonStringLiteral to JsonLiteral JsonErrorSort's JsonLiteral is error info, a literal mismatch, not a literal value; the JsonType of a string literal takes its name. Co-Authored-By: Claude Opus 5.5 --- .../src/Control/Lens/Grammar/Json.hs | 24 +++++++++---------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/distributors-json/src/Control/Lens/Grammar/Json.hs b/distributors-json/src/Control/Lens/Grammar/Json.hs index 7d567463..357f463c 100644 --- a/distributors-json/src/Control/Lens/Grammar/Json.hs +++ b/distributors-json/src/Control/Lens/Grammar/Json.hs @@ -688,7 +688,7 @@ data JsonError = JsonError -- | How a t'JsonError' failed, so that alternatives report the closest. data JsonErrorSort - = JsonLiteral + = JsonIlliteral -- ^ a string literal mismatch; the alternative doesn't apply | JsonMismatch -- ^ the value was rejected as a whole @@ -775,8 +775,8 @@ jsonOrElse err1 err2 , jsonErrorSort = max (jsonErrorSort err1) (jsonErrorSort err2) , jsonErrorRules = jsonErrorRules err1 <> jsonErrorRules err2 } - | jsonErrorSort err2 == JsonLiteral - , jsonErrorSort err1 /= JsonLiteral = err1 + | jsonErrorSort err2 == JsonIlliteral + , jsonErrorSort err1 /= JsonIlliteral = err1 | otherwise = err2 where depth1 = length (jsonErrorPath err1) @@ -839,14 +839,14 @@ mapParsing f parsor = JsonParsor 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)) JsonLiteral []) + 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)) - JsonLiteral [] + JsonIlliteral [] v -> jsonMismatch "object" v literals :: Map Text a -> [String] @@ -937,7 +937,7 @@ instance (x ~ (), y ~ ()) => IsString (JsonParsor x y) where literal = Text.pack s parse = \case String t | t == literal -> Right () - v -> Left (JsonError [] [show s] (Just (Right v)) JsonLiteral []) + v -> Left (JsonError [] [show s] (Just (Right v)) JsonIlliteral []) instance JsonStr JsonParsor where jsonText = (primitiveParsor "string" $ \case String t -> Just t @@ -2009,7 +2009,7 @@ data JsonType | JsonBoolean -- ^ @true@ or @false@ | JsonNumber -- ^ numbers | JsonString -- ^ strings - | JsonStringLiteral Text -- ^ a string + | JsonLiteral Text -- ^ a string | JsonSubtype JsonType -- ^ some values of a type | JsonArray JsonElements -- ^ arrays of elements | JsonObject [JsonProperty] -- ^ objects of properties @@ -2111,7 +2111,7 @@ 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 [JsonStringLiteral "LT",JsonStringLiteral "EQ",JsonStringLiteral "GT"])]} +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)) @@ -2219,11 +2219,11 @@ 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 . JsonStringLiteral . Text.pack + fromString = typing . JsonLiteral . Text.pack instance JsonStr JsonTypor where jsonText = typing JsonString jsonEnumWith _ table = - typing (jsonUnion [JsonStringLiteral literal | (literal, _) <- table]) + typing (jsonUnion [JsonLiteral literal | (literal, _) <- table]) instance JsonVal JsonTypor where jsonNull = typing JsonNull jsonBool = typing JsonBoolean @@ -2383,7 +2383,7 @@ tsType rules names = typeNode JsonBoolean -> KeywordType BooleanKeyword JsonNumber -> KeywordType NumberKeyword JsonString -> KeywordType StringKeyword - JsonStringLiteral text -> LiteralType (TextLiteral text) + JsonLiteral text -> LiteralType (TextLiteral text) JsonSubtype t -> typeNode t t@(JsonArray _) -> typeNode (JsonUnion [t]) JsonObject props -> object props @@ -2433,7 +2433,7 @@ tsType rules names = typeNode [ MappedType Nothing "key" base exclusion (Just QuestionToken) (typeNode t) | (keyType, keyAlternatives, t) <- dicts , let - literalKeys = [l | JsonStringLiteral l <- keyAlternatives] + literalKeys = [l | JsonLiteral l <- keyAlternatives] excluded = [l | l <- literalKeys, l `elem` keys] base | length literalKeys == length keyAlternatives = typeNode keyType From d35adf201b25b871e56c83e7c8569ec3f463d402 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Fri, 13 Nov 2026 08:39:42 -0800 Subject: [PATCH 110/130] Varifocal: context-sensitive optics over MonadicTrans profunctors MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit type Varifocal s t a b = forall p m. (MonadicTrans p, Alternator (p m), MonadPlus m, Filterable m) => p m a (m b) -> p m s (m t) A Varifocal's shape may depend on the foci it builds, as no Bifocal's can. Its Applicative is the monad m of its profunctor, absorbed by joinP, so Bifocal ⊂ Varifocal & lens optics compose by (.). - MonadicTrans, in Data.Profunctor.Monadic: profunctors transforming a monad, with liftP & joinP, laws (tested) & a MINIMAL pragma; Printor & Parsor are instances. Parsector deliberately isn't: its failure backtracks by its state, which a monad's mzero can't reach. - >?=< applies a Varifocal by joinP. - Varifocus, the free concrete form: a free MonadicTrans Alternator on a focus, with constructors named for their methods (FocusP ... ManyTillP), keeping targets' own manyP & co; AVarifocal, varifocus, runVarifocus & cloneVarifocal, round-tripping as tested. - terminatedBy & delimited: sentinel-terminated & matching-delimited sequences, not context-free; a heredoc grammar example & doc. - Data.Profunctor.Monadic splits: Monadic & MonadicTrans to import unqualified, & Data.Profunctor.Monadic.Do, the qualified do-notation. - Control.Lens.Grammar re-exports Control.Lens.Varifocal & Data.Profunctor.Monadic. Co-Authored-By: Claude Opus 5.5 --- distributors-core/CHANGELOG.md | 13 ++ distributors-core/distributors.cabal | 2 + .../Internal/Distributor/NestedPrismTH.hs | 2 +- .../src/Control/Lens/Varifocal.hs | 211 ++++++++++++++++++ .../src/Data/Profunctor/Monadic.hs | 61 ++--- .../src/Data/Profunctor/Monadic/Do.hs | 57 +++++ distributors-grammar/CHANGELOG.md | 4 + .../distributors-grammar.cabal | 2 + .../src/Control/Lens/Grammar.hs | 42 +++- .../src/Data/Profunctor/Grammar.hs | 5 + distributors-grammar/test/Examples/Heredoc.hs | 42 ++++ distributors-grammar/test/Examples/LenVec.hs | 2 +- distributors-grammar/test/Examples/SemVer.hs | 2 +- distributors-grammar/test/Main.hs | 2 + .../test/Properties/Varifocal.hs | 100 +++++++++ .../src/Control/Lens/Grammar/TypeScript.hs | 4 +- 16 files changed, 504 insertions(+), 47 deletions(-) create mode 100644 distributors-core/src/Control/Lens/Varifocal.hs create mode 100644 distributors-core/src/Data/Profunctor/Monadic/Do.hs create mode 100644 distributors-grammar/test/Examples/Heredoc.hs create mode 100644 distributors-grammar/test/Properties/Varifocal.hs diff --git a/distributors-core/CHANGELOG.md b/distributors-core/CHANGELOG.md index 4828f0c5..662d987e 100644 --- a/distributors-core/CHANGELOG.md +++ b/distributors-core/CHANGELOG.md @@ -41,6 +41,15 @@ `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 applicator `>?=<`, the free concrete + form `Varifocus`, `AVarifocal`, `varifocus`, `runVarifocus` & + `cloneVarifocal`; & `terminatedBy` & `delimited`, sentinel-terminated & + matching-delimited sequences, which no `Bifocal` can express. +- `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 @@ -149,6 +158,10 @@ - `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`. diff --git a/distributors-core/distributors.cabal b/distributors-core/distributors.cabal index aa474cab..dbeabb3d 100644 --- a/distributors-core/distributors.cabal +++ b/distributors-core/distributors.cabal @@ -37,11 +37,13 @@ library Control.Lens.Monocle Control.Lens.PartialIso Control.Lens.Prismoid + Control.Lens.Varifocal Control.Lens.Wither Data.Monoid.Disjunctive Data.Profunctor.Distributor Data.Profunctor.Filtrator Data.Profunctor.Monadic + Data.Profunctor.Monadic.Do Data.Profunctor.Monoidal Data.Profunctor.Monoidal.Cocartesian Data.Traversable.Homogeneous diff --git a/distributors-core/src/Control/Lens/Internal/Distributor/NestedPrismTH.hs b/distributors-core/src/Control/Lens/Internal/Distributor/NestedPrismTH.hs index a8a68e23..97ee0261 100644 --- a/distributors-core/src/Control/Lens/Internal/Distributor/NestedPrismTH.hs +++ b/distributors-core/src/Control/Lens/Internal/Distributor/NestedPrismTH.hs @@ -46,7 +46,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./ -- diff --git a/distributors-core/src/Control/Lens/Varifocal.hs b/distributors-core/src/Control/Lens/Varifocal.hs new file mode 100644 index 00000000..48ccb6cf --- /dev/null +++ b/distributors-core/src/Control/Lens/Varifocal.hs @@ -0,0 +1,211 @@ +{- | +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 + , cloneVarifocal + -- * Applicator + , (>?=<) + -- * Combinators + , terminatedBy + , delimited + ) where + +import Control.Applicative (Alternative (..)) +import Control.Lens +import Control.Lens.PartialIso ((>?)) +import Control.Monad (MonadPlus (..), ap) +import Data.Monoid.Disjunctive (DisjunctiveMonoid) +import Data.Profunctor (Cochoice (..)) +import Data.Profunctor.Distributor +import Data.Profunctor.Filtrator (Filtrator (..), mfiltrate) +import Data.Profunctor.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] +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`. -} +varifocus :: AVarifocal s t a b -> Varifocus a b [] s t +varifocus vari = joinP (vari (rmap pure FocusP)) + +{- | Run a t'Varifocus' on a `MonadicTrans` `Alternator`, +interpreting each constructor by its method, +& its lists as the `MonadPlus`'s choices. +-} +runVarifocus + :: forall p m a b s t. (MonadicTrans p, Alternator (p m), MonadPlus m) + => Varifocus a b [] s t -> p m a b -> p m s t +runVarifocus v p = go v + where + go :: Varifocus a b [] s' t' -> p m s' t' + go = \case + FocusP -> p + LiftP xs -> liftP (foldr (mplus . pure) mzero xs) + BindP x k -> go x >>= go . k + LmapP f x -> lmap f (go x) + AltsP xs -> case map go xs of + [] -> empty + ys -> foldr1 (<|>) ys + 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 (runVarifocus (varifocus vari) (joinP q)) + +{- | Action of a `Varifocal` on `MonadicTrans` `Alternator`s, +absorbing its monad by `joinP`. + +> prop> vari >?=< p = joinP (vari (rmap pure p)) +-} +(>?=<) + :: (MonadicTrans p, Alternator (p m), MonadPlus m, Filterable m) + => Varifocal s t a b -> p m a b -> p m s t +vari >?=< p = joinP (vari (rmap pure p)) +infixl 4 >?=< + +{- | Zero or more foci, then one which @end@s them, deciding by +each focus built, as no `Control.Lens.Bifocal.Bifocal` can, +like a sentinel-terminated sequence, a C string's. +A list which doesn't end by its first ending focus doesn't match. +-} +terminatedBy :: (a -> Bool) -> Varifocal' [a] a +terminatedBy end q = rmap pure go + where + focus = joinP q + go = _Cons >? (focus P.>>= \b -> if end b then asEmpty else go) + +{- | Foci opened by the first, & closed by the first after it +which matches it, deciding by the opening focus built, +like a heredoc's tag, or a fenced code block's fence, +which no `Control.Lens.Bifocal.Bifocal` can, since its language, +of matching delimiters, isn't context-free. +A list which doesn't close by its first match doesn't match. +After its first focus, @open@, it's @`terminatedBy` (same open)@. +-} +delimited :: (a -> a -> Bool) -> Varifocal' [a] a +delimited same q = rmap pure + (_Cons >? (joinP q P.>>= \open -> joinP (terminatedBy (same open) q))) diff --git a/distributors-core/src/Data/Profunctor/Monadic.hs b/distributors-core/src/Data/Profunctor/Monadic.hs index ba2a0713..716500ae 100644 --- a/distributors-core/src/Data/Profunctor/Monadic.hs +++ b/distributors-core/src/Data/Profunctor/Monadic.hs @@ -10,54 +10,39 @@ 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. - ->>> :set -XQualifiedDo ->>> import qualified Data.Profunctor.Monadic as P - -See "Control.Lens.Grammar#t:CtxGrammar" for -an example of how to use qualified do-notation -with pattern bonding. +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 - , (>>=) - , (>>) - , return - , fail + -- * MonadicTrans + , MonadicTrans (..) ) where -import Control.Lens -import Control.Monad hiding ((>>=), (>>), return) -import Data.Profunctor.Monoidal -import Prelude hiding ((>>=), (>>), return) +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)) -{- | The pair bonding operator @P.@`>>=` is a context-sensitive -version of `>*<`. +{- | 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`. -> prop> x >*< y = x P.>>= (\_ -> y) --} -(>>=) :: Monadic p => p a b -> (b -> p c d) -> p (a,c) (b,d) -infixl 1 >>= -p >>= f = do - b <- lmap fst p - d <- lmap snd (f b) - pure (b,d) - -{- | @P.@`>>` sequences actions. -} -(>>) :: Monadic p => p () c -> p a b -> p a b -infixl 1 >> -x >> y = do _ <- lmap (const ()) x; y - -{- | @P.@`return` is a `Monadic`-restricted -version of `pureP`. - -> prop> pureP = P.return +`liftP` is a monad morphism. + +> prop> liftP . pure = pure +> prop> liftP (m >>= k) = liftP m >>= liftP . k +> prop> joinP (fmap pure p) = p +> prop> joinP = join . fmap liftP -} -return :: (Monadic p, Choice p) => APrism a b () () -> p a b -return = pureP +class (forall m x. Monad m => Monad (p m x)) => 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/distributors-core/src/Data/Profunctor/Monadic/Do.hs b/distributors-core/src/Data/Profunctor/Monadic/Do.hs new file mode 100644 index 00000000..ec51eb2d --- /dev/null +++ b/distributors-core/src/Data/Profunctor/Monadic/Do.hs @@ -0,0 +1,57 @@ +{-| +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 + +Qualified do-notation for `Monadic` profunctors, +with pattern bonding, to import qualified. + +>>> :set -XQualifiedDo +>>> 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.Do + ( (>>=) + , (>>) + , return + -- | The "Prelude"'s, for patterns which may fail. + , fail + ) where + +import Control.Lens +import Data.Profunctor.Monadic (Monadic) +import Data.Profunctor.Monoidal +import Prelude hiding ((>>=), (>>), return) + +{- | The pair bonding operator @P.@`>>=` is a context-sensitive +version of `>*<`. + +> prop> x >*< y = x P.>>= (\_ -> y) +-} +(>>=) :: Monadic p => p a b -> (b -> p c d) -> p (a,c) (b,d) +infixl 1 >>= +p >>= f = do + b <- lmap fst p + d <- lmap snd (f b) + pure (b,d) + +{- | @P.@`>>` sequences actions. -} +(>>) :: Monadic p => p () c -> p a b -> p a b +infixl 1 >> +x >> y = do _ <- lmap (const ()) x; y + +{- | @P.@`return` is a `Monadic`-restricted +version of `pureP`. + +> prop> pureP = P.return +-} +return :: (Monadic p, Choice p) => APrism a b () () -> p a b +return = pureP diff --git a/distributors-grammar/CHANGELOG.md b/distributors-grammar/CHANGELOG.md index 85d86cfe..344bb815 100644 --- a/distributors-grammar/CHANGELOG.md +++ b/distributors-grammar/CHANGELOG.md @@ -11,6 +11,10 @@ `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. diff --git a/distributors-grammar/distributors-grammar.cabal b/distributors-grammar/distributors-grammar.cabal index 947755cb..1ad8f719 100644 --- a/distributors-grammar/distributors-grammar.cabal +++ b/distributors-grammar/distributors-grammar.cabal @@ -169,6 +169,7 @@ test-suite test Examples.Arithmetic Examples.Chain Examples.Expression + Examples.Heredoc Examples.Json Examples.Lambda Examples.LenVec @@ -176,6 +177,7 @@ test-suite test Examples.SemVer Examples.SExpr Properties.Kleene + Properties.Varifocal Paths_distributors_grammar autogen-modules: Paths_distributors_grammar diff --git a/distributors-grammar/src/Control/Lens/Grammar.hs b/distributors-grammar/src/Control/Lens/Grammar.hs index 6bdc6482..e6a29504 100644 --- a/distributors-grammar/src/Control/Lens/Grammar.hs +++ b/distributors-grammar/src/Control/Lens/Grammar.hs @@ -55,7 +55,7 @@ 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 @@ -76,6 +76,7 @@ import Control.Lens.Grammar.Token as X import Control.Lens.PartialIso 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 @@ -358,7 +359,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. @@ -374,7 +375,7 @@ _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 @@ -387,7 +388,7 @@ lenvecGrammar = _LenVec >? P.do :} 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@, @@ -436,6 +437,39 @@ 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, +run by the applicator `>?=<` on a `MonadicTrans` profunctor, +like a t'Printor' or t'Parsor'. A heredoc's lines are its foci, +its tag, its body, & its tag again, `delimited` by the first line +equal to the opening tag, a language which isn't context-free. + +>>> :{ +data Heredoc = Heredoc String [String] deriving (Eq, Show) +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 = lined >~ symbol "<<" >* (delimited (==) >?=< lineP) + where + symbol :: String -> p m () () + symbol = terminal + lineP = manyP (notOneOf "\n") *< symbol "\n" + lined = iso + (\(Heredoc tag body) -> tag : body ++ [tag]) + (\case + tag : rest -> Heredoc tag (if null rest then [] else init rest) + [] -> Heredoc "" []) +:} + +>>> ($ "") <$> printP (heredocP :: Printor String Maybe Heredoc Heredoc) (Heredoc "EOF" ["hi"]) +Just "<>> parseP (heredocP :: Parsor String Maybe Heredoc Heredoc) "<>> ($ "") <$> printP (heredocP :: Printor String Maybe Heredoc Heredoc) (Heredoc "EOF" ["EOF"]) +Nothing + Finally, `CtxGrammar`s support failure reporting and backtracking. This has no effect on `Control.Lens.Grammar.printG`, `Control.Lens.Grammar.parseG` or `Control.Lens.Grammar.unparseG`; diff --git a/distributors-grammar/src/Data/Profunctor/Grammar.hs b/distributors-grammar/src/Data/Profunctor/Grammar.hs index 522ca1b6..5e5066d7 100644 --- a/distributors-grammar/src/Data/Profunctor/Grammar.hs +++ b/distributors-grammar/src/Data/Profunctor/Grammar.hs @@ -39,6 +39,7 @@ 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 @@ -88,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 @@ -216,6 +219,8 @@ 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 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 $ diff --git a/distributors-grammar/test/Examples/Heredoc.hs b/distributors-grammar/test/Examples/Heredoc.hs new file mode 100644 index 00000000..2131380c --- /dev/null +++ b/distributors-grammar/test/Examples/Heredoc.hs @@ -0,0 +1,42 @@ +module Examples.Heredoc + ( Heredoc (..) + , heredocP + , 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, `delimited` 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 "<<" >* (delimited (==) >?=< lineP) + where + symbol :: String -> p m () () + symbol = terminal + lineP = manyP (notOneOf "\n") *< symbol "\n" + +heredocExamples :: [(Heredoc, String)] +heredocExamples = + [ (Heredoc "EOF" ["hello", "world"], "< String -> Maybe String + printed v s = + ($ "") <$> printP (v >?=< (anyToken :: Printor String Maybe Char Char)) s + parsed :: Varifocal' String Char -> String -> Maybe (String, String) + parsed v = parseP (v >?=< (anyToken :: Parsor String Maybe Char Char)) + ended :: Varifocal' String Char + ended = terminatedBy (== '.') + 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 "terminatedBy" $ 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 "cloneVarifocal, by its free Varifocus" $ do + prop "clones terminatedBy, 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 delimited" $ 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 (v >?=< (anyToken :: Printor String Maybe Char Char)) e + parsedE :: Varifocal' (Either Int String) Char -> String -> Maybe (Either Int String, String) + parsedE v = parseP (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 "Bifocal ⊂ Varifocal" $ + prop "a Prismoid applies by >?=< 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/src/Control/Lens/Grammar/TypeScript.hs b/distributors-json/src/Control/Lens/Grammar/TypeScript.hs index 50862fb4..f81edb19 100644 --- a/distributors-json/src/Control/Lens/Grammar/TypeScript.hs +++ b/distributors-json/src/Control/Lens/Grammar/TypeScript.hs @@ -67,7 +67,7 @@ import Control.Lens import Control.Lens.Grammar import Data.Char (chr, ord) import Data.Maybe (fromMaybe, listToMaybe) -import Data.Profunctor.Monadic qualified as P +import Data.Profunctor.Monadic.Do qualified as P import Data.Text (Text) import Data.Text qualified as Text import Numeric (readHex, showHex) @@ -561,7 +561,7 @@ 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.>>=`, the depths that a @}@ is scanned by. +@P.@`Data.Profunctor.Monadic.Do.>>=`, the depths that a @}@ is scanned by. -} tsTokensGrammar :: CtxGrammar Char [TsToken] tsTokensGrammar = rmap From 4e3d69deb0d120875d9b055ee954d76754747c16 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Fri, 13 Nov 2026 08:44:41 -0800 Subject: [PATCH 111/130] varifocus at any MonadPlus; runVarifocus at the same monad varifocus :: MonadPlus m => AVarifocal s t a b -> Varifocus a b m s t embeds the captured list monad's choices into m, so runVarifocus interprets LiftP by liftP directly, needing only Monad m. Co-Authored-By: Claude Opus 5.5 --- .../src/Control/Lens/Varifocal.hs | 33 ++++++++++++++----- 1 file changed, 24 insertions(+), 9 deletions(-) diff --git a/distributors-core/src/Control/Lens/Varifocal.hs b/distributors-core/src/Control/Lens/Varifocal.hs index 48ccb6cf..04ccb2fa 100644 --- a/distributors-core/src/Control/Lens/Varifocal.hs +++ b/distributors-core/src/Control/Lens/Varifocal.hs @@ -141,23 +141,38 @@ instance Monad m => Filtrator (Varifocus a b m) where instance MonadicTrans (Varifocus a b) where liftP = LiftP -{- | The t'Varifocus' of `AVarifocal`. -} -varifocus :: AVarifocal s t a b -> Varifocus a b [] s t -varifocus vari = joinP (vari (rmap pure FocusP)) +{- | 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' on a `MonadicTrans` `Alternator`, -interpreting each constructor by its method, -& its lists as the `MonadPlus`'s choices. +interpreting each constructor by its method. -} runVarifocus - :: forall p m a b s t. (MonadicTrans p, Alternator (p m), MonadPlus m) - => Varifocus a b [] s t -> p m a b -> p m s t + :: 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 runVarifocus v p = go v where - go :: Varifocus a b [] s' t' -> p m s' t' + go :: Varifocus a b m s' t' -> p m s' t' go = \case FocusP -> p - LiftP xs -> liftP (foldr (mplus . pure) mzero xs) + LiftP mt -> liftP mt BindP x k -> go x >>= go . k LmapP f x -> lmap f (go x) AltsP xs -> case map go xs of From 1914d242c18f36a8a5f459620bd51b28a29bed52 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Fri, 13 Nov 2026 08:47:09 -0800 Subject: [PATCH 112/130] Rename >?=< to contextually contextually :: Varifocal s t a b -> p m a b -> p m s t, a Varifocal's applicator, conflicting with no names in the library, lens, profunctors or aeson. Co-Authored-By: Claude Opus 5.5 --- distributors-core/CHANGELOG.md | 2 +- distributors-core/src/Control/Lens/Varifocal.hs | 9 ++++----- distributors-grammar/src/Control/Lens/Grammar.hs | 4 ++-- distributors-grammar/test/Examples/Heredoc.hs | 2 +- distributors-grammar/test/Properties/Varifocal.hs | 10 +++++----- 5 files changed, 13 insertions(+), 14 deletions(-) diff --git a/distributors-core/CHANGELOG.md b/distributors-core/CHANGELOG.md index 662d987e..591d5194 100644 --- a/distributors-core/CHANGELOG.md +++ b/distributors-core/CHANGELOG.md @@ -44,7 +44,7 @@ - `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 applicator `>?=<`, the free concrete + by `joinP`; with `Varifocal'`, the applicator `contextually`, the free concrete form `Varifocus`, `AVarifocal`, `varifocus`, `runVarifocus` & `cloneVarifocal`; & `terminatedBy` & `delimited`, sentinel-terminated & matching-delimited sequences, which no `Bifocal` can express. diff --git a/distributors-core/src/Control/Lens/Varifocal.hs b/distributors-core/src/Control/Lens/Varifocal.hs index 04ccb2fa..cb0afb76 100644 --- a/distributors-core/src/Control/Lens/Varifocal.hs +++ b/distributors-core/src/Control/Lens/Varifocal.hs @@ -18,7 +18,7 @@ module Control.Lens.Varifocal , runVarifocus , cloneVarifocal -- * Applicator - , (>?=<) + , contextually -- * Combinators , terminatedBy , delimited @@ -194,13 +194,12 @@ cloneVarifocal vari q = rmap pure (runVarifocus (varifocus vari) (joinP q)) {- | Action of a `Varifocal` on `MonadicTrans` `Alternator`s, absorbing its monad by `joinP`. -> prop> vari >?=< p = joinP (vari (rmap pure p)) +> prop> contextually vari p = joinP (vari (rmap pure p)) -} -(>?=<) +contextually :: (MonadicTrans p, Alternator (p m), MonadPlus m, Filterable m) => Varifocal s t a b -> p m a b -> p m s t -vari >?=< p = joinP (vari (rmap pure p)) -infixl 4 >?=< +contextually vari p = joinP (vari (rmap pure p)) {- | Zero or more foci, then one which @end@s them, deciding by each focus built, as no `Control.Lens.Bifocal.Bifocal` can, diff --git a/distributors-grammar/src/Control/Lens/Grammar.hs b/distributors-grammar/src/Control/Lens/Grammar.hs index e6a29504..fc63bf42 100644 --- a/distributors-grammar/src/Control/Lens/Grammar.hs +++ b/distributors-grammar/src/Control/Lens/Grammar.hs @@ -439,7 +439,7 @@ 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, -run by the applicator `>?=<` on a `MonadicTrans` profunctor, +run `contextually` on a `MonadicTrans` profunctor, like a t'Printor' or t'Parsor'. A heredoc's lines are its foci, its tag, its body, & its tag again, `delimited` by the first line equal to the opening tag, a language which isn't context-free. @@ -451,7 +451,7 @@ heredocP ( MonadicTrans p, Alternator (p m), MonadPlus m, Filterable m , Tokenized Char (p m Char Char), TerminalSymbol Char (p m () ()) ) => p m Heredoc Heredoc -heredocP = lined >~ symbol "<<" >* (delimited (==) >?=< lineP) +heredocP = lined >~ symbol "<<" >* contextually (delimited (==)) lineP where symbol :: String -> p m () () symbol = terminal diff --git a/distributors-grammar/test/Examples/Heredoc.hs b/distributors-grammar/test/Examples/Heredoc.hs index 2131380c..951cdc51 100644 --- a/distributors-grammar/test/Examples/Heredoc.hs +++ b/distributors-grammar/test/Examples/Heredoc.hs @@ -28,7 +28,7 @@ heredocP ( 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 "<<" >* (delimited (==) >?=< lineP) +heredocP = heredocLines >~ symbol "<<" >* contextually (delimited (==)) lineP where symbol :: String -> p m () () symbol = terminal diff --git a/distributors-grammar/test/Properties/Varifocal.hs b/distributors-grammar/test/Properties/Varifocal.hs index b7d67321..b86d21d4 100644 --- a/distributors-grammar/test/Properties/Varifocal.hs +++ b/distributors-grammar/test/Properties/Varifocal.hs @@ -12,9 +12,9 @@ varifocalProperties = do let printed :: Varifocal' String Char -> String -> Maybe String printed v s = - ($ "") <$> printP (v >?=< (anyToken :: Printor String Maybe Char Char)) s + ($ "") <$> printP (contextually v (anyToken :: Printor String Maybe Char Char)) s parsed :: Varifocal' String Char -> String -> Maybe (String, String) - parsed v = parseP (v >?=< (anyToken :: Parsor String Maybe Char Char)) + parsed v = parseP (contextually v (anyToken :: Parsor String Maybe Char Char)) ended :: Varifocal' String Char ended = terminatedBy (== '.') plain = Prelude.filter (/= '.') <$> arbitrary @@ -84,16 +84,16 @@ varifocalProperties = do composite = _Right . ended printedE :: Varifocal' (Either Int String) Char -> Either Int String -> Maybe String printedE v e = - ($ "") <$> printP (v >?=< (anyToken :: Printor String Maybe Char Char)) e + ($ "") <$> printP (contextually v (anyToken :: Printor String Maybe Char Char)) e parsedE :: Varifocal' (Either Int String) Char -> String -> Maybe (Either Int String, String) - parsedE v = parseP (v >?=< (anyToken :: Parsor String Maybe Char Char)) + parsedE v = parseP (contextually 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 "Bifocal ⊂ Varifocal" $ - prop "a Prismoid applies by >?=< as by >?*" $ \(s :: String) -> + prop "a Prismoid applies contextually as by >?*" $ \(s :: String) -> parsed (atLeast 1) s === parseP (atLeast 1 >?* (anyToken :: Parsor String Maybe Char Char)) s .&&. printed (atLeast 1) s From 3b455b2a2e8f90f26623237626d76efc64b0de5b Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Fri, 13 Nov 2026 08:49:34 -0800 Subject: [PATCH 113/130] Link heredoc's first mention in Varifocal's & Grammar's docs Co-Authored-By: Claude Opus 5.5 --- distributors-core/src/Control/Lens/Varifocal.hs | 3 ++- distributors-grammar/src/Control/Lens/Grammar.hs | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/distributors-core/src/Control/Lens/Varifocal.hs b/distributors-core/src/Control/Lens/Varifocal.hs index cb0afb76..a0314c29 100644 --- a/distributors-core/src/Control/Lens/Varifocal.hs +++ b/distributors-core/src/Control/Lens/Varifocal.hs @@ -214,7 +214,8 @@ terminatedBy end q = rmap pure go {- | Foci opened by the first, & closed by the first after it which matches it, deciding by the opening focus built, -like a heredoc's tag, or a fenced code block's fence, +like a [heredoc](https://en.wikipedia.org/wiki/Here_document)'s tag, +or a fenced code block's fence, which no `Control.Lens.Bifocal.Bifocal` can, since its language, of matching delimiters, isn't context-free. A list which doesn't close by its first match doesn't match. diff --git a/distributors-grammar/src/Control/Lens/Grammar.hs b/distributors-grammar/src/Control/Lens/Grammar.hs index fc63bf42..f5acde94 100644 --- a/distributors-grammar/src/Control/Lens/Grammar.hs +++ b/distributors-grammar/src/Control/Lens/Grammar.hs @@ -440,7 +440,8 @@ 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, run `contextually` on a `MonadicTrans` profunctor, -like a t'Printor' or t'Parsor'. A heredoc's lines are its foci, +like a t'Printor' or t'Parsor'. +A [heredoc](https://en.wikipedia.org/wiki/Here_document)'s lines are its foci, its tag, its body, & its tag again, `delimited` by the first line equal to the opening tag, a language which isn't context-free. From 9d8d1621a677f3cc17e3dcdd145d7227553d2fe7 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Fri, 13 Nov 2026 09:06:56 -0800 Subject: [PATCH 114/130] contextually in any CtxGrammar, by Varifocus; contextuallyT for MonadicTrans contextually :: (Monadic p, Alternator p) => AVarifocal s t a b -> p a b -> p s t runs a Varifocal's concrete form, interpreting its list monad's choices & failures by the Alternator's own, so it applies in CtxGrammars, TypeScript's included, & backtracks as Parsector does. The MonadicTrans applicator & runner are renamed contextuallyT & runVarifocusT. The heredoc example is a CtxGrammar, running by parseG, printG, parsecG & unparsecG, as tested & documented. Co-Authored-By: Claude Opus 5.5 --- distributors-core/CHANGELOG.md | 6 +- .../src/Control/Lens/Varifocal.hs | 57 ++++++++++++++++--- .../src/Control/Lens/Grammar.hs | 30 +++++----- distributors-grammar/test/Examples/Heredoc.hs | 10 +++- .../test/Properties/Varifocal.hs | 21 +++++-- 5 files changed, 91 insertions(+), 33 deletions(-) diff --git a/distributors-core/CHANGELOG.md b/distributors-core/CHANGELOG.md index 591d5194..a7a5e224 100644 --- a/distributors-core/CHANGELOG.md +++ b/distributors-core/CHANGELOG.md @@ -44,8 +44,10 @@ - `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 applicator `contextually`, the free concrete - form `Varifocus`, `AVarifocal`, `varifocus`, `runVarifocus` & + 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`; & `terminatedBy` & `delimited`, sentinel-terminated & matching-delimited sequences, which no `Bifocal` can express. - `MonadicTrans`, in `Data.Profunctor.Monadic`, profunctors transforming a diff --git a/distributors-core/src/Control/Lens/Varifocal.hs b/distributors-core/src/Control/Lens/Varifocal.hs index a0314c29..7839d153 100644 --- a/distributors-core/src/Control/Lens/Varifocal.hs +++ b/distributors-core/src/Control/Lens/Varifocal.hs @@ -16,9 +16,11 @@ module Control.Lens.Varifocal , Varifocus (..) , varifocus , runVarifocus + , runVarifocusT , cloneVarifocal -- * Applicator , contextually + , contextuallyT -- * Combinators , terminatedBy , delimited @@ -32,7 +34,7 @@ import Data.Monoid.Disjunctive (DisjunctiveMonoid) import Data.Profunctor (Cochoice (..)) import Data.Profunctor.Distributor import Data.Profunctor.Filtrator (Filtrator (..), mfiltrate) -import Data.Profunctor.Monadic (MonadicTrans (..)) +import Data.Profunctor.Monadic (Monadic, MonadicTrans (..)) import qualified Data.Profunctor.Monadic.Do as P import Data.Profunctor.Monoidal (asEmpty) import Data.Profunctor.Monoidal.Cocartesian @@ -161,13 +163,40 @@ varifocus vari = go (joinP (vari (rmap pure FocusP))) 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 -> case map pure xs of + [] -> empty + ys -> foldr1 (<|>) ys + BindP x k -> go x >>= go . k + LmapP f x -> lmap f (go x) + AltsP xs -> case map go xs of + [] -> empty + ys -> foldr1 (<|>) ys + 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. -} -runVarifocus +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 -runVarifocus v p = go v +runVarifocusT v p = go v where go :: Varifocus a b m s' t' -> p m s' t' go = \case @@ -189,17 +218,29 @@ runVarifocus v p = go v monomorphically typed `Varifocal` for different purposes. -} cloneVarifocal :: AVarifocal s t a b -> Varifocal s t a b -cloneVarifocal vari q = rmap pure (runVarifocus (varifocus vari) (joinP q)) +cloneVarifocal vari q = rmap pure (runVarifocusT (varifocus vari) (joinP q)) -{- | Action of a `Varifocal` on `MonadicTrans` `Alternator`s, -absorbing its monad by `joinP`. +{- | 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 p = joinP (vari (rmap pure p)) +> 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 -contextually vari p = joinP (vari (rmap pure p)) +contextuallyT vari p = joinP (vari (rmap pure p)) {- | Zero or more foci, then one which @end@s them, deciding by each focus built, as no `Control.Lens.Bifocal.Bifocal` can, diff --git a/distributors-grammar/src/Control/Lens/Grammar.hs b/distributors-grammar/src/Control/Lens/Grammar.hs index f5acde94..074e755c 100644 --- a/distributors-grammar/src/Control/Lens/Grammar.hs +++ b/distributors-grammar/src/Control/Lens/Grammar.hs @@ -439,24 +439,18 @@ 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, -run `contextually` on a `MonadicTrans` profunctor, -like a t'Printor' or t'Parsor'. +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, `delimited` by the first line equal to the opening tag, a language which isn't context-free. >>> :{ data Heredoc = Heredoc String [String] deriving (Eq, Show) -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 = lined >~ symbol "<<" >* contextually (delimited (==)) lineP +heredocG :: CtxGrammar Char Heredoc +heredocG = lined >~ terminal "<<" >* contextually (delimited (==)) lineG where - symbol :: String -> p m () () - symbol = terminal - lineP = manyP (notOneOf "\n") *< symbol "\n" + lineG = manyP (notOneOf "\n") *< terminal "\n" lined = iso (\(Heredoc tag body) -> tag : body ++ [tag]) (\case @@ -464,12 +458,14 @@ heredocP = lined >~ symbol "<<" >* contextually (delimited (==)) lineP [] -> Heredoc "" []) :} ->>> ($ "") <$> printP (heredocP :: Printor String Maybe Heredoc Heredoc) (Heredoc "EOF" ["hi"]) -Just "<>> parseP (heredocP :: Parsor String Maybe Heredoc Heredoc) "<>> ($ "") <$> printP (heredocP :: Printor String Maybe Heredoc Heredoc) (Heredoc "EOF" ["EOF"]) -Nothing +>>> [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 `Control.Lens.Grammar.printG`, diff --git a/distributors-grammar/test/Examples/Heredoc.hs b/distributors-grammar/test/Examples/Heredoc.hs index 951cdc51..a8bf96d7 100644 --- a/distributors-grammar/test/Examples/Heredoc.hs +++ b/distributors-grammar/test/Examples/Heredoc.hs @@ -1,6 +1,7 @@ module Examples.Heredoc ( Heredoc (..) , heredocP + , heredocG , heredocExamples ) where @@ -28,12 +29,19 @@ heredocP ( 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 "<<" >* contextually (delimited (==)) lineP +heredocP = heredocLines >~ symbol "<<" >* contextuallyT (delimited (==)) lineP where symbol :: String -> p m () () symbol = terminal lineP = manyP (notOneOf "\n") *< symbol "\n" +-- | Heredocs as a `CtxGrammar`, applying `delimited` `contextually`, +-- so it runs as any `CtxGrammar` does, by `Parsector` too. +heredocG :: CtxGrammar Char Heredoc +heredocG = heredocLines >~ terminal "<<" >* contextually (delimited (==)) lineG + where + lineG = manyP (notOneOf "\n") *< terminal "\n" + heredocExamples :: [(Heredoc, String)] heredocExamples = [ (Heredoc "EOF" ["hello", "world"], "< String -> Maybe String printed v s = - ($ "") <$> printP (contextually v (anyToken :: Printor String Maybe Char Char)) s + ($ "") <$> printP (contextuallyT v (anyToken :: Printor String Maybe Char Char)) s parsed :: Varifocal' String Char -> String -> Maybe (String, String) - parsed v = parseP (contextually v (anyToken :: Parsor String Maybe Char Char)) + parsed v = parseP (contextuallyT v (anyToken :: Parsor String Maybe Char Char)) ended :: Varifocal' String Char ended = terminatedBy (== '.') plain = Prelude.filter (/= '.') <$> arbitrary @@ -84,16 +84,27 @@ varifocalProperties = do composite = _Right . ended printedE :: Varifocal' (Either Int String) Char -> Either Int String -> Maybe String printedE v e = - ($ "") <$> printP (contextually v (anyToken :: Printor String Maybe Char Char)) e + ($ "") <$> printP (contextuallyT v (anyToken :: Printor String Maybe Char Char)) e parsedE :: Varifocal' (Either Int String) Char -> String -> Maybe (Either Int String, String) - parsedE v = parseP (contextually v (anyToken :: Parsor String Maybe Char Char)) + parsedE v = parseP (contextuallyT v (anyToken :: Parsor String Maybe Char Char)) prop "prints & parses as the composite does" $ forAll plain $ \s -> \(n :: Int) -> let es = [Left n, Right s, Right (s ++ ".")] 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 "<?*" $ \(s :: String) -> + 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 From 1aa918790800a8d6eed00509b52825e0775e058f Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Fri, 13 Nov 2026 09:13:54 -0800 Subject: [PATCH 115/130] stepping: a machine over foci; balanced & countPrefixed stepping :: st -> (st -> a -> Either Bool st) -> Varifocal' [a] a decides by each focus built to continue (Right st), stop (Left True) or reject (Left False). terminatedBy & delimited are its instances, with new balanced, nested open/close pairs, & countPrefixed, a count then that many, as tested, cloned too. Co-Authored-By: Claude Opus 5.5 --- distributors-core/CHANGELOG.md | 7 ++- .../src/Control/Lens/Varifocal.hs | 62 +++++++++++++++---- .../test/Properties/Varifocal.hs | 26 ++++++++ 3 files changed, 82 insertions(+), 13 deletions(-) diff --git a/distributors-core/CHANGELOG.md b/distributors-core/CHANGELOG.md index a7a5e224..c72efbba 100644 --- a/distributors-core/CHANGELOG.md +++ b/distributors-core/CHANGELOG.md @@ -48,8 +48,11 @@ `Monadic` `Alternator`, like a `CtxGrammar`, by its free concrete form `Varifocus`, & `contextuallyT`, on a `MonadicTrans` profunctor; `AVarifocal`, `varifocus`, `runVarifocus`, `runVarifocusT` & - `cloneVarifocal`; & `terminatedBy` & `delimited`, sentinel-terminated & - matching-delimited sequences, which no `Bifocal` can express. + `cloneVarifocal`; & `stepping`, a deterministic machine over foci, + deciding by each built whether to continue, stop or reject, with its + instances `terminatedBy`, `delimited`, `balanced` & `countPrefixed`: + sentinel-terminated, matching-delimited, nested & count-prefixed + sequences, which no `Bifocal` can express. - `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: diff --git a/distributors-core/src/Control/Lens/Varifocal.hs b/distributors-core/src/Control/Lens/Varifocal.hs index 7839d153..19530b51 100644 --- a/distributors-core/src/Control/Lens/Varifocal.hs +++ b/distributors-core/src/Control/Lens/Varifocal.hs @@ -22,8 +22,11 @@ module Control.Lens.Varifocal , contextually , contextuallyT -- * Combinators + , stepping , terminatedBy , delimited + , balanced + , countPrefixed ) where import Control.Applicative (Alternative (..)) @@ -242,26 +245,63 @@ contextuallyT => 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 list matches when its last focus, & no earlier one, stops it. +-} +stepping :: st -> (st -> a -> Either Bool st) -> Varifocal' [a] a +stepping st0 step q = rmap pure (go st0) + where + focus = joinP q + go st = _Cons >? (focus P.>>= \b -> case step st b of + Right st' -> go st' + Left True -> asEmpty + Left False -> empty) + {- | Zero or more foci, then one which @end@s them, deciding by -each focus built, as no `Control.Lens.Bifocal.Bifocal` can, -like a sentinel-terminated sequence, a C string's. +each focus built, like a sentinel-terminated sequence, a C string's. A list which doesn't end by its first ending focus doesn't match. + +> prop> terminatedBy end = stepping () (\() b -> if end b then Left True else Right ()) -} terminatedBy :: (a -> Bool) -> Varifocal' [a] a -terminatedBy end q = rmap pure go - where - focus = joinP q - go = _Cons >? (focus P.>>= \b -> if end b then asEmpty else go) +terminatedBy end = stepping () (\() b -> if end b then Left True else Right ()) {- | 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, -which no `Control.Lens.Bifocal.Bifocal` can, since its language, +or a fenced code block's fence, whose language, of matching delimiters, isn't context-free. A list which doesn't close by its first match doesn't match. -After its first focus, @open@, it's @`terminatedBy` (same open)@. -} delimited :: (a -> a -> Bool) -> Varifocal' [a] a -delimited same q = rmap pure - (_Cons >? (joinP q P.>>= \open -> joinP (terminatedBy (same open) q))) +delimited same = stepping Nothing $ \st b -> case st of + Nothing -> Right (Just b) + Just open -> if same open b then Left True else Right st + +{- | Foci opened by one which @open@s, & closed by the one which @close@s, +at the same nesting depth, like nested comments, @/* /* */ */@, +or a balanced block, whose language, of nested pairs, isn't regular. +A focus may not both @open@ & @close@. +A list which doesn't open first, or close only last, doesn't match. +-} +balanced :: (a -> Bool) -> (a -> Bool) -> Varifocal' [a] a +balanced open close = stepping (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 list which doesn't have as many as its first focus counts doesn't match. +-} +countPrefixed :: (a -> Int) -> Varifocal' [a] a +countPrefixed count = stepping Nothing $ \st b -> case st of + Nothing -> if count b <= 0 then Left True else Right (Just (count b)) + Just n -> if n <= 1 then Left True else Right (Just (n - 1)) diff --git a/distributors-grammar/test/Properties/Varifocal.hs b/distributors-grammar/test/Properties/Varifocal.hs index 2f39df75..5d953699 100644 --- a/distributors-grammar/test/Properties/Varifocal.hs +++ b/distributors-grammar/test/Properties/Varifocal.hs @@ -1,6 +1,7 @@ module Properties.Varifocal (varifocalProperties) where import Control.Lens.Grammar +import Data.Char (digitToInt, isDigit) import Data.Foldable (for_) import Examples.Heredoc import Test.Hspec @@ -46,6 +47,31 @@ varifocalProperties = do prop "doesn't print an early end" $ forAll plain $ \s -> forAll plain $ \t -> printed ended (s ++ "." ++ t ++ ".") === Nothing + describe "balanced & countPrefixed, by stepping" $ do + let + nested :: Varifocal' String Char + nested = balanced (== '(') (== ')') + counted :: Varifocal' String Char + counted = countPrefixed (\c -> if isDigit c then digitToInt c else 0) + it "balanced parses a nested block, leaving the rest" $ + parsed nested "(a(b)c)rest" `shouldBe` Just ("(a(b)c)", "rest") + it "balanced prints only a balanced 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 "balanced 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 "countPrefixed 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 balanced, 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 "cloneVarifocal, by its free Varifocus" $ do prop "clones terminatedBy, printing & parsing as it does" $ forAll plain $ \s -> forAll plain $ \t -> From 6b6e801069469af1657394c8b28778eac26fb7a4 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Fri, 13 Nov 2026 09:15:12 -0800 Subject: [PATCH 116/130] bool in terminatedBy & delimited Co-Authored-By: Claude Opus 5.5 --- distributors-core/src/Control/Lens/Varifocal.hs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/distributors-core/src/Control/Lens/Varifocal.hs b/distributors-core/src/Control/Lens/Varifocal.hs index 19530b51..d03d9b3a 100644 --- a/distributors-core/src/Control/Lens/Varifocal.hs +++ b/distributors-core/src/Control/Lens/Varifocal.hs @@ -33,6 +33,7 @@ import Control.Applicative (Alternative (..)) import Control.Lens import Control.Lens.PartialIso ((>?)) import Control.Monad (MonadPlus (..), ap) +import Data.Bool (bool) import Data.Monoid.Disjunctive (DisjunctiveMonoid) import Data.Profunctor (Cochoice (..)) import Data.Profunctor.Distributor @@ -264,10 +265,10 @@ stepping st0 step q = rmap pure (go st0) each focus built, like a sentinel-terminated sequence, a C string's. A list which doesn't end by its first ending focus doesn't match. -> prop> terminatedBy end = stepping () (\() b -> if end b then Left True else Right ()) +> prop> terminatedBy end = stepping () (\() -> bool (Right ()) (Left True) . end) -} terminatedBy :: (a -> Bool) -> Varifocal' [a] a -terminatedBy end = stepping () (\() b -> if end b then Left True else Right ()) +terminatedBy end = stepping () (\() -> 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, @@ -279,7 +280,7 @@ A list which doesn't close by its first match doesn't match. delimited :: (a -> a -> Bool) -> Varifocal' [a] a delimited same = stepping Nothing $ \st b -> case st of Nothing -> Right (Just b) - Just open -> if same open b then Left True else Right st + 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, @/* /* */ */@, From 2ac5d151f934f0ccbc5e132681e78a08e85b020d Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Fri, 13 Nov 2026 09:26:14 -0800 Subject: [PATCH 117/130] crossVarifocal, altVarifocal & bindVarifocal Varifocals of the same foci, side by side on a pair, one or the other on a sum, or the second chosen by what the first built, as only Varifocals can, like a netstring, tested over random payloads. Co-Authored-By: Claude Opus 5.5 --- distributors-core/CHANGELOG.md | 3 +- .../src/Control/Lens/Varifocal.hs | 44 ++++++++++++++++--- .../test/Properties/Varifocal.hs | 31 +++++++++++++ 3 files changed, 72 insertions(+), 6 deletions(-) diff --git a/distributors-core/CHANGELOG.md b/distributors-core/CHANGELOG.md index c72efbba..fa12957b 100644 --- a/distributors-core/CHANGELOG.md +++ b/distributors-core/CHANGELOG.md @@ -48,7 +48,8 @@ `Monadic` `Alternator`, like a `CtxGrammar`, by its free concrete form `Varifocus`, & `contextuallyT`, on a `MonadicTrans` profunctor; `AVarifocal`, `varifocus`, `runVarifocus`, `runVarifocusT` & - `cloneVarifocal`; & `stepping`, a deterministic machine over foci, + `cloneVarifocal`; `crossVarifocal`, `altVarifocal` & `bindVarifocal`, + the last choosing a second by what the first built, like a netstring; & `stepping`, a deterministic machine over foci, deciding by each built whether to continue, stop or reject, with its instances `terminatedBy`, `delimited`, `balanced` & `countPrefixed`: sentinel-terminated, matching-delimited, nested & count-prefixed diff --git a/distributors-core/src/Control/Lens/Varifocal.hs b/distributors-core/src/Control/Lens/Varifocal.hs index d03d9b3a..5aafb453 100644 --- a/distributors-core/src/Control/Lens/Varifocal.hs +++ b/distributors-core/src/Control/Lens/Varifocal.hs @@ -18,6 +18,9 @@ module Control.Lens.Varifocal , runVarifocus , runVarifocusT , cloneVarifocal + , crossVarifocal + , altVarifocal + , bindVarifocal -- * Applicator , contextually , contextuallyT @@ -40,7 +43,7 @@ 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 (asEmpty, (>*<)) import Data.Profunctor.Monoidal.Cocartesian import Witherable (Filterable (..)) @@ -224,6 +227,35 @@ 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) + +{- | 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, @@ -256,10 +288,12 @@ stepping :: st -> (st -> a -> Either Bool st) -> Varifocal' [a] a stepping st0 step q = rmap pure (go st0) where focus = joinP q - go st = _Cons >? (focus P.>>= \b -> case step st b of - Right st' -> go st' - Left True -> asEmpty - Left False -> empty) + go st = _Cons >? P.do + b <- focus + case step st b of + Right st' -> go st' + Left True -> asEmpty + Left False -> empty {- | Zero or more foci, then one which @end@s them, deciding by each focus built, like a sentinel-terminated sequence, a C string's. diff --git a/distributors-grammar/test/Properties/Varifocal.hs b/distributors-grammar/test/Properties/Varifocal.hs index 5d953699..ab67974c 100644 --- a/distributors-grammar/test/Properties/Varifocal.hs +++ b/distributors-grammar/test/Properties/Varifocal.hs @@ -3,6 +3,8 @@ 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) @@ -72,6 +74,35 @@ varifocalProperties = do 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 (terminatedBy (== '.')) (delimited (==)) + alted :: Varifocal' (Either String String) Char + alted = altVarifocal (terminatedBy (== '.')) (balanced (== '(') (== ')')) + netstring :: Varifocal' (String, String) Char + netstring = bindVarifocal (terminatedBy (== ':')) + (\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 describe "cloneVarifocal, by its free Varifocus" $ do prop "clones terminatedBy, printing & parsing as it does" $ forAll plain $ \s -> forAll plain $ \t -> From d7ab9553a465732eb741dd6680302c3853cd3e17 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Fri, 13 Nov 2026 09:59:58 -0800 Subject: [PATCH 118/130] Optic units & cross/alt/or combinators; drop imprism - oneOptic, zeroOptic & falseOptic: the units of the crosses, alts & ors, each in its least optic, the rest by inclusion. - crossPrismoid/Bifocal/Diopter/Grate, altPrismoid/Bifocal/Diopter, orPrismoid/Bifocal/Varifocal. - crossComonocle ~> alongsideComonocle: it pairs differing foci, as lens's alongside, with unit id, unlike the crosses. - Remove imprism & the orphan Applicative (Market a b s): a Monocle without foci made an improper Prism breaking even preview l (review l b) = Just b. Co-Authored-By: Claude Opus 5.5 --- distributors-core/CHANGELOG.md | 15 ++++- distributors-core/src/Control/Lens/Bifocal.hs | 44 ++++++++++++++- .../src/Control/Lens/Comonocle.hs | 17 ++++-- distributors-core/src/Control/Lens/Diopter.hs | 30 ++++++++++ distributors-core/src/Control/Lens/Grate.hs | 14 +++++ .../Lens/Internal/Distributor/Orphanage.hs | 12 ---- distributors-core/src/Control/Lens/Monocle.hs | 17 +++--- .../src/Control/Lens/Prismoid.hs | 56 +++++++++++++++++++ .../src/Control/Lens/Varifocal.hs | 14 ++++- .../test/Properties/Varifocal.hs | 8 +++ 10 files changed, 199 insertions(+), 28 deletions(-) diff --git a/distributors-core/CHANGELOG.md b/distributors-core/CHANGELOG.md index fa12957b..428ba188 100644 --- a/distributors-core/CHANGELOG.md +++ b/distributors-core/CHANGELOG.md @@ -12,7 +12,7 @@ `Comonocular`s, with `runComonocular`. - `WrappedPafb f p` is `CocartesianMonoidal` for any `Functor f`. - `AComonocle`, `withComonocle`, `cloneComonocle`, `mapComonocle`, - `altComonocle`, `crossComonocle`, `indexComonocle` & + `altComonocle`, `alongsideComonocle`, `indexComonocle` & `zipWithComonocle`; & `crossMonocle`. - `Ditraversal`s, a secondary concrete representation of `Monocle`s, by `Traversable` & `Distributive` homogeneous products, @@ -48,12 +48,19 @@ `Monadic` `Alternator`, like a `CtxGrammar`, by its free concrete form `Varifocus`, & `contextuallyT`, on a `MonadicTrans` profunctor; `AVarifocal`, `varifocus`, `runVarifocus`, `runVarifocusT` & - `cloneVarifocal`; `crossVarifocal`, `altVarifocal` & `bindVarifocal`, + `cloneVarifocal`; `crossVarifocal`, `altVarifocal`, `orVarifocal` + & `bindVarifocal`, the last choosing a second by what the first built, like a netstring; & `stepping`, a deterministic machine over foci, deciding by each built whether to continue, stop or reject, with its instances `terminatedBy`, `delimited`, `balanced` & `countPrefixed`: sentinel-terminated, matching-delimited, 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: @@ -116,6 +123,10 @@ `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 diff --git a/distributors-core/src/Control/Lens/Bifocal.hs b/distributors-core/src/Control/Lens/Bifocal.hs index 49779ae3..a8717174 100644 --- a/distributors-core/src/Control/Lens/Bifocal.hs +++ b/distributors-core/src/Control/Lens/Bifocal.hs @@ -19,6 +19,9 @@ module Control.Lens.Bifocal , withBifocal , cloneBifocal , mapBifocal + , crossBifocal + , altBifocal + , orBifocal ) where import Control.Applicative @@ -29,6 +32,7 @@ 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 @@ -37,7 +41,7 @@ import GHC.Generics (Par1 (..), U1 (..), V1, (:*:) (..), (:+:) (..), (:.:) (..)) import Witherable -- $setup --- >>> import Control.Lens (_Just) +-- >>> import Control.Lens (_Just, _Left, _Right) -- >>> import Control.Lens.PartialIso (clonePartialIso) {- | `Bifocal`s are bidirectional parser optics. @@ -78,6 +82,44 @@ monomorphically typed `Bifocal` for different purposes. cloneBifocal :: ABifocal s t a b -> Bifocal s t a b cloneBifocal bif = unwrapPafb . mapBifocal bif . WrapPafb +{- | 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 diff --git a/distributors-core/src/Control/Lens/Comonocle.hs b/distributors-core/src/Control/Lens/Comonocle.hs index afefbe42..d19050e1 100644 --- a/distributors-core/src/Control/Lens/Comonocle.hs +++ b/distributors-core/src/Control/Lens/Comonocle.hs @@ -19,7 +19,8 @@ module Control.Lens.Comonocle , cloneComonocle , mapComonocle , altComonocle - , crossComonocle + , zeroOptic + , alongsideComonocle , indexComonocle , countComonocle , copiesComonocle @@ -105,6 +106,14 @@ mapComonocle 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. @@ -123,14 +132,14 @@ altComonocle x y p = rmap (either (fmap Left) (fmap Right)) since products of sums of copies distribute, \(m a \times n c = (m n) (a \times c)\). ->>> over (crossComonocle _Enumerable id) (\(a, c) -> (a + c, show c)) (Identity 1, 2) +>>> over (alongsideComonocle _Enumerable id) (\(a, c) -> (a + c, show c)) (Identity 1, 2) (Identity 3,"2") -} -crossComonocle +alongsideComonocle :: AComonocle s t a b -> AComonocle u v c d -> Comonocle (s,u) (t,v) (a,c) (b,d) -crossComonocle x y = +alongsideComonocle x y = withComonocle x $ \e f -> withComonocle y $ \g h -> comonocle $ Comonocular diff --git a/distributors-core/src/Control/Lens/Diopter.hs b/distributors-core/src/Control/Lens/Diopter.hs index d0cc2ae3..121ed9f4 100644 --- a/distributors-core/src/Control/Lens/Diopter.hs +++ b/distributors-core/src/Control/Lens/Diopter.hs @@ -17,6 +17,8 @@ module Control.Lens.Diopter , diopter , withDiopter , cloneDiopter + , crossDiopter + , altDiopter , mapDiopter , optioned , several @@ -32,12 +34,14 @@ 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 ((*<)) @@ -91,6 +95,32 @@ 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 diff --git a/distributors-core/src/Control/Lens/Grate.hs b/distributors-core/src/Control/Lens/Grate.hs index 7c52e93c..3f3c31c1 100644 --- a/distributors-core/src/Control/Lens/Grate.hs +++ b/distributors-core/src/Control/Lens/Grate.hs @@ -21,6 +21,7 @@ module Control.Lens.Grate , grate , withGrate , cloneGrate + , crossGrate , mapGrate , cotraversed , represented @@ -82,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)) diff --git a/distributors-core/src/Control/Lens/Internal/Distributor/Orphanage.hs b/distributors-core/src/Control/Lens/Internal/Distributor/Orphanage.hs index 9d5ac240..bb0ebc0d 100644 --- a/distributors-core/src/Control/Lens/Internal/Distributor/Orphanage.hs +++ b/distributors-core/src/Control/Lens/Internal/Distributor/Orphanage.hs @@ -18,7 +18,6 @@ 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 @@ -127,14 +126,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 index 0b5ac893..4c20b5de 100644 --- a/distributors-core/src/Control/Lens/Monocle.hs +++ b/distributors-core/src/Control/Lens/Monocle.hs @@ -22,8 +22,8 @@ module Control.Lens.Monocle , withMonocle , cloneMonocle , mapMonocle - , imprism , crossMonocle + , oneOptic , ditraversed , forevered , zipMonocle @@ -83,15 +83,16 @@ 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`. +{- | 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. ->>> review (imprism ditraversed) 1 :: Complex Int -1 :+ 1 ->>> preview (imprism ditraversed) (1 :+ 2 :: Complex Int) -Just 1 +>>> toListOf oneOptic () :: [Int] +[] -} -imprism :: Monocle s t a b -> Prism s t a b -imprism mon = clonePrism mon +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}\), diff --git a/distributors-core/src/Control/Lens/Prismoid.hs b/distributors-core/src/Control/Lens/Prismoid.hs index 3b18f4ed..bc7c243c 100644 --- a/distributors-core/src/Control/Lens/Prismoid.hs +++ b/distributors-core/src/Control/Lens/Prismoid.hs @@ -22,6 +22,10 @@ module Control.Lens.Prismoid , prismoid , withPrismoid , clonePrismoid + , crossPrismoid + , altPrismoid + , orPrismoid + , falseOptic , opted , lefted , righted @@ -132,6 +136,58 @@ 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")) diff --git a/distributors-core/src/Control/Lens/Varifocal.hs b/distributors-core/src/Control/Lens/Varifocal.hs index 5aafb453..a1381611 100644 --- a/distributors-core/src/Control/Lens/Varifocal.hs +++ b/distributors-core/src/Control/Lens/Varifocal.hs @@ -20,6 +20,7 @@ module Control.Lens.Varifocal , cloneVarifocal , crossVarifocal , altVarifocal + , orVarifocal , bindVarifocal -- * Applicator , contextually @@ -37,7 +38,7 @@ import Control.Lens import Control.Lens.PartialIso ((>?)) import Control.Monad (MonadPlus (..), ap) import Data.Bool (bool) -import Data.Monoid.Disjunctive (DisjunctiveMonoid) +import Data.Monoid.Disjunctive (DisjunctiveMonoid (..)) import Data.Profunctor (Cochoice (..)) import Data.Profunctor.Distributor import Data.Profunctor.Filtrator (Filtrator (..), mfiltrate) @@ -243,6 +244,17 @@ altVarifocal 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. diff --git a/distributors-grammar/test/Properties/Varifocal.hs b/distributors-grammar/test/Properties/Varifocal.hs index ab67974c..c949c9b6 100644 --- a/distributors-grammar/test/Properties/Varifocal.hs +++ b/distributors-grammar/test/Properties/Varifocal.hs @@ -103,6 +103,14 @@ varifocalProperties = do === 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 (terminatedBy (== '.')) (balanced (== '(') (== ')')) + emptied = orVarifocal falseOptic (terminatedBy (== '.')) + 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 terminatedBy, printing & parsing as it does" $ forAll plain $ \s -> forAll plain $ \t -> From 62407cd922a11a589a1e85063550019358b2b06b Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Fri, 13 Nov 2026 10:47:52 -0800 Subject: [PATCH 119/130] Collapse lambdas in a Varifocal property, for HLint Co-Authored-By: Claude Opus 5.5 --- distributors-grammar/test/Properties/Varifocal.hs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/distributors-grammar/test/Properties/Varifocal.hs b/distributors-grammar/test/Properties/Varifocal.hs index c949c9b6..e95d8dc7 100644 --- a/distributors-grammar/test/Properties/Varifocal.hs +++ b/distributors-grammar/test/Properties/Varifocal.hs @@ -153,7 +153,7 @@ varifocalProperties = do 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) -> + 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 ++ ".") From e9bf19e71724a65f55e32fc5b2c3422ae095ae4c Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Fri, 13 Nov 2026 13:06:05 -0800 Subject: [PATCH 120/130] Faster counted Prismoids & withOperators printing; tie manyP's knot - inRange (exactly, atLeast, atMost) sequences its foci at the target itself, then its Applicative once, rather than at WrappedPafb per focus: 25-34% faster printing & Parsector parsing of counted repetitions, 15-21% for sepBy exactly. - withOperators decomposes left-associated chains by accumulating their steps, linearly rather than quadratically: expression printing 10-13% faster. - Distributor's default manyP ties its knot, building its action once. Measured by distributors-grammar's bench:core (uncommitted). Co-Authored-By: Claude Opus 5.5 --- distributors-core/src/Control/Lens/Prismoid.hs | 14 +++++++------- .../src/Data/Profunctor/Distributor.hs | 2 +- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/distributors-core/src/Control/Lens/Prismoid.hs b/distributors-core/src/Control/Lens/Prismoid.hs index bc7c243c..f3715ed7 100644 --- a/distributors-core/src/Control/Lens/Prismoid.hs +++ b/distributors-core/src/Control/Lens/Prismoid.hs @@ -255,7 +255,7 @@ It never matches where @lo > hi@. ["12","123"] -} inRange :: Int -> Maybe Int -> Prismoid [a] [b] a b -inRange lo hi = unwrapPafb . go lo hi . WrapPafb +inRange lo hi = rmap sequenceA . go lo hi where go :: Alternator p => Int -> Maybe Int -> p a b -> p [a] [b] go l h p @@ -636,15 +636,15 @@ withOperators table p = foldl makeLevel p table -- 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 + fwd x = decompose x [] where - decompose y = case tryTags y of - Nothing -> (y, []) + -- 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 in (l, (i,r0) : rest) - _ -> - let (l0, prior) = decompose l in (l0, prior ++ [(i,r)]) + 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 ] diff --git a/distributors-core/src/Data/Profunctor/Distributor.hs b/distributors-core/src/Data/Profunctor/Distributor.hs index 11e9c4b8..341fb694 100644 --- a/distributors-core/src/Data/Profunctor/Distributor.hs +++ b/distributors-core/src/Data/Profunctor/Distributor.hs @@ -67,7 +67,7 @@ class (Monoidal p, CocartesianMonoidal p) => Distributor p where {- | Zero or more. -} manyP :: p a b -> p [a] [b] - manyP p = eotList . swapped >~ p >*< manyP p >+< oneP + manyP p = let ps = eotList . swapped >~ p >*< ps >+< oneP in ps instance Distributor (->) instance Monoid s => Distributor (Forget s) From 856df3e31311c6c801228e2555289e447619def3 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Fri, 13 Nov 2026 13:24:43 -0800 Subject: [PATCH 121/130] alongside & without PartialIsos; core benchmarks; changelog - crossPartialIso ~> alongsidePartialIso & altPartialIso ~> withoutPartialIso, after lens's alongside & without, since they pair & sum differing foci; emptyPartialIso ~> falsePartialIso, as falseOptic. - distributors-grammar's bench:core benchmarks distributors' combinators & the test examples, scaled, at parsing, printing & Parsector. - Changelog: orPartialIso, the renames & the performance changes. - Eitan's edits to Varifocal, Monadic, Homogeneous, Grammar & tests. Co-Authored-By: Claude Opus 5.5 --- distributors-core/CHANGELOG.md | 22 ++- .../src/Control/Lens/PartialIso.hs | 46 ++--- .../src/Control/Lens/Varifocal.hs | 31 ++- .../src/Data/Profunctor/Monadic.hs | 10 +- .../src/Data/Traversable/Homogeneous.hs | 2 +- .../Traversable/Homogeneous/Enumerable.hs | 2 +- .../test/Properties/PartialIso.hs | 14 +- distributors-grammar/bench/Main.hs | 186 ++++++++++++++++++ .../distributors-grammar.cabal | 70 +++++++ distributors-grammar/package.yaml | 22 +++ .../src/Control/Lens/Grammar.hs | 6 +- distributors-grammar/test/Examples/Heredoc.hs | 8 +- .../test/Properties/Varifocal.hs | 34 ++-- 13 files changed, 372 insertions(+), 81 deletions(-) create mode 100644 distributors-grammar/bench/Main.hs diff --git a/distributors-core/CHANGELOG.md b/distributors-core/CHANGELOG.md index 428ba188..611c997f 100644 --- a/distributors-core/CHANGELOG.md +++ b/distributors-core/CHANGELOG.md @@ -27,7 +27,7 @@ - `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 balanced tree. + 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 @@ -52,8 +52,8 @@ & `bindVarifocal`, the last choosing a second by what the first built, like a netstring; & `stepping`, a deterministic machine over foci, deciding by each built whether to continue, stop or reject, with its - instances `terminatedBy`, `delimited`, `balanced` & `countPrefixed`: - sentinel-terminated, matching-delimited, nested & count-prefixed + 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`, @@ -91,6 +91,17 @@ - `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. +- `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 @@ -99,7 +110,10 @@ ### Breaking Changes -- `altPartialIso` & `crossPartialIso` keep a `Prism`'s passing a mismatch +- `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 `>?`. diff --git a/distributors-core/src/Control/Lens/PartialIso.hs b/distributors-core/src/Control/Lens/PartialIso.hs index b98ae1a8..1e129ec2 100644 --- a/distributors-core/src/Control/Lens/PartialIso.hs +++ b/distributors-core/src/Control/Lens/PartialIso.hs @@ -23,10 +23,10 @@ module Control.Lens.PartialIso , withPartialIso , clonePartialIso , coPartialIso - , crossPartialIso - , altPartialIso + , alongsidePartialIso + , withoutPartialIso , orPartialIso - , emptyPartialIso + , falsePartialIso -- * Applicators , dimapMaybe , (>?) @@ -414,22 +414,23 @@ 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 (crossPartialIso _Just _Just) (\(x, y) -> Just (x + y, x * y)) (Just 2, Just 3 :: Maybe Int) +>>> traverseOf (alongsidePartialIso _Just _Just) (\(x, y) -> Just (x + y, x * y)) (Just 2, Just 3 :: Maybe Int) Just (Just 5,Just 6) ->>> traverseOf (crossPartialIso _Just _Just) (Just . id) (Nothing, Nothing :: Maybe Int) +>>> traverseOf (alongsidePartialIso _Just _Just) (Just . id) (Nothing, Nothing :: Maybe Int) Just (Nothing,Nothing) ->>> traverseOf (crossPartialIso _Just _Just) (Just . id) (Just 2, Nothing :: Maybe Int) +>>> traverseOf (alongsidePartialIso _Just _Just) (Just . id) (Just 2, Nothing :: Maybe Int) Nothing -} -crossPartialIso +alongsidePartialIso :: APartialIso s t a b -> APartialIso u v c d -> PartialIso (s,u) (t,v) (a,c) (b,d) -crossPartialIso x y = +alongsidePartialIso x y = withPartialMarket x $ \build0 match0 -> withPartialMarket y $ \build1 match1 -> partialMarket @@ -440,20 +441,21 @@ crossPartialIso x y = _ -> 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 (altPartialIso _Just _Just) (Just . either (Left . succ) (Right . pred)) (Left (Just 1) :: Either (Maybe Int) (Maybe Int)) +>>> traverseOf (withoutPartialIso _Just _Just) (Just . either (Left . succ) (Right . pred)) (Left (Just 1) :: Either (Maybe Int) (Maybe Int)) Just (Left (Just 2)) ->>> traverseOf (altPartialIso _Just _Just) (Just . either (Left . succ) (Right . pred)) (Left Nothing :: Either (Maybe Int) (Maybe Int)) +>>> traverseOf (withoutPartialIso _Just _Just) (Just . either (Left . succ) (Right . pred)) (Left Nothing :: Either (Maybe Int) (Maybe Int)) Just (Left Nothing) -} -altPartialIso +withoutPartialIso :: 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 = +withoutPartialIso x y = withPartialMarket x $ \build0 match0 -> withPartialMarket y $ \build1 match1 -> partialMarket @@ -490,15 +492,15 @@ orPartialIso x y = {- | The pattern which never matches & never builds, failing in both directions, the identity of `orPartialIso`. -> prop> orPartialIso emptyPartialIso pattern = clonePartialIso pattern -> prop> orPartialIso pattern emptyPartialIso = clonePartialIso pattern -> prop> satisfied (const False) = emptyPartialIso +> prop> orPartialIso falsePartialIso pattern = clonePartialIso pattern +> prop> orPartialIso pattern falsePartialIso = clonePartialIso pattern +> prop> satisfied (const False) = falsePartialIso ->>> preview emptyPartialIso 'x' :: Maybe Char +>>> preview falsePartialIso 'x' :: Maybe Char Nothing -} -emptyPartialIso :: PartialIso s t a b -emptyPartialIso = partialMarket (const Nothing) (const (Left Nothing)) +falsePartialIso :: PartialIso s t a b +falsePartialIso = partialMarket (const Nothing) (const (Left Nothing)) {- | Action of `APrism` on `Choice` `Profunctor`s. -} (>?) @@ -681,9 +683,9 @@ difoldl1 pattern = (\(c,(a,s)) -> ((c,a),s)) (\((d,b),t) -> (d,(b,t))) step - = crossPartialIso id _Cons + = alongsidePartialIso id _Cons . associate - . crossPartialIso (coPartialIso pattern) id + . alongsidePartialIso (coPartialIso pattern) id in from (iterating step) {- | Right fold & unfold `APartialIso` to an `Control.Lens.Iso.Iso`. -} @@ -697,9 +699,9 @@ difoldr1 pattern = (\((s,a),c) -> (s,(a,c))) (\(t,(b,d)) -> ((t,b),d)) step - = crossPartialIso _Snoc id + = alongsidePartialIso _Snoc id . reorder - . crossPartialIso id (coPartialIso pattern) + . alongsidePartialIso id (coPartialIso pattern) in from (iterating step) {- | Left fold & unfold `APartialIso` to a `Control.Lens.Prism.Prism`. -} diff --git a/distributors-core/src/Control/Lens/Varifocal.hs b/distributors-core/src/Control/Lens/Varifocal.hs index a1381611..1741ac5a 100644 --- a/distributors-core/src/Control/Lens/Varifocal.hs +++ b/distributors-core/src/Control/Lens/Varifocal.hs @@ -27,10 +27,10 @@ module Control.Lens.Varifocal , contextuallyT -- * Combinators , stepping - , terminatedBy - , delimited - , balanced - , countPrefixed + , terminateBy + , delimitBy + , balanceBy + , countWith ) where import Control.Applicative (Alternative (..)) @@ -299,9 +299,8 @@ A list matches when its last focus, & no earlier one, stops it. stepping :: st -> (st -> a -> Either Bool st) -> Varifocal' [a] a stepping st0 step q = rmap pure (go st0) where - focus = joinP q go st = _Cons >? P.do - b <- focus + b <- joinP q case step st b of Right st' -> go st' Left True -> asEmpty @@ -311,10 +310,10 @@ stepping st0 step q = rmap pure (go st0) each focus built, like a sentinel-terminated sequence, a C string's. A list which doesn't end by its first ending focus doesn't match. -> prop> terminatedBy end = stepping () (\() -> bool (Right ()) (Left True) . end) +> prop> terminateBy end = stepping () (\() -> bool (Right ()) (Left True) . end) -} -terminatedBy :: (a -> Bool) -> Varifocal' [a] a -terminatedBy end = stepping () (\() -> bool (Right ()) (Left True) . end) +terminateBy :: (a -> Bool) -> Varifocal' [a] a +terminateBy end = stepping () (\() -> 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, @@ -323,19 +322,19 @@ or a fenced code block's fence, whose language, of matching delimiters, isn't context-free. A list which doesn't close by its first match doesn't match. -} -delimited :: (a -> a -> Bool) -> Varifocal' [a] a -delimited same = stepping Nothing $ \st b -> case st of +delimitBy :: (a -> a -> Bool) -> Varifocal' [a] a +delimitBy same = stepping 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 balanced block, whose language, of nested pairs, isn't regular. +or a balanceBy block, whose language, of nested pairs, isn't regular. A focus may not both @open@ & @close@. A list which doesn't open first, or close only last, doesn't match. -} -balanced :: (a -> Bool) -> (a -> Bool) -> Varifocal' [a] a -balanced open close = stepping (0 :: Int) step +balanceBy :: (a -> Bool) -> (a -> Bool) -> Varifocal' [a] a +balanceBy open close = stepping (0 :: Int) step where step depth b | open b = Right (depth + 1) @@ -348,7 +347,7 @@ balanced open close = stepping (0 :: Int) step like a length-prefixed record of bytes in a binary format. A list which doesn't have as many as its first focus counts doesn't match. -} -countPrefixed :: (a -> Int) -> Varifocal' [a] a -countPrefixed count = stepping Nothing $ \st b -> case st of +countWith :: (a -> Int) -> Varifocal' [a] a +countWith count = stepping Nothing $ \st b -> case st of Nothing -> if count b <= 0 then Left True else Right (Just (count b)) Just n -> if n <= 1 then Left True else Right (Just (n - 1)) diff --git a/distributors-core/src/Data/Profunctor/Monadic.hs b/distributors-core/src/Data/Profunctor/Monadic.hs index 716500ae..676c15cf 100644 --- a/distributors-core/src/Data/Profunctor/Monadic.hs +++ b/distributors-core/src/Data/Profunctor/Monadic.hs @@ -34,13 +34,11 @@ may run effects of @m@ forwards, by `liftP`, & absorb them backwards, by `joinP`. `liftP` is a monad morphism. - -> prop> liftP . pure = pure -> prop> liftP (m >>= k) = liftP m >>= liftP . k -> prop> joinP (fmap pure p) = p -> prop> joinP = join . fmap liftP -} -class (forall m x. Monad m => Monad (p m x)) => MonadicTrans p where +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 diff --git a/distributors-core/src/Data/Traversable/Homogeneous.hs b/distributors-core/src/Data/Traversable/Homogeneous.hs index ec0c435c..e16567eb 100644 --- a/distributors-core/src/Data/Traversable/Homogeneous.hs +++ b/distributors-core/src/Data/Traversable/Homogeneous.hs @@ -198,7 +198,7 @@ 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 balanced tree, built lazily. +summed in a balanceBy tree, built lazily. >>> zipWithHomogeneous (+) (True, 1) (True, 2 :: Int) Just (True,3) diff --git a/distributors-core/src/Data/Traversable/Homogeneous/Enumerable.hs b/distributors-core/src/Data/Traversable/Homogeneous/Enumerable.hs index 3b4e603b..4f4ac981 100644 --- a/distributors-core/src/Data/Traversable/Homogeneous/Enumerable.hs +++ b/distributors-core/src/Data/Traversable/Homogeneous/Enumerable.hs @@ -126,7 +126,7 @@ 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 balanced tree, built lazily. +& summed in a balanceBy tree, built lazily. >>> map (review fromEnumerable) [(False, 'a'), (True, 'b')] [(0,'a'),(1,'b')] diff --git a/distributors-core/test/Properties/PartialIso.hs b/distributors-core/test/Properties/PartialIso.hs index 39daa911..3860f1e4 100644 --- a/distributors-core/test/Properties/PartialIso.hs +++ b/distributors-core/test/Properties/PartialIso.hs @@ -69,13 +69,13 @@ partialIsoProperties = do 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 "altPartialIso of Prisms is their sum" $ + prop "withoutPartialIso of Prisms is their sum" $ \(Fun _ f :: Fun Int (Maybe Int)) (e :: Either (Maybe Int) (Maybe Int)) -> within second $ - traverseOf (altPartialIso _Just _Just) (either (fmap Left . f) (fmap Right . f)) e + 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 "crossPartialIso of Prisms passes through where both do" $ + 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 (crossPartialIso _Just _Just) f (m, n) + 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) @@ -83,10 +83,10 @@ partialIsoProperties = do prop "orPartialIso is the union of patterns" $ \(n :: Int) -> within second $ traverseOf (orPartialIso (satisfied even) (satisfied odd)) Just n === Just n - prop "emptyPartialIso is orPartialIso's identity" $ + prop "falsePartialIso is orPartialIso's identity" $ \(Fun _ f :: Fun Int (Maybe Int)) (m :: Maybe Int) -> within second $ - traverseOf (orPartialIso emptyPartialIso _Just) f m === traverseOf _Just f m - .&&. traverseOf (orPartialIso _Just emptyPartialIso) f m === traverseOf _Just f m + 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 diff --git a/distributors-grammar/bench/Main.hs b/distributors-grammar/bench/Main.hs new file mode 100644 index 00000000..eaab09a0 --- /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 (terminal "." >* asEmpty)) (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 index 1ad8f719..cae63344 100644 --- a/distributors-grammar/distributors-grammar.cabal +++ b/distributors-grammar/distributors-grammar.cabal @@ -239,3 +239,73 @@ test-suite test , 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/package.yaml b/distributors-grammar/package.yaml index c1c40393..c29da918 100644 --- a/distributors-grammar/package.yaml +++ b/distributors-grammar/package.yaml @@ -102,3 +102,25 @@ tests: - 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/distributors-grammar/src/Control/Lens/Grammar.hs b/distributors-grammar/src/Control/Lens/Grammar.hs index 074e755c..bf5d9787 100644 --- a/distributors-grammar/src/Control/Lens/Grammar.hs +++ b/distributors-grammar/src/Control/Lens/Grammar.hs @@ -442,13 +442,13 @@ 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, `delimited` by the first line +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 (delimited (==)) lineG +heredocG = lined >~ terminal "<<" >* contextually (delimitBy (==)) lineG where lineG = manyP (notOneOf "\n") *< terminal "\n" lined = iso @@ -674,7 +674,7 @@ makeNestedPrisms ''RegBnf {- | `regexGrammar` is a context-free `Grammar` for t'RegString's. It can't be a `RegGrammar`, since t'RegString's include parenthesization. -But [balanced parentheses](https://en.wikipedia.org/wiki/Dyck_language) +But [balanceBy parentheses](https://en.wikipedia.org/wiki/Dyck_language) are a context-free language. >>> putStringLn (regbnfG regexGrammar) diff --git a/distributors-grammar/test/Examples/Heredoc.hs b/distributors-grammar/test/Examples/Heredoc.hs index a8bf96d7..0fb9de08 100644 --- a/distributors-grammar/test/Examples/Heredoc.hs +++ b/distributors-grammar/test/Examples/Heredoc.hs @@ -22,23 +22,23 @@ heredocLines = iso tag : rest -> Heredoc tag (if null rest then [] else init rest) [] -> Heredoc "" []) --- | Heredocs, by their lines, `delimited` by their tag, +-- | 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 (delimited (==)) lineP +heredocP = heredocLines >~ symbol "<<" >* contextuallyT (delimitBy (==)) lineP where symbol :: String -> p m () () symbol = terminal lineP = manyP (notOneOf "\n") *< symbol "\n" --- | Heredocs as a `CtxGrammar`, applying `delimited` `contextually`, +-- | 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 (delimited (==)) lineG +heredocG = heredocLines >~ terminal "<<" >* contextually (delimitBy (==)) lineG where lineG = manyP (notOneOf "\n") *< terminal "\n" diff --git a/distributors-grammar/test/Properties/Varifocal.hs b/distributors-grammar/test/Properties/Varifocal.hs index e95d8dc7..cda4d9c2 100644 --- a/distributors-grammar/test/Properties/Varifocal.hs +++ b/distributors-grammar/test/Properties/Varifocal.hs @@ -19,7 +19,7 @@ varifocalProperties = do parsed :: Varifocal' String Char -> String -> Maybe (String, String) parsed v = parseP (contextuallyT v (anyToken :: Parsor String Maybe Char Char)) ended :: Varifocal' String Char - ended = terminatedBy (== '.') + ended = terminateBy (== '.') plain = Prelude.filter (/= '.') <$> arbitrary describe "MonadicTrans laws, at Printor & Parsor" $ do let @@ -39,7 +39,7 @@ varifocalProperties = do 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 "terminatedBy" $ do + describe "terminateBy" $ do prop "prints & parses up to its first end" $ forAll plain $ \s -> forAll plain $ \rest -> printed ended (s ++ ".") === Just (s ++ ".") @@ -49,26 +49,26 @@ varifocalProperties = do prop "doesn't print an early end" $ forAll plain $ \s -> forAll plain $ \t -> printed ended (s ++ "." ++ t ++ ".") === Nothing - describe "balanced & countPrefixed, by stepping" $ do + describe "balanceBy & countWith, by stepping" $ do let nested :: Varifocal' String Char - nested = balanced (== '(') (== ')') + nested = balanceBy (== '(') (== ')') counted :: Varifocal' String Char - counted = countPrefixed (\c -> if isDigit c then digitToInt c else 0) - it "balanced parses a nested block, leaving the rest" $ + 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 "balanced prints only a balanced block" $ do + 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 "balanced round-trips nesting of any depth" $ + 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 "countPrefixed reads as many as its first focus counts" $ do + 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 balanced, as it does" $ do + it "clones balanceBy, as it does" $ do let cloned :: Varifocal' String Char cloned = cloneVarifocal nested strs = ["(a(b)c)", "(a(b)", "a", "((x))"] @@ -82,11 +82,11 @@ varifocalProperties = do 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 (terminatedBy (== '.')) (delimited (==)) + crossed = crossVarifocal (terminateBy (== '.')) (delimitBy (==)) alted :: Varifocal' (Either String String) Char - alted = altVarifocal (terminatedBy (== '.')) (balanced (== '(') (== ')')) + alted = altVarifocal (terminateBy (== '.')) (balanceBy (== '(') (== ')')) netstring :: Varifocal' (String, String) Char - netstring = bindVarifocal (terminatedBy (== ':')) + netstring = bindVarifocal (terminateBy (== ':')) (\header -> exactly (fromMaybe 0 (readMaybe (init header)))) it "crosses side by side" $ do printedG crossed ("ab.", "xyx") `shouldBe` Just "ab.xyx" @@ -105,14 +105,14 @@ varifocalProperties = do 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 (terminatedBy (== '.')) (balanced (== '(') (== ')')) - emptied = orVarifocal falseOptic (terminatedBy (== '.')) + 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 terminatedBy, printing & parsing as it does" $ + prop "clones terminateBy, printing & parsing as it does" $ forAll plain $ \s -> forAll plain $ \t -> let cloned :: Varifocal' String Char cloned = cloneVarifocal ended @@ -125,7 +125,7 @@ varifocalProperties = do range = inRange lo (Just hi) in printed (cloneVarifocal range) s === printed range s .&&. parsed (cloneVarifocal range) s === parsed range s - describe "heredocs, by delimited" $ do + describe "heredocs, by delimitBy" $ do let printedH h = ($ "") <$> printP (heredocP :: Printor String Maybe Heredoc Heredoc) h From d259dd10ec8726065461e9efad98fb8f93e80a70 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Fri, 13 Nov 2026 13:53:37 -0800 Subject: [PATCH 122/130] Test token classes by Set; document snoc's cost in printing - tokenClass's default tests a class's sets of tokens by Set.member & Set.notMember, & predicates' oneOf & notOneOf collect their tokens into a Set once, rather than testing by Foldable's elem, linearly: the JSON example parses ~665x faster (4.36 s -> 6.5 ms on 4.6 KB), its characters being a class of over a million tokens. - unparseG & unparsecG document that they snoc, so print to a Seq, not a String, which prints quadratically (16000 tokens: 4 s vs 6 ms). - bench:core's manyTillP workload checks emptiness before printing its terminator, as an LL(1) printer requires; manyTillP round-trips. Co-Authored-By: Claude Opus 5.5 --- distributors-grammar/CHANGELOG.md | 8 ++++++++ distributors-grammar/bench/Main.hs | 2 +- distributors-grammar/src/Control/Lens/Grammar.hs | 6 ++++++ .../src/Control/Lens/Grammar/Token.hs | 14 +++++++++----- 4 files changed, 24 insertions(+), 6 deletions(-) diff --git a/distributors-grammar/CHANGELOG.md b/distributors-grammar/CHANGELOG.md index 344bb815..efd70a84 100644 --- a/distributors-grammar/CHANGELOG.md +++ b/distributors-grammar/CHANGELOG.md @@ -2,6 +2,14 @@ ## 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. +- `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` diff --git a/distributors-grammar/bench/Main.hs b/distributors-grammar/bench/Main.hs index eaab09a0..dd3cc2f2 100644 --- a/distributors-grammar/bench/Main.hs +++ b/distributors-grammar/bench/Main.hs @@ -107,7 +107,7 @@ repeats = , 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 (terminal "." >* asEmpty)) (digits <> ".") digits + , Workload "manyTillP" (manyTillP digitG (asEmpty *< terminal ".")) (digits <> ".") digits , Workload "skipManyP" (skipManyP (terminal " ")) (replicate size ' ') () ] diff --git a/distributors-grammar/src/Control/Lens/Grammar.hs b/distributors-grammar/src/Control/Lens/Grammar.hs index bf5d9787..c6de5c84 100644 --- a/distributors-grammar/src/Control/Lens/Grammar.hs +++ b/distributors-grammar/src/Control/Lens/Grammar.hs @@ -1009,6 +1009,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) @@ -1046,6 +1049,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) diff --git a/distributors-grammar/src/Control/Lens/Grammar/Token.hs b/distributors-grammar/src/Control/Lens/Grammar/Token.hs index 22c0a786..95905283 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/Token.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/Token.hs @@ -137,8 +137,10 @@ tokens = foldr ((>:<) . token) asEmpty instance Categorized token => Tokenized token (token -> Bool) where anyToken _ = True token = (==) - oneOf = flip elem - notOneOf = flip notElem + -- 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) @@ -283,12 +285,14 @@ class Tokenized token p => TokenAlgebra token p where 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 -> oneOf chars + OneOf chars -> satisfy (`Set.member` chars) NotOneOf chars (AndAsIn cat) -> - satisfy (notOneOf chars >&< asIn cat) + satisfy ((`Set.notMember` chars) >&< asIn cat) NotOneOf chars (AndNotAsIn cats) -> - satisfy (notOneOf chars >&< allP notAsIn cats) + satisfy ((`Set.notMember` chars) >&< allP notAsIn cats) Alternate p q ps -> foldr1 (>|<) (p : q : ps) deriving stock instance Generic (TokenExam token alg) From d86d1541b5fb66d9222bd136a7ae3eef5bd5604f Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Fri, 13 Nov 2026 14:03:52 -0800 Subject: [PATCH 123/130] Parsor: direct repetition Parsor's manyP & optionalP parse & print their elements in turn, rather than by Distributor's defaults, through isomorphisms & sums, as Printor's do, parsing more before fewer, as the defaults do. bench:core: manyP & someP parse 0.58x, sepBy 0.77x, heredoc 0.48x, sexpr 0.67x, expr 0.72x; printing & Parsector unchanged. Co-Authored-By: Claude Opus 5.5 --- distributors-grammar/CHANGELOG.md | 3 +++ .../src/Data/Profunctor/Grammar.hs | 24 ++++++++++++++++++- 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/distributors-grammar/CHANGELOG.md b/distributors-grammar/CHANGELOG.md index efd70a84..996351b0 100644 --- a/distributors-grammar/CHANGELOG.md +++ b/distributors-grammar/CHANGELOG.md @@ -6,6 +6,9 @@ `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. +- `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 diff --git a/distributors-grammar/src/Data/Profunctor/Grammar.hs b/distributors-grammar/src/Data/Profunctor/Grammar.hs index 5e5066d7..507a6cec 100644 --- a/distributors-grammar/src/Data/Profunctor/Grammar.hs +++ b/distributors-grammar/src/Data/Profunctor/Grammar.hs @@ -111,7 +111,29 @@ instance Filterable f => Filtrator (Parsor s f) where (p (fmap Right ma) s) ) instance (Alternative m, Monad m) => CocartesianMonoidal (Parsor s m) -instance (Alternative m, Monad m) => Distributor (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 From 0ce26e1ff40bd67afeadf1fd7171a4b8db847035 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Fri, 13 Nov 2026 16:26:13 -0800 Subject: [PATCH 124/130] Control.Lens.Prism.Nested: genericNestedPrism & genericNestedIso Control.Lens.Internal.Distributor.NestedPrismTH is renamed Control.Lens.Prism.Nested, & gains the Generic versions of what makeNestedPrisms generates, focusing fields as right-nested pairs: genericNestedPrism :: forall s -> forall (con :: Symbol) -> ... => Prism' s (ConFocus con (Rep s)) genericNestedIso :: forall s -> ... => Iso' s (IsoFocus (Rep s)) by required type arguments, e.g. genericNestedPrism Shape "Rect" & genericNestedIso (type Point), with type errors for a missing constructor & for an Iso of a sum. No new dependency: a closed family finds the constructor by name & a class right-nests its product, which generic-lens-core's tupled _GCtor couldn't. Tested against makeNestedPrisms's prisms & iso; re-exported by Control.Lens.PartialIso. Co-Authored-By: Claude Opus 5.5 --- distributors-core/CHANGELOG.md | 9 + distributors-core/distributors.cabal | 3 +- .../src/Control/Lens/PartialIso.hs | 6 +- .../NestedPrismTH.hs => Prism/Nested.hs} | 174 +++++++++++++++++- distributors-core/test/Main.hs | 2 + distributors-core/test/Properties/Nested.hs | 57 ++++++ 6 files changed, 245 insertions(+), 6 deletions(-) rename distributors-core/src/Control/Lens/{Internal/Distributor/NestedPrismTH.hs => Prism/Nested.hs} (63%) create mode 100644 distributors-core/test/Properties/Nested.hs diff --git a/distributors-core/CHANGELOG.md b/distributors-core/CHANGELOG.md index 611c997f..de77c0da 100644 --- a/distributors-core/CHANGELOG.md +++ b/distributors-core/CHANGELOG.md @@ -91,6 +91,13 @@ - `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`. @@ -110,6 +117,8 @@ ### Breaking Changes +- `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. diff --git a/distributors-core/distributors.cabal b/distributors-core/distributors.cabal index dbeabb3d..2f2b41c5 100644 --- a/distributors-core/distributors.cabal +++ b/distributors-core/distributors.cabal @@ -32,10 +32,10 @@ library Control.Lens.Comonocle Control.Lens.Diopter Control.Lens.Grate - Control.Lens.Internal.Distributor.NestedPrismTH Control.Lens.Internal.Distributor.Orphanage Control.Lens.Monocle Control.Lens.PartialIso + Control.Lens.Prism.Nested Control.Lens.Prismoid Control.Lens.Varifocal Control.Lens.Wither @@ -182,6 +182,7 @@ test-suite test main-is: Main.hs other-modules: Properties.Homogeneous + Properties.Nested Properties.Parsing Properties.PartialIso Paths_distributors diff --git a/distributors-core/src/Control/Lens/PartialIso.hs b/distributors-core/src/Control/Lens/PartialIso.hs index 1e129ec2..78e1f96a 100644 --- a/distributors-core/src/Control/Lens/PartialIso.hs +++ b/distributors-core/src/Control/Lens/PartialIso.hs @@ -49,8 +49,10 @@ module Control.Lens.PartialIso , difoldr1 , difoldl , difoldr - -- * Template Haskell + -- * Nested prisms , makeNestedPrisms + , genericNestedPrism + , genericNestedIso -- * Re-exports , module Control.Lens.Iso , module Control.Lens.Prism @@ -58,7 +60,7 @@ module Control.Lens.PartialIso import Control.Lens import Control.Lens.Internal.Distributor.Orphanage () -import Control.Lens.Internal.Distributor.NestedPrismTH +import Control.Lens.Prism.Nested import Control.Lens.Internal.Profunctor import Control.Lens.Iso import Control.Lens.Prism diff --git a/distributors-core/src/Control/Lens/Internal/Distributor/NestedPrismTH.hs b/distributors-core/src/Control/Lens/Prism/Nested.hs similarity index 63% rename from distributors-core/src/Control/Lens/Internal/Distributor/NestedPrismTH.hs rename to distributors-core/src/Control/Lens/Prism/Nested.hs index 97ee0261..ce2e6fe6 100644 --- a/distributors-core/src/Control/Lens/Internal/Distributor/NestedPrismTH.hs +++ b/distributors-core/src/Control/Lens/Prism/Nested.hs @@ -1,5 +1,6 @@ +{-# LANGUAGE RequiredTypeArguments #-} {- | -Module : Control.Lens.Internal.Distributor.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.Internal.Distributor.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 @@ -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/test/Main.hs b/distributors-core/test/Main.hs index 7a0c7b47..55429b23 100644 --- a/distributors-core/test/Main.hs +++ b/distributors-core/test/Main.hs @@ -6,6 +6,7 @@ import Data.Profunctor.Types (Star (..)) import Test.Hspec import Properties.Homogeneous +import Properties.Nested import Properties.PartialIso import Properties.Parsing @@ -13,6 +14,7 @@ main :: IO () main = hspec $ do describe "Homogeneous" homogeneousProperties describe "PartialIso" partialIsoProperties + describe "Nested" nestedProperties describe "Parsing" parsingProperties describe "meander" meanderProperties 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)) From b72ae5239beef3edd8fdb228dea1cf678951b5c5 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Fri, 13 Nov 2026 16:41:36 -0800 Subject: [PATCH 125/130] Bifocal's applicator, >?<*, replacing mapBifocal bif >?<* p = catMaybes (bif (rmap Just p)) applies a Bifocal directly at a partial Alternator, as >?* does a Prismoid: the target's own methods act as they are (an opted default prints nothing at Printor, as its optionP does, where through a Spectacle it printed the default), & it's faster than through a Spectacle (atLeast 1 at Parsor/Printor: parse 212 vs 234-292 us, print 43 vs 59 us). It agrees with >?* on Prismoids & >?< on PartialIsos, tested at Parsor & Printor. ABifocal applies by cloneBifocal, now by withSpectacle. Grammar re-exports Control.Lens.Bifocal, as CtxGrammars are Filtrators. Co-Authored-By: Claude Opus 5.5 --- distributors-core/CHANGELOG.md | 4 ++ distributors-core/src/Control/Lens/Bifocal.hs | 39 +++++++++++++++---- distributors-grammar/CHANGELOG.md | 2 + .../src/Control/Lens/Grammar.hs | 1 + .../test/Properties/Varifocal.hs | 14 +++++++ 5 files changed, 52 insertions(+), 8 deletions(-) diff --git a/distributors-core/CHANGELOG.md b/distributors-core/CHANGELOG.md index de77c0da..e0a26bba 100644 --- a/distributors-core/CHANGELOG.md +++ b/distributors-core/CHANGELOG.md @@ -117,6 +117,10 @@ ### 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` ~> diff --git a/distributors-core/src/Control/Lens/Bifocal.hs b/distributors-core/src/Control/Lens/Bifocal.hs index a8717174..0f79026b 100644 --- a/distributors-core/src/Control/Lens/Bifocal.hs +++ b/distributors-core/src/Control/Lens/Bifocal.hs @@ -14,11 +14,12 @@ module Control.Lens.Bifocal , ABifocal , Spectacle (..), runSpectacle, spectacle, withSpectacle , Binocular (..), runBinocular + -- * Applicator + , (>?<*) -- * Combinators , bifocal , withBifocal , cloneBifocal - , mapBifocal , crossBifocal , altBifocal , orBifocal @@ -42,7 +43,11 @@ import Witherable -- $setup -- >>> import Control.Lens (_Just, _Left, _Right) --- >>> import Control.Lens.PartialIso (clonePartialIso) +-- >>> 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`, @@ -70,17 +75,35 @@ type ABifocal s t a b = 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 +{- | 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) - => ABifocal s t a b -> p a b -> p s t -mapBifocal bif = runSpectacle (catMaybes (bif (Just <$> Spectacle (Just . Par1) (Just . unPar1)))) + => 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 = unwrapPafb . mapBifocal bif . WrapPafb +cloneBifocal bif = withSpectacle bif $ \match build -> + spectacle (Spectacle match build) {- | Construct a `Bifocal` on pairs from components, with the same foci. @@ -125,7 +148,7 @@ by partial probes. -} withBifocal :: (Alternative f, Filterable f) => ABifocal s t a b -> ((s -> Maybe a) -> f b) -> f t -withBifocal bif = unBinocular (mapBifocal bif (Binocular ($ Just))) +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. -} diff --git a/distributors-grammar/CHANGELOG.md b/distributors-grammar/CHANGELOG.md index 996351b0..77257c43 100644 --- a/distributors-grammar/CHANGELOG.md +++ b/distributors-grammar/CHANGELOG.md @@ -6,6 +6,8 @@ `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%. diff --git a/distributors-grammar/src/Control/Lens/Grammar.hs b/distributors-grammar/src/Control/Lens/Grammar.hs index c6de5c84..ae91a62b 100644 --- a/distributors-grammar/src/Control/Lens/Grammar.hs +++ b/distributors-grammar/src/Control/Lens/Grammar.hs @@ -74,6 +74,7 @@ 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 diff --git a/distributors-grammar/test/Properties/Varifocal.hs b/distributors-grammar/test/Properties/Varifocal.hs index cda4d9c2..d4f96b64 100644 --- a/distributors-grammar/test/Properties/Varifocal.hs +++ b/distributors-grammar/test/Properties/Varifocal.hs @@ -168,6 +168,20 @@ varifocalProperties = do [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 From 66f4f63905826e388419815c1e50d7f73c07773b Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Fri, 20 Nov 2026 12:39:54 -0800 Subject: [PATCH 126/130] distributors-core changes from json-algebra-grammar Brings distributors-core to its state on json-algebra-grammar (83e1623), leaving distributors-grammar & distributors-json as on json-algebra: - timesK & timesP: repetition between bounds, x{lo,hi} & x{lo,}; inRange, exactly, atLeast & atMost by timesP - DisjunctiveMonoid for every Alternative of the dependencies, & for Set, IntSet, Map & IntMap by union - Bits types as BooleanAlgebras; Predicate & Ap Kleene algebras; ReadPrec Filterable - Varifocal: stepping over any Cons stream, steppingTree & arityWith, many & some by manyP & someP, alternatives by anyP Co-Authored-By: Claude Opus 5.5 --- distributors-core/CHANGELOG.md | 25 ++ distributors-core/distributors.cabal | 4 + distributors-core/package.yaml | 1 + .../Lens/Internal/Distributor/Orphanage.hs | 3 + .../src/Control/Lens/Prismoid.hs | 19 +- .../src/Control/Lens/Varifocal.hs | 96 +++++-- .../src/Data/Monoid/Disjunctive.hs | 245 +++++++++++++++++- .../src/Data/Profunctor/Distributor.hs | 33 +++ distributors-core/test/Main.hs | 2 + .../test/Properties/Disjunctive.hs | 47 ++++ 10 files changed, 428 insertions(+), 47 deletions(-) create mode 100644 distributors-core/test/Properties/Disjunctive.hs diff --git a/distributors-core/CHANGELOG.md b/distributors-core/CHANGELOG.md index e0a26bba..8787f286 100644 --- a/distributors-core/CHANGELOG.md +++ b/distributors-core/CHANGELOG.md @@ -4,6 +4,31 @@ ### New APIs +- `timesK`, a `KleeneStarAlgebra` method, & `timesP`, an `Alternator` + method, repeat between some numbers of times, @x{lo,hi}@ or @x{lo,}@, + defaulting to their unfoldings, so static `Alternator`s & Kleene algebras + may keep counts. `inRange`, & so `exactly`, `atLeast` & `atMost`, are + `timesP`. +- More `DisjunctiveMonoid` instances: every `Alternative` of the + dependencies, `base`, `containers`, `vector`, `transformers`, `free`, + `lens` & `witherable`, by `empty` & `<|>`, now with lists, `Seq`s, + `Vector`s, monad transformers, free monads & `ReifiedFold`s; & `Set`s, + `IntSet`s, `Map`s & `IntMap`s, by their monoids, of union. +- `Bits` types are `BooleanAlgebra`s of bit vectors, by `.|.`, `.&.` & + `complement`: every `Int` & `Word`, `Integer`, `IntPtr`, `WordPtr` & the + integers of `Foreign.C.Types`; & `Natural`, without `complement`, only a + `DisjunctiveMonoid`. +- `KleeneStarAlgebra`s: `Predicate`s, whose star is true, & `Ap`s of + `Alternative`s of `Monoid`s, languages, starred by `many`, a + near-semiring. `ReadPrec` is `Filterable`. +- `stepping` & its combinators, `terminateBy`, `delimitBy`, `balanceBy` + & `countWith`, step through any stream, @(Cons s s a a, AsEmpty s)@, + like a `Data.Sequence.Seq` or `Data.Text.Text`, not only lists. +- `steppingTree`, a deterministic top-down tree machine over the cofree + comonad of a `Traversable`, deciding by each node's focus its children's + states, of which `stepping` is the case of `Maybe`, of non-empty streams; + & `arityWith`, count-prefixed trees, each node's focus counting its + children, as `countWith` counts a stream's. - `Enumerable`, in `Data.Traversable.Homogeneous`, of `Homogeneous` countable sums of single copies, sequenced `enumerably` by `CocartesianMonoidal`s, with generic defaults by `Generic1`. diff --git a/distributors-core/distributors.cabal b/distributors-core/distributors.cabal index 2f2b41c5..1a519709 100644 --- a/distributors-core/distributors.cabal +++ b/distributors-core/distributors.cabal @@ -100,6 +100,7 @@ library , containers >=0.6 && <1 , contravariant >=1.5 && <2 , distributive >=0.6 && <1 + , free >=5.1 && <6 , lens >=5.0 && <6 , profunctors >=5.6 && <6 , tagged >=0.8 && <1 @@ -167,6 +168,7 @@ test-suite doctests , distributive >=0.6 && <1 , distributors , doctest-parallel >=0.3 && <1 + , free >=5.1 && <6 , lens >=5.0 && <6 , profunctors >=5.6 && <6 , tagged >=0.8 && <1 @@ -181,6 +183,7 @@ test-suite test type: exitcode-stdio-1.0 main-is: Main.hs other-modules: + Properties.Disjunctive Properties.Homogeneous Properties.Nested Properties.Parsing @@ -238,6 +241,7 @@ test-suite test , contravariant >=1.5 && <2 , distributive >=0.6 && <1 , distributors + , free >=5.1 && <6 , hspec >=2.7 && <3 , lens >=5.0 && <6 , profunctors >=5.6 && <6 diff --git a/distributors-core/package.yaml b/distributors-core/package.yaml index 4e1f822f..713bcf89 100644 --- a/distributors-core/package.yaml +++ b/distributors-core/package.yaml @@ -25,6 +25,7 @@ dependencies: - containers >= 0.6 && < 1 - contravariant >= 1.5 && < 2 - distributive >= 0.6 && < 1 +- free >= 5.1 && < 6 - lens >= 5.0 && < 6 - transformers >= 0.5 && < 1 - profunctors >= 5.6 && < 6 diff --git a/distributors-core/src/Control/Lens/Internal/Distributor/Orphanage.hs b/distributors-core/src/Control/Lens/Internal/Distributor/Orphanage.hs index bb0ebc0d..d160e6c3 100644 --- a/distributors-core/src/Control/Lens/Internal/Distributor/Orphanage.hs +++ b/distributors-core/src/Control/Lens/Internal/Distributor/Orphanage.hs @@ -33,6 +33,7 @@ import Data.Profunctor.Composition import Data.Profunctor.Monad import Data.Profunctor.Yoneda import Text.ParserCombinators.ReadP (ReadP) +import Text.ParserCombinators.ReadPrec (ReadPrec) import Witherable -- Orphanage -- @@ -76,6 +77,8 @@ instance Filterable f => Cochoice (Joker f) where (mapMaybe (either (const Nothing) Just) x) instance Filterable ReadP where catMaybes m = m >>= maybe empty pure +instance Filterable ReadPrec where + catMaybes m = m >>= maybe empty pure deriving via Compose (p a) f instance (Profunctor p, Applicative (p a), Applicative f) => Applicative (WrappedPafb f p a) diff --git a/distributors-core/src/Control/Lens/Prismoid.hs b/distributors-core/src/Control/Lens/Prismoid.hs index f3715ed7..534e15ae 100644 --- a/distributors-core/src/Control/Lens/Prismoid.hs +++ b/distributors-core/src/Control/Lens/Prismoid.hs @@ -42,7 +42,7 @@ module Control.Lens.Prismoid import Control.Applicative import Control.Monad (void) -import Data.Maybe (fromMaybe, isJust) +import Data.Maybe (fromMaybe) import Control.Lens import Control.Lens.Internal.Profunctor import Control.Lens.PartialIso @@ -204,7 +204,7 @@ withPrismoid pat k = {- | Exactly some number of times, or separated by `sepBy`. > prop> exactly n = inRange n (Just n) -> prop> exactly n >?* p = replicateP n p +> prop> exactly n >?* p = replicateP n p, for @n >= 0@ -} exactly :: Int -> Prismoid [a] [b] a b exactly n = inRange n (Just n) @@ -246,7 +246,7 @@ atMost n = inRange 0 (Just n) It takes the mandatory times first, then, unbounded, the `Alternator`'s own `someP` or `manyP`, or, bounded, the optional times, trying more first. -It never matches where @lo > hi@. +It never matches where @lo > hi@, nor where @hi@ is negative. >>> let digits lo hi = runJoker (inRange lo hi >?* Joker (satisfy isDigit)) :: ReadP String >>> [ds | (ds, "") <- readP_to_S (digits 2 (Just 3)) "123"] @@ -255,18 +255,7 @@ It never matches where @lo > hi@. ["12","123"] -} inRange :: Int -> Maybe Int -> Prismoid [a] [b] a b -inRange lo hi = rmap sequenceA . go lo hi - where - go :: Alternator p => Int -> Maybe Int -> p a b -> p [a] [b] - go l h p - | maybe False (l >) h = empty - | l > 1 || (l == 1 && isJust h) = p >:< go (l - 1) (subtract 1 <$> h) p - | l == 1 = someP p - | otherwise = case h of - Nothing -> manyP p - Just m - | m <= 0 -> eotList . swapped >~ empty >+< oneP - | otherwise -> eotList . swapped >~ p >*< go 0 (Just (m - 1)) p >+< oneP +inRange lo hi = rmap sequenceA . timesP lo hi {- | One or zero with default. -} opted :: APrism a b () () -> Prismoid a b a b diff --git a/distributors-core/src/Control/Lens/Varifocal.hs b/distributors-core/src/Control/Lens/Varifocal.hs index 1741ac5a..675016ce 100644 --- a/distributors-core/src/Control/Lens/Varifocal.hs +++ b/distributors-core/src/Control/Lens/Varifocal.hs @@ -1,3 +1,7 @@ +-- `Varifocal` requires a `Filterable` monad, so that every +-- `Control.Lens.Bifocal.Bifocal` is a `Varifocal`, which the stepping +-- combinators, generic in their streams, needn't use. +{-# OPTIONS_GHC -Wno-redundant-constraints #-} {- | Module : Control.Lens.Varifocal Description : varifocals @@ -27,18 +31,24 @@ module Control.Lens.Varifocal , contextuallyT -- * Combinators , stepping + , steppingTree , terminateBy , delimitBy , balanceBy , countWith + , arityWith ) where import Control.Applicative (Alternative (..)) -import Control.Lens -import Control.Lens.PartialIso ((>?)) +import Control.Comonad.Cofree (Cofree (..)) +import Control.Lens hiding ((:<)) +import Control.Lens.PartialIso ((>?), (>~)) import Control.Monad (MonadPlus (..), ap) import Data.Bool (bool) -import Data.Monoid.Disjunctive (DisjunctiveMonoid (..)) +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) @@ -127,6 +137,8 @@ instance Monad m => Monad (Varifocus a b m s) where instance Monad m => Alternative (Varifocus a b m s) where empty = AltsP [] x <|> y = AltsP [x, y] + many = lmap repeat . manyP + some = lmap repeat . someP instance Monad m => DisjunctiveMonoid (Varifocus a b m s t) instance Monad m => Choice (Varifocus a b m) where left' = AlternateP . Left @@ -183,14 +195,10 @@ runVarifocus v p = go v go :: Varifocus a b [] s' t' -> p s' t' go = \case FocusP -> p - LiftP xs -> case map pure xs of - [] -> empty - ys -> foldr1 (<|>) ys + LiftP xs -> anyP pure xs BindP x k -> go x >>= go . k LmapP f x -> lmap f (go x) - AltsP xs -> case map go xs of - [] -> empty - ys -> foldr1 (<|>) ys + AltsP xs -> anyP go xs AlternateP e -> alternate (either (Left . go) (Right . go) e) ManyP x -> manyP (go x) OptionalP x -> optionalP (go x) @@ -212,9 +220,7 @@ runVarifocusT v p = go v LiftP mt -> liftP mt BindP x k -> go x >>= go . k LmapP f x -> lmap f (go x) - AltsP xs -> case map go xs of - [] -> empty - ys -> foldr1 (<|>) ys + AltsP xs -> anyP go xs AlternateP e -> alternate (either (Left . go) (Right . go) e) ManyP x -> manyP (go x) OptionalP x -> optionalP (go x) @@ -294,9 +300,12 @@ contextuallyT vari p = joinP (vari (rmap pure p)) deciding by each focus built whether to continue, @`Right` state@, to stop there, @`Left` `True`@, or to reject, @`Left` `False`@, as no `Control.Lens.Bifocal.Bifocal` can. -A list matches when its last focus, & no earlier one, stops it. +A stream, like a list, matches when its last focus, +& no earlier one, stops it. -} -stepping :: st -> (st -> a -> Either Bool st) -> Varifocal' [a] a +stepping + :: (Cons s s a a, AsEmpty s) + => st -> (st -> a -> Either Bool st) -> Varifocal' s a stepping st0 step q = rmap pure (go st0) where go st = _Cons >? P.do @@ -306,13 +315,44 @@ stepping st0 step q = rmap pure (go st0) Left True -> asEmpty Left False -> empty +{- | Foci stepped through by a deterministic top-down tree machine, +from a state, deciding by each node's focus built which children +it has, a state for each position of a `Traversable` @g@, +or rejecting it, by `Nothing`, as no `Control.Lens.Bifocal.Bifocal` can. +Foci are visited in preorder, a node's before its children's. +A tree matches when each node's children have the shape +its focus decides, so that it parses as it prints. + +`stepping` is `steppingTree` at `Maybe`, of non-empty streams, +as the cofree comonad of `Maybe`, by which +@`Left` `False`@, @`Left` `True`@ & @`Right` state@ +decide `Nothing`, @`Just` `Nothing`@ & @`Just` (`Just` state)@; +`stepping` steps through a stream directly, rather than through +a `Cofree`, & needn't check a shape, as a stream's is its focus's. +-} +steppingTree + :: (Traversable g, Eq (g ())) + => st -> (st -> a -> Maybe (g st)) -> Varifocal' (Cofree g a) a +steppingTree st0 step q = rmap pure (go st0) + where + go st = cofreed >~ P.do + b <- joinP q + maybe empty offspring (step st b) + offspring states = shaped states >? sequenceA + (snd (mapAccumL (\i st -> (i + 1, child i st)) (0 :: Int) states)) + -- after shaping, the child at a position of the children + child i st = lmap (\kids -> toList kids !! i) (go st) + shaped states = prism' id $ \kids -> + if void kids == void states then Just kids else Nothing + cofreed = iso (\(b :< kids) -> (b, kids)) (uncurry (:<)) + {- | Zero or more foci, then one which @end@s them, deciding by each focus built, like a sentinel-terminated sequence, a C string's. -A list which doesn't end by its first ending focus doesn't match. +A stream which doesn't end by its first ending focus doesn't match. > prop> terminateBy end = stepping () (\() -> bool (Right ()) (Left True) . end) -} -terminateBy :: (a -> Bool) -> Varifocal' [a] a +terminateBy :: (Cons s s a a, AsEmpty s) => (a -> Bool) -> Varifocal' s a terminateBy end = stepping () (\() -> bool (Right ()) (Left True) . end) {- | Foci opened by the first, & closed by the first after it @@ -320,9 +360,9 @@ which matches it, deciding by the opening focus built, like a [heredoc](https://en.wikipedia.org/wiki/Here_document)'s tag, or a fenced code block's fence, whose language, of matching delimiters, isn't context-free. -A list which doesn't close by its first match doesn't match. +A stream which doesn't close by its first match doesn't match. -} -delimitBy :: (a -> a -> Bool) -> Varifocal' [a] a +delimitBy :: (Cons s s a a, AsEmpty s) => (a -> a -> Bool) -> Varifocal' s a delimitBy same = stepping Nothing $ \st b -> case st of Nothing -> Right (Just b) Just open -> bool (Right st) (Left True) (same open b) @@ -331,9 +371,11 @@ delimitBy same = stepping Nothing $ \st b -> case st of at the same nesting depth, like nested comments, @/* /* */ */@, or a balanceBy block, whose language, of nested pairs, isn't regular. A focus may not both @open@ & @close@. -A list which doesn't open first, or close only last, doesn't match. +A stream which doesn't open first, or close only last, doesn't match. -} -balanceBy :: (a -> Bool) -> (a -> Bool) -> Varifocal' [a] a +balanceBy + :: (Cons s s a a, AsEmpty s) + => (a -> Bool) -> (a -> Bool) -> Varifocal' s a balanceBy open close = stepping (0 :: Int) step where step depth b @@ -345,9 +387,19 @@ balanceBy open close = stepping (0 :: Int) step {- | A focus counting how many foci follow it, then those, like a length-prefixed record of bytes in a binary format. -A list which doesn't have as many as its first focus counts doesn't match. +A stream which doesn't have as many as its first focus counts +doesn't match. -} -countWith :: (a -> Int) -> Varifocal' [a] a +countWith :: (Cons s s a a, AsEmpty s) => (a -> Int) -> Varifocal' s a countWith count = stepping Nothing $ \st b -> case st of Nothing -> if count b <= 0 then Left True else Right (Just (count b)) Just n -> if n <= 1 then Left True else Right (Just (n - 1)) + +{- | A tree whose nodes' foci each count their children, +like a count-prefixed tree of records in a binary format, +by `steppingTree`, as `countWith` counts a stream's. +A node counting fewer than none doesn't match. +-} +arityWith :: (a -> Int) -> Varifocal' (Cofree [] a) a +arityWith arity = steppingTree () $ \() b -> + if arity b < 0 then Nothing else Just (replicate (arity b) ()) diff --git a/distributors-core/src/Data/Monoid/Disjunctive.hs b/distributors-core/src/Data/Monoid/Disjunctive.hs index 8f0406da..ebffe693 100644 --- a/distributors-core/src/Data/Monoid/Disjunctive.hs +++ b/distributors-core/src/Data/Monoid/Disjunctive.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE DeriveAnyClass #-} {- | Module : Data.Monoid.Disjunctive Description : disjunctive monoids, Boolean & Kleene star algebras @@ -41,10 +42,47 @@ 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 @@ -140,6 +178,33 @@ class (Monoid k, DisjunctiveMonoid k) => KleeneStarAlgebra k where plusK x = x <> starK x optK x = mempty >|< x + {- | Between some numbers of times, inclusive, at least a lower bound, + & at most an upper bound, if there's one, like a regular expression's + @x{lo,hi}@, or @x{lo,}@. Its counts are those @n >= 0@ within its + bounds, so it fails where they're out of order, or all negative, + as regular expression languages reject such quantifiers. + + > prop> timesK 0 Nothing = starK + > prop> timesK 1 Nothing = plusK + > prop> timesK 0 (Just 1) = optK + > prop> timesK n (Just n) x = mconcat (replicate n x), for @n >= 0@ + > prop> timesK (n + 1) hi x = x <> timesK n (subtract 1 <$> hi) x, for @n >= 0@ + > prop> timesK (-1) hi = timesK 0 hi + > prop> timesK 0 (Just (-1)) x = falseP + -} + timesK :: Int -> Maybe Int -> k -> k + timesK lo hi x + | lo < 0 = timesK 0 hi x + | maybe False (lo >) hi = falseP + | lo > 1 || (lo == 1 && isJust hi) = + x <> timesK (lo - 1) (subtract 1 <$> hi) x + | lo == 1 = plusK x + | otherwise = case hi of + Nothing -> starK x + Just m + | m <= 0 -> mempty + | otherwise -> optK (x <> timesK 0 (Just (m - 1)) x) + --instances instance DisjunctiveMonoid Bool where falseP = False @@ -235,16 +300,176 @@ deriving via Generically (Const a b) deriving via Generically (Proxy a) instance DisjunctiveMonoid (Proxy a) deriving via Generically (Proxy a) instance BooleanAlgebra (Proxy a) deriving via Generically (Proxy a) instance KleeneStarAlgebra (Proxy a) -instance DisjunctiveMonoid (Maybe a) -instance DisjunctiveMonoid (IO a) -instance DisjunctiveMonoid (STM a) -instance DisjunctiveMonoid (ZipList a) -instance DisjunctiveMonoid (ReadP a) -instance DisjunctiveMonoid (ReadPrec a) -instance DisjunctiveMonoid (U1 p) -instance MonadPlus m => DisjunctiveMonoid (WrappedMonad m a) -instance ArrowPlus a => DisjunctiveMonoid (WrappedArrow a b c) -instance ArrowPlus a => DisjunctiveMonoid (ArrowMonad a b) +{- | 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) diff --git a/distributors-core/src/Data/Profunctor/Distributor.hs b/distributors-core/src/Data/Profunctor/Distributor.hs index 341fb694..37139d20 100644 --- a/distributors-core/src/Data/Profunctor/Distributor.hs +++ b/distributors-core/src/Data/Profunctor/Distributor.hs @@ -37,6 +37,7 @@ import Data.Profunctor.Monad import Data.Profunctor.Monoidal import Data.Profunctor.Yoneda import Data.Profunctor.Monoidal.Cocartesian +import Data.Maybe (isJust) -- $setup -- >>> import Data.Bifunctor.Joker (Joker (..)) @@ -193,18 +194,50 @@ class (Distributor p, CocartesianChoice p, forall x. Alternative (p x)) manyTillP :: p a b -> p [a] [b] -> p [a] [b] manyTillP p q = let r = q >|< p >:< r in r + {- | Between some numbers of times, inclusive, at least a lower bound, + & at most an upper bound, if there's one, like a regular expression's + @{lo,hi}@, or @{lo,}@. It takes the mandatory times first, then, + unbounded, `someP` or `manyP`, or, bounded, the optional times, + trying more first. It never matches where @lo > hi@, + nor where @hi@ is negative, its counts being those @n >= 0@ within + its bounds. + + It mirrors a `KleeneStarAlgebra`'s `timesK`, so that a static + `Alternator` may keep its counts, rather than unfolding them. + + > prop> timesP 0 Nothing = manyP + > prop> timesP 1 Nothing = someP + > prop> timesP n (Just n) = replicateP n, for @n >= 0@ + -} + timesP :: Int -> Maybe Int -> p a b -> p [a] [b] + timesP lo hi p + | lo < 0 = timesP 0 hi p + | maybe False (lo >) hi = empty + | lo > 1 || (lo == 1 && isJust hi) = + p >:< timesP (lo - 1) (subtract 1 <$> hi) p + | lo == 1 = someP p + | otherwise = case hi of + Nothing -> manyP p + Just m + | m <= 0 -> eotList . swapped >~ empty >+< oneP + | otherwise -> + eotList . swapped >~ p >*< timesP 0 (Just (m - 1)) p >+< oneP + instance (Alternator p, Applicative f) => Alternator (WrappedPafb f p) where someP (WrapPafb x) = WrapPafb (rmap sequenceA (someP x)) optionP def (WrapPafb x) = WrapPafb (optionP (prism pure pure . def) x) + timesP lo hi (WrapPafb x) = WrapPafb (rmap sequenceA (timesP lo hi x)) instance Alternator p => Alternator (Coyoneda p) where someP = proreturn . someP . proextract optionP def = proreturn . optionP def . proextract manyTillP p q = proreturn (manyTillP (proextract p) (proextract q)) + timesP lo hi = proreturn . timesP lo hi . proextract instance Alternator p => Alternator (Yoneda p) where someP = proreturn . someP . proextract optionP def = proreturn . optionP def . proextract manyTillP p q = proreturn (manyTillP (proextract p) (proextract q)) + timesP lo hi = proreturn . timesP lo hi . proextract instance Alternative f => Alternator (Joker f) where someP (Joker x) = Joker (some x) optionP def (Joker x) = diff --git a/distributors-core/test/Main.hs b/distributors-core/test/Main.hs index 55429b23..838ca7a8 100644 --- a/distributors-core/test/Main.hs +++ b/distributors-core/test/Main.hs @@ -5,6 +5,7 @@ import Data.Profunctor.Monoidal (meander) import Data.Profunctor.Types (Star (..)) import Test.Hspec +import Properties.Disjunctive import Properties.Homogeneous import Properties.Nested import Properties.PartialIso @@ -12,6 +13,7 @@ import Properties.Parsing main :: IO () main = hspec $ do + describe "Disjunctive" disjunctiveProperties describe "Homogeneous" homogeneousProperties describe "PartialIso" partialIsoProperties describe "Nested" nestedProperties diff --git a/distributors-core/test/Properties/Disjunctive.hs b/distributors-core/test/Properties/Disjunctive.hs new file mode 100644 index 00000000..d872d9c6 --- /dev/null +++ b/distributors-core/test/Properties/Disjunctive.hs @@ -0,0 +1,47 @@ +module Properties.Disjunctive (disjunctiveProperties) where + +import Data.Functor.Contravariant (Predicate (..)) +import Data.Int (Int8) +import Data.Monoid (Ap (..)) +import Data.Monoid.Disjunctive +import Data.Word (Word8) +import Numeric.Natural (Natural) +import Test.Hspec +import Test.Hspec.QuickCheck (prop) +import Test.QuickCheck +import Text.ParserCombinators.ReadP (ReadP, readP_to_S, string) + +disjunctiveProperties :: Spec +disjunctiveProperties = do + describe "Bits, as a BooleanAlgebra of bit vectors" $ do + booleanLaws "Int" (arbitrary :: Gen Int) + booleanLaws "Int8" (arbitrary :: Gen Int8) + booleanLaws "Word8" (arbitrary :: Gen Word8) + booleanLaws "Integer" (arbitrary :: Gen Integer) + prop "Natural disjoins as a monoid" $ \(NonNegative (x :: Integer)) y -> + let n = fromInteger x :: Natural + m = fromInteger (getNonNegative y) :: Natural + in (falseP >|< n) === n .&&. (n >|< m) === (m >|< n) + describe "Predicate, as a Kleene algebra" $ + prop "its star is true" $ \(Fun _ p) (x :: Int) -> + getPredicate (starK (Predicate p)) x === True + .&&. getPredicate (optK (Predicate p)) x === True + describe "Ap, as a Kleene algebra of languages" $ + it "stars by many, concatenated" $ do + let star = getAp (starK (Ap (string "ab"))) :: ReadP String + [w | (w, "") <- readP_to_S star "ababab"] `shouldBe` ["ababab"] + [w | (w, "") <- readP_to_S star ""] `shouldBe` [""] + let plus = getAp (plusK (Ap (string "ab"))) :: ReadP String + [w | (w, "") <- readP_to_S plus ""] `shouldBe` [] + +booleanLaws + :: (Show b, Eq b, BooleanAlgebra b) => String -> Gen b -> Spec +booleanLaws name gen = describe name $ do + prop "x >&< notP x = falseP & x >|< notP x = trueP" $ + forAll gen $ \x -> + (x >&< notP x) === falseP .&&. (x >|< notP x) === trueP + prop "de Morgan" $ forAll gen $ \x -> forAll gen $ \y -> + notP (x >|< y) === (notP x >&< notP y) + prop "notP . notP = id" $ forAll gen $ \x -> notP (notP x) === x + prop "units" $ forAll gen $ \x -> + (x >|< falseP) === x .&&. (x >&< trueP) === x From f05cc17ed4179154822bed8739989fc6cd43322b Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Fri, 20 Nov 2026 12:59:31 -0800 Subject: [PATCH 127/130] Kleene quantifiers quantK & quantP; ctxList & ctxTree Renames timesK ~> quantK, timesP ~> quantP, stepping ~> ctxList & steppingTree ~> ctxTree. Documents quantK & quantP as Kleene quantifiers, with quantP 0 (Just 1) by optionalP. Co-Authored-By: Claude Opus 5.5 --- distributors-core/CHANGELOG.md | 18 +++++----- .../src/Control/Lens/Prismoid.hs | 2 +- .../src/Control/Lens/Varifocal.hs | 34 +++++++++---------- .../src/Data/Monoid/Disjunctive.hs | 30 ++++++++-------- .../src/Data/Profunctor/Distributor.hs | 31 +++++++++-------- .../test/Properties/Varifocal.hs | 2 +- 6 files changed, 59 insertions(+), 58 deletions(-) diff --git a/distributors-core/CHANGELOG.md b/distributors-core/CHANGELOG.md index 8787f286..f09aebf4 100644 --- a/distributors-core/CHANGELOG.md +++ b/distributors-core/CHANGELOG.md @@ -4,11 +4,11 @@ ### New APIs -- `timesK`, a `KleeneStarAlgebra` method, & `timesP`, an `Alternator` - method, repeat between some numbers of times, @x{lo,hi}@ or @x{lo,}@, - defaulting to their unfoldings, so static `Alternator`s & Kleene algebras - may keep counts. `inRange`, & so `exactly`, `atLeast` & `atMost`, are - `timesP`. +- 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, @@ -21,12 +21,12 @@ - `KleeneStarAlgebra`s: `Predicate`s, whose star is true, & `Ap`s of `Alternative`s of `Monoid`s, languages, starred by `many`, a near-semiring. `ReadPrec` is `Filterable`. -- `stepping` & its combinators, `terminateBy`, `delimitBy`, `balanceBy` +- `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. -- `steppingTree`, a deterministic top-down tree machine over the cofree +- `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 `stepping` is the case of `Maybe`, of non-empty streams; + 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` @@ -75,7 +75,7 @@ `AVarifocal`, `varifocus`, `runVarifocus`, `runVarifocusT` & `cloneVarifocal`; `crossVarifocal`, `altVarifocal`, `orVarifocal` & `bindVarifocal`, - the last choosing a second by what the first built, like a netstring; & `stepping`, a deterministic machine over foci, + 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 diff --git a/distributors-core/src/Control/Lens/Prismoid.hs b/distributors-core/src/Control/Lens/Prismoid.hs index 534e15ae..3389dae4 100644 --- a/distributors-core/src/Control/Lens/Prismoid.hs +++ b/distributors-core/src/Control/Lens/Prismoid.hs @@ -255,7 +255,7 @@ It never matches where @lo > hi@, nor where @hi@ is negative. ["12","123"] -} inRange :: Int -> Maybe Int -> Prismoid [a] [b] a b -inRange lo hi = rmap sequenceA . timesP lo hi +inRange lo hi = rmap sequenceA . quantP lo hi {- | One or zero with default. -} opted :: APrism a b () () -> Prismoid a b a b diff --git a/distributors-core/src/Control/Lens/Varifocal.hs b/distributors-core/src/Control/Lens/Varifocal.hs index 675016ce..2dabf629 100644 --- a/distributors-core/src/Control/Lens/Varifocal.hs +++ b/distributors-core/src/Control/Lens/Varifocal.hs @@ -1,6 +1,6 @@ -- `Varifocal` requires a `Filterable` monad, so that every --- `Control.Lens.Bifocal.Bifocal` is a `Varifocal`, which the stepping --- combinators, generic in their streams, needn't use. +-- `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 @@ -30,8 +30,8 @@ module Control.Lens.Varifocal , contextually , contextuallyT -- * Combinators - , stepping - , steppingTree + , ctxList + , ctxTree , terminateBy , delimitBy , balanceBy @@ -303,10 +303,10 @@ as no `Control.Lens.Bifocal.Bifocal` can. A stream, like a list, matches when its last focus, & no earlier one, stops it. -} -stepping +ctxList :: (Cons s s a a, AsEmpty s) => st -> (st -> a -> Either Bool st) -> Varifocal' s a -stepping st0 step q = rmap pure (go st0) +ctxList st0 step q = rmap pure (go st0) where go st = _Cons >? P.do b <- joinP q @@ -323,17 +323,17 @@ Foci are visited in preorder, a node's before its children's. A tree matches when each node's children have the shape its focus decides, so that it parses as it prints. -`stepping` is `steppingTree` at `Maybe`, of non-empty streams, +`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)@; -`stepping` steps through a stream directly, rather than through +`ctxList` steps through a stream directly, rather than through a `Cofree`, & needn't check a shape, as a stream's is its focus's. -} -steppingTree +ctxTree :: (Traversable g, Eq (g ())) => st -> (st -> a -> Maybe (g st)) -> Varifocal' (Cofree g a) a -steppingTree st0 step q = rmap pure (go st0) +ctxTree st0 step q = rmap pure (go st0) where go st = cofreed >~ P.do b <- joinP q @@ -350,10 +350,10 @@ steppingTree st0 step q = rmap pure (go st0) 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 = stepping () (\() -> bool (Right ()) (Left True) . end) +> prop> terminateBy end = ctxList () (\() -> bool (Right ()) (Left True) . end) -} terminateBy :: (Cons s s a a, AsEmpty s) => (a -> Bool) -> Varifocal' s a -terminateBy end = stepping () (\() -> bool (Right ()) (Left True) . end) +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, @@ -363,7 +363,7 @@ 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 = stepping Nothing $ \st b -> case st of +delimitBy same = ctxList Nothing $ \st b -> case st of Nothing -> Right (Just b) Just open -> bool (Right st) (Left True) (same open b) @@ -376,7 +376,7 @@ 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 = stepping (0 :: Int) step +balanceBy open close = ctxList (0 :: Int) step where step depth b | open b = Right (depth + 1) @@ -391,15 +391,15 @@ 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 = stepping Nothing $ \st b -> case st of +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 `steppingTree`, as `countWith` counts a stream's. +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 = steppingTree () $ \() b -> +arityWith arity = ctxTree () $ \() b -> if arity b < 0 then Nothing else Just (replicate (arity b) ()) diff --git a/distributors-core/src/Data/Monoid/Disjunctive.hs b/distributors-core/src/Data/Monoid/Disjunctive.hs index ebffe693..b7f76ed1 100644 --- a/distributors-core/src/Data/Monoid/Disjunctive.hs +++ b/distributors-core/src/Data/Monoid/Disjunctive.hs @@ -178,32 +178,32 @@ class (Monoid k, DisjunctiveMonoid k) => KleeneStarAlgebra k where plusK x = x <> starK x optK x = mempty >|< x - {- | Between some numbers of times, inclusive, at least a lower bound, - & at most an upper bound, if there's one, like a regular expression's - @x{lo,hi}@, or @x{lo,}@. Its counts are those @n >= 0@ within its + {- | 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> timesK 0 Nothing = starK - > prop> timesK 1 Nothing = plusK - > prop> timesK 0 (Just 1) = optK - > prop> timesK n (Just n) x = mconcat (replicate n x), for @n >= 0@ - > prop> timesK (n + 1) hi x = x <> timesK n (subtract 1 <$> hi) x, for @n >= 0@ - > prop> timesK (-1) hi = timesK 0 hi - > prop> timesK 0 (Just (-1)) x = falseP + > 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 -} - timesK :: Int -> Maybe Int -> k -> k - timesK lo hi x - | lo < 0 = timesK 0 hi x + 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 <> timesK (lo - 1) (subtract 1 <$> hi) x + 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 <> timesK 0 (Just (m - 1)) x) + | otherwise -> optK (x <> quantK 0 (Just (m - 1)) x) --instances instance DisjunctiveMonoid Bool where diff --git a/distributors-core/src/Data/Profunctor/Distributor.hs b/distributors-core/src/Data/Profunctor/Distributor.hs index 37139d20..8c6fc873 100644 --- a/distributors-core/src/Data/Profunctor/Distributor.hs +++ b/distributors-core/src/Data/Profunctor/Distributor.hs @@ -194,50 +194,51 @@ class (Distributor p, CocartesianChoice p, forall x. Alternative (p x)) manyTillP :: p a b -> p [a] [b] -> p [a] [b] manyTillP p q = let r = q >|< p >:< r in r - {- | Between some numbers of times, inclusive, at least a lower bound, - & at most an upper bound, if there's one, like a regular expression's - @{lo,hi}@, or @{lo,}@. It takes the mandatory times first, then, + {- | 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 `timesK`, so that a static + It mirrors a `KleeneStarAlgebra`'s `quantK`, so that a static `Alternator` may keep its counts, rather than unfolding them. - > prop> timesP 0 Nothing = manyP - > prop> timesP 1 Nothing = someP - > prop> timesP n (Just n) = replicateP n, for @n >= 0@ + > prop> quantP 0 Nothing = manyP + > prop> quantP 1 Nothing = someP + > prop> quantP n (Just n) = replicateP n, for @n >= 0@ + > prop> quantP 0 (Just 1) x = iso listToMaybe toList >~ optionalP x, on lists of at most one -} - timesP :: Int -> Maybe Int -> p a b -> p [a] [b] - timesP lo hi p - | lo < 0 = timesP 0 hi p + 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 >:< timesP (lo - 1) (subtract 1 <$> hi) p + 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 >*< timesP 0 (Just (m - 1)) p >+< oneP + 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) - timesP lo hi (WrapPafb x) = WrapPafb (rmap sequenceA (timesP lo hi 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)) - timesP lo hi = proreturn . timesP lo hi . proextract + 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)) - timesP lo hi = proreturn . timesP lo hi . proextract + 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) = diff --git a/distributors-grammar/test/Properties/Varifocal.hs b/distributors-grammar/test/Properties/Varifocal.hs index d4f96b64..c4d7e535 100644 --- a/distributors-grammar/test/Properties/Varifocal.hs +++ b/distributors-grammar/test/Properties/Varifocal.hs @@ -49,7 +49,7 @@ varifocalProperties = do prop "doesn't print an early end" $ forAll plain $ \s -> forAll plain $ \t -> printed ended (s ++ "." ++ t ++ ".") === Nothing - describe "balanceBy & countWith, by stepping" $ do + describe "balanceBy & countWith, by ctxList" $ do let nested :: Varifocal' String Char nested = balanceBy (== '(') (== ')') From 26b7735372768c14c6c5797b6d61bbbb33826639 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Fri, 20 Nov 2026 13:01:23 -0800 Subject: [PATCH 128/130] Remove quantP 0 (Just 1) prop, false for lists of two or more Co-Authored-By: Claude Opus 5.5 --- distributors-core/src/Data/Profunctor/Distributor.hs | 1 - 1 file changed, 1 deletion(-) diff --git a/distributors-core/src/Data/Profunctor/Distributor.hs b/distributors-core/src/Data/Profunctor/Distributor.hs index 8c6fc873..b1cd9a6d 100644 --- a/distributors-core/src/Data/Profunctor/Distributor.hs +++ b/distributors-core/src/Data/Profunctor/Distributor.hs @@ -208,7 +208,6 @@ class (Distributor p, CocartesianChoice p, forall x. Alternative (p x)) > prop> quantP 0 Nothing = manyP > prop> quantP 1 Nothing = someP > prop> quantP n (Just n) = replicateP n, for @n >= 0@ - > prop> quantP 0 (Just 1) x = iso listToMaybe toList >~ optionalP x, on lists of at most one -} quantP :: Int -> Maybe Int -> p a b -> p [a] [b] quantP lo hi p From abfc5681e9768c4a91552e7dc33b552b546c1367 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Fri, 20 Nov 2026 13:01:58 -0800 Subject: [PATCH 129/130] quantP 0 (Just 1) is optionalP, by a partial iso to Maybe Co-Authored-By: Claude Opus 5.5 --- distributors-core/src/Data/Profunctor/Distributor.hs | 1 + 1 file changed, 1 insertion(+) diff --git a/distributors-core/src/Data/Profunctor/Distributor.hs b/distributors-core/src/Data/Profunctor/Distributor.hs index b1cd9a6d..307326ec 100644 --- a/distributors-core/src/Data/Profunctor/Distributor.hs +++ b/distributors-core/src/Data/Profunctor/Distributor.hs @@ -208,6 +208,7 @@ class (Distributor p, CocartesianChoice p, forall x. Alternative (p x)) > prop> quantP 0 Nothing = manyP > prop> quantP 1 Nothing = someP > prop> quantP n (Just n) = replicateP n, for @n >= 0@ + > prop> quantP 0 (Just 1) x = partialIso (\as -> if length as <= 1 then Just (listToMaybe as) else Nothing) (Just . toList) >? optionalP x -} quantP :: Int -> Maybe Int -> p a b -> p [a] [b] quantP lo hi p From 33122d6f98e47f26103b8cc5b9c02b3f75eb28f2 Mon Sep 17 00:00:00 2001 From: Eitan Chatav Date: Fri, 20 Nov 2026 13:02:30 -0800 Subject: [PATCH 130/130] Remove the quantP 0 (Just 1) partialIso prop Co-Authored-By: Claude Opus 5.5 --- distributors-core/src/Data/Profunctor/Distributor.hs | 1 - 1 file changed, 1 deletion(-) diff --git a/distributors-core/src/Data/Profunctor/Distributor.hs b/distributors-core/src/Data/Profunctor/Distributor.hs index 307326ec..b1cd9a6d 100644 --- a/distributors-core/src/Data/Profunctor/Distributor.hs +++ b/distributors-core/src/Data/Profunctor/Distributor.hs @@ -208,7 +208,6 @@ class (Distributor p, CocartesianChoice p, forall x. Alternative (p x)) > prop> quantP 0 Nothing = manyP > prop> quantP 1 Nothing = someP > prop> quantP n (Just n) = replicateP n, for @n >= 0@ - > prop> quantP 0 (Just 1) x = partialIso (\as -> if length as <= 1 then Just (listToMaybe as) else Nothing) (Just . toList) >? optionalP x -} quantP :: Int -> Maybe Int -> p a b -> p [a] [b] quantP lo hi p