TyCon.hs 105 KB
Newer Older
1 2 3 4
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998

5 6

The @TyCon@ datatype
7
-}
8

9
{-# LANGUAGE CPP, FlexibleInstances #-}
10

11
module TyCon(
batterseapower's avatar
batterseapower committed
12
        -- * Main TyCon data types
13 14
        TyCon,
        AlgTyConRhs(..), visibleDataCons,
15
        AlgTyConFlav(..), isNoParent,
16
        FamTyConFlav(..), Role(..), Injectivity(..),
17
        RuntimeRepInfo(..), TyConFlavour(..),
18

19
        -- * TyConBinder
Ningning Xie's avatar
Ningning Xie committed
20
        TyConBinder, TyConBndrVis(..), TyConTyCoBinder,
21
        mkNamedTyConBinder, mkNamedTyConBinders,
Tobias Dammers's avatar
Tobias Dammers committed
22
        mkRequiredTyConBinder,
23
        mkAnonTyConBinder, mkAnonTyConBinders,
24
        tyConBinderArgFlag, tyConBndrVisArgFlag, isNamedTyConBinder,
25 26
        isVisibleTyConBinder, isInvisibleTyConBinder,

27
        -- ** Field labels
28
        tyConFieldLabels, lookupTyConFieldLabel,
29

batterseapower's avatar
batterseapower committed
30
        -- ** Constructing TyCons
31 32 33 34 35 36 37
        mkAlgTyCon,
        mkClassTyCon,
        mkFunTyCon,
        mkPrimTyCon,
        mkKindTyCon,
        mkLiftedPrimTyCon,
        mkTupleTyCon,
38
        mkSumTyCon,
39
        mkDataTyConRhs,
40 41
        mkSynonymTyCon,
        mkFamilyTyCon,
42
        mkPromotedDataCon,
43
        mkTcTyCon,
batterseapower's avatar
batterseapower committed
44 45

        -- ** Predicates on TyCons
46
        isAlgTyCon, isVanillaAlgTyCon,
47 48
        isClassTyCon, isFamInstTyCon,
        isFunTyCon,
batterseapower's avatar
batterseapower committed
49
        isPrimTyCon,
50
        isTupleTyCon, isUnboxedTupleTyCon, isBoxedTupleTyCon,
51
        isUnboxedSumTyCon, isPromotedTupleTyCon,
52
        isTypeSynonymTyCon,
Simon Peyton Jones's avatar
Simon Peyton Jones committed
53
        mustBeSaturated,
54 55
        isPromotedDataCon, isPromotedDataCon_maybe,
        isKindTyCon, isLiftedTypeKindTyConName,
56
        isTauTyCon, isFamFreeTyCon,
batterseapower's avatar
batterseapower committed
57

58
        isDataTyCon, isProductTyCon, isDataProductTyCon_maybe,
59
        isDataSumTyCon_maybe,
60
        isEnumerationTyCon,
61
        isNewTyCon, isAbstractTyCon,
62
        isFamilyTyCon, isOpenFamilyTyCon,
63
        isTypeFamilyTyCon, isDataFamilyTyCon,
64
        isOpenTypeFamilyTyCon, isClosedSynFamilyTyConWithAxiom_maybe,
65
        tyConInjectivityInfo,
66
        isBuiltInSynFamTyCon_maybe,
67
        isUnliftedTyCon,
68
        isGadtSyntaxTyCon, isInjectiveTyCon, isGenerativeTyCon, isGenInjAlgRhs,
Tobias Dammers's avatar
Tobias Dammers committed
69
        isTyConAssoc, tyConAssoc_maybe, tyConFlavourAssoc_maybe,
70
        isImplicitTyCon,
71
        isTyConWithSrcDataCons,
Simon Peyton Jones's avatar
Simon Peyton Jones committed
72 73
        isTcTyCon, setTcTyConKind,
        isTcLevPoly,
batterseapower's avatar
batterseapower committed
74 75

        -- ** Extracting information out of TyCons
76
        tyConName,
77
        tyConSkolem,
78 79
        tyConKind,
        tyConUnique,
80
        tyConTyVars, tyConVisibleTyVars,
81
        tyConCType, tyConCType_maybe,
Jan Stolarek's avatar
Jan Stolarek committed
82
        tyConDataCons, tyConDataCons_maybe,
83 84
        tyConSingleDataCon_maybe, tyConSingleDataCon,
        tyConSingleAlgDataCon_maybe,
85
        tyConFamilySize,
86 87
        tyConStupidTheta,
        tyConArity,
88
        tyConRoles,
89
        tyConFlavour,
90
        tyConTuple_maybe, tyConClass_maybe, tyConATs,
91
        tyConFamInst_maybe, tyConFamInstSig_maybe, tyConFamilyCoercion_maybe,
Jan Stolarek's avatar
Jan Stolarek committed
92 93 94
        tyConFamilyResVar_maybe,
        synTyConDefn_maybe, synTyConRhs_maybe,
        famTyConFlav_maybe, famTcResVar,
95
        algTyConRhs,
Jan Stolarek's avatar
Jan Stolarek committed
96
        newTyConRhs, newTyConEtadArity, newTyConEtadRhs,
97
        unwrapNewTyCon_maybe, unwrapNewTyConEtad_maybe,
98
        newTyConDataCon_maybe,
99
        algTcFields,
100
        tyConRuntimeRepInfo,
101
        tyConBinders, tyConResKind, tyConTyVarBinders,
Tobias Dammers's avatar
Tobias Dammers committed
102
        tcTyConScopedTyVars, tcTyConUserTyVars, tcTyConIsPoly,
103
        mkTyConTagMap,
104

batterseapower's avatar
batterseapower committed
105
        -- ** Manipulating TyCons
106
        expandSynTyCon_maybe,
107
        makeRecoveryTyCon,
108
        newTyConCo, newTyConCo_maybe,
109
        pprPromotionQuote, mkTyConKind,
110

111
        -- ** Predicated on TyConFlavours
Simon Peyton Jones's avatar
Simon Peyton Jones committed
112
        tcFlavourIsOpen,
113

114 115
        -- * Runtime type representation
        TyConRepName, tyConRepName_maybe,
116 117
        mkPrelTyConRepName,
        tyConRepModOcc,
118

batterseapower's avatar
batterseapower committed
119
        -- * Primitive representations of Types
120
        PrimRep(..), PrimElemRep(..),
121
        isVoidRep, isGcPtrRep,
122 123
        primRepSizeB,
        primElemRepSizeB,
124
        primRepIsFloat,
125 126

        -- * Recursion breaking
127 128
        RecTcChecker, initRecTc, defaultRecTcMaxBound,
        setRecTcMaxBound, checkRecTc
129

130 131
) where

132
#include "HsVersions.h"
133

134 135
import GhcPrelude

136 137 138 139
import {-# SOURCE #-} TyCoRep    ( Kind, Type, PredType, pprType )
import {-# SOURCE #-} TysWiredIn ( runtimeRepTyCon, constraintKind
                                 , vecCountTyCon, vecElemTyCon, liftedTypeKind
                                 , mkFunKind, mkForAllKind )
Ningning Xie's avatar
Ningning Xie committed
140
import {-# SOURCE #-} DataCon    ( DataCon, dataConExTyCoVars, dataConFieldLabels
David Eichmann's avatar
David Eichmann committed
141 142
                                 , dataConTyCon, dataConFullSig
                                 , isUnboxedSumCon )
143

Jan Stolarek's avatar
Jan Stolarek committed
144
import Binary
145
import Var
Tobias Dammers's avatar
Tobias Dammers committed
146
import VarSet
147 148
import Class
import BasicTypes
149
import DynFlags
150
import ForeignCall
151
import Name
152
import NameEnv
153
import CoAxiom
154 155
import PrelNames
import Maybes
156
import Outputable
157 158
import FastStringEnv
import FieldLabel
159
import Constants
160
import Util
161
import Unique( tyConRepNameUnique, dataConTyRepNameUnique )
162
import UniqSet
163
import Module
164

165
import qualified Data.Data as Data
166

167
{-
168
-----------------------------------------------
169
        Notes about type families
170 171
-----------------------------------------------

simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
172 173
Note [Type synonym families]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
174 175 176
* Type synonym families, also known as "type functions", map directly
  onto the type functions in FC:

177 178 179
        type family F a :: *
        type instance F Int = Bool
        ..etc...
180

181
* Reply "yes" to isTypeFamilyTyCon, and isFamilyTyCon
182

183
* From the user's point of view (F Int) and Bool are simply
184
  equivalent types.
185 186 187 188 189

* A Haskell 98 type synonym is a degenerate form of a type synonym
  family.

* Type functions can't appear in the LHS of a type function:
190
        type instance F (F Int) = ...   -- BAD!
191

192
* Translation of type family decl:
193
        type family F a :: *
194
  translates to
195
    a FamilyTyCon 'F', whose FamTyConFlav is OpenSynFamilyTyCon
196

197 198 199 200
        type family G a :: * where
          G Int = Bool
          G Bool = Char
          G a = ()
201
  translates to
202
    a FamilyTyCon 'G', whose FamTyConFlav is ClosedSynFamilyTyCon, with the
203
    appropriate CoAxiom representing the equations
204

Jan Stolarek's avatar
Jan Stolarek committed
205
We also support injective type families -- see Note [Injective type families]
206

207 208
Note [Data type families]
~~~~~~~~~~~~~~~~~~~~~~~~~
209
See also Note [Wrappers for data instance tycons] in MkId.hs
210

211
* Data type families are declared thus
212 213
        data family T a :: *
        data instance T Int = T1 | T2 Bool
214 215

  Here T is the "family TyCon".
216

217 218
* Reply "yes" to isDataFamilyTyCon, and isFamilyTyCon

219 220
* The user does not see any "equivalent types" as he did with type
  synonym families.  He just sees constructors with types
221 222
        T1 :: T Int
        T2 :: Bool -> T Int
223

224
* Here's the FC version of the above declarations:
225

226 227
        data T a
        data R:TInt = T1 | T2 Bool
228
        axiom ax_ti : T Int ~R R:TInt
229

230
  Note that this is a *representational* coercion
231
  The R:TInt is the "representation TyCons".
232 233
  It has an AlgTyConFlav of
        DataFamInstTyCon T [Int] ax_ti
234

235
* The axiom ax_ti may be eta-reduced; see
236
  Note [Eta reduction for data families] in FamInstEnv
237 238 239

* Data family instances may have a different arity than the data family.
  See Note [Arity of data families] in FamInstEnv
240

241
* The data constructor T2 has a wrapper (which is what the
242 243
  source-level "T2" invokes):

244 245
        $WT2 :: Bool -> T Int
        $WT2 b = T2 b `cast` sym ax_ti
246 247 248

* A data instance can declare a fully-fledged GADT:

249
        data instance T (a,b) where
250
          X1 :: T (Int,Bool)
251
          X2 :: a -> b -> T (a,b)
252

253 254
  Here's the FC version of the above declaration:

Ningning Xie's avatar
Ningning Xie committed
255
        data R:TPair a b where
256 257
          X1 :: R:TPair Int Bool
          X2 :: a -> b -> R:TPair a b
258
        axiom ax_pr :: T (a,b)  ~R  R:TPair a b
259

260 261
        $WX1 :: forall a b. a -> b -> T (a,b)
        $WX1 a b (x::a) (y::b) = X2 a b x y `cast` sym (ax_pr a b)
262 263 264 265 266 267

  The R:TPair are the "representation TyCons".
  We have a bit of work to do, to unpick the result types of the
  data instance declaration for T (a,b), to get the result type in the
  representation; e.g.  T (a,b) --> R:TPair a b

268
  The representation TyCon R:TList, has an AlgTyConFlav of
269

270
        DataFamInstTyCon T [(a,b)] ax_pr
271 272

* Notice that T is NOT translated to a FC type function; it just
Ningning Xie's avatar
Ningning Xie committed
273
  becomes a "data type" with no constructors, which can be coerced
274 275
  into R:TInt, R:TPair by the axioms.  These axioms
  axioms come into play when (and *only* when) you
276 277
        - use a data constructor
        - do pattern matching
278 279 280
  Rather like newtype, in fact

  As a result
281 282

  - T behaves just like a data type so far as decomposition is concerned
283

284
  - (T Int) is not implicitly converted to R:TInt during type inference.
285 286
    Indeed the latter type is unknown to the programmer.

287
  - There *is* an instance for (T Int) in the type-family instance
288 289
    environment, but it is only used for overlap checking

290
  - It's fine to have T in the LHS of a type function:
291 292 293 294 295 296
    type instance F (T a) = [a]

  It was this last point that confused me!  The big thing is that you
  should not think of a data family T as a *type function* at all, not
  even an injective one!  We can't allow even injective type functions
  on the LHS of a type function:
297 298
        type family injective G a :: *
        type instance F (G Int) = Bool
299
  is no good, even if G is injective, because consider
300 301
        type instance G Int = Bool
        type instance F Bool = Char
302 303

  So a data type family is not an injective type function. It's just a
304
  data type with some axioms that connect it to other data types.
305

306 307 308 309 310
* The tyConTyVars of the representation tycon are the tyvars that the
  user wrote in the patterns. This is important in TcDeriv, where we
  bring these tyvars into scope before type-checking the deriving
  clause. This fact is arranged for in TcInstDecls.tcDataFamInstDecl.

311 312 313
Note [Associated families and their parent class]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*Associated* families are just like *non-associated* families, except
Tobias Dammers's avatar
Tobias Dammers committed
314
that they have a famTcParent field of (Just cls_tc), which identifies the
315 316
parent class.

317
However there is an important sharing relationship between
318
  * the tyConTyVars of the parent Class
Ningning Xie's avatar
Ningning Xie committed
319
  * the tyConTyVars of the associated TyCon
320 321 322

   class C a b where
     data T p a
323
     type F a q b
324 325 326

Here the 'a' and 'b' are shared with the 'Class'; that is, they have
the same Unique.
327 328

This is important. In an instance declaration we expect
329 330 331 332 333 334 335 336
  * all the shared variables to be instantiated the same way
  * the non-shared variables of the associated type should not
    be instantiated at all

  instance C [x] (Tree y) where
     data T p [x] = T1 x | T2 p
     type F [x] q (Tree y) = (x,y,q)

337 338 339 340
Note [TyCon Role signatures]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Every tycon has a role signature, assigning a role to each of the tyConTyVars
(or of equal length to the tyConArity, if there are no tyConTyVars). An
341 342 343 344 345 346
example demonstrates these best: say we have a tycon T, with parameters a at
nominal, b at representational, and c at phantom. Then, to prove
representational equality between T a1 b1 c1 and T a2 b2 c2, we need to have
nominal equality between a1 and a2, representational equality between b1 and
b2, and nothing in particular (i.e., phantom equality) between c1 and c2. This
might happen, say, with the following declaration:
347 348 349 350 351 352 353 354 355 356 357 358

  data T a b c where
    MkT :: b -> T Int b c

Data and class tycons have their roles inferred (see inferRoles in TcTyDecls),
as do vanilla synonym tycons. Family tycons have all parameters at role N,
though it is conceivable that we could relax this restriction. (->)'s and
tuples' parameters are at role R. Each primitive tycon declares its roles;
it's worth noting that (~#)'s parameters are at role N. Promoted data
constructors' type arguments are at role R. All kind arguments are at role
N.

359 360 361 362 363
Note [Unboxed tuple RuntimeRep vars]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The contents of an unboxed tuple may have any representation. Accordingly,
the kind of the unboxed tuple constructor is runtime-representation
polymorphic. For example,
364

365
   (#,#) :: forall (q :: RuntimeRep) (r :: RuntimeRep). TYPE q -> TYPE r -> #
366 367 368 369 370

These extra tyvars (v and w) cause some delicate processing around tuples,
where we used to be able to assume that the tycon arity and the
datacon arity were the same.

Jan Stolarek's avatar
Jan Stolarek committed
371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
Note [Injective type families]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We allow injectivity annotations for type families (both open and closed):

  type family F (a :: k) (b :: k) = r | r -> a
  type family G a b = res | res -> a b where ...

Injectivity information is stored in the `famTcInj` field of `FamilyTyCon`.
`famTcInj` maybe stores a list of Bools, where each entry corresponds to a
single element of `tyConTyVars` (both lists should have identical length). If no
injectivity annotation was provided `famTcInj` is Nothing. From this follows an
invariant that if `famTcInj` is a Just then at least one element in the list
must be True.

See also:
 * [Injectivity annotation] in HsDecls
 * [Renaming injectivity annotation] in RnSource
 * [Verifying injectivity annotation] in FamInstEnv
 * [Type inference for type families with injectivity] in TcInteract

391 392
************************************************************************
*                                                                      *
Ningning Xie's avatar
Ningning Xie committed
393
                    TyConBinder, TyConTyCoBinder
394 395 396
*                                                                      *
************************************************************************
-}
397

Ningning Xie's avatar
Ningning Xie committed
398 399 400 401 402
type TyConBinder = VarBndr TyVar TyConBndrVis

-- In the whole definition of @data TyCon@, only @PromotedDataCon@ will really
-- contain CoVar.
type TyConTyCoBinder = VarBndr TyCoVar TyConBndrVis
403 404

data TyConBndrVis
405
  = NamedTCB ArgFlag
406 407
  | AnonTCB

408 409 410 411
instance Outputable TyConBndrVis where
  ppr (NamedTCB flag) = text "NamedTCB" <+> ppr flag
  ppr AnonTCB         = text "AnonTCB"

412
mkAnonTyConBinder :: TyVar -> TyConBinder
Ningning Xie's avatar
Ningning Xie committed
413 414
mkAnonTyConBinder tv = ASSERT( isTyVar tv)
                       Bndr tv AnonTCB
415 416 417 418

mkAnonTyConBinders :: [TyVar] -> [TyConBinder]
mkAnonTyConBinders tvs = map mkAnonTyConBinder tvs

419
mkNamedTyConBinder :: ArgFlag -> TyVar -> TyConBinder
420
-- The odd argument order supports currying
Ningning Xie's avatar
Ningning Xie committed
421 422
mkNamedTyConBinder vis tv = ASSERT( isTyVar tv )
                            Bndr tv (NamedTCB vis)
423

424
mkNamedTyConBinders :: ArgFlag -> [TyVar] -> [TyConBinder]
425 426 427
-- The odd argument order supports currying
mkNamedTyConBinders vis tvs = map (mkNamedTyConBinder vis) tvs

Tobias Dammers's avatar
Tobias Dammers committed
428 429 430 431 432 433 434 435 436
-- | Make a Required TyConBinder. It chooses between NamedTCB and
-- AnonTCB based on whether the tv is mentioned in the dependent set
mkRequiredTyConBinder :: TyCoVarSet  -- these are used dependently
                      -> TyVar
                      -> TyConBinder
mkRequiredTyConBinder dep_set tv
  | tv `elemVarSet` dep_set = mkNamedTyConBinder Required tv
  | otherwise               = mkAnonTyConBinder tv

437
tyConBinderArgFlag :: TyConBinder -> ArgFlag
Ningning Xie's avatar
Ningning Xie committed
438
tyConBinderArgFlag (Bndr _ vis) = tyConBndrVisArgFlag vis
439 440 441 442

tyConBndrVisArgFlag :: TyConBndrVis -> ArgFlag
tyConBndrVisArgFlag (NamedTCB vis) = vis
tyConBndrVisArgFlag AnonTCB        = Required
443 444

isNamedTyConBinder :: TyConBinder -> Bool
445 446 447
-- Identifies kind variables
-- E.g. data T k (a:k) = blah
-- Here 'k' is a NamedTCB, a variable used in the kind of other binders
Ningning Xie's avatar
Ningning Xie committed
448 449
isNamedTyConBinder (Bndr _ (NamedTCB {})) = True
isNamedTyConBinder _                      = False
450

Ningning Xie's avatar
Ningning Xie committed
451
isVisibleTyConBinder :: VarBndr tv TyConBndrVis -> Bool
452
-- Works for IfaceTyConBinder too
Ningning Xie's avatar
Ningning Xie committed
453
isVisibleTyConBinder (Bndr _ tcb_vis) = isVisibleTcbVis tcb_vis
454 455 456 457

isVisibleTcbVis :: TyConBndrVis -> Bool
isVisibleTcbVis (NamedTCB vis) = isVisibleArgFlag vis
isVisibleTcbVis AnonTCB        = True
458

Ningning Xie's avatar
Ningning Xie committed
459
isInvisibleTyConBinder :: VarBndr tv TyConBndrVis -> Bool
460 461 462 463 464 465 466
-- Works for IfaceTyConBinder too
isInvisibleTyConBinder tcb = not (isVisibleTyConBinder tcb)

mkTyConKind :: [TyConBinder] -> Kind -> Kind
mkTyConKind bndrs res_kind = foldr mk res_kind bndrs
  where
    mk :: TyConBinder -> Kind -> Kind
Ningning Xie's avatar
Ningning Xie committed
467 468
    mk (Bndr tv AnonTCB)        k = mkFunKind (varType tv) k
    mk (Bndr tv (NamedTCB vis)) k = mkForAllKind tv vis k
469

470 471 472 473 474 475
tyConTyVarBinders :: [TyConBinder]   -- From the TyCon
                  -> [TyVarBinder]   -- Suitable for the foralls of a term function
-- See Note [Building TyVarBinders from TyConBinders]
tyConTyVarBinders tc_bndrs
 = map mk_binder tc_bndrs
 where
Ningning Xie's avatar
Ningning Xie committed
476
   mk_binder (Bndr tv tc_vis) = mkTyVarBinder vis tv
477 478 479 480 481 482
      where
        vis = case tc_vis of
                AnonTCB           -> Specified
                NamedTCB Required -> Specified
                NamedTCB vis      -> vis

Ningning Xie's avatar
Ningning Xie committed
483
-- Returns only tyvars, as covars are always inferred
484 485
tyConVisibleTyVars :: TyCon -> [TyVar]
tyConVisibleTyVars tc
Ningning Xie's avatar
Ningning Xie committed
486
  = [ tv | Bndr tv vis <- tyConBinders tc
487 488
         , isVisibleTcbVis vis ]

489 490 491 492 493 494 495 496 497
{- Note [Building TyVarBinders from TyConBinders]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We sometimes need to build the quantified type of a value from
the TyConBinders of a type or class.  For that we need not
TyConBinders but TyVarBinders (used in forall-type)  E.g:

 *  From   data T a = MkT (Maybe a)
    we are going to make a data constructor with type
           MkT :: forall a. Maybe a -> T a
Ningning Xie's avatar
Ningning Xie committed
498
    See the TyCoVarBinders passed to buildDataCon
499 500 501 502

 * From    class C a where { op :: a -> Maybe a }
   we are going to make a default method
           $dmop :: forall a. C a => a -> Maybe a
Ningning Xie's avatar
Ningning Xie committed
503
   See the TyCoVarBinders passed to mkSigmaTy in mkDefaultMethodType
504 505 506 507 508 509 510 511 512 513 514 515 516

Both of these are user-callable.  (NB: default methods are not callable
directly by the user but rather via the code generated by 'deriving',
which uses visible type application; see mkDefMethBind.)

Since they are user-callable we must get their type-argument visibility
information right; and that info is in the TyConBinders.
Here is an example:

  data App a b = MkApp (a b) -- App :: forall {k}. (k->*) -> k -> *

The TyCon has

Ningning Xie's avatar
Ningning Xie committed
517
  tyConTyBinders = [ Named (Bndr (k :: *) Inferred), Anon (k->*), Anon k ]
518 519 520 521 522 523

The TyConBinders for App line up with App's kind, given above.

But the DataCon MkApp has the type
  MkApp :: forall {k} (a:k->*) (b:k). a b -> App k a b

Ningning Xie's avatar
Ningning Xie committed
524
That is, its TyCoVarBinders should be
525

Ningning Xie's avatar
Ningning Xie committed
526 527 528
  dataConUnivTyVarBinders = [ Bndr (k:*)    Inferred
                            , Bndr (a:k->*) Specified
                            , Bndr (b:k)    Specified ]
529

Gabor Greif's avatar
Gabor Greif committed
530
So tyConTyVarBinders converts TyCon's TyConBinders into TyVarBinders:
531 532 533 534 535 536
  - variable names from the TyConBinders
  - but changing Anon/Required to Specified

The last part about Required->Specified comes from this:
  data T k (a:k) b = MkT (a b)
Here k is Required in T's kind, but we don't have Required binders in
Ningning Xie's avatar
Ningning Xie committed
537 538
the TyCoBinders for a term (see Note [No Required TyCoBinder in terms]
in TyCoRep), so we change it to Specified when making MkT's TyCoBinders
539 540 541
-}


542 543 544
{- Note [The binders/kind/arity fields of a TyCon]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
All TyCons have this group of fields
Ningning Xie's avatar
Ningning Xie committed
545 546 547 548 549 550 551 552
  tyConBinders   :: [TyConBinder/TyConTyCoBinder]
  tyConResKind   :: Kind
  tyConTyVars    :: [TyVar]   -- Cached = binderVars tyConBinders
                              --   NB: Currently (Aug 2018), TyCons that own this
                              --   field really only contain TyVars. So it is
                              --   [TyVar] instead of [TyCoVar].
  tyConKind      :: Kind      -- Cached = mkTyConKind tyConBinders tyConResKind
  tyConArity     :: Arity     -- Cached = length tyConBinders
553 554 555

They fit together like so:

Ningning Xie's avatar
Ningning Xie committed
556
* tyConBinders gives the telescope of type/coercion variables on the LHS of the
557 558 559 560
  type declaration.  For example:

    type App a (b :: k) = a b

Ningning Xie's avatar
Ningning Xie committed
561 562 563
  tyConBinders = [ Bndr (k::*)   (NamedTCB Inferred)
                 , Bndr (a:k->*) AnonTCB
                 , Bndr (b:k)    AnonTCB ]
564 565 566

  Note that that are three binders here, including the
  kind variable k.
567

568
* See Note [VarBndrs, TyCoVarBinders, TyConBinders, and visibility] in TyCoRep
569
  for what the visibility flag means.
570

Ningning Xie's avatar
Ningning Xie committed
571 572 573
* Each TyConBinder tyConBinders has a TyVar (sometimes it is TyCoVar), and
  that TyVar may scope over some other part of the TyCon's definition. Eg
      type T a = a -> a
574
  we have
Ningning Xie's avatar
Ningning Xie committed
575 576
      tyConBinders = [ Bndr (a:*) AnonTCB ]
      synTcRhs     = a -> a
577 578 579 580 581 582 583 584 585 586 587
  So the 'a' scopes over the synTcRhs

* From the tyConBinders and tyConResKind we can get the tyConKind
  E.g for our App example:
      App :: forall k. (k->*) -> k -> *

  We get a 'forall' in the kind for each NamedTCB, and an arrow
  for each AnonTCB

  tyConKind is the full kind of the TyCon, not just the result kind

588 589 590 591 592 593 594 595 596
* For type families, tyConArity is the arguments this TyCon must be
  applied to, to be considered saturated.  Here we mean "applied to in
  the actual Type", not surface syntax; i.e. including implicit kind
  variables.  So it's just (length tyConBinders)

* For an algebraic data type, or data instance, the tyConResKind is
  always (TYPE r); that is, the tyConBinders are enough to saturate
  the type constructor.  I'm not quite sure why we have this invariant,
  but it's enforced by etaExpandAlgTyCon
597 598
-}

Ningning Xie's avatar
Ningning Xie committed
599 600 601 602 603
instance Outputable tv => Outputable (VarBndr tv TyConBndrVis) where
  ppr (Bndr v AnonTCB)              = text "anon" <+> parens (ppr v)
  ppr (Bndr v (NamedTCB Required))  = text "req"  <+> parens (ppr v)
  ppr (Bndr v (NamedTCB Specified)) = text "spec" <+> parens (ppr v)
  ppr (Bndr v (NamedTCB Inferred))  = text "inf"  <+> parens (ppr v)
604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622

instance Binary TyConBndrVis where
  put_ bh AnonTCB        = putByte bh 0
  put_ bh (NamedTCB vis) = do { putByte bh 1; put_ bh vis }

  get bh = do { h <- getByte bh
              ; case h of
                  0 -> return AnonTCB
                  _ -> do { vis <- get bh; return (NamedTCB vis) } }


{- *********************************************************************
*                                                                      *
               The TyCon type
*                                                                      *
************************************************************************
-}


623 624
-- | TyCons represent type constructors. Type constructors are introduced by
-- things such as:
batterseapower's avatar
batterseapower committed
625
--
626 627
-- 1) Data declarations: @data Foo = ...@ creates the @Foo@ type constructor of
--    kind @*@
batterseapower's avatar
batterseapower committed
628 629 630
--
-- 2) Type synonyms: @type Foo = ...@ creates the @Foo@ type constructor
--
631 632
-- 3) Newtypes: @newtype Foo a = MkFoo ...@ creates the @Foo@ type constructor
--    of kind @* -> *@
batterseapower's avatar
batterseapower committed
633
--
634 635
-- 4) Class declarations: @class Foo where@ creates the @Foo@ type constructor
--    of kind @*@
batterseapower's avatar
batterseapower committed
636
--
637 638
-- This data type also encodes a number of primitive, built in type constructors
-- such as those for function and tuple types.
639 640

