aeson-match-qq 1.9.0 → 2.0.0
raw patch · 18 files changed
+849/−422 lines, 18 filesdep +aeson-value-qqdep +ghc-hs-metadep +hspec-waidep −aeson-qqdep −haskell-src-metaPVP ok
version bump matches the API change (PVP)
Dependencies added: aeson-value-qq, ghc-hs-meta, hspec-wai
Dependencies removed: aeson-qq, haskell-src-meta
API changes (from Hackage documentation)
- Aeson.Match.QQ.Internal.Match: instance Data.Aeson.Types.ToJSON.ToJSON Aeson.Match.QQ.Internal.Match.Error
- Aeson.Match.QQ.Internal.Match: instance Data.Aeson.Types.ToJSON.ToJSON Aeson.Match.QQ.Internal.Match.Mismatch
- Aeson.Match.QQ.Internal.Match: instance Data.Aeson.Types.ToJSON.ToJSON Aeson.Match.QQ.Internal.Match.TypeMismatch
- Aeson.Match.QQ.Internal.Match: match :: Matcher Value -> Value -> Either (NonEmpty Error) (HashMap Text Value)
- Aeson.Match.QQ.Internal.Value: AnyT :: Type
- Aeson.Match.QQ.Internal.Value: ArrayT :: Type
- Aeson.Match.QQ.Internal.Value: ArrayUOT :: Type
- Aeson.Match.QQ.Internal.Value: BoolT :: Type
- Aeson.Match.QQ.Internal.Value: Box :: a -> Bool -> Box a
- Aeson.Match.QQ.Internal.Value: NumberT :: Type
- Aeson.Match.QQ.Internal.Value: ObjectT :: Type
- Aeson.Match.QQ.Internal.Value: StringCIT :: Type
- Aeson.Match.QQ.Internal.Value: StringT :: Type
- Aeson.Match.QQ.Internal.Value: [extra] :: Box a -> Bool
- Aeson.Match.QQ.Internal.Value: [values] :: Box a -> a
- Aeson.Match.QQ.Internal.Value: data Box a
- Aeson.Match.QQ.Internal.Value: data Matcher ext
- Aeson.Match.QQ.Internal.Value: data Type
- Aeson.Match.QQ.Internal.Value: instance Data.Aeson.Types.ToJSON.ToJSON Aeson.Match.QQ.Internal.Value.Type
- Aeson.Match.QQ.Internal.Value: instance Data.Aeson.Types.ToJSON.ToJSON a => Data.Aeson.Types.ToJSON.ToJSON (Aeson.Match.QQ.Internal.Value.Box a)
- Aeson.Match.QQ.Internal.Value: instance Data.Aeson.Types.ToJSON.ToJSON ext => Data.Aeson.Types.ToJSON.ToJSON (Aeson.Match.QQ.Internal.Value.Matcher ext)
- Aeson.Match.QQ.Internal.Value: instance GHC.Base.Functor Aeson.Match.QQ.Internal.Value.Box
- Aeson.Match.QQ.Internal.Value: instance GHC.Base.Functor Aeson.Match.QQ.Internal.Value.Matcher
- Aeson.Match.QQ.Internal.Value: instance GHC.Classes.Eq Aeson.Match.QQ.Internal.Value.Type
- Aeson.Match.QQ.Internal.Value: instance GHC.Classes.Eq a => GHC.Classes.Eq (Aeson.Match.QQ.Internal.Value.Box a)
- Aeson.Match.QQ.Internal.Value: instance GHC.Classes.Eq ext => GHC.Classes.Eq (Aeson.Match.QQ.Internal.Value.Matcher ext)
- Aeson.Match.QQ.Internal.Value: instance GHC.Show.Show Aeson.Match.QQ.Internal.Value.Type
- Aeson.Match.QQ.Internal.Value: instance GHC.Show.Show a => GHC.Show.Show (Aeson.Match.QQ.Internal.Value.Box a)
- Aeson.Match.QQ.Internal.Value: instance GHC.Show.Show ext => GHC.Show.Show (Aeson.Match.QQ.Internal.Value.Matcher ext)
- Aeson.Match.QQ.Internal.Value: instance Language.Haskell.TH.Syntax.Lift Aeson.Match.QQ.Internal.Value.Type
- Aeson.Match.QQ.Internal.Value: instance Text.PrettyPrint.HughesPJClass.Pretty Aeson.Match.QQ.Internal.Value.Type
- Aeson.Match.QQ.Internal.Value: type Array ext = Box Vector Matcher ext
- Aeson.Match.QQ.Internal.Value: type Object ext = Box HashMap Text NonEmpty Matcher ext
+ Aeson.Match.QQ: [CCons] :: forall (names1 :: [Symbol]) (name :: Symbol). Value -> Captures names1 -> Captures (name ': names1)
+ Aeson.Match.QQ: [CEmpty] :: Captures ('[] :: [Symbol])
+ Aeson.Match.QQ: class HasCapture (name :: Symbol) (names :: [Symbol])
+ Aeson.Match.QQ: data Captures (names :: [Symbol])
+ Aeson.Match.QQ: data MatcherAST
+ Aeson.Match.QQ: extractDecoded :: forall (name :: Symbol) (names :: [Symbol]) r. (HasCapture name names, FromJSON r) => Captures names -> Either String r
+ Aeson.Match.QQ: extractValue :: HasCapture name names => Captures names -> Value
+ Aeson.Match.QQ.Internal.Box: Box :: a -> Bool -> Box a
+ Aeson.Match.QQ.Internal.Box: [extra] :: Box a -> Bool
+ Aeson.Match.QQ.Internal.Box: [values] :: Box a -> a
+ Aeson.Match.QQ.Internal.Box: data Box a
+ Aeson.Match.QQ.Internal.Box: instance GHC.Base.Functor Aeson.Match.QQ.Internal.Box.Box
+ Aeson.Match.QQ.Internal.Box: instance GHC.Classes.Eq a => GHC.Classes.Eq (Aeson.Match.QQ.Internal.Box.Box a)
+ Aeson.Match.QQ.Internal.Box: instance GHC.Show.Show a => GHC.Show.Show (Aeson.Match.QQ.Internal.Box.Box a)
+ Aeson.Match.QQ.Internal.Box: type Array a = Box Vector a
+ Aeson.Match.QQ.Internal.Box: type Object a = Box HashMap Text NonEmpty a
+ Aeson.Match.QQ.Internal.Captures: [CCons] :: forall (names1 :: [Symbol]) (name :: Symbol). Value -> Captures names1 -> Captures (name ': names1)
+ Aeson.Match.QQ.Internal.Captures: [CEmpty] :: Captures ('[] :: [Symbol])
+ Aeson.Match.QQ.Internal.Captures: class HasCapture (name :: Symbol) (names :: [Symbol])
+ Aeson.Match.QQ.Internal.Captures: data Captures (names :: [Symbol])
+ Aeson.Match.QQ.Internal.Captures: extractValue :: HasCapture name names => Captures names -> Value
+ Aeson.Match.QQ.Internal.Captures: instance (TypeError ...) => Aeson.Match.QQ.Internal.Captures.HasCapture name '[]
+ Aeson.Match.QQ.Internal.Captures: instance Aeson.Match.QQ.Internal.Captures.HasCapture name (name : names)
+ Aeson.Match.QQ.Internal.Captures: instance Aeson.Match.QQ.Internal.Captures.HasCapture name names => Aeson.Match.QQ.Internal.Captures.HasCapture name (other : names)
+ Aeson.Match.QQ.Internal.Captures: instance GHC.Classes.Eq (Aeson.Match.QQ.Internal.Captures.Captures names)
+ Aeson.Match.QQ.Internal.Captures: instance GHC.Show.Show (Aeson.Match.QQ.Internal.Captures.Captures names)
+ Aeson.Match.QQ.Internal.Match: matchAST :: MatcherAST -> Value -> Either (NonEmpty Error) (HashMap Text Value)
+ Aeson.Match.QQ.Internal.Matcher: data Matcher (names :: [Symbol])
+ Aeson.Match.QQ.Internal.Matcher: match :: forall (names :: [Symbol]). Matcher names -> Value -> Either (NonEmpty Error) (Captures names)
+ Aeson.Match.QQ.Internal.Matcher: quoteMatcher :: Parsed -> Q Exp
+ Aeson.Match.QQ.Internal.Parse: Array :: Array Parsed -> Parsed
+ Aeson.Match.QQ.Internal.Parse: ArrayUO :: Array Parsed -> Parsed
+ Aeson.Match.QQ.Internal.Parse: Bool :: Bool -> Parsed
+ Aeson.Match.QQ.Internal.Parse: CI :: CI
+ Aeson.Match.QQ.Internal.Parse: CS :: CI
+ Aeson.Match.QQ.Internal.Parse: Ext :: Exp -> Parsed
+ Aeson.Match.QQ.Internal.Parse: Interpolate :: Exp -> StringFrag
+ Aeson.Match.QQ.Internal.Parse: Null :: Parsed
+ Aeson.Match.QQ.Internal.Parse: Number :: Scientific -> Parsed
+ Aeson.Match.QQ.Internal.Parse: Object :: Object Parsed -> Parsed
+ Aeson.Match.QQ.Internal.Parse: Raw :: Text -> StringFrag
+ Aeson.Match.QQ.Internal.Parse: Sig :: Type -> Bool -> Parsed -> Parsed
+ Aeson.Match.QQ.Internal.Parse: String :: CI -> NonEmpty StringFrag -> Parsed
+ Aeson.Match.QQ.Internal.Parse: Var :: Text -> Parsed
+ Aeson.Match.QQ.Internal.Parse: data CI
+ Aeson.Match.QQ.Internal.Parse: data Parsed
+ Aeson.Match.QQ.Internal.Parse: data StringFrag
+ Aeson.Match.QQ.Internal.Parse: instance GHC.Classes.Eq Aeson.Match.QQ.Internal.Parse.CI
+ Aeson.Match.QQ.Internal.Parse: instance GHC.Classes.Eq Aeson.Match.QQ.Internal.Parse.Parsed
+ Aeson.Match.QQ.Internal.Parse: instance GHC.Classes.Eq Aeson.Match.QQ.Internal.Parse.StringFrag
+ Aeson.Match.QQ.Internal.Parse: instance GHC.Show.Show Aeson.Match.QQ.Internal.Parse.CI
+ Aeson.Match.QQ.Internal.Parse: instance GHC.Show.Show Aeson.Match.QQ.Internal.Parse.Parsed
+ Aeson.Match.QQ.Internal.Parse: instance GHC.Show.Show Aeson.Match.QQ.Internal.Parse.StringFrag
+ Aeson.Match.QQ.Internal.Parse.CollectNames: DuplicateHoleName :: Text -> CollectNamesError
+ Aeson.Match.QQ.Internal.Parse.CollectNames: collectNames :: Parsed -> Either CollectNamesError [Text]
+ Aeson.Match.QQ.Internal.Parse.CollectNames: data CollectNamesError
+ Aeson.Match.QQ.Internal.Parse.CollectNames: instance GHC.Classes.Eq Aeson.Match.QQ.Internal.Parse.CollectNames.CollectNamesError
+ Aeson.Match.QQ.Internal.Parse.CollectNames: instance GHC.Show.Show Aeson.Match.QQ.Internal.Parse.CollectNames.CollectNamesError
+ Aeson.Match.QQ.Internal.Type: AnyT :: Type
+ Aeson.Match.QQ.Internal.Type: ArrayT :: Type
+ Aeson.Match.QQ.Internal.Type: ArrayUOT :: Type
+ Aeson.Match.QQ.Internal.Type: BoolT :: Type
+ Aeson.Match.QQ.Internal.Type: NumberT :: Type
+ Aeson.Match.QQ.Internal.Type: ObjectT :: Type
+ Aeson.Match.QQ.Internal.Type: StringCIT :: Type
+ Aeson.Match.QQ.Internal.Type: StringT :: Type
+ Aeson.Match.QQ.Internal.Type: data Type
+ Aeson.Match.QQ.Internal.Type: instance GHC.Classes.Eq Aeson.Match.QQ.Internal.Type.Type
+ Aeson.Match.QQ.Internal.Type: instance GHC.Show.Show Aeson.Match.QQ.Internal.Type.Type
+ Aeson.Match.QQ.Internal.Type: instance Language.Haskell.TH.Syntax.Lift Aeson.Match.QQ.Internal.Type.Type
+ Aeson.Match.QQ.Internal.Type: instance Text.PrettyPrint.HughesPJClass.Pretty Aeson.Match.QQ.Internal.Type.Type
+ Aeson.Match.QQ.Internal.Value: data MatcherAST
+ Aeson.Match.QQ.Internal.Value: instance GHC.Classes.Eq Aeson.Match.QQ.Internal.Value.MatcherAST
+ Aeson.Match.QQ.Internal.Value: instance GHC.Show.Show Aeson.Match.QQ.Internal.Value.MatcherAST
- Aeson.Match.QQ: Array :: Array ext -> Matcher ext
+ Aeson.Match.QQ: Array :: Array MatcherAST -> MatcherAST
- Aeson.Match.QQ: ArrayUO :: Array ext -> Matcher ext
+ Aeson.Match.QQ: ArrayUO :: Array MatcherAST -> MatcherAST
- Aeson.Match.QQ: Bool :: Bool -> Matcher ext
+ Aeson.Match.QQ: Bool :: Bool -> MatcherAST
- Aeson.Match.QQ: Ext :: ext -> Matcher ext
+ Aeson.Match.QQ: Ext :: Value -> MatcherAST
- Aeson.Match.QQ: MkMismatch :: Path -> Matcher Value -> Value -> Mismatch
+ Aeson.Match.QQ: MkMismatch :: Path -> MatcherAST -> Value -> Mismatch
- Aeson.Match.QQ: MkTypeMismatch :: Path -> Type -> Matcher Value -> Value -> TypeMismatch
+ Aeson.Match.QQ: MkTypeMismatch :: Path -> Type -> MatcherAST -> Value -> TypeMismatch
- Aeson.Match.QQ: Null :: Matcher ext
+ Aeson.Match.QQ: Null :: MatcherAST
- Aeson.Match.QQ: Number :: Scientific -> Matcher ext
+ Aeson.Match.QQ: Number :: Scientific -> MatcherAST
- Aeson.Match.QQ: Object :: Object ext -> Matcher ext
+ Aeson.Match.QQ: Object :: Object MatcherAST -> MatcherAST
- Aeson.Match.QQ: Sig :: Type -> Bool -> Matcher ext -> Matcher ext
+ Aeson.Match.QQ: Sig :: Type -> Bool -> MatcherAST -> MatcherAST
- Aeson.Match.QQ: String :: Text -> Matcher ext
+ Aeson.Match.QQ: String :: Text -> MatcherAST
- Aeson.Match.QQ: StringCI :: CI Text -> Matcher ext
+ Aeson.Match.QQ: StringCI :: CI Text -> MatcherAST
- Aeson.Match.QQ: Var :: Text -> Matcher ext
+ Aeson.Match.QQ: Var :: Text -> MatcherAST
- Aeson.Match.QQ: [matcher] :: Mismatch -> Matcher Value
+ Aeson.Match.QQ: [matcher] :: Mismatch -> MatcherAST
- Aeson.Match.QQ: data Matcher ext
+ Aeson.Match.QQ: data Matcher (names :: [Symbol])
- Aeson.Match.QQ: match :: Matcher Value -> Value -> Either (NonEmpty Error) (HashMap Text Value)
+ Aeson.Match.QQ: match :: forall (names :: [Symbol]). Matcher names -> Value -> Either (NonEmpty Error) (Captures names)
- Aeson.Match.QQ: parse :: ByteString -> Either String (Matcher Exp)
+ Aeson.Match.QQ: parse :: [Extension] -> ByteString -> Either String Parsed
- Aeson.Match.QQ: type Array ext = Box Vector Matcher ext
+ Aeson.Match.QQ: type Array a = Box Vector a
- Aeson.Match.QQ: type Object ext = Box HashMap Text NonEmpty Matcher ext
+ Aeson.Match.QQ: type Object a = Box HashMap Text NonEmpty a
- Aeson.Match.QQ.Internal.Match: MkMismatch :: Path -> Matcher Value -> Value -> Mismatch
+ Aeson.Match.QQ.Internal.Match: MkMismatch :: Path -> MatcherAST -> Value -> Mismatch
- Aeson.Match.QQ.Internal.Match: MkTypeMismatch :: Path -> Type -> Matcher Value -> Value -> TypeMismatch
+ Aeson.Match.QQ.Internal.Match: MkTypeMismatch :: Path -> Type -> MatcherAST -> Value -> TypeMismatch
- Aeson.Match.QQ.Internal.Match: [matcher] :: Mismatch -> Matcher Value
+ Aeson.Match.QQ.Internal.Match: [matcher] :: Mismatch -> MatcherAST
- Aeson.Match.QQ.Internal.Parse: parse :: ByteString -> Either String (Matcher Exp)
+ Aeson.Match.QQ.Internal.Parse: parse :: [Extension] -> ByteString -> Either String Parsed
- Aeson.Match.QQ.Internal.PrettyPrint: pp :: Matcher Value -> Doc
+ Aeson.Match.QQ.Internal.PrettyPrint: pp :: MatcherAST -> Doc
- Aeson.Match.QQ.Internal.Value: Array :: Array ext -> Matcher ext
+ Aeson.Match.QQ.Internal.Value: Array :: Array MatcherAST -> MatcherAST
- Aeson.Match.QQ.Internal.Value: ArrayUO :: Array ext -> Matcher ext
+ Aeson.Match.QQ.Internal.Value: ArrayUO :: Array MatcherAST -> MatcherAST
- Aeson.Match.QQ.Internal.Value: Bool :: Bool -> Matcher ext
+ Aeson.Match.QQ.Internal.Value: Bool :: Bool -> MatcherAST
- Aeson.Match.QQ.Internal.Value: Ext :: ext -> Matcher ext
+ Aeson.Match.QQ.Internal.Value: Ext :: Value -> MatcherAST
- Aeson.Match.QQ.Internal.Value: Null :: Matcher ext
+ Aeson.Match.QQ.Internal.Value: Null :: MatcherAST
- Aeson.Match.QQ.Internal.Value: Number :: Scientific -> Matcher ext
+ Aeson.Match.QQ.Internal.Value: Number :: Scientific -> MatcherAST
- Aeson.Match.QQ.Internal.Value: Object :: Object ext -> Matcher ext
+ Aeson.Match.QQ.Internal.Value: Object :: Object MatcherAST -> MatcherAST
- Aeson.Match.QQ.Internal.Value: Sig :: Type -> Bool -> Matcher ext -> Matcher ext
+ Aeson.Match.QQ.Internal.Value: Sig :: Type -> Bool -> MatcherAST -> MatcherAST
- Aeson.Match.QQ.Internal.Value: String :: Text -> Matcher ext
+ Aeson.Match.QQ.Internal.Value: String :: Text -> MatcherAST
- Aeson.Match.QQ.Internal.Value: StringCI :: CI Text -> Matcher ext
+ Aeson.Match.QQ.Internal.Value: StringCI :: CI Text -> MatcherAST
- Aeson.Match.QQ.Internal.Value: Var :: Text -> Matcher ext
+ Aeson.Match.QQ.Internal.Value: Var :: Text -> MatcherAST
- Aeson.Match.QQ.Internal.Value: embed :: Value -> Matcher ext
+ Aeson.Match.QQ.Internal.Value: embed :: Value -> MatcherAST
- Aeson.Match.QQ.Internal.Value: quote :: Matcher Exp -> Q Exp
+ Aeson.Match.QQ.Internal.Value: quote :: Parsed -> Q Exp
Files
- CHANGELOG.markdown +9/−0
- README.markdown +38/−17
- aeson-match-qq.cabal +14/−4
- src/Aeson/Match/QQ.hs +47/−16
- src/Aeson/Match/QQ/Internal/Box.hs +25/−0
- src/Aeson/Match/QQ/Internal/Captures.hs +43/−0
- src/Aeson/Match/QQ/Internal/Match.hs +18/−63
- src/Aeson/Match/QQ/Internal/Matcher.hs +94/−0
- src/Aeson/Match/QQ/Internal/Parse.hs +127/−50
- src/Aeson/Match/QQ/Internal/Parse/CollectNames.hs +54/−0
- src/Aeson/Match/QQ/Internal/PrettyPrint.hs +10/−14
- src/Aeson/Match/QQ/Internal/Type.hs +41/−0
- src/Aeson/Match/QQ/Internal/Value.hs +64/−170
- test/Aeson/Match/QQ/Internal/CapturesSpec.hs +41/−0
- test/Aeson/Match/QQ/Internal/ParseSpec.hs +92/−3
- test/Aeson/Match/QQ/Internal/PrettyPrintSpec.hs +2/−1
- test/Aeson/Match/QQSpec.hs +109/−84
- test/SpecHelper/NoCaptureQQ.hs +21/−0
CHANGELOG.markdown view
@@ -1,3 +1,12 @@+2.0.0+=====++ * Replaced dependency `haskell-src-meta` with `ghc-hs-meta` (https://github.com/supki/aeson-match-qq/pull/45)+ * Added string interpolation syntax (https://github.com/supki/aeson-match-qq/pull/48)+ * Changed how captures are returned. `match` now returns `Captures names` instead of a `HashMap`, where `names` is a sorted type-level list containing the names of the named holes in a matcher.+ * Provided `extractValue` and `extractDecoded` for capture lookup.+ * Required named holes to be unique throughout a matcher.+ 1.9.0 ====
README.markdown view
@@ -1,56 +1,77 @@ aeson-match-qq ============== -[](https://circleci.com/gh/supki/aeson-match-qq)- Declarative JSON matchers. Motivation ---------- -When testing an HTTP service that spouts JSON documents, it's often inconvenient to write out the whole response as-the expected value. Sometimes, you only care about a couple specific properties, or simply want to ensure that the-response has certain structure. This package provides a quasiquoter to define declarative matchers using a variation-of the familiar syntax.+When testing an HTTP service that spouts JSON documents, it's often inconvenient to write out the whole response as the expected value. Sometimes, you only care about a couple specific properties, or simply want to ensure that the response has certain structure. This package provides a quasiquoter to define declarative matchers using a variation of the familiar syntax. Features -------- ### Basic JSON construction -Since this package is heavily inspired by [aeson-qq][0], the parser tries to follow its behavior and has support for-optional quotes for simple keys and the `#{exp}` syntax for Haskell expression interpolation. It currently does not support-variable keys though and there are no plans to add them.+Since this package is heavily inspired by [aeson-qq][0], the parser tries to follow its behavior and has support for optional quotes for simple keys and the `#{exp}` syntax for Haskell expression interpolation. It currently does not support variable keys though and there are no plans to add them. ### Spread-like syntax for arrays and objects This syntax allows you to match only the part of the structure you care about: -`[match| [1, 2, 3, ...] |]` matches arrays starting with `[1, 2, 3]` -`[match| {foo: 1, bar: 2, ...} |]` matches objects that are supersets of `{foo: 1, bar: 2}`+`[qq| [1, 2, 3, ...] |]` matches arrays starting with `[1, 2, 3]`. +`[qq| {foo: 1, bar: 2, ...} |]` matches objects that are supersets of `{foo: 1, bar: 2}`+ ### Holes Holes are placeholders that match anything: -`[match| _ |]` matches any JSON document -`[match| {foo: _} |]` matches any object that has the `foo` property.+`[qq| _ |]` matches any JSON document. -If a hole is named, its value will be returned from `match`+`[qq| {foo: _} |]` matches any object that has the `foo` property. -`[match| {foo: {bar: _n} |]` will return `{n: 4}` if matched with `{foo: {bar: 4}}`+A matcher returns JSON values, referenced by named holes as `Captures names`, indexed by their names at the type level. Enable `-XTypeApplications` to look up captures by name with `extractValue` or `extractDecoded`: +```haskell+{-# LANGUAGE DataKinds #-}+{-# LANGUAGE QuasiQuotes #-}+{-# LANGUAGE TypeApplications #-}++import Aeson.Match.QQ+import qualified Data.Aeson as Aeson+import Data.List.NonEmpty (NonEmpty)++matcher :: Matcher '["age", "name"]+matcher =+ [qq|+ { name: _name : string+ , age: _age : number+ }+ |]++-- lookup up the raw Aeson.Value+extractName :: Aeson.Value -> Either (NonEmpty Error) Aeson.Value+extractName document = extractValue @"name" <$> match matcher document++-- lookup any type that implements `Aeson.FromJSON`+extractAge :: Captures '["age", "name"] -> Either String Int+extractAge = extractDecoded @"age"+```++In `Captures names`, the names appear in ascending order. Each named hole must be unique throughout a matcher; this is checked at compile time. Anonymous `_` holes may be repeated and are not captured.+ ### Case-insensitive strings A small addition to the JSON syntax that allows string matches that ignore case: -`[match| (ci) "foo" |]` matches any of `"Foo"`, `"fOO"`, or `"FOO"`.+`[qq| (ci) "foo" |]` matches any of `"Foo"`, `"fOO"`, or `"FOO"`. ### Unordered arrays A small addition to the JSON syntax that allows array matches that ignore the order of the elements, for example: -`[match| (unordered) [1,2,3] |]` matches `[3, 1, 2]`.+`[qq| (unordered) [1,2,3] |]` matches `[3, 1, 2]`. [0]: https://hackage.haskell.org/package/aeson-qq
aeson-match-qq.cabal view
@@ -1,11 +1,11 @@ cabal-version: 1.12 --- This file has been generated from package.yaml by hpack version 0.38.1.+-- This file has been generated from package.yaml by hpack version 0.39.1. -- -- see: https://github.com/sol/hpack name: aeson-match-qq-version: 1.9.0+version: 2.0.0 synopsis: Declarative JSON matchers. description: See README.markdown category: Web@@ -30,9 +30,14 @@ exposed-modules: Aeson.Match.QQ Aeson.Match.QQ.Internal.AesonUtils+ Aeson.Match.QQ.Internal.Box+ Aeson.Match.QQ.Internal.Captures Aeson.Match.QQ.Internal.Match+ Aeson.Match.QQ.Internal.Matcher Aeson.Match.QQ.Internal.Parse+ Aeson.Match.QQ.Internal.Parse.CollectNames Aeson.Match.QQ.Internal.PrettyPrint+ Aeson.Match.QQ.Internal.Type Aeson.Match.QQ.Internal.Value other-modules: Paths_aeson_match_qq@@ -50,7 +55,7 @@ , case-insensitive , containers , either- , haskell-src-meta+ , ghc-hs-meta , pretty , scientific , template-haskell@@ -63,9 +68,11 @@ type: exitcode-stdio-1.0 main-is: Spec.hs other-modules:+ Aeson.Match.QQ.Internal.CapturesSpec Aeson.Match.QQ.Internal.ParseSpec Aeson.Match.QQ.Internal.PrettyPrintSpec Aeson.Match.QQSpec+ SpecHelper.NoCaptureQQ Paths_aeson_match_qq hs-source-dirs: test@@ -77,8 +84,11 @@ build-depends: aeson , aeson-match-qq- , aeson-qq+ , aeson-value-qq , base >=4.14 && <5 , hspec+ , hspec-wai+ , template-haskell+ , text , unordered-containers default-language: Haskell2010
src/Aeson/Match/QQ.hs view
@@ -1,7 +1,16 @@+{-# LANGUAGE AllowAmbiguousTypes #-} {-# LANGUAGE DuplicateRecordFields #-}+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE TypeApplications #-} module Aeson.Match.QQ ( match , qq+ , Matcher+ , Captures(..)+ , HasCapture+ , extractValue+ , extractDecoded , Error(..) , TypeMismatch(..)@@ -11,7 +20,7 @@ , ExtraObjectValues(..) , prettyError - , Matcher(..)+ , MatcherAST(..) , Array , Object , Box(..)@@ -22,15 +31,21 @@ , parse ) where +import Control.Monad (filterM)+import Data.Aeson qualified as Aeson+import Data.Aeson.Types qualified as Aeson (parseEither)+import Data.List.NonEmpty (NonEmpty) import Data.String (IsString(..)) import Data.Text.Encoding qualified as Text import Language.Haskell.TH.Quote (QuasiQuoter(..))+import Language.Haskell.TH.Syntax (isExtEnabled) import Text.PrettyPrint qualified as PP (render) import Text.PrettyPrint.HughesPJClass qualified as PP (Pretty(..)) +import Aeson.Match.QQ.Internal.Box (Box(..), Array, Object)+import Aeson.Match.QQ.Internal.Captures (Captures(..), HasCapture, extractValue) import Aeson.Match.QQ.Internal.Match- ( match- , Error(..)+ ( Error(..) , TypeMismatch(..) , Mismatch(..) , MissingPathElem(..)@@ -40,25 +55,29 @@ , PathElem(..) ) import Aeson.Match.QQ.Internal.Parse (parse)-import Aeson.Match.QQ.Internal.Value- ( Matcher(..)- , Box(..)- , Array- , Object- , Type(..)- , quote- )+import Aeson.Match.QQ.Internal.Value (MatcherAST(..))+import Aeson.Match.QQ.Internal.Type (Type(..))+import Aeson.Match.QQ.Internal.Matcher (Matcher, quoteMatcher)+import Aeson.Match.QQ.Internal.Matcher qualified as Matcher --- | Construct a 'Matcher'.+-- | Match a JSON value, returning hole captures indexed by their names.+match+ :: Matcher names+ -> Aeson.Value+ -> Either (NonEmpty Error) (Captures names)+match = Matcher.match++-- | Construct a 'Matcher'. Requires @DataKinds@ and @QuasiQuotes@ at the use site. qq :: QuasiQuoter qq = QuasiQuoter- { quoteExp = \str ->- case parse (Text.encodeUtf8 (fromString str)) of+ { quoteExp = \str -> do+ exts <- reifyEnabledExtensions+ case parse exts (Text.encodeUtf8 (fromString str)) of Left err ->- error ("Aeson.Match.QQ.qq: " ++ err)+ fail ("Aeson.Match.QQ.qq: " ++ err) Right val ->- quote val+ quoteMatcher val , quotePat = \_ -> error "Aeson.Match.QQ.qq: no quotePat" , quoteType =@@ -66,6 +85,18 @@ , quoteDec = \_ -> error "Aeson.Match.QQ.qq: no quoteDec" }+ where+ reifyEnabledExtensions =+ filterM isExtEnabled [minBound .. maxBound]++-- | Look up a capture using visible type application: @extractDecoded \@"name" captures@.+extractDecoded+ :: forall name names r+ . (HasCapture name names, Aeson.FromJSON r)+ => Captures names+ -> Either String r+extractDecoded =+ Aeson.parseEither Aeson.parseJSON . extractValue @name -- | Pretty print an 'Error'. prettyError :: Error -> String
+ src/Aeson/Match/QQ/Internal/Box.hs view
@@ -0,0 +1,25 @@+{-# LANGUAGE DeriveFunctor #-}+{-# LANGUAGE StrictData #-}+module Aeson.Match.QQ.Internal.Box+ ( Box(..)+ , Array+ , Object+ ) where++import Data.HashMap.Strict (HashMap)+import Data.List.NonEmpty (NonEmpty)+import Data.Text (Text)+import Data.Vector (Vector)+++-- | A wrapper for matchers that support the `...` syntax.+data Box a = Box+ { values :: a+ , extra :: Bool+ -- ^ Are extra elements, not specifically mentioned by+ -- the matcher, allowed in the JSON value?+ } deriving (Show, Eq, Functor)++type Array a = Box (Vector a)++type Object a = Box (HashMap Text (NonEmpty a))
+ src/Aeson/Match/QQ/Internal/Captures.hs view
@@ -0,0 +1,43 @@+{-# LANGUAGE AllowAmbiguousTypes #-}+{-# LANGUAGE DataKinds #-}+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE GADTs #-}+{-# LANGUAGE KindSignatures #-}+{-# LANGUAGE MultiParamTypeClasses #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE StandaloneDeriving #-}+{-# LANGUAGE TypeApplications #-}+{-# LANGUAGE TypeOperators #-}+module Aeson.Match.QQ.Internal.Captures+ ( Captures(..)+ , HasCapture+ , extractValue+ ) where++import Data.Aeson qualified as Aeson+import GHC.TypeLits (Symbol, TypeError, ErrorMessage(..))+++-- | JSON values indexed by their hole names.+data Captures (names :: [Symbol]) where+ CEmpty :: Captures '[]+ CCons :: Aeson.Value -> Captures names -> Captures (name ': names)++deriving instance Eq (Captures names)+deriving instance Show (Captures names)+++-- | Look up a capture using visible type application: @extractValue \@"name" captures@.+class HasCapture (name :: Symbol) (names :: [Symbol]) where+ extractValue :: Captures names -> Aeson.Value++instance {-# OVERLAPPING #-} HasCapture name (name ': names) where+ extractValue (CCons value _) = value++instance HasCapture name names => HasCapture name (other ': names) where+ extractValue (CCons _ rest) = extractValue @name @names rest++instance TypeError ('Text "No capture named " ':<>: 'ShowType name)+ => HasCapture name '[] where+ extractValue _ =+ error "unreachable"
src/Aeson/Match/QQ/Internal/Match.hs view
@@ -8,7 +8,7 @@ {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE ViewPatterns #-} module Aeson.Match.QQ.Internal.Match- ( match+ ( matchAST , Error(..) , TypeMismatch(..) , Mismatch(..)@@ -55,23 +55,20 @@ import Text.PrettyPrint.HughesPJClass qualified as PP (Pretty(..)) import Aeson.Match.QQ.Internal.AesonUtils qualified as AesonUtils (pp)-import Aeson.Match.QQ.Internal.PrettyPrint qualified as Matcher (pp)-import Aeson.Match.QQ.Internal.Value- ( Matcher(..)- , Box(..)- , Type(..)- , embed- )+import Aeson.Match.QQ.Internal.Box (Box(..), Array)+import Aeson.Match.QQ.Internal.PrettyPrint qualified as MatcherAST (pp)+import Aeson.Match.QQ.Internal.Value (MatcherAST(..), embed)+import Aeson.Match.QQ.Internal.Type (Type(..)) --- | Test if a 'Matcher' matches a 'Aeson.Value'.-match- :: Matcher Aeson.Value+-- | Test if a 'MatcherAST' matches a 'Aeson.Value'.+matchAST+ :: MatcherAST -> Aeson.Value -> Either (NonEmpty Error) (HashMap Text Aeson.Value) -- ^ Either a non-empty list of errors, or a mapping -- from named _holes to their values.-match matcher0 given0 =+matchAST matcher0 given0 = validationToEither (go [] matcher0 given0) where go path matcher given = do@@ -180,7 +177,7 @@ matchArrayUO :: Validation (NonEmpty Error) (HashMap Text Aeson.Value) -> [PathElem]- -> Box (Vector (Matcher Aeson.Value))+ -> Array MatcherAST -> Vector Aeson.Value -> Validation (NonEmpty Error) (HashMap Text Aeson.Value) matchArrayUO mismatched path Box {values, extra} xs = do@@ -198,7 +195,7 @@ | length ivs < length values -> mismatched -- If there are some members of `xs` that aren't matched by- -- anything in `values`, we check if the 'Matcher' allows for+ -- anything in `values`, we check if the 'MatcherAST' allows for -- extra values. | length ivs < length xs && not extra -> do let is = Set.fromList (map fst ivs)@@ -211,7 +208,7 @@ imapMaybe matchingIndex is where matchingIndex i x =- case match knownValue x of+ case matchAST knownValue x of Left _ -> Nothing Right vs ->@@ -237,7 +234,7 @@ mismatch :: [PathElem]- -> Matcher Aeson.Value+ -> MatcherAST -> Aeson.Value -> Validation (NonEmpty Error) a mismatch (Path . reverse -> path) matcher given =@@ -246,7 +243,7 @@ mistype :: [PathElem] -> Type- -> Matcher Aeson.Value+ -> MatcherAST -> Aeson.Value -> Validation (NonEmpty Error) a mistype (Path . reverse -> path) expected matcher given =@@ -319,55 +316,21 @@ , PP.pPrint err ] -instance Aeson.ToJSON Error where- toJSON =- Aeson.object . \case- Mismatch v ->- [ "type" .= ("mismatch" :: Text)- , "value" .= v- ]- Mistype v ->- [ "type" .= ("mistype" :: Text)- , "value" .= v- ]- MissingPathElem v ->- [ "type" .= ("missing-path-elem" :: Text)- , "value" .= v- ]- ExtraArrayValues v ->- [ "type" .= ("extra-array-values" :: Text)- , "value" .= v- ]- ExtraObjectValues v ->- [ "type" .= ("extra-object-values" :: Text)- , "value" .= v- ]- -- | This error type covers the case where the type of the value does not match. data TypeMismatch = MkTypeMismatch { path :: Path , expected :: Type- , matcher :: Matcher Aeson.Value+ , matcher :: MatcherAST , given :: Aeson.Value } deriving (Show, Eq) -instance Aeson.ToJSON TypeMismatch where- toJSON MkTypeMismatch {..} =- Aeson.object- [ "path" .= path- , "expected" .= expected- , "actual" .= typeJOf given- , "matcher" .= matcher- , "given" .= given- ]- instance PP.Pretty TypeMismatch where pPrint MkTypeMismatch {..} = PP.vcat [ PP.hsep ["expected:", PP.pPrint expected] , PP.hsep [" actual:", PP.pPrint (typeJOf given)] , PP.hsep [" path:", PP.pPrint path]- , PP.hsep [" matcher:", Matcher.pp matcher]+ , PP.hsep [" matcher:", MatcherAST.pp matcher] , PP.hsep [" given:", AesonUtils.pp given] ] @@ -412,23 +375,15 @@ -- | This error type covers the case where the type matches but the value does not. data Mismatch = MkMismatch { path :: Path- , matcher :: Matcher Aeson.Value+ , matcher :: MatcherAST , given :: Aeson.Value } deriving (Show, Eq) -instance Aeson.ToJSON Mismatch where- toJSON MkMismatch {..} =- Aeson.object- [ "path" .= path- , "matcher" .= matcher- , "given" .= given- ]- instance PP.Pretty Mismatch where pPrint MkMismatch {..} = PP.vcat [ PP.hsep [" path:", PP.pPrint path]- , PP.hsep ["matcher:", Matcher.pp matcher]+ , PP.hsep ["matcher:", MatcherAST.pp matcher] , PP.hsep [" given:", AesonUtils.pp given] ]
+ src/Aeson/Match/QQ/Internal/Matcher.hs view
@@ -0,0 +1,94 @@+{-# LANGUAGE DataKinds #-}+{-# LANGUAGE KindSignatures #-}+{-# LANGUAGE TemplateHaskell #-}+module Aeson.Match.QQ.Internal.Matcher+ ( Matcher+ , match+ , quoteMatcher+ ) where++import Data.Aeson qualified as Aeson+import Data.HashMap.Strict (HashMap)+import Data.HashMap.Strict qualified as HashMap+import Data.List.NonEmpty (NonEmpty)+import Data.Text (Text)+import Data.Text qualified as Text+import GHC.TypeLits (Symbol)+import Language.Haskell.TH (Q, Exp(..), Pat(..), Type(..), TyLit(..), newName)+import Prelude hiding (exp)++import Aeson.Match.QQ.Internal.Captures (Captures(..))+import Aeson.Match.QQ.Internal.Match (Error, matchAST)+import Aeson.Match.QQ.Internal.Parse (Parsed)+import Aeson.Match.QQ.Internal.Parse.CollectNames qualified as CollectNames+ ( CollectNamesError(..)+ , collectNames+ )+import Aeson.Match.QQ.Internal.Value (MatcherAST, quote)+++-- | A matcher whose type records its named holes in ascending order.+data Matcher (names :: [Symbol]) = Matcher+ MatcherAST+ (HashMap Text Aeson.Value -> Captures names)++-- | Match a JSON value and return its named captures.+match+ :: Matcher names+ -> Aeson.Value+ -> Either (NonEmpty Error) (Captures names)+match (Matcher matcher build) given =+ fmap build (matchAST matcher given)++-- | Build a Matcher expression, along with its signature, from the parsed input.+quoteMatcher :: Parsed -> Q Exp+quoteMatcher parsed = do+ names <- collectNames parsed+ let+ captureExp =+ buildCaptureExp names+ exp <- [| Matcher $(quote parsed) $captureExp |]+ let+ nameListT =+ promoteNames names+ t =+ AppT (ConT ''Matcher) nameListT+ pure (SigE exp t)++collectNames :: Parsed -> Q [Text]+collectNames parsed =+ case CollectNames.collectNames parsed of+ Left (CollectNames.DuplicateHoleName name) -> fail ("Duplicate hole name: " ++ show name)+ Right names -> pure names++-- ["a", "b", "c"] -->+-- '["a", "b", "c"]+promoteNames :: [Text] -> Type+promoteNames names =+ foldr+ (\name rest -> AppT (AppT PromotedConsT (LitT (StrTyLit (Text.unpack name)))) rest)+ PromotedNilT+ names++-- ["a", "b", "c"] --->+-- \values -> CCons (lookup "a" values) : CCons (lookup "b" values) : CCons (lookup "c" values) : CEmpty+buildCaptureExp :: [Text] -> Q Exp+buildCaptureExp names = do+ values <- newName "values"+ let+ captures [] =+ [| CEmpty |]+ captures (name : rest) =+ [| CCons (captureValue name $(pure (VarE values))) $(captures rest) |]+ binder =+ case names of+ [] -> [| \_ -> CEmpty |]+ _ -> fmap (LamE [VarP values]) (captures names)+ binder++captureValue :: Text -> HashMap Text Aeson.Value -> Aeson.Value+captureValue name values =+ HashMap.findWithDefault err name values+ where+ err =+ error ("Aeson.Match.QQ.Internal.Matcher: missing capture " ++ show name)
src/Aeson/Match/QQ/Internal/Parse.hs view
@@ -1,10 +1,14 @@ {-# LANGUAGE BangPatterns #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE PackageImports #-} {-# LANGUAGE PatternSynonyms #-} {-# LANGUAGE ViewPatterns #-} module Aeson.Match.QQ.Internal.Parse- ( parse+ ( Parsed(..)+ , CI(..)+ , StringFrag(..)+ , parse ) where import Control.Applicative ((<|>), optional)@@ -13,36 +17,59 @@ import Data.ByteString qualified as ByteString -- cannot use .Text here due to .Aeson parsers being tied to .ByteString import Data.ByteString (ByteString)-import Data.CaseInsensitive qualified as CI import Data.Char qualified as Char import Data.Foldable (asum)+import Data.List.NonEmpty (NonEmpty(..), nonEmpty) import Data.HashMap.Strict qualified as HashMap-import Data.Maybe (isJust)+import Data.Maybe (isJust, fromMaybe)+import Data.Scientific (Scientific) import Data.Text (Text) import Data.Text qualified as Text import Data.Text.Encoding qualified as Text import Data.Vector qualified as Vector import Data.Word (Word8)-import Language.Haskell.Meta.Parse (parseExp)+import "ghc-hs-meta" Language.Haskell.Meta.Parse (parseExpWithExts) import Language.Haskell.TH (Exp(..))-import Prelude hiding (any, null)+import Language.Haskell.TH.Syntax qualified as Haskell (Extension)+import Prelude hiding (any, exp, null)+import Text.Printf (printf) -import Aeson.Match.QQ.Internal.Value- ( Matcher(..)- , Box(..)- , Type(..)- )+import Aeson.Match.QQ.Internal.Box (Box(..), Array, Object)+import Aeson.Match.QQ.Internal.Type (Type(..)) --- | An 'attoparsec' parser for a 'Matcher'.+data Parsed+ = Null+ | Bool Bool+ | Number Scientific+ | String CI (NonEmpty StringFrag)+ | Array (Array Parsed)+ | ArrayUO (Array Parsed)+ | Object (Object Parsed)+ | Var Text+ | Sig Type Bool Parsed+ | Ext Exp+ deriving (Show, Eq)++data CI+ = CS -- ^ case-sensitive+ | CI -- ^ case-insensitive+ deriving (Show, Eq)++data StringFrag+ = Raw Text+ | Interpolate Exp+ deriving (Show, Eq)++-- | An 'attoparsec' parser for a matcher. -- -- /Note:/ consumes spaces before and after the matcher.-parse :: ByteString -> Either String (Matcher Exp)-parse =- Atto.parseOnly (value <* eof)+parse :: [Haskell.Extension] -> ByteString -> Either String Parsed+parse exts =+ Atto.parseOnly (value exts <* eof) -value :: Atto.Parser (Matcher Exp)-value = do+value :: [Haskell.Extension] -> Atto.Parser Parsed+value exts = do val <- between spaces spaces $ do b <- Atto.peekWord8' case b of@@ -55,15 +82,15 @@ TP -> true DoubleQuoteP ->- string+ string exts OpenSquareBracketP ->- array+ array exts OpenParenP ->- arrayUO <|> stringCI+ arrayUO exts <|> stringCI exts OpenCurlyBracketP ->- object+ object exts HashP ->- haskellExp+ haskellExp exts _ | startOfNumber b -> number | otherwise ->@@ -75,7 +102,7 @@ between a b p = a *> p <* b -optimize :: Matcher Exp -> Matcher Exp+optimize :: Parsed -> Parsed optimize = \case -- [...] -> _ : array Array Box {extra = True, values = (Vector.null -> True)} ->@@ -91,7 +118,7 @@ val -> val -any :: Atto.Parser (Matcher Exp)+any :: Atto.Parser Parsed any = do _ <- Atto.word8 HoleP name <- key <|> pure ""@@ -104,34 +131,75 @@ pure (AnyT, False) pure (Sig type_ nullable (Var name)) -null :: Atto.Parser (Matcher Exp)+null :: Atto.Parser Parsed null = Null <$ Atto.string "null" -false :: Atto.Parser (Matcher Exp)+false :: Atto.Parser Parsed false = Bool False <$ Atto.string "false" -true :: Atto.Parser (Matcher Exp)+true :: Atto.Parser Parsed true = Bool True <$ Atto.string "true" -number :: Atto.Parser (Matcher Exp)+number :: Atto.Parser Parsed number = fmap Number Aeson.scientific -string :: Atto.Parser (Matcher Exp)-string =- fmap String Aeson.jstring+string :: [Haskell.Extension] -> Atto.Parser Parsed+string exts = do+ str <- Aeson.jstring+ either fail (pure . String CS) (fragments exts str) -stringCI :: Atto.Parser (Matcher Exp)-stringCI = do+stringCI :: [Haskell.Extension] -> Atto.Parser Parsed+stringCI exts = do _ <- Atto.string "(ci)" spaces- fmap (StringCI . CI.mk) Aeson.jstring+ str <- Aeson.jstring+ either fail (pure . String CI) (fragments exts str) -array :: Atto.Parser (Matcher Exp)-array = do+fragments :: [Haskell.Extension] -> Text -> Either String (NonEmpty StringFrag)+fragments exts str = do+ frags <- Atto.parseOnly (interpolatedP exts <* eof) (Text.encodeUtf8 str)+ pure (fromMaybe (pure (Raw "")) (nonEmpty frags))++interpolatedP :: [Haskell.Extension] -> Atto.Parser [StringFrag]+interpolatedP exts =+ go []+ where+ go acc = do+ b0 <- Atto.peekWord8+ case b0 of+ Just BackSlashP -> do+ _ <- Atto.anyWord8+ b1 <- Atto.peekWord8+ case b1 of+ Just HashP -> do+ _ <- Atto.anyWord8+ go (Raw "#" : acc)+ _ ->+ go (Raw "\\" : acc)+ Just HashP -> do+ _ <- Atto.anyWord8+ b1 <- Atto.peekWord8+ case b1 of+ Just OpenCurlyBracketP -> do+ _ <- Atto.anyWord8+ str <- Atto.takeWhile (/= CloseCurlyBracketP)+ _ <- Atto.word8 CloseCurlyBracketP+ exp <- parseExp exts (Text.decodeUtf8 str)+ go (Interpolate exp : acc)+ _ ->+ go (Raw "#" : acc)+ Just _ -> do+ frag <- fmap (Raw . Text.decodeUtf8) (Atto.takeWhile1 (\b -> b /= HashP && b /= BackSlashP))+ go (frag : acc)+ Nothing ->+ pure (reverse acc)++array :: [Haskell.Extension] -> Atto.Parser Parsed+array exts = do _ <- Atto.word8 OpenSquareBracketP spaces b <- Atto.peekWord8'@@ -155,7 +223,7 @@ , extra = True } _ -> do- val <- value+ val <- value exts sep <- Atto.satisfy (\w -> w == CommaP || w == CloseSquareBracketP) Atto.<?> "',' or ']'" case sep of CommaP ->@@ -168,15 +236,15 @@ _ -> error "impossible" -arrayUO :: Atto.Parser (Matcher Exp)-arrayUO = do+arrayUO :: [Haskell.Extension] -> Atto.Parser Parsed+arrayUO exts = do _ <- Atto.string "(unordered)" spaces- Array box <- array+ Array box <- array exts pure (ArrayUO box) -object :: Atto.Parser (Matcher Exp)-object = do+object :: [Haskell.Extension] -> Atto.Parser Parsed+object exts = do _ <- Atto.word8 OpenCurlyBracketP spaces b <- Atto.peekWord8'@@ -196,14 +264,14 @@ spaces _ <- Atto.word8 CloseCurlyBracketP pure $ Object Box- { values = HashMap.fromList acc+ { values = HashMap.fromListWith (<>) acc , extra = True } _ -> do k <- key spaces _ <- Atto.word8 ColonP- val <- value+ val <- value exts sep <- Atto.satisfy (\w -> w == CommaP || w == CloseCurlyBracketP) Atto.<?> "',' or '}'" case sep of CommaP ->@@ -235,14 +303,22 @@ rest = () <$ Atto.string "..." -haskellExp :: Atto.Parser (Matcher Exp)-haskellExp =- fmap Ext (Atto.string "#{" *> go)+haskellExp :: [Haskell.Extension] -> Atto.Parser Parsed+haskellExp exts =+ fmap Ext (Atto.string "#{" *> p) where- go = do+ p = do str <- Atto.takeWhile1 (/= CloseCurlyBracketP) <* Atto.word8 CloseCurlyBracketP- either fail pure (parseExp (Text.unpack (Text.decodeUtf8 str)))+ parseExp exts (Text.decodeUtf8 str) +parseExp :: [Haskell.Extension] -> Text -> Atto.Parser Exp+parseExp exts str =+ case parseExpWithExts exts (Text.unpack str) of+ Left (line, col, err) ->+ fail (printf "%d:%d: %s" line col err)+ Right exp ->+ pure exp+ sig :: Atto.Parser (Type, Bool) sig = do _ <- Atto.word8 ColonP@@ -307,8 +383,6 @@ pattern OpenParenP :: Word8 pattern OpenParenP = 40 -- '('--- pattern CloseParenP :: Word8--- pattern CloseParenP = 41 -- ')' pattern OpenCurlyBracketP, CloseCurlyBracketP, ColonP :: Word8 pattern OpenCurlyBracketP = 123 -- '{'@@ -326,6 +400,9 @@ pattern NewLineP = 0x0a pattern CRP = 0x0d pattern TabP = 0x09++pattern BackSlashP :: Word8+pattern BackSlashP = 92 -- '\' pattern QuestionMarkP :: Word8 pattern QuestionMarkP = 63 -- '?'
+ src/Aeson/Match/QQ/Internal/Parse/CollectNames.hs view
@@ -0,0 +1,54 @@+{-# LANGUAGE BangPatterns #-}+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE PackageImports #-}+{-# LANGUAGE PatternSynonyms #-}+{-# LANGUAGE ViewPatterns #-}+module Aeson.Match.QQ.Internal.Parse.CollectNames+ ( CollectNamesError(..)+ , collectNames+ ) where++import Control.Monad (foldM)+import Data.List qualified as List+import Data.HashMap.Strict qualified as HashMap+import Data.Set qualified as Set+import Data.Text (Text)+import Data.Text qualified as Text+import Prelude hiding (any, exp, null)++import Aeson.Match.QQ.Internal.Box (Box(..))+import Aeson.Match.QQ.Internal.Parse (Parsed(..))+++data CollectNamesError+ = DuplicateHoleName Text+ deriving (Show, Eq)++-- | Collect named holes in ascending order, rejecting duplicate names anywhere in the tree.+collectNames :: Parsed -> Either CollectNamesError [Text]+collectNames =+ fmap Set.toAscList . go Set.empty+ where+ go seen = \case+ Var name+ | Text.null name ->+ Right seen+ | name `Set.member` seen ->+ Left (DuplicateHoleName name)+ | otherwise ->+ Right (Set.insert name seen)+ Sig _ _ val ->+ go seen val+ Array box ->+ foldM go seen (values box)+ ArrayUO box ->+ foldM go seen (values box)+ Object box ->+ -- sort keys so the first reported duplicate is deterministic too+ foldM (foldM go) seen (map snd (List.sortOn fst (HashMap.toList (values box))))+ Null -> Right seen+ Bool _ -> Right seen+ Number _ -> Right seen+ String _ _ -> Right seen+ Ext _ -> Right seen
src/Aeson/Match/QQ/Internal/PrettyPrint.hs view
@@ -18,24 +18,20 @@ import Data.HashMap.Strict qualified as HashMap import Data.Int (Int64) import Data.List qualified as List-import Data.List.NonEmpty (NonEmpty) import Data.Scientific (Scientific, floatingOrInteger) import Data.String (fromString) import Data.Text qualified as Text import Data.Text.Encoding qualified as Text import Data.Text (Text)-import Data.Vector (Vector) import Text.PrettyPrint ((<+>)) import Text.PrettyPrint qualified as PP -import Aeson.Match.QQ.Internal.Value- ( Matcher(..)- , Type(..)- , Box(..)- )+import Aeson.Match.QQ.Internal.Value (MatcherAST(..))+import Aeson.Match.QQ.Internal.Box (Box(..), Array, Object)+import Aeson.Match.QQ.Internal.Type (Type(..)) -pp :: Matcher Aeson.Value -> PP.Doc+pp :: MatcherAST -> PP.Doc pp value = PP.vcat [ "[qq|"@@ -43,7 +39,7 @@ , "|]" ] -rValue :: Matcher Aeson.Value -> PP.Doc+rValue :: MatcherAST -> PP.Doc rValue = \case Null -> rNull@@ -91,7 +87,7 @@ , rString (CI.original str) ] -rArray :: Box (Vector (Matcher Aeson.Value)) -> PP.Doc+rArray :: Array MatcherAST -> PP.Doc rArray Box {values, extra} = case toList values of [] ->@@ -102,14 +98,14 @@ map (\x' -> "," <+> rValue x') xs <> [bool PP.empty ", ..." extra, "]"] -rArrayUO :: Box (Vector (Matcher Aeson.Value)) -> PP.Doc+rArrayUO :: Array MatcherAST -> PP.Doc rArrayUO box = PP.vcat [ "(unordered)" , rArray box ] -rObject :: Box (HashMap Text (NonEmpty (Matcher Aeson.Value))) -> PP.Doc+rObject :: Object MatcherAST -> PP.Doc rObject Box {values, extra} = case toKeyValues values of [] ->@@ -133,7 +129,7 @@ toKeyValues = traverse toList <=< List.sortOn fst . HashMap.toList -rSig :: Type -> Bool -> Matcher Aeson.Value -> PP.Doc+rSig :: Type -> Bool -> MatcherAST -> PP.Doc rSig type_ nullable val = rValue val <+> ((":" <+> rType type_) <> bool PP.empty "?" nullable) where@@ -162,7 +158,7 @@ rExt = fromString . Text.unpack . Text.decodeUtf8 . ByteString.Lazy.toStrict . Aeson.encode -simpleValue :: Matcher Aeson.Value -> Bool+simpleValue :: MatcherAST -> Bool simpleValue = \case Null {} -> True
+ src/Aeson/Match/QQ/Internal/Type.hs view
@@ -0,0 +1,41 @@+{-# LANGUAGE DeriveLift #-}+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE OverloadedStrings #-}+module Aeson.Match.QQ.Internal.Type+ ( Type(..)+ ) where++import Language.Haskell.TH.Syntax (Lift(..))+import Text.PrettyPrint.HughesPJClass qualified as PP (Pretty(..))+++-- | _hole type+data Type+ = AnyT+ -- ^ @_ : any@ or, equivalently, @_@+ | BoolT+ -- ^ @_ : bool@+ | NumberT+ -- ^ @_ : number@+ | StringT+ -- ^ @_ : string@+ | StringCIT+ -- ^ @_ : ci-string@+ | ArrayT+ -- ^ @_ : array@+ | ArrayUOT+ -- ^ @_ : unordered-array@+ | ObjectT+ -- ^ @_ : object@+ deriving (Show, Eq, Lift)++instance PP.Pretty Type where+ pPrint = \case+ AnyT {} -> "any"+ BoolT {} -> "bool"+ NumberT {} -> "number"+ StringT {} -> "string"+ StringCIT {} -> "ci-string"+ ArrayT {} -> "array"+ ArrayUOT {} -> "unordered-array"+ ObjectT {} -> "object"
src/Aeson/Match/QQ/Internal/Value.hs view
@@ -6,227 +6,121 @@ {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE StrictData #-} {-# LANGUAGE TemplateHaskell #-}-{-# LANGUAGE TypeFamilies #-} module Aeson.Match.QQ.Internal.Value- ( Matcher(..)- , Box(..)- , Array- , Object- , Type(..)+ ( MatcherAST(..) , embed , quote ) where -import Data.Aeson ((.=)) import Data.Aeson qualified as Aeson import Data.Aeson.KeyMap qualified as Aeson (toHashMapText) import Data.CaseInsensitive (CI) import Data.CaseInsensitive qualified as CI-import Data.HashMap.Strict (HashMap)+import Data.Foldable (toList) import Data.HashMap.Strict qualified as HashMap import Data.List.NonEmpty (NonEmpty(..)) import Data.Scientific (Scientific) import Data.Text (Text) import Data.Text qualified as Text-import Data.Vector (Vector) import Data.Vector qualified as Vector import Language.Haskell.TH (Q, Exp(..), Lit(..))-import Language.Haskell.TH.Syntax (Lift(..))-import Prelude hiding (any, null)-import Text.PrettyPrint.HughesPJClass qualified as PP (Pretty(..))+import Prelude hiding (any, exp, null) import Aeson.Match.QQ.Internal.AesonUtils (toJSONE)+import Aeson.Match.QQ.Internal.Box (Box(..), Array, Object)+import Aeson.Match.QQ.Internal.Parse (Parsed)+import Aeson.Match.QQ.Internal.Parse qualified as Parsed+ ( Parsed(..)+ , CI(..)+ , StringFrag(..)+ )+import Aeson.Match.QQ.Internal.Type (Type) --- | A value constructed using 'qq' that attempts to match--- a JSON document.-data Matcher ext+-- | The matcher AST used by the matching engine and error reports.+data MatcherAST = Null | Bool Bool | Number Scientific | String Text | StringCI (CI Text) -- ^ Case-insensitive strings- | Array (Array ext)- | ArrayUO (Array ext)+ | Array (Array MatcherAST)+ | ArrayUO (Array MatcherAST) -- ^ Unordered arrays- | Object (Object ext)+ | Object (Object MatcherAST) | Var Text- -- ^ Unless the name of the variable is '_', then- -- the value is returned to the user in a 'HashMap'.- | Sig Type Bool (Matcher ext)- | Ext ext- -- ^ External values spliced into a 'Matcher' using the `#{}` syntax- deriving (Show, Eq, Functor)--type Array ext = Box (Vector (Matcher ext))--type Object ext = Box (HashMap Text (NonEmpty (Matcher ext)))--instance Aeson.ToJSON ext => Aeson.ToJSON (Matcher ext) where- toJSON =- Aeson.object . \case- Null ->- [ "type" .= ("null" :: Text)- ]- Bool v ->- [ "type" .= ("bool" :: Text)- , "value" .= v- ]- Number v ->- [ "type" .= ("number" :: Text)- , "value" .= v- ]- String v ->- [ "type" .= ("string" :: Text)- , "value" .= v- ]- StringCI v ->- [ "type" .= ("string-ci" :: Text)- , "value" .= CI.original v- ]- Array v ->- [ "type" .= ("array" :: Text)- , "value" .= v- ]- ArrayUO v ->- [ "type" .= ("array-unordered" :: Text)- , "value" .= v- ]- Object v ->- [ "type" .= ("object" :: Text)- , "value" .= v- ]- Var name ->- [ "type" .= ("var" :: Text)- , "name" .= name- ]- Sig type_ nullable v ->- [ "type" .= ("sig" :: Text)- , "expected-type" .= type_- , "nullable" .= nullable- , "value" .= v- ]- Ext v ->- [ "type" .= ("extension" :: Text)- , "value" .= v- ]---- | A wrapper for those matchers that support the `...` syntax.-data Box a = Box- { values :: a- , extra :: Bool- -- ^ Are extra, not specifically mentioned by a 'Matcher', values- -- allowed in a 'Value'?- } deriving (Show, Eq, Functor)--instance Aeson.ToJSON a => Aeson.ToJSON (Box a) where- toJSON Box {..} =- Aeson.object- [ "values" .= values- , "extra" .= extra- ]+ -- ^ A hole. The empty name is anonymous; named holes contribute captures.+ | Sig Type Bool MatcherAST+ | Ext Aeson.Value+ -- ^ External values spliced into a 'MatcherAST' using the `#{}` syntax+ deriving (Show, Eq) --- | It may be tempting to make this the 'Lift' instance for 'Matcher', but I don't+-- | It may be tempting to make this the 'Lift' instance for 'MatcherAST', but I don't -- think it would be correct. We can get a lot from re-using 'Lift' machinery: namely, -- we can cpmpletely bypass manual 'Exp' construction. But, fundamentally, 'Lift' is -- for "serializing" Haskell values and it is not what we are attempting here.-quote :: Matcher Exp -> Q Exp+quote :: Parsed -> Q Exp quote = \case- Null ->- [| Null :: Matcher Aeson.Value |]- Bool b ->- [| Bool b :: Matcher Aeson.Value |]- Number n ->- [| Number n :: Matcher Aeson.Value |]- String str ->- [| String str :: Matcher Aeson.Value |]- StringCI ci -> let- original = CI.original ci- in- [| StringCI (CI.mk original) :: Matcher Aeson.Value |]- Array Box {values, extra} -> do+ Parsed.Null ->+ [| Null |]++ Parsed.Bool b ->+ [| Bool b |]++ Parsed.Number n ->+ [| Number n |]++ Parsed.String ci str -> do let+ fromFrag = \case+ Parsed.Raw lit ->+ [| lit |]+ Parsed.Interpolate exp ->+ [| $(pure exp) |]+ exps =+ fmap ListE (traverse fromFrag (toList str)) :: Q Exp+ case ci of+ Parsed.CS ->+ [| String (mconcat $exps) |]+ Parsed.CI ->+ [| StringCI (CI.mk (mconcat $exps)) |]++ Parsed.Array Box {values, extra} -> do+ let quoted = fmap ListE (traverse quote (Vector.toList values))- [| Array Box- { values = Vector.fromList $quoted- , extra- } :: Matcher Aeson.Value |]- ArrayUO Box {values, extra} -> do+ [| Array Box {values = Vector.fromList $quoted, extra} |]++ Parsed.ArrayUO Box {values, extra} -> do let quoted = fmap ListE (traverse quote (Vector.toList values))- [| ArrayUO Box- { values = Vector.fromList $quoted- , extra- } :: Matcher Aeson.Value |]- Object Box {values, extra} -> do+ [| ArrayUO Box {values = Vector.fromList $quoted, extra} |]++ Parsed.Object Box {values, extra} -> do let quoted =- fmap toExp (traverse (traverse (traverse quote)) (HashMap.toList values))+ fmap (toExp . HashMap.toList) ((traverse . traverse) quote values) toExp = ListE . map (\(k, v) -> tup2 (LitE (StringL (Text.unpack k)), nonEmptyE v)) tup2 (a, b) = TupE [Just a, Just b] nonEmptyE (e :| es) = AppE (AppE (ConE '(:|)) e) (ListE es)- [| Object Box- { values = HashMap.fromList $quoted- , extra- } :: Matcher Aeson.Value |]- Sig type_ nullable val ->- [| Sig type_ nullable $(quote val) :: Matcher Aeson.Value |]- Var name ->- [| Var name :: Matcher Aeson.Value |]- -- | This is fundamentally type-unsafe as long as we try to splice `Exp` in.- Ext ext ->- [| Ext (toJSONE $(pure ext)) :: Matcher Aeson.Value |]+ [| Object Box {values = HashMap.fromList $quoted, extra} |] --- | _hole type-data Type- = AnyT- -- ^ @_ : any@ or, equivalently, @_@- | BoolT- -- ^ @_ : bool@- | NumberT- -- ^ @_ : number@- | StringT- -- ^ @_ : string@- | StringCIT- -- ^ @_ : ci-string@- | ArrayT- -- ^ @_ : array@- | ArrayUOT- -- ^ @_ : unordered-array@- | ObjectT- -- ^ @_ : object@- deriving (Show, Eq, Lift)+ Parsed.Sig type_ nullable val ->+ [| Sig type_ nullable $(quote val) |] -instance Aeson.ToJSON Type where- toJSON =- Aeson.toJSON . \case- AnyT {} -> "any" :: Text- BoolT {} -> "bool"- NumberT {} -> "number"- StringT {} -> "string"- StringCIT {} -> "ci-string"- ArrayT {} -> "array"- ArrayUOT {} -> "unordered-array"- ObjectT {} -> "object"+ Parsed.Var name ->+ [| Var name |] -instance PP.Pretty Type where- pPrint = \case- AnyT {} -> "any"- BoolT {} -> "bool"- NumberT {} -> "number"- StringT {} -> "string"- StringCIT {} -> "ci-string"- ArrayT {} -> "array"- ArrayUOT {} -> "unordered-array"- ObjectT {} -> "object"+ -- | This is fundamentally type-unsafe as long as we try to splice `Exp` in.+ Parsed.Ext exp ->+ [| Ext (toJSONE $(pure exp)) |] -embed :: Aeson.Value -> Matcher ext+embed :: Aeson.Value -> MatcherAST embed = \case Aeson.Null -> Null
+ test/Aeson/Match/QQ/Internal/CapturesSpec.hs view
@@ -0,0 +1,41 @@+{-# LANGUAGE DataKinds #-}+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE TypeApplications #-}+module Aeson.Match.QQ.Internal.CapturesSpec (spec) where++import Data.Aeson qualified as Aeson+import Test.Hspec++import Aeson.Match.QQ.Internal.Captures+++spec :: Spec+spec = do+ describe "get" $ do+ let captures :: Captures '["name", "age", "active"]+ captures =+ CCons (Aeson.String "Ada")+ (CCons (Aeson.Number 37) (CCons (Aeson.Bool True) CEmpty))++ it "looks up the first capture" $+ extractValue @"name" captures `shouldBe` Aeson.String "Ada"++ it "looks up an interior capture" $+ extractValue @"age" captures `shouldBe` Aeson.Number 37++ it "looks up the last capture" $+ extractValue @"active" captures `shouldBe` Aeson.Bool True++ it "works through a polymorphic HasCapture constraint" $+ extractValue @"name" captures `shouldBe` Aeson.String "Ada"++ it "returns the first value for a repeated name" $ do+ let repeated :: Captures '["name", "name"]+ repeated = CCons Aeson.Null (CCons (Aeson.String "Ada") CEmpty)+ extractValue @"name" repeated `shouldBe` Aeson.Null++ it "supports names that are not Haskell identifiers" $ do+ let captures' :: Captures '["a fancy-name"]+ captures' = CCons Aeson.Null CEmpty+ extractValue @"a fancy-name" captures' `shouldBe` Aeson.Null
test/Aeson/Match/QQ/Internal/ParseSpec.hs view
@@ -1,6 +1,7 @@ {-# LANGUAGE DuplicateRecordFields #-} {-# LANGUAGE GeneralisedNewtypeDeriving #-} {-# LANGUAGE OverloadedLists #-}+{-# LANGUAGE OverloadedRecordDot #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} module Aeson.Match.QQ.Internal.ParseSpec (spec) where@@ -8,11 +9,81 @@ import Data.Aeson qualified as Aeson import Test.Hspec -import Aeson.Match.QQ+import Aeson.Match.QQ hiding (qq)+import Aeson.Match.QQ.Internal.Parse.CollectNames+ ( CollectNamesError(..)+ , collectNames+ ) +import SpecHelper.NoCaptureQQ (qq) + spec :: Spec spec = do+ describe "collectNames" $ do+ let+ collect input = do+ let+ Right parsed =+ parse [] input+ collectNames parsed++ it "a top-level hole" $+ collect "_name" `shouldBe` Right ["name"]++ it "nested arrays, objects, and signatures" $+ collect "{z: [_z : string?, {a: _a}], b: (unordered) [_b : number, ...]}"+ `shouldBe` Right ["a", "b", "z"]++ it "repeated object keys" $ do+ collect "{a: _first, a: _second}" `shouldBe` Right ["first", "second"]+ collect "{a: _first, a: _second, ...}" `shouldBe` Right ["first", "second"]++ it "quoted names and treats names as case-sensitive" $+ collect "_\"a fancy-name\""+ `shouldBe` Right ["a fancy-name"]++ it "case-sensitive" $+ collect "[_Name, _name]"+ `shouldBe` Right ["Name", "name"]++ it "empty and spread-only containers" $+ collect "[[], {}, (unordered) [], [...], {...}, (unordered) [...]]"+ `shouldBe` Right []++ it "ignores anonymous holes" $+ collect "[_, _ : string?, {a: _, b: (unordered) [_, ...]}, ...]"+ `shouldBe` Right []++ it "ignores literals, interpolation, and object keys" $+ collect "{_key: [null, true, 1, \"_name\", (ci) \"_name\", #{value}, \"#{value}\"]}"+ `shouldBe` Right []++ context "duplicates" $ do+ it "in arrays" $+ collect "[_name, _name]" `shouldBe`+ Left (DuplicateHoleName "name")++ it "in unordered arrays" $+ collect "(unordered) [_name, _name]" `shouldBe`+ Left (DuplicateHoleName "name")++ it "across object keys" $+ collect "{a: _name, b: _name}" `shouldBe`+ Left (DuplicateHoleName "name")++ it "under the same object key" $+ collect "{a: _name, a: _name}" `shouldBe`+ Left (DuplicateHoleName "name")++ it "under the same key with a spread" $+ collect "{a: _name, a: _name, ...}" `shouldBe`+ Left (DuplicateHoleName "name")++ it "across nested branches" $+ collect "[{a: _name : number}, (unordered) [_name : string]]" `shouldBe`+ Left (DuplicateHoleName "name")+ it "specs" $ do [qq| _ |] `shouldBe` Sig AnyT False (Var "") [qq| _hole |] `shouldBe` Sig AnyT False (Var "hole")@@ -29,7 +100,10 @@ [qq| 4 |] `shouldBe` Number 4 [qq| -7 |] `shouldBe` Number (-7) - [qq| "foo" |] `shouldBe` String "foo"+ [qq| "" |] `shouldBe` String ""+ [qq| (ci) "" |] `shouldBe` StringCI ""+ [qq| "#{\"foo\" <> \"bar\"}" |] `shouldBe` String "foobar"+ [qq| (ci) "#{\"foo\" <> \"bar\"}" |] `shouldBe` StringCI "foobar" [qq| [] |] `shouldBe` Array Box {values = [], extra = False}@@ -68,7 +142,7 @@ [qq| {foo: #{4 + 7 :: Int}} |] `shouldBe` Object Box {values = [("foo", [Ext (Aeson.Number 11)])], extra = False}- [qq| {foo: #{4 + 7 :: ToEncoding Int}} |] `shouldBe`+ [qq| {foo: #{4 + 7 :: ToEncodingInt}} |] `shouldBe` Object Box {values = [("foo", [Ext (Aeson.Number 11)])], extra = False} it "comments" $ do@@ -106,6 +180,21 @@ # too |] `shouldBe` Object Box {values = [("foo", [Number 4]), ("bar", [Number 7])], extra = False}++ it "overloaded-record-dot" $ do+ let+ foo = Foo 4+ -- note that for this to work -XOverloadedRecordDot+ -- needs to be enabled in the module+ [qq|+ #{foo.bar}+ |] `shouldBe` Ext (Aeson.Number 4)+++data Foo = Foo { bar :: Int }++-- ghc-hs-meta regression+type ToEncodingInt = ToEncoding Int newtype ToEncoding a = ToEncoding { unToEncoding :: a } deriving (Show, Eq, Num)
test/Aeson/Match/QQ/Internal/PrettyPrintSpec.hs view
@@ -7,8 +7,9 @@ import Test.Hspec -import Aeson.Match.QQ (qq) import Aeson.Match.QQ.Internal.PrettyPrint (pp)++import SpecHelper.NoCaptureQQ (qq) spec :: Spec
test/Aeson/Match/QQSpec.hs view
@@ -1,119 +1,144 @@+{-# LANGUAGE DataKinds #-} {-# LANGUAGE DuplicateRecordFields #-} {-# LANGUAGE GeneralisedNewtypeDeriving #-} {-# LANGUAGE OverloadedLists #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-}+{-# LANGUAGE TemplateHaskell #-}+{-# LANGUAGE TypeApplications #-} module Aeson.Match.QQSpec (spec) where import Data.Aeson qualified as Aeson-import Data.Aeson.QQ (aesonQQ)+import Aeson.Value.QQ qualified as Value (qq)+import Data.Either (isLeft) import Data.List.NonEmpty (NonEmpty(..)) import Data.HashMap.Strict qualified as HashMap+import Data.String (fromString)+import Data.Text (Text) import Test.Hspec import Aeson.Match.QQ +import SpecHelper.NoCaptureQQ qualified as AST (qq) + spec :: Spec spec = do describe "match" $ do+ let+ text :: Int -> Text+ text =+ fromString . show it "specs" $ do- [qq| _ |] `shouldMatch` [aesonQQ| {foo: 4, bar: 7} |]- [qq| _ : any |] `shouldMatch` [aesonQQ| {foo: 4, bar: 7} |]- [qq| null |] `shouldMatch` [aesonQQ| null |]- [qq| true |] `shouldMatch` [aesonQQ| true |]- [qq| false |] `shouldMatch` [aesonQQ| false |]- [qq| 4 |] `shouldMatch` [aesonQQ| 4 |]- [qq| "foo" |] `shouldMatch` [aesonQQ| "foo" |]- [qq| (ci) "foo" |] `shouldMatch` [aesonQQ| "Foo" |]- [qq| [1, 2, 3] |] `shouldMatch` [aesonQQ| [1, 2, 3] |]- [qq| [1, _ : number, 3, ...] |] `shouldMatch` [aesonQQ| [1, 2, 3, 4] |]- [qq| [1, _ : string] |] `shouldMatch` [aesonQQ| [1, "foo"] |]- [qq| [1, _ : ci-string] |] `shouldMatch` [aesonQQ| [1, "foo"] |]- [qq| [1, _ : unordered-array] |] `shouldMatch` [aesonQQ| [1, ["foo"]] |]- [qq| (unordered) [] |] `shouldMatch` [aesonQQ| [] |]- [qq| (unordered) [1, 2, 3] |] `shouldMatch` [aesonQQ| [1, 2, 3] |]- [qq| (unordered) [1, 2, 3] |] `shouldMatch` [aesonQQ| [2, 3, 1] |]- [qq| (unordered) [1, 2, 2] |] `shouldMatch` [aesonQQ| [2, 2, 1] |]- [qq| (unordered) [1, _, 2] |] `shouldMatch` [aesonQQ| [2, 2, 1] |]- [qq| (unordered) [1, 2, ...] |] `shouldMatch` [aesonQQ| [2, 3, 1] |]- [qq| (unordered) [1, 2, ...] |] `shouldMatch` [aesonQQ| [2, 2, 1] |]- [qq| {foo: 4, bar: 7} |] `shouldMatch` [aesonQQ| {foo: 4, bar: 7} |]- [qq| {foo: 4, bar: 7, ...} |] `shouldMatch` [aesonQQ| {foo: 4, bar: 7, baz: 11} |]- [qq| #{1 + 2 :: Int} |] `shouldMatch` [aesonQQ| 3 |]- [qq| {foo: _ : number, bar: 7} |] `shouldMatch` [aesonQQ| {foo: 4, bar: 7} |]- [qq| {foo: _ : number?, bar: 7} |] `shouldMatch` [aesonQQ| {foo: null, bar: 7} |]+ [qq| _ |] `shouldMatch` [Value.qq| {foo: 4, bar: 7} |]+ [qq| _ : any |] `shouldMatch` [Value.qq| {foo: 4, bar: 7} |]+ [qq| null |] `shouldMatch` [Value.qq| null |]+ [qq| true |] `shouldMatch` [Value.qq| true |]+ [qq| false |] `shouldMatch` [Value.qq| false |]+ [qq| 4 |] `shouldMatch` [Value.qq| 4 |]+ [qq| "foo" |] `shouldMatch` [Value.qq| "foo" |]+ [qq| (ci) "foo" |] `shouldMatch` [Value.qq| "Foo" |]+ [qq| "" |] `shouldMatch` [Value.qq| "" |]+ [qq| "foo#{text 4}" |] `shouldMatch` [Value.qq| "foo4" |]+ [qq| "#{text 7}bar" |] `shouldMatch` [Value.qq| "7bar" |]+ [qq| "#{text 4}#{text 7}" |] `shouldMatch` [Value.qq| "47" |]+ [qq| (ci) "foo#{text 4}" |] `shouldMatch` [Value.qq| "FOO4" |]+ [qq| (ci) "foo#{\"bar\"}" |] `shouldMatch` [Value.qq| "FoObAr" |]+ [qq| [1, 2, 3] |] `shouldMatch` [Value.qq| [1, 2, 3] |]+ [qq| [1, _ : number, 3, ...] |] `shouldMatch` [Value.qq| [1, 2, 3, 4] |]+ [qq| [1, _ : string] |] `shouldMatch` [Value.qq| [1, "foo"] |]+ [qq| [1, _ : ci-string] |] `shouldMatch` [Value.qq| [1, "foo"] |]+ [qq| [1, _ : unordered-array] |] `shouldMatch` [Value.qq| [1, ["foo"]] |]+ [qq| (unordered) [] |] `shouldMatch` [Value.qq| [] |]+ [qq| (unordered) [1, 2, 3] |] `shouldMatch` [Value.qq| [1, 2, 3] |]+ [qq| (unordered) [1, 2, 3] |] `shouldMatch` [Value.qq| [2, 3, 1] |]+ [qq| (unordered) [1, 2, 2] |] `shouldMatch` [Value.qq| [2, 2, 1] |]+ [qq| (unordered) [1, _, 2] |] `shouldMatch` [Value.qq| [2, 2, 1] |]+ [qq| (unordered) [1, 2, ...] |] `shouldMatch` [Value.qq| [2, 3, 1] |]+ [qq| (unordered) [1, 2, ...] |] `shouldMatch` [Value.qq| [2, 2, 1] |]+ [qq| {foo: 4, bar: 7} |] `shouldMatch` [Value.qq| {foo: 4, bar: 7} |]+ [qq| {foo: 4, bar: 7, ...} |] `shouldMatch` [Value.qq| {foo: 4, bar: 7, baz: 11} |]+ [qq| #{1 + 2 :: Int} |] `shouldMatch` [Value.qq| 3 |]+ [qq| {foo: _ : number, bar: 7} |] `shouldMatch` [Value.qq| {foo: 4, bar: 7} |]+ [qq| {foo: _ : number?, bar: 7} |] `shouldMatch` [Value.qq| {foo: null, bar: 7} |] - [qq| null |] `shouldNotMatch` [aesonQQ| 4 |]- [qq| true |] `shouldNotMatch` [aesonQQ| false |]- [qq| false |] `shouldNotMatch` [aesonQQ| true |]- [qq| 4 |] `shouldNotMatch` [aesonQQ| 7 |]- [qq| "foo" |] `shouldNotMatch` [aesonQQ| "bar" |]- [qq| (ci) "foo" |] `shouldNotMatch` [aesonQQ| "Bar" |]- [qq| [1, 2, 3] |] `shouldNotMatch` [aesonQQ| [1, 2, 3, 4] |]- [qq| [1, 2, 3, ...] |] `shouldNotMatch` [aesonQQ| [1, 2] |]- [qq| [1, _ : string] |] `shouldNotMatch` [aesonQQ| [1, 2] |]- [qq| [1, 2, 3, ...] |] `shouldNotMatch` [aesonQQ| [1, 2, 4] |]- [qq| (unordered) [1, 2, 3] |] `shouldNotMatch` [aesonQQ| [1, 2, 4] |]- [qq| (unordered) [1, 2, 3, 4] |] `shouldNotMatch` [aesonQQ| [1, 2, 3] |]- [qq| (unordered) [1, 2] |] `shouldNotMatch` [aesonQQ| [1, 2, 2] |]- [qq| {foo: 4, bar: 7} |] `shouldNotMatch` [aesonQQ| {foo: 7, bar: 4} |]- [qq| {foo: 4, bar: 7} |] `shouldNotMatch` [aesonQQ| {foo: 4, baz: 7} |]- [qq| {foo: 4, bar: 7, ...} |] `shouldNotMatch` [aesonQQ| {foo: 4, baz: 11} |]- [qq| #{1 + 2 :: Int} |] `shouldNotMatch` [aesonQQ| 4 |]- [qq| {foo: _ : number, bar: 7} |] `shouldNotMatch` [aesonQQ| {foo: "foo", bar: 7} |]- [qq| {foo: _ : number, bar: 7} |] `shouldNotMatch` [aesonQQ| {foo: null, bar: 7} |]+ [qq| null |] `shouldNotMatch` [Value.qq| 4 |]+ [qq| true |] `shouldNotMatch` [Value.qq| false |]+ [qq| false |] `shouldNotMatch` [Value.qq| true |]+ [qq| 4 |] `shouldNotMatch` [Value.qq| 7 |]+ [qq| "foo" |] `shouldNotMatch` [Value.qq| "bar" |]+ [qq| (ci) "foo" |] `shouldNotMatch` [Value.qq| "Bar" |]+ [qq| [1, 2, 3] |] `shouldNotMatch` [Value.qq| [1, 2, 3, 4] |]+ [qq| [1, 2, 3, ...] |] `shouldNotMatch` [Value.qq| [1, 2] |]+ [qq| [1, _ : string] |] `shouldNotMatch` [Value.qq| [1, 2] |]+ [qq| [1, 2, 3, ...] |] `shouldNotMatch` [Value.qq| [1, 2, 4] |]+ [qq| (unordered) [1, 2, 3] |] `shouldNotMatch` [Value.qq| [1, 2, 4] |]+ [qq| (unordered) [1, 2, 3, 4] |] `shouldNotMatch` [Value.qq| [1, 2, 3] |]+ [qq| (unordered) [1, 2] |] `shouldNotMatch` [Value.qq| [1, 2, 2] |]+ [qq| {foo: 4, bar: 7} |] `shouldNotMatch` [Value.qq| {foo: 7, bar: 4} |]+ [qq| {foo: 4, bar: 7} |] `shouldNotMatch` [Value.qq| {foo: 4, baz: 7} |]+ [qq| {foo: 4, bar: 7, ...} |] `shouldNotMatch` [Value.qq| {foo: 4, baz: 11} |]+ [qq| #{1 + 2 :: Int} |] `shouldNotMatch` [Value.qq| 4 |]+ [qq| {foo: _ : number, bar: 7} |] `shouldNotMatch` [Value.qq| {foo: "foo", bar: 7} |]+ [qq| {foo: _ : number, bar: 7} |] `shouldNotMatch` [Value.qq| {foo: null, bar: 7} |] [qq| { foo: _ : string , bar: 7- } |] `shouldNotMatch` [aesonQQ| {foo: null, bar: 7} |]- [qq| {foo: 4, foo: 7} |] `shouldNotMatch` [aesonQQ| {foo: 4} |]- [qq| {foo: 4, foo: 7} |] `shouldNotMatch` [aesonQQ| {foo: 7} |]+ } |] `shouldNotMatch` [Value.qq| {foo: null, bar: 7} |]+ [qq| {foo: 4, foo: 7} |] `shouldNotMatch` [Value.qq| {foo: 4} |]+ [qq| {foo: 4, foo: 7} |] `shouldNotMatch` [Value.qq| {foo: 7} |] it "paths" $ do- match [qq| {foo: {bar: {baz: [1, 4]}}} |] [aesonQQ| {foo: {bar: {baz: [1, 7]}}} |] `shouldBe`+ match [qq| {foo: {bar: {baz: [1, 4]}}} |] [Value.qq| {foo: {bar: {baz: [1, 7]}}} |] `shouldBe` throwE (Mismatch MkMismatch { path = ["foo", "bar", "baz", Idx 1]- , matcher = [qq| 4 |]- , given = [aesonQQ| 7 |]+ , matcher = [AST.qq| 4 |]+ , given = [Value.qq| 7 |] }) context "named holes" $ do it "matches" $- match [qq| {foo: _hole} |] [aesonQQ| {foo: {bar: {baz: [1, 4]}}} |] `shouldBe`- pure (HashMap.singleton "hole" [aesonQQ| {bar: {baz: [1, 4]}} |])+ match [qq| {foo: _hole} |] [Value.qq| {foo: {bar: {baz: [1, 4]}}} |] `shouldBe`+ pure (CCons [Value.qq| {bar: {baz: [1, 4]}} |] CEmpty) + it "supports named lookup and JSON decoding through the public API" $ do+ let userMatcher :: Matcher '["age", "name"]+ userMatcher = [qq| {name: _name : string, age: _age : number} |]+ result = match userMatcher [Value.qq| {name: "Ada", age: 37} |]+ fmap (extractValue @"name") result `shouldBe` Right (Aeson.String "Ada")+ fmap (extractDecoded @"age") result `shouldBe` Right (Right (37 :: Int))+ context "unordered array" $ it "matches" $ do- match [qq| (unordered) [1, _hole] |] [aesonQQ| [2, 1] |] `shouldBe`- pure (HashMap.singleton "hole" [aesonQQ| 2 |])- match [qq| (unordered) [{foo: _hole}, ...] |] [aesonQQ| [{foo: 2}, 1] |] `shouldBe`- pure (HashMap.singleton "hole" [aesonQQ| 2 |])+ match [qq| (unordered) [1, _hole] |] [Value.qq| [2, 1] |] `shouldBe`+ pure (CCons [Value.qq| 2 |] CEmpty)+ match [qq| (unordered) [{foo: _hole}, ...] |] [Value.qq| [{foo: 2}, 1] |] `shouldBe`+ pure (CCons [Value.qq| 2 |] CEmpty) context "duplicate keys" $ do it "matches" $ do- match [qq| {foo: _name, foo: 4} |] [aesonQQ| {foo: 4} |] `shouldBe`- pure (HashMap.singleton "name" [aesonQQ| 4 |])- match [qq| {foo: [_a, 7], foo: [4, _b]} |] [aesonQQ| {foo: [4, 7]} |] `shouldBe`- pure [("a", [aesonQQ| 4 |]), ("b", [aesonQQ| 7 |])]+ match [qq| {foo: _name, foo: 4} |] [Value.qq| {foo: 4} |] `shouldBe`+ pure (CCons [Value.qq| 4 |] CEmpty)+ match [qq| {foo: [_a, 7], foo: [4, _b]} |] [Value.qq| {foo: [4, 7]} |] `shouldBe`+ pure (CCons [Value.qq| 4 |] (CCons [Value.qq| 7 |] CEmpty)) it "doesn't match" $ do- match [qq| {foo: _name, foo: 7} |] [aesonQQ| {foo: 4} |] `shouldBe`+ match [qq| {foo: _name, foo: 7} |] [Value.qq| {foo: 4} |] `shouldBe` throwE (Mismatch MkMismatch { path = [Key "foo"]- , matcher = [qq| 7 |]+ , matcher = [AST.qq| 7 |] , given = Aeson.Number 4 }) describe "repro" $ do -- https://github.com/supki/aeson-match-qq/issues/7 it "#7" $ do- match [qq| {foo: _} |] [aesonQQ| {} |] `shouldBe`+ match [qq| {foo: _} |] [Value.qq| {} |] `shouldBe` throwE (MissingPathElem MkMissingPathElem { path = [] , missing = "foo" })- match [qq| [_] |] [aesonQQ| [] |] `shouldBe`+ match [qq| [_] |] [Value.qq| [] |] `shouldBe` throwE (MissingPathElem MkMissingPathElem { path = [] , missing = Idx 0@@ -121,13 +146,13 @@ -- https://github.com/supki/aeson-match-qq/issues/10 it "#10" $ do- [qq| {foo: []} |] `shouldBe`+ [AST.qq| {foo: []} |] `shouldBe` Object (Box { values = [("foo", [Array (Box {values = [], extra = False})])] , extra = False })- [qq| [{}] |] `shouldBe`+ [AST.qq| [{}] |] `shouldBe` Array (Box { values = [Object (Box {values = [], extra = False})]@@ -136,25 +161,25 @@ -- https://github.com/supki/aeson-match-qq/issues/12 it "#12" $ do- [qq| [ ... ] |] `shouldBe` [qq| _ : array |]- [qq| (unordered) [ ... ] |] `shouldBe` [qq| _ : unordered-array |]- [qq| { ... } |] `shouldBe` [qq| _ : object |]+ [AST.qq| [ ... ] |] `shouldBe` [AST.qq| _ : array |]+ [AST.qq| (unordered) [ ... ] |] `shouldBe` [AST.qq| _ : unordered-array |]+ [AST.qq| { ... } |] `shouldBe` [AST.qq| _ : object |] -- https://github.com/supki/aeson-match-qq/issues/13 it "#13" $- [qq| "Слава Україні" |] `shouldMatch` [aesonQQ| "Слава Україні" |]+ [qq| "Слава Україні" |] `shouldMatch` [Value.qq| "Слава Україні" |] -- https://github.com/supki/aeson-match-qq/issues/18 it "#18" $ do -- string ~ string- match [qq| "foo" |] [aesonQQ| "bar" |] `shouldBe`+ match [qq| "foo" |] [Value.qq| "bar" |] `shouldBe` throwE (Mismatch MkMismatch { path = [] , matcher = String "foo" , given = Aeson.String "bar" }) -- string !~ number- match [qq| "foo" |] [aesonQQ| 4 |] `shouldBe`+ match [qq| "foo" |] [Value.qq| 4 |] `shouldBe` throwE (Mistype MkTypeMismatch { path = [] , expected = StringT@@ -162,7 +187,7 @@ , given = Aeson.Number 4 }) -- string !~ null- match [qq| "foo" |] [aesonQQ| null |] `shouldBe`+ match [qq| "foo" |] [Value.qq| null |] `shouldBe` throwE (Mistype MkTypeMismatch { path = [] , expected = StringT@@ -170,7 +195,7 @@ , given = Aeson.Null }) -- null !~ number- match [qq| null |] [aesonQQ| 4 |] `shouldBe`+ match [qq| null |] [Value.qq| 4 |] `shouldBe` throwE (Mismatch MkMismatch { path = [] , matcher = Null@@ -182,14 +207,14 @@ match [qq| { foo: _hole }- |] [aesonQQ| {foo: {bar: {baz: [1, 4]}}} |] `shouldBe`- pure (HashMap.singleton "hole" [aesonQQ| {bar: {baz: [1, 4]}} |])+ |] [Value.qq| {foo: {bar: {baz: [1, 4]}}} |] `shouldBe`+ pure (CCons [Value.qq| {bar: {baz: [1, 4]}} |] CEmpty) -- https://github.com/supki/aeson-match-qq/issues/28 it "#28" $ do let Left (err :| _) =- match [qq| [{foo: 4, bar: 7}] |] [aesonQQ| {foo: 4, bar: 7}|]+ match [qq| [{foo: 4, bar: 7}] |] [Value.qq| {foo: 4, bar: 7}|] prettyError err `shouldBe` " error: type of value does not match\n\ \expected: array\n\@@ -207,12 +232,12 @@ -- https://github.com/supki/aeson-match-qq/issues/29 it "#29" $ do- parse "_ : not-a-known-type" `shouldBe`+ parse [] "_ : not-a-known-type" `shouldBe` Left "unknown type in hole signature: Failed reading: empty" -- https://github.com/supki/aeson-match-qq/issues/32 it "#32" $ do- parse "null some garbage" `shouldBe`+ parse [] "null some garbage" `shouldBe` Left "trailing garbage after a Matcher value: endOfInput" describe "pretty-printing" $@@ -277,13 +302,13 @@ toEncoding = Aeson.toEncoding . unToEncoding -shouldMatch :: HasCallStack => Matcher Aeson.Value -> Aeson.Value -> Expectation+shouldMatch :: HasCallStack => Matcher names -> Aeson.Value -> Expectation shouldMatch a b =- match a b `shouldBe` pure mempty+ fmap (const ()) (match a b) `shouldBe` Right () -shouldNotMatch :: HasCallStack => Matcher Aeson.Value -> Aeson.Value -> Expectation+shouldNotMatch :: HasCallStack => Matcher names -> Aeson.Value -> Expectation shouldNotMatch a b =- match a b `shouldNotBe` pure mempty+ match a b `shouldSatisfy` isLeft throwE :: e -> Either (NonEmpty e) a throwE =
+ test/SpecHelper/NoCaptureQQ.hs view
@@ -0,0 +1,21 @@+module SpecHelper.NoCaptureQQ (qq) where++import Control.Monad (filterM)+import Data.String (fromString)+import Data.Text.Encoding qualified as Text+import Language.Haskell.TH.Quote (QuasiQuoter(..))+import Language.Haskell.TH.Syntax (isExtEnabled)++import Aeson.Match.QQ qualified as Match (qq)+import Aeson.Match.QQ.Internal.Parse (parse)+import Aeson.Match.QQ.Internal.Value (quote)+++-- A quasiquoter without capturing machinery.+qq :: QuasiQuoter+qq = Match.qq+ { quoteExp = \str -> do+ exts <- filterM isExtEnabled [minBound .. maxBound]+ parsed <- either fail pure (parse exts (Text.encodeUtf8 (fromString str)))+ quote parsed+ }