a31ecddd72f748613300dd2ec486803a52540b57
[ghc.git] / compiler / types / TyCon.hs
1 {-
2 (c) The University of Glasgow 2006
3 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4
5
6 The @TyCon@ datatype
7 -}
8
9 {-# LANGUAGE CPP, FlexibleInstances #-}
10
11 module TyCon(
12 -- * Main TyCon data types
13 TyCon, AlgTyConRhs(..), visibleDataCons,
14 AlgTyConFlav(..), isNoParent,
15 FamTyConFlav(..), Role(..), Injectivity(..),
16 RuntimeRepInfo(..),
17
18 -- * TyConBinder
19 TyConBinder, TyConBndrVis(..),
20 mkNamedTyConBinder, mkNamedTyConBinders,
21 mkAnonTyConBinder, mkAnonTyConBinders,
22 tyConBinderArgFlag, isNamedTyConBinder,
23 isVisibleTyConBinder, isInvisibleTyConBinder,
24
25 -- ** Field labels
26 tyConFieldLabels, tyConFieldLabelEnv,
27
28 -- ** Constructing TyCons
29 mkAlgTyCon,
30 mkClassTyCon,
31 mkFunTyCon,
32 mkPrimTyCon,
33 mkKindTyCon,
34 mkLiftedPrimTyCon,
35 mkTupleTyCon,
36 mkSynonymTyCon,
37 mkFamilyTyCon,
38 mkPromotedDataCon,
39 mkTcTyCon,
40
41 -- ** Predicates on TyCons
42 isAlgTyCon, isVanillaAlgTyCon,
43 isClassTyCon, isFamInstTyCon,
44 isFunTyCon,
45 isPrimTyCon,
46 isTupleTyCon, isUnboxedTupleTyCon, isBoxedTupleTyCon,
47 isTypeSynonymTyCon,
48 mightBeUnsaturatedTyCon,
49 isPromotedDataCon, isPromotedDataCon_maybe,
50 isKindTyCon, isLiftedTypeKindTyConName,
51
52 isDataTyCon, isProductTyCon, isDataProductTyCon_maybe,
53 isEnumerationTyCon,
54 isNewTyCon, isAbstractTyCon,
55 isFamilyTyCon, isOpenFamilyTyCon,
56 isTypeFamilyTyCon, isDataFamilyTyCon,
57 isOpenTypeFamilyTyCon, isClosedSynFamilyTyConWithAxiom_maybe,
58 familyTyConInjectivityInfo,
59 isBuiltInSynFamTyCon_maybe,
60 isUnliftedTyCon,
61 isGadtSyntaxTyCon, isInjectiveTyCon, isGenerativeTyCon, isGenInjAlgRhs,
62 isTyConAssoc, tyConAssoc_maybe,
63 isImplicitTyCon,
64 isTyConWithSrcDataCons,
65 isTcTyCon,
66
67 -- ** Extracting information out of TyCons
68 tyConName,
69 tyConKind,
70 tyConUnique,
71 tyConTyVars,
72 tyConCType, tyConCType_maybe,
73 tyConDataCons, tyConDataCons_maybe,
74 tyConSingleDataCon_maybe, tyConSingleDataCon,
75 tyConSingleAlgDataCon_maybe,
76 tyConFamilySize,
77 tyConStupidTheta,
78 tyConArity,
79 tyConRoles,
80 tyConFlavour,
81 tyConTuple_maybe, tyConClass_maybe, tyConATs,
82 tyConFamInst_maybe, tyConFamInstSig_maybe, tyConFamilyCoercion_maybe,
83 tyConFamilyResVar_maybe,
84 synTyConDefn_maybe, synTyConRhs_maybe,
85 famTyConFlav_maybe, famTcResVar,
86 algTyConRhs,
87 newTyConRhs, newTyConEtadArity, newTyConEtadRhs,
88 unwrapNewTyCon_maybe, unwrapNewTyConEtad_maybe,
89 newTyConDataCon_maybe,
90 algTcFields,
91 tyConRuntimeRepInfo,
92 tyConBinders, tyConResKind,
93 tcTyConScopedTyVars,
94
95 -- ** Manipulating TyCons
96 expandSynTyCon_maybe,
97 makeTyConAbstract,
98 newTyConCo, newTyConCo_maybe,
99 pprPromotionQuote, mkTyConKind,
100
101 -- * Runtime type representation
102 TyConRepName, tyConRepName_maybe,
103 mkPrelTyConRepName,
104 tyConRepModOcc,
105
106 -- * Primitive representations of Types
107 PrimRep(..), PrimElemRep(..),
108 isVoidRep, isGcPtrRep,
109 primRepSizeW, primElemRepSizeB,
110 primRepIsFloat,
111
112 -- * Recursion breaking
113 RecTcChecker, initRecTc, checkRecTc
114
115 ) where
116
117 #include "HsVersions.h"
118
119 import {-# SOURCE #-} TyCoRep ( Kind, Type, PredType, pprType )
120 import {-# SOURCE #-} TysWiredIn ( runtimeRepTyCon, constraintKind
121 , vecCountTyCon, vecElemTyCon, liftedTypeKind
122 , mkFunKind, mkForAllKind )
123 import {-# SOURCE #-} DataCon ( DataCon, dataConExTyVars, dataConFieldLabels )
124
125 import Binary
126 import Var
127 import Class
128 import BasicTypes
129 import DynFlags
130 import ForeignCall
131 import Name
132 import NameEnv
133 import CoAxiom
134 import PrelNames
135 import Maybes
136 import Outputable
137 import FastStringEnv
138 import FieldLabel
139 import Constants
140 import Util
141 import Unique( tyConRepNameUnique, dataConRepNameUnique )
142 import UniqSet
143 import Module
144
145 import qualified Data.Data as Data
146
147 {-
148 -----------------------------------------------
149 Notes about type families
150 -----------------------------------------------
151
152 Note [Type synonym families]
153 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
154 * Type synonym families, also known as "type functions", map directly
155 onto the type functions in FC:
156
157 type family F a :: *
158 type instance F Int = Bool
159 ..etc...
160
161 * Reply "yes" to isTypeFamilyTyCon, and isFamilyTyCon
162
163 * From the user's point of view (F Int) and Bool are simply
164 equivalent types.
165
166 * A Haskell 98 type synonym is a degenerate form of a type synonym
167 family.
168
169 * Type functions can't appear in the LHS of a type function:
170 type instance F (F Int) = ... -- BAD!
171
172 * Translation of type family decl:
173 type family F a :: *
174 translates to
175 a FamilyTyCon 'F', whose FamTyConFlav is OpenSynFamilyTyCon
176
177 type family G a :: * where
178 G Int = Bool
179 G Bool = Char
180 G a = ()
181 translates to
182 a FamilyTyCon 'G', whose FamTyConFlav is ClosedSynFamilyTyCon, with the
183 appropriate CoAxiom representing the equations
184
185 We also support injective type families -- see Note [Injective type families]
186
187 Note [Data type families]
188 ~~~~~~~~~~~~~~~~~~~~~~~~~
189 See also Note [Wrappers for data instance tycons] in MkId.hs
190
191 * Data type families are declared thus
192 data family T a :: *
193 data instance T Int = T1 | T2 Bool
194
195 Here T is the "family TyCon".
196
197 * Reply "yes" to isDataFamilyTyCon, and isFamilyTyCon
198
199 * The user does not see any "equivalent types" as he did with type
200 synonym families. He just sees constructors with types
201 T1 :: T Int
202 T2 :: Bool -> T Int
203
204 * Here's the FC version of the above declarations:
205
206 data T a
207 data R:TInt = T1 | T2 Bool
208 axiom ax_ti : T Int ~R R:TInt
209
210 Note that this is a *representational* coercion
211 The R:TInt is the "representation TyCons".
212 It has an AlgTyConFlav of
213 DataFamInstTyCon T [Int] ax_ti
214
215 * The axiom ax_ti may be eta-reduced; see
216 Note [Eta reduction for data family axioms] in TcInstDcls
217
218 * The data constructor T2 has a wrapper (which is what the
219 source-level "T2" invokes):
220
221 $WT2 :: Bool -> T Int
222 $WT2 b = T2 b `cast` sym ax_ti
223
224 * A data instance can declare a fully-fledged GADT:
225
226 data instance T (a,b) where
227 X1 :: T (Int,Bool)
228 X2 :: a -> b -> T (a,b)
229
230 Here's the FC version of the above declaration:
231
232 data R:TPair a where
233 X1 :: R:TPair Int Bool
234 X2 :: a -> b -> R:TPair a b
235 axiom ax_pr :: T (a,b) ~R R:TPair a b
236
237 $WX1 :: forall a b. a -> b -> T (a,b)
238 $WX1 a b (x::a) (y::b) = X2 a b x y `cast` sym (ax_pr a b)
239
240 The R:TPair are the "representation TyCons".
241 We have a bit of work to do, to unpick the result types of the
242 data instance declaration for T (a,b), to get the result type in the
243 representation; e.g. T (a,b) --> R:TPair a b
244
245 The representation TyCon R:TList, has an AlgTyConFlav of
246
247 DataFamInstTyCon T [(a,b)] ax_pr
248
249 * Notice that T is NOT translated to a FC type function; it just
250 becomes a "data type" with no constructors, which can be coerced inot
251 into R:TInt, R:TPair by the axioms. These axioms
252 axioms come into play when (and *only* when) you
253 - use a data constructor
254 - do pattern matching
255 Rather like newtype, in fact
256
257 As a result
258
259 - T behaves just like a data type so far as decomposition is concerned
260
261 - (T Int) is not implicitly converted to R:TInt during type inference.
262 Indeed the latter type is unknown to the programmer.
263
264 - There *is* an instance for (T Int) in the type-family instance
265 environment, but it is only used for overlap checking
266
267 - It's fine to have T in the LHS of a type function:
268 type instance F (T a) = [a]
269
270 It was this last point that confused me! The big thing is that you
271 should not think of a data family T as a *type function* at all, not
272 even an injective one! We can't allow even injective type functions
273 on the LHS of a type function:
274 type family injective G a :: *
275 type instance F (G Int) = Bool
276 is no good, even if G is injective, because consider
277 type instance G Int = Bool
278 type instance F Bool = Char
279
280 So a data type family is not an injective type function. It's just a
281 data type with some axioms that connect it to other data types.
282
283 * The tyConTyVars of the representation tycon are the tyvars that the
284 user wrote in the patterns. This is important in TcDeriv, where we
285 bring these tyvars into scope before type-checking the deriving
286 clause. This fact is arranged for in TcInstDecls.tcDataFamInstDecl.
287
288 Note [Associated families and their parent class]
289 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
290 *Associated* families are just like *non-associated* families, except
291 that they have a famTcParent field of (Just cls), which identifies the
292 parent class.
293
294 However there is an important sharing relationship between
295 * the tyConTyVars of the parent Class
296 * the tyConTyvars of the associated TyCon
297
298 class C a b where
299 data T p a
300 type F a q b
301
302 Here the 'a' and 'b' are shared with the 'Class'; that is, they have
303 the same Unique.
304
305 This is important. In an instance declaration we expect
306 * all the shared variables to be instantiated the same way
307 * the non-shared variables of the associated type should not
308 be instantiated at all
309
310 instance C [x] (Tree y) where
311 data T p [x] = T1 x | T2 p
312 type F [x] q (Tree y) = (x,y,q)
313
314 Note [TyCon Role signatures]
315 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
316 Every tycon has a role signature, assigning a role to each of the tyConTyVars
317 (or of equal length to the tyConArity, if there are no tyConTyVars). An
318 example demonstrates these best: say we have a tycon T, with parameters a at
319 nominal, b at representational, and c at phantom. Then, to prove
320 representational equality between T a1 b1 c1 and T a2 b2 c2, we need to have
321 nominal equality between a1 and a2, representational equality between b1 and
322 b2, and nothing in particular (i.e., phantom equality) between c1 and c2. This
323 might happen, say, with the following declaration:
324
325 data T a b c where
326 MkT :: b -> T Int b c
327
328 Data and class tycons have their roles inferred (see inferRoles in TcTyDecls),
329 as do vanilla synonym tycons. Family tycons have all parameters at role N,
330 though it is conceivable that we could relax this restriction. (->)'s and
331 tuples' parameters are at role R. Each primitive tycon declares its roles;
332 it's worth noting that (~#)'s parameters are at role N. Promoted data
333 constructors' type arguments are at role R. All kind arguments are at role
334 N.
335
336 Note [Unboxed tuple RuntimeRep vars]
337 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
338 The contents of an unboxed tuple may have any representation. Accordingly,
339 the kind of the unboxed tuple constructor is runtime-representation
340 polymorphic. For example,
341
342 (#,#) :: forall (q :: RuntimeRep) (r :: RuntimeRep). TYPE q -> TYPE r -> #
343
344 These extra tyvars (v and w) cause some delicate processing around tuples,
345 where we used to be able to assume that the tycon arity and the
346 datacon arity were the same.
347
348 Note [Injective type families]
349 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
350 We allow injectivity annotations for type families (both open and closed):
351
352 type family F (a :: k) (b :: k) = r | r -> a
353 type family G a b = res | res -> a b where ...
354
355 Injectivity information is stored in the `famTcInj` field of `FamilyTyCon`.
356 `famTcInj` maybe stores a list of Bools, where each entry corresponds to a
357 single element of `tyConTyVars` (both lists should have identical length). If no
358 injectivity annotation was provided `famTcInj` is Nothing. From this follows an
359 invariant that if `famTcInj` is a Just then at least one element in the list
360 must be True.
361
362 See also:
363 * [Injectivity annotation] in HsDecls
364 * [Renaming injectivity annotation] in RnSource
365 * [Verifying injectivity annotation] in FamInstEnv
366 * [Type inference for type families with injectivity] in TcInteract
367
368 ************************************************************************
369 * *
370 TyConBinder
371 * *
372 ************************************************************************
373 -}
374
375 type TyConBinder = TyVarBndr TyVar TyConBndrVis
376
377 data TyConBndrVis
378 = NamedTCB ArgFlag
379 | AnonTCB
380
381 mkAnonTyConBinder :: TyVar -> TyConBinder
382 mkAnonTyConBinder tv = TvBndr tv AnonTCB
383
384 mkAnonTyConBinders :: [TyVar] -> [TyConBinder]
385 mkAnonTyConBinders tvs = map mkAnonTyConBinder tvs
386
387 mkNamedTyConBinder :: ArgFlag -> TyVar -> TyConBinder
388 -- The odd argument order supports currying
389 mkNamedTyConBinder vis tv = TvBndr tv (NamedTCB vis)
390
391 mkNamedTyConBinders :: ArgFlag -> [TyVar] -> [TyConBinder]
392 -- The odd argument order supports currying
393 mkNamedTyConBinders vis tvs = map (mkNamedTyConBinder vis) tvs
394
395 tyConBinderArgFlag :: TyConBinder -> ArgFlag
396 tyConBinderArgFlag (TvBndr _ (NamedTCB vis)) = vis
397 tyConBinderArgFlag (TvBndr _ AnonTCB) = Required
398
399 isNamedTyConBinder :: TyConBinder -> Bool
400 isNamedTyConBinder (TvBndr _ (NamedTCB {})) = True
401 isNamedTyConBinder _ = False
402
403 isVisibleTyConBinder :: TyVarBndr tv TyConBndrVis -> Bool
404 -- Works for IfaceTyConBinder too
405 isVisibleTyConBinder (TvBndr _ (NamedTCB vis)) = isVisibleArgFlag vis
406 isVisibleTyConBinder (TvBndr _ AnonTCB) = True
407
408 isInvisibleTyConBinder :: TyVarBndr tv TyConBndrVis -> Bool
409 -- Works for IfaceTyConBinder too
410 isInvisibleTyConBinder tcb = not (isVisibleTyConBinder tcb)
411
412 mkTyConKind :: [TyConBinder] -> Kind -> Kind
413 mkTyConKind bndrs res_kind = foldr mk res_kind bndrs
414 where
415 mk :: TyConBinder -> Kind -> Kind
416 mk (TvBndr tv AnonTCB) k = mkFunKind (tyVarKind tv) k
417 mk (TvBndr tv (NamedTCB vis)) k = mkForAllKind tv vis k
418
419 {- Note [The binders/kind/arity fields of a TyCon]
420 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
421 All TyCons have this group of fields
422 tyConBinders :: [TyConBinder]
423 tyConResKind :: Kind
424 tyConTyVars :: [TyVra] -- Cached = binderVars tyConBinders
425 tyConKind :: Kind -- Cached = mkTyConKind tyConBinders tyConResKind
426 tyConArity :: Arity -- Cached = length tyConBinders
427
428 They fit together like so:
429
430 * tyConBinders gives the telescope of type variables on the LHS of the
431 type declaration. For example:
432
433 type App a (b :: k) = a b
434
435 tyConBinders = [ TvBndr (k::*) (NamedTCB Inferred)
436 , TvBndr (a:k->*) AnonTCB
437 , TvBndr (b:k) AnonTCB ]
438
439 Note that that are three binders here, including the
440 kind variable k.
441
442 See Note [TyBinders and ArgFlags] in TyCoRep for what
443 the visibility flag means.
444
445 * Each TyConBinder tyConBinders has a TyVar, and that TyVar may
446 scope over some other part of the TyCon's definition. Eg
447 type T a = a->a
448 we have
449 tyConBinders = [ TvBndr (a:*) AnonTCB ]
450 synTcRhs = a->a
451 So the 'a' scopes over the synTcRhs
452
453 * From the tyConBinders and tyConResKind we can get the tyConKind
454 E.g for our App example:
455 App :: forall k. (k->*) -> k -> *
456
457 We get a 'forall' in the kind for each NamedTCB, and an arrow
458 for each AnonTCB
459
460 tyConKind is the full kind of the TyCon, not just the result kind
461
462 * tyConArity is the arguments this TyCon must be applied to, to be
463 considered saturated. Here we mean "applied to in the actual Type",
464 not surface syntax; i.e. including implicit kind variables.
465 So it's just (length tyConBinders)
466 -}
467
468 instance Outputable tv => Outputable (TyVarBndr tv TyConBndrVis) where
469 ppr (TvBndr v AnonTCB) = ppr v
470 ppr (TvBndr v (NamedTCB Required)) = ppr v
471 ppr (TvBndr v (NamedTCB Specified)) = char '@' <> ppr v
472 ppr (TvBndr v (NamedTCB Inferred)) = braces (ppr v)
473
474 instance Binary TyConBndrVis where
475 put_ bh AnonTCB = putByte bh 0
476 put_ bh (NamedTCB vis) = do { putByte bh 1; put_ bh vis }
477
478 get bh = do { h <- getByte bh
479 ; case h of
480 0 -> return AnonTCB
481 _ -> do { vis <- get bh; return (NamedTCB vis) } }
482
483
484 {- *********************************************************************
485 * *
486 The TyCon type
487 * *
488 ************************************************************************
489 -}
490
491
492 -- | TyCons represent type constructors. Type constructors are introduced by
493 -- things such as:
494 --
495 -- 1) Data declarations: @data Foo = ...@ creates the @Foo@ type constructor of
496 -- kind @*@
497 --
498 -- 2) Type synonyms: @type Foo = ...@ creates the @Foo@ type constructor
499 --
500 -- 3) Newtypes: @newtype Foo a = MkFoo ...@ creates the @Foo@ type constructor
501 -- of kind @* -> *@
502 --
503 -- 4) Class declarations: @class Foo where@ creates the @Foo@ type constructor
504 -- of kind @*@
505 --
506 -- This data type also encodes a number of primitive, built in type constructors
507 -- such as those for function and tuple types.
508
509 -- If you edit this type, you may need to update the GHC formalism
510 -- See Note [GHC Formalism] in coreSyn/CoreLint.hs
511 data TyCon
512 = -- | The function type constructor, @(->)@
513 FunTyCon {
514 tyConUnique :: Unique, -- ^ A Unique of this TyCon. Invariant:
515 -- identical to Unique of Name stored in
516 -- tyConName field.
517
518 tyConName :: Name, -- ^ Name of the constructor
519
520 -- See Note [The binders/kind/arity fields of a TyCon]
521 tyConBinders :: [TyConBinder], -- ^ Full binders
522 tyConResKind :: Kind, -- ^ Result kind
523 tyConKind :: Kind, -- ^ Kind of this TyCon
524 tyConArity :: Arity, -- ^ Arity
525
526 tcRepName :: TyConRepName
527 }
528
529 -- | Algebraic data types, from
530 -- - @data@ declararations
531 -- - @newtype@ declarations
532 -- - data instance declarations
533 -- - type instance declarations
534 -- - the TyCon generated by a class declaration
535 -- - boxed tuples
536 -- - unboxed tuples
537 -- - constraint tuples
538 -- All these constructors are lifted and boxed except unboxed tuples
539 -- which should have an 'UnboxedAlgTyCon' parent.
540 -- Data/newtype/type /families/ are handled by 'FamilyTyCon'.
541 -- See 'AlgTyConRhs' for more information.
542 | AlgTyCon {
543 tyConUnique :: Unique, -- ^ A Unique of this TyCon. Invariant:
544 -- identical to Unique of Name stored in
545 -- tyConName field.
546
547 tyConName :: Name, -- ^ Name of the constructor
548
549 -- See Note [The binders/kind/arity fields of a TyCon]
550 tyConBinders :: [TyConBinder], -- ^ Full binders
551 tyConTyVars :: [TyVar], -- ^ TyVar binders
552 tyConResKind :: Kind, -- ^ Result kind
553 tyConKind :: Kind, -- ^ Kind of this TyCon
554 tyConArity :: Arity, -- ^ Arity
555
556 -- The tyConTyVars scope over:
557 --
558 -- 1. The 'algTcStupidTheta'
559 -- 2. The cached types in algTyConRhs.NewTyCon
560 -- 3. The family instance types if present
561 --
562 -- Note that it does /not/ scope over the data
563 -- constructors.
564
565 tcRoles :: [Role], -- ^ The role for each type variable
566 -- This list has length = tyConArity
567 -- See also Note [TyCon Role signatures]
568
569 tyConCType :: Maybe CType,-- ^ The C type that should be used
570 -- for this type when using the FFI
571 -- and CAPI
572
573 algTcGadtSyntax :: Bool, -- ^ Was the data type declared with GADT
574 -- syntax? If so, that doesn't mean it's a
575 -- true GADT; only that the "where" form
576 -- was used. This field is used only to
577 -- guide pretty-printing
578
579 algTcStupidTheta :: [PredType], -- ^ The \"stupid theta\" for the data
580 -- type (always empty for GADTs). A
581 -- \"stupid theta\" is the context to
582 -- the left of an algebraic type
583 -- declaration, e.g. @Eq a@ in the
584 -- declaration @data Eq a => T a ...@.
585
586 algTcRhs :: AlgTyConRhs, -- ^ Contains information about the
587 -- data constructors of the algebraic type
588
589 algTcFields :: FieldLabelEnv, -- ^ Maps a label to information
590 -- about the field
591
592 algTcParent :: AlgTyConFlav -- ^ Gives the class or family declaration
593 -- 'TyCon' for derived 'TyCon's representing
594 -- class or family instances, respectively.
595
596 }
597
598 -- | Represents type synonyms
599 | SynonymTyCon {
600 tyConUnique :: Unique, -- ^ A Unique of this TyCon. Invariant:
601 -- identical to Unique of Name stored in
602 -- tyConName field.
603
604 tyConName :: Name, -- ^ Name of the constructor
605
606 -- See Note [The binders/kind/arity fields of a TyCon]
607 tyConBinders :: [TyConBinder], -- ^ Full binders
608 tyConTyVars :: [TyVar], -- ^ TyVar binders
609 tyConResKind :: Kind, -- ^ Result kind
610 tyConKind :: Kind, -- ^ Kind of this TyCon
611 tyConArity :: Arity, -- ^ Arity
612 -- tyConTyVars scope over: synTcRhs
613
614 tcRoles :: [Role], -- ^ The role for each type variable
615 -- This list has length = tyConArity
616 -- See also Note [TyCon Role signatures]
617
618 synTcRhs :: Type -- ^ Contains information about the expansion
619 -- of the synonym
620 }
621
622 -- | Represents families (both type and data)
623 -- Argument roles are all Nominal
624 | FamilyTyCon {
625 tyConUnique :: Unique, -- ^ A Unique of this TyCon. Invariant:
626 -- identical to Unique of Name stored in
627 -- tyConName field.
628
629 tyConName :: Name, -- ^ Name of the constructor
630
631 -- See Note [The binders/kind/arity fields of a TyCon]
632 tyConBinders :: [TyConBinder], -- ^ Full binders
633 tyConTyVars :: [TyVar], -- ^ TyVar binders
634 tyConResKind :: Kind, -- ^ Result kind
635 tyConKind :: Kind, -- ^ Kind of this TyCon
636 tyConArity :: Arity, -- ^ Arity
637 -- tyConTyVars connect an associated family TyCon
638 -- with its parent class; see TcValidity.checkConsistentFamInst
639
640 famTcResVar :: Maybe Name, -- ^ Name of result type variable, used
641 -- for pretty-printing with --show-iface
642 -- and for reifying TyCon in Template
643 -- Haskell
644
645 famTcFlav :: FamTyConFlav, -- ^ Type family flavour: open, closed,
646 -- abstract, built-in. See comments for
647 -- FamTyConFlav
648
649 famTcParent :: Maybe Class, -- ^ For *associated* type/data families
650 -- The class in whose declaration the family is declared
651 -- See Note [Associated families and their parent class]
652
653 famTcInj :: Injectivity -- ^ is this a type family injective in
654 -- its type variables? Nothing if no
655 -- injectivity annotation was given
656 }
657
658 -- | Primitive types; cannot be defined in Haskell. This includes
659 -- the usual suspects (such as @Int#@) as well as foreign-imported
660 -- types and kinds (@*@, @#@, and @?@)
661 | PrimTyCon {
662 tyConUnique :: Unique, -- ^ A Unique of this TyCon. Invariant:
663 -- identical to Unique of Name stored in
664 -- tyConName field.
665
666 tyConName :: Name, -- ^ Name of the constructor
667
668 -- See Note [The binders/kind/arity fields of a TyCon]
669 tyConBinders :: [TyConBinder], -- ^ Full binders
670 tyConResKind :: Kind, -- ^ Result kind
671 tyConKind :: Kind, -- ^ Kind of this TyCon
672 tyConArity :: Arity, -- ^ Arity
673
674 tcRoles :: [Role], -- ^ The role for each type variable
675 -- This list has length = tyConArity
676 -- See also Note [TyCon Role signatures]
677
678 isUnlifted :: Bool, -- ^ Most primitive tycons are unlifted (may
679 -- not contain bottom) but other are lifted,
680 -- e.g. @RealWorld@
681 -- Only relevant if tyConKind = *
682
683 primRepName :: Maybe TyConRepName -- Only relevant for kind TyCons
684 -- i.e, *, #, ?
685 }
686
687 -- | Represents promoted data constructor.
688 | PromotedDataCon { -- See Note [Promoted data constructors]
689 tyConUnique :: Unique, -- ^ Same Unique as the data constructor
690 tyConName :: Name, -- ^ Same Name as the data constructor
691
692 -- See Note [The binders/kind/arity fields of a TyCon]
693 tyConBinders :: [TyConBinder], -- ^ Full binders
694 tyConResKind :: Kind, -- ^ Result kind
695 tyConKind :: Kind, -- ^ Kind of this TyCon
696 tyConArity :: Arity, -- ^ Arity
697
698 tcRoles :: [Role], -- ^ Roles: N for kind vars, R for type vars
699 dataCon :: DataCon, -- ^ Corresponding data constructor
700 tcRepName :: TyConRepName,
701 promDcRepInfo :: RuntimeRepInfo -- ^ See comments with 'RuntimeRepInfo'
702 }
703
704 -- | These exist only during a recursive type/class type-checking knot.
705 | TcTyCon {
706 tyConUnique :: Unique,
707 tyConName :: Name,
708 tyConUnsat :: Bool, -- ^ can this tycon be unsaturated?
709
710 -- See Note [The binders/kind/arity fields of a TyCon]
711 tyConBinders :: [TyConBinder], -- ^ Full binders
712 tyConTyVars :: [TyVar], -- ^ TyVar binders
713 tyConResKind :: Kind, -- ^ Result kind
714 tyConKind :: Kind, -- ^ Kind of this TyCon
715 tyConArity :: Arity, -- ^ Arity
716
717 tcTyConScopedTyVars :: [TyVar] -- ^ Scoped tyvars over the
718 -- tycon's body. See Note [TcTyCon]
719 }
720
721
722 -- | Represents right-hand-sides of 'TyCon's for algebraic types
723 data AlgTyConRhs
724
725 -- | Says that we know nothing about this data type, except that
726 -- it's represented by a pointer. Used when we export a data type
727 -- abstractly into an .hi file.
728 = AbstractTyCon
729 Bool -- True <=> It's definitely a distinct data type,
730 -- equal only to itself; ie not a newtype
731 -- False <=> Not sure
732
733 -- | Information about those 'TyCon's derived from a @data@
734 -- declaration. This includes data types with no constructors at
735 -- all.
736 | DataTyCon {
737 data_cons :: [DataCon],
738 -- ^ The data type constructors; can be empty if the
739 -- user declares the type to have no constructors
740 --
741 -- INVARIANT: Kept in order of increasing 'DataCon'
742 -- tag (see the tag assignment in DataCon.mkDataCon)
743
744 is_enum :: Bool -- ^ Cached value: is this an enumeration type?
745 -- See Note [Enumeration types]
746 }
747
748 | TupleTyCon { -- A boxed, unboxed, or constraint tuple
749 data_con :: DataCon, -- NB: it can be an *unboxed* tuple
750 tup_sort :: TupleSort -- ^ Is this a boxed, unboxed or constraint
751 -- tuple?
752 }
753
754 -- | Information about those 'TyCon's derived from a @newtype@ declaration
755 | NewTyCon {
756 data_con :: DataCon, -- ^ The unique constructor for the @newtype@.
757 -- It has no existentials
758
759 nt_rhs :: Type, -- ^ Cached value: the argument type of the
760 -- constructor, which is just the representation
761 -- type of the 'TyCon' (remember that @newtype@s
762 -- do not exist at runtime so need a different
763 -- representation type).
764 --
765 -- The free 'TyVar's of this type are the
766 -- 'tyConTyVars' from the corresponding 'TyCon'
767
768 nt_etad_rhs :: ([TyVar], Type),
769 -- ^ Same as the 'nt_rhs', but this time eta-reduced.
770 -- Hence the list of 'TyVar's in this field may be
771 -- shorter than the declared arity of the 'TyCon'.
772
773 -- See Note [Newtype eta]
774 nt_co :: CoAxiom Unbranched
775 -- The axiom coercion that creates the @newtype@
776 -- from the representation 'Type'.
777
778 -- See Note [Newtype coercions]
779 -- Invariant: arity = #tvs in nt_etad_rhs;
780 -- See Note [Newtype eta]
781 -- Watch out! If any newtypes become transparent
782 -- again check Trac #1072.
783 }
784
785 -- | Some promoted datacons signify extra info relevant to GHC. For example,
786 -- the @IntRep@ constructor of @RuntimeRep@ corresponds to the 'IntRep'
787 -- constructor of 'PrimRep'. This data structure allows us to store this
788 -- information right in the 'TyCon'. The other approach would be to look
789 -- up things like @RuntimeRep@'s @PrimRep@ by known-key every time.
790 data RuntimeRepInfo
791 = NoRRI -- ^ an ordinary promoted data con
792 | RuntimeRep ([Type] -> PrimRep)
793 -- ^ A constructor of @RuntimeRep@. The argument to the function should
794 -- be the list of arguments to the promoted datacon.
795 | VecCount Int -- ^ A constructor of @VecCount@
796 | VecElem PrimElemRep -- ^ A constructor of @VecElem@
797
798 -- | Extract those 'DataCon's that we are able to learn about. Note
799 -- that visibility in this sense does not correspond to visibility in
800 -- the context of any particular user program!
801 visibleDataCons :: AlgTyConRhs -> [DataCon]
802 visibleDataCons (AbstractTyCon {}) = []
803 visibleDataCons (DataTyCon{ data_cons = cs }) = cs
804 visibleDataCons (NewTyCon{ data_con = c }) = [c]
805 visibleDataCons (TupleTyCon{ data_con = c }) = [c]
806
807 -- ^ Both type classes as well as family instances imply implicit
808 -- type constructors. These implicit type constructors refer to their parent
809 -- structure (ie, the class or family from which they derive) using a type of
810 -- the following form.
811 data AlgTyConFlav
812 = -- | An ordinary type constructor has no parent.
813 VanillaAlgTyCon
814 TyConRepName
815
816 -- | An unboxed type constructor. Note that this carries no TyConRepName
817 -- as it is not representable.
818 | UnboxedAlgTyCon
819
820 -- | Type constructors representing a class dictionary.
821 -- See Note [ATyCon for classes] in TyCoRep
822 | ClassTyCon
823 Class -- INVARIANT: the classTyCon of this Class is the
824 -- current tycon
825 TyConRepName
826
827 -- | Type constructors representing an *instance* of a *data* family.
828 -- Parameters:
829 --
830 -- 1) The type family in question
831 --
832 -- 2) Instance types; free variables are the 'tyConTyVars'
833 -- of the current 'TyCon' (not the family one). INVARIANT:
834 -- the number of types matches the arity of the family 'TyCon'
835 --
836 -- 3) A 'CoTyCon' identifying the representation
837 -- type with the type instance family
838 | DataFamInstTyCon -- See Note [Data type families]
839 (CoAxiom Unbranched) -- The coercion axiom.
840 -- A *Representational* coercion,
841 -- of kind T ty1 ty2 ~R R:T a b c
842 -- where T is the family TyCon,
843 -- and R:T is the representation TyCon (ie this one)
844 -- and a,b,c are the tyConTyVars of this TyCon
845 --
846 -- BUT may be eta-reduced; see TcInstDcls
847 -- Note [Eta reduction for data family axioms]
848
849 -- Cached fields of the CoAxiom, but adjusted to
850 -- use the tyConTyVars of this TyCon
851 TyCon -- The family TyCon
852 [Type] -- Argument types (mentions the tyConTyVars of this TyCon)
853 -- Match in length the tyConTyVars of the family TyCon
854
855 -- E.g. data instance T [a] = ...
856 -- gives a representation tycon:
857 -- data R:TList a = ...
858 -- axiom co a :: T [a] ~ R:TList a
859 -- with R:TList's algTcParent = DataFamInstTyCon T [a] co
860
861 instance Outputable AlgTyConFlav where
862 ppr (VanillaAlgTyCon {}) = text "Vanilla ADT"
863 ppr (UnboxedAlgTyCon {}) = text "Unboxed ADT"
864 ppr (ClassTyCon cls _) = text "Class parent" <+> ppr cls
865 ppr (DataFamInstTyCon _ tc tys) = text "Family parent (family instance)"
866 <+> ppr tc <+> sep (map pprType tys)
867
868 -- | Checks the invariants of a 'AlgTyConFlav' given the appropriate type class
869 -- name, if any
870 okParent :: Name -> AlgTyConFlav -> Bool
871 okParent _ (VanillaAlgTyCon {}) = True
872 okParent _ (UnboxedAlgTyCon) = True
873 okParent tc_name (ClassTyCon cls _) = tc_name == tyConName (classTyCon cls)
874 okParent _ (DataFamInstTyCon _ fam_tc tys) = tyConArity fam_tc == length tys
875
876 isNoParent :: AlgTyConFlav -> Bool
877 isNoParent (VanillaAlgTyCon {}) = True
878 isNoParent _ = False
879
880 --------------------
881
882 data Injectivity
883 = NotInjective
884 | Injective [Bool] -- 1-1 with tyConTyVars (incl kind vars)
885 deriving( Eq )
886
887 -- | Information pertaining to the expansion of a type synonym (@type@)
888 data FamTyConFlav
889 = -- | Represents an open type family without a fixed right hand
890 -- side. Additional instances can appear at any time.
891 --
892 -- These are introduced by either a top level declaration:
893 --
894 -- > data family T a :: *
895 --
896 -- Or an associated data type declaration, within a class declaration:
897 --
898 -- > class C a b where
899 -- > data T b :: *
900 DataFamilyTyCon
901 TyConRepName
902
903 -- | An open type synonym family e.g. @type family F x y :: * -> *@
904 | OpenSynFamilyTyCon
905
906 -- | A closed type synonym family e.g.
907 -- @type family F x where { F Int = Bool }@
908 | ClosedSynFamilyTyCon (Maybe (CoAxiom Branched))
909 -- See Note [Closed type families]
910
911 -- | A closed type synonym family declared in an hs-boot file with
912 -- type family F a where ..
913 | AbstractClosedSynFamilyTyCon
914
915 -- | Built-in type family used by the TypeNats solver
916 | BuiltInSynFamTyCon BuiltInSynFamily
917
918 {- Note [Closed type families]
919 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
920 * In an open type family you can add new instances later. This is the
921 usual case.
922
923 * In a closed type family you can only put equations where the family
924 is defined.
925
926 A non-empty closed type family has a single axiom with multiple
927 branches, stored in the 'ClosedSynFamilyTyCon' constructor. A closed
928 type family with no equations does not have an axiom, because there is
929 nothing for the axiom to prove!
930
931
932 Note [Promoted data constructors]
933 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
934 All data constructors can be promoted to become a type constructor,
935 via the PromotedDataCon alternative in TyCon.
936
937 * The TyCon promoted from a DataCon has the *same* Name and Unique as
938 the DataCon. Eg. If the data constructor Data.Maybe.Just(unique 78,
939 say) is promoted to a TyCon whose name is Data.Maybe.Just(unique 78)
940
941 * Small note: We promote the *user* type of the DataCon. Eg
942 data T = MkT {-# UNPACK #-} !(Bool, Bool)
943 The promoted kind is
944 MkT :: (Bool,Bool) -> T
945 *not*
946 MkT :: Bool -> Bool -> T
947
948 Note [Enumeration types]
949 ~~~~~~~~~~~~~~~~~~~~~~~~
950 We define datatypes with no constructors to *not* be
951 enumerations; this fixes trac #2578, Otherwise we
952 end up generating an empty table for
953 <mod>_<type>_closure_tbl
954 which is used by tagToEnum# to map Int# to constructors
955 in an enumeration. The empty table apparently upset
956 the linker.
957
958 Moreover, all the data constructor must be enumerations, meaning
959 they have type (forall abc. T a b c). GADTs are not enumerations.
960 For example consider
961 data T a where
962 T1 :: T Int
963 T2 :: T Bool
964 T3 :: T a
965 What would [T1 ..] be? [T1,T3] :: T Int? Easiest thing is to exclude them.
966 See Trac #4528.
967
968 Note [Newtype coercions]
969 ~~~~~~~~~~~~~~~~~~~~~~~~
970 The NewTyCon field nt_co is a CoAxiom which is used for coercing from
971 the representation type of the newtype, to the newtype itself. For
972 example,
973
974 newtype T a = MkT (a -> a)
975
976 the NewTyCon for T will contain nt_co = CoT where CoT t : T t ~ t -> t.
977
978 In the case that the right hand side is a type application
979 ending with the same type variables as the left hand side, we
980 "eta-contract" the coercion. So if we had
981
982 newtype S a = MkT [a]
983
984 then we would generate the arity 0 axiom CoS : S ~ []. The
985 primary reason we do this is to make newtype deriving cleaner.
986
987 In the paper we'd write
988 axiom CoT : (forall t. T t) ~ (forall t. [t])
989 and then when we used CoT at a particular type, s, we'd say
990 CoT @ s
991 which encodes as (TyConApp instCoercionTyCon [TyConApp CoT [], s])
992
993 Note [Newtype eta]
994 ~~~~~~~~~~~~~~~~~~
995 Consider
996 newtype Parser a = MkParser (IO a) deriving Monad
997 Are these two types equal (to Core)?
998 Monad Parser
999 Monad IO
1000 which we need to make the derived instance for Monad Parser.
1001
1002 Well, yes. But to see that easily we eta-reduce the RHS type of
1003 Parser, in this case to ([], Froogle), so that even unsaturated applications
1004 of Parser will work right. This eta reduction is done when the type
1005 constructor is built, and cached in NewTyCon.
1006
1007 Here's an example that I think showed up in practice
1008 Source code:
1009 newtype T a = MkT [a]
1010 newtype Foo m = MkFoo (forall a. m a -> Int)
1011
1012 w1 :: Foo []
1013 w1 = ...
1014
1015 w2 :: Foo T
1016 w2 = MkFoo (\(MkT x) -> case w1 of MkFoo f -> f x)
1017
1018 After desugaring, and discarding the data constructors for the newtypes,
1019 we get:
1020 w2 = w1 `cast` Foo CoT
1021 so the coercion tycon CoT must have
1022 kind: T ~ []
1023 and arity: 0
1024
1025 Note [TcTyCon]
1026 ~~~~~~~~~~~~~~
1027 When checking a type/class declaration (in module TcTyClsDecls), we come
1028 upon knowledge of the eventual tycon in bits and pieces. First, we use
1029 getInitialKinds to look over the user-provided kind signature of a tycon
1030 (including, for example, the number of parameters written to the tycon)
1031 to get an initial shape of the tycon's kind. Then, using these initial
1032 kinds, we kind-check the body of the tycon (class methods, data constructors,
1033 etc.), filling in the metavariables in the tycon's initial kind.
1034 We then generalize to get the tycon's final, fixed kind. Finally, once
1035 this has happened for all tycons in a mutually recursive group, we
1036 can desugar the lot.
1037
1038 For convenience, we store partially-known tycons in TcTyCons, which
1039 might store meta-variables. These TcTyCons are stored in the local
1040 environment in TcTyClsDecls, until the real full TyCons can be created
1041 during desugaring. A desugared program should never have a TcTyCon.
1042
1043 A challenging piece in all of this is that we end up taking three separate
1044 passes over every declaration: one in getInitialKind (this pass look only
1045 at the head, not the body), one in kcTyClDecls (to kind-check the body),
1046 and a final one in tcTyClDecls (to desugar). In the latter two passes,
1047 we need to connect the user-written type variables in an LHsQTyVars
1048 with the variables in the tycon's inferred kind. Because the tycon might
1049 not have a CUSK, this matching up is, in general, quite hard to do.
1050 (Look through the git history between Dec 2015 and Apr 2016 for
1051 TcHsType.splitTelescopeTvs!) Instead of trying, we just store the list
1052 of type variables to bring into scope in the later passes when we create
1053 a TcTyCon in getInitialKinds. Much easier this way! These tyvars are
1054 brought into scope in kcTyClTyVars and tcTyClTyVars, both in TcHsType.
1055
1056 It is important that the scoped type variables not be zonked, as some
1057 scoped type variables come into existence as SigTvs. If we zonk, the
1058 Unique will change and the user-written occurrences won't match up with
1059 what we expect.
1060
1061 In a TcTyCon, everything is zonked (except the scoped vars) after
1062 the kind-checking pass.
1063
1064 ************************************************************************
1065 * *
1066 TyConRepName
1067 * *
1068 ********************************************************************* -}
1069
1070 type TyConRepName = Name -- The Name of the top-level declaration
1071 -- $tcMaybe :: Data.Typeable.Internal.TyCon
1072 -- $tcMaybe = TyCon { tyConName = "Maybe", ... }
1073
1074 tyConRepName_maybe :: TyCon -> Maybe TyConRepName
1075 tyConRepName_maybe (FunTyCon { tcRepName = rep_nm })
1076 = Just rep_nm
1077 tyConRepName_maybe (PrimTyCon { primRepName = mb_rep_nm })
1078 = mb_rep_nm
1079 tyConRepName_maybe (AlgTyCon { algTcParent = parent })
1080 | VanillaAlgTyCon rep_nm <- parent = Just rep_nm
1081 | ClassTyCon _ rep_nm <- parent = Just rep_nm
1082 tyConRepName_maybe (FamilyTyCon { famTcFlav = DataFamilyTyCon rep_nm })
1083 = Just rep_nm
1084 tyConRepName_maybe (PromotedDataCon { tcRepName = rep_nm })
1085 = Just rep_nm
1086 tyConRepName_maybe _ = Nothing
1087
1088 -- | Make a 'Name' for the 'Typeable' representation of the given wired-in type
1089 mkPrelTyConRepName :: Name -> TyConRepName
1090 -- See Note [Grand plan for Typeable] in 'TcTypeable' in TcTypeable.
1091 mkPrelTyConRepName tc_name -- Prelude tc_name is always External,
1092 -- so nameModule will work
1093 = mkExternalName rep_uniq rep_mod rep_occ (nameSrcSpan tc_name)
1094 where
1095 name_occ = nameOccName tc_name
1096 name_mod = nameModule tc_name
1097 name_uniq = nameUnique tc_name
1098 rep_uniq | isTcOcc name_occ = tyConRepNameUnique name_uniq
1099 | otherwise = dataConRepNameUnique name_uniq
1100 (rep_mod, rep_occ) = tyConRepModOcc name_mod name_occ
1101
1102 -- | The name (and defining module) for the Typeable representation (TyCon) of a
1103 -- type constructor.
1104 --
1105 -- See Note [Grand plan for Typeable] in 'TcTypeable' in TcTypeable.
1106 tyConRepModOcc :: Module -> OccName -> (Module, OccName)
1107 tyConRepModOcc tc_module tc_occ = (rep_module, mkTyConRepOcc tc_occ)
1108 where
1109 rep_module
1110 | tc_module == gHC_PRIM = gHC_TYPES
1111 | otherwise = tc_module
1112
1113
1114 {- *********************************************************************
1115 * *
1116 PrimRep
1117 * *
1118 ************************************************************************
1119
1120 Note [rep swamp]
1121
1122 GHC has a rich selection of types that represent "primitive types" of
1123 one kind or another. Each of them makes a different set of
1124 distinctions, and mostly the differences are for good reasons,
1125 although it's probably true that we could merge some of these.
1126
1127 Roughly in order of "includes more information":
1128
1129 - A Width (cmm/CmmType) is simply a binary value with the specified
1130 number of bits. It may represent a signed or unsigned integer, a
1131 floating-point value, or an address.
1132
1133 data Width = W8 | W16 | W32 | W64 | W80 | W128
1134
1135 - Size, which is used in the native code generator, is Width +
1136 floating point information.
1137
1138 data Size = II8 | II16 | II32 | II64 | FF32 | FF64 | FF80
1139
1140 it is necessary because e.g. the instruction to move a 64-bit float
1141 on x86 (movsd) is different from the instruction to move a 64-bit
1142 integer (movq), so the mov instruction is parameterised by Size.
1143
1144 - CmmType wraps Width with more information: GC ptr, float, or
1145 other value.
1146
1147 data CmmType = CmmType CmmCat Width
1148
1149 data CmmCat -- "Category" (not exported)
1150 = GcPtrCat -- GC pointer
1151 | BitsCat -- Non-pointer
1152 | FloatCat -- Float
1153
1154 It is important to have GcPtr information in Cmm, since we generate
1155 info tables containing pointerhood for the GC from this. As for
1156 why we have float (and not signed/unsigned) here, see Note [Signed
1157 vs unsigned].
1158
1159 - ArgRep makes only the distinctions necessary for the call and
1160 return conventions of the STG machine. It is essentially CmmType
1161 + void.
1162
1163 - PrimRep makes a few more distinctions than ArgRep: it divides
1164 non-GC-pointers into signed/unsigned and addresses, information
1165 that is necessary for passing these values to foreign functions.
1166
1167 There's another tension here: whether the type encodes its size in
1168 bytes, or whether its size depends on the machine word size. Width
1169 and CmmType have the size built-in, whereas ArgRep and PrimRep do not.
1170
1171 This means to turn an ArgRep/PrimRep into a CmmType requires DynFlags.
1172
1173 On the other hand, CmmType includes some "nonsense" values, such as
1174 CmmType GcPtrCat W32 on a 64-bit machine.
1175 -}
1176
1177 -- | A 'PrimRep' is an abstraction of a type. It contains information that
1178 -- the code generator needs in order to pass arguments, return results,
1179 -- and store values of this type.
1180 data PrimRep
1181 = VoidRep
1182 | PtrRep
1183 | IntRep -- ^ Signed, word-sized value
1184 | WordRep -- ^ Unsigned, word-sized value
1185 | Int64Rep -- ^ Signed, 64 bit value (with 32-bit words only)
1186 | Word64Rep -- ^ Unsigned, 64 bit value (with 32-bit words only)
1187 | AddrRep -- ^ A pointer, but /not/ to a Haskell value (use 'PtrRep')
1188 | FloatRep
1189 | DoubleRep
1190 | VecRep Int PrimElemRep -- ^ A vector
1191 deriving( Eq, Show )
1192
1193 data PrimElemRep
1194 = Int8ElemRep
1195 | Int16ElemRep
1196 | Int32ElemRep
1197 | Int64ElemRep
1198 | Word8ElemRep
1199 | Word16ElemRep
1200 | Word32ElemRep
1201 | Word64ElemRep
1202 | FloatElemRep
1203 | DoubleElemRep
1204 deriving( Eq, Show )
1205
1206 instance Outputable PrimRep where
1207 ppr r = text (show r)
1208
1209 instance Outputable PrimElemRep where
1210 ppr r = text (show r)
1211
1212 isVoidRep :: PrimRep -> Bool
1213 isVoidRep VoidRep = True
1214 isVoidRep _other = False
1215
1216 isGcPtrRep :: PrimRep -> Bool
1217 isGcPtrRep PtrRep = True
1218 isGcPtrRep _ = False
1219
1220 -- | Find the size of a 'PrimRep', in words
1221 primRepSizeW :: DynFlags -> PrimRep -> Int
1222 primRepSizeW _ IntRep = 1
1223 primRepSizeW _ WordRep = 1
1224 primRepSizeW dflags Int64Rep = wORD64_SIZE `quot` wORD_SIZE dflags
1225 primRepSizeW dflags Word64Rep = wORD64_SIZE `quot` wORD_SIZE dflags
1226 primRepSizeW _ FloatRep = 1 -- NB. might not take a full word
1227 primRepSizeW dflags DoubleRep = dOUBLE_SIZE dflags `quot` wORD_SIZE dflags
1228 primRepSizeW _ AddrRep = 1
1229 primRepSizeW _ PtrRep = 1
1230 primRepSizeW _ VoidRep = 0
1231 primRepSizeW dflags (VecRep len rep) = len * primElemRepSizeB rep `quot` wORD_SIZE dflags
1232
1233 primElemRepSizeB :: PrimElemRep -> Int
1234 primElemRepSizeB Int8ElemRep = 1
1235 primElemRepSizeB Int16ElemRep = 2
1236 primElemRepSizeB Int32ElemRep = 4
1237 primElemRepSizeB Int64ElemRep = 8
1238 primElemRepSizeB Word8ElemRep = 1
1239 primElemRepSizeB Word16ElemRep = 2
1240 primElemRepSizeB Word32ElemRep = 4
1241 primElemRepSizeB Word64ElemRep = 8
1242 primElemRepSizeB FloatElemRep = 4
1243 primElemRepSizeB DoubleElemRep = 8
1244
1245 -- | Return if Rep stands for floating type,
1246 -- returns Nothing for vector types.
1247 primRepIsFloat :: PrimRep -> Maybe Bool
1248 primRepIsFloat FloatRep = Just True
1249 primRepIsFloat DoubleRep = Just True
1250 primRepIsFloat (VecRep _ _) = Nothing
1251 primRepIsFloat _ = Just False
1252
1253
1254 {-
1255 ************************************************************************
1256 * *
1257 Field labels
1258 * *
1259 ************************************************************************
1260 -}
1261
1262 -- | The labels for the fields of this particular 'TyCon'
1263 tyConFieldLabels :: TyCon -> [FieldLabel]
1264 tyConFieldLabels tc = dFsEnvElts $ tyConFieldLabelEnv tc
1265
1266 -- | The labels for the fields of this particular 'TyCon'
1267 tyConFieldLabelEnv :: TyCon -> FieldLabelEnv
1268 tyConFieldLabelEnv tc
1269 | isAlgTyCon tc = algTcFields tc
1270 | otherwise = emptyDFsEnv
1271
1272
1273 -- | Make a map from strings to FieldLabels from all the data
1274 -- constructors of this algebraic tycon
1275 fieldsOfAlgTcRhs :: AlgTyConRhs -> FieldLabelEnv
1276 fieldsOfAlgTcRhs rhs = mkDFsEnv [ (flLabel fl, fl)
1277 | fl <- dataConsFields (visibleDataCons rhs) ]
1278 where
1279 -- Duplicates in this list will be removed by 'mkFsEnv'
1280 dataConsFields dcs = concatMap dataConFieldLabels dcs
1281
1282
1283 {-
1284 ************************************************************************
1285 * *
1286 \subsection{TyCon Construction}
1287 * *
1288 ************************************************************************
1289
1290 Note: the TyCon constructors all take a Kind as one argument, even though
1291 they could, in principle, work out their Kind from their other arguments.
1292 But to do so they need functions from Types, and that makes a nasty
1293 module mutual-recursion. And they aren't called from many places.
1294 So we compromise, and move their Kind calculation to the call site.
1295 -}
1296
1297 -- | Given the name of the function type constructor and it's kind, create the
1298 -- corresponding 'TyCon'. It is reccomended to use 'TyCoRep.funTyCon' if you want
1299 -- this functionality
1300 mkFunTyCon :: Name -> [TyConBinder] -> Name -> TyCon
1301 mkFunTyCon name binders rep_nm
1302 = FunTyCon {
1303 tyConUnique = nameUnique name,
1304 tyConName = name,
1305 tyConBinders = binders,
1306 tyConResKind = liftedTypeKind,
1307 tyConKind = mkTyConKind binders liftedTypeKind,
1308 tyConArity = 2,
1309 tcRepName = rep_nm
1310 }
1311
1312 -- | This is the making of an algebraic 'TyCon'. Notably, you have to
1313 -- pass in the generic (in the -XGenerics sense) information about the
1314 -- type constructor - you can get hold of it easily (see Generics
1315 -- module)
1316 mkAlgTyCon :: Name
1317 -> [TyConBinder] -- ^ Binders of the 'TyCon'
1318 -> Kind -- ^ Result kind
1319 -> [Role] -- ^ The roles for each TyVar
1320 -> Maybe CType -- ^ The C type this type corresponds to
1321 -- when using the CAPI FFI
1322 -> [PredType] -- ^ Stupid theta: see 'algTcStupidTheta'
1323 -> AlgTyConRhs -- ^ Information about data constructors
1324 -> AlgTyConFlav -- ^ What flavour is it?
1325 -- (e.g. vanilla, type family)
1326 -> Bool -- ^ Was the 'TyCon' declared with GADT syntax?
1327 -> TyCon
1328 mkAlgTyCon name binders res_kind roles cType stupid rhs parent gadt_syn
1329 = AlgTyCon {
1330 tyConName = name,
1331 tyConUnique = nameUnique name,
1332 tyConBinders = binders,
1333 tyConResKind = res_kind,
1334 tyConKind = mkTyConKind binders res_kind,
1335 tyConArity = length binders,
1336 tyConTyVars = binderVars binders,
1337 tcRoles = roles,
1338 tyConCType = cType,
1339 algTcStupidTheta = stupid,
1340 algTcRhs = rhs,
1341 algTcFields = fieldsOfAlgTcRhs rhs,
1342 algTcParent = ASSERT2( okParent name parent, ppr name $$ ppr parent ) parent,
1343 algTcGadtSyntax = gadt_syn
1344 }
1345
1346 -- | Simpler specialization of 'mkAlgTyCon' for classes
1347 mkClassTyCon :: Name -> [TyConBinder]
1348 -> [Role] -> AlgTyConRhs -> Class
1349 -> Name -> TyCon
1350 mkClassTyCon name binders roles rhs clas tc_rep_name
1351 = mkAlgTyCon name binders constraintKind roles Nothing [] rhs
1352 (ClassTyCon clas tc_rep_name)
1353 False
1354
1355 mkTupleTyCon :: Name
1356 -> [TyConBinder]
1357 -> Kind -- ^ Result kind of the 'TyCon'
1358 -> Arity -- ^ Arity of the tuple
1359 -> DataCon
1360 -> TupleSort -- ^ Whether the tuple is boxed or unboxed
1361 -> AlgTyConFlav
1362 -> TyCon
1363 mkTupleTyCon name binders res_kind arity con sort parent
1364 = AlgTyCon {
1365 tyConName = name,
1366 tyConUnique = nameUnique name,
1367 tyConBinders = binders,
1368 tyConResKind = res_kind,
1369 tyConKind = mkTyConKind binders res_kind,
1370 tyConArity = arity,
1371 tyConTyVars = binderVars binders,
1372 tcRoles = replicate arity Representational,
1373 tyConCType = Nothing,
1374 algTcStupidTheta = [],
1375 algTcRhs = TupleTyCon { data_con = con,
1376 tup_sort = sort },
1377 algTcFields = emptyDFsEnv,
1378 algTcParent = parent,
1379 algTcGadtSyntax = False
1380 }
1381
1382 -- | Makes a tycon suitable for use during type-checking.
1383 -- The only real need for this is for printing error messages during
1384 -- a recursive type/class type-checking knot. It has a kind because
1385 -- TcErrors sometimes calls typeKind.
1386 -- See also Note [Kind checking recursive type and class declarations]
1387 -- in TcTyClsDecls.
1388 mkTcTyCon :: Name
1389 -> [TyConBinder]
1390 -> Kind -- ^ /result/ kind only
1391 -> Bool -- ^ Can this be unsaturated?
1392 -> [TyVar] -- ^ Scoped type variables, see Note [TcTyCon]
1393 -> TyCon
1394 mkTcTyCon name binders res_kind unsat scoped_tvs
1395 = TcTyCon { tyConUnique = getUnique name
1396 , tyConName = name
1397 , tyConTyVars = binderVars binders
1398 , tyConBinders = binders
1399 , tyConResKind = res_kind
1400 , tyConKind = mkTyConKind binders res_kind
1401 , tyConUnsat = unsat
1402 , tyConArity = length binders
1403 , tcTyConScopedTyVars = scoped_tvs }
1404
1405 -- | Create an unlifted primitive 'TyCon', such as @Int#@
1406 mkPrimTyCon :: Name -> [TyConBinder]
1407 -> Kind -- ^ /result/ kind
1408 -> [Role] -> TyCon
1409 mkPrimTyCon name binders res_kind roles
1410 = mkPrimTyCon' name binders res_kind roles True (Just $ mkPrelTyConRepName name)
1411
1412 -- | Kind constructors
1413 mkKindTyCon :: Name -> [TyConBinder]
1414 -> Kind -- ^ /result/ kind
1415 -> [Role] -> Name -> TyCon
1416 mkKindTyCon name binders res_kind roles rep_nm
1417 = tc
1418 where
1419 tc = mkPrimTyCon' name binders res_kind roles False (Just rep_nm)
1420
1421 -- | Create a lifted primitive 'TyCon' such as @RealWorld@
1422 mkLiftedPrimTyCon :: Name -> [TyConBinder]
1423 -> Kind -- ^ /result/ kind
1424 -> [Role] -> TyCon
1425 mkLiftedPrimTyCon name binders res_kind roles
1426 = mkPrimTyCon' name binders res_kind roles False (Just rep_nm)
1427 where rep_nm = mkPrelTyConRepName name
1428
1429 mkPrimTyCon' :: Name -> [TyConBinder]
1430 -> Kind -- ^ /result/ kind
1431 -> [Role]
1432 -> Bool -> Maybe TyConRepName -> TyCon
1433 mkPrimTyCon' name binders res_kind roles is_unlifted rep_nm
1434 = PrimTyCon {
1435 tyConName = name,
1436 tyConUnique = nameUnique name,
1437 tyConBinders = binders,
1438 tyConResKind = res_kind,
1439 tyConKind = mkTyConKind binders res_kind,
1440 tyConArity = length roles,
1441 tcRoles = roles,
1442 isUnlifted = is_unlifted,
1443 primRepName = rep_nm
1444 }
1445
1446 -- | Create a type synonym 'TyCon'
1447 mkSynonymTyCon :: Name -> [TyConBinder] -> Kind -- ^ /result/ kind
1448 -> [Role] -> Type -> TyCon
1449 mkSynonymTyCon name binders res_kind roles rhs
1450 = SynonymTyCon {
1451 tyConName = name,
1452 tyConUnique = nameUnique name,
1453 tyConBinders = binders,
1454 tyConResKind = res_kind,
1455 tyConKind = mkTyConKind binders res_kind,
1456 tyConArity = length binders,
1457 tyConTyVars = binderVars binders,
1458 tcRoles = roles,
1459 synTcRhs = rhs
1460 }
1461
1462 -- | Create a type family 'TyCon'
1463 mkFamilyTyCon :: Name -> [TyConBinder] -> Kind -- ^ /result/ kind
1464 -> Maybe Name -> FamTyConFlav
1465 -> Maybe Class -> Injectivity -> TyCon
1466 mkFamilyTyCon name binders res_kind resVar flav parent inj
1467 = FamilyTyCon
1468 { tyConUnique = nameUnique name
1469 , tyConName = name
1470 , tyConBinders = binders
1471 , tyConResKind = res_kind
1472 , tyConKind = mkTyConKind binders res_kind
1473 , tyConArity = length binders
1474 , tyConTyVars = binderVars binders
1475 , famTcResVar = resVar
1476 , famTcFlav = flav
1477 , famTcParent = parent
1478 , famTcInj = inj
1479 }
1480
1481
1482 -- | Create a promoted data constructor 'TyCon'
1483 -- Somewhat dodgily, we give it the same Name
1484 -- as the data constructor itself; when we pretty-print
1485 -- the TyCon we add a quote; see the Outputable TyCon instance
1486 mkPromotedDataCon :: DataCon -> Name -> TyConRepName
1487 -> [TyConBinder] -> Kind -> [Role]
1488 -> RuntimeRepInfo -> TyCon
1489 mkPromotedDataCon con name rep_name binders res_kind roles rep_info
1490 = PromotedDataCon {
1491 tyConUnique = nameUnique name,
1492 tyConName = name,
1493 tyConArity = length roles,
1494 tcRoles = roles,
1495 tyConBinders = binders,
1496 tyConResKind = res_kind,
1497 tyConKind = mkTyConKind binders res_kind,
1498 dataCon = con,
1499 tcRepName = rep_name,
1500 promDcRepInfo = rep_info
1501 }
1502
1503 isFunTyCon :: TyCon -> Bool
1504 isFunTyCon (FunTyCon {}) = True
1505 isFunTyCon _ = False
1506
1507 -- | Test if the 'TyCon' is algebraic but abstract (invisible data constructors)
1508 isAbstractTyCon :: TyCon -> Bool
1509 isAbstractTyCon (AlgTyCon { algTcRhs = AbstractTyCon {} }) = True
1510 isAbstractTyCon _ = False
1511
1512 -- | Make an fake, abstract 'TyCon' from an existing one.
1513 -- Used when recovering from errors
1514 makeTyConAbstract :: TyCon -> TyCon
1515 makeTyConAbstract tc
1516 = mkTcTyCon (tyConName tc)
1517 (tyConBinders tc) (tyConResKind tc)
1518 (mightBeUnsaturatedTyCon tc) [{- no scoped vars -}]
1519
1520 -- | Does this 'TyCon' represent something that cannot be defined in Haskell?
1521 isPrimTyCon :: TyCon -> Bool
1522 isPrimTyCon (PrimTyCon {}) = True
1523 isPrimTyCon _ = False
1524
1525 -- | Is this 'TyCon' unlifted (i.e. cannot contain bottom)? Note that this can
1526 -- only be true for primitive and unboxed-tuple 'TyCon's
1527 isUnliftedTyCon :: TyCon -> Bool
1528 isUnliftedTyCon (PrimTyCon {isUnlifted = is_unlifted})
1529 = is_unlifted
1530 isUnliftedTyCon (AlgTyCon { algTcRhs = rhs } )
1531 | TupleTyCon { tup_sort = sort } <- rhs
1532 = not (isBoxed (tupleSortBoxity sort))
1533 isUnliftedTyCon _ = False
1534
1535 -- | Returns @True@ if the supplied 'TyCon' resulted from either a
1536 -- @data@ or @newtype@ declaration
1537 isAlgTyCon :: TyCon -> Bool
1538 isAlgTyCon (AlgTyCon {}) = True
1539 isAlgTyCon _ = False
1540
1541 -- | Returns @True@ for vanilla AlgTyCons -- that is, those created
1542 -- with a @data@ or @newtype@ declaration.
1543 isVanillaAlgTyCon :: TyCon -> Bool
1544 isVanillaAlgTyCon (AlgTyCon { algTcParent = VanillaAlgTyCon _ }) = True
1545 isVanillaAlgTyCon _ = False
1546
1547 isDataTyCon :: TyCon -> Bool
1548 -- ^ Returns @True@ for data types that are /definitely/ represented by
1549 -- heap-allocated constructors. These are scrutinised by Core-level
1550 -- @case@ expressions, and they get info tables allocated for them.
1551 --
1552 -- Generally, the function will be true for all @data@ types and false
1553 -- for @newtype@s, unboxed tuples and type family 'TyCon's. But it is
1554 -- not guaranteed to return @True@ in all cases that it could.
1555 --
1556 -- NB: for a data type family, only the /instance/ 'TyCon's
1557 -- get an info table. The family declaration 'TyCon' does not
1558 isDataTyCon (AlgTyCon {algTcRhs = rhs})
1559 = case rhs of
1560 TupleTyCon { tup_sort = sort }
1561 -> isBoxed (tupleSortBoxity sort)
1562 DataTyCon {} -> True
1563 NewTyCon {} -> False
1564 AbstractTyCon {} -> False -- We don't know, so return False
1565 isDataTyCon _ = False
1566
1567 -- | 'isInjectiveTyCon' is true of 'TyCon's for which this property holds
1568 -- (where X is the role passed in):
1569 -- If (T a1 b1 c1) ~X (T a2 b2 c2), then (a1 ~X1 a2), (b1 ~X2 b2), and (c1 ~X3 c2)
1570 -- (where X1, X2, and X3, are the roles given by tyConRolesX tc X)
1571 -- See also Note [Decomposing equality] in TcCanonical
1572 isInjectiveTyCon :: TyCon -> Role -> Bool
1573 isInjectiveTyCon _ Phantom = False
1574 isInjectiveTyCon (FunTyCon {}) _ = True
1575 isInjectiveTyCon (AlgTyCon {}) Nominal = True
1576 isInjectiveTyCon (AlgTyCon {algTcRhs = rhs}) Representational
1577 = isGenInjAlgRhs rhs
1578 isInjectiveTyCon (SynonymTyCon {}) _ = False
1579 isInjectiveTyCon (FamilyTyCon { famTcFlav = DataFamilyTyCon _ })
1580 Nominal = True
1581 isInjectiveTyCon (FamilyTyCon { famTcInj = Injective inj }) _ = and inj
1582 isInjectiveTyCon (FamilyTyCon {}) _ = False
1583 isInjectiveTyCon (PrimTyCon {}) _ = True
1584 isInjectiveTyCon (PromotedDataCon {}) _ = True
1585 isInjectiveTyCon tc@(TcTyCon {}) _
1586 = pprPanic "isInjectiveTyCon sees a TcTyCon" (ppr tc)
1587
1588 -- | 'isGenerativeTyCon' is true of 'TyCon's for which this property holds
1589 -- (where X is the role passed in):
1590 -- If (T tys ~X t), then (t's head ~X T).
1591 -- See also Note [Decomposing equality] in TcCanonical
1592 isGenerativeTyCon :: TyCon -> Role -> Bool
1593 isGenerativeTyCon (FamilyTyCon { famTcFlav = DataFamilyTyCon _ }) Nominal = True
1594 isGenerativeTyCon (FamilyTyCon {}) _ = False
1595 -- in all other cases, injectivity implies generativitiy
1596 isGenerativeTyCon tc r = isInjectiveTyCon tc r
1597
1598 -- | Is this an 'AlgTyConRhs' of a 'TyCon' that is generative and injective
1599 -- with respect to representational equality?
1600 isGenInjAlgRhs :: AlgTyConRhs -> Bool
1601 isGenInjAlgRhs (TupleTyCon {}) = True
1602 isGenInjAlgRhs (DataTyCon {}) = True
1603 isGenInjAlgRhs (AbstractTyCon distinct) = distinct
1604 isGenInjAlgRhs (NewTyCon {}) = False
1605
1606 -- | Is this 'TyCon' that for a @newtype@
1607 isNewTyCon :: TyCon -> Bool
1608 isNewTyCon (AlgTyCon {algTcRhs = NewTyCon {}}) = True
1609 isNewTyCon _ = False
1610
1611 -- | Take a 'TyCon' apart into the 'TyVar's it scopes over, the 'Type' it expands
1612 -- into, and (possibly) a coercion from the representation type to the @newtype@.
1613 -- Returns @Nothing@ if this is not possible.
1614 unwrapNewTyCon_maybe :: TyCon -> Maybe ([TyVar], Type, CoAxiom Unbranched)
1615 unwrapNewTyCon_maybe (AlgTyCon { tyConTyVars = tvs,
1616 algTcRhs = NewTyCon { nt_co = co,
1617 nt_rhs = rhs }})
1618 = Just (tvs, rhs, co)
1619 unwrapNewTyCon_maybe _ = Nothing
1620
1621 unwrapNewTyConEtad_maybe :: TyCon -> Maybe ([TyVar], Type, CoAxiom Unbranched)
1622 unwrapNewTyConEtad_maybe (AlgTyCon { algTcRhs = NewTyCon { nt_co = co,
1623 nt_etad_rhs = (tvs,rhs) }})
1624 = Just (tvs, rhs, co)
1625 unwrapNewTyConEtad_maybe _ = Nothing
1626
1627 isProductTyCon :: TyCon -> Bool
1628 -- True of datatypes or newtypes that have
1629 -- one, non-existential, data constructor
1630 -- See Note [Product types]
1631 isProductTyCon tc@(AlgTyCon {})
1632 = case algTcRhs tc of
1633 TupleTyCon {} -> True
1634 DataTyCon{ data_cons = [data_con] }
1635 -> null (dataConExTyVars data_con)
1636 NewTyCon {} -> True
1637 _ -> False
1638 isProductTyCon _ = False
1639
1640 isDataProductTyCon_maybe :: TyCon -> Maybe DataCon
1641 -- True of datatypes (not newtypes) with
1642 -- one, vanilla, data constructor
1643 -- See Note [Product types]
1644 isDataProductTyCon_maybe (AlgTyCon { algTcRhs = rhs })
1645 = case rhs of
1646 DataTyCon { data_cons = [con] }
1647 | null (dataConExTyVars con) -- non-existential
1648 -> Just con
1649 TupleTyCon { data_con = con }
1650 -> Just con
1651 _ -> Nothing
1652 isDataProductTyCon_maybe _ = Nothing
1653
1654 {- Note [Product types]
1655 ~~~~~~~~~~~~~~~~~~~~~~~
1656 A product type is
1657 * A data type (not a newtype)
1658 * With one, boxed data constructor
1659 * That binds no existential type variables
1660
1661 The main point is that product types are amenable to unboxing for
1662 * Strict function calls; we can transform
1663 f (D a b) = e
1664 to
1665 fw a b = e
1666 via the worker/wrapper transformation. (Question: couldn't this
1667 work for existentials too?)
1668
1669 * CPR for function results; we can transform
1670 f x y = let ... in D a b
1671 to
1672 fw x y = let ... in (# a, b #)
1673
1674 Note that the data constructor /can/ have evidence arguments: equality
1675 constraints, type classes etc. So it can be GADT. These evidence
1676 arguments are simply value arguments, and should not get in the way.
1677 -}
1678
1679
1680 -- | Is this a 'TyCon' representing a regular H98 type synonym (@type@)?
1681 isTypeSynonymTyCon :: TyCon -> Bool
1682 isTypeSynonymTyCon (SynonymTyCon {}) = True
1683 isTypeSynonymTyCon _ = False
1684
1685
1686 -- As for newtypes, it is in some contexts important to distinguish between
1687 -- closed synonyms and synonym families, as synonym families have no unique
1688 -- right hand side to which a synonym family application can expand.
1689 --
1690
1691 -- | True iff we can decompose (T a b c) into ((T a b) c)
1692 -- I.e. is it injective and generative w.r.t nominal equality?
1693 -- That is, if (T a b) ~N d e f, is it always the case that
1694 -- (T ~N d), (a ~N e) and (b ~N f)?
1695 -- Specifically NOT true of synonyms (open and otherwise)
1696 --
1697 -- It'd be unusual to call mightBeUnsaturatedTyCon on a regular H98
1698 -- type synonym, because you should probably have expanded it first
1699 -- But regardless, it's not decomposable
1700 mightBeUnsaturatedTyCon :: TyCon -> Bool
1701 mightBeUnsaturatedTyCon (SynonymTyCon {}) = False
1702 mightBeUnsaturatedTyCon (FamilyTyCon { famTcFlav = flav}) = isDataFamFlav flav
1703 mightBeUnsaturatedTyCon (TcTyCon { tyConUnsat = unsat }) = unsat
1704 mightBeUnsaturatedTyCon _other = True
1705
1706 -- | Is this an algebraic 'TyCon' declared with the GADT syntax?
1707 isGadtSyntaxTyCon :: TyCon -> Bool
1708 isGadtSyntaxTyCon (AlgTyCon { algTcGadtSyntax = res }) = res
1709 isGadtSyntaxTyCon _ = False
1710
1711 -- | Is this an algebraic 'TyCon' which is just an enumeration of values?
1712 isEnumerationTyCon :: TyCon -> Bool
1713 -- See Note [Enumeration types] in TyCon
1714 isEnumerationTyCon (AlgTyCon { tyConArity = arity, algTcRhs = rhs })
1715 = case rhs of
1716 DataTyCon { is_enum = res } -> res
1717 TupleTyCon {} -> arity == 0
1718 _ -> False
1719 isEnumerationTyCon _ = False
1720
1721 -- | Is this a 'TyCon', synonym or otherwise, that defines a family?
1722 isFamilyTyCon :: TyCon -> Bool
1723 isFamilyTyCon (FamilyTyCon {}) = True
1724 isFamilyTyCon _ = False
1725
1726 -- | Is this a 'TyCon', synonym or otherwise, that defines a family with
1727 -- instances?
1728 isOpenFamilyTyCon :: TyCon -> Bool
1729 isOpenFamilyTyCon (FamilyTyCon {famTcFlav = flav })
1730 | OpenSynFamilyTyCon <- flav = True
1731 | DataFamilyTyCon {} <- flav = True
1732 isOpenFamilyTyCon _ = False
1733
1734 -- | Is this a synonym 'TyCon' that can have may have further instances appear?
1735 isTypeFamilyTyCon :: TyCon -> Bool
1736 isTypeFamilyTyCon (FamilyTyCon { famTcFlav = flav }) = not (isDataFamFlav flav)
1737 isTypeFamilyTyCon _ = False
1738
1739 -- | Is this a synonym 'TyCon' that can have may have further instances appear?
1740 isDataFamilyTyCon :: TyCon -> Bool
1741 isDataFamilyTyCon (FamilyTyCon { famTcFlav = flav }) = isDataFamFlav flav
1742 isDataFamilyTyCon _ = False
1743
1744 -- | Is this an open type family TyCon?
1745 isOpenTypeFamilyTyCon :: TyCon -> Bool
1746 isOpenTypeFamilyTyCon (FamilyTyCon {famTcFlav = OpenSynFamilyTyCon }) = True
1747 isOpenTypeFamilyTyCon _ = False
1748
1749 -- | Is this a non-empty closed type family? Returns 'Nothing' for
1750 -- abstract or empty closed families.
1751 isClosedSynFamilyTyConWithAxiom_maybe :: TyCon -> Maybe (CoAxiom Branched)
1752 isClosedSynFamilyTyConWithAxiom_maybe
1753 (FamilyTyCon {famTcFlav = ClosedSynFamilyTyCon mb}) = mb
1754 isClosedSynFamilyTyConWithAxiom_maybe _ = Nothing
1755
1756 -- | Try to read the injectivity information from a FamilyTyCon.
1757 -- For every other TyCon this function panics.
1758 familyTyConInjectivityInfo :: TyCon -> Injectivity
1759 familyTyConInjectivityInfo (FamilyTyCon { famTcInj = inj }) = inj
1760 familyTyConInjectivityInfo _ = panic "familyTyConInjectivityInfo"
1761
1762 isBuiltInSynFamTyCon_maybe :: TyCon -> Maybe BuiltInSynFamily
1763 isBuiltInSynFamTyCon_maybe
1764 (FamilyTyCon {famTcFlav = BuiltInSynFamTyCon ops }) = Just ops
1765 isBuiltInSynFamTyCon_maybe _ = Nothing
1766
1767 isDataFamFlav :: FamTyConFlav -> Bool
1768 isDataFamFlav (DataFamilyTyCon {}) = True -- Data family
1769 isDataFamFlav _ = False -- Type synonym family
1770
1771 -- | Are we able to extract information 'TyVar' to class argument list
1772 -- mapping from a given 'TyCon'?
1773 isTyConAssoc :: TyCon -> Bool
1774 isTyConAssoc tc = isJust (tyConAssoc_maybe tc)
1775
1776 tyConAssoc_maybe :: TyCon -> Maybe Class
1777 tyConAssoc_maybe (FamilyTyCon { famTcParent = mb_cls }) = mb_cls
1778 tyConAssoc_maybe _ = Nothing
1779
1780 -- The unit tycon didn't used to be classed as a tuple tycon
1781 -- but I thought that was silly so I've undone it
1782 -- If it can't be for some reason, it should be a AlgTyCon
1783 isTupleTyCon :: TyCon -> Bool
1784 -- ^ Does this 'TyCon' represent a tuple?
1785 --
1786 -- NB: when compiling @Data.Tuple@, the tycons won't reply @True@ to
1787 -- 'isTupleTyCon', because they are built as 'AlgTyCons'. However they
1788 -- get spat into the interface file as tuple tycons, so I don't think
1789 -- it matters.
1790 isTupleTyCon (AlgTyCon { algTcRhs = TupleTyCon {} }) = True
1791 isTupleTyCon _ = False
1792
1793 tyConTuple_maybe :: TyCon -> Maybe TupleSort
1794 tyConTuple_maybe (AlgTyCon { algTcRhs = rhs })
1795 | TupleTyCon { tup_sort = sort} <- rhs = Just sort
1796 tyConTuple_maybe _ = Nothing
1797
1798 -- | Is this the 'TyCon' for an unboxed tuple?
1799 isUnboxedTupleTyCon :: TyCon -> Bool
1800 isUnboxedTupleTyCon (AlgTyCon { algTcRhs = rhs })
1801 | TupleTyCon { tup_sort = sort } <- rhs
1802 = not (isBoxed (tupleSortBoxity sort))
1803 isUnboxedTupleTyCon _ = False
1804
1805 -- | Is this the 'TyCon' for a boxed tuple?
1806 isBoxedTupleTyCon :: TyCon -> Bool
1807 isBoxedTupleTyCon (AlgTyCon { algTcRhs = rhs })
1808 | TupleTyCon { tup_sort = sort } <- rhs
1809 = isBoxed (tupleSortBoxity sort)
1810 isBoxedTupleTyCon _ = False
1811
1812 -- | Is this a PromotedDataCon?
1813 isPromotedDataCon :: TyCon -> Bool
1814 isPromotedDataCon (PromotedDataCon {}) = True
1815 isPromotedDataCon _ = False
1816
1817 -- | Retrieves the promoted DataCon if this is a PromotedDataCon;
1818 isPromotedDataCon_maybe :: TyCon -> Maybe DataCon
1819 isPromotedDataCon_maybe (PromotedDataCon { dataCon = dc }) = Just dc
1820 isPromotedDataCon_maybe _ = Nothing
1821
1822 -- | Is this tycon really meant for use at the kind level? That is,
1823 -- should it be permitted without -XDataKinds?
1824 isKindTyCon :: TyCon -> Bool
1825 isKindTyCon tc = getUnique tc `elementOfUniqSet` kindTyConKeys
1826
1827 -- | These TyCons should be allowed at the kind level, even without
1828 -- -XDataKinds.
1829 kindTyConKeys :: UniqSet Unique
1830 kindTyConKeys = unionManyUniqSets
1831 ( mkUniqSet [ liftedTypeKindTyConKey, starKindTyConKey, unicodeStarKindTyConKey
1832 , constraintKindTyConKey, tYPETyConKey ]
1833 : map (mkUniqSet . tycon_with_datacons) [ runtimeRepTyCon
1834 , vecCountTyCon, vecElemTyCon ] )
1835 where
1836 tycon_with_datacons tc = getUnique tc : map getUnique (tyConDataCons tc)
1837
1838 isLiftedTypeKindTyConName :: Name -> Bool
1839 isLiftedTypeKindTyConName
1840 = (`hasKey` liftedTypeKindTyConKey) <||>
1841 (`hasKey` starKindTyConKey) <||>
1842 (`hasKey` unicodeStarKindTyConKey)
1843
1844 -- | Identifies implicit tycons that, in particular, do not go into interface
1845 -- files (because they are implicitly reconstructed when the interface is
1846 -- read).
1847 --
1848 -- Note that:
1849 --
1850 -- * Associated families are implicit, as they are re-constructed from
1851 -- the class declaration in which they reside, and
1852 --
1853 -- * Family instances are /not/ implicit as they represent the instance body
1854 -- (similar to a @dfun@ does that for a class instance).
1855 --
1856 -- * Tuples are implicit iff they have a wired-in name
1857 -- (namely: boxed and unboxed tupeles are wired-in and implicit,
1858 -- but constraint tuples are not)
1859 isImplicitTyCon :: TyCon -> Bool
1860 isImplicitTyCon (FunTyCon {}) = True
1861 isImplicitTyCon (PrimTyCon {}) = True
1862 isImplicitTyCon (PromotedDataCon {}) = True
1863 isImplicitTyCon (AlgTyCon { algTcRhs = rhs, tyConName = name })
1864 | TupleTyCon {} <- rhs = isWiredInName name
1865 | otherwise = False
1866 isImplicitTyCon (FamilyTyCon { famTcParent = parent }) = isJust parent
1867 isImplicitTyCon (SynonymTyCon {}) = False
1868 isImplicitTyCon tc@(TcTyCon {})
1869 = pprPanic "isImplicitTyCon sees a TcTyCon" (ppr tc)
1870
1871 tyConCType_maybe :: TyCon -> Maybe CType
1872 tyConCType_maybe tc@(AlgTyCon {}) = tyConCType tc
1873 tyConCType_maybe _ = Nothing
1874
1875 -- | Is this a TcTyCon? (That is, one only used during type-checking?)
1876 isTcTyCon :: TyCon -> Bool
1877 isTcTyCon (TcTyCon {}) = True
1878 isTcTyCon _ = False
1879
1880 {-
1881 -----------------------------------------------
1882 -- Expand type-constructor applications
1883 -----------------------------------------------
1884 -}
1885
1886 expandSynTyCon_maybe
1887 :: TyCon
1888 -> [tyco] -- ^ Arguments to 'TyCon'
1889 -> Maybe ([(TyVar,tyco)],
1890 Type,
1891 [tyco]) -- ^ Returns a 'TyVar' substitution, the body
1892 -- type of the synonym (not yet substituted)
1893 -- and any arguments remaining from the
1894 -- application
1895
1896 -- ^ Expand a type synonym application, if any
1897 expandSynTyCon_maybe tc tys
1898 | SynonymTyCon { tyConTyVars = tvs, synTcRhs = rhs, tyConArity = arity } <- tc
1899 = case arity `compare` length tys of
1900 LT -> Just (tvs `zip` tys, rhs, drop arity tys)
1901 EQ -> Just (tvs `zip` tys, rhs, [])
1902 GT -> Nothing
1903 | otherwise
1904 = Nothing
1905
1906 ----------------
1907
1908 -- | Check if the tycon actually refers to a proper `data` or `newtype`
1909 -- with user defined constructors rather than one from a class or other
1910 -- construction.
1911 isTyConWithSrcDataCons :: TyCon -> Bool
1912 isTyConWithSrcDataCons (AlgTyCon { algTcRhs = rhs, algTcParent = parent }) =
1913 case rhs of
1914 DataTyCon {} -> isSrcParent
1915 NewTyCon {} -> isSrcParent
1916 TupleTyCon {} -> isSrcParent
1917 _ -> False
1918 where
1919 isSrcParent = isNoParent parent
1920 isTyConWithSrcDataCons _ = False
1921
1922
1923 -- | As 'tyConDataCons_maybe', but returns the empty list of constructors if no
1924 -- constructors could be found
1925 tyConDataCons :: TyCon -> [DataCon]
1926 -- It's convenient for tyConDataCons to return the
1927 -- empty list for type synonyms etc
1928 tyConDataCons tycon = tyConDataCons_maybe tycon `orElse` []
1929
1930 -- | Determine the 'DataCon's originating from the given 'TyCon', if the 'TyCon'
1931 -- is the sort that can have any constructors (note: this does not include
1932 -- abstract algebraic types)
1933 tyConDataCons_maybe :: TyCon -> Maybe [DataCon]
1934 tyConDataCons_maybe (AlgTyCon {algTcRhs = rhs})
1935 = case rhs of
1936 DataTyCon { data_cons = cons } -> Just cons
1937 NewTyCon { data_con = con } -> Just [con]
1938 TupleTyCon { data_con = con } -> Just [con]
1939 _ -> Nothing
1940 tyConDataCons_maybe _ = Nothing
1941
1942 -- | If the given 'TyCon' has a /single/ data constructor, i.e. it is a @data@
1943 -- type with one alternative, a tuple type or a @newtype@ then that constructor
1944 -- is returned. If the 'TyCon' has more than one constructor, or represents a
1945 -- primitive or function type constructor then @Nothing@ is returned. In any
1946 -- other case, the function panics
1947 tyConSingleDataCon_maybe :: TyCon -> Maybe DataCon
1948 tyConSingleDataCon_maybe (AlgTyCon { algTcRhs = rhs })
1949 = case rhs of
1950 DataTyCon { data_cons = [c] } -> Just c
1951 TupleTyCon { data_con = c } -> Just c
1952 NewTyCon { data_con = c } -> Just c
1953 _ -> Nothing
1954 tyConSingleDataCon_maybe _ = Nothing
1955
1956 tyConSingleDataCon :: TyCon -> DataCon
1957 tyConSingleDataCon tc
1958 = case tyConSingleDataCon_maybe tc of
1959 Just c -> c
1960 Nothing -> pprPanic "tyConDataCon" (ppr tc)
1961
1962 tyConSingleAlgDataCon_maybe :: TyCon -> Maybe DataCon
1963 -- Returns (Just con) for single-constructor
1964 -- *algebraic* data types *not* newtypes
1965 tyConSingleAlgDataCon_maybe (AlgTyCon { algTcRhs = rhs })
1966 = case rhs of
1967 DataTyCon { data_cons = [c] } -> Just c
1968 TupleTyCon { data_con = c } -> Just c
1969 _ -> Nothing
1970 tyConSingleAlgDataCon_maybe _ = Nothing
1971
1972 -- | Determine the number of value constructors a 'TyCon' has. Panics if the
1973 -- 'TyCon' is not algebraic or a tuple
1974 tyConFamilySize :: TyCon -> Int
1975 tyConFamilySize tc@(AlgTyCon { algTcRhs = rhs })
1976 = case rhs of
1977 DataTyCon { data_cons = cons } -> length cons
1978 NewTyCon {} -> 1
1979 TupleTyCon {} -> 1
1980 _ -> pprPanic "tyConFamilySize 1" (ppr tc)
1981 tyConFamilySize tc = pprPanic "tyConFamilySize 2" (ppr tc)
1982
1983 -- | Extract an 'AlgTyConRhs' with information about data constructors from an
1984 -- algebraic or tuple 'TyCon'. Panics for any other sort of 'TyCon'
1985 algTyConRhs :: TyCon -> AlgTyConRhs
1986 algTyConRhs (AlgTyCon {algTcRhs = rhs}) = rhs
1987 algTyConRhs other = pprPanic "algTyConRhs" (ppr other)
1988
1989 -- | Extract type variable naming the result of injective type family
1990 tyConFamilyResVar_maybe :: TyCon -> Maybe Name
1991 tyConFamilyResVar_maybe (FamilyTyCon {famTcResVar = res}) = res
1992 tyConFamilyResVar_maybe _ = Nothing
1993
1994 -- | Get the list of roles for the type parameters of a TyCon
1995 tyConRoles :: TyCon -> [Role]
1996 -- See also Note [TyCon Role signatures]
1997 tyConRoles tc
1998 = case tc of
1999 { FunTyCon {} -> const_role Representational
2000 ; AlgTyCon { tcRoles = roles } -> roles
2001 ; SynonymTyCon { tcRoles = roles } -> roles
2002 ; FamilyTyCon {} -> const_role Nominal
2003 ; PrimTyCon { tcRoles = roles } -> roles
2004 ; PromotedDataCon { tcRoles = roles } -> roles
2005 ; TcTyCon {} -> pprPanic "tyConRoles sees a TcTyCon" (ppr tc)
2006 }
2007 where
2008 const_role r = replicate (tyConArity tc) r
2009
2010 -- | Extract the bound type variables and type expansion of a type synonym
2011 -- 'TyCon'. Panics if the 'TyCon' is not a synonym
2012 newTyConRhs :: TyCon -> ([TyVar], Type)
2013 newTyConRhs (AlgTyCon {tyConTyVars = tvs, algTcRhs = NewTyCon { nt_rhs = rhs }})
2014 = (tvs, rhs)
2015 newTyConRhs tycon = pprPanic "newTyConRhs" (ppr tycon)
2016
2017 -- | The number of type parameters that need to be passed to a newtype to
2018 -- resolve it. May be less than in the definition if it can be eta-contracted.
2019 newTyConEtadArity :: TyCon -> Int
2020 newTyConEtadArity (AlgTyCon {algTcRhs = NewTyCon { nt_etad_rhs = tvs_rhs }})
2021 = length (fst tvs_rhs)
2022 newTyConEtadArity tycon = pprPanic "newTyConEtadArity" (ppr tycon)
2023
2024 -- | Extract the bound type variables and type expansion of an eta-contracted
2025 -- type synonym 'TyCon'. Panics if the 'TyCon' is not a synonym
2026 newTyConEtadRhs :: TyCon -> ([TyVar], Type)
2027 newTyConEtadRhs (AlgTyCon {algTcRhs = NewTyCon { nt_etad_rhs = tvs_rhs }}) = tvs_rhs
2028 newTyConEtadRhs tycon = pprPanic "newTyConEtadRhs" (ppr tycon)
2029
2030 -- | Extracts the @newtype@ coercion from such a 'TyCon', which can be used to
2031 -- construct something with the @newtype@s type from its representation type
2032 -- (right hand side). If the supplied 'TyCon' is not a @newtype@, returns
2033 -- @Nothing@
2034 newTyConCo_maybe :: TyCon -> Maybe (CoAxiom Unbranched)
2035 newTyConCo_maybe (AlgTyCon {algTcRhs = NewTyCon { nt_co = co }}) = Just co
2036 newTyConCo_maybe _ = Nothing
2037
2038 newTyConCo :: TyCon -> CoAxiom Unbranched
2039 newTyConCo tc = case newTyConCo_maybe tc of
2040 Just co -> co
2041 Nothing -> pprPanic "newTyConCo" (ppr tc)
2042
2043 newTyConDataCon_maybe :: TyCon -> Maybe DataCon
2044 newTyConDataCon_maybe (AlgTyCon {algTcRhs = NewTyCon { data_con = con }}) = Just con
2045 newTyConDataCon_maybe _ = Nothing
2046
2047 -- | Find the \"stupid theta\" of the 'TyCon'. A \"stupid theta\" is the context
2048 -- to the left of an algebraic type declaration, e.g. @Eq a@ in the declaration
2049 -- @data Eq a => T a ...@
2050 tyConStupidTheta :: TyCon -> [PredType]
2051 tyConStupidTheta (AlgTyCon {algTcStupidTheta = stupid}) = stupid
2052 tyConStupidTheta tycon = pprPanic "tyConStupidTheta" (ppr tycon)
2053
2054 -- | Extract the 'TyVar's bound by a vanilla type synonym
2055 -- and the corresponding (unsubstituted) right hand side.
2056 synTyConDefn_maybe :: TyCon -> Maybe ([TyVar], Type)
2057 synTyConDefn_maybe (SynonymTyCon {tyConTyVars = tyvars, synTcRhs = ty})
2058 = Just (tyvars, ty)
2059 synTyConDefn_maybe _ = Nothing
2060
2061 -- | Extract the information pertaining to the right hand side of a type synonym
2062 -- (@type@) declaration.
2063 synTyConRhs_maybe :: TyCon -> Maybe Type
2064 synTyConRhs_maybe (SynonymTyCon {synTcRhs = rhs}) = Just rhs
2065 synTyConRhs_maybe _ = Nothing
2066
2067 -- | Extract the flavour of a type family (with all the extra information that
2068 -- it carries)
2069 famTyConFlav_maybe :: TyCon -> Maybe FamTyConFlav
2070 famTyConFlav_maybe (FamilyTyCon {famTcFlav = flav}) = Just flav
2071 famTyConFlav_maybe _ = Nothing
2072
2073 -- | Is this 'TyCon' that for a class instance?
2074 isClassTyCon :: TyCon -> Bool
2075 isClassTyCon (AlgTyCon {algTcParent = ClassTyCon {}}) = True
2076 isClassTyCon _ = False
2077
2078 -- | If this 'TyCon' is that for a class instance, return the class it is for.
2079 -- Otherwise returns @Nothing@
2080 tyConClass_maybe :: TyCon -> Maybe Class
2081 tyConClass_maybe (AlgTyCon {algTcParent = ClassTyCon clas _}) = Just clas
2082 tyConClass_maybe _ = Nothing
2083
2084 -- | Return the associated types of the 'TyCon', if any
2085 tyConATs :: TyCon -> [TyCon]
2086 tyConATs (AlgTyCon {algTcParent = ClassTyCon clas _}) = classATs clas
2087 tyConATs _ = []
2088
2089 ----------------------------------------------------------------------------
2090 -- | Is this 'TyCon' that for a data family instance?
2091 isFamInstTyCon :: TyCon -> Bool
2092 isFamInstTyCon (AlgTyCon {algTcParent = DataFamInstTyCon {} })
2093 = True
2094 isFamInstTyCon _ = False
2095
2096 tyConFamInstSig_maybe :: TyCon -> Maybe (TyCon, [Type], CoAxiom Unbranched)
2097 tyConFamInstSig_maybe (AlgTyCon {algTcParent = DataFamInstTyCon ax f ts })
2098 = Just (f, ts, ax)
2099 tyConFamInstSig_maybe _ = Nothing
2100
2101 -- | If this 'TyCon' is that of a data family instance, return the family in question
2102 -- and the instance types. Otherwise, return @Nothing@
2103 tyConFamInst_maybe :: TyCon -> Maybe (TyCon, [Type])
2104 tyConFamInst_maybe (AlgTyCon {algTcParent = DataFamInstTyCon _ f ts })
2105 = Just (f, ts)
2106 tyConFamInst_maybe _ = Nothing
2107
2108 -- | If this 'TyCon' is that of a data family instance, return a 'TyCon' which
2109 -- represents a coercion identifying the representation type with the type
2110 -- instance family. Otherwise, return @Nothing@
2111 tyConFamilyCoercion_maybe :: TyCon -> Maybe (CoAxiom Unbranched)
2112 tyConFamilyCoercion_maybe (AlgTyCon {algTcParent = DataFamInstTyCon ax _ _ })
2113 = Just ax
2114 tyConFamilyCoercion_maybe _ = Nothing
2115
2116 -- | Extract any 'RuntimeRepInfo' from this TyCon
2117 tyConRuntimeRepInfo :: TyCon -> RuntimeRepInfo
2118 tyConRuntimeRepInfo (PromotedDataCon { promDcRepInfo = rri }) = rri
2119 tyConRuntimeRepInfo _ = NoRRI
2120 -- could panic in that second case. But Douglas Adams told me not to.
2121
2122 {-
2123 ************************************************************************
2124 * *
2125 \subsection[TyCon-instances]{Instance declarations for @TyCon@}
2126 * *
2127 ************************************************************************
2128
2129 @TyCon@s are compared by comparing their @Unique@s.
2130 -}
2131
2132 instance Eq TyCon where
2133 a == b = getUnique a == getUnique b
2134 a /= b = getUnique a /= getUnique b
2135
2136 instance Uniquable TyCon where
2137 getUnique tc = tyConUnique tc
2138
2139 instance Outputable TyCon where
2140 -- At the moment a promoted TyCon has the same Name as its
2141 -- corresponding TyCon, so we add the quote to distinguish it here
2142 ppr tc = pprPromotionQuote tc <> ppr (tyConName tc)
2143
2144 tyConFlavour :: TyCon -> String
2145 tyConFlavour (AlgTyCon { algTcParent = parent, algTcRhs = rhs })
2146 | ClassTyCon _ _ <- parent = "class"
2147 | otherwise = case rhs of
2148 TupleTyCon { tup_sort = sort }
2149 | isBoxed (tupleSortBoxity sort) -> "tuple"
2150 | otherwise -> "unboxed tuple"
2151 DataTyCon {} -> "data type"
2152 NewTyCon {} -> "newtype"
2153 AbstractTyCon {} -> "abstract type"
2154 tyConFlavour (FamilyTyCon { famTcFlav = flav })
2155 | isDataFamFlav flav = "data family"
2156 | otherwise = "type family"
2157 tyConFlavour (SynonymTyCon {}) = "type synonym"
2158 tyConFlavour (FunTyCon {}) = "built-in type"
2159 tyConFlavour (PrimTyCon {}) = "built-in type"
2160 tyConFlavour (PromotedDataCon {}) = "promoted data constructor"
2161 tyConFlavour tc@(TcTyCon {})
2162 = pprPanic "tyConFlavour sees a TcTyCon" (ppr tc)
2163
2164 pprPromotionQuote :: TyCon -> SDoc
2165 -- Promoted data constructors already have a tick in their OccName
2166 pprPromotionQuote tc
2167 = case tc of
2168 PromotedDataCon {} -> char '\'' -- Always quote promoted DataCons in types
2169 _ -> empty
2170
2171 instance NamedThing TyCon where
2172 getName = tyConName
2173
2174 instance Data.Data TyCon where
2175 -- don't traverse?
2176 toConstr _ = abstractConstr "TyCon"
2177 gunfold _ _ = error "gunfold"
2178 dataTypeOf _ = mkNoRepType "TyCon"
2179
2180 instance Binary Injectivity where
2181 put_ bh NotInjective = putByte bh 0
2182 put_ bh (Injective xs) = putByte bh 1 >> put_ bh xs
2183
2184 get bh = do { h <- getByte bh
2185 ; case h of
2186 0 -> return NotInjective
2187 _ -> do { xs <- get bh
2188 ; return (Injective xs) } }
2189
2190 {-
2191 ************************************************************************
2192 * *
2193 Walking over recursive TyCons
2194 * *
2195 ************************************************************************
2196
2197 Note [Expanding newtypes and products]
2198 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2199 When expanding a type to expose a data-type constructor, we need to be
2200 careful about newtypes, lest we fall into an infinite loop. Here are
2201 the key examples:
2202
2203 newtype Id x = MkId x
2204 newtype Fix f = MkFix (f (Fix f))
2205 newtype T = MkT (T -> T)
2206
2207 Type Expansion
2208 --------------------------
2209 T T -> T
2210 Fix Maybe Maybe (Fix Maybe)
2211 Id (Id Int) Int
2212 Fix Id NO NO NO
2213
2214 Notice that
2215 * We can expand T, even though it's recursive.
2216 * We can expand Id (Id Int), even though the Id shows up
2217 twice at the outer level, because Id is non-recursive
2218
2219 So, when expanding, we keep track of when we've seen a recursive
2220 newtype at outermost level; and bale out if we see it again.
2221
2222 We sometimes want to do the same for product types, so that the
2223 strictness analyser doesn't unbox infinitely deeply.
2224
2225 More precisely, we keep a *count* of how many times we've seen it.
2226 This is to account for
2227 data instance T (a,b) = MkT (T a) (T b)
2228 Then (Trac #10482) if we have a type like
2229 T (Int,(Int,(Int,(Int,Int))))
2230 we can still unbox deeply enough during strictness analysis.
2231 We have to treat T as potentially recursive, but it's still
2232 good to be able to unwrap multiple layers.
2233
2234 The function that manages all this is checkRecTc.
2235 -}
2236
2237 data RecTcChecker = RC !Int (NameEnv Int)
2238 -- The upper bound, and the number of times
2239 -- we have encountered each TyCon
2240
2241 initRecTc :: RecTcChecker
2242 -- Intialise with a fixed max bound of 100
2243 -- We should probably have a flag for this
2244 initRecTc = RC 100 emptyNameEnv
2245
2246 checkRecTc :: RecTcChecker -> TyCon -> Maybe RecTcChecker
2247 -- Nothing => Recursion detected
2248 -- Just rec_tcs => Keep going
2249 checkRecTc (RC bound rec_nts) tc
2250 = case lookupNameEnv rec_nts tc_name of
2251 Just n | n >= bound -> Nothing
2252 | otherwise -> Just (RC bound (extendNameEnv rec_nts tc_name (n+1)))
2253 Nothing -> Just (RC bound (extendNameEnv rec_nts tc_name 1))
2254 where
2255 tc_name = tyConName tc