-- If you edit this type, you may need to update the GHC formalism
641
-- See Note [GHC Formalism] in coreSyn/CoreLint.hs
642
data TyCon
batterseapower's avatar
batterseapower committed
643 644
  = -- | The function type constructor, @(->)@
    FunTyCon {
645 646 647 648 649 650
        tyConUnique :: Unique,   -- ^ A Unique of this TyCon. Invariant:
                                 -- identical to Unique of Name stored in
                                 -- tyConName field.

        tyConName   :: Name,     -- ^ Name of the constructor

651
        -- See Note [The binders/kind/arity fields of a TyCon]
652 653 654 655
        tyConBinders :: [TyConBinder], -- ^ Full binders
        tyConResKind :: Kind,             -- ^ Result kind
        tyConKind    :: Kind,             -- ^ Kind of this TyCon
        tyConArity   :: Arity,            -- ^ Arity
656 657

        tcRepName :: TyConRepName
658 659
    }

660
  -- | Algebraic data types, from
661
  --     - @data@ declarations
662 663 664 665 666 667 668 669 670 671 672
  --     - @newtype@ declarations
  --     - data instance declarations
  --     - type instance declarations
  --     - the TyCon generated by a class declaration
  --     - boxed tuples
  --     - unboxed tuples
  --     - constraint tuples
  -- All these constructors are lifted and boxed except unboxed tuples
  -- which should have an 'UnboxedAlgTyCon' parent.
  -- Data/newtype/type /families/ are handled by 'FamilyTyCon'.
  -- See 'AlgTyConRhs' for more information.
