packages feed

th-extras-0.1.0.0: test/Gen.hs

{-# LANGUAGE CPP, TemplateHaskellQuotes, TypeOperators #-}

-- | Hedgehog generators for Template Haskell syntax, plus independent reference
-- implementations used as oracles by the properties in "Main".
module Gen
  ( genVarName
  , genConName
  , genType
  , freeVars
  , genPat
  , patVars
  , SubstCase (..)
  , genSubstCase
  , genRefinedSubstCase
  , genExistentialSubstCase
  , genWrappedSubstCase
  , genHeadedType
  , genBuiltinHeadedType
  , genUnresolvedHeadedType
  , typeHead
  , genKindWithArity
  , genKindWithArityAnyArrow
  , genDec
  , genCon
  , genDataLikeDec
  , ConInfo (..)
  , conInfo
  , decNames
  , genQuotedDecs
  , allNames
  ) where

import Data.Generics (Data, everything, everywhere, mkQ, mkT)
import qualified Data.Kind as Kind
import Data.List (nub)
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Set (Set)
import qualified Data.Set as Set
#if MIN_VERSION_template_haskell(2,17,0)
import GHC.Exts (FUN)
#endif
import Hedgehog (Gen)
import qualified Hedgehog.Gen as Gen
import qualified Hedgehog.Range as Range
import Language.Haskell.TH
import Language.Haskell.TH.Syntax (Name (..), NameFlavour (..), mkNameU, occString)
import Language.Haskell.TH.Datatype.TyVarBndr

-- | Type variable names come from a small pool so that binders, free variables
-- and substitution targets collide often.
genVarName :: Gen Name
genVarName = Gen.element (map mkName ["a", "b", "c", "x", "y"])

genConName :: Gen Name
genConName = Gen.element (map mkName ["T", "Maybe", "Either"])

genSmallList :: Gen a -> Gen [a]
genSmallList = Gen.list (Range.linear 0 3)

genBndrSpec :: Gen TyVarBndrSpec
genBndrSpec =
  Gen.choice
    [ plainTVSpecified <$> genVarName
    , kindedTVSpecified <$> genVarName <*> Gen.small genType
    ]

#if MIN_VERSION_template_haskell(2,16,0)
genBndrUnit :: Gen TyVarBndrUnit
genBndrUnit =
  Gen.choice
    [ plainTV <$> genVarName
    , kindedTV <$> genVarName <*> Gen.small genType
    ]
#endif

-- | Generates types covering every 'Type' constructor available in the
-- template-haskell version being compiled against.
genType :: Gen Type
genType =
  Gen.recursive Gen.choice
    [ VarT <$> genVarName
    , ConT <$> genConName
    , PromotedT <$> genConName
    , TupleT <$> Gen.int (Range.linear 0 3)
    , UnboxedTupleT <$> Gen.int (Range.linear 0 3)
    , UnboxedSumT <$> Gen.int (Range.linear 2 3)
    , PromotedTupleT <$> Gen.int (Range.linear 0 3)
    , Gen.element
        [ ArrowT, EqualityT, ListT, PromotedNilT, PromotedConsT, StarT
        , ConstraintT, WildCardT, LitT (NumTyLit 1), LitT (StrTyLit "s")
#if MIN_VERSION_template_haskell(2,17,0)
        , MulArrowT
#endif
        ]
    ]
    [ Gen.subterm2 genType genType AppT
    , Gen.subterm2 genType genType SigT
    , Gen.subterm genType ParensT
    , Gen.subterm2 genType genType (\l r -> InfixT l (mkName "+") r)
    , Gen.subterm2 genType genType (\l r -> UInfixT l (mkName "+") r)
    , ForallT <$> genSmallList genBndrSpec <*> genSmallList genType <*> genType
#if MIN_VERSION_template_haskell(2,15,0)
    , Gen.subterm2 genType genType AppKindT
    , Gen.subterm genType (ImplicitParamT "p")
#endif
#if MIN_VERSION_template_haskell(2,16,0)
    , ForallVisT <$> genSmallList genBndrUnit <*> genType
#endif
#if MIN_VERSION_template_haskell(2,19,0)
    , Gen.subterm2 genType genType (\l r -> PromotedInfixT l (mkName ":+") r)
    , Gen.subterm2 genType genType (\l r -> PromotedUInfixT l (mkName ":+") r)
#endif
    ]

-- | Reference implementation: the free type variables of a type, including
-- those in kinds and contexts. Binders in a telescope scope over later binders'
-- kinds and over the body.
freeVars :: Type -> Set Name
freeVars ty = case ty of
  VarT n -> Set.singleton n
  AppT f x -> freeVars f <> freeVars x
  SigT t k -> freeVars t <> freeVars k
  ParensT t -> freeVars t
  InfixT l _ r -> freeVars l <> freeVars r
  UInfixT l _ r -> freeVars l <> freeVars r
  ForallT bndrs ctx t -> telescope bndrs (Set.unions (map freeVars (t : ctx)))
#if MIN_VERSION_template_haskell(2,15,0)
  AppKindT t k -> freeVars t <> freeVars k
  ImplicitParamT _ t -> freeVars t
#endif
#if MIN_VERSION_template_haskell(2,16,0)
  ForallVisT bndrs t -> telescope bndrs (freeVars t)
#endif
#if MIN_VERSION_template_haskell(2,19,0)
  PromotedInfixT l _ r -> freeVars l <> freeVars r
  PromotedUInfixT l _ r -> freeVars l <> freeVars r
#endif
  -- Everything else generated by 'genType' is a leaf with no type variables.
  _ -> Set.empty
  where
    telescope :: [TyVarBndr_ flag] -> Set Name -> Set Name
    telescope bndrs body =
      foldr
        (\b rest -> bndrKindVars b <> Set.delete (tvName b) rest)
        body
        bndrs

    bndrKindVars :: TyVarBndr_ flag -> Set Name
    bndrKindVars = elimTV (const Set.empty) (\_ k -> freeVars k)

-- | Generates patterns covering every 'Pat' constructor that can bind term
-- variables, in the template-haskell version being compiled against.
genPat :: Gen Pat
genPat =
  Gen.recursive Gen.choice
    [ VarP <$> genTermName
    , pure WildP
    , pure (LitP (IntegerL 1))
    ]
    [ TupP <$> genSmallList genPat
    , UnboxedTupP <$> genSmallList genPat
    , do
        arity <- Gen.int (Range.linear 2 3)
        alt <- Gen.int (Range.linear 1 arity)
        p <- genPat
        pure (UnboxedSumP p alt arity)
    , mkConP <$> genConName <*> genSmallList genPat
    , Gen.subterm2 genPat genPat (\l r -> InfixP l (mkName ":") r)
    , Gen.subterm2 genPat genPat (\l r -> UInfixP l (mkName ":") r)
    , Gen.subterm genPat ParensP
    , Gen.subterm genPat TildeP
    , Gen.subterm genPat BangP
    , AsP <$> genTermName <*> genPat
    , RecP <$> genConName <*> genSmallList ((,) <$> genFieldName <*> genPat)
    , ListP <$> genSmallList genPat
    , Gen.subterm genPat (\p -> SigP p (ConT (mkName "Int")))
    , Gen.subterm genPat (ViewP (VarE (mkName "f")))
    ]
  where
    genTermName = Gen.element (map mkName ["x", "y", "z"])
    genFieldName = Gen.element (map mkName ["f1", "f2"])
#if MIN_VERSION_template_haskell(2,18,0)
    mkConP n = ConP n []
#else
    mkConP = ConP
#endif

-- | Reference implementation: the term variables bound by a pattern, in
-- left-to-right order.
patVars :: Pat -> [Name]
patVars pat = case pat of
  VarP n -> [n]
  AsP n p -> n : patVars p
  TupP ps -> concatMap patVars ps
  UnboxedTupP ps -> concatMap patVars ps
  UnboxedSumP p _ _ -> patVars p
#if MIN_VERSION_template_haskell(2,18,0)
  ConP _ _ ps -> concatMap patVars ps
#else
  ConP _ ps -> concatMap patVars ps
#endif
  InfixP l _ r -> patVars l ++ patVars r
  UInfixP l _ r -> patVars l ++ patVars r
  ParensP p -> patVars p
  TildeP p -> patVars p
  BangP p -> patVars p
  RecP _ fps -> concatMap (patVars . snd) fps
  ListP ps -> concatMap patVars ps
  SigP p _ -> patVars p
  ViewP _ p -> patVars p
  -- Everything else generated by 'genPat' binds nothing.
  _ -> []

-- | Inputs for 'substVarsWith', plus the substitution it is expected to apply
-- to the free variables of the argument type.
data SubstCase = SubstCase
  { scTopVars :: [Name]
  , scResultType :: Type
  , scArgType :: Type
  , scExpected :: Map Name Name
  } deriving Show

-- | Generates a constructor result type @T x_1 ... x_(n-1) i@ whose parameters
-- include every free variable of the argument type, and distinct instance head
-- variables @v_1 ... v_(n-1)@ drawn from a pool that overlaps the argument
-- type's variable names, so that substituted names can clash with binders.
genSubstCase :: Gen SubstCase
genSubstCase = genSubstCaseWith (Range.singleton 0)

-- | Like 'genSubstCase', but some of the parameters @x_i@ of the result type are
-- refined to concrete types, as a GADT constructor's result type can be, e.g.
-- @C :: T Int b i@.
genRefinedSubstCase :: Gen SubstCase
genRefinedSubstCase = genSubstCaseWith (Range.linear 1 3)

-- | Like 'genSubstCase', but the argument type also mentions variables that are
-- not parameters of the result type, which the substitution must leave alone:
-- existentially quantified variables (whose binders 'argTypesOfCon' discards)
-- and the GADT index variable @i@. Their names are distinct from every instance
-- head variable, so leaving them alone cannot conflate them with one.
genExistentialSubstCase :: Gen SubstCase
genExistentialSubstCase = do
  sc <- genSubstCaseWith (Range.linear 0 2)
  others <- Gen.filter (not . null) (Gen.subsequence (map mkName ["e1", "e2", "i"]))
  pure sc { scArgType = foldl AppT (scArgType sc) (map VarT others) }

-- | Like 'genSubstCase' (with some refined parameters), but the result type is
-- written with extra syntax that does not change its meaning: parentheses and
-- kind signatures around the whole type, around partial applications and
-- around parameters, and kind applications in the application spine.
genWrappedSubstCase :: Gen SubstCase
genWrappedSubstCase = do
  sc <- genSubstCaseWith (Range.linear 0 2)
  resultType <- wrapSpine (scResultType sc)
  pure sc { scResultType = resultType }
  where
    wrapSpine :: Type -> Gen Type
    wrapSpine ty = case ty of
      AppT f x -> do
        f' <- wrapSpine f
        x' <- wrapAnnotated x
        wrapParens (AppT f' x')
      _ -> do
        kindApps <- genSmallList (Gen.small genType)
        wrapParens (foldl appKind ty kindApps)

    wrapParens t = Gen.element [t, ParensT t]
    wrapAnnotated t = Gen.element [t, ParensT t, SigT t StarT, ParensT (SigT t StarT)]

#if MIN_VERSION_template_haskell(2,15,0)
    appKind = AppKindT
#else
    appKind t _ = t
#endif

-- | The range is the number of parameters of the result type that are refined
-- to concrete types rather than being variables.
genSubstCaseWith :: Range.Range Int -> Gen SubstCase
genSubstCaseWith refined = do
  argType <- genType
  extra <- genSmallList genVarName
  nRefined <- Gen.int refined
  concrete <- Gen.list (Range.singleton nRefined) (ConT <$> Gen.element (map mkName ["Int", "Bool"]))
  params <- Gen.shuffle
    (map Right (nub (Set.toList (freeVars argType) ++ extra)) ++ map Left concrete)
  pool <- Gen.shuffle (map mkName ["a", "b", "c", "x", "y", "p", "q", "r", "s", "t"])
  let topVars = take (length params) pool
      resultType =
        AppT (foldl AppT (ConT (mkName "T")) (map (either id VarT) params)) (VarT (mkName "i"))
  pure SubstCase
    { scTopVars = topVars
    , scResultType = resultType
    , scArgType = argType
    , scExpected = Map.fromList [ (x, v) | (Right x, v) <- zip params topVars ]
    }

-- | Generates a type together with the name at its head: a head type wrapped in
-- any number of applications, parentheses, kind signatures, foralls and kind
-- applications, none of which change the head.
genHeadedType :: Gen (Type, Name)
genHeadedType = genHeadedTypeFrom genHead
  where
    genHead :: Gen (Type, Name)
    genHead = Gen.choice
      [ (\n -> (ConT n, n)) <$> genConName
      , (\n -> (VarT n, n)) <$> genVarName
      , (\n -> (PromotedT n, n)) <$> genConName
      , (\k -> (TupleT k, tupleTypeName k)) <$> Gen.int (Range.linear 0 3)
      , (\k -> (UnboxedTupleT k, unboxedTupleTypeName k)) <$> Gen.int (Range.linear 0 3)
      , pure (ListT, ''[])
      , pure (ArrowT, ''(->))
      , (\l r -> (InfixT l (mkName "+") r, mkName "+")) <$> Gen.small genType <*> Gen.small genType
#if MIN_VERSION_template_haskell(2,19,0)
      , (\l r -> (PromotedInfixT l (mkName ":+") r, mkName ":+")) <$> Gen.small genType <*> Gen.small genType
#endif
      ]

-- | Like 'genHeadedType', but the head is one of the built-in type constructors
-- that Template Haskell represents with dedicated 'Type' constructors rather
-- than 'ConT', paired with the name of that type constructor.
genBuiltinHeadedType :: Gen (Type, Name)
genBuiltinHeadedType = genHeadedTypeFrom $ Gen.choice
  [ (\k -> (UnboxedSumT k, unboxedSumTypeName k)) <$> Gen.int (Range.linear 2 3)
  , (\k -> (PromotedTupleT k, tupleDataName k)) <$> Gen.element [0, 2, 3]
  , pure (PromotedNilT, '[])
  , pure (PromotedConsT, '(:))
  , pure (StarT, ''Kind.Type)
  , pure (ConstraintT, ''Kind.Constraint)
#if MIN_VERSION_template_haskell(2,19,0)
  , pure (EqualityT, ''(~))
#endif
#if MIN_VERSION_template_haskell(2,17,0)
  , pure (MulArrowT, ''FUN)
#endif
  ]

-- | Like 'genHeadedType', but the head is a chain of unresolved infix
-- applications ('UInfixT' or 'PromotedUInfixT') of arbitrary shape whose
-- operators are all the same, so that the head is that operator whatever the
-- operator's fixity.
genUnresolvedHeadedType :: Gen (Type, Name)
genUnresolvedHeadedType = genHeadedTypeFrom $ Gen.choice
  [ (\t -> (t, mkName "+++")) <$> genChain (\l r -> UInfixT l (mkName "+++") r)
#if MIN_VERSION_template_haskell(2,19,0)
  , (\t -> (t, mkName ":+++")) <$> genChain (\l r -> PromotedUInfixT l (mkName ":+++") r)
#endif
  ]
  where
    -- A tree of at least one unresolved application, with operands that do not
    -- themselves continue the chain.
    genChain :: (Type -> Type -> Type) -> Gen Type
    genChain node = Gen.recursive Gen.choice
      [ node <$> genOperand <*> genOperand ]
      [ Gen.subterm2 (genChain node) (genChain node) node
      , Gen.subterm (genChain node) (`node` VarT (mkName "a"))
      , Gen.subterm (genChain node) (node (VarT (mkName "a")))
      ]

    -- Operands that are themselves unresolved applications would extend the
    -- chain, so parenthesise them.
    genOperand :: Gen Type
    genOperand = protect <$> Gen.small genType

    protect t = case t of
      UInfixT {} -> ParensT t
#if MIN_VERSION_template_haskell(2,19,0)
      PromotedUInfixT {} -> ParensT t
#endif
      _ -> t

-- | Wraps a generated head type in any number of applications, parentheses,
-- kind signatures, foralls and kind applications, none of which change the
-- head.
genHeadedTypeFrom :: Gen (Type, Name) -> Gen (Type, Name)
genHeadedTypeFrom genHead = do
  (ty0, name) <- genHead
  layers <- Gen.list (Range.linear 0 5) genLayer
  ty <- foldr (=<<) (pure ty0) layers
  pure (ty, name)
  where
    genLayer :: Gen (Type -> Gen Type)
    genLayer = Gen.element
      [ \t -> AppT t <$> Gen.small genType
      , \t -> pure (ParensT t)
      , \t -> SigT t <$> Gen.small genType
      , \t -> (\bndrs -> ForallT bndrs [] t) <$> genSmallList genBndrSpec
#if MIN_VERSION_template_haskell(2,15,0)
      , \t -> AppKindT t <$> Gen.small genType
#endif
#if MIN_VERSION_template_haskell(2,16,0)
      , \t -> (\bndrs -> ForallVisT bndrs t) <$> genSmallList genBndrUnit
#endif
      ]

-- | Generates a kind together with its arity: the number of arguments (visible
-- type arguments and arrow arguments) it takes before reaching a result kind.
-- The kind is built by wrapping a result kind in arrows, parentheses, kind
-- signatures and foralls, in any order.
genKindWithArity :: Gen (Kind, Int)
genKindWithArity = genKindWithArityFrom (pure (\arg k -> AppT (AppT ArrowT arg) k))

-- | Like 'genKindWithArity', but each arrow is written in any of the ways
-- Template Haskell can represent @arg -> k@: with 'ArrowT', with the arrow's
-- partial application parenthesised, infix (resolved or not), by name with
-- 'ConT', or as a multiplicity arrow.
genKindWithArityAnyArrow :: Gen (Kind, Int)
genKindWithArityAnyArrow = genKindWithArityFrom $ Gen.element
  [ \arg k -> AppT (AppT ArrowT arg) k
  , \arg k -> AppT (ParensT (AppT ArrowT arg)) k
  , \arg k -> InfixT arg ''(->) k
  , \arg k -> UInfixT arg ''(->) k
  , \arg k -> AppT (AppT (ConT ''(->)) arg) k
#if MIN_VERSION_template_haskell(2,17,0)
  , \arg k -> AppT (AppT (AppT MulArrowT (VarT (mkName "m"))) arg) k
#endif
  ]

-- | The generator gives the ways to build an arrow kind @arg -> k@ from @arg@
-- and @k@.
genKindWithArityFrom :: Gen (Type -> Kind -> Kind) -> Gen (Kind, Int)
genKindWithArityFrom genArrow = do
  result <- Gen.element [StarT, ConstraintT, ConT (mkName "Type"), VarT (mkName "k")]
  layers <- Gen.list (Range.linear 0 6) genLayer
  foldr (=<<) (pure (result, 0)) layers
  where
    genLayer :: Gen ((Kind, Int) -> Gen (Kind, Int))
    genLayer = Gen.element
      [ \(k, n) -> (\arrow arg -> (arrow arg k, n + 1)) <$> genArrow <*> Gen.small genType
      , \(k, n) -> pure (ParensT k, n)
      , \(k, n) -> (\s -> (SigT k s, n)) <$> Gen.element [StarT, ConT (mkName "Type")]
      , \(k, n) -> (\bndrs -> (ForallT bndrs [] k, n)) <$> genSmallList genBndrSpec
#if MIN_VERSION_template_haskell(2,16,0)
      , \(k, n) -> (\bndrs -> (ForallVisT bndrs k, n + length bndrs)) <$> genSmallList genBndrUnit
#endif
      ]

-- | Generates declarations of every kind that can bind names, plus some that
-- bind none. Names come from small per-namespace pools.
genDec :: Gen Dec
genDec = Gen.choice
  [ FunD <$> genValName <*> pure []
  , (\p -> ValD p (NormalB (VarE (mkName "undefined"))) []) <$> genPat
  , DataD [] <$> genTyConName <*> pure [] <*> pure Nothing <*> genSmallList genCon <*> pure []
  , NewtypeD [] <$> genTyConName <*> pure [] <*> pure Nothing <*> genCon <*> pure []
#if MIN_VERSION_template_haskell(2,20,0)
  , TypeDataD <$> genTyConName <*> pure [] <*> pure Nothing <*> genSmallList genCon
#endif
  , TySynD <$> genTyConName <*> pure [] <*> pure intT
  , ClassD [] <$> genTyConName <*> pure [] <*> pure [] <*> genSmallList genClassBodyDec
  , (\n -> ForeignD (ImportF CCall Safe "foo" n intT)) <$> genValName
  , (\n -> ForeignD (ExportF CCall "foo" n intT)) <$> genValName
  , (\n -> OpenTypeFamilyD (TypeFamilyHead n [] NoSig Nothing)) <$> genTyConName
  , (\n -> ClosedTypeFamilyD (TypeFamilyHead n [] NoSig Nothing) []) <$> genTyConName
  , (\n -> DataFamilyD n [] Nothing) <$> genTyConName
#if MIN_VERSION_template_haskell(2,15,0)
  , genDataInstD
  , InstanceD Nothing [] (ConT (mkName "C")) <$> genSmallList genDataInstD
#endif
  , (\n -> PatSynD n (PrefixPatSyn []) ImplBidir WildP) <$> genValName
  , (\n fs -> PatSynD n (RecordPatSyn fs) ImplBidir WildP) <$> genValName <*> genSmallList genFieldName
  , (\n -> SigD n intT) <$> genValName
  ]
  where
    intT = ConT (mkName "Int")

    genValName = Gen.element (map mkName ["f", "g", "h"])
    genTyConName = Gen.element (map mkName ["T", "U", "V"])
    genFieldName = Gen.element (map mkName ["f1", "f2", "f3"])

    -- Declarations that can appear in a class body.
    genClassBodyDec :: Gen Dec
    genClassBodyDec = Gen.choice
      [ (\n -> SigD n intT) <$> genValName
      , FunD <$> genValName <*> pure []
      , (\n -> OpenTypeFamilyD (TypeFamilyHead n [] NoSig Nothing)) <$> genTyConName
      , (\n -> DataFamilyD n [] Nothing) <$> genTyConName
      ]

#if MIN_VERSION_template_haskell(2,15,0)
    genDataInstD :: Gen Dec
    genDataInstD = Gen.choice
      [ DataInstD [] Nothing (AppT (ConT (mkName "F")) intT) Nothing <$> genSmallList genCon <*> pure []
      , NewtypeInstD [] Nothing (AppT (ConT (mkName "F")) intT) Nothing <$> genCon <*> pure []
      ]
#endif

-- | Generates data constructors of every form, including GADT constructors
-- declaring several names at once.
genCon :: Gen Con
genCon = Gen.recursive Gen.choice
  [ NormalC <$> genDataConName <*> pure [(noBang, intT)]
  , RecC <$> genDataConName <*> genSmallList ((\f -> (f, noBang, intT)) <$> genFieldName)
  , (\n -> InfixC (noBang, intT) n (noBang, intT)) <$> genDataConName
  , GadtC <$> Gen.list (Range.linear 1 3) genDataConName <*> pure [] <*> pure resT
  , RecGadtC <$> Gen.list (Range.linear 1 3) genDataConName
      <*> genSmallList ((\f -> (f, noBang, intT)) <$> genFieldName) <*> pure resT
  ]
  [ Gen.subterm genCon (ForallC [] [])
  , ForallC <$> genSmallList genBndrSpec <*> pure [] <*> genCon
  ]
  where
    intT = ConT (mkName "Int")
    noBang = Bang NoSourceUnpackedness NoSourceStrictness
    resT = ConT (mkName "T")
    genDataConName = Gen.element (map mkName ["A", "B", "C"])
    genFieldName = Gen.element (map mkName ["f1", "f2", "f3"])

-- | Generates every kind of declaration that declares data constructors,
-- together with those constructors.
genDataLikeDec :: Gen (Dec, [Con])
genDataLikeDec = Gen.choice
  [ (\n cs -> (DataD [] n [] Nothing cs [], cs)) <$> genTyConName <*> genSmallList genCon
  , (\n c -> (NewtypeD [] n [] Nothing c [], [c])) <$> genTyConName <*> genCon
#if MIN_VERSION_template_haskell(2,20,0)
  , (\n cs -> (TypeDataD n [] Nothing cs, cs)) <$> genTyConName <*> genSmallList genCon
#endif
#if MIN_VERSION_template_haskell(2,15,0)
  , (\cs -> (DataInstD [] Nothing instHead Nothing cs [], cs)) <$> genSmallList genCon
  , (\c -> (NewtypeInstD [] Nothing instHead Nothing c [], [c])) <$> genCon
#endif
  ]
  where
    genTyConName = Gen.element (map mkName ["T", "U", "V"])
#if MIN_VERSION_template_haskell(2,15,0)
    instHead = AppT (ConT (mkName "F")) (ConT (mkName "Int"))
#endif

-- | Reference implementation: every name a declaration brings into scope, in
-- order: the declared thing itself, then its data constructors and record
-- fields, class methods and associated families, or pattern synonym fields.
-- Class default methods and instance method definitions define existing
-- names, so they bind nothing new.
decNames :: Dec -> [Name]
decNames dec = case dec of
  FunD n _ -> [n]
  ValD p _ _ -> patVars p
  DataD _ n _ _ cons _ -> n : concatMap conNames cons
  NewtypeD _ n _ _ con _ -> n : conNames con
#if MIN_VERSION_template_haskell(2,20,0)
  TypeDataD n _ _ cons -> n : concatMap conNames cons
#endif
  TySynD n _ _ -> [n]
  ClassD _ n _ _ body -> n : concatMap classBodyNames body
  ForeignD (ImportF _ _ _ n _) -> [n]
  ForeignD (ExportF {}) -> []
  OpenTypeFamilyD (TypeFamilyHead n _ _ _) -> [n]
  ClosedTypeFamilyD (TypeFamilyHead n _ _ _) _ -> [n]
  DataFamilyD n _ _ -> [n]
  DataInstD _ _ _ _ cons _ -> concatMap conNames cons
  NewtypeInstD _ _ _ _ con _ -> conNames con
  InstanceD _ _ _ body -> concatMap decNames [ d | d <- body, isDataInst d ]
  PatSynD n (RecordPatSyn fs) _ _ -> n : fs
  PatSynD n _ _ _ -> [n]
  _ -> []
  where
    conNames con = case con of
      NormalC n _ -> [n]
      RecC n fs -> n : [ f | (f, _, _) <- fs ]
      InfixC _ n _ -> [n]
      ForallC _ _ c -> conNames c
      GadtC ns _ _ -> ns
      RecGadtC ns fs _ -> ns ++ [ f | (f, _, _) <- fs ]

    classBodyNames d = case d of
      SigD n _ -> [n]
      OpenTypeFamilyD {} -> decNames d
      DataFamilyD {} -> decNames d
      _ -> []

    isDataInst d = case d of
      DataInstD {} -> True
      NewtypeInstD {} -> True
      _ -> False

-- | Generates declarations as a declaration quote would produce them: every
-- name, bound or not, is made fresh ('NameU'), with the same unique for every
-- occurrence of the same name.
genQuotedDecs :: Gen [Dec]
genQuotedDecs = do
  decs <- Gen.list (Range.linear 1 4) genDec
  let bases = nub [ occString occ | Name occ NameS <- allNames decs ]
      uniques = Map.fromList (zip bases [1 ..])
      freshen n@(Name occ NameS) =
        maybe n (mkNameU (occString occ) . fromInteger) (Map.lookup (occString occ) uniques)
      freshen n = n
  pure (everywhere (mkT freshen) decs)

-- | Every 'Name' occurring in a value, in traversal order.
allNames :: Data a => a -> [Name]
allNames = everything (++) (mkQ [] (\n -> [n]))

-- | Reference implementation of what the constructor accessors should report.
data ConInfo = ConInfo
  { ciNames :: [Name]
  , ciArgTypes :: [Type]
  , ciBinders :: [Name]
  } deriving (Eq, Show)

conInfo :: Con -> ConInfo
conInfo con = case con of
  NormalC n args -> ConInfo [n] (map snd args) []
  RecC n fields -> ConInfo [n] [ t | (_, _, t) <- fields ] []
  InfixC (_, l) n (_, r) -> ConInfo [n] [l, r] []
  ForallC bndrs _ c -> let ci = conInfo c in ci { ciBinders = map tvName bndrs ++ ciBinders ci }
  GadtC ns args _ -> ConInfo ns (map snd args) []
  RecGadtC ns fields _ -> ConInfo ns [ t | (_, _, t) <- fields ] []

-- | Reference implementation: the name of the type constructor (or variable)
-- at the head of a type, if it has one. Type-level literals, wildcards and
-- implicit parameters have none, and nor does a chain of unresolved infix
-- applications whose operators differ, since its head depends on fixities.
typeHead :: Type -> Maybe Name
typeHead ty = case ty of
  ForallT _ _ t -> typeHead t
  AppT f _ -> typeHead f
  SigT t _ -> typeHead t
  ParensT t -> typeHead t
  VarT n -> Just n
  ConT n -> Just n
  PromotedT n -> Just n
  TupleT k -> Just (tupleTypeName k)
  UnboxedTupleT k -> Just (unboxedTupleTypeName k)
  UnboxedSumT k -> Just (unboxedSumTypeName k)
  PromotedTupleT k -> Just (tupleDataName k)
  ArrowT -> Just ''(->)
  ListT -> Just ''[]
  PromotedNilT -> Just '[]
  PromotedConsT -> Just '(:)
  StarT -> Just ''Kind.Type
  ConstraintT -> Just ''Kind.Constraint
  InfixT _ n _ -> Just n
  UInfixT {} -> sameOperator (unresolvedOperators ty)
#if MIN_VERSION_template_haskell(2,15,0)
  AppKindT t _ -> typeHead t
#endif
#if MIN_VERSION_template_haskell(2,16,0)
  ForallVisT _ t -> typeHead t
#endif
#if MIN_VERSION_template_haskell(2,17,0)
  MulArrowT -> Just ''FUN
#endif
#if MIN_VERSION_template_haskell(2,19,0)
  EqualityT -> Just ''(~)
  PromotedInfixT _ n _ -> Just n
  PromotedUInfixT {} -> sameOperator (unresolvedOperators ty)
#endif
  -- LitT, WildCardT, ImplicitParamT, and EqualityT before template-haskell 2.19.
  _ -> Nothing
  where
    sameOperator ops = case ops of
      op : rest | all (== op) rest -> Just op
      _ -> Nothing

    unresolvedOperators t = case t of
      UInfixT l n r -> unresolvedOperators l ++ [n] ++ unresolvedOperators r
#if MIN_VERSION_template_haskell(2,19,0)
      PromotedUInfixT l n r -> unresolvedOperators l ++ [n] ++ unresolvedOperators r
#endif
      _ -> []