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