673
  | AlgTyCon {
674 675 676 677 678 679
        tyConUnique  :: Unique,  -- ^ A Unique of this TyCon. Invariant:
                                 -- identical to Unique of Name stored in
                                 -- tyConName field.

        tyConName    :: Name,    -- ^ Name of the constructor

680
        -- See Note [The binders/kind/arity fields of a TyCon]
681 682 683 684 685 686 687 688 689 690 691 692 693 694
        tyConBinders :: [TyConBinder], -- ^ Full binders
        tyConTyVars  :: [TyVar],          -- ^ TyVar binders
        tyConResKind :: Kind,             -- ^ Result kind
        tyConKind    :: Kind,             -- ^ Kind of this TyCon
        tyConArity   :: Arity,            -- ^ Arity

              -- The tyConTyVars scope over:
              --
              -- 1. The 'algTcStupidTheta'
              -- 2. The cached types in algTyConRhs.NewTyCon
              -- 3. The family instance types if present
              --
              -- Note that it does /not/ scope over the data
              -- constructors.
695 696

        tcRoles      :: [Role],  -- ^ The role for each type variable
697
                                 -- This list has length = tyConArity
698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719
                                 -- See also Note [TyCon Role signatures]

        tyConCType   :: Maybe CType,-- ^ The C type that should be used
                                    -- for this type when using the FFI
                                    -- and CAPI

        algTcGadtSyntax  :: Bool,   -- ^ Was the data type declared with GADT
                                    -- syntax?  If so, that doesn't mean it's a
                                    -- true GADT; only that the "where" form
                                    -- was used.  This field is used only to
                                    -- guide pretty-printing

        algTcStupidTheta :: [PredType], -- ^ The \"stupid theta\" for the data
                                        -- type (always empty for GADTs).  A
                                        -- \"stupid theta\" is the context to
                                        -- the left of an algebraic type
                                        -- declaration, e.g. @Eq a@ in the
                                        -- declaration @data Eq a => T a ...@.

        algTcRhs    :: AlgTyConRhs, -- ^ Contains information about the
                                    -- data constructors of the algebraic type

720 721 722
        algTcFields :: FieldLabelEnv, -- ^ Maps a label to information
                                      -- about the field

723
        algTcParent :: AlgTyConFlav -- ^ Gives the class or family declaration
724 725
                                       -- 'TyCon' for derived 'TyCon's representing
                                       -- class or family instances, respectively.
726

727 728
    }

