packages feed

th-extras 0.0.0.9 → 0.1.0.0

raw patch · 7 files changed

+1194/−112 lines, 7 filesdep +hedgehogdep +th-extrasdep ~basedep ~containersdep ~sybPVP ok

version bump matches the API change (PVP)

Dependencies added: hedgehog, th-extras

Dependency ranges changed: base, containers, syb, template-haskell, th-abstraction

API changes (from Hackage documentation)

+ Language.Haskell.TH.Extras: namesBoundInCon :: Con -> [Name]

Files

ChangeLog.md view
@@ -1,5 +1,19 @@ # Revision history for th-extras +## 0.1.0.0 - 2026-11-27++* Major version bump due to behaviour changes rather than ABI changes.+* `occursInType` now finds variables in kinds and contexts.+* `namesBoundInDec` also returns constructors, fields, methods and+  families, so genericalizeDecs renames more names.+* `substVarsWith` renames clashing binders, substitutes kinds, leaves+  existential and index variables alone instead of crashing, and looks+  through parentheses and kind signatures.+* `kindArity` and `tyConArity` give different arities in some cases.+* `headOfType`, `decCons` and `namesBoundInPat` handle cases that+  previously crashed or were missed.+* Drop support for `ghc-8.0` and `ghc-8.2`.+ ## 0.0.0.9 - 2026-02-11  * Support a bunch of new Type constructors in `substVarsWith`.
ReadMe.md view
@@ -1,5 +1,5 @@ # th-extras-[![Haskell](https://img.shields.io/badge/language-Haskell-orange.svg)](https://haskell.org) [![Hackage](https://img.shields.io/hackage/v/th-extras.svg)](https://hackage.haskell.org/package/th-extras) [![Hackage CI](https://matrix.hackage.haskell.org/api/v2/packages/th-extras/badge)](https://matrix.hackage.haskell.org/#/package/th-extras) [![Github CI](https://github.com/mokus0/th-extras/workflows/github-action/badge.svg)](https://github.com/mokus0/th-extras/actions) [![BSD3 License](https://img.shields.io/badge/license-BSD3-blue.svg)](https://github.com/mokus0/th-extras/blob/master/LICENSE)+[![Haskell](https://img.shields.io/badge/language-Haskell-orange.svg)](https://haskell.org) [![Hackage](https://img.shields.io/hackage/v/th-extras.svg)](https://hackage.haskell.org/package/th-extras) [![Hackage CI](https://matrix.hackage.haskell.org/api/v2/packages/th-extras/badge)](https://matrix.hackage.haskell.org/#/package/th-extras) [![Github CI](https://github.com/erikd/th-extras/actions/workflows/haskell-ci.yml/badge.svg)](https://github.com/erikd/th-extras/actions/workflows/haskell-ci.yml) [![Public Domain](https://img.shields.io/badge/license-Public%20Domain-blue.svg)](https://github.com/erikd/th-extras/blob/master/th-extras.cabal)  A grab bag of useful functions for use with Template Haskell. 
src/Language/Haskell/TH/Extras.hs view
@@ -1,4 +1,4 @@-{-# LANGUAGE CPP, TemplateHaskell #-}+{-# LANGUAGE CPP, ScopedTypeVariables, TemplateHaskell, TypeOperators #-}  {-# OPTIONS_GHC -Wno-incomplete-uni-patterns #-} @@ -6,13 +6,15 @@  import Control.Monad import Data.Generics+import qualified Data.Kind as Kind+import Data.Map (Map)+import qualified Data.Map as Map import Data.Maybe-import Data.Set (Set) import qualified Data.Set as Set-import Language.Haskell.TH-#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ < 914-import Language.Haskell.TH.Syntax+#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 900+import GHC.Exts (FUN) #endif+import Language.Haskell.TH import Language.Haskell.TH.Datatype.TyVarBndr  intIs64 :: Bool@@ -34,12 +36,10 @@ nameOfCon (RecC     name _) = name nameOfCon (InfixC _ name _) = name nameOfCon (ForallC _ _ con) = nameOfCon con-#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 800 nameOfCon (GadtC [name] _ _)    = name nameOfCon (GadtC _ _ _)    = error $ "nameOfCon: GadtC: only single constructor names are supported" nameOfCon (RecGadtC [name] _ _) = name nameOfCon (RecGadtC _ _ _)    = error $ "nameOfCon: RecGadtC: only single constructor names are supported"-#endif  -- |WARNING: discards binders in GADTs and existentially-quantified constructors argTypesOfCon :: Con -> [Type]@@ -47,10 +47,8 @@ argTypesOfCon (RecC     _ args) = [t | (_,_,t) <- args] argTypesOfCon (InfixC x _ y)    = map snd [x,y] argTypesOfCon (ForallC _ _ con) = argTypesOfCon con-#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 800 argTypesOfCon (GadtC _ args _)    = map snd args argTypesOfCon (RecGadtC _ args _) = [t | (_,_,t) <- args]-#endif  nameOfBinder :: TyVarBndr_ a -> Name nameOfBinder = tvName@@ -59,62 +57,71 @@ varsBoundInCon (ForallC bndrs _ con) = bndrs ++ varsBoundInCon con varsBoundInCon _ = [] +-- | Determines the term variables bound by a pattern, in left-to-right order. namesBoundInPat :: Pat -> [Name]-namesBoundInPat (VarP name)             = [name]-namesBoundInPat (TupP pats)             = pats >>= namesBoundInPat-#if MIN_VERSION_template_haskell(2,18,0)-namesBoundInPat (ConP _ _ pats)         = pats >>= namesBoundInPat-#else-namesBoundInPat (ConP _ pats)           = pats >>= namesBoundInPat-#endif-namesBoundInPat (InfixP p1 _ p2)        = namesBoundInPat p1 ++ namesBoundInPat p2-namesBoundInPat (TildeP pat)            = namesBoundInPat pat-namesBoundInPat (AsP name pat)          = name : namesBoundInPat pat-namesBoundInPat (RecP _ fieldPats)      = map snd fieldPats >>= namesBoundInPat-namesBoundInPat (ListP pats)            = pats >>= namesBoundInPat-namesBoundInPat (SigP pat _)            = namesBoundInPat pat--#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 612-namesBoundInPat (BangP pat)             = namesBoundInPat pat-#endif--#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 700-namesBoundInPat (ViewP _ pat)           = namesBoundInPat pat-#endif--#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 702-namesBoundInPat (UnboxedTupP pats)      = pats >>= namesBoundInPat-#endif--namesBoundInPat _                       = []+namesBoundInPat pat = case pat of+    VarP name     -> [name]+    AsP name pat' -> name : namesBoundInPat pat'+    -- The expression in a view pattern binds nothing in the enclosing scope.+    ViewP _ pat'  -> namesBoundInPat pat'+    -- Every other constructor binds nothing itself, so just look at all of its+    -- sub-patterns.+    _ -> concat (gmapQ goData pat)+  where+    goData :: Data d => d -> [Name]+    goData d+        | Just p <- cast d = namesBoundInPat p+        -- Patterns cannot bind variables inside expressions or types.+        | Just (_ :: Exp) <- cast d = []+        | Just (_ :: Type) <- cast d = []+        | otherwise = concat (gmapQ goData d)  +-- | Determines the names a declaration brings into scope: the declared thing itself, plus any data+-- constructors and record fields, class methods and associated families, or pattern synonym record fields.+-- Class default methods and instance method definitions define names declared elsewhere, so they are not+-- included, but data constructors of associated data instances are. namesBoundInDec :: Dec -> [Name]-namesBoundInDec (FunD name _)                       = [name]-namesBoundInDec (ValD pat _ _)                      = namesBoundInPat pat--#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 800-namesBoundInDec (DataD _ name _ _ _ _)              = [name]-namesBoundInDec (NewtypeD _ name _ _ _ _)           = [name]-#else-namesBoundInDec (DataD _ name _ _ _)                = [name]-namesBoundInDec (NewtypeD _ name _ _ _)             = [name]-#endif--namesBoundInDec (TySynD name _ _)                   = [name]-namesBoundInDec (ClassD _ name _ _ _)               = [name]-namesBoundInDec (ForeignD (ImportF _ _ _ name _))   = [name]--#if defined(__GLASGOW_HASKELL__)-#if __GLASGOW_HASKELL__ >= 800-namesBoundInDec (OpenTypeFamilyD (TypeFamilyHead name _ _ _))     = [name]-namesBoundInDec (ClosedTypeFamilyD (TypeFamilyHead name _ _ _) _) = [name]-#elif __GLASGOW_HASKELL__ >= 612-namesBoundInDec (FamilyD _ name _ _)                = [name]-#endif+namesBoundInDec dec = case dec of+    FunD name _                                       -> [name]+    ValD pat _ _                                      -> namesBoundInPat pat+    DataD _ name _ _ cons _                           -> name : concatMap namesBoundInCon cons+    NewtypeD _ name _ _ con _                         -> name : namesBoundInCon con+#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 906+    TypeDataD name _ _ cons                           -> name : concatMap namesBoundInCon cons #endif+    TySynD name _ _                                   -> [name]+    ClassD _ name _ _ decs                            -> name : concatMap namesBoundInClassDec decs+    ForeignD (ImportF _ _ _ name _)                   -> [name]+    OpenTypeFamilyD (TypeFamilyHead name _ _ _)       -> [name]+    ClosedTypeFamilyD (TypeFamilyHead name _ _ _) _   -> [name]+    DataFamilyD name _ _                              -> [name]+    DataInstD _ _ _ _ cons _                          -> concatMap namesBoundInCon cons+    NewtypeInstD _ _ _ _ con _                        -> namesBoundInCon con+    InstanceD _ _ _ decs                              -> concatMap namesBoundInInstanceDec decs+    PatSynD name (RecordPatSyn fields) _ _            -> name : fields+    PatSynD name _ _ _                                -> [name]+    _                                                 -> []+  where+    namesBoundInClassDec d = case d of+        SigD name _ -> [name]+        OpenTypeFamilyD {} -> namesBoundInDec d+        DataFamilyD {} -> namesBoundInDec d+        _ -> []+    namesBoundInInstanceDec d = case d of+        DataInstD {} -> namesBoundInDec d+        NewtypeInstD {} -> namesBoundInDec d+        _ -> [] -namesBoundInDec _                                   = []+-- | Determines the data constructor names and record field names bound by a constructor.+namesBoundInCon :: Con -> [Name]+namesBoundInCon con = case con of+    NormalC name _          -> [name]+    RecC name fields        -> name : [ f | (f, _, _) <- fields ]+    InfixC _ name _         -> [name]+    ForallC _ _ con'        -> namesBoundInCon con'+    GadtC names _ _         -> names+    RecGadtC names fields _ -> names ++ [ f | (f, _, _) <- fields ]  genericalizeName :: Name -> Name genericalizeName = mkName . nameBase@@ -140,76 +147,150 @@ headOfType ArrowT = ''(->) headOfType ListT = ''[] headOfType (AppT t _) = headOfType t-#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 612 headOfType (SigT t _) = headOfType t-#endif-#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 702 headOfType (UnboxedTupleT n) = unboxedTupleTypeName n+headOfType (UnboxedSumT n) = unboxedSumTypeName n+headOfType (PromotedTupleT n) = tupleDataName n+headOfType PromotedNilT = '[]+headOfType PromotedConsT = '(:)+headOfType StarT = ''Kind.Type+headOfType ConstraintT = ''Kind.Constraint+#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 904+headOfType EqualityT = ''(~) #endif-#if defined (__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 704-headOfType ty = error $ "headOfType: Unhandled type: " ++ show ty+#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 900+headOfType MulArrowT = ''FUN #endif+headOfType (PromotedT name) = name+headOfType (ParensT t) = headOfType t+headOfType (InfixT _ name _) = name+#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 808+headOfType (AppKindT t _) = headOfType t+#endif+#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 810+headOfType (ForallVisT _ t) = headOfType t+#endif+#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 904+headOfType (PromotedInfixT _ name _) = name+#endif+-- A chain of unresolved infix applications: if every operator in it is the same, that operator is the head+-- whatever its fixity. Otherwise the head depends on fixities, which are not available here.+headOfType ty+  | op : ops <- unresolvedOps ty =+      if all (== op) ops+        then op+        else error $ "headOfType: the head of an unresolved infix type with different operators "+          ++ "depends on their fixities: " ++ show ty+  where+    unresolvedOps t = case t of+      UInfixT l n r -> unresolvedOps l ++ n : unresolvedOps r+#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 904+      PromotedUInfixT l n r -> unresolvedOps l ++ n : unresolvedOps r+#endif+      _ -> []+headOfType ty = error $ "headOfType: Unhandled type: " ++ show ty +-- | Determines whether a type variable occurs free in a type, including in kinds and contexts.+-- Binders in a 'forall' telescope scope over the kinds of later binders and over the body. occursInType :: Name -> Type -> Bool-occursInType var ty = case ty of-        ForallT bndrs _ ty'-            | any (var ==) (map tvName bndrs)-                -> False-            | otherwise-                -> occursInType var ty'-        VarT name-            | name == var -> True-            | otherwise   -> False-        AppT ty1 ty2 -> occursInType var ty1 || occursInType var ty2-#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 612-        SigT ty' _ -> occursInType var ty'+occursInType var = goType+  where+    goType :: Type -> Bool+    goType ty = case ty of+        VarT name -> name == var+        ForallT bndrs cxt1 ty' -> goBndrs [(tvName b, goData b) | b <- bndrs] (any goType cxt1 || goType ty')+#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 810+        ForallVisT bndrs ty' -> goBndrs [(tvName b, goData b) | b <- bndrs] (goType ty') #endif-        _ -> False+        -- Every other constructor binds nothing, so just look at all of its sub-terms.+        _ -> or (gmapQ goData ty) +    goData :: Data d => d -> Bool+    goData d = case cast d of+        Just ty -> goType ty+        Nothing -> or (gmapQ goData d)++    -- Each binder is given as its name and whether 'var' occurs in its kind.+    goBndrs :: [(Name, Bool)] -> Bool -> Bool+    goBndrs bndrs body = foldr (\(name, inKind) rest -> inKind || (name /= var && rest)) body bndrs+ -- | Assuming that we're building an instance of the form C (T v_1 ... v_(n-1)) for some GADT T, this function -- takes a list of the variables v_1 ... v_(n-1) used in the instance head, as well as the result type of some data -- constructor, say T x_1 ... x_(n-1) x_n, as well as the type t of some argument to it, and substitutes any of--- x_i (1 <= i <= n-1) occurring in t for the corresponding v_i, taking care to avoid name capture by foralls in t.+-- x_i (1 <= i <= n-1) occurring free in t (including in kinds) for the corresponding v_i, taking care to avoid+-- name capture by foralls in t: a forall-bound variable whose name clashes with one of the v_i is renamed.+-- Free variables of t that are not among x_1 ... x_(n-1), such as existentially quantified variables or the+-- index x_n, are left unchanged; it is up to the caller to ensure they do not share a name with any v_i. substVarsWith   :: [Name] -- Names of variables used in the instance head in argument order   -> Type -- Result type of constructor   -> Type -- Type of argument to the constructor   -> Type -- Type of argument with variables substituted for instance head variables.-substVarsWith topVars resultType argType = subst Set.empty argType+substVarsWith topVars resultType argType = subst Map.empty argType   where     topVars' = reverse topVars-    AppT resultType' _indexType = resultType-    subst :: Set Name -> Type -> Type+    -- The result type without its index, x_n.+    resultType' = case unwrapSpine resultType of+      AppT f _indexType -> f+      _ -> error $ "substVarsWith: result type is not an application: " ++ show resultType++    -- Looks through syntax that does not change which type constructor is applied to which parameters.+    unwrapSpine t = case t of+      ParensT t' -> unwrapSpine t'+      SigT t' _ -> unwrapSpine t'+#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 808+      AppKindT t' _ -> unwrapSpine t'+#endif+      _ -> t++    -- Looks through syntax that does not change whether a parameter is a variable.+    unwrapParam t = case t of+      ParensT t' -> unwrapParam t'+      SigT t' _ -> unwrapParam t'+      _ -> t++    -- Names that a forall-bound variable must not be called, lest it capture a substituted variable.+    avoid = Set.fromList topVars+    -- Names that a renamed forall-bound variable must also not be called.+    taken = Set.union avoid (Set.fromList (listify (const True :: Name -> Bool) argType))+    fresh n = until (\n' -> not (Set.member n' taken)) prime (prime n)+    prime n = mkName (nameBase n ++ "'")++    -- Brings a telescope of binders into scope. Each binder's kind is in the scope of the earlier binders.+    -- Returns the environment for the body, mapping each bound variable to its (possibly new) name.+    bindAll :: Map Name Name -> [TyVarBndr_ flag] -> (Map Name Name, [TyVarBndr_ flag])+    bindAll env [] = (env, [])+    bindAll env (b:rest) =+      let n = tvName b+          n' = if Set.member n avoid then fresh n else n+          (env', rest') = bindAll (Map.insert n n' env) rest+      in (env', mapTVName (const n') (mapTVKind (subst env) b) : rest')++    -- The environment maps each variable bound by an enclosing forall to its (possibly new) name.+    subst :: Map Name Name -> Type -> Type     subst bs ty = case ty of       -- Several of the following cases could all be covered by an "x -> x" case, but       -- I'd rather know if new cases need to be handled specially in future versions       -- of Template Haskell.       ForallT bndrs cxt1 t ->-        let bs' = Set.union bs (Set.fromList (map tvName bndrs))-        in ForallT bndrs (map (subst bs') cxt1) (subst bs' t)+        let (bs', bndrs') = bindAll bs bndrs+        in ForallT bndrs' (map (subst bs') cxt1) (subst bs' t)       AppT f x -> AppT (subst bs f) (subst bs x)-      SigT t k -> SigT (subst bs t) k-      VarT v -> if Set.member v bs-        then VarT v-        else VarT (findVar v topVars' resultType')+      SigT t k -> SigT (subst bs t) (subst bs k)+      VarT v -> case Map.lookup v bs of+        Just v' -> VarT v'+        Nothing -> VarT (findVar v topVars' resultType')       ConT n -> ConT n       TupleT k -> TupleT k       ArrowT -> ArrowT       ListT -> ListT       UnboxedTupleT k -> UnboxedTupleT k-#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 800       InfixT t1 x t2 -> InfixT (subst bs t1) x (subst bs t2)       ParensT t -> ParensT (subst bs t)       UInfixT t1 x t2 -> UInfixT (subst bs t1) x (subst bs t2)       WildCardT -> WildCardT-#endif-#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 802       UnboxedSumT k -> UnboxedSumT k-#endif-#if defined (__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 710       EqualityT -> EqualityT-#endif-#if defined (__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 706       ConstraintT -> ConstraintT       LitT l -> LitT l       PromotedConsT -> PromotedConsT@@ -217,7 +298,6 @@       PromotedT n -> PromotedT n       PromotedTupleT k -> PromotedTupleT k       StarT -> StarT-#endif #if defined (__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 904       PromotedInfixT t1 x t2 -> PromotedInfixT (subst bs t1) x (subst bs t2)       PromotedUInfixT t1 x t2 -> PromotedUInfixT (subst bs t1) x (subst bs t2)@@ -225,31 +305,58 @@ #if defined (__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 900       MulArrowT -> MulArrowT #endif-#if defined (__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 900-      ForallVisT xs t -> ForallVisT xs (subst bs t)+#if defined (__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 810+      ForallVisT bndrs t ->+        let (bs', bndrs') = bindAll bs bndrs+        in ForallVisT bndrs' (subst bs' t) #endif #if defined (__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 808       ImplicitParamT s t -> ImplicitParamT s (subst bs t)       AppKindT f x -> AppKindT (subst bs f) (subst bs x) #endif -    findVar v (tv:_) (AppT _ (VarT v')) | v == v' = tv-    findVar v (_:tvs) (AppT t (VarT _)) = findVar v tvs t-    findVar v _ _ = error $ "substVarsWith: couldn't look up variable substitution for " ++ show v-      ++ " with topVars: " ++ show topVars ++ " resultType: " ++ show resultType ++ " argType: " ++ show argType+    -- Walks the parameters of the result type from the right, alongside the instance head variables.+    findVar v (tv:tvs) t | AppT f x <- unwrapSpine t = case unwrapParam x of+      VarT v' | v == v' -> tv+      -- Skip any other parameter, which may be a variable or (in a GADT) a refined type.+      _ -> findVar v tvs f+    -- Not a parameter of the result type (e.g. an existential or the index): leave it alone.+    findVar v _ _ = v  -- | Determine the arity of a kind. -- Starting in template-haskell 2.8.0.0, 'Kind' and 'Type' became synonymous. kindArity :: Kind -> Int kindArity k = case k of   ForallT _ _ t -> kindArity t-  AppT (AppT ArrowT _) t -> 1 + kindArity t+  AppT f t | isArrowApp f -> 1 + kindArity t+  InfixT _ n t | n == ''(->) -> 1 + kindArity t+  UInfixT _ n t | n == ''(->) -> 1 + kindArity t   SigT t _ -> kindArity t-#if defined (__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 800   ParensT t -> kindArity t+#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 810+  -- Each visibly quantified variable (forall k ->) is an argument.+  ForallVisT bndrs t -> length bndrs + kindArity t #endif   _ -> 0+  where+    -- Is this an arrow applied to its argument, i.e. the @(->) arg@ in @arg -> result@?+    isArrowApp t = case t of+      AppT arrow _ -> isArrow arrow+      ParensT t' -> isArrowApp t'+      SigT t' _ -> isArrowApp t'+      _ -> False +    isArrow t = case t of+      ArrowT -> True+      ConT n -> n == ''(->)+#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 900+      -- A multiplicity arrow applied to its multiplicity, as in arg %m -> result.+      AppT MulArrowT _ -> True+#endif+      ParensT t' -> isArrow t'+      SigT t' _ -> isArrow t'+      _ -> False+ -- | Given the name of a type constructor, determine its full arity tyConArity :: Name -> Q Int tyConArity n = do@@ -259,7 +366,7 @@ -- | Given the name of a type constructor, determine a list of type variables bound as parameters by -- its declaration, and the arity of the kind of type being defined (i.e. how many more arguments would -- need to be supplied in addition to the bound parameters in order to obtain an ordinary type of kind *).--- If the supplied 'Name' is anything other than a data or newtype, produces an error.+-- If the supplied 'Name' is anything other than a data, newtype or @type data@ declaration, produces an error. #if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ < 908 tyConArity' :: Name -> Q ([TyVarBndrUnit], Int) #else@@ -270,15 +377,23 @@   return $ case r of     TyConI (DataD _ _ ts mk _ _) -> (ts, fromMaybe 0 (fmap kindArity mk))     TyConI (NewtypeD _ _ ts mk _ _) -> (ts, fromMaybe 0 (fmap kindArity mk))+#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 906+    TyConI (TypeDataD _ ts mk _) -> (ts, fromMaybe 0 (fmap kindArity mk))+#endif     _ -> error $ "tyConArity': Supplied name reified to something other than a data declaration: " ++ show n --- | Determine the constructors bound by a data or newtype declaration. Errors out if supplied with another--- sort of declaration.+-- | Determine the constructors bound by a data, newtype or @type data@ declaration, or a data or newtype+-- instance. Errors out if supplied with another sort of declaration. decCons :: Dec -> [Con] decCons d = case d of   DataD _ _ _ _ cs _ -> cs   NewtypeD _ _ _ _ c _ -> [c]-  _ -> error "decCons: Declaration found was not a data or newtype declaration."+#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 906+  TypeDataD _ _ _ cs -> cs+#endif+  DataInstD _ _ _ _ cs _ -> cs+  NewtypeInstD _ _ _ _ c _ -> [c]+  _ -> error "decCons: Declaration found was not a data, newtype or type data declaration, or a data or newtype instance."  -- | Determine the arity of a data constructor. conArity :: Con -> Int
+ test/Fixtures.hs view
@@ -0,0 +1,90 @@+{-# LANGUAGE CPP, GADTs, KindSignatures, PolyKinds, TemplateHaskell #-}+#if __GLASGOW_HASKELL__ >= 810+{-# LANGUAGE RankNTypes, StandaloneKindSignatures #-}+#endif+#if __GLASGOW_HASKELL__ >= 906+{-# LANGUAGE TypeData #-}+#endif++-- | Declarations to reify in compile-time tests, and helpers for splicing in+-- the results of running library functions on them.+module Fixtures+  ( arityCases+  , KindSig (..)+  , Mixed (..)+  , NewtypeKindSig (..)+#if __GLASGOW_HASKELL__ >= 810+  , Standalone (..)+  , VisibleForall (..)+#endif+#if __GLASGOW_HASKELL__ >= 906+  , TypeData (..)+#endif+  ) where++import Control.Exception (ErrorCall (..), evaluate, try)+import Data.Functor.Compose (Compose)+import Data.Functor.Const (Const)+import Data.Kind (Type)+import Data.Proxy (Proxy)+import Language.Haskell.TH (Exp, Name, Q, runIO)+import Language.Haskell.TH.Syntax (lift)+import Language.Haskell.TH.Extras (tyConArity')++data KindSig :: Type -> Type -> Type where+  KindSig :: KindSig a b++data Mixed a :: Type -> Type where+  Mixed :: Mixed a b++newtype NewtypeKindSig :: Type -> Type where+  NewtypeKindSig :: Int -> NewtypeKindSig a++#if __GLASGOW_HASKELL__ >= 810+type Standalone :: Type -> Type -> Type+data Standalone a b = Standalone++type VisibleForall :: forall k -> k -> Type+data VisibleForall k a = VisibleForall+#endif++#if __GLASGOW_HASKELL__ >= 906+type data TypeData a b = TypeDataA | TypeDataB+#endif++-- | The type constructors to test, with their expected arities.+arityFixtures :: [(Name, Int)]+arityFixtures =+  [ (''Maybe, 1)+  , (''Either, 2)+  , (''Proxy, 1)+  , (''Const, 2)+  , (''Compose, 3)+  , (''KindSig, 2)+  , (''Mixed, 2)+  , (''NewtypeKindSig, 1)+#if __GLASGOW_HASKELL__ >= 810+  , (''Standalone, 2)+  , (''VisibleForall, 2)+#endif+#if __GLASGOW_HASKELL__ >= 906+  , (''TypeData, 2)+#endif+  ]++-- | Splices in a list of @(name, result, expected)@, where the result is that of+-- 'tyConArity' on the name at compile time, or the message if it called+-- 'error', so that an error is reported as a test failure at run time rather+-- than failing compilation.+arityCases :: Q Exp+arityCases = do+  cases <- mapM arityCase arityFixtures+  lift cases+  where+    arityCase :: (Name, Int) -> Q (String, Either String Int, Int)+    arityCase (name, expected) = do+      -- tyConArity' returns its result lazily, so any error is raised only+      -- when the result is forced, inside 'try'.+      result <- tyConArity' name+      arity <- runIO (try (evaluate (let (ts, ka) = result in length ts + ka)))+      pure (show name, either (\(ErrorCall msg) -> Left msg) Right arity, expected)
+ test/Gen.hs view
@@ -0,0 +1,660 @@+{-# 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+      _ -> []
+ test/Main.hs view
@@ -0,0 +1,189 @@+{-# LANGUAGE OverloadedStrings, ScopedTypeVariables, TemplateHaskell #-}++module Main (main) where++import qualified Data.Map as Map+import qualified Data.Set as Set+import Control.Exception (ErrorCall, evaluate, try)+import Control.Monad (forM_)+import Fixtures (arityCases)+import Gen+import Hedgehog+import Hedgehog.Main (defaultMain)+import Language.Haskell.TH (mkName, nameBase)+import Language.Haskell.TH.Datatype.TyVarBndr (tvName)+import Language.Haskell.TH.Extras++main :: IO ()+main =+  defaultMain+    [ checkParallel $ Group "Language.Haskell.TH.Extras"+        [ ("prop_occursInType", prop_occursInType)+        , ("prop_namesBoundInPat", prop_namesBoundInPat)+        , ("prop_substVarsWith", prop_substVarsWith)+        , ("prop_headOfType", prop_headOfType)+        , ("prop_kindArity", prop_kindArity)+        , ("prop_substVarsWith_refined", prop_substVarsWith_refined)+        , ("prop_namesBoundInDec", prop_namesBoundInDec)+        , ("prop_genericalizeDecs", prop_genericalizeDecs)+        , ("prop_headOfType_builtin", prop_headOfType_builtin)+        , ("prop_substVarsWith_existential", prop_substVarsWith_existential)+        , ("prop_tyConArity", prop_tyConArity)+        , ("prop_decCons", prop_decCons)+        , ("prop_conAccessors", prop_conAccessors)+        , ("prop_substVarsWith_wrapped", prop_substVarsWith_wrapped)+        , ("prop_kindArity_anyArrow", prop_kindArity_anyArrow)+        , ("prop_headOfType_unresolved", prop_headOfType_unresolved)+        , ("prop_headOfType_any", prop_headOfType_any)+        ]+    ]++-- | 'occursInType' agrees with the reference free-variable function for+-- every kind of type.+prop_occursInType :: Property+prop_occursInType = withTests 1000 . property $ do+  ty <- forAll genType+  v <- forAll genVarName+  occursInType v ty === Set.member v (freeVars ty)++-- | 'namesBoundInPat' finds every variable bound by a pattern, in order.+prop_namesBoundInPat :: Property+prop_namesBoundInPat = withTests 1000 . property $ do+  pat <- forAll genPat+  namesBoundInPat pat === patVars pat++-- | 'substVarsWith' renames exactly the free variables of the argument type:+-- no free variable is missed and no substituted variable is captured by a+-- binder in the argument type.+prop_substVarsWith :: Property+prop_substVarsWith = withTests 1000 . property $ checkSubstCase =<< forAll genSubstCase++-- | As 'prop_substVarsWith', but for GADT constructors whose result type refines+-- some of the type constructor's parameters to concrete types.+prop_substVarsWith_refined :: Property+prop_substVarsWith_refined = withTests 1000 . property $ checkSubstCase =<< forAll genRefinedSubstCase++-- | As 'prop_substVarsWith', but the argument type also mentions existential+-- variables and the index variable, which are not parameters of the result+-- type and so must be left unchanged.+prop_substVarsWith_existential :: Property+prop_substVarsWith_existential = withTests 1000 . property $ checkSubstCase =<< forAll genExistentialSubstCase++-- | As 'prop_substVarsWith', but the result type is written with parentheses,+-- kind signatures and kind applications, which must not change the result.+prop_substVarsWith_wrapped :: Property+prop_substVarsWith_wrapped = withTests 1000 . property $ checkSubstCase =<< forAll genWrappedSubstCase++checkSubstCase :: SubstCase -> PropertyT IO ()+checkSubstCase sc = do+  let result = substVarsWith (scTopVars sc) (scResultType sc) (scArgType sc)+      rename v = Map.findWithDefault v v (scExpected sc)+  -- Force the whole result here, so that an 'error' call is reported as a+  -- failure of this property rather than escaping from 'annotateShow'.+  _ <- eval (length (show result))+  annotateShow result+  freeVars result === Set.map rename (freeVars (scArgType sc))++-- | 'headOfType' sees through applications, parentheses, kind signatures,+-- foralls and kind applications to the name at the head of a type.+prop_headOfType :: Property+prop_headOfType = withTests 1000 . property $ do+  (ty, name) <- forAll genHeadedType+  headOfType ty === name++-- | 'kindArity' counts every argument a kind takes, including visible+-- dependent quantification, looking through parentheses, kind signatures and+-- invisible foralls.+prop_kindArity :: Property+prop_kindArity = withTests 1000 . property $ do+  (k, n) <- forAll genKindWithArity+  kindArity k === n++-- | 'namesBoundInDec' finds every name a declaration brings into scope,+-- including data constructors, record fields, class methods, associated+-- families and pattern synonym fields.+prop_namesBoundInDec :: Property+prop_namesBoundInDec = withTests 1000 . property $ do+  dec <- forAll genDec+  namesBoundInDec dec === decNames dec++-- | 'genericalizeDecs' replaces every occurrence of every name bound at the top+-- level of the declarations with a generic name, and leaves all other names+-- (including fresh ones bound locally) alone.+prop_genericalizeDecs :: Property+prop_genericalizeDecs = withTests 1000 . property $ do+  decs <- forAll genQuotedDecs+  let bound = Set.fromList (concatMap decNames decs)+      expected n = if Set.member n bound then mkName (nameBase n) else n+  allNames (genericalizeDecs decs) === map expected (allNames decs)++-- | 'headOfType' finds the type constructor at the head of a type whose head is+-- a built-in type constructor with dedicated Template Haskell syntax, such as+-- unboxed sums, promoted lists and tuples, 'Type', 'Constraint', equality and+-- the multiplicity-polymorphic arrow.+prop_headOfType_builtin :: Property+prop_headOfType_builtin = withTests 1000 . property $ do+  (ty, name) <- forAll genBuiltinHeadedType+  headOfType ty === name++-- | 'tyConArity' gives the number of type arguments a data type or newtype+-- takes, however its parameters are declared: binders, kind signatures,+-- standalone kind signatures or @type data@. The arities are computed at+-- compile time by reifying the declarations in "Fixtures".+prop_tyConArity :: Property+prop_tyConArity = withTests 1 . property $+  forM_ ($(arityCases) :: [(String, Either String Int, Int)]) $ \(name, result, expected) ->+    (name, result) === (name, Right expected)++-- | 'decCons' returns the data constructors of every kind of declaration that+-- declares them: data, newtype and @type data@ declarations, and data and+-- newtype instances.+prop_decCons :: Property+prop_decCons = withTests 1000 . property $ do+  (dec, cons) <- forAll genDataLikeDec+  result <- eval (decCons dec)+  result === cons++-- | 'nameOfCon', 'argTypesOfCon', 'conArity' and 'varsBoundInCon' agree with a+-- reference for constructors of every form, through any number of foralls.+-- 'nameOfCon' is only checked for constructors declaring a single name, since+-- it is documented to fail otherwise.+prop_conAccessors :: Property+prop_conAccessors = withTests 1000 . property $ do+  con <- forAll genCon+  let ci = conInfo con+  argTypesOfCon con === ciArgTypes ci+  conArity con === length (ciArgTypes ci)+  map tvName (varsBoundInCon con) === ciBinders ci+  case ciNames ci of+    [name] -> nameOfCon con === name+    _ -> success++-- | As 'prop_kindArity', but with arrows written in any of the ways Template+-- Haskell can represent them, which must not change the arity.+prop_kindArity_anyArrow :: Property+prop_kindArity_anyArrow = withTests 1000 . property $ do+  (k, n) <- forAll genKindWithArityAnyArrow+  kindArity k === n++-- | 'headOfType' finds the operator at the head of a chain of unresolved infix+-- applications when every operator in the chain is the same, since the head+-- is then that operator whatever its fixity.+prop_headOfType_unresolved :: Property+prop_headOfType_unresolved = withTests 1000 . property $ do+  (ty, name) <- forAll genUnresolvedHeadedType+  result <- eval (headOfType ty)+  result === name++-- | On arbitrary types, 'headOfType' returns the head wherever the type has one,+-- and calls 'error' (rather than returning something wrong) wherever it does+-- not.+prop_headOfType_any :: Property+prop_headOfType_any = withTests 2000 . property $ do+  ty <- forAll genType+  result <- evalIO (try (evaluate (headOfType ty)))+  classify "has a head" (typeHead ty /= Nothing)+  classify "has no head" (typeHead ty == Nothing)+  case result of+    Left (_ :: ErrorCall) -> typeHead ty === Nothing+    Right name -> Just name === typeHead ty
th-extras.cabal view
@@ -1,5 +1,5 @@ name:                   th-extras-version:                0.0.0.9+version:                0.1.0.0 stability:              experimental  cabal-version:          >= 1.10@@ -31,8 +31,6 @@                         GHC == 8.8.4                         GHC == 8.6.5                         GHC == 8.4.4-                        GHC == 8.2.2-                        GHC == 8.0.2  extra-source-files:     ReadMe.md                       , ChangeLog.md@@ -45,9 +43,25 @@   hs-source-dirs:       src   ghc-options:          -Wall   exposed-modules:      Language.Haskell.TH.Extras-  build-depends:        base >= 4.9 && < 5+  build-depends:        base >= 4.11 && < 5                       , containers < 0.9                       , template-haskell < 2.25                       , th-abstraction >= 0.4 && < 0.8                       , syb < 0.8+  default-language:     Haskell2010++test-suite test+  type:                 exitcode-stdio-1.0+  hs-source-dirs:       test+  main-is:              Main.hs+  other-modules:        Fixtures+                      , Gen+  ghc-options:          -Wall -threaded+  build-depends:        base >= 4.11 && < 5+                      , containers+                      , hedgehog >= 1.0 && < 1.8+                      , syb+                      , template-haskell+                      , th-abstraction+                      , th-extras   default-language:     Haskell2010