never executed always true always false
    1 
    2 {-# LANGUAGE FlexibleInstances  #-}
    3 {-# LANGUAGE LambdaCase         #-}
    4 {-# LANGUAGE DeriveDataTypeable #-}
    5 
    6 {-
    7 (c) The University of Glasgow 2006
    8 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
    9 
   10 
   11 The @TyCon@ datatype
   12 -}
   13 
   14 module GHC.Core.TyCon(
   15         -- * Main TyCon data types
   16         TyCon,
   17         AlgTyConRhs(..), visibleDataCons,
   18         AlgTyConFlav(..), isNoParent,
   19         FamTyConFlav(..), Role(..), Injectivity(..),
   20         RuntimeRepInfo(..), TyConFlavour(..),
   21 
   22         -- * TyConBinder
   23         TyConBinder, TyConBndrVis(..), TyConTyCoBinder,
   24         mkNamedTyConBinder, mkNamedTyConBinders,
   25         mkRequiredTyConBinder,
   26         mkAnonTyConBinder, mkAnonTyConBinders,
   27         tyConBinderArgFlag, tyConBndrVisArgFlag, isNamedTyConBinder,
   28         isVisibleTyConBinder, isInvisibleTyConBinder,
   29 
   30         -- ** Field labels
   31         tyConFieldLabels, lookupTyConFieldLabel,
   32 
   33         -- ** Constructing TyCons
   34         mkAlgTyCon,
   35         mkClassTyCon,
   36         mkFunTyCon,
   37         mkPrimTyCon,
   38         mkKindTyCon,
   39         mkLiftedPrimTyCon,
   40         mkTupleTyCon,
   41         mkSumTyCon,
   42         mkDataTyConRhs,
   43         mkLevPolyDataTyConRhs,
   44         mkSynonymTyCon,
   45         mkFamilyTyCon,
   46         mkPromotedDataCon,
   47         mkTcTyCon,
   48         noTcTyConScopedTyVars,
   49 
   50         -- ** Predicates on TyCons
   51         isAlgTyCon, isVanillaAlgTyCon, isConstraintKindCon,
   52         isClassTyCon, isFamInstTyCon,
   53         isFunTyCon,
   54         isPrimTyCon,
   55         isTupleTyCon, isUnboxedTupleTyCon, isBoxedTupleTyCon,
   56         isUnboxedSumTyCon, isPromotedTupleTyCon,
   57         isTypeSynonymTyCon,
   58         mustBeSaturated,
   59         isPromotedDataCon, isPromotedDataCon_maybe,
   60         isKindTyCon, isLiftedTypeKindTyConName,
   61         isTauTyCon, isFamFreeTyCon, isForgetfulSynTyCon,
   62 
   63         isDataTyCon,
   64         isEnumerationTyCon,
   65         isNewTyCon, isAbstractTyCon,
   66         isFamilyTyCon, isOpenFamilyTyCon,
   67         isTypeFamilyTyCon, isDataFamilyTyCon,
   68         isOpenTypeFamilyTyCon, isClosedSynFamilyTyConWithAxiom_maybe,
   69         tyConInjectivityInfo,
   70         isBuiltInSynFamTyCon_maybe,
   71         isUnliftedTyCon,
   72         isGadtSyntaxTyCon, isInjectiveTyCon, isGenerativeTyCon, isGenInjAlgRhs,
   73         isTyConAssoc, tyConAssoc_maybe, tyConFlavourAssoc_maybe,
   74         isImplicitTyCon,
   75         isTyConWithSrcDataCons,
   76         isTcTyCon, setTcTyConKind,
   77         tcHasFixedRuntimeRep,
   78         isConcreteTyCon,
   79 
   80         -- ** Extracting information out of TyCons
   81         tyConName,
   82         tyConSkolem,
   83         tyConKind,
   84         tyConUnique,
   85         tyConTyVars, tyConVisibleTyVars,
   86         tyConCType, tyConCType_maybe,
   87         tyConDataCons, tyConDataCons_maybe,
   88         tyConSingleDataCon_maybe, tyConSingleDataCon,
   89         tyConAlgDataCons_maybe,
   90         tyConSingleAlgDataCon_maybe,
   91         tyConFamilySize,
   92         tyConStupidTheta,
   93         tyConArity,
   94         tyConNullaryTy,
   95         tyConRoles,
   96         tyConFlavour,
   97         tyConTuple_maybe, tyConClass_maybe, tyConATs,
   98         tyConFamInst_maybe, tyConFamInstSig_maybe, tyConFamilyCoercion_maybe,
   99         tyConFamilyResVar_maybe,
  100         synTyConDefn_maybe, synTyConRhs_maybe,
  101         famTyConFlav_maybe, famTcResVar,
  102         algTyConRhs,
  103         newTyConRhs, newTyConEtadArity, newTyConEtadRhs,
  104         unwrapNewTyCon_maybe, unwrapNewTyConEtad_maybe,
  105         newTyConDataCon_maybe,
  106         algTcFields,
  107         tyConRuntimeRepInfo,
  108         tyConBinders, tyConResKind, tyConInvisTVBinders,
  109         tcTyConScopedTyVars, tcTyConIsPoly,
  110         mkTyConTagMap,
  111 
  112         -- ** Manipulating TyCons
  113         expandSynTyCon_maybe,
  114         newTyConCo, newTyConCo_maybe,
  115         pprPromotionQuote, mkTyConKind,
  116 
  117         -- ** Predicated on TyConFlavours
  118         tcFlavourIsOpen,
  119 
  120         -- * Runtime type representation
  121         TyConRepName, tyConRepName_maybe,
  122         mkPrelTyConRepName,
  123         tyConRepModOcc,
  124 
  125         -- * Primitive representations of Types
  126         PrimRep(..), PrimElemRep(..),
  127         primElemRepToPrimRep,
  128         isVoidRep, isGcPtrRep,
  129         primRepSizeB,
  130         primElemRepSizeB,
  131         primRepIsFloat,
  132         primRepsCompatible,
  133         primRepCompatible,
  134 
  135 ) where
  136 
  137 import GHC.Prelude
  138 import GHC.Platform
  139 
  140 import {-# SOURCE #-} GHC.Core.TyCo.Rep
  141    ( Kind, Type, PredType, mkForAllTy, mkFunTyMany, mkTyConTy_ )
  142 import {-# SOURCE #-} GHC.Core.TyCo.Ppr
  143    ( pprType )
  144 import {-# SOURCE #-} GHC.Builtin.Types
  145    ( runtimeRepTyCon, constraintKind, levityTyCon
  146    , multiplicityTyCon
  147    , vecCountTyCon, vecElemTyCon, liftedTypeKind )
  148 import {-# SOURCE #-} GHC.Core.DataCon
  149    ( DataCon, dataConFieldLabels
  150    , dataConTyCon, dataConFullSig
  151    , isUnboxedSumDataCon )
  152 import GHC.Builtin.Uniques
  153   ( tyConRepNameUnique
  154   , dataConTyRepNameUnique )
  155 
  156 import GHC.Utils.Binary
  157 import GHC.Types.Var
  158 import GHC.Types.Var.Set
  159 import GHC.Core.Class
  160 import GHC.Types.Basic
  161 import GHC.Types.ForeignCall
  162 import GHC.Types.Name
  163 import GHC.Types.Name.Env
  164 import GHC.Core.Coercion.Axiom
  165 import GHC.Builtin.Names
  166 import GHC.Data.Maybe
  167 import GHC.Utils.Outputable
  168 import GHC.Utils.Panic
  169 import GHC.Utils.Panic.Plain
  170 import GHC.Data.FastString.Env
  171 import GHC.Types.FieldLabel
  172 import GHC.Settings.Constants
  173 import GHC.Utils.Misc
  174 import GHC.Types.Unique.Set
  175 import GHC.Unit.Module
  176 
  177 import qualified Data.Data as Data
  178 
  179 {-
  180 -----------------------------------------------
  181         Notes about type families
  182 -----------------------------------------------
  183 
  184 Note [Type synonym families]
  185 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  186 * Type synonym families, also known as "type functions", map directly
  187   onto the type functions in FC:
  188 
  189         type family F a :: *
  190         type instance F Int = Bool
  191         ..etc...
  192 
  193 * Reply "yes" to isTypeFamilyTyCon, and isFamilyTyCon
  194 
  195 * From the user's point of view (F Int) and Bool are simply
  196   equivalent types.
  197 
  198 * A Haskell 98 type synonym is a degenerate form of a type synonym
  199   family.
  200 
  201 * Type functions can't appear in the LHS of a type function:
  202         type instance F (F Int) = ...   -- BAD!
  203 
  204 * Translation of type family decl:
  205         type family F a :: *
  206   translates to
  207     a FamilyTyCon 'F', whose FamTyConFlav is OpenSynFamilyTyCon
  208 
  209         type family G a :: * where
  210           G Int = Bool
  211           G Bool = Char
  212           G a = ()
  213   translates to
  214     a FamilyTyCon 'G', whose FamTyConFlav is ClosedSynFamilyTyCon, with the
  215     appropriate CoAxiom representing the equations
  216 
  217 We also support injective type families -- see Note [Injective type families]
  218 
  219 Note [Data type families]
  220 ~~~~~~~~~~~~~~~~~~~~~~~~~
  221 See also Note [Wrappers for data instance tycons] in GHC.Types.Id.Make
  222 
  223 * Data type families are declared thus
  224         data family T a :: *
  225         data instance T Int = T1 | T2 Bool
  226 
  227   Here T is the "family TyCon".
  228 
  229 * Reply "yes" to isDataFamilyTyCon, and isFamilyTyCon
  230 
  231 * The user does not see any "equivalent types" as they did with type
  232   synonym families.  They just see constructors with types
  233         T1 :: T Int
  234         T2 :: Bool -> T Int
  235 
  236 * Here's the FC version of the above declarations:
  237 
  238         data T a
  239         data R:TInt = T1 | T2 Bool
  240         axiom ax_ti : T Int ~R R:TInt
  241 
  242   Note that this is a *representational* coercion
  243   The R:TInt is the "representation TyCons".
  244   It has an AlgTyConFlav of
  245         DataFamInstTyCon T [Int] ax_ti
  246 
  247 * The axiom ax_ti may be eta-reduced; see
  248   Note [Eta reduction for data families] in GHC.Core.Coercion.Axiom
  249 
  250 * Data family instances may have a different arity than the data family.
  251   See Note [Arity of data families] in GHC.Core.FamInstEnv
  252 
  253 * The data constructor T2 has a wrapper (which is what the
  254   source-level "T2" invokes):
  255 
  256         $WT2 :: Bool -> T Int
  257         $WT2 b = T2 b `cast` sym ax_ti
  258 
  259 * A data instance can declare a fully-fledged GADT:
  260 
  261         data instance T (a,b) where
  262           X1 :: T (Int,Bool)
  263           X2 :: a -> b -> T (a,b)
  264 
  265   Here's the FC version of the above declaration:
  266 
  267         data R:TPair a b where
  268           X1 :: R:TPair Int Bool
  269           X2 :: a -> b -> R:TPair a b
  270         axiom ax_pr :: T (a,b)  ~R  R:TPair a b
  271 
  272         $WX1 :: forall a b. a -> b -> T (a,b)
  273         $WX1 a b (x::a) (y::b) = X2 a b x y `cast` sym (ax_pr a b)
  274 
  275   The R:TPair are the "representation TyCons".
  276   We have a bit of work to do, to unpick the result types of the
  277   data instance declaration for T (a,b), to get the result type in the
  278   representation; e.g.  T (a,b) --> R:TPair a b
  279 
  280   The representation TyCon R:TList, has an AlgTyConFlav of
  281 
  282         DataFamInstTyCon T [(a,b)] ax_pr
  283 
  284 * Notice that T is NOT translated to a FC type function; it just
  285   becomes a "data type" with no constructors, which can be coerced
  286   into R:TInt, R:TPair by the axioms.  These axioms
  287   axioms come into play when (and *only* when) you
  288         - use a data constructor
  289         - do pattern matching
  290   Rather like newtype, in fact
  291 
  292   As a result
  293 
  294   - T behaves just like a data type so far as decomposition is concerned
  295 
  296   - (T Int) is not implicitly converted to R:TInt during type inference.
  297     Indeed the latter type is unknown to the programmer.
  298 
  299   - There *is* an instance for (T Int) in the type-family instance
  300     environment, but it is looked up (via tcLookupDataFamilyInst)
  301     in can_eq_nc (via tcTopNormaliseNewTypeTF_maybe) when trying to
  302     solve representational equalities like
  303          T Int ~R# Bool
  304     Here we look up (T Int), convert it to R:TInt, and then unwrap the
  305     newtype R:TInt.
  306 
  307     It is also looked up in reduceTyFamApp_maybe.
  308 
  309   - It's fine to have T in the LHS of a type function:
  310     type instance F (T a) = [a]
  311 
  312   It was this last point that confused me!  The big thing is that you
  313   should not think of a data family T as a *type function* at all, not
  314   even an injective one!  We can't allow even injective type functions
  315   on the LHS of a type function:
  316         type family injective G a :: *
  317         type instance F (G Int) = Bool
  318   is no good, even if G is injective, because consider
  319         type instance G Int = Bool
  320         type instance F Bool = Char
  321 
  322   So a data type family is not an injective type function. It's just a
  323   data type with some axioms that connect it to other data types.
  324 
  325 * The tyConTyVars of the representation tycon are the tyvars that the
  326   user wrote in the patterns. This is important in GHC.Tc.Deriv, where we
  327   bring these tyvars into scope before type-checking the deriving
  328   clause. This fact is arranged for in TcInstDecls.tcDataFamInstDecl.
  329 
  330 Note [Associated families and their parent class]
  331 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  332 *Associated* families are just like *non-associated* families, except
  333 that they have a famTcParent field of (Just cls_tc), which identifies the
  334 parent class.
  335 
  336 However there is an important sharing relationship between
  337   * the tyConTyVars of the parent Class
  338   * the tyConTyVars of the associated TyCon
  339 
  340    class C a b where
  341      data T p a
  342      type F a q b
  343 
  344 Here the 'a' and 'b' are shared with the 'Class'; that is, they have
  345 the same Unique.
  346 
  347 This is important. In an instance declaration we expect
  348   * all the shared variables to be instantiated the same way
  349   * the non-shared variables of the associated type should not
  350     be instantiated at all
  351 
  352   instance C [x] (Tree y) where
  353      data T p [x] = T1 x | T2 p
  354      type F [x] q (Tree y) = (x,y,q)
  355 
  356 Note [TyCon Role signatures]
  357 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  358 Every tycon has a role signature, assigning a role to each of the tyConTyVars
  359 (or of equal length to the tyConArity, if there are no tyConTyVars). An
  360 example demonstrates these best: say we have a tycon T, with parameters a at
  361 nominal, b at representational, and c at phantom. Then, to prove
  362 representational equality between T a1 b1 c1 and T a2 b2 c2, we need to have
  363 nominal equality between a1 and a2, representational equality between b1 and
  364 b2, and nothing in particular (i.e., phantom equality) between c1 and c2. This
  365 might happen, say, with the following declaration:
  366 
  367   data T a b c where
  368     MkT :: b -> T Int b c
  369 
  370 Data and class tycons have their roles inferred (see inferRoles in GHC.Tc.TyCl.Utils),
  371 as do vanilla synonym tycons. Family tycons have all parameters at role N,
  372 though it is conceivable that we could relax this restriction. (->)'s and
  373 tuples' parameters are at role R. Each primitive tycon declares its roles;
  374 it's worth noting that (~#)'s parameters are at role N. Promoted data
  375 constructors' type arguments are at role R. All kind arguments are at role
  376 N.
  377 
  378 Note [Unboxed tuple RuntimeRep vars]
  379 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  380 The contents of an unboxed tuple may have any representation. Accordingly,
  381 the kind of the unboxed tuple constructor is runtime-representation
  382 polymorphic.
  383 
  384 Type constructor (2 kind arguments)
  385    (#,#) :: forall (q :: RuntimeRep) (r :: RuntimeRep).
  386                    TYPE q -> TYPE r -> TYPE (TupleRep [q, r])
  387 Data constructor (4 type arguments)
  388    (#,#) :: forall (q :: RuntimeRep) (r :: RuntimeRep)
  389                    (a :: TYPE q) (b :: TYPE r). a -> b -> (# a, b #)
  390 
  391 These extra tyvars (q and r) cause some delicate processing around tuples,
  392 where we need to manually insert RuntimeRep arguments.
  393 The same situation happens with unboxed sums: each alternative
  394 has its own RuntimeRep.
  395 For boxed tuples, there is no representation polymorphism, and therefore
  396 we add RuntimeReps only for the unboxed version.
  397 
  398 Type constructor (no kind arguments)
  399    (,) :: Type -> Type -> Type
  400 Data constructor (2 type arguments)
  401    (,) :: forall a b. a -> b -> (a, b)
  402 
  403 
  404 Note [Injective type families]
  405 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  406 We allow injectivity annotations for type families (both open and closed):
  407 
  408   type family F (a :: k) (b :: k) = r | r -> a
  409   type family G a b = res | res -> a b where ...
  410 
  411 Injectivity information is stored in the `famTcInj` field of `FamilyTyCon`.
  412 `famTcInj` maybe stores a list of Bools, where each entry corresponds to a
  413 single element of `tyConTyVars` (both lists should have identical length). If no
  414 injectivity annotation was provided `famTcInj` is Nothing. From this follows an
  415 invariant that if `famTcInj` is a Just then at least one element in the list
  416 must be True.
  417 
  418 See also:
  419  * [Injectivity annotation] in GHC.Hs.Decls
  420  * [Renaming injectivity annotation] in GHC.Rename.Module
  421  * [Verifying injectivity annotation] in GHC.Core.FamInstEnv
  422  * [Type inference for type families with injectivity] in GHC.Tc.Solver.Interact
  423 
  424 Note [Sharing nullary TyConApps]
  425 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  426 Nullary type constructor applications are extremely common. For this reason
  427 each TyCon carries with it a @TyConApp tycon []@. This ensures that
  428 'mkTyConTy' does not need to allocate and eliminates quite a bit of heap
  429 residency. Furthermore, we use 'mkTyConTy' in the nullary case of 'mkTyConApp',
  430 ensuring that this function also benefits from sharing.
  431 
  432 This optimisation improves allocations in the Cabal test by around 0.3% and
  433 decreased cache misses measurably.
  434 
  435 See #19367.
  436 
  437 
  438 ************************************************************************
  439 *                                                                      *
  440                     TyConBinder, TyConTyCoBinder
  441 *                                                                      *
  442 ************************************************************************
  443 -}
  444 
  445 type TyConBinder     = VarBndr TyVar   TyConBndrVis
  446 type TyConTyCoBinder = VarBndr TyCoVar TyConBndrVis
  447      -- Only PromotedDataCon has TyConTyCoBinders
  448      -- See Note [Promoted GADT data construtors]
  449 
  450 data TyConBndrVis
  451   = NamedTCB ArgFlag
  452   | AnonTCB  AnonArgFlag
  453 
  454 instance Outputable TyConBndrVis where
  455   ppr (NamedTCB flag) = text "NamedTCB" <> ppr flag
  456   ppr (AnonTCB af)    = text "AnonTCB"  <> ppr af
  457 
  458 mkAnonTyConBinder :: AnonArgFlag -> TyVar -> TyConBinder
  459 mkAnonTyConBinder af tv = assert (isTyVar tv) $
  460                           Bndr tv (AnonTCB af)
  461 
  462 mkAnonTyConBinders :: AnonArgFlag -> [TyVar] -> [TyConBinder]
  463 mkAnonTyConBinders af tvs = map (mkAnonTyConBinder af) tvs
  464 
  465 mkNamedTyConBinder :: ArgFlag -> TyVar -> TyConBinder
  466 -- The odd argument order supports currying
  467 mkNamedTyConBinder vis tv = assert (isTyVar tv) $
  468                             Bndr tv (NamedTCB vis)
  469 
  470 mkNamedTyConBinders :: ArgFlag -> [TyVar] -> [TyConBinder]
  471 -- The odd argument order supports currying
  472 mkNamedTyConBinders vis tvs = map (mkNamedTyConBinder vis) tvs
  473 
  474 -- | Make a Required TyConBinder. It chooses between NamedTCB and
  475 -- AnonTCB based on whether the tv is mentioned in the dependent set
  476 mkRequiredTyConBinder :: TyCoVarSet  -- these are used dependently
  477                       -> TyVar
  478                       -> TyConBinder
  479 mkRequiredTyConBinder dep_set tv
  480   | tv `elemVarSet` dep_set = mkNamedTyConBinder Required tv
  481   | otherwise               = mkAnonTyConBinder  VisArg   tv
  482 
  483 tyConBinderArgFlag :: TyConBinder -> ArgFlag
  484 tyConBinderArgFlag (Bndr _ vis) = tyConBndrVisArgFlag vis
  485 
  486 tyConBndrVisArgFlag :: TyConBndrVis -> ArgFlag
  487 tyConBndrVisArgFlag (NamedTCB vis)     = vis
  488 tyConBndrVisArgFlag (AnonTCB VisArg)   = Required
  489 tyConBndrVisArgFlag (AnonTCB InvisArg) = Inferred    -- See Note [AnonTCB InvisArg]
  490 
  491 isNamedTyConBinder :: TyConBinder -> Bool
  492 -- Identifies kind variables
  493 -- E.g. data T k (a:k) = blah
  494 -- Here 'k' is a NamedTCB, a variable used in the kind of other binders
  495 isNamedTyConBinder (Bndr _ (NamedTCB {})) = True
  496 isNamedTyConBinder _                      = False
  497 
  498 isVisibleTyConBinder :: VarBndr tv TyConBndrVis -> Bool
  499 -- Works for IfaceTyConBinder too
  500 isVisibleTyConBinder (Bndr _ tcb_vis) = isVisibleTcbVis tcb_vis
  501 
  502 isVisibleTcbVis :: TyConBndrVis -> Bool
  503 isVisibleTcbVis (NamedTCB vis)     = isVisibleArgFlag vis
  504 isVisibleTcbVis (AnonTCB VisArg)   = True
  505 isVisibleTcbVis (AnonTCB InvisArg) = False
  506 
  507 isInvisibleTyConBinder :: VarBndr tv TyConBndrVis -> Bool
  508 -- Works for IfaceTyConBinder too
  509 isInvisibleTyConBinder tcb = not (isVisibleTyConBinder tcb)
  510 
  511 -- Build the 'tyConKind' from the binders and the result kind.
  512 -- Keep in sync with 'mkTyConKind' in GHC.Iface.Type.
  513 mkTyConKind :: [TyConBinder] -> Kind -> Kind
  514 mkTyConKind bndrs res_kind = foldr mk res_kind bndrs
  515   where
  516     mk :: TyConBinder -> Kind -> Kind
  517     mk (Bndr tv (AnonTCB af))   k = mkFunTyMany af (varType tv) k
  518     mk (Bndr tv (NamedTCB vis)) k = mkForAllTy tv vis k
  519 
  520 tyConInvisTVBinders :: [TyConBinder]   -- From the TyCon
  521                     -> [InvisTVBinder] -- Suitable for the foralls of a term function
  522 -- See Note [Building TyVarBinders from TyConBinders]
  523 tyConInvisTVBinders tc_bndrs
  524  = map mk_binder tc_bndrs
  525  where
  526    mk_binder (Bndr tv tc_vis) = mkTyVarBinder vis tv
  527       where
  528         vis = case tc_vis of
  529                 AnonTCB VisArg           -> SpecifiedSpec
  530                 AnonTCB InvisArg         -> InferredSpec   -- See Note [AnonTCB InvisArg]
  531                 NamedTCB Required        -> SpecifiedSpec
  532                 NamedTCB (Invisible vis) -> vis
  533 
  534 -- Returns only tyvars, as covars are always inferred
  535 tyConVisibleTyVars :: TyCon -> [TyVar]
  536 tyConVisibleTyVars tc
  537   = [ tv | Bndr tv vis <- tyConBinders tc
  538          , isVisibleTcbVis vis ]
  539 
  540 {- Note [AnonTCB InvisArg]
  541 ~~~~~~~~~~~~~~~~~~~~~~~~~~
  542 It's pretty rare to have an (AnonTCB InvisArg) binder.  The
  543 only way it can occur is through equality constraints in kinds. These
  544 can arise in one of two ways:
  545 
  546 * In a PromotedDataCon whose kind has an equality constraint:
  547 
  548     'MkT :: forall a b. (a~b) => blah
  549 
  550   See Note [Constraints in kinds] in GHC.Core.TyCo.Rep, and
  551   Note [Promoted data constructors] in this module.
  552 * In a data type whose kind has an equality constraint, as in the
  553   following example from #12102:
  554 
  555     data T :: forall a. (IsTypeLit a ~ 'True) => a -> Type
  556 
  557 When mapping an (AnonTCB InvisArg) to an ArgFlag, in
  558 tyConBndrVisArgFlag, we use "Inferred" to mean "the user cannot
  559 specify this arguments, even with visible type/kind application;
  560 instead the type checker must fill it in.
  561 
  562 We map (AnonTCB VisArg) to Required, of course: the user must
  563 provide it. It would be utterly wrong to do this for constraint
  564 arguments, which is why AnonTCB must have the AnonArgFlag in
  565 the first place.
  566 
  567 Note [Building TyVarBinders from TyConBinders]
  568 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  569 We sometimes need to build the quantified type of a value from
  570 the TyConBinders of a type or class.  For that we need not
  571 TyConBinders but TyVarBinders (used in forall-type)  E.g:
  572 
  573  *  From   data T a = MkT (Maybe a)
  574     we are going to make a data constructor with type
  575            MkT :: forall a. Maybe a -> T a
  576     See the TyCoVarBinders passed to buildDataCon
  577 
  578  * From    class C a where { op :: a -> Maybe a }
  579    we are going to make a default method
  580            $dmop :: forall a. C a => a -> Maybe a
  581    See the TyCoVarBinders passed to mkSigmaTy in mkDefaultMethodType
  582 
  583 Both of these are user-callable.  (NB: default methods are not callable
  584 directly by the user but rather via the code generated by 'deriving',
  585 which uses visible type application; see mkDefMethBind.)
  586 
  587 Since they are user-callable we must get their type-argument visibility
  588 information right; and that info is in the TyConBinders.
  589 Here is an example:
  590 
  591   data App a b = MkApp (a b) -- App :: forall {k}. (k->*) -> k -> *
  592 
  593 The TyCon has
  594 
  595   tyConTyBinders = [ Named (Bndr (k :: *) Inferred), Anon (k->*), Anon k ]
  596 
  597 The TyConBinders for App line up with App's kind, given above.
  598 
  599 But the DataCon MkApp has the type
  600   MkApp :: forall {k} (a:k->*) (b:k). a b -> App k a b
  601 
  602 That is, its TyCoVarBinders should be
  603 
  604   dataConUnivTyVarBinders = [ Bndr (k:*)    Inferred
  605                             , Bndr (a:k->*) Specified
  606                             , Bndr (b:k)    Specified ]
  607 
  608 So tyConTyVarBinders converts TyCon's TyConBinders into TyVarBinders:
  609   - variable names from the TyConBinders
  610   - but changing Anon/Required to Specified
  611 
  612 The last part about Required->Specified comes from this:
  613   data T k (a:k) b = MkT (a b)
  614 Here k is Required in T's kind, but we don't have Required binders in
  615 the TyCoBinders for a term (see Note [No Required TyCoBinder in terms]
  616 in GHC.Core.TyCo.Rep), so we change it to Specified when making MkT's TyCoBinders
  617 -}
  618 
  619 
  620 {- Note [The binders/kind/arity fields of a TyCon]
  621 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  622 All TyCons have this group of fields
  623   tyConBinders   :: [TyConBinder/TyConTyCoBinder]
  624   tyConResKind   :: Kind
  625   tyConTyVars    :: [TyVar]   -- Cached = binderVars tyConBinders
  626                               --   NB: Currently (Aug 2018), TyCons that own this
  627                               --   field really only contain TyVars. So it is
  628                               --   [TyVar] instead of [TyCoVar].
  629   tyConKind      :: Kind      -- Cached = mkTyConKind tyConBinders tyConResKind
  630   tyConArity     :: Arity     -- Cached = length tyConBinders
  631 
  632 They fit together like so:
  633 
  634 * tyConBinders gives the telescope of type/coercion variables on the LHS of the
  635   type declaration.  For example:
  636 
  637     type App a (b :: k) = a b
  638 
  639   tyConBinders = [ Bndr (k::*)   (NamedTCB Inferred)
  640                  , Bndr (a:k->*) AnonTCB
  641                  , Bndr (b:k)    AnonTCB ]
  642 
  643   Note that there are three binders here, including the
  644   kind variable k.
  645 
  646 * See Note [VarBndrs, TyCoVarBinders, TyConBinders, and visibility] in GHC.Core.TyCo.Rep
  647   for what the visibility flag means.
  648 
  649 * Each TyConBinder tyConBinders has a TyVar (sometimes it is TyCoVar), and
  650   that TyVar may scope over some other part of the TyCon's definition. Eg
  651       type T a = a -> a
  652   we have
  653       tyConBinders = [ Bndr (a:*) AnonTCB ]
  654       synTcRhs     = a -> a
  655   So the 'a' scopes over the synTcRhs
  656 
  657 * From the tyConBinders and tyConResKind we can get the tyConKind
  658   E.g for our App example:
  659       App :: forall k. (k->*) -> k -> *
  660 
  661   We get a 'forall' in the kind for each NamedTCB, and an arrow
  662   for each AnonTCB
  663 
  664   tyConKind is the full kind of the TyCon, not just the result kind
  665 
  666 * For type families, tyConArity is the arguments this TyCon must be
  667   applied to, to be considered saturated.  Here we mean "applied to in
  668   the actual Type", not surface syntax; i.e. including implicit kind
  669   variables.  So it's just (length tyConBinders)
  670 
  671 * For an algebraic data type, or data instance, the tyConResKind is
  672   always (TYPE r); that is, the tyConBinders are enough to saturate
  673   the type constructor.  I'm not quite sure why we have this invariant,
  674   but it's enforced by etaExpandAlgTyCon
  675 -}
  676 
  677 instance OutputableBndr tv => Outputable (VarBndr tv TyConBndrVis) where
  678   ppr (Bndr v bi) = ppr_bi bi <+> parens (pprBndr LetBind v)
  679     where
  680       ppr_bi (AnonTCB VisArg)     = text "anon-vis"
  681       ppr_bi (AnonTCB InvisArg)   = text "anon-invis"
  682       ppr_bi (NamedTCB Required)  = text "req"
  683       -- See Note [Explicit Case Statement for Specificity]
  684       ppr_bi (NamedTCB (Invisible spec)) = case spec of
  685         SpecifiedSpec -> text "spec"
  686         InferredSpec  -> text "inf"
  687 
  688 instance Binary TyConBndrVis where
  689   put_ bh (AnonTCB af)   = do { putByte bh 0; put_ bh af }
  690   put_ bh (NamedTCB vis) = do { putByte bh 1; put_ bh vis }
  691 
  692   get bh = do { h <- getByte bh
  693               ; case h of
  694                   0 -> do { af  <- get bh; return (AnonTCB af) }
  695                   _ -> do { vis <- get bh; return (NamedTCB vis) } }
  696 
  697 
  698 {- *********************************************************************
  699 *                                                                      *
  700                The TyCon type
  701 *                                                                      *
  702 ************************************************************************
  703 -}
  704 
  705 
  706 -- | TyCons represent type constructors. Type constructors are introduced by
  707 -- things such as:
  708 --
  709 -- 1) Data declarations: @data Foo = ...@ creates the @Foo@ type constructor of
  710 --    kind @*@
  711 --
  712 -- 2) Type synonyms: @type Foo = ...@ creates the @Foo@ type constructor
  713 --
  714 -- 3) Newtypes: @newtype Foo a = MkFoo ...@ creates the @Foo@ type constructor
  715 --    of kind @* -> *@
  716 --
  717 -- 4) Class declarations: @class Foo where@ creates the @Foo@ type constructor
  718 --    of kind @*@
  719 --
  720 -- This data type also encodes a number of primitive, built in type constructors
  721 -- such as those for function and tuple types.
  722 
  723 -- If you edit this type, you may need to update the GHC formalism
  724 -- See Note [GHC Formalism] in GHC.Core.Lint
  725 data TyCon
  726   = -- | The function type constructor, @(->)@
  727     FunTyCon {
  728         tyConUnique :: Unique,   -- ^ A Unique of this TyCon. Invariant:
  729                                  -- identical to Unique of Name stored in
  730                                  -- tyConName field.
  731 
  732         tyConName   :: Name,     -- ^ Name of the constructor
  733 
  734         -- See Note [The binders/kind/arity fields of a TyCon]
  735         tyConBinders :: [TyConBinder], -- ^ Full binders
  736         tyConResKind :: Kind,             -- ^ Result kind
  737         tyConKind    :: Kind,             -- ^ Kind of this TyCon
  738         tyConArity   :: Arity,            -- ^ Arity
  739         tyConNullaryTy :: Type,
  740 
  741         tcRepName :: TyConRepName
  742     }
  743 
  744   -- | Algebraic data types, from
  745   --     - @data@ declarations
  746   --     - @newtype@ declarations
  747   --     - data instance declarations
  748   --     - type instance declarations
  749   --     - the TyCon generated by a class declaration
  750   --     - boxed tuples
  751   --     - unboxed tuples
  752   --     - constraint tuples
  753   -- All these constructors are lifted and boxed except unboxed tuples
  754   -- which should have an 'UnboxedAlgTyCon' parent.
  755   -- Data/newtype/type /families/ are handled by 'FamilyTyCon'.
  756   -- See 'AlgTyConRhs' for more information.
  757   | AlgTyCon {
  758         tyConUnique  :: Unique,  -- ^ A Unique of this TyCon. Invariant:
  759                                  -- identical to Unique of Name stored in
  760                                  -- tyConName field.
  761 
  762         tyConName    :: Name,    -- ^ Name of the constructor
  763 
  764         -- See Note [The binders/kind/arity fields of a TyCon]
  765         tyConBinders :: [TyConBinder], -- ^ Full binders
  766         tyConTyVars  :: [TyVar],          -- ^ TyVar binders
  767         tyConResKind :: Kind,             -- ^ Result kind
  768         tyConKind    :: Kind,             -- ^ Kind of this TyCon
  769         tyConArity   :: Arity,            -- ^ Arity
  770         tyConNullaryTy :: Type,           -- ^ A pre-allocated @TyConApp tycon []@
  771 
  772               -- The tyConTyVars scope over:
  773               --
  774               -- 1. The 'algTcStupidTheta'
  775               -- 2. The cached types in algTyConRhs.NewTyCon
  776               -- 3. The family instance types if present
  777               --
  778               -- Note that it does /not/ scope over the data
  779               -- constructors.
  780 
  781         tcRoles      :: [Role],  -- ^ The role for each type variable
  782                                  -- This list has length = tyConArity
  783                                  -- See also Note [TyCon Role signatures]
  784 
  785         tyConCType   :: Maybe CType,-- ^ The C type that should be used
  786                                     -- for this type when using the FFI
  787                                     -- and CAPI
  788 
  789         algTcGadtSyntax  :: Bool,   -- ^ Was the data type declared with GADT
  790                                     -- syntax?  If so, that doesn't mean it's a
  791                                     -- true GADT; only that the "where" form
  792                                     -- was used.  This field is used only to
  793                                     -- guide pretty-printing
  794 
  795         algTcStupidTheta :: [PredType], -- ^ The \"stupid theta\" for the data
  796                                         -- type (always empty for GADTs).  A
  797                                         -- \"stupid theta\" is the context to
  798                                         -- the left of an algebraic type
  799                                         -- declaration, e.g. @Eq a@ in the
  800                                         -- declaration @data Eq a => T a ...@.
  801 
  802         algTcRhs    :: AlgTyConRhs, -- ^ Contains information about the
  803                                     -- data constructors of the algebraic type
  804 
  805         algTcFields :: FieldLabelEnv, -- ^ Maps a label to information
  806                                       -- about the field
  807 
  808         algTcParent :: AlgTyConFlav -- ^ Gives the class or family declaration
  809                                        -- 'TyCon' for derived 'TyCon's representing
  810                                        -- class or family instances, respectively.
  811 
  812     }
  813 
  814   -- | Represents type synonyms
  815   | SynonymTyCon {
  816         tyConUnique  :: Unique,  -- ^ A Unique of this TyCon. Invariant:
  817                                  -- identical to Unique of Name stored in
  818                                  -- tyConName field.
  819 
  820         tyConName    :: Name,    -- ^ Name of the constructor
  821 
  822         -- See Note [The binders/kind/arity fields of a TyCon]
  823         tyConBinders :: [TyConBinder], -- ^ Full binders
  824         tyConTyVars  :: [TyVar],          -- ^ TyVar binders
  825         tyConResKind :: Kind,             -- ^ Result kind
  826         tyConKind    :: Kind,             -- ^ Kind of this TyCon
  827         tyConArity   :: Arity,            -- ^ Arity
  828         tyConNullaryTy :: Type,           -- ^ A pre-allocated @TyConApp tycon []@
  829              -- tyConTyVars scope over: synTcRhs
  830 
  831         tcRoles      :: [Role],  -- ^ The role for each type variable
  832                                  -- This list has length = tyConArity
  833                                  -- See also Note [TyCon Role signatures]
  834 
  835         synTcRhs     :: Type,    -- ^ Contains information about the expansion
  836                                  -- of the synonym
  837 
  838         synIsTau     :: Bool,   -- True <=> the RHS of this synonym does not
  839                                  --          have any foralls, after expanding any
  840                                  --          nested synonyms
  841         synIsFamFree  :: Bool,   -- True <=> the RHS of this synonym does not mention
  842                                  --          any type synonym families (data families
  843                                  --          are fine), again after expanding any
  844                                  --          nested synonyms
  845         synIsForgetful :: Bool   -- True <=  at least one argument is not mentioned
  846                                  --          in the RHS (or is mentioned only under
  847                                  --          forgetful synonyms)
  848                                  -- Test is conservative, so True does not guarantee
  849                                  -- forgetfulness.
  850     }
  851 
  852   -- | Represents families (both type and data)
  853   -- Argument roles are all Nominal
  854   | FamilyTyCon {
  855         tyConUnique  :: Unique,  -- ^ A Unique of this TyCon. Invariant:
  856                                  -- identical to Unique of Name stored in
  857                                  -- tyConName field.
  858 
  859         tyConName    :: Name,    -- ^ Name of the constructor
  860 
  861         -- See Note [The binders/kind/arity fields of a TyCon]
  862         tyConBinders :: [TyConBinder], -- ^ Full binders
  863         tyConTyVars  :: [TyVar],          -- ^ TyVar binders
  864         tyConResKind :: Kind,             -- ^ Result kind
  865         tyConKind    :: Kind,             -- ^ Kind of this TyCon
  866         tyConArity   :: Arity,            -- ^ Arity
  867         tyConNullaryTy :: Type,           -- ^ A pre-allocated @TyConApp tycon []@
  868             -- tyConTyVars connect an associated family TyCon
  869             -- with its parent class; see GHC.Tc.Validity.checkConsistentFamInst
  870 
  871         famTcResVar  :: Maybe Name,   -- ^ Name of result type variable, used
  872                                       -- for pretty-printing with --show-iface
  873                                       -- and for reifying TyCon in Template
  874                                       -- Haskell
  875 
  876         famTcFlav    :: FamTyConFlav, -- ^ Type family flavour: open, closed,
  877                                       -- abstract, built-in. See comments for
  878                                       -- FamTyConFlav
  879 
  880         famTcParent  :: Maybe TyCon,  -- ^ For *associated* type/data families
  881                                       -- The class tycon in which the family is declared
  882                                       -- See Note [Associated families and their parent class]
  883 
  884         famTcInj     :: Injectivity   -- ^ is this a type family injective in
  885                                       -- its type variables? Nothing if no
  886                                       -- injectivity annotation was given
  887     }
  888 
  889   -- | Primitive types; cannot be defined in Haskell. This includes
  890   -- the usual suspects (such as @Int#@) as well as foreign-imported
  891   -- types and kinds (@*@, @#@, and @?@)
  892   | PrimTyCon {
  893         tyConUnique   :: Unique, -- ^ A Unique of this TyCon. Invariant:
  894                                  -- identical to Unique of Name stored in
  895                                  -- tyConName field.
  896 
  897         tyConName     :: Name,   -- ^ Name of the constructor
  898 
  899         -- See Note [The binders/kind/arity fields of a TyCon]
  900         tyConBinders :: [TyConBinder], -- ^ Full binders
  901         tyConResKind :: Kind,             -- ^ Result kind
  902         tyConKind    :: Kind,             -- ^ Kind of this TyCon
  903         tyConArity   :: Arity,            -- ^ Arity
  904         tyConNullaryTy :: Type,           -- ^ A pre-allocated @TyConApp tycon []@
  905 
  906         tcRoles       :: [Role], -- ^ The role for each type variable
  907                                  -- This list has length = tyConArity
  908                                  -- See also Note [TyCon Role signatures]
  909 
  910         isUnlifted   :: Bool,    -- ^ Most primitive tycons are unlifted (may
  911                                  -- not contain bottom) but other are lifted,
  912                                  -- e.g. @RealWorld@
  913                                  -- Only relevant if tyConKind = *
  914 
  915         primRepName :: TyConRepName   -- ^ The 'Typeable' representation.
  916                                       -- A cached version of
  917                                       -- @'mkPrelTyConRepName' ('tyConName' tc)@.
  918     }
  919 
  920   -- | Represents promoted data constructor.
  921   | PromotedDataCon {          -- See Note [Promoted data constructors]
  922         tyConUnique  :: Unique,     -- ^ Same Unique as the data constructor
  923         tyConName    :: Name,       -- ^ Same Name as the data constructor
  924 
  925         -- See Note [The binders/kind/arity fields of a TyCon]
  926         tyConBinders :: [TyConTyCoBinder], -- ^ Full binders
  927            -- TyConTyCoBinder: see Note [Promoted GADT data construtors]
  928         tyConResKind :: Kind,             -- ^ Result kind
  929         tyConKind    :: Kind,             -- ^ Kind of this TyCon
  930         tyConArity   :: Arity,            -- ^ Arity
  931         tyConNullaryTy :: Type,           -- ^ A pre-allocated @TyConApp tycon []@
  932 
  933         tcRoles       :: [Role],    -- ^ Roles: N for kind vars, R for type vars
  934         dataCon       :: DataCon,   -- ^ Corresponding data constructor
  935         tcRepName     :: TyConRepName,
  936         promDcRepInfo :: RuntimeRepInfo  -- ^ See comments with 'RuntimeRepInfo'
  937     }
  938 
  939   -- | These exist only during type-checking. See Note [How TcTyCons work]
  940   -- in "GHC.Tc.TyCl"
  941   | TcTyCon {
  942         tyConUnique :: Unique,
  943         tyConName   :: Name,
  944 
  945         -- See Note [The binders/kind/arity fields of a TyCon]
  946         tyConBinders :: [TyConBinder], -- ^ Full binders
  947         tyConTyVars  :: [TyVar],       -- ^ TyVar binders
  948         tyConResKind :: Kind,          -- ^ Result kind
  949         tyConKind    :: Kind,          -- ^ Kind of this TyCon
  950         tyConArity   :: Arity,         -- ^ Arity
  951         tyConNullaryTy :: Type,           -- ^ A pre-allocated @TyConApp tycon []@
  952 
  953           -- NB: the TyConArity of a TcTyCon must match
  954           -- the number of Required (positional, user-specified)
  955           -- arguments to the type constructor; see the use
  956           -- of tyConArity in generaliseTcTyCon
  957 
  958         tcTyConScopedTyVars :: [(Name,TyVar)],
  959           -- ^ Scoped tyvars over the tycon's body
  960           -- See Note [Scoped tyvars in a TcTyCon]
  961 
  962         tcTyConIsPoly     :: Bool, -- ^ Is this TcTyCon already generalized?
  963 
  964         tcTyConFlavour :: TyConFlavour
  965                            -- ^ What sort of 'TyCon' this represents.
  966       }
  967 {- Note [Scoped tyvars in a TcTyCon]
  968 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  969 The tcTyConScopedTyVars field records the lexicial-binding connection
  970 between the original, user-specified Name (i.e. thing in scope) and
  971 the TcTyVar that the Name is bound to.
  972 
  973 Order *does* matter; the tcTyConScopedTyvars list consists of
  974      specified_tvs ++ required_tvs
  975 
  976 where
  977    * specified ones first
  978    * required_tvs the same as tyConTyVars
  979    * tyConArity = length required_tvs
  980 
  981 There are some situations where we need to keep the tcTyConScopedTyVars around
  982 for later use, even after the TcTyCon has been zonked away:
  983 
  984 * When typechecking `deriving` clauses for top-level data declarations, the
  985   tcTyConScopedTyVars are brought into scope in through the `di_scoped_tvs`
  986   field of GHC.Tc.Deriv.DerivInfo. Example (#16731):
  987 
  988     class C x1 x2
  989 
  990     type T :: a -> Type
  991     data T (x :: z) deriving (C z)
  992 
  993   When typechecking `C z`, we want `z` to map to `a`, which is exactly what the
  994   tcTyConScopedTyVars for T give us.
  995 
  996 * Similarly, when typechecking default definitions for class methods, the
  997   tcTyConScopedTyVars ought to be brought into scope. Example (#19738):
  998 
  999     type P :: k -> Type
 1000     data P a = MkP
 1001 
 1002     type T :: k -> Constraint
 1003     class T (a :: j) where
 1004       f :: P a
 1005       f = MkP @j @a
 1006 
 1007   We pass the tcTyConScopedTyVars to GHC.Tc.TyCl.Class.tcClassDecl2, the
 1008   function responsible for typechecking the default definition of `f`, by way
 1009   of a ClassScopedTVEnv, which maps each class name to its scoped tyvars.
 1010 
 1011 See also Note [How TcTyCons work] in GHC.Tc.TyCl
 1012 
 1013 Note [Promoted GADT data constructors]
 1014 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 1015 Any promoted GADT data constructor will have a type with equality
 1016 constraints in its type; e.g.
 1017     K :: forall a b. (a ~# [b]) => a -> b -> T a
 1018 
 1019 So, when promoted to become a type constructor, the tyConBinders
 1020 will include CoVars.  That is why we use [TyConTyCoBinder] for the
 1021 tyconBinders field.  TyConTyCoBinder is a synonym for TyConBinder,
 1022 but with the clue that the binder can be a CoVar not just a TyVar.
 1023 
 1024 Note [Representation-polymorphic TyCons]
 1025 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 1026 To check for representation-polymorphism directly in the typechecker,
 1027 e.g. when using GHC.Tc.Utils.TcMType.checkTypeHasFixedRuntimeRep,
 1028 we need to compute whether a type has a fixed RuntimeRep,
 1029 as per Note [Fixed RuntimeRep] in GHC.Tc.Utils.Concrete.
 1030 
 1031 It's useful to have a quick way to check whether a saturated application
 1032 of a type constructor has a fixed RuntimeRep. That is, we want
 1033 to know, given a TyCon 'T' of arity 'n', does
 1034 
 1035   T a_1 ... a_n
 1036 
 1037 always have a fixed RuntimeRep? That is, is it always the case
 1038 that this application has a kind of the form
 1039 
 1040   T a_1 ... a_n :: TYPE rep
 1041 
 1042 in which 'rep' is a concrete 'RuntimeRep'?
 1043 ('Concrete' in the sense of Note [The Concrete mechanism] in GHC.Tc.Utils.Concrete:
 1044 it contains no type-family applications or type variables.)
 1045 
 1046 To answer this question, we have 'tcHasFixedRuntimeRep'.
 1047 If 'tcHasFixedRuntimeRep' returns 'True', it means we're sure that
 1048 every saturated application of `T` has a fixed RuntimeRep.
 1049 However, if it returns 'False', we don't know: perhaps some application might not
 1050 have a fixed RuntimeRep.
 1051 
 1052 Examples:
 1053 
 1054   - For type families, we won't know in general whether an application
 1055     will have a fixed RuntimeRep:
 1056 
 1057       type F :: k -> k
 1058       type family F a where {..}
 1059 
 1060     `tcHasFixedRuntimeRep F = False'
 1061 
 1062   - For newtypes, we're usually OK:
 1063 
 1064       newtype N a b c = MkN Int
 1065 
 1066     No matter what arguments we apply `N` to, we always get something of
 1067     kind `Type`, which has a fixed RuntimeRep.
 1068     Thus `tcHasFixedRuntimeRep N = True`.
 1069 
 1070     However, with `-XUnliftedNewtypes`, we can have representation-polymorphic
 1071     newtypes:
 1072 
 1073       type UN :: TYPE rep -> TYPE rep
 1074       newtype UN a = MkUN a
 1075 
 1076     `tcHasFixedRuntimeRep UN = False`
 1077 
 1078     For example, `UN @Int8Rep Int8#` is represented by an 8-bit value,
 1079     while `UN @LiftedRep Int` is represented by a heap pointer.
 1080 
 1081     To distinguish whether we are dealing with a representation-polymorphic newtype,
 1082     we keep track of which situation we are in using the 'nt_fixed_rep'
 1083     field of the 'NewTyCon' constructor of 'AlgTyConRhs', and read this field
 1084     to compute 'tcHasFixedRuntimeRep'.
 1085 
 1086   - A similar story can be told for datatypes: we're usually OK,
 1087     except with `-XUnliftedDatatypes` which allows for levity polymorphism,
 1088     e.g.:
 1089 
 1090       type UC :: TYPE (BoxedRep l) -> TYPE (BoxedRep l)
 1091       type UC a = MkUC a
 1092 
 1093     `tcHasFixedRuntimeRep UC = False`
 1094 
 1095     Here, we keep track of whether we are dealing with a levity-polymorphic
 1096     unlifted datatype using the 'data_fixed_lev' field of the 'DataTyCon'
 1097     constructor of 'AlgTyConRhs'.
 1098 
 1099     N.B.: technically, the representation of a datatype is fixed,
 1100     as it is always a pointer. However, we currently require that we
 1101     know the specific `RuntimeRep`: knowing that it's `BoxedRep l`
 1102     for a type-variable `l` isn't enough. See #15532.
 1103 -}
 1104 
 1105 -- | Represents right-hand-sides of 'TyCon's for algebraic types
 1106 data AlgTyConRhs
 1107 
 1108     -- | Says that we know nothing about this data type, except that
 1109     -- it's represented by a pointer.  Used when we export a data type
 1110     -- abstractly into an .hi file.
 1111   = AbstractTyCon
 1112 
 1113     -- | Information about those 'TyCon's derived from a @data@
 1114     -- declaration. This includes data types with no constructors at
 1115     -- all.
 1116   | DataTyCon {
 1117         data_cons :: [DataCon],
 1118                           -- ^ The data type constructors; can be empty if the
 1119                           --   user declares the type to have no constructors
 1120                           --
 1121                           -- INVARIANT: Kept in order of increasing 'DataCon'
 1122                           -- tag (see the tag assignment in mkTyConTagMap)
 1123         data_cons_size :: Int,
 1124                           -- ^ Cached value: length data_cons
 1125         is_enum :: Bool,  -- ^ Cached value: is this an enumeration type?
 1126                           --   See Note [Enumeration types]
 1127         data_fixed_lev :: Bool
 1128                         -- ^ 'True' if the data type constructor has
 1129                         -- a known, fixed levity when fully applied
 1130                         -- to its arguments, False otherwise.
 1131                         --
 1132                         -- This can only be 'False' with UnliftedDatatypes,
 1133                         -- e.g.
 1134                         --
 1135                         -- > data A :: TYPE (BoxedRep l) where { MkA :: Int -> A }
 1136                         --
 1137                         -- This boolean is cached to make it cheaper to check
 1138                         -- for levity and representation-polymorphism in
 1139                         -- tcHasFixedRuntimeRep.
 1140     }
 1141 
 1142   | TupleTyCon {                   -- A boxed, unboxed, or constraint tuple
 1143         data_con :: DataCon,       -- NB: it can be an *unboxed* tuple
 1144         tup_sort :: TupleSort      -- ^ Is this a boxed, unboxed or constraint
 1145                                    -- tuple?
 1146     }
 1147 
 1148   -- | An unboxed sum type.
 1149   | SumTyCon {
 1150         data_cons :: [DataCon],
 1151         data_cons_size :: Int  -- ^ Cached value: length data_cons
 1152     }
 1153 
 1154   -- | Information about those 'TyCon's derived from a @newtype@ declaration
 1155   | NewTyCon {
 1156         data_con :: DataCon,    -- ^ The unique constructor for the @newtype@.
 1157                                 --   It has no existentials
 1158 
 1159         nt_rhs :: Type,         -- ^ Cached value: the argument type of the
 1160                                 -- constructor, which is just the representation
 1161                                 -- type of the 'TyCon' (remember that @newtype@s
 1162                                 -- do not exist at runtime so need a different
 1163                                 -- representation type).
 1164                                 --
 1165                                 -- The free 'TyVar's of this type are the
 1166                                 -- 'tyConTyVars' from the corresponding 'TyCon'
 1167 
 1168         nt_etad_rhs :: ([TyVar], Type),
 1169                         -- ^ Same as the 'nt_rhs', but this time eta-reduced.
 1170                         -- Hence the list of 'TyVar's in this field may be
 1171                         -- shorter than the declared arity of the 'TyCon'.
 1172 
 1173                         -- See Note [Newtype eta]
 1174         nt_co :: CoAxiom Unbranched,
 1175                              -- The axiom coercion that creates the @newtype@
 1176                              -- from the representation 'Type'.
 1177 
 1178                              -- See Note [Newtype coercions]
 1179                              -- Invariant: arity = #tvs in nt_etad_rhs;
 1180                              -- See Note [Newtype eta]
 1181                              -- Watch out!  If any newtypes become transparent
 1182                              -- again check #1072.
 1183         nt_fixed_rep :: Bool
 1184                         -- ^ 'True' if the newtype has a know, fixed representation
 1185                         -- when fully applied to its arguments, 'False' otherwise.
 1186                         -- This can only ever be 'False' with UnliftedNewtypes.
 1187                         --
 1188                         -- Example:
 1189                         --
 1190                         -- > newtype N (a :: TYPE r) = MkN a
 1191                         --
 1192                         -- Invariant: nt_fixed_rep nt = tcHasFixedRuntimeRep (nt_rhs nt)
 1193                         --
 1194                         -- This boolean is cached to make it cheaper to check if a
 1195                         -- variable binding is representation-polymorphic
 1196                         -- in tcHasFixedRuntimeRep.
 1197     }
 1198 
 1199 mkSumTyConRhs :: [DataCon] -> AlgTyConRhs
 1200 mkSumTyConRhs data_cons = SumTyCon data_cons (length data_cons)
 1201 
 1202 -- | Create an 'AlgTyConRhs' from the data constructors,
 1203 -- for a potentially levity-polymorphic datatype (with `UnliftedDatatypes`).
 1204 mkLevPolyDataTyConRhs :: Bool -- ^ whether the 'DataCon' has a fixed levity
 1205                       -> [DataCon]
 1206                       -> AlgTyConRhs
 1207 mkLevPolyDataTyConRhs fixed_lev cons
 1208   = DataTyCon {
 1209         data_cons = cons,
 1210         data_cons_size = length cons,
 1211         is_enum = not (null cons) && all is_enum_con cons,
 1212                   -- See Note [Enumeration types] in GHC.Core.TyCon
 1213         data_fixed_lev = fixed_lev
 1214     }
 1215   where
 1216     is_enum_con con
 1217        | (_univ_tvs, ex_tvs, eq_spec, theta, arg_tys, _res)
 1218            <- dataConFullSig con
 1219        = null ex_tvs && null eq_spec && null theta && null arg_tys
 1220 
 1221 -- | Create an 'AlgTyConRhs' from the data constructors.
 1222 --
 1223 -- Use 'mkLevPolyDataConRhs' if the datatype can be levity-polymorphic.
 1224 mkDataTyConRhs :: [DataCon] -> AlgTyConRhs
 1225 mkDataTyConRhs = mkLevPolyDataTyConRhs False
 1226 
 1227 -- | Some promoted datacons signify extra info relevant to GHC. For example,
 1228 -- the @IntRep@ constructor of @RuntimeRep@ corresponds to the 'IntRep'
 1229 -- constructor of 'PrimRep'. This data structure allows us to store this
 1230 -- information right in the 'TyCon'. The other approach would be to look
 1231 -- up things like @RuntimeRep@'s @PrimRep@ by known-key every time.
 1232 -- See also Note [Getting from RuntimeRep to PrimRep] in "GHC.Types.RepType"
 1233 data RuntimeRepInfo
 1234   = NoRRI       -- ^ an ordinary promoted data con
 1235   | RuntimeRep ([Type] -> [PrimRep])
 1236       -- ^ A constructor of @RuntimeRep@. The argument to the function should
 1237       -- be the list of arguments to the promoted datacon.
 1238   | VecCount Int         -- ^ A constructor of @VecCount@
 1239   | VecElem PrimElemRep  -- ^ A constructor of @VecElem@
 1240   | LiftedInfo           -- ^ A constructor of @Levity@
 1241   | UnliftedInfo         -- ^ A constructor of @Levity@
 1242 
 1243 -- | Extract those 'DataCon's that we are able to learn about.  Note
 1244 -- that visibility in this sense does not correspond to visibility in
 1245 -- the context of any particular user program!
 1246 visibleDataCons :: AlgTyConRhs -> [DataCon]
 1247 visibleDataCons (AbstractTyCon {})            = []
 1248 visibleDataCons (DataTyCon{ data_cons = cs }) = cs
 1249 visibleDataCons (NewTyCon{ data_con = c })    = [c]
 1250 visibleDataCons (TupleTyCon{ data_con = c })  = [c]
 1251 visibleDataCons (SumTyCon{ data_cons = cs })  = cs
 1252 
 1253 -- ^ Both type classes as well as family instances imply implicit
 1254 -- type constructors.  These implicit type constructors refer to their parent
 1255 -- structure (ie, the class or family from which they derive) using a type of
 1256 -- the following form.
 1257 data AlgTyConFlav
 1258   = -- | An ordinary type constructor has no parent.
 1259     VanillaAlgTyCon
 1260        TyConRepName   -- For Typeable
 1261 
 1262     -- | An unboxed type constructor. The TyConRepName is a Maybe since we
 1263     -- currently don't allow unboxed sums to be Typeable since there are too
 1264     -- many of them. See #13276.
 1265   | UnboxedAlgTyCon
 1266        (Maybe TyConRepName)
 1267 
 1268   -- | Type constructors representing a class dictionary.
 1269   -- See Note [ATyCon for classes] in "GHC.Core.TyCo.Rep"
 1270   | ClassTyCon
 1271         Class           -- INVARIANT: the classTyCon of this Class is the
 1272                         -- current tycon
 1273         TyConRepName
 1274 
 1275   -- | Type constructors representing an *instance* of a *data* family.
 1276   -- Parameters:
 1277   --
 1278   --  1) The type family in question
 1279   --
 1280   --  2) Instance types; free variables are the 'tyConTyVars'
 1281   --  of the current 'TyCon' (not the family one). INVARIANT:
 1282   --  the number of types matches the arity of the family 'TyCon'
 1283   --
 1284   --  3) A 'CoTyCon' identifying the representation
 1285   --  type with the type instance family
 1286   | DataFamInstTyCon          -- See Note [Data type families]
 1287         (CoAxiom Unbranched)  -- The coercion axiom.
 1288                -- A *Representational* coercion,
 1289                -- of kind   T ty1 ty2   ~R   R:T a b c
 1290                -- where T is the family TyCon,
 1291                -- and R:T is the representation TyCon (ie this one)
 1292                -- and a,b,c are the tyConTyVars of this TyCon
 1293                --
 1294                -- BUT may be eta-reduced; see
 1295                --     Note [Eta reduction for data families] in
 1296                --     GHC.Core.Coercion.Axiom
 1297 
 1298           -- Cached fields of the CoAxiom, but adjusted to
 1299           -- use the tyConTyVars of this TyCon
 1300         TyCon   -- The family TyCon
 1301         [Type]  -- Argument types (mentions the tyConTyVars of this TyCon)
 1302                 -- No shorter in length than the tyConTyVars of the family TyCon
 1303                 -- How could it be longer? See [Arity of data families] in GHC.Core.FamInstEnv
 1304 
 1305         -- E.g.  data instance T [a] = ...
 1306         -- gives a representation tycon:
 1307         --      data R:TList a = ...
 1308         --      axiom co a :: T [a] ~ R:TList a
 1309         -- with R:TList's algTcParent = DataFamInstTyCon T [a] co
 1310 
 1311 instance Outputable AlgTyConFlav where
 1312     ppr (VanillaAlgTyCon {})        = text "Vanilla ADT"
 1313     ppr (UnboxedAlgTyCon {})        = text "Unboxed ADT"
 1314     ppr (ClassTyCon cls _)          = text "Class parent" <+> ppr cls
 1315     ppr (DataFamInstTyCon _ tc tys) = text "Family parent (family instance)"
 1316                                       <+> ppr tc <+> sep (map pprType tys)
 1317 
 1318 -- | Checks the invariants of a 'AlgTyConFlav' given the appropriate type class
 1319 -- name, if any
 1320 okParent :: Name -> AlgTyConFlav -> Bool
 1321 okParent _       (VanillaAlgTyCon {})            = True
 1322 okParent _       (UnboxedAlgTyCon {})            = True
 1323 okParent tc_name (ClassTyCon cls _)              = tc_name == tyConName (classTyCon cls)
 1324 okParent _       (DataFamInstTyCon _ fam_tc tys) = tys `lengthAtLeast` tyConArity fam_tc
 1325 
 1326 isNoParent :: AlgTyConFlav -> Bool
 1327 isNoParent (VanillaAlgTyCon {}) = True
 1328 isNoParent _                   = False
 1329 
 1330 --------------------
 1331 
 1332 data Injectivity
 1333   = NotInjective
 1334   | Injective [Bool]   -- 1-1 with tyConTyVars (incl kind vars)
 1335   deriving( Eq )
 1336 
 1337 -- | Information pertaining to the expansion of a type synonym (@type@)
 1338 data FamTyConFlav
 1339   = -- | Represents an open type family without a fixed right hand
 1340     -- side.  Additional instances can appear at any time.
 1341     --
 1342     -- These are introduced by either a top level declaration:
 1343     --
 1344     -- > data family T a :: *
 1345     --
 1346     -- Or an associated data type declaration, within a class declaration:
 1347     --
 1348     -- > class C a b where
 1349     -- >   data T b :: *
 1350      DataFamilyTyCon
 1351        TyConRepName
 1352 
 1353      -- | An open type synonym family  e.g. @type family F x y :: * -> *@
 1354    | OpenSynFamilyTyCon
 1355 
 1356    -- | A closed type synonym family  e.g.
 1357    -- @type family F x where { F Int = Bool }@
 1358    | ClosedSynFamilyTyCon (Maybe (CoAxiom Branched))
 1359      -- See Note [Closed type families]
 1360 
 1361    -- | A closed type synonym family declared in an hs-boot file with
 1362    -- type family F a where ..
 1363    | AbstractClosedSynFamilyTyCon
 1364 
 1365    -- | Built-in type family used by the TypeNats solver
 1366    | BuiltInSynFamTyCon BuiltInSynFamily
 1367 
 1368 instance Outputable FamTyConFlav where
 1369     ppr (DataFamilyTyCon n) = text "data family" <+> ppr n
 1370     ppr OpenSynFamilyTyCon = text "open type family"
 1371     ppr (ClosedSynFamilyTyCon Nothing) = text "closed type family"
 1372     ppr (ClosedSynFamilyTyCon (Just coax)) = text "closed type family" <+> ppr coax
 1373     ppr AbstractClosedSynFamilyTyCon = text "abstract closed type family"
 1374     ppr (BuiltInSynFamTyCon _) = text "built-in type family"
 1375 
 1376 {- Note [Closed type families]
 1377 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 1378 * In an open type family you can add new instances later.  This is the
 1379   usual case.
 1380 
 1381 * In a closed type family you can only put equations where the family
 1382   is defined.
 1383 
 1384 A non-empty closed type family has a single axiom with multiple
 1385 branches, stored in the 'ClosedSynFamilyTyCon' constructor.  A closed
 1386 type family with no equations does not have an axiom, because there is
 1387 nothing for the axiom to prove!
 1388 
 1389 
 1390 Note [Promoted data constructors]
 1391 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 1392 All data constructors can be promoted to become a type constructor,
 1393 via the PromotedDataCon alternative in GHC.Core.TyCon.
 1394 
 1395 * The TyCon promoted from a DataCon has the *same* Name and Unique as
 1396   the DataCon.  Eg. If the data constructor Data.Maybe.Just(unique 78,
 1397   say) is promoted to a TyCon whose name is Data.Maybe.Just(unique 78)
 1398 
 1399 * We promote the *user* type of the DataCon.  Eg
 1400      data T = MkT {-# UNPACK #-} !(Bool, Bool)
 1401   The promoted kind is
 1402      'MkT :: (Bool,Bool) -> T
 1403   *not*
 1404      'MkT :: Bool -> Bool -> T
 1405 
 1406 * Similarly for GADTs:
 1407      data G a where
 1408        MkG :: forall b. b -> G [b]
 1409   The promoted data constructor has kind
 1410        'MkG :: forall b. b -> G [b]
 1411   *not*
 1412        'MkG :: forall a b. (a ~# [b]) => b -> G a
 1413 
 1414 Note [Enumeration types]
 1415 ~~~~~~~~~~~~~~~~~~~~~~~~
 1416 We define datatypes with no constructors to *not* be
 1417 enumerations; this fixes trac #2578,  Otherwise we
 1418 end up generating an empty table for
 1419   <mod>_<type>_closure_tbl
 1420 which is used by tagToEnum# to map Int# to constructors
 1421 in an enumeration. The empty table apparently upset
 1422 the linker.
 1423 
 1424 Moreover, all the data constructor must be enumerations, meaning
 1425 they have type  (forall abc. T a b c).  GADTs are not enumerations.
 1426 For example consider
 1427     data T a where
 1428       T1 :: T Int
 1429       T2 :: T Bool
 1430       T3 :: T a
 1431 What would [T1 ..] be?  [T1,T3] :: T Int? Easiest thing is to exclude them.
 1432 See #4528.
 1433 
 1434 Note [Newtype coercions]
 1435 ~~~~~~~~~~~~~~~~~~~~~~~~
 1436 The NewTyCon field nt_co is a CoAxiom which is used for coercing from
 1437 the representation type of the newtype, to the newtype itself. For
 1438 example,
 1439 
 1440    newtype T a = MkT (a -> a)
 1441 
 1442 the NewTyCon for T will contain nt_co = CoT where CoT :: forall a. T a ~ a -> a.
 1443 
 1444 We might also eta-contract the axiom: see Note [Newtype eta].
 1445 
 1446 Note [Newtype eta]
 1447 ~~~~~~~~~~~~~~~~~~
 1448 Consider
 1449         newtype Parser a = MkParser (IO a) deriving Monad
 1450 Are these two types equal? That is, does a coercion exist between them?
 1451         Monad Parser
 1452         Monad IO
 1453 (We need this coercion to make the derived instance for Monad Parser.)
 1454 
 1455 Well, yes.  But to see that easily we eta-reduce the RHS type of
 1456 Parser, in this case to IO, so that even unsaturated applications of
 1457 Parser will work right.  So instead of
 1458    axParser :: forall a. Parser a ~ IO a
 1459 we generate an eta-reduced axiom
 1460    axParser :: Parser ~ IO
 1461 
 1462 This eta reduction is done when the type constructor is built, in
 1463 GHC.Tc.TyCl.Build.mkNewTyConRhs, and cached in NewTyCon.
 1464 
 1465 Here's an example that I think showed up in practice.
 1466 Source code:
 1467         newtype T a = MkT [a]
 1468         newtype Foo m = MkFoo (forall a. m a -> Int)
 1469 
 1470         w1 :: Foo []
 1471         w1 = ...
 1472 
 1473         w2 :: Foo T
 1474         w2 = MkFoo (\(MkT x) -> case w1 of MkFoo f -> f x)
 1475 
 1476 After desugaring, and discarding the data constructors for the newtypes,
 1477 we would like to get:
 1478         w2 = w1 `cast` Foo axT
 1479 
 1480 so that w2 and w1 share the same code. To do this, the coercion axiom
 1481 axT must have
 1482         kind:    axT :: T ~ []
 1483  and    arity:   0
 1484 
 1485 See also Note [Newtype eta and homogeneous axioms] in GHC.Tc.TyCl.Build.
 1486 
 1487 ************************************************************************
 1488 *                                                                      *
 1489                  TyConRepName
 1490 *                                                                      *
 1491 ********************************************************************* -}
 1492 
 1493 type TyConRepName = Name
 1494    -- The Name of the top-level declaration for the Typeable world
 1495    --    $tcMaybe :: Data.Typeable.Internal.TyCon
 1496    --    $tcMaybe = TyCon { tyConName = "Maybe", ... }
 1497 
 1498 tyConRepName_maybe :: TyCon -> Maybe TyConRepName
 1499 tyConRepName_maybe (FunTyCon   { tcRepName = rep_nm })
 1500   = Just rep_nm
 1501 tyConRepName_maybe (PrimTyCon  { primRepName = rep_nm })
 1502   = Just rep_nm
 1503 tyConRepName_maybe (AlgTyCon { algTcParent = parent })
 1504   | VanillaAlgTyCon rep_nm <- parent = Just rep_nm
 1505   | ClassTyCon _ rep_nm    <- parent = Just rep_nm
 1506   | UnboxedAlgTyCon rep_nm <- parent = rep_nm
 1507 tyConRepName_maybe (FamilyTyCon { famTcFlav = DataFamilyTyCon rep_nm })
 1508   = Just rep_nm
 1509 tyConRepName_maybe (PromotedDataCon { dataCon = dc, tcRepName = rep_nm })
 1510   | isUnboxedSumDataCon dc   -- see #13276
 1511   = Nothing
 1512   | otherwise
 1513   = Just rep_nm
 1514 tyConRepName_maybe _ = Nothing
 1515 
 1516 -- | Make a 'Name' for the 'Typeable' representation of the given wired-in type
 1517 mkPrelTyConRepName :: Name -> TyConRepName
 1518 -- See Note [Grand plan for Typeable] in "GHC.Tc.Instance.Typeable".
 1519 mkPrelTyConRepName tc_name  -- Prelude tc_name is always External,
 1520                             -- so nameModule will work
 1521   = mkExternalName rep_uniq rep_mod rep_occ (nameSrcSpan tc_name)
 1522   where
 1523     name_occ  = nameOccName tc_name
 1524     name_mod  = nameModule  tc_name
 1525     name_uniq = nameUnique  tc_name
 1526     rep_uniq | isTcOcc name_occ = tyConRepNameUnique   name_uniq
 1527              | otherwise        = dataConTyRepNameUnique name_uniq
 1528     (rep_mod, rep_occ) = tyConRepModOcc name_mod name_occ
 1529 
 1530 -- | The name (and defining module) for the Typeable representation (TyCon) of a
 1531 -- type constructor.
 1532 --
 1533 -- See Note [Grand plan for Typeable] in "GHC.Tc.Instance.Typeable".
 1534 tyConRepModOcc :: Module -> OccName -> (Module, OccName)
 1535 tyConRepModOcc tc_module tc_occ = (rep_module, mkTyConRepOcc tc_occ)
 1536   where
 1537     rep_module
 1538       | tc_module == gHC_PRIM = gHC_TYPES
 1539       | otherwise             = tc_module
 1540 
 1541 
 1542 {- *********************************************************************
 1543 *                                                                      *
 1544                  PrimRep
 1545 *                                                                      *
 1546 ************************************************************************
 1547 
 1548 Note [rep swamp]
 1549 ~~~~~~~~~~~~~~~~
 1550 GHC has a rich selection of types that represent "primitive types" of
 1551 one kind or another.  Each of them makes a different set of
 1552 distinctions, and mostly the differences are for good reasons,
 1553 although it's probably true that we could merge some of these.
 1554 
 1555 Roughly in order of "includes more information":
 1556 
 1557  - A Width ("GHC.Cmm.Type") is simply a binary value with the specified
 1558    number of bits.  It may represent a signed or unsigned integer, a
 1559    floating-point value, or an address.
 1560 
 1561     data Width = W8 | W16 | W32 | W64  | W128
 1562 
 1563  - Size, which is used in the native code generator, is Width +
 1564    floating point information.
 1565 
 1566    data Size = II8 | II16 | II32 | II64 | FF32 | FF64
 1567 
 1568    it is necessary because e.g. the instruction to move a 64-bit float
 1569    on x86 (movsd) is different from the instruction to move a 64-bit
 1570    integer (movq), so the mov instruction is parameterised by Size.
 1571 
 1572  - CmmType wraps Width with more information: GC ptr, float, or
 1573    other value.
 1574 
 1575     data CmmType = CmmType CmmCat Width
 1576 
 1577     data CmmCat     -- "Category" (not exported)
 1578        = GcPtrCat   -- GC pointer
 1579        | BitsCat    -- Non-pointer
 1580        | FloatCat   -- Float
 1581 
 1582    It is important to have GcPtr information in Cmm, since we generate
 1583    info tables containing pointerhood for the GC from this.  As for
 1584    why we have float (and not signed/unsigned) here, see Note [Signed
 1585    vs unsigned].
 1586 
 1587  - ArgRep makes only the distinctions necessary for the call and
 1588    return conventions of the STG machine.  It is essentially CmmType
 1589    + void.
 1590 
 1591  - PrimRep makes a few more distinctions than ArgRep: it divides
 1592    non-GC-pointers into signed/unsigned and addresses, information
 1593    that is necessary for passing these values to foreign functions.
 1594 
 1595 There's another tension here: whether the type encodes its size in
 1596 bytes, or whether its size depends on the machine word size.  Width
 1597 and CmmType have the size built-in, whereas ArgRep and PrimRep do not.
 1598 
 1599 This means to turn an ArgRep/PrimRep into a CmmType requires DynFlags.
 1600 
 1601 On the other hand, CmmType includes some "nonsense" values, such as
 1602 CmmType GcPtrCat W32 on a 64-bit machine.
 1603 
 1604 The PrimRep type is closely related to the user-visible RuntimeRep type.
 1605 See Note [RuntimeRep and PrimRep] in GHC.Types.RepType.
 1606 
 1607 -}
 1608 
 1609 -- | A 'PrimRep' is an abstraction of a type.  It contains information that
 1610 -- the code generator needs in order to pass arguments, return results,
 1611 -- and store values of this type. See also Note [RuntimeRep and PrimRep] in
 1612 -- "GHC.Types.RepType" and Note [VoidRep] in "GHC.Types.RepType".
 1613 data PrimRep
 1614   = VoidRep
 1615   | LiftedRep
 1616   | UnliftedRep   -- ^ Unlifted pointer
 1617   | Int8Rep       -- ^ Signed, 8-bit value
 1618   | Int16Rep      -- ^ Signed, 16-bit value
 1619   | Int32Rep      -- ^ Signed, 32-bit value
 1620   | Int64Rep      -- ^ Signed, 64 bit value
 1621   | IntRep        -- ^ Signed, word-sized value
 1622   | Word8Rep      -- ^ Unsigned, 8 bit value
 1623   | Word16Rep     -- ^ Unsigned, 16 bit value
 1624   | Word32Rep     -- ^ Unsigned, 32 bit value
 1625   | Word64Rep     -- ^ Unsigned, 64 bit value
 1626   | WordRep       -- ^ Unsigned, word-sized value
 1627   | AddrRep       -- ^ A pointer, but /not/ to a Haskell value (use '(Un)liftedRep')
 1628   | FloatRep
 1629   | DoubleRep
 1630   | VecRep Int PrimElemRep  -- ^ A vector
 1631   deriving( Data.Data, Eq, Ord, Show )
 1632 
 1633 data PrimElemRep
 1634   = Int8ElemRep
 1635   | Int16ElemRep
 1636   | Int32ElemRep
 1637   | Int64ElemRep
 1638   | Word8ElemRep
 1639   | Word16ElemRep
 1640   | Word32ElemRep
 1641   | Word64ElemRep
 1642   | FloatElemRep
 1643   | DoubleElemRep
 1644    deriving( Data.Data, Eq, Ord, Show, Enum )
 1645 
 1646 instance Outputable PrimRep where
 1647   ppr r = text (show r)
 1648 
 1649 instance Outputable PrimElemRep where
 1650   ppr r = text (show r)
 1651 
 1652 instance Binary PrimRep where
 1653   put_ bh VoidRep        = putByte bh 0
 1654   put_ bh LiftedRep      = putByte bh 1
 1655   put_ bh UnliftedRep    = putByte bh 2
 1656   put_ bh Int8Rep        = putByte bh 3
 1657   put_ bh Int16Rep       = putByte bh 4
 1658   put_ bh Int32Rep       = putByte bh 5
 1659   put_ bh Int64Rep       = putByte bh 6
 1660   put_ bh IntRep         = putByte bh 7
 1661   put_ bh Word8Rep       = putByte bh 8
 1662   put_ bh Word16Rep      = putByte bh 9
 1663   put_ bh Word32Rep      = putByte bh 10
 1664   put_ bh Word64Rep      = putByte bh 11
 1665   put_ bh WordRep        = putByte bh 12
 1666   put_ bh AddrRep        = putByte bh 13
 1667   put_ bh FloatRep       = putByte bh 14
 1668   put_ bh DoubleRep      = putByte bh 15
 1669   put_ bh (VecRep n per) = putByte bh 16 *> put_ bh n *> put_ bh per
 1670   get  bh = do
 1671     h <- getByte bh
 1672     case h of
 1673       0  -> pure VoidRep
 1674       1  -> pure LiftedRep
 1675       2  -> pure UnliftedRep
 1676       3  -> pure Int8Rep
 1677       4  -> pure Int16Rep
 1678       5  -> pure Int32Rep
 1679       6  -> pure Int64Rep
 1680       7  -> pure IntRep
 1681       8  -> pure Word8Rep
 1682       9  -> pure Word16Rep
 1683       10 -> pure Word32Rep
 1684       11 -> pure Word64Rep
 1685       12 -> pure WordRep
 1686       13 -> pure AddrRep
 1687       14 -> pure FloatRep
 1688       15 -> pure DoubleRep
 1689       16 -> VecRep <$> get bh <*> get bh
 1690       _  -> pprPanic "Binary:PrimRep" (int (fromIntegral h))
 1691 
 1692 instance Binary PrimElemRep where
 1693   put_ bh per = putByte bh (fromIntegral (fromEnum per))
 1694   get  bh = toEnum . fromIntegral <$> getByte bh
 1695 
 1696 isVoidRep :: PrimRep -> Bool
 1697 isVoidRep VoidRep = True
 1698 isVoidRep _other  = False
 1699 
 1700 isGcPtrRep :: PrimRep -> Bool
 1701 isGcPtrRep LiftedRep   = True
 1702 isGcPtrRep UnliftedRep = True
 1703 isGcPtrRep _           = False
 1704 
 1705 -- A PrimRep is compatible with another iff one can be coerced to the other.
 1706 -- See Note [bad unsafe coercion] in GHC.Core.Lint for when are two types coercible.
 1707 primRepCompatible :: Platform -> PrimRep -> PrimRep -> Bool
 1708 primRepCompatible platform rep1 rep2 =
 1709     (isUnboxed rep1 == isUnboxed rep2) &&
 1710     (primRepSizeB platform rep1 == primRepSizeB platform rep2) &&
 1711     (primRepIsFloat rep1 == primRepIsFloat rep2)
 1712   where
 1713     isUnboxed = not . isGcPtrRep
 1714 
 1715 -- More general version of `primRepCompatible` for types represented by zero or
 1716 -- more than one PrimReps.
 1717 primRepsCompatible :: Platform -> [PrimRep] -> [PrimRep] -> Bool
 1718 primRepsCompatible platform reps1 reps2 =
 1719     length reps1 == length reps2 &&
 1720     and (zipWith (primRepCompatible platform) reps1 reps2)
 1721 
 1722 -- | The size of a 'PrimRep' in bytes.
 1723 --
 1724 -- This applies also when used in a constructor, where we allow packing the
 1725 -- fields. For instance, in @data Foo = Foo Float# Float#@ the two fields will
 1726 -- take only 8 bytes, which for 64-bit arch will be equal to 1 word.
 1727 -- See also mkVirtHeapOffsetsWithPadding for details of how data fields are
 1728 -- laid out.
 1729 primRepSizeB :: Platform -> PrimRep -> Int
 1730 primRepSizeB platform = \case
 1731    IntRep           -> platformWordSizeInBytes platform
 1732    WordRep          -> platformWordSizeInBytes platform
 1733    Int8Rep          -> 1
 1734    Int16Rep         -> 2
 1735    Int32Rep         -> 4
 1736    Int64Rep         -> 8
 1737    Word8Rep         -> 1
 1738    Word16Rep        -> 2
 1739    Word32Rep        -> 4
 1740    Word64Rep        -> 8
 1741    FloatRep         -> fLOAT_SIZE
 1742    DoubleRep        -> dOUBLE_SIZE
 1743    AddrRep          -> platformWordSizeInBytes platform
 1744    LiftedRep        -> platformWordSizeInBytes platform
 1745    UnliftedRep      -> platformWordSizeInBytes platform
 1746    VoidRep          -> 0
 1747    (VecRep len rep) -> len * primElemRepSizeB platform rep
 1748 
 1749 primElemRepSizeB :: Platform -> PrimElemRep -> Int
 1750 primElemRepSizeB platform = primRepSizeB platform . primElemRepToPrimRep
 1751 
 1752 primElemRepToPrimRep :: PrimElemRep -> PrimRep
 1753 primElemRepToPrimRep Int8ElemRep   = Int8Rep
 1754 primElemRepToPrimRep Int16ElemRep  = Int16Rep
 1755 primElemRepToPrimRep Int32ElemRep  = Int32Rep
 1756 primElemRepToPrimRep Int64ElemRep  = Int64Rep
 1757 primElemRepToPrimRep Word8ElemRep  = Word8Rep
 1758 primElemRepToPrimRep Word16ElemRep = Word16Rep
 1759 primElemRepToPrimRep Word32ElemRep = Word32Rep
 1760 primElemRepToPrimRep Word64ElemRep = Word64Rep
 1761 primElemRepToPrimRep FloatElemRep  = FloatRep
 1762 primElemRepToPrimRep DoubleElemRep = DoubleRep
 1763 
 1764 -- | Return if Rep stands for floating type,
 1765 -- returns Nothing for vector types.
 1766 primRepIsFloat :: PrimRep -> Maybe Bool
 1767 primRepIsFloat  FloatRep     = Just True
 1768 primRepIsFloat  DoubleRep    = Just True
 1769 primRepIsFloat  (VecRep _ _) = Nothing
 1770 primRepIsFloat  _            = Just False
 1771 
 1772 {-
 1773 ************************************************************************
 1774 *                                                                      *
 1775                              Field labels
 1776 *                                                                      *
 1777 ************************************************************************
 1778 -}
 1779 
 1780 -- | The labels for the fields of this particular 'TyCon'
 1781 tyConFieldLabels :: TyCon -> [FieldLabel]
 1782 tyConFieldLabels tc = dFsEnvElts $ tyConFieldLabelEnv tc
 1783 
 1784 -- | The labels for the fields of this particular 'TyCon'
 1785 tyConFieldLabelEnv :: TyCon -> FieldLabelEnv
 1786 tyConFieldLabelEnv tc
 1787   | isAlgTyCon tc = algTcFields tc
 1788   | otherwise     = emptyDFsEnv
 1789 
 1790 -- | Look up a field label belonging to this 'TyCon'
 1791 lookupTyConFieldLabel :: FieldLabelString -> TyCon -> Maybe FieldLabel
 1792 lookupTyConFieldLabel lbl tc = lookupDFsEnv (tyConFieldLabelEnv tc) lbl
 1793 
 1794 -- | Make a map from strings to FieldLabels from all the data
 1795 -- constructors of this algebraic tycon
 1796 fieldsOfAlgTcRhs :: AlgTyConRhs -> FieldLabelEnv
 1797 fieldsOfAlgTcRhs rhs = mkDFsEnv [ (flLabel fl, fl)
 1798                                 | fl <- dataConsFields (visibleDataCons rhs) ]
 1799   where
 1800     -- Duplicates in this list will be removed by 'mkFsEnv'
 1801     dataConsFields dcs = concatMap dataConFieldLabels dcs
 1802 
 1803 
 1804 {-
 1805 ************************************************************************
 1806 *                                                                      *
 1807 \subsection{TyCon Construction}
 1808 *                                                                      *
 1809 ************************************************************************
 1810 
 1811 Note: the TyCon constructors all take a Kind as one argument, even though
 1812 they could, in principle, work out their Kind from their other arguments.
 1813 But to do so they need functions from Types, and that makes a nasty
 1814 module mutual-recursion.  And they aren't called from many places.
 1815 So we compromise, and move their Kind calculation to the call site.
 1816 -}
 1817 
 1818 -- | Given the name of the function type constructor and it's kind, create the
 1819 -- corresponding 'TyCon'. It is recommended to use 'GHC.Core.TyCo.Rep.funTyCon' if you want
 1820 -- this functionality
 1821 mkFunTyCon :: Name -> [TyConBinder] -> Name -> TyCon
 1822 mkFunTyCon name binders rep_nm
 1823   = let tc =
 1824           FunTyCon {
 1825               tyConUnique  = nameUnique name,
 1826               tyConName    = name,
 1827               tyConBinders = binders,
 1828               tyConResKind = liftedTypeKind,
 1829               tyConKind    = mkTyConKind binders liftedTypeKind,
 1830               tyConArity   = length binders,
 1831               tyConNullaryTy = mkTyConTy_ tc,
 1832               tcRepName    = rep_nm
 1833           }
 1834     in tc
 1835 
 1836 -- | This is the making of an algebraic 'TyCon'.
 1837 mkAlgTyCon :: Name
 1838            -> [TyConBinder]  -- ^ Binders of the 'TyCon'
 1839            -> Kind              -- ^ Result kind
 1840            -> [Role]            -- ^ The roles for each TyVar
 1841            -> Maybe CType       -- ^ The C type this type corresponds to
 1842                                 --   when using the CAPI FFI
 1843            -> [PredType]        -- ^ Stupid theta: see 'algTcStupidTheta'
 1844            -> AlgTyConRhs       -- ^ Information about data constructors
 1845            -> AlgTyConFlav      -- ^ What flavour is it?
 1846                                 -- (e.g. vanilla, type family)
 1847            -> Bool              -- ^ Was the 'TyCon' declared with GADT syntax?
 1848            -> TyCon
 1849 mkAlgTyCon name binders res_kind roles cType stupid rhs parent gadt_syn
 1850   = let tc =
 1851           AlgTyCon {
 1852               tyConName        = name,
 1853               tyConUnique      = nameUnique name,
 1854               tyConBinders     = binders,
 1855               tyConResKind     = res_kind,
 1856               tyConKind        = mkTyConKind binders res_kind,
 1857               tyConArity       = length binders,
 1858               tyConNullaryTy   = mkTyConTy_ tc,
 1859               tyConTyVars      = binderVars binders,
 1860               tcRoles          = roles,
 1861               tyConCType       = cType,
 1862               algTcStupidTheta = stupid,
 1863               algTcRhs         = rhs,
 1864               algTcFields      = fieldsOfAlgTcRhs rhs,
 1865               algTcParent      = assertPpr (okParent name parent) (ppr name $$ ppr parent) parent,
 1866               algTcGadtSyntax  = gadt_syn
 1867           }
 1868     in tc
 1869 
 1870 -- | Simpler specialization of 'mkAlgTyCon' for classes
 1871 mkClassTyCon :: Name -> [TyConBinder]
 1872              -> [Role] -> AlgTyConRhs -> Class
 1873              -> Name -> TyCon
 1874 mkClassTyCon name binders roles rhs clas tc_rep_name
 1875   = mkAlgTyCon name binders constraintKind roles Nothing [] rhs
 1876                (ClassTyCon clas tc_rep_name)
 1877                False
 1878 
 1879 mkTupleTyCon :: Name
 1880              -> [TyConBinder]
 1881              -> Kind    -- ^ Result kind of the 'TyCon'
 1882              -> Arity   -- ^ Arity of the tuple 'TyCon'
 1883              -> DataCon
 1884              -> TupleSort    -- ^ Whether the tuple is boxed or unboxed
 1885              -> AlgTyConFlav
 1886              -> TyCon
 1887 mkTupleTyCon name binders res_kind arity con sort parent
 1888   = let tc =
 1889           AlgTyCon {
 1890               tyConUnique      = nameUnique name,
 1891               tyConName        = name,
 1892               tyConBinders     = binders,
 1893               tyConTyVars      = binderVars binders,
 1894               tyConResKind     = res_kind,
 1895               tyConKind        = mkTyConKind binders res_kind,
 1896               tyConArity       = arity,
 1897               tyConNullaryTy   = mkTyConTy_ tc,
 1898               tcRoles          = replicate arity Representational,
 1899               tyConCType       = Nothing,
 1900               algTcGadtSyntax  = False,
 1901               algTcStupidTheta = [],
 1902               algTcRhs         = TupleTyCon { data_con = con,
 1903                                               tup_sort = sort },
 1904               algTcFields      = emptyDFsEnv,
 1905               algTcParent      = parent
 1906           }
 1907     in tc
 1908 
 1909 mkSumTyCon :: Name
 1910              -> [TyConBinder]
 1911              -> Kind    -- ^ Kind of the resulting 'TyCon'
 1912              -> Arity   -- ^ Arity of the sum
 1913              -> [TyVar] -- ^ 'TyVar's scoped over: see 'tyConTyVars'
 1914              -> [DataCon]
 1915              -> AlgTyConFlav
 1916              -> TyCon
 1917 mkSumTyCon name binders res_kind arity tyvars cons parent
 1918   = let tc =
 1919           AlgTyCon {
 1920               tyConUnique      = nameUnique name,
 1921               tyConName        = name,
 1922               tyConBinders     = binders,
 1923               tyConTyVars      = tyvars,
 1924               tyConResKind     = res_kind,
 1925               tyConKind        = mkTyConKind binders res_kind,
 1926               tyConArity       = arity,
 1927               tyConNullaryTy   = mkTyConTy_ tc,
 1928               tcRoles          = replicate arity Representational,
 1929               tyConCType       = Nothing,
 1930               algTcGadtSyntax  = False,
 1931               algTcStupidTheta = [],
 1932               algTcRhs         = mkSumTyConRhs cons,
 1933               algTcFields      = emptyDFsEnv,
 1934               algTcParent      = parent
 1935           }
 1936     in tc
 1937 
 1938 -- | Makes a tycon suitable for use during type-checking. It stores
 1939 -- a variety of details about the definition of the TyCon, but no
 1940 -- right-hand side. It lives only during the type-checking of a
 1941 -- mutually-recursive group of tycons; it is then zonked to a proper
 1942 -- TyCon in zonkTcTyCon.
 1943 -- See also Note [Kind checking recursive type and class declarations]
 1944 -- in "GHC.Tc.TyCl".
 1945 mkTcTyCon :: Name
 1946           -> [TyConBinder]
 1947           -> Kind                -- ^ /result/ kind only
 1948           -> [(Name,TcTyVar)]    -- ^ Scoped type variables;
 1949                                  -- see Note [How TcTyCons work] in GHC.Tc.TyCl
 1950           -> Bool                -- ^ Is this TcTyCon generalised already?
 1951           -> TyConFlavour        -- ^ What sort of 'TyCon' this represents
 1952           -> TyCon
 1953 mkTcTyCon name binders res_kind scoped_tvs poly flav
 1954   = let tc =
 1955           TcTyCon { tyConUnique  = getUnique name
 1956                   , tyConName    = name
 1957                   , tyConTyVars  = binderVars binders
 1958                   , tyConBinders = binders
 1959                   , tyConResKind = res_kind
 1960                   , tyConKind    = mkTyConKind binders res_kind
 1961                   , tyConArity   = length binders
 1962                   , tyConNullaryTy = mkTyConTy_ tc
 1963                   , tcTyConScopedTyVars = scoped_tvs
 1964                   , tcTyConIsPoly       = poly
 1965                   , tcTyConFlavour      = flav }
 1966     in tc
 1967 
 1968 -- | No scoped type variables (to be used with mkTcTyCon).
 1969 noTcTyConScopedTyVars :: [(Name, TcTyVar)]
 1970 noTcTyConScopedTyVars = []
 1971 
 1972 -- | Create an unlifted primitive 'TyCon', such as @Int#@.
 1973 mkPrimTyCon :: Name -> [TyConBinder]
 1974             -> Kind   -- ^ /result/ kind
 1975                       -- Must answer 'True' to 'isFixedRuntimeRepKind' (no representation polymorphism).
 1976             -> [Role] -> TyCon
 1977 mkPrimTyCon name binders res_kind roles
 1978   = mkPrimTyCon' name binders res_kind roles True (mkPrelTyConRepName name)
 1979 
 1980 -- | Kind constructors
 1981 mkKindTyCon :: Name -> [TyConBinder]
 1982             -> Kind  -- ^ /result/ kind
 1983             -> [Role] -> Name -> TyCon
 1984 mkKindTyCon name binders res_kind roles rep_nm
 1985   = tc
 1986   where
 1987     tc = mkPrimTyCon' name binders res_kind roles False rep_nm
 1988 
 1989 -- | Create a lifted primitive 'TyCon' such as @RealWorld@
 1990 mkLiftedPrimTyCon :: Name -> [TyConBinder]
 1991                   -> Kind   -- ^ /result/ kind
 1992                   -> [Role] -> TyCon
 1993 mkLiftedPrimTyCon name binders res_kind roles
 1994   = mkPrimTyCon' name binders res_kind roles False rep_nm
 1995   where rep_nm = mkPrelTyConRepName name
 1996 
 1997 mkPrimTyCon' :: Name -> [TyConBinder]
 1998              -> Kind    -- ^ /result/ kind
 1999                         -- Must answer 'True' to 'isFixedRuntimeRepKind' (i.e., no representation polymorphism).
 2000                         -- (If you need a representation-polymorphic PrimTyCon,
 2001                         -- change tcHasFixedRuntimeRep.)
 2002              -> [Role]
 2003              -> Bool -> TyConRepName -> TyCon
 2004 mkPrimTyCon' name binders res_kind roles is_unlifted rep_nm
 2005   = let tc =
 2006           PrimTyCon {
 2007               tyConName    = name,
 2008               tyConUnique  = nameUnique name,
 2009               tyConBinders = binders,
 2010               tyConResKind = res_kind,
 2011               tyConKind    = mkTyConKind binders res_kind,
 2012               tyConArity   = length roles,
 2013               tyConNullaryTy = mkTyConTy_ tc,
 2014               tcRoles      = roles,
 2015               isUnlifted   = is_unlifted,
 2016               primRepName  = rep_nm
 2017           }
 2018     in tc
 2019 
 2020 -- | Create a type synonym 'TyCon'
 2021 mkSynonymTyCon :: Name -> [TyConBinder] -> Kind   -- ^ /result/ kind
 2022                -> [Role] -> Type -> Bool -> Bool -> Bool -> TyCon
 2023 mkSynonymTyCon name binders res_kind roles rhs is_tau is_fam_free is_forgetful
 2024   = let tc =
 2025           SynonymTyCon {
 2026               tyConName      = name,
 2027               tyConUnique    = nameUnique name,
 2028               tyConBinders   = binders,
 2029               tyConResKind   = res_kind,
 2030               tyConKind      = mkTyConKind binders res_kind,
 2031               tyConArity     = length binders,
 2032               tyConNullaryTy = mkTyConTy_ tc,
 2033               tyConTyVars    = binderVars binders,
 2034               tcRoles        = roles,
 2035               synTcRhs       = rhs,
 2036               synIsTau       = is_tau,
 2037               synIsFamFree   = is_fam_free,
 2038               synIsForgetful = is_forgetful
 2039           }
 2040     in tc
 2041 
 2042 -- | Create a type family 'TyCon'
 2043 mkFamilyTyCon :: Name -> [TyConBinder] -> Kind  -- ^ /result/ kind
 2044               -> Maybe Name -> FamTyConFlav
 2045               -> Maybe Class -> Injectivity -> TyCon
 2046 mkFamilyTyCon name binders res_kind resVar flav parent inj
 2047   = let tc =
 2048           FamilyTyCon
 2049             { tyConUnique  = nameUnique name
 2050             , tyConName    = name
 2051             , tyConBinders = binders
 2052             , tyConResKind = res_kind
 2053             , tyConKind    = mkTyConKind binders res_kind
 2054             , tyConArity   = length binders
 2055             , tyConNullaryTy = mkTyConTy_ tc
 2056             , tyConTyVars  = binderVars binders
 2057             , famTcResVar  = resVar
 2058             , famTcFlav    = flav
 2059             , famTcParent  = classTyCon <$> parent
 2060             , famTcInj     = inj
 2061             }
 2062     in tc
 2063 
 2064 
 2065 -- | Create a promoted data constructor 'TyCon'
 2066 -- Somewhat dodgily, we give it the same Name
 2067 -- as the data constructor itself; when we pretty-print
 2068 -- the TyCon we add a quote; see the Outputable TyCon instance
 2069 mkPromotedDataCon :: DataCon -> Name -> TyConRepName
 2070                   -> [TyConTyCoBinder] -> Kind -> [Role]
 2071                   -> RuntimeRepInfo -> TyCon
 2072 mkPromotedDataCon con name rep_name binders res_kind roles rep_info
 2073   = let tc =
 2074           PromotedDataCon {
 2075             tyConUnique   = nameUnique name,
 2076             tyConName     = name,
 2077             tyConArity    = length roles,
 2078             tyConNullaryTy = mkTyConTy_ tc,
 2079             tcRoles       = roles,
 2080             tyConBinders  = binders,
 2081             tyConResKind  = res_kind,
 2082             tyConKind     = mkTyConKind binders res_kind,
 2083             dataCon       = con,
 2084             tcRepName     = rep_name,
 2085             promDcRepInfo = rep_info
 2086           }
 2087     in tc
 2088 
 2089 isFunTyCon :: TyCon -> Bool
 2090 isFunTyCon (FunTyCon {}) = True
 2091 isFunTyCon _             = False
 2092 
 2093 -- | Test if the 'TyCon' is algebraic but abstract (invisible data constructors)
 2094 isAbstractTyCon :: TyCon -> Bool
 2095 isAbstractTyCon (AlgTyCon { algTcRhs = AbstractTyCon {} }) = True
 2096 isAbstractTyCon _ = False
 2097 
 2098 -- | Does this 'TyCon' represent something that cannot be defined in Haskell?
 2099 isPrimTyCon :: TyCon -> Bool
 2100 isPrimTyCon (PrimTyCon {}) = True
 2101 isPrimTyCon _              = False
 2102 
 2103 -- | Is this 'TyCon' unlifted (i.e. cannot contain bottom)? Note that this can
 2104 -- only be true for primitive and unboxed-tuple 'TyCon's
 2105 isUnliftedTyCon :: TyCon -> Bool
 2106 isUnliftedTyCon (PrimTyCon  {isUnlifted = is_unlifted})
 2107   = is_unlifted
 2108 isUnliftedTyCon (AlgTyCon { algTcRhs = rhs } )
 2109   | TupleTyCon { tup_sort = sort } <- rhs
 2110   = not (isBoxed (tupleSortBoxity sort))
 2111 isUnliftedTyCon (AlgTyCon { algTcRhs = rhs } )
 2112   | SumTyCon {} <- rhs
 2113   = True
 2114 isUnliftedTyCon _ = False
 2115 
 2116 -- | Returns @True@ if the supplied 'TyCon' resulted from either a
 2117 -- @data@ or @newtype@ declaration
 2118 isAlgTyCon :: TyCon -> Bool
 2119 isAlgTyCon (AlgTyCon {})   = True
 2120 isAlgTyCon _               = False
 2121 
 2122 -- | Returns @True@ for vanilla AlgTyCons -- that is, those created
 2123 -- with a @data@ or @newtype@ declaration.
 2124 isVanillaAlgTyCon :: TyCon -> Bool
 2125 isVanillaAlgTyCon (AlgTyCon { algTcParent = VanillaAlgTyCon _ }) = True
 2126 isVanillaAlgTyCon _                                              = False
 2127 
 2128 -- | Returns @True@ for the 'TyCon' of the 'Constraint' kind.
 2129 {-# INLINE isConstraintKindCon #-} -- See Note [Inlining coreView] in GHC.Core.Type
 2130 isConstraintKindCon :: TyCon -> Bool
 2131 -- NB: We intentionally match on AlgTyCon, because 'constraintKindTyCon' is
 2132 -- always an AlgTyCon (see 'pcTyCon' in TysWiredIn) and the record selector
 2133 -- for 'tyConUnique' would generate unreachable code for every other data
 2134 -- constructor of TyCon (see #18026).
 2135 isConstraintKindCon AlgTyCon { tyConUnique = u } = u == constraintKindTyConKey
 2136 isConstraintKindCon _                            = False
 2137 
 2138 isDataTyCon :: TyCon -> Bool
 2139 -- ^ Returns @True@ for data types that are /definitely/ represented by
 2140 -- heap-allocated constructors.  These are scrutinised by Core-level
 2141 -- @case@ expressions, and they get info tables allocated for them.
 2142 --
 2143 -- Generally, the function will be true for all @data@ types and false
 2144 -- for @newtype@s, unboxed tuples, unboxed sums and type family
 2145 -- 'TyCon's. But it is not guaranteed to return @True@ in all cases
 2146 -- that it could.
 2147 --
 2148 -- NB: for a data type family, only the /instance/ 'TyCon's
 2149 --     get an info table.  The family declaration 'TyCon' does not
 2150 isDataTyCon (AlgTyCon {algTcRhs = rhs})
 2151   = case rhs of
 2152         TupleTyCon { tup_sort = sort }
 2153                            -> isBoxed (tupleSortBoxity sort)
 2154         SumTyCon {}        -> False
 2155         DataTyCon {}       -> True
 2156         NewTyCon {}        -> False
 2157         AbstractTyCon {}   -> False      -- We don't know, so return False
 2158 isDataTyCon _ = False
 2159 
 2160 -- | 'isInjectiveTyCon' is true of 'TyCon's for which this property holds
 2161 -- (where X is the role passed in):
 2162 --   If (T a1 b1 c1) ~X (T a2 b2 c2), then (a1 ~X1 a2), (b1 ~X2 b2), and (c1 ~X3 c2)
 2163 -- (where X1, X2, and X3, are the roles given by tyConRolesX tc X)
 2164 -- See also Note [Decomposing equality] in "GHC.Tc.Solver.Canonical"
 2165 isInjectiveTyCon :: TyCon -> Role -> Bool
 2166 isInjectiveTyCon _                             Phantom          = False
 2167 isInjectiveTyCon (FunTyCon {})                 _                = True
 2168 isInjectiveTyCon (AlgTyCon {})                 Nominal          = True
 2169 isInjectiveTyCon (AlgTyCon {algTcRhs = rhs})   Representational
 2170   = isGenInjAlgRhs rhs
 2171 isInjectiveTyCon (SynonymTyCon {})             _                = False
 2172 isInjectiveTyCon (FamilyTyCon { famTcFlav = DataFamilyTyCon _ })
 2173                                                Nominal          = True
 2174 isInjectiveTyCon (FamilyTyCon { famTcInj = Injective inj }) Nominal = and inj
 2175 isInjectiveTyCon (FamilyTyCon {})              _                = False
 2176 isInjectiveTyCon (PrimTyCon {})                _                = True
 2177 isInjectiveTyCon (PromotedDataCon {})          _                = True
 2178 isInjectiveTyCon (TcTyCon {})                  _                = True
 2179   -- Reply True for TcTyCon to minimise knock on type errors
 2180   -- See Note [How TcTyCons work] item (1) in GHC.Tc.TyCl
 2181 
 2182 -- | 'isGenerativeTyCon' is true of 'TyCon's for which this property holds
 2183 -- (where X is the role passed in):
 2184 --   If (T tys ~X t), then (t's head ~X T).
 2185 -- See also Note [Decomposing equality] in "GHC.Tc.Solver.Canonical"
 2186 isGenerativeTyCon :: TyCon -> Role -> Bool
 2187 isGenerativeTyCon (FamilyTyCon { famTcFlav = DataFamilyTyCon _ }) Nominal = True
 2188 isGenerativeTyCon (FamilyTyCon {}) _ = False
 2189   -- in all other cases, injectivity implies generativity
 2190 isGenerativeTyCon tc               r = isInjectiveTyCon tc r
 2191 
 2192 -- | Is this an 'AlgTyConRhs' of a 'TyCon' that is generative and injective
 2193 -- with respect to representational equality?
 2194 isGenInjAlgRhs :: AlgTyConRhs -> Bool
 2195 isGenInjAlgRhs (TupleTyCon {})          = True
 2196 isGenInjAlgRhs (SumTyCon {})            = True
 2197 isGenInjAlgRhs (DataTyCon {})           = True
 2198 isGenInjAlgRhs (AbstractTyCon {})       = False
 2199 isGenInjAlgRhs (NewTyCon {})            = False
 2200 
 2201 -- | Is this 'TyCon' that for a @newtype@
 2202 isNewTyCon :: TyCon -> Bool
 2203 isNewTyCon (AlgTyCon {algTcRhs = NewTyCon {}}) = True
 2204 isNewTyCon _                                   = False
 2205 
 2206 -- | Take a 'TyCon' apart into the 'TyVar's it scopes over, the 'Type' it
 2207 -- expands into, and (possibly) a coercion from the representation type to the
 2208 -- @newtype@.
 2209 -- Returns @Nothing@ if this is not possible.
 2210 unwrapNewTyCon_maybe :: TyCon -> Maybe ([TyVar], Type, CoAxiom Unbranched)
 2211 unwrapNewTyCon_maybe (AlgTyCon { tyConTyVars = tvs,
 2212                                  algTcRhs = NewTyCon { nt_co = co,
 2213                                                        nt_rhs = rhs }})
 2214                            = Just (tvs, rhs, co)
 2215 unwrapNewTyCon_maybe _     = Nothing
 2216 
 2217 unwrapNewTyConEtad_maybe :: TyCon -> Maybe ([TyVar], Type, CoAxiom Unbranched)
 2218 unwrapNewTyConEtad_maybe (AlgTyCon { algTcRhs = NewTyCon { nt_co = co,
 2219                                                            nt_etad_rhs = (tvs,rhs) }})
 2220                            = Just (tvs, rhs, co)
 2221 unwrapNewTyConEtad_maybe _ = Nothing
 2222 
 2223 -- | Is this a 'TyCon' representing a regular H98 type synonym (@type@)?
 2224 {-# INLINE isTypeSynonymTyCon #-}  -- See Note [Inlining coreView] in GHC.Core.Type
 2225 isTypeSynonymTyCon :: TyCon -> Bool
 2226 isTypeSynonymTyCon (SynonymTyCon {}) = True
 2227 isTypeSynonymTyCon _                 = False
 2228 
 2229 isTauTyCon :: TyCon -> Bool
 2230 isTauTyCon (SynonymTyCon { synIsTau = is_tau }) = is_tau
 2231 isTauTyCon _                                    = True
 2232 
 2233 -- | Is this tycon neither a type family nor a synonym that expands
 2234 -- to a type family?
 2235 isFamFreeTyCon :: TyCon -> Bool
 2236 isFamFreeTyCon (SynonymTyCon { synIsFamFree = fam_free }) = fam_free
 2237 isFamFreeTyCon (FamilyTyCon { famTcFlav = flav })         = isDataFamFlav flav
 2238 isFamFreeTyCon _                                          = True
 2239 
 2240 -- | Is this a forgetful type synonym? If this is a type synonym whose
 2241 -- RHS does not mention one (or more) of its bound variables, returns
 2242 -- True. Thus, False means that all bound variables appear on the RHS;
 2243 -- True may not mean anything, as the test to set this flag is
 2244 -- conservative.
 2245 isForgetfulSynTyCon :: TyCon -> Bool
 2246 isForgetfulSynTyCon (SynonymTyCon { synIsForgetful = forget }) = forget
 2247 isForgetfulSynTyCon _                                          = False
 2248 
 2249 -- As for newtypes, it is in some contexts important to distinguish between
 2250 -- closed synonyms and synonym families, as synonym families have no unique
 2251 -- right hand side to which a synonym family application can expand.
 2252 --
 2253 
 2254 -- | True iff we can decompose (T a b c) into ((T a b) c)
 2255 --   I.e. is it injective and generative w.r.t nominal equality?
 2256 --   That is, if (T a b) ~N d e f, is it always the case that
 2257 --            (T ~N d), (a ~N e) and (b ~N f)?
 2258 -- Specifically NOT true of synonyms (open and otherwise)
 2259 --
 2260 -- It'd be unusual to call mustBeSaturated on a regular H98
 2261 -- type synonym, because you should probably have expanded it first
 2262 -- But regardless, it's not decomposable
 2263 mustBeSaturated :: TyCon -> Bool
 2264 mustBeSaturated = tcFlavourMustBeSaturated . tyConFlavour
 2265 
 2266 -- | Is this an algebraic 'TyCon' declared with the GADT syntax?
 2267 isGadtSyntaxTyCon :: TyCon -> Bool
 2268 isGadtSyntaxTyCon (AlgTyCon { algTcGadtSyntax = res }) = res
 2269 isGadtSyntaxTyCon _                                    = False
 2270 
 2271 -- | Is this an algebraic 'TyCon' which is just an enumeration of values?
 2272 isEnumerationTyCon :: TyCon -> Bool
 2273 -- See Note [Enumeration types] in GHC.Core.TyCon
 2274 isEnumerationTyCon (AlgTyCon { tyConArity = arity, algTcRhs = rhs })
 2275   = case rhs of
 2276        DataTyCon { is_enum = res } -> res
 2277        TupleTyCon {}               -> arity == 0
 2278        _                           -> False
 2279 isEnumerationTyCon _ = False
 2280 
 2281 -- | Is this a 'TyCon', synonym or otherwise, that defines a family?
 2282 isFamilyTyCon :: TyCon -> Bool
 2283 isFamilyTyCon (FamilyTyCon {}) = True
 2284 isFamilyTyCon _                = False
 2285 
 2286 -- | Is this a 'TyCon', synonym or otherwise, that defines a family with
 2287 -- instances?
 2288 isOpenFamilyTyCon :: TyCon -> Bool
 2289 isOpenFamilyTyCon (FamilyTyCon {famTcFlav = flav })
 2290   | OpenSynFamilyTyCon <- flav = True
 2291   | DataFamilyTyCon {} <- flav = True
 2292 isOpenFamilyTyCon _            = False
 2293 
 2294 -- | Is this a synonym 'TyCon' that can have may have further instances appear?
 2295 isTypeFamilyTyCon :: TyCon -> Bool
 2296 isTypeFamilyTyCon (FamilyTyCon { famTcFlav = flav }) = not (isDataFamFlav flav)
 2297 isTypeFamilyTyCon _                                  = False
 2298 
 2299 -- | Is this a synonym 'TyCon' that can have may have further instances appear?
 2300 isDataFamilyTyCon :: TyCon -> Bool
 2301 isDataFamilyTyCon (FamilyTyCon { famTcFlav = flav }) = isDataFamFlav flav
 2302 isDataFamilyTyCon _                                  = False
 2303 
 2304 -- | Is this an open type family TyCon?
 2305 isOpenTypeFamilyTyCon :: TyCon -> Bool
 2306 isOpenTypeFamilyTyCon (FamilyTyCon {famTcFlav = OpenSynFamilyTyCon }) = True
 2307 isOpenTypeFamilyTyCon _                                               = False
 2308 
 2309 -- | Is this a non-empty closed type family? Returns 'Nothing' for
 2310 -- abstract or empty closed families.
 2311 isClosedSynFamilyTyConWithAxiom_maybe :: TyCon -> Maybe (CoAxiom Branched)
 2312 isClosedSynFamilyTyConWithAxiom_maybe
 2313   (FamilyTyCon {famTcFlav = ClosedSynFamilyTyCon mb}) = mb
 2314 isClosedSynFamilyTyConWithAxiom_maybe _               = Nothing
 2315 
 2316 -- | @'tyConInjectivityInfo' tc@ returns @'Injective' is@ if @tc@ is an
 2317 -- injective tycon (where @is@ states for which 'tyConBinders' @tc@ is
 2318 -- injective), or 'NotInjective' otherwise.
 2319 tyConInjectivityInfo :: TyCon -> Injectivity
 2320 tyConInjectivityInfo tc
 2321   | FamilyTyCon { famTcInj = inj } <- tc
 2322   = inj
 2323   | isInjectiveTyCon tc Nominal
 2324   = Injective (replicate (tyConArity tc) True)
 2325   | otherwise
 2326   = NotInjective
 2327 
 2328 isBuiltInSynFamTyCon_maybe :: TyCon -> Maybe BuiltInSynFamily
 2329 isBuiltInSynFamTyCon_maybe
 2330   (FamilyTyCon {famTcFlav = BuiltInSynFamTyCon ops }) = Just ops
 2331 isBuiltInSynFamTyCon_maybe _                          = Nothing
 2332 
 2333 isDataFamFlav :: FamTyConFlav -> Bool
 2334 isDataFamFlav (DataFamilyTyCon {}) = True   -- Data family
 2335 isDataFamFlav _                    = False  -- Type synonym family
 2336 
 2337 -- | Is this TyCon for an associated type?
 2338 isTyConAssoc :: TyCon -> Bool
 2339 isTyConAssoc = isJust . tyConAssoc_maybe
 2340 
 2341 -- | Get the enclosing class TyCon (if there is one) for the given TyCon.
 2342 tyConAssoc_maybe :: TyCon -> Maybe TyCon
 2343 tyConAssoc_maybe = tyConFlavourAssoc_maybe . tyConFlavour
 2344 
 2345 -- | Get the enclosing class TyCon (if there is one) for the given TyConFlavour
 2346 tyConFlavourAssoc_maybe :: TyConFlavour -> Maybe TyCon
 2347 tyConFlavourAssoc_maybe (DataFamilyFlavour mb_parent)     = mb_parent
 2348 tyConFlavourAssoc_maybe (OpenTypeFamilyFlavour mb_parent) = mb_parent
 2349 tyConFlavourAssoc_maybe _                                 = Nothing
 2350 
 2351 -- The unit tycon didn't used to be classed as a tuple tycon
 2352 -- but I thought that was silly so I've undone it
 2353 -- If it can't be for some reason, it should be a AlgTyCon
 2354 isTupleTyCon :: TyCon -> Bool
 2355 -- ^ Does this 'TyCon' represent a tuple?
 2356 --
 2357 -- NB: when compiling @Data.Tuple@, the tycons won't reply @True@ to
 2358 -- 'isTupleTyCon', because they are built as 'AlgTyCons'.  However they
 2359 -- get spat into the interface file as tuple tycons, so I don't think
 2360 -- it matters.
 2361 isTupleTyCon (AlgTyCon { algTcRhs = TupleTyCon {} }) = True
 2362 isTupleTyCon _ = False
 2363 
 2364 tyConTuple_maybe :: TyCon -> Maybe TupleSort
 2365 tyConTuple_maybe (AlgTyCon { algTcRhs = rhs })
 2366   | TupleTyCon { tup_sort = sort} <- rhs = Just sort
 2367 tyConTuple_maybe _                       = Nothing
 2368 
 2369 -- | Is this the 'TyCon' for an unboxed tuple?
 2370 isUnboxedTupleTyCon :: TyCon -> Bool
 2371 isUnboxedTupleTyCon (AlgTyCon { algTcRhs = rhs })
 2372   | TupleTyCon { tup_sort = sort } <- rhs
 2373   = not (isBoxed (tupleSortBoxity sort))
 2374 isUnboxedTupleTyCon _ = False
 2375 
 2376 -- | Is this the 'TyCon' for a boxed tuple?
 2377 isBoxedTupleTyCon :: TyCon -> Bool
 2378 isBoxedTupleTyCon (AlgTyCon { algTcRhs = rhs })
 2379   | TupleTyCon { tup_sort = sort } <- rhs
 2380   = isBoxed (tupleSortBoxity sort)
 2381 isBoxedTupleTyCon _ = False
 2382 
 2383 -- | Is this the 'TyCon' for an unboxed sum?
 2384 isUnboxedSumTyCon :: TyCon -> Bool
 2385 isUnboxedSumTyCon (AlgTyCon { algTcRhs = rhs })
 2386   | SumTyCon {} <- rhs
 2387   = True
 2388 isUnboxedSumTyCon _ = False
 2389 
 2390 -- | Is this the 'TyCon' for a /promoted/ tuple?
 2391 isPromotedTupleTyCon :: TyCon -> Bool
 2392 isPromotedTupleTyCon tyCon
 2393   | Just dataCon <- isPromotedDataCon_maybe tyCon
 2394   , isTupleTyCon (dataConTyCon dataCon) = True
 2395   | otherwise                           = False
 2396 
 2397 -- | Is this a PromotedDataCon?
 2398 isPromotedDataCon :: TyCon -> Bool
 2399 isPromotedDataCon (PromotedDataCon {}) = True
 2400 isPromotedDataCon _                    = False
 2401 
 2402 -- | Retrieves the promoted DataCon if this is a PromotedDataCon;
 2403 isPromotedDataCon_maybe :: TyCon -> Maybe DataCon
 2404 isPromotedDataCon_maybe (PromotedDataCon { dataCon = dc }) = Just dc
 2405 isPromotedDataCon_maybe _ = Nothing
 2406 
 2407 -- | Is this tycon really meant for use at the kind level? That is,
 2408 -- should it be permitted without -XDataKinds?
 2409 isKindTyCon :: TyCon -> Bool
 2410 isKindTyCon tc = getUnique tc `elementOfUniqSet` kindTyConKeys
 2411 
 2412 -- | These TyCons should be allowed at the kind level, even without
 2413 -- -XDataKinds.
 2414 kindTyConKeys :: UniqSet Unique
 2415 kindTyConKeys = unionManyUniqSets
 2416   ( mkUniqSet [ liftedTypeKindTyConKey, liftedRepTyConKey, constraintKindTyConKey, tYPETyConKey ]
 2417   : map (mkUniqSet . tycon_with_datacons) [ runtimeRepTyCon, levityTyCon
 2418                                           , multiplicityTyCon
 2419                                           , vecCountTyCon, vecElemTyCon ] )
 2420   where
 2421     tycon_with_datacons tc = getUnique tc : map getUnique (tyConDataCons tc)
 2422 
 2423 isLiftedTypeKindTyConName :: Name -> Bool
 2424 isLiftedTypeKindTyConName = (`hasKey` liftedTypeKindTyConKey)
 2425 
 2426 -- | Identifies implicit tycons that, in particular, do not go into interface
 2427 -- files (because they are implicitly reconstructed when the interface is
 2428 -- read).
 2429 --
 2430 -- Note that:
 2431 --
 2432 -- * Associated families are implicit, as they are re-constructed from
 2433 --   the class declaration in which they reside, and
 2434 --
 2435 -- * Family instances are /not/ implicit as they represent the instance body
 2436 --   (similar to a @dfun@ does that for a class instance).
 2437 --
 2438 -- * Tuples are implicit iff they have a wired-in name
 2439 --   (namely: boxed and unboxed tuples are wired-in and implicit,
 2440 --            but constraint tuples are not)
 2441 isImplicitTyCon :: TyCon -> Bool
 2442 isImplicitTyCon (FunTyCon {})        = True
 2443 isImplicitTyCon (PrimTyCon {})       = True
 2444 isImplicitTyCon (PromotedDataCon {}) = True
 2445 isImplicitTyCon (AlgTyCon { algTcRhs = rhs, tyConName = name })
 2446   | TupleTyCon {} <- rhs             = isWiredInName name
 2447   | SumTyCon {} <- rhs               = True
 2448   | otherwise                        = False
 2449 isImplicitTyCon (FamilyTyCon { famTcParent = parent }) = isJust parent
 2450 isImplicitTyCon (SynonymTyCon {})    = False
 2451 isImplicitTyCon (TcTyCon {})         = False
 2452 
 2453 tyConCType_maybe :: TyCon -> Maybe CType
 2454 tyConCType_maybe tc@(AlgTyCon {}) = tyConCType tc
 2455 tyConCType_maybe _ = Nothing
 2456 
 2457 -- | Is this a TcTyCon? (That is, one only used during type-checking?)
 2458 isTcTyCon :: TyCon -> Bool
 2459 isTcTyCon (TcTyCon {}) = True
 2460 isTcTyCon _            = False
 2461 
 2462 setTcTyConKind :: TyCon -> Kind -> TyCon
 2463 -- Update the Kind of a TcTyCon
 2464 -- The new kind is always a zonked version of its previous
 2465 -- kind, so we don't need to update any other fields.
 2466 -- See Note [The Purely Kinded Invariant] in GHC.Tc.Gen.HsType
 2467 setTcTyConKind tc@(TcTyCon {}) kind = let tc' = tc { tyConKind = kind
 2468                                                    , tyConNullaryTy = mkTyConTy_ tc'
 2469                                                        -- see Note [Sharing nullary TyCons]
 2470                                                    }
 2471                                       in tc'
 2472 setTcTyConKind tc              _    = pprPanic "setTcTyConKind" (ppr tc)
 2473 
 2474 -- | Does this 'TyCon' have a fixed RuntimeRep when fully applied,
 2475 -- as per Note [Fixed RuntimeRep] in GHC.Tc.Utils.Concrete?
 2476 --
 2477 -- False is safe. True means we're sure.
 2478 -- Does only a quick check, based on the TyCon's category.
 2479 --
 2480 -- See Note [Representation-polymorphic TyCons]
 2481 tcHasFixedRuntimeRep :: TyCon -> Bool
 2482 tcHasFixedRuntimeRep FunTyCon{}           = True
 2483 tcHasFixedRuntimeRep (AlgTyCon { algTcParent = parent, algTcRhs = rhs })
 2484   | UnboxedAlgTyCon _ <- parent
 2485   = False
 2486   | NewTyCon { nt_fixed_rep = fixed_rep } <- rhs
 2487   = fixed_rep -- A newtype might not have a fixed runtime representation
 2488               -- with UnliftedNewtypes (#17360)
 2489   | DataTyCon { data_fixed_lev = fixed_lev } <- rhs
 2490   = fixed_lev -- A datatype might not have a fixed levity with UnliftedDatatypes (#20423).
 2491               -- NB: the current representation-polymorphism checks require that
 2492               -- the representation be fully-known, including levity variables.
 2493               -- This might be relaxed in the future (#15532).
 2494   | AbstractTyCon {} <- rhs
 2495   = False -- An abstract TyCon might not have a fixed runtime representation.
 2496           -- Note that this is an entirely different matter from the concreteness
 2497           -- of the 'TyCon', in the sense of 'isConcreteTyCon'.
 2498   | otherwise
 2499   = True
 2500 tcHasFixedRuntimeRep SynonymTyCon{}       = False
 2501 tcHasFixedRuntimeRep FamilyTyCon{}        = False
 2502 tcHasFixedRuntimeRep PrimTyCon{}          = True
 2503 tcHasFixedRuntimeRep TcTyCon{}            = False
 2504 tcHasFixedRuntimeRep tc@PromotedDataCon{} = pprPanic "tcHasFixedRuntimeRep datacon" (ppr tc)
 2505 
 2506 -- | Is this 'TyCon' concrete (i.e. not a synonym/type family)?
 2507 --
 2508 -- Used for representation polymorphism checks.
 2509 isConcreteTyCon :: TyCon -> Bool
 2510 isConcreteTyCon = isConcreteTyConFlavour . tyConFlavour
 2511 
 2512 -- | Is this 'TyConFlavour' concrete (i.e. not a synonym/type family)?
 2513 --
 2514 -- Used for representation polymorphism checks.
 2515 isConcreteTyConFlavour :: TyConFlavour -> Bool
 2516 isConcreteTyConFlavour = \case
 2517   ClassFlavour             -> True
 2518   TupleFlavour {}          -> True
 2519   SumFlavour               -> True
 2520   DataTypeFlavour          -> True
 2521   NewtypeFlavour           -> True
 2522   AbstractTypeFlavour      -> True  -- See (3) in Note [Solving Concrete# constraints] in GHC.Tc.Utils.Concrete
 2523   DataFamilyFlavour {}     -> False -- See
 2524   OpenTypeFamilyFlavour {} -> False
 2525   ClosedTypeFamilyFlavour  -> False
 2526   TypeSynonymFlavour       -> False
 2527   BuiltInTypeFlavour       -> True
 2528   PromotedDataConFlavour   -> True
 2529 
 2530 {-
 2531 -----------------------------------------------
 2532 --      Expand type-constructor applications
 2533 -----------------------------------------------
 2534 -}
 2535 
 2536 expandSynTyCon_maybe
 2537         :: TyCon
 2538         -> [tyco]                 -- ^ Arguments to 'TyCon'
 2539         -> Maybe ([(TyVar,tyco)],
 2540                   Type,
 2541                   [tyco])         -- ^ Returns a 'TyVar' substitution, the body
 2542                                   -- type of the synonym (not yet substituted)
 2543                                   -- and any arguments remaining from the
 2544                                   -- application
 2545 -- ^ Expand a type synonym application
 2546 -- Return Nothing if the TyCon is not a synonym,
 2547 -- or if not enough arguments are supplied
 2548 expandSynTyCon_maybe tc tys
 2549   | SynonymTyCon { tyConTyVars = tvs, synTcRhs = rhs, tyConArity = arity } <- tc
 2550   = if arity == 0
 2551     then Just ([], rhs, tys)  -- Avoid a bit of work in the case of nullary synonyms
 2552     else case tys `listLengthCmp` arity of
 2553               GT -> Just (tvs `zip` tys, rhs, drop arity tys)
 2554               EQ -> Just (tvs `zip` tys, rhs, [])
 2555               LT -> Nothing
 2556    | otherwise
 2557    = Nothing
 2558 
 2559 ----------------
 2560 
 2561 -- | Check if the tycon actually refers to a proper `data` or `newtype`
 2562 --  with user defined constructors rather than one from a class or other
 2563 --  construction.
 2564 
 2565 -- NB: This is only used in GHC.Tc.Gen.Export.checkPatSynParent to determine if an
 2566 -- exported tycon can have a pattern synonym bundled with it, e.g.,
 2567 -- module Foo (TyCon(.., PatSyn)) where
 2568 isTyConWithSrcDataCons :: TyCon -> Bool
 2569 isTyConWithSrcDataCons (AlgTyCon { algTcRhs = rhs, algTcParent = parent }) =
 2570   case rhs of
 2571     DataTyCon {}  -> isSrcParent
 2572     NewTyCon {}   -> isSrcParent
 2573     TupleTyCon {} -> isSrcParent
 2574     _ -> False
 2575   where
 2576     isSrcParent = isNoParent parent
 2577 isTyConWithSrcDataCons (FamilyTyCon { famTcFlav = DataFamilyTyCon {} })
 2578                          = True -- #14058
 2579 isTyConWithSrcDataCons _ = False
 2580 
 2581 
 2582 -- | As 'tyConDataCons_maybe', but returns the empty list of constructors if no
 2583 -- constructors could be found
 2584 tyConDataCons :: TyCon -> [DataCon]
 2585 -- It's convenient for tyConDataCons to return the
 2586 -- empty list for type synonyms etc
 2587 tyConDataCons tycon = tyConDataCons_maybe tycon `orElse` []
 2588 
 2589 -- | Determine the 'DataCon's originating from the given 'TyCon', if the 'TyCon'
 2590 -- is the sort that can have any constructors (note: this does not include
 2591 -- abstract algebraic types)
 2592 tyConDataCons_maybe :: TyCon -> Maybe [DataCon]
 2593 tyConDataCons_maybe (AlgTyCon {algTcRhs = rhs})
 2594   = case rhs of
 2595        DataTyCon { data_cons = cons } -> Just cons
 2596        NewTyCon { data_con = con }    -> Just [con]
 2597        TupleTyCon { data_con = con }  -> Just [con]
 2598        SumTyCon { data_cons = cons }  -> Just cons
 2599        _                              -> Nothing
 2600 tyConDataCons_maybe _ = Nothing
 2601 
 2602 -- | If the given 'TyCon' has a /single/ data constructor, i.e. it is a @data@
 2603 -- type with one alternative, a tuple type or a @newtype@ then that constructor
 2604 -- is returned. If the 'TyCon' has more than one constructor, or represents a
 2605 -- primitive or function type constructor then @Nothing@ is returned.
 2606 tyConSingleDataCon_maybe :: TyCon -> Maybe DataCon
 2607 tyConSingleDataCon_maybe (AlgTyCon { algTcRhs = rhs })
 2608   = case rhs of
 2609       DataTyCon { data_cons = [c] } -> Just c
 2610       TupleTyCon { data_con = c }   -> Just c
 2611       NewTyCon { data_con = c }     -> Just c
 2612       _                             -> Nothing
 2613 tyConSingleDataCon_maybe _           = Nothing
 2614 
 2615 -- | Like 'tyConSingleDataCon_maybe', but panics if 'Nothing'.
 2616 tyConSingleDataCon :: TyCon -> DataCon
 2617 tyConSingleDataCon tc
 2618   = case tyConSingleDataCon_maybe tc of
 2619       Just c  -> c
 2620       Nothing -> pprPanic "tyConDataCon" (ppr tc)
 2621 
 2622 -- | Like 'tyConSingleDataCon_maybe', but returns 'Nothing' for newtypes.
 2623 tyConSingleAlgDataCon_maybe :: TyCon -> Maybe DataCon
 2624 tyConSingleAlgDataCon_maybe tycon
 2625   | isNewTyCon tycon = Nothing
 2626   | otherwise        = tyConSingleDataCon_maybe tycon
 2627 
 2628 -- | Returns @Just dcs@ if the given 'TyCon' is a @data@ type, a tuple type
 2629 -- or a sum type with data constructors dcs. If the 'TyCon' has more than one
 2630 -- constructor, or represents a primitive or function type constructor then
 2631 -- @Nothing@ is returned.
 2632 --
 2633 -- Like 'tyConDataCons_maybe', but returns 'Nothing' for newtypes.
 2634 tyConAlgDataCons_maybe :: TyCon -> Maybe [DataCon]
 2635 tyConAlgDataCons_maybe tycon
 2636   | isNewTyCon tycon = Nothing
 2637   | otherwise        = tyConDataCons_maybe tycon
 2638 
 2639 -- | Determine the number of value constructors a 'TyCon' has. Panics if the
 2640 -- 'TyCon' is not algebraic or a tuple
 2641 tyConFamilySize  :: TyCon -> Int
 2642 tyConFamilySize tc@(AlgTyCon { algTcRhs = rhs })
 2643   = case rhs of
 2644       DataTyCon { data_cons_size = size } -> size
 2645       NewTyCon {}                    -> 1
 2646       TupleTyCon {}                  -> 1
 2647       SumTyCon { data_cons_size = size }  -> size
 2648       _                              -> pprPanic "tyConFamilySize 1" (ppr tc)
 2649 tyConFamilySize tc = pprPanic "tyConFamilySize 2" (ppr tc)
 2650 
 2651 -- | Extract an 'AlgTyConRhs' with information about data constructors from an
 2652 -- algebraic or tuple 'TyCon'. Panics for any other sort of 'TyCon'
 2653 algTyConRhs :: TyCon -> AlgTyConRhs
 2654 algTyConRhs (AlgTyCon {algTcRhs = rhs}) = rhs
 2655 algTyConRhs other = pprPanic "algTyConRhs" (ppr other)
 2656 
 2657 -- | Extract type variable naming the result of injective type family
 2658 tyConFamilyResVar_maybe :: TyCon -> Maybe Name
 2659 tyConFamilyResVar_maybe (FamilyTyCon {famTcResVar = res}) = res
 2660 tyConFamilyResVar_maybe _                                 = Nothing
 2661 
 2662 -- | Get the list of roles for the type parameters of a TyCon
 2663 tyConRoles :: TyCon -> [Role]
 2664 -- See also Note [TyCon Role signatures]
 2665 tyConRoles tc
 2666   = case tc of
 2667     { FunTyCon {}                         -> [Nominal, Nominal, Nominal, Representational, Representational]
 2668     ; AlgTyCon { tcRoles = roles }        -> roles
 2669     ; SynonymTyCon { tcRoles = roles }    -> roles
 2670     ; FamilyTyCon {}                      -> const_role Nominal
 2671     ; PrimTyCon { tcRoles = roles }       -> roles
 2672     ; PromotedDataCon { tcRoles = roles } -> roles
 2673     ; TcTyCon {}                          -> const_role Nominal
 2674     }
 2675   where
 2676     const_role r = replicate (tyConArity tc) r
 2677 
 2678 -- | Extract the bound type variables and type expansion of a type synonym
 2679 -- 'TyCon'. Panics if the 'TyCon' is not a synonym
 2680 newTyConRhs :: TyCon -> ([TyVar], Type)
 2681 newTyConRhs (AlgTyCon {tyConTyVars = tvs, algTcRhs = NewTyCon { nt_rhs = rhs }})
 2682     = (tvs, rhs)
 2683 newTyConRhs tycon = pprPanic "newTyConRhs" (ppr tycon)
 2684 
 2685 -- | The number of type parameters that need to be passed to a newtype to
 2686 -- resolve it. May be less than in the definition if it can be eta-contracted.
 2687 newTyConEtadArity :: TyCon -> Int
 2688 newTyConEtadArity (AlgTyCon {algTcRhs = NewTyCon { nt_etad_rhs = tvs_rhs }})
 2689         = length (fst tvs_rhs)
 2690 newTyConEtadArity tycon = pprPanic "newTyConEtadArity" (ppr tycon)
 2691 
 2692 -- | Extract the bound type variables and type expansion of an eta-contracted
 2693 -- type synonym 'TyCon'.  Panics if the 'TyCon' is not a synonym
 2694 newTyConEtadRhs :: TyCon -> ([TyVar], Type)
 2695 newTyConEtadRhs (AlgTyCon {algTcRhs = NewTyCon { nt_etad_rhs = tvs_rhs }}) = tvs_rhs
 2696 newTyConEtadRhs tycon = pprPanic "newTyConEtadRhs" (ppr tycon)
 2697 
 2698 -- | Extracts the @newtype@ coercion from such a 'TyCon', which can be used to
 2699 -- construct something with the @newtype@s type from its representation type
 2700 -- (right hand side). If the supplied 'TyCon' is not a @newtype@, returns
 2701 -- @Nothing@
 2702 newTyConCo_maybe :: TyCon -> Maybe (CoAxiom Unbranched)
 2703 newTyConCo_maybe (AlgTyCon {algTcRhs = NewTyCon { nt_co = co }}) = Just co
 2704 newTyConCo_maybe _                                               = Nothing
 2705 
 2706 newTyConCo :: TyCon -> CoAxiom Unbranched
 2707 newTyConCo tc = case newTyConCo_maybe tc of
 2708                  Just co -> co
 2709                  Nothing -> pprPanic "newTyConCo" (ppr tc)
 2710 
 2711 newTyConDataCon_maybe :: TyCon -> Maybe DataCon
 2712 newTyConDataCon_maybe (AlgTyCon {algTcRhs = NewTyCon { data_con = con }}) = Just con
 2713 newTyConDataCon_maybe _ = Nothing
 2714 
 2715 -- | Find the \"stupid theta\" of the 'TyCon'. A \"stupid theta\" is the context
 2716 -- to the left of an algebraic type declaration, e.g. @Eq a@ in the declaration
 2717 -- @data Eq a => T a ...@
 2718 tyConStupidTheta :: TyCon -> [PredType]
 2719 tyConStupidTheta (AlgTyCon {algTcStupidTheta = stupid}) = stupid
 2720 tyConStupidTheta (FunTyCon {}) = []
 2721 tyConStupidTheta tycon = pprPanic "tyConStupidTheta" (ppr tycon)
 2722 
 2723 -- | Extract the 'TyVar's bound by a vanilla type synonym
 2724 -- and the corresponding (unsubstituted) right hand side.
 2725 synTyConDefn_maybe :: TyCon -> Maybe ([TyVar], Type)
 2726 synTyConDefn_maybe (SynonymTyCon {tyConTyVars = tyvars, synTcRhs = ty})
 2727   = Just (tyvars, ty)
 2728 synTyConDefn_maybe _ = Nothing
 2729 
 2730 -- | Extract the information pertaining to the right hand side of a type synonym
 2731 -- (@type@) declaration.
 2732 synTyConRhs_maybe :: TyCon -> Maybe Type
 2733 synTyConRhs_maybe (SynonymTyCon {synTcRhs = rhs}) = Just rhs
 2734 synTyConRhs_maybe _                               = Nothing
 2735 
 2736 -- | Extract the flavour of a type family (with all the extra information that
 2737 -- it carries)
 2738 famTyConFlav_maybe :: TyCon -> Maybe FamTyConFlav
 2739 famTyConFlav_maybe (FamilyTyCon {famTcFlav = flav}) = Just flav
 2740 famTyConFlav_maybe _                                = Nothing
 2741 
 2742 -- | Is this 'TyCon' that for a class instance?
 2743 isClassTyCon :: TyCon -> Bool
 2744 isClassTyCon (AlgTyCon {algTcParent = ClassTyCon {}}) = True
 2745 isClassTyCon _                                        = False
 2746 
 2747 -- | If this 'TyCon' is that for a class instance, return the class it is for.
 2748 -- Otherwise returns @Nothing@
 2749 tyConClass_maybe :: TyCon -> Maybe Class
 2750 tyConClass_maybe (AlgTyCon {algTcParent = ClassTyCon clas _}) = Just clas
 2751 tyConClass_maybe _                                            = Nothing
 2752 
 2753 -- | Return the associated types of the 'TyCon', if any
 2754 tyConATs :: TyCon -> [TyCon]
 2755 tyConATs (AlgTyCon {algTcParent = ClassTyCon clas _}) = classATs clas
 2756 tyConATs _                                            = []
 2757 
 2758 ----------------------------------------------------------------------------
 2759 -- | Is this 'TyCon' that for a data family instance?
 2760 isFamInstTyCon :: TyCon -> Bool
 2761 isFamInstTyCon (AlgTyCon {algTcParent = DataFamInstTyCon {} })
 2762   = True
 2763 isFamInstTyCon _ = False
 2764 
 2765 tyConFamInstSig_maybe :: TyCon -> Maybe (TyCon, [Type], CoAxiom Unbranched)
 2766 tyConFamInstSig_maybe (AlgTyCon {algTcParent = DataFamInstTyCon ax f ts })
 2767   = Just (f, ts, ax)
 2768 tyConFamInstSig_maybe _ = Nothing
 2769 
 2770 -- | If this 'TyCon' is that of a data family instance, return the family in question
 2771 -- and the instance types. Otherwise, return @Nothing@
 2772 tyConFamInst_maybe :: TyCon -> Maybe (TyCon, [Type])
 2773 tyConFamInst_maybe (AlgTyCon {algTcParent = DataFamInstTyCon _ f ts })
 2774   = Just (f, ts)
 2775 tyConFamInst_maybe _ = Nothing
 2776 
 2777 -- | If this 'TyCon' is that of a data family instance, return a 'TyCon' which
 2778 -- represents a coercion identifying the representation type with the type
 2779 -- instance family.  Otherwise, return @Nothing@
 2780 tyConFamilyCoercion_maybe :: TyCon -> Maybe (CoAxiom Unbranched)
 2781 tyConFamilyCoercion_maybe (AlgTyCon {algTcParent = DataFamInstTyCon ax _ _ })
 2782   = Just ax
 2783 tyConFamilyCoercion_maybe _ = Nothing
 2784 
 2785 -- | Extract any 'RuntimeRepInfo' from this TyCon
 2786 tyConRuntimeRepInfo :: TyCon -> RuntimeRepInfo
 2787 tyConRuntimeRepInfo (PromotedDataCon { promDcRepInfo = rri }) = rri
 2788 tyConRuntimeRepInfo _                                         = NoRRI
 2789   -- could panic in that second case. But Douglas Adams told me not to.
 2790 
 2791 {-
 2792 Note [Constructor tag allocation]
 2793 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 2794 When typechecking we need to allocate constructor tags to constructors.
 2795 They are allocated based on the position in the data_cons field of TyCon,
 2796 with the first constructor getting fIRST_TAG.
 2797 
 2798 We used to pay linear cost per constructor, with each constructor looking up
 2799 its relative index in the constructor list. That was quadratic and prohibitive
 2800 for large data types with more than 10k constructors.
 2801 
 2802 The current strategy is to build a NameEnv with a mapping from constructor's
 2803 Name to ConTag and pass it down to buildDataCon for efficient lookup.
 2804 
 2805 Relevant ticket: #14657
 2806 -}
 2807 
 2808 mkTyConTagMap :: TyCon -> NameEnv ConTag
 2809 mkTyConTagMap tycon =
 2810   mkNameEnv $ map getName (tyConDataCons tycon) `zip` [fIRST_TAG..]
 2811   -- See Note [Constructor tag allocation]
 2812 
 2813 {-
 2814 ************************************************************************
 2815 *                                                                      *
 2816 \subsection[TyCon-instances]{Instance declarations for @TyCon@}
 2817 *                                                                      *
 2818 ************************************************************************
 2819 
 2820 @TyCon@s are compared by comparing their @Unique@s.
 2821 -}
 2822 
 2823 instance Eq TyCon where
 2824     a == b = getUnique a == getUnique b
 2825     a /= b = getUnique a /= getUnique b
 2826 
 2827 instance Uniquable TyCon where
 2828     getUnique tc = tyConUnique tc
 2829 
 2830 instance Outputable TyCon where
 2831   -- At the moment a promoted TyCon has the same Name as its
 2832   -- corresponding TyCon, so we add the quote to distinguish it here
 2833   ppr tc = pprPromotionQuote tc <> ppr (tyConName tc) <> pp_tc
 2834     where
 2835       pp_tc = getPprStyle $ \sty ->
 2836               getPprDebug $ \debug ->
 2837                if ((debug || dumpStyle sty) && isTcTyCon tc)
 2838                   then text "[tc]"
 2839                   else empty
 2840 
 2841 -- | Paints a picture of what a 'TyCon' represents, in broad strokes.
 2842 -- This is used towards more informative error messages.
 2843 data TyConFlavour
 2844   = ClassFlavour
 2845   | TupleFlavour Boxity
 2846   | SumFlavour
 2847   | DataTypeFlavour
 2848   | NewtypeFlavour
 2849   | AbstractTypeFlavour
 2850   | DataFamilyFlavour (Maybe TyCon)     -- Just tc <=> (tc == associated class)
 2851   | OpenTypeFamilyFlavour (Maybe TyCon) -- Just tc <=> (tc == associated class)
 2852   | ClosedTypeFamilyFlavour
 2853   | TypeSynonymFlavour
 2854   | BuiltInTypeFlavour -- ^ e.g., the @(->)@ 'TyCon'.
 2855   | PromotedDataConFlavour
 2856   deriving Eq
 2857 
 2858 instance Outputable TyConFlavour where
 2859   ppr = text . go
 2860     where
 2861       go ClassFlavour = "class"
 2862       go (TupleFlavour boxed) | isBoxed boxed = "tuple"
 2863                               | otherwise     = "unboxed tuple"
 2864       go SumFlavour              = "unboxed sum"
 2865       go DataTypeFlavour         = "data type"
 2866       go NewtypeFlavour          = "newtype"
 2867       go AbstractTypeFlavour     = "abstract type"
 2868       go (DataFamilyFlavour (Just _))  = "associated data family"
 2869       go (DataFamilyFlavour Nothing)   = "data family"
 2870       go (OpenTypeFamilyFlavour (Just _)) = "associated type family"
 2871       go (OpenTypeFamilyFlavour Nothing)  = "type family"
 2872       go ClosedTypeFamilyFlavour = "type family"
 2873       go TypeSynonymFlavour      = "type synonym"
 2874       go BuiltInTypeFlavour      = "built-in type"
 2875       go PromotedDataConFlavour  = "promoted data constructor"
 2876 
 2877 tyConFlavour :: TyCon -> TyConFlavour
 2878 tyConFlavour (AlgTyCon { algTcParent = parent, algTcRhs = rhs })
 2879   | ClassTyCon _ _ <- parent = ClassFlavour
 2880   | otherwise = case rhs of
 2881                   TupleTyCon { tup_sort = sort }
 2882                                      -> TupleFlavour (tupleSortBoxity sort)
 2883                   SumTyCon {}        -> SumFlavour
 2884                   DataTyCon {}       -> DataTypeFlavour
 2885                   NewTyCon {}        -> NewtypeFlavour
 2886                   AbstractTyCon {}   -> AbstractTypeFlavour
 2887 tyConFlavour (FamilyTyCon { famTcFlav = flav, famTcParent = parent })
 2888   = case flav of
 2889       DataFamilyTyCon{}            -> DataFamilyFlavour parent
 2890       OpenSynFamilyTyCon           -> OpenTypeFamilyFlavour parent
 2891       ClosedSynFamilyTyCon{}       -> ClosedTypeFamilyFlavour
 2892       AbstractClosedSynFamilyTyCon -> ClosedTypeFamilyFlavour
 2893       BuiltInSynFamTyCon{}         -> ClosedTypeFamilyFlavour
 2894 tyConFlavour (SynonymTyCon {})    = TypeSynonymFlavour
 2895 tyConFlavour (FunTyCon {})        = BuiltInTypeFlavour
 2896 tyConFlavour (PrimTyCon {})       = BuiltInTypeFlavour
 2897 tyConFlavour (PromotedDataCon {}) = PromotedDataConFlavour
 2898 tyConFlavour (TcTyCon { tcTyConFlavour = flav }) = flav
 2899 
 2900 -- | Can this flavour of 'TyCon' appear unsaturated?
 2901 tcFlavourMustBeSaturated :: TyConFlavour -> Bool
 2902 tcFlavourMustBeSaturated ClassFlavour            = False
 2903 tcFlavourMustBeSaturated DataTypeFlavour         = False
 2904 tcFlavourMustBeSaturated NewtypeFlavour          = False
 2905 tcFlavourMustBeSaturated DataFamilyFlavour{}     = False
 2906 tcFlavourMustBeSaturated TupleFlavour{}          = False
 2907 tcFlavourMustBeSaturated SumFlavour              = False
 2908 tcFlavourMustBeSaturated AbstractTypeFlavour {}  = False
 2909 tcFlavourMustBeSaturated BuiltInTypeFlavour      = False
 2910 tcFlavourMustBeSaturated PromotedDataConFlavour  = False
 2911 tcFlavourMustBeSaturated TypeSynonymFlavour      = True
 2912 tcFlavourMustBeSaturated OpenTypeFamilyFlavour{} = True
 2913 tcFlavourMustBeSaturated ClosedTypeFamilyFlavour = True
 2914 
 2915 -- | Is this flavour of 'TyCon' an open type family or a data family?
 2916 tcFlavourIsOpen :: TyConFlavour -> Bool
 2917 tcFlavourIsOpen DataFamilyFlavour{}     = True
 2918 tcFlavourIsOpen OpenTypeFamilyFlavour{} = True
 2919 tcFlavourIsOpen ClosedTypeFamilyFlavour = False
 2920 tcFlavourIsOpen ClassFlavour            = False
 2921 tcFlavourIsOpen DataTypeFlavour         = False
 2922 tcFlavourIsOpen NewtypeFlavour          = False
 2923 tcFlavourIsOpen TupleFlavour{}          = False
 2924 tcFlavourIsOpen SumFlavour              = False
 2925 tcFlavourIsOpen AbstractTypeFlavour {}  = False
 2926 tcFlavourIsOpen BuiltInTypeFlavour      = False
 2927 tcFlavourIsOpen PromotedDataConFlavour  = False
 2928 tcFlavourIsOpen TypeSynonymFlavour      = False
 2929 
 2930 pprPromotionQuote :: TyCon -> SDoc
 2931 -- Promoted data constructors already have a tick in their OccName
 2932 pprPromotionQuote tc
 2933   = case tc of
 2934       PromotedDataCon {} -> char '\'' -- Always quote promoted DataCons in types
 2935       _                  -> empty
 2936 
 2937 instance NamedThing TyCon where
 2938     getName = tyConName
 2939 
 2940 instance Data.Data TyCon where
 2941     -- don't traverse?
 2942     toConstr _   = abstractConstr "TyCon"
 2943     gunfold _ _  = error "gunfold"
 2944     dataTypeOf _ = mkNoRepType "TyCon"
 2945 
 2946 instance Binary Injectivity where
 2947     put_ bh NotInjective   = putByte bh 0
 2948     put_ bh (Injective xs) = putByte bh 1 >> put_ bh xs
 2949 
 2950     get bh = do { h <- getByte bh
 2951                 ; case h of
 2952                     0 -> return NotInjective
 2953                     _ -> do { xs <- get bh
 2954                             ; return (Injective xs) } }
 2955 
 2956 -- | Returns whether or not this 'TyCon' is definite, or a hole
 2957 -- that may be filled in at some later point.  See Note [Skolem abstract data]
 2958 tyConSkolem :: TyCon -> Bool
 2959 tyConSkolem = isHoleName . tyConName
 2960 
 2961 -- Note [Skolem abstract data]
 2962 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~
 2963 -- Skolem abstract data arises from data declarations in an hsig file.
 2964 --
 2965 -- The best analogy is to interpret the types declared in signature files as
 2966 -- elaborating to universally quantified type variables; e.g.,
 2967 --
 2968 --    unit p where
 2969 --        signature H where
 2970 --            data T
 2971 --            data S
 2972 --        module M where
 2973 --            import H
 2974 --            f :: (T ~ S) => a -> b
 2975 --            f x = x
 2976 --
 2977 -- elaborates as (with some fake structural types):
 2978 --
 2979 --    p :: forall t s. { f :: forall a b. t ~ s => a -> b }
 2980 --    p = { f = \x -> x } -- ill-typed
 2981 --
 2982 -- It is clear that inside p, t ~ s is not provable (and
 2983 -- if we tried to write a function to cast t to s, that
 2984 -- would not work), but if we call p @Int @Int, clearly Int ~ Int
 2985 -- is provable.  The skolem variables are all distinct from
 2986 -- one another, but we can't make assumptions like "f is
 2987 -- inaccessible", because the skolem variables will get
 2988 -- instantiated eventually!
 2989 --
 2990 -- Skolem abstractness can apply to "non-abstract" data as well):
 2991 --
 2992 --    unit p where
 2993 --        signature H1 where
 2994 --            data T = MkT
 2995 --        signature H2 where
 2996 --            data T = MkT
 2997 --        module M where
 2998 --            import qualified H1
 2999 --            import qualified H2
 3000 --            f :: (H1.T ~ H2.T) => a -> b
 3001 --            f x = x
 3002 --
 3003 -- This is why the test is on the original name of the TyCon,
 3004 -- not whether it is abstract or not.