batterseapower's avatar
batterseapower committed
729
  -- | Represents type synonyms
730 731 732 733 734 735 736
  | SynonymTyCon {
        tyConUnique  :: Unique,  -- ^ A Unique of this TyCon. Invariant:
                                 -- identical to Unique of Name stored in
                                 -- tyConName field.

        tyConName    :: Name,    -- ^ Name of the constructor

737
        -- See Note [The binders/kind/arity fields of a TyCon]
738 739 740 741 742 743
        tyConBinders :: [TyConBinder], -- ^ Full binders
        tyConTyVars  :: [TyVar],          -- ^ TyVar binders
        tyConResKind :: Kind,             -- ^ Result kind
        tyConKind    :: Kind,             -- ^ Kind of this TyCon
        tyConArity   :: Arity,            -- ^ Arity
             -- tyConTyVars scope over: synTcRhs
744 745

        tcRoles      :: [Role],  -- ^ The role for each type variable
746
                                 -- This list has length = tyConArity
747 748
                                 -- See also Note [TyCon Role signatures]

749
        synTcRhs     :: Type,    -- ^ Contains information about the expansion
750
                                 -- of the synonym
751 752 753 754

        synIsTau     :: Bool,   -- True <=> the RHS of this synonym does not
                                 --          have any foralls, after expanding any
                                 --          nested synonyms
755
        synIsFamFree  :: Bool    -- True <=> the RHS of this synonym does not mention
756 757 758
                                 --          any type synonym families (data families
                                 --          are fine), again after expanding any
                                 --          nested synonyms
759
    }
