packages feed

aeson-match-qq-2.0.0: src/Aeson/Match/QQ/Internal/Matcher.hs

{-# 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)