760

761 762
  -- | Represents families (both type and data)
  -- Argument roles are all Nominal
763 764 765 766
  | FamilyTyCon {
        tyConUnique  :: Unique,  -- ^ A Unique of this TyCon. Invariant:
                                 -- identical to Unique of Name stored in
                                 -- tyConName field.
767

768
        tyConName    :: Name,    -- ^ Name of the constructor
769

770
        -- See Note [The binders/kind/arity fields of a TyCon]
771 772 773 774 775 776
        tyConBinders :: [TyConBinder], -- ^ Full binders
        tyConTyVars  :: [TyVar],          -- ^ TyVar binders
        tyConResKind :: Kind,             -- ^ Result kind
        tyConKind    :: Kind,             -- ^ Kind of this TyCon
        tyConArity   :: Arity,            -- ^ Arity
            -- tyConTyVars connect an associated family TyCon
777
            -- with its parent class; see TcValidity.checkConsistentFamInst
778

Jan Stolarek's avatar
Jan Stolarek committed
779 780 781 782 783
        famTcResVar  :: Maybe Name,   -- ^ Name of result type variable, used
                                      -- for pretty-printing with --show-iface
                                      -- and for reifying TyCon in Template
                                      -- Haskell

784 785 786 787
        famTcFlav    :: FamTyConFlav, -- ^ Type family flavour: open, closed,
                                      -- abstract, built-in. See comments for
                                      -- FamTyConFlav

Tobias Dammers's avatar
Tobias Dammers committed
788 789
        famTcParent  :: Maybe TyCon,  -- ^ For *associated* type/data families
                                      -- The class tycon in which the family is declared
790
                                      -- See Note [Associated families and their parent class]
791

Jan Stolarek's avatar
Jan Stolarek committed
792 793 794
        famTcInj     :: Injectivity   -- ^ is this a type family injective in
                                      -- its type variables? Nothing if no
                                      -- injectivity annotation was given
795 796
    }

simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
797 798
  -- | Primitive types; cannot be defined in Haskell. This includes
  -- the usual suspects (such as @Int#@) as well as foreign-imported
799
  -- types and kinds (@*@, @#@, and @?@)
800
  | PrimTyCon {
801 802 803 804 805 806
        tyConUnique   :: Unique, -- ^ A Unique of this TyCon. Invariant:
                                 -- identical to Unique of Name stored in
                                 -- tyConName field.

        tyConName     :: Name,   -- ^ Name of the constructor

807
        -- See Note [The binders/kind/arity fields of a TyCon]
808 809 810 811
        tyConBinders :: [TyConBinder], -- ^ Full binders
        tyConResKind :: Kind,             -- ^ Result kind
        tyConKind    :: Kind,             -- ^ Kind of this TyCon
        tyConArity   :: Arity,            -- ^ Arity
812 813

        tcRoles       :: [Role], -- ^ The role for each type variable
814
                                 -- This list has length = tyConArity
815 816
                                 -- See also Note [TyCon Role signatures]

817
        isUnlifted   :: Bool,    -- ^ Most primitive tycons are unlifted (may
818 819
                                 -- not contain bottom) but other are lifted,
                                 -- e.g. @RealWorld@
820 821 822 823
                                 -- Only relevant if tyConKind = *

        primRepName :: Maybe TyConRepName   -- Only relevant for kind TyCons
                                            -- i.e, *, #, ?
824 825
    }

dreixel's avatar
dreixel committed
826
  -- | Represents promoted data constructor.
827
  | PromotedDataCon {          -- See Note [Promoted data constructors]
828 829 830 831
        tyConUnique  :: Unique,     -- ^ Same Unique as the data constructor
        tyConName    :: Name,       -- ^ Same Name as the data constructor

        -- See Note [The binders/kind/arity fields of a TyCon]
Ningning Xie's avatar
Ningning Xie committed
832
        tyConBinders :: [TyConTyCoBinder], -- ^ Full binders
833 834 835
        tyConResKind :: Kind,             -- ^ Result kind
        tyConKind    :: Kind,             -- ^ Kind of this TyCon
        tyConArity   :: Arity,            -- ^ Arity
836 837 838

        tcRoles       :: [Role],    -- ^ Roles: N for kind vars, R for type vars
        dataCon       :: DataCon,   -- ^ Corresponding data constructor
839 840
        tcRepName     :: TyConRepName,
        promDcRepInfo :: RuntimeRepInfo  -- ^ See comments with 'RuntimeRepInfo'
dreixel's avatar
dreixel committed
841 842
    }

843 844
  -- | These exist only during type-checking. See Note [How TcTyCons work]
  -- in TcTyClsDecls
845
  | TcTyCon {
846 847 848 849
        tyConUnique :: Unique,
        tyConName   :: Name,

        -- See Note [The binders/kind/arity fields of a TyCon]
850 851 852 853 854
        tyConBinders :: [TyConBinder], -- ^ Full binders
        tyConTyVars  :: [TyVar],          -- ^ TyVar binders
        tyConResKind :: Kind,             -- ^ Result kind
        tyConKind    :: Kind,             -- ^ Kind of this TyCon
        tyConArity   :: Arity,            -- ^ Arity
855

856 857 858
        tcTyConScopedTyVars :: [(Name,TyVar)],
                           -- ^ Scoped tyvars over the tycon's body
                           -- See Note [How TcTyCons work] in TcTyClsDecls
Tobias Dammers's avatar
Tobias Dammers committed
859 860 861 862 863
                           -- Order *does* matter: for TcTyCons with a CUSK,
                           -- it's the correct dependency order. For TcTyCons
                           -- without a CUSK, it's the original left-to-right
                           -- that the user wrote. Nec'y for getting Specified
                           -- variables in the right order.
864
        tcTyConUserTyVars :: SDoc, -- ^ Original, user-written tycon tyvars
Tobias Dammers's avatar
Tobias Dammers committed
865
        tcTyConIsPoly     :: Bool, -- ^ Is this TcTyCon already generalized?
866

867 868
        tcTyConFlavour :: TyConFlavour
                           -- ^ What sort of 'TyCon' this represents.
869
      }
870

batterseapower's avatar
batterseapower committed
871
-- | Represents right-hand-sides of 'TyCon's for algebraic types
872
data AlgTyConRhs
873

simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
874 875 876
    -- | Says that we know nothing about this data type, except that
    -- it's represented by a pointer.  Used when we export a data type
    -- abstractly into an .hi file.
877
  = AbstractTyCon
878

simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
879 880 881
    -- | Information about those 'TyCon's derived from a @data@
    -- declaration. This includes data types with no constructors at
    -- all.
882
  | DataTyCon {
883
        data_cons :: [DataCon],
884 885
                          -- ^ The data type constructors; can be empty if the
                          --   user declares the type to have no constructors
886
                          --
887
                          -- INVARIANT: Kept in order of increasing 'DataCon'
888
                          -- tag (see the tag assignment in mkTyConTagMap)
889 890
        data_cons_size :: Int,
                          -- ^ Cached value: length data_cons
891
        is_enum :: Bool   -- ^ Cached value: is this an enumeration type?
892
                          --   See Note [Enumeration types]
batterseapower's avatar
batterseapower committed
893
    }
894

895 896 897 898 899 900
  | TupleTyCon {                   -- A boxed, unboxed, or constraint tuple
        data_con :: DataCon,       -- NB: it can be an *unboxed* tuple
        tup_sort :: TupleSort      -- ^ Is this a boxed, unboxed or constraint
                                   -- tuple?
    }

Simon Jakobi's avatar
Simon Jakobi committed
901
  -- | An unboxed sum type.
902
  | SumTyCon {
903 904
        data_cons :: [DataCon],
        data_cons_size :: Int  -- ^ Cached value: length data_cons
905 906
    }

batterseapower's avatar
batterseapower committed
907
  -- | Information about those 'TyCon's derived from a @newtype@ declaration
908
  | NewTyCon {
909
        data_con :: DataCon,    -- ^ The unique constructor for the @newtype@.
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
910
                                --   It has no existentials
batterseapower's avatar
batterseapower committed
911

912 913 914 915 916
        nt_rhs :: Type,         -- ^ Cached value: the argument type of the
                                -- constructor, which is just the representation
                                -- type of the 'TyCon' (remember that @newtype@s
                                -- do not exist at runtime so need a different
                                -- representation type).
917
                                --
918 919
                                -- The free 'TyVar's of this type are the
                                -- 'tyConTyVars' from the corresponding 'TyCon'
batterseapower's avatar
batterseapower committed
920

921 922 923 924 925 926
        nt_etad_rhs :: ([TyVar], Type),
                        -- ^ Same as the 'nt_rhs', but this time eta-reduced.
                        -- Hence the list of 'TyVar's in this field may be
                        -- shorter than the declared arity of the 'TyCon'.

                        -- See Note [Newtype eta]
927
        nt_co :: CoAxiom Unbranched
928 929
                             -- The axiom coercion that creates the @newtype@
                             -- from the representation 'Type'.
930

931 932
                             -- See Note [Newtype coercions]
                             -- Invariant: arity = #tvs in nt_etad_rhs;
933
                             -- See Note [Newtype eta]
934 935
                             -- Watch out!  If any newtypes become transparent
                             -- again check Trac #1072.
936
    }
937

938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954
mkSumTyConRhs :: [DataCon] -> AlgTyConRhs
mkSumTyConRhs data_cons = SumTyCon data_cons (length data_cons)

mkDataTyConRhs :: [DataCon] -> AlgTyConRhs
mkDataTyConRhs cons
  = DataTyCon {
        data_cons = cons,
        data_cons_size = length cons,
        is_enum = not (null cons) && all is_enum_con cons
                  -- See Note [Enumeration types] in TyCon
    }
  where
    is_enum_con con
       | (_univ_tvs, ex_tvs, eq_spec, theta, arg_tys, _res)
           <- dataConFullSig con
       = null ex_tvs && null eq_spec && null theta && null arg_tys

955 956 957 958 959 960 961
-- | Some promoted datacons signify extra info relevant to GHC. For example,
-- the @IntRep@ constructor of @RuntimeRep@ corresponds to the 'IntRep'
-- constructor of 'PrimRep'. This data structure allows us to store this
-- information right in the 'TyCon'. The other approach would be to look
-- up things like @RuntimeRep@'s @PrimRep@ by known-key every time.
data RuntimeRepInfo
  = NoRRI       -- ^ an ordinary promoted data con
962
  | RuntimeRep ([Type] -> [PrimRep])
963 964 965 966 967
      -- ^ A constructor of @RuntimeRep@. The argument to the function should
      -- be the list of arguments to the promoted datacon.
  | VecCount Int         -- ^ A constructor of @VecCount@
  | VecElem PrimElemRep  -- ^ A constructor of @VecElem@

simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
968 969 970
-- | Extract those 'DataCon's that we are able to learn about.  Note
-- that visibility in this sense does not correspond to visibility in
-- the context of any particular user program!
971
visibleDataCons :: AlgTyConRhs -> [DataCon]
972
visibleDataCons (AbstractTyCon {})            = []
973 974
visibleDataCons (DataTyCon{ data_cons = cs }) = cs
visibleDataCons (NewTyCon{ data_con = c })    = [c]
975
visibleDataCons (TupleTyCon{ data_con = c })  = [c]
976
visibleDataCons (SumTyCon{ data_cons = cs })  = cs
977

batterseapower's avatar
batterseapower committed
978
-- ^ Both type classes as well as family instances imply implicit
979
-- type constructors.  These implicit type constructors refer to their parent
980
-- structure (ie, the class or family from which they derive) using a type of
981 982
-- the following form.
data AlgTyConFlav
batterseapower's avatar
batterseapower committed
983
  = -- | An ordinary type constructor has no parent.
984 985 986
    VanillaAlgTyCon
       TyConRepName

987 988 989
    -- | An unboxed type constructor. The TyConRepName is a Maybe since we
    -- currently don't allow unboxed sums to be Typeable since there are too
    -- many of them. See #13276.
990
  | UnboxedAlgTyCon
991
       (Maybe TyConRepName)
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
992

batterseapower's avatar
batterseapower committed
993
  -- | Type constructors representing a class dictionary.
994
  -- See Note [ATyCon for classes] in TyCoRep
995
  | ClassTyCon
996 997
        Class           -- INVARIANT: the classTyCon of this Class is the
                        -- current tycon
998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011
        TyConRepName

  -- | Type constructors representing an *instance* of a *data* family.
  -- Parameters:
  --
  --  1) The type family in question
  --
  --  2) Instance types; free variables are the 'tyConTyVars'
  --  of the current 'TyCon' (not the family one). INVARIANT:
  --  the number of types matches the arity of the family 'TyCon'
  --
  --  3) A 'CoTyCon' identifying the representation
  --  type with the type instance family
  | DataFamInstTyCon          -- See Note [Data type families]
1012
        (CoAxiom Unbranched)  -- The coercion axiom.
1013 1014
               -- A *Representational* coercion,
               -- of kind   T ty1 ty2   ~R   R:T a b c
1015 1016 1017 1018
               -- where T is the family TyCon,
               -- and R:T is the representation TyCon (ie this one)
               -- and a,b,c are the tyConTyVars of this TyCon
               --
1019 1020
               -- BUT may be eta-reduced; see FamInstEnv
               --     Note [Eta reduction for data families]
1021 1022 1023

          -- Cached fields of the CoAxiom, but adjusted to
          -- use the tyConTyVars of this TyCon
1024 1025
        TyCon   -- The family TyCon
        [Type]  -- Argument types (mentions the tyConTyVars of this TyCon)
1026 1027
                -- No shorter in length than the tyConTyVars of the family TyCon
                -- How could it be longer? See [Arity of data families] in FamInstEnv
1028

1029
        -- E.g.  data instance T [a] = ...
1030 1031 1032
        -- gives a representation tycon:
        --      data R:TList a = ...
        --      axiom co a :: T [a] ~ R:TList a
1033 1034 1035 1036 1037 1038
        -- with R:TList's algTcParent = DataFamInstTyCon T [a] co

instance Outputable AlgTyConFlav where
    ppr (VanillaAlgTyCon {})        = text "Vanilla ADT"
    ppr (UnboxedAlgTyCon {})        = text "Unboxed ADT"
    ppr (ClassTyCon cls _)          = text "Class parent" <+> ppr cls
1039 1040
    ppr (DataFamInstTyCon _ tc tys) = text "Family parent (family instance)"
                                      <+> ppr tc <+> sep (map pprType tys)
batterseapower's avatar
batterseapower committed
1041

1042
-- | Checks the invariants of a 'AlgTyConFlav' given the appropriate type class
1043
-- name, if any
1044 1045
okParent :: Name -> AlgTyConFlav -> Bool
okParent _       (VanillaAlgTyCon {})            = True
Ben Gamari's avatar
Ben Gamari committed
1046
okParent _       (UnboxedAlgTyCon {})            = True
1047
okParent tc_name (ClassTyCon cls _)              = tc_name == tyConName (classTyCon cls)
1048
okParent _       (DataFamInstTyCon _ fam_tc tys) = tys `lengthAtLeast` tyConArity fam_tc
1049

1050 1051 1052
isNoParent :: AlgTyConFlav -> Bool
isNoParent (VanillaAlgTyCon {}) = True
isNoParent _                   = False