Major patch to introduce TyConBinder
[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 tyConBinderVisibility, 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 isRecursiveTyCon,
64 isImplicitTyCon,
65 isTyConWithSrcDataCons,
66 isTcTyCon,
67
68 -- ** Extracting information out of TyCons
69 tyConName,
70 tyConKind,
71 tyConUnique,
72 tyConTyVars,
73 tyConCType, tyConCType_maybe,
74 tyConDataCons, tyConDataCons_maybe,
75 tyConSingleDataCon_maybe, tyConSingleDataCon,
76 tyConSingleAlgDataCon_maybe,
77 tyConFamilySize,
78 tyConStupidTheta,
79 tyConArity,
80 tyConRoles,
81 tyConFlavour,
82 tyConTuple_maybe, tyConClass_maybe, tyConATs,
83 tyConFamInst_maybe, tyConFamInstSig_maybe, tyConFamilyCoercion_maybe,
84 tyConFamilyResVar_maybe,
85 synTyConDefn_maybe, synTyConRhs_maybe,
86 famTyConFlav_maybe, famTcResVar,
87 algTyConRhs,
88 newTyConRhs, newTyConEtadArity, newTyConEtadRhs,
89 unwrapNewTyCon_maybe, unwrapNewTyConEtad_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 contructor 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 VisibilityFlag
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 :: VisibilityFlag -> TyVar -> TyConBinder
388 -- The odd argument order supports currying
389 mkNamedTyConBinder vis tv = TvBndr tv (NamedTCB vis)
390
391 mkNamedTyConBinders :: VisibilityFlag -> [TyVar] -> [TyConBinder]
392 -- The odd argument order supports currying
393 mkNamedTyConBinders vis tvs = map (mkNamedTyConBinder vis) tvs
394
395 tyConBinderVisibility :: TyConBinder -> VisibilityFlag
396 tyConBinderVisibility (TvBndr _ (NamedTCB vis)) = vis
397 tyConBinderVisibility (TvBndr _ AnonTCB) = Visible
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)) = isVisible 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 Invisible)
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 VisibilityFlags] in TyConRep 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 Visible)) = ppr v
471 ppr (TvBndr v (NamedTCB Specified)) = char '@' <> ppr v
472 ppr (TvBndr v (NamedTCB Invisible)) = 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 algTcRec :: RecFlag, -- ^ Tells us whether the data type is part
593 -- of a mutually-recursive group or not
594
595 algTcParent :: AlgTyConFlav -- ^ Gives the class or family declaration
596 -- 'TyCon' for derived 'TyCon's representing
597 -- class or family instances, respectively.
598
599 }
600
601 -- | Represents type synonyms
602 | SynonymTyCon {
603 tyConUnique :: Unique, -- ^ A Unique of this TyCon. Invariant:
604 -- identical to Unique of Name stored in
605 -- tyConName field.
606
607 tyConName :: Name, -- ^ Name of the constructor
608
609 -- See Note [The binders/kind/arity fields of a TyCon]
610 tyConBinders :: [TyConBinder], -- ^ Full binders
611 tyConTyVars :: [TyVar], -- ^ TyVar binders
612 tyConResKind :: Kind, -- ^ Result kind
613 tyConKind :: Kind, -- ^ Kind of this TyCon
614 tyConArity :: Arity, -- ^ Arity
615 -- tyConTyVars scope over: synTcRhs
616
617 tcRoles :: [Role], -- ^ The role for each type variable
618 -- This list has length = tyConArity
619 -- See also Note [TyCon Role signatures]
620
621 synTcRhs :: Type -- ^ Contains information about the expansion
622 -- of the synonym
623 }
624
625 -- | Represents families (both type and data)
626 -- Argument roles are all Nominal
627 | FamilyTyCon {
628 tyConUnique :: Unique, -- ^ A Unique of this TyCon. Invariant:
629 -- identical to Unique of Name stored in
630 -- tyConName field.
631
632 tyConName :: Name, -- ^ Name of the constructor
633
634 -- See Note [The binders/kind/arity fields of a TyCon]
635 tyConBinders :: [TyConBinder], -- ^ Full binders
636 tyConTyVars :: [TyVar], -- ^ TyVar binders
637 tyConResKind :: Kind, -- ^ Result kind
638 tyConKind :: Kind, -- ^ Kind of this TyCon
639 tyConArity :: Arity, -- ^ Arity
640 -- tyConTyVars connect an associated family TyCon
641 -- with its parent class; see TcValidity.checkConsistentFamInst
642
643 famTcResVar :: Maybe Name, -- ^ Name of result type variable, used
644 -- for pretty-printing with --show-iface
645 -- and for reifying TyCon in Template
646 -- Haskell
647
648 famTcFlav :: FamTyConFlav, -- ^ Type family flavour: open, closed,
649 -- abstract, built-in. See comments for
650 -- FamTyConFlav
651
652 famTcParent :: Maybe Class, -- ^ For *associated* type/data families
653 -- The class in whose declaration the family is declared
654 -- See Note [Associated families and their parent class]
655
656 famTcInj :: Injectivity -- ^ is this a type family injective in
657 -- its type variables? Nothing if no
658 -- injectivity annotation was given
659 }
660
661 -- | Primitive types; cannot be defined in Haskell. This includes
662 -- the usual suspects (such as @Int#@) as well as foreign-imported
663 -- types and kinds (@*@, @#@, and @?@)
664 | PrimTyCon {
665 tyConUnique :: Unique, -- ^ A Unique of this TyCon. Invariant:
666 -- identical to Unique of Name stored in
667 -- tyConName field.
668
669 tyConName :: Name, -- ^ Name of the constructor
670
671 -- See Note [The binders/kind/arity fields of a TyCon]
672 tyConBinders :: [TyConBinder], -- ^ Full binders
673 tyConResKind :: Kind, -- ^ Result kind
674 tyConKind :: Kind, -- ^ Kind of this TyCon
675 tyConArity :: Arity, -- ^ Arity
676
677 tcRoles :: [Role], -- ^ The role for each type variable
678 -- This list has length = tyConArity
679 -- See also Note [TyCon Role signatures]
680
681 isUnlifted :: Bool, -- ^ Most primitive tycons are unlifted (may
682 -- not contain bottom) but other are lifted,
683 -- e.g. @RealWorld@
684 -- Only relevant if tyConKind = *
685
686 primRepName :: Maybe TyConRepName -- Only relevant for kind TyCons
687 -- i.e, *, #, ?
688 }
689
690 -- | Represents promoted data constructor.
691 | PromotedDataCon { -- See Note [Promoted data constructors]
692 tyConUnique :: Unique, -- ^ Same Unique as the data constructor
693 tyConName :: Name, -- ^ Same Name as the data constructor
694
695 -- See Note [The binders/kind/arity fields of a TyCon]
696 tyConBinders :: [TyConBinder], -- ^ Full binders
697 tyConResKind :: Kind, -- ^ Result kind
698 tyConKind :: Kind, -- ^ Kind of this TyCon
699 tyConArity :: Arity, -- ^ Arity
700
701 tcRoles :: [Role], -- ^ Roles: N for kind vars, R for type vars
702 dataCon :: DataCon, -- ^ Corresponding data constructor
703 tcRepName :: TyConRepName,
704 promDcRepInfo :: RuntimeRepInfo -- ^ See comments with 'RuntimeRepInfo'
705 }
706
707 -- | These exist only during a recursive type/class type-checking knot.
708 | TcTyCon {
709 tyConUnique :: Unique,
710 tyConName :: Name,
711 tyConUnsat :: Bool, -- ^ can this tycon be unsaturated?
712
713 -- See Note [The binders/kind/arity fields of a TyCon]
714 tyConBinders :: [TyConBinder], -- ^ Full binders
715 tyConTyVars :: [TyVar], -- ^ TyVar binders
716 tyConResKind :: Kind, -- ^ Result kind
717 tyConKind :: Kind, -- ^ Kind of this TyCon
718 tyConArity :: Arity, -- ^ Arity
719
720 tcTyConScopedTyVars :: [TyVar] -- ^ Scoped tyvars over the
721 -- tycon's body. See Note [TcTyCon]
722 }
723
724
725 -- | Represents right-hand-sides of 'TyCon's for algebraic types
726 data AlgTyConRhs
727
728 -- | Says that we know nothing about this data type, except that
729 -- it's represented by a pointer. Used when we export a data type
730 -- abstractly into an .hi file.
731 = AbstractTyCon
732 Bool -- True <=> It's definitely a distinct data type,
733 -- equal only to itself; ie not a newtype
734 -- False <=> Not sure
735
736 -- | Information about those 'TyCon's derived from a @data@
737 -- declaration. This includes data types with no constructors at
738 -- all.
739 | DataTyCon {
740 data_cons :: [DataCon],
741 -- ^ The data type constructors; can be empty if the
742 -- user declares the type to have no constructors
743 --
744 -- INVARIANT: Kept in order of increasing 'DataCon'
745 -- tag (see the tag assignment in DataCon.mkDataCon)
746
747 is_enum :: Bool -- ^ Cached value: is this an enumeration type?
748 -- See Note [Enumeration types]
749 }
750
751 | TupleTyCon { -- A boxed, unboxed, or constraint tuple
752 data_con :: DataCon, -- NB: it can be an *unboxed* tuple
753 tup_sort :: TupleSort -- ^ Is this a boxed, unboxed or constraint
754 -- tuple?
755 }
756
757 -- | Information about those 'TyCon's derived from a @newtype@ declaration
758 | NewTyCon {
759 data_con :: DataCon, -- ^ The unique constructor for the @newtype@.
760 -- It has no existentials
761
762 nt_rhs :: Type, -- ^ Cached value: the argument type of the
763 -- constructor, which is just the representation
764 -- type of the 'TyCon' (remember that @newtype@s
765 -- do not exist at runtime so need a different
766 -- representation type).
767 --
768 -- The free 'TyVar's of this type are the
769 -- 'tyConTyVars' from the corresponding 'TyCon'
770
771 nt_etad_rhs :: ([TyVar], Type),
772 -- ^ Same as the 'nt_rhs', but this time eta-reduced.
773 -- Hence the list of 'TyVar's in this field may be
774 -- shorter than the declared arity of the 'TyCon'.
775
776 -- See Note [Newtype eta]
777 nt_co :: CoAxiom Unbranched
778 -- The axiom coercion that creates the @newtype@
779 -- from the representation 'Type'.
780
781 -- See Note [Newtype coercions]
782 -- Invariant: arity = #tvs in nt_etad_rhs;
783 -- See Note [Newtype eta]
784 -- Watch out! If any newtypes become transparent
785 -- again check Trac #1072.
786 }
787
788 -- | Some promoted datacons signify extra info relevant to GHC. For example,
789 -- the @IntRep@ constructor of @RuntimeRep@ corresponds to the 'IntRep'
790 -- constructor of 'PrimRep'. This data structure allows us to store this
791 -- information right in the 'TyCon'. The other approach would be to look
792 -- up things like @RuntimeRep@'s @PrimRep@ by known-key every time.
793 data RuntimeRepInfo
794 = NoRRI -- ^ an ordinary promoted data con
795 | RuntimeRep ([Type] -> PrimRep)
796 -- ^ A constructor of @RuntimeRep@. The argument to the function should
797 -- be the list of arguments to the promoted datacon.
798 | VecCount Int -- ^ A constructor of @VecCount@
799 | VecElem PrimElemRep -- ^ A constructor of @VecElem@
800
801 -- | Extract those 'DataCon's that we are able to learn about. Note
802 -- that visibility in this sense does not correspond to visibility in
803 -- the context of any particular user program!
804 visibleDataCons :: AlgTyConRhs -> [DataCon]
805 visibleDataCons (AbstractTyCon {}) = []
806 visibleDataCons (DataTyCon{ data_cons = cs }) = cs
807 visibleDataCons (NewTyCon{ data_con = c }) = [c]
808 visibleDataCons (TupleTyCon{ data_con = c }) = [c]
809
810 -- ^ Both type classes as well as family instances imply implicit
811 -- type constructors. These implicit type constructors refer to their parent
812 -- structure (ie, the class or family from which they derive) using a type of
813 -- the following form.
814 data AlgTyConFlav
815 = -- | An ordinary type constructor has no parent.
816 VanillaAlgTyCon
817 TyConRepName
818
819 -- | An unboxed type constructor. Note that this carries no TyConRepName
820 -- as it is not representable.
821 | UnboxedAlgTyCon
822
823 -- | Type constructors representing a class dictionary.
824 -- See Note [ATyCon for classes] in TyCoRep
825 | ClassTyCon
826 Class -- INVARIANT: the classTyCon of this Class is the
827 -- current tycon
828 TyConRepName
829
830 -- | Type constructors representing an *instance* of a *data* family.
831 -- Parameters:
832 --
833 -- 1) The type family in question
834 --
835 -- 2) Instance types; free variables are the 'tyConTyVars'
836 -- of the current 'TyCon' (not the family one). INVARIANT:
837 -- the number of types matches the arity of the family 'TyCon'
838 --
839 -- 3) A 'CoTyCon' identifying the representation
840 -- type with the type instance family
841 | DataFamInstTyCon -- See Note [Data type families]
842 (CoAxiom Unbranched) -- The coercion axiom.
843 -- A *Representational* coercion,
844 -- of kind T ty1 ty2 ~R R:T a b c
845 -- where T is the family TyCon,
846 -- and R:T is the representation TyCon (ie this one)
847 -- and a,b,c are the tyConTyVars of this TyCon
848 --
849 -- BUT may be eta-reduced; see TcInstDcls
850 -- Note [Eta reduction for data family axioms]
851
852 -- Cached fields of the CoAxiom, but adjusted to
853 -- use the tyConTyVars of this TyCon
854 TyCon -- The family TyCon
855 [Type] -- Argument types (mentions the tyConTyVars of this TyCon)
856 -- Match in length the tyConTyVars of the family TyCon
857
858 -- E.g. data intance T [a] = ...
859 -- gives a representation tycon:
860 -- data R:TList a = ...
861 -- axiom co a :: T [a] ~ R:TList a
862 -- with R:TList's algTcParent = DataFamInstTyCon T [a] co
863
864 instance Outputable AlgTyConFlav where
865 ppr (VanillaAlgTyCon {}) = text "Vanilla ADT"
866 ppr (UnboxedAlgTyCon {}) = text "Unboxed ADT"
867 ppr (ClassTyCon cls _) = text "Class parent" <+> ppr cls
868 ppr (DataFamInstTyCon _ tc tys) = text "Family parent (family instance)"
869 <+> ppr tc <+> sep (map pprType tys)
870
871 -- | Checks the invariants of a 'AlgTyConFlav' given the appropriate type class
872 -- name, if any
873 okParent :: Name -> AlgTyConFlav -> Bool
874 okParent _ (VanillaAlgTyCon {}) = True
875 okParent _ (UnboxedAlgTyCon) = True
876 okParent tc_name (ClassTyCon cls _) = tc_name == tyConName (classTyCon cls)
877 okParent _ (DataFamInstTyCon _ fam_tc tys) = tyConArity fam_tc == length tys
878
879 isNoParent :: AlgTyConFlav -> Bool
880 isNoParent (VanillaAlgTyCon {}) = True
881 isNoParent _ = False
882
883 --------------------
884
885 data Injectivity
886 = NotInjective
887 | Injective [Bool] -- 1-1 with tyConTyVars (incl kind vars)
888 deriving( Eq )
889
890 -- | Information pertaining to the expansion of a type synonym (@type@)
891 data FamTyConFlav
892 = -- | Represents an open type family without a fixed right hand
893 -- side. Additional instances can appear at any time.
894 --
895 -- These are introduced by either a top level declaration:
896 --
897 -- > data family T a :: *
898 --
899 -- Or an associated data type declaration, within a class declaration:
900 --
901 -- > class C a b where
902 -- > data T b :: *
903 DataFamilyTyCon
904 TyConRepName
905
906 -- | An open type synonym family e.g. @type family F x y :: * -> *@
907 | OpenSynFamilyTyCon
908
909 -- | A closed type synonym family e.g.
910 -- @type family F x where { F Int = Bool }@
911 | ClosedSynFamilyTyCon (Maybe (CoAxiom Branched))
912 -- See Note [Closed type families]
913
914 -- | A closed type synonym family declared in an hs-boot file with
915 -- type family F a where ..
916 | AbstractClosedSynFamilyTyCon
917
918 -- | Built-in type family used by the TypeNats solver
919 | BuiltInSynFamTyCon BuiltInSynFamily
920
921 {- Note [Closed type families]
922 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
923 * In an open type family you can add new instances later. This is the
924 usual case.
925
926 * In a closed type family you can only put equations where the family
927 is defined.
928
929 A non-empty closed type family has a single axiom with multiple
930 branches, stored in the 'ClosedSynFamilyTyCon' constructor. A closed
931 type family with no equations does not have an axiom, because there is
932 nothing for the axiom to prove!
933
934
935 Note [Promoted data constructors]
936 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
937 All data constructors can be promoted to become a type constructor,
938 via the PromotedDataCon alternative in TyCon.
939
940 * The TyCon promoted from a DataCon has the *same* Name and Unique as
941 the DataCon. Eg. If the data constructor Data.Maybe.Just(unique 78,
942 say) is promoted to a TyCon whose name is Data.Maybe.Just(unique 78)
943
944 * Small note: We promote the *user* type of the DataCon. Eg
945 data T = MkT {-# UNPACK #-} !(Bool, Bool)
946 The promoted kind is
947 MkT :: (Bool,Bool) -> T
948 *not*
949 MkT :: Bool -> Bool -> T
950
951 Note [Enumeration types]
952 ~~~~~~~~~~~~~~~~~~~~~~~~
953 We define datatypes with no constructors to *not* be
954 enumerations; this fixes trac #2578, Otherwise we
955 end up generating an empty table for
956 <mod>_<type>_closure_tbl
957 which is used by tagToEnum# to map Int# to constructors
958 in an enumeration. The empty table apparently upset
959 the linker.
960
961 Moreover, all the data constructor must be enumerations, meaning
962 they have type (forall abc. T a b c). GADTs are not enumerations.
963 For example consider
964 data T a where
965 T1 :: T Int
966 T2 :: T Bool
967 T3 :: T a
968 What would [T1 ..] be? [T1,T3] :: T Int? Easiest thing is to exclude them.
969 See Trac #4528.
970
971 Note [Newtype coercions]
972 ~~~~~~~~~~~~~~~~~~~~~~~~
973 The NewTyCon field nt_co is a CoAxiom which is used for coercing from
974 the representation type of the newtype, to the newtype itself. For
975 example,
976
977 newtype T a = MkT (a -> a)
978
979 the NewTyCon for T will contain nt_co = CoT where CoT t : T t ~ t -> t.
980
981 In the case that the right hand side is a type application
982 ending with the same type variables as the left hand side, we
983 "eta-contract" the coercion. So if we had
984
985 newtype S a = MkT [a]
986
987 then we would generate the arity 0 axiom CoS : S ~ []. The
988 primary reason we do this is to make newtype deriving cleaner.
989
990 In the paper we'd write
991 axiom CoT : (forall t. T t) ~ (forall t. [t])
992 and then when we used CoT at a particular type, s, we'd say
993 CoT @ s
994 which encodes as (TyConApp instCoercionTyCon [TyConApp CoT [], s])
995
996 Note [Newtype eta]
997 ~~~~~~~~~~~~~~~~~~
998 Consider
999 newtype Parser a = MkParser (IO a) deriving Monad
1000 Are these two types equal (to Core)?
1001 Monad Parser
1002 Monad IO
1003 which we need to make the derived instance for Monad Parser.
1004
1005 Well, yes. But to see that easily we eta-reduce the RHS type of
1006 Parser, in this case to ([], Froogle), so that even unsaturated applications
1007 of Parser will work right. This eta reduction is done when the type
1008 constructor is built, and cached in NewTyCon.
1009
1010 Here's an example that I think showed up in practice
1011 Source code:
1012 newtype T a = MkT [a]
1013 newtype Foo m = MkFoo (forall a. m a -> Int)
1014
1015 w1 :: Foo []
1016 w1 = ...
1017
1018 w2 :: Foo T
1019 w2 = MkFoo (\(MkT x) -> case w1 of MkFoo f -> f x)
1020
1021 After desugaring, and discarding the data constructors for the newtypes,
1022 we get:
1023 w2 = w1 `cast` Foo CoT
1024 so the coercion tycon CoT must have
1025 kind: T ~ []
1026 and arity: 0
1027
1028 Note [TcTyCon]
1029 ~~~~~~~~~~~~~~
1030 When checking a type/class declaration (in module TcTyClsDecls), we come
1031 upon knowledge of the eventual tycon in bits and pieces. First, we use
1032 getInitialKinds to look over the user-provided kind signature of a tycon
1033 (including, for example, the number of parameters written to the tycon)
1034 to get an initial shape of the tycon's kind. Then, using these initial
1035 kinds, we kind-check the body of the tycon (class methods, data constructors,
1036 etc.), filling in the metavariables in the tycon's initial kind.
1037 We then generalize to get the tycon's final, fixed kind. Finally, once
1038 this has happened for all tycons in a mutually recursive group, we
1039 can desugar the lot.
1040
1041 For convenience, we store partially-known tycons in TcTyCons, which
1042 might store meta-variables. These TcTyCons are stored in the local
1043 environment in TcTyClsDecls, until the real full TyCons can be created
1044 during desugaring. A desugared program should never have a TcTyCon.
1045
1046 A challenging piece in all of this is that we end up taking three separate
1047 passes over every declaration: one in getInitialKind (this pass look only
1048 at the head, not the body), one in kcTyClDecls (to kind-check the body),
1049 and a final one in tcTyClDecls (to desugar). In the latter two passes,
1050 we need to connect the user-written type variables in an LHsQTyVars
1051 with the variables in the tycon's inferred kind. Because the tycon might
1052 not have a CUSK, this matching up is, in general, quite hard to do.
1053 (Look through the git history between Dec 2015 and Apr 2016 for
1054 TcHsType.splitTelescopeTvs!) Instead of trying, we just store the list
1055 of type variables to bring into scope in the later passes when we create
1056 a TcTyCon in getInitialKinds. Much easier this way! These tyvars are
1057 brought into scope in kcTyClTyVars and tcTyClTyVars, both in TcHsType.
1058
1059 It is important that the scoped type variables not be zonked, as some
1060 scoped type variables come into existence as SigTvs. If we zonk, the
1061 Unique will change and the user-written occurrences won't match up with
1062 what we expect.
1063
1064 In a TcTyCon, everything is zonked (except the scoped vars) after
1065 the kind-checking pass.
1066
1067 ************************************************************************
1068 * *
1069 TyConRepName
1070 * *
1071 ********************************************************************* -}
1072
1073 type TyConRepName = Name -- The Name of the top-level declaration
1074 -- $tcMaybe :: Data.Typeable.Internal.TyCon
1075 -- $tcMaybe = TyCon { tyConName = "Maybe", ... }
1076
1077 tyConRepName_maybe :: TyCon -> Maybe TyConRepName
1078 tyConRepName_maybe (FunTyCon { tcRepName = rep_nm })
1079 = Just rep_nm
1080 tyConRepName_maybe (PrimTyCon { primRepName = mb_rep_nm })
1081 = mb_rep_nm
1082 tyConRepName_maybe (AlgTyCon { algTcParent = parent })
1083 | VanillaAlgTyCon rep_nm <- parent = Just rep_nm
1084 | ClassTyCon _ rep_nm <- parent = Just rep_nm
1085 tyConRepName_maybe (FamilyTyCon { famTcFlav = DataFamilyTyCon rep_nm })
1086 = Just rep_nm
1087 tyConRepName_maybe (PromotedDataCon { tcRepName = rep_nm })
1088 = Just rep_nm
1089 tyConRepName_maybe _ = Nothing
1090
1091 -- | Make a 'Name' for the 'Typeable' representation of the given wired-in type
1092 mkPrelTyConRepName :: Name -> TyConRepName
1093 -- See Note [Grand plan for Typeable] in 'TcTypeable' in TcTypeable.
1094 mkPrelTyConRepName tc_name -- Prelude tc_name is always External,
1095 -- so nameModule will work
1096 = mkExternalName rep_uniq rep_mod rep_occ (nameSrcSpan tc_name)
1097 where
1098 name_occ = nameOccName tc_name
1099 name_mod = nameModule tc_name
1100 name_uniq = nameUnique tc_name
1101 rep_uniq | isTcOcc name_occ = tyConRepNameUnique name_uniq
1102 | otherwise = dataConRepNameUnique name_uniq
1103 (rep_mod, rep_occ) = tyConRepModOcc name_mod name_occ
1104
1105 -- | The name (and defining module) for the Typeable representation (TyCon) of a
1106 -- type constructor.
1107 --
1108 -- See Note [Grand plan for Typeable] in 'TcTypeable' in TcTypeable.
1109 tyConRepModOcc :: Module -> OccName -> (Module, OccName)
1110 tyConRepModOcc tc_module tc_occ = (rep_module, mkTyConRepOcc tc_occ)
1111 where
1112 rep_module
1113 | tc_module == gHC_PRIM = gHC_TYPES
1114 | otherwise = tc_module
1115
1116
1117 {- *********************************************************************
1118 * *
1119 PrimRep
1120 * *
1121 ************************************************************************
1122
1123 Note [rep swamp]
1124
1125 GHC has a rich selection of types that represent "primitive types" of
1126 one kind or another. Each of them makes a different set of
1127 distinctions, and mostly the differences are for good reasons,
1128 although it's probably true that we could merge some of these.
1129
1130 Roughly in order of "includes more information":
1131
1132 - A Width (cmm/CmmType) is simply a binary value with the specified
1133 number of bits. It may represent a signed or unsigned integer, a
1134 floating-point value, or an address.
1135
1136 data Width = W8 | W16 | W32 | W64 | W80 | W128
1137
1138 - Size, which is used in the native code generator, is Width +
1139 floating point information.
1140
1141 data Size = II8 | II16 | II32 | II64 | FF32 | FF64 | FF80
1142
1143 it is necessary because e.g. the instruction to move a 64-bit float
1144 on x86 (movsd) is different from the instruction to move a 64-bit
1145 integer (movq), so the mov instruction is parameterised by Size.
1146
1147 - CmmType wraps Width with more information: GC ptr, float, or
1148 other value.
1149
1150 data CmmType = CmmType CmmCat Width
1151
1152 data CmmCat -- "Category" (not exported)
1153 = GcPtrCat -- GC pointer
1154 | BitsCat -- Non-pointer
1155 | FloatCat -- Float
1156
1157 It is important to have GcPtr information in Cmm, since we generate
1158 info tables containing pointerhood for the GC from this. As for
1159 why we have float (and not signed/unsigned) here, see Note [Signed
1160 vs unsigned].
1161
1162 - ArgRep makes only the distinctions necessary for the call and
1163 return conventions of the STG machine. It is essentially CmmType
1164 + void.
1165
1166 - PrimRep makes a few more distinctions than ArgRep: it divides
1167 non-GC-pointers into signed/unsigned and addresses, information
1168 that is necessary for passing these values to foreign functions.
1169
1170 There's another tension here: whether the type encodes its size in
1171 bytes, or whether its size depends on the machine word size. Width
1172 and CmmType have the size built-in, whereas ArgRep and PrimRep do not.
1173
1174 This means to turn an ArgRep/PrimRep into a CmmType requires DynFlags.
1175
1176 On the other hand, CmmType includes some "nonsense" values, such as
1177 CmmType GcPtrCat W32 on a 64-bit machine.
1178 -}
1179
1180 -- | A 'PrimRep' is an abstraction of a type. It contains information that
1181 -- the code generator needs in order to pass arguments, return results,
1182 -- and store values of this type.
1183 data PrimRep
1184 = VoidRep
1185 | PtrRep
1186 | IntRep -- ^ Signed, word-sized value
1187 | WordRep -- ^ Unsigned, word-sized value
1188 | Int64Rep -- ^ Signed, 64 bit value (with 32-bit words only)
1189 | Word64Rep -- ^ Unsigned, 64 bit value (with 32-bit words only)
1190 | AddrRep -- ^ A pointer, but /not/ to a Haskell value (use 'PtrRep')
1191 | FloatRep
1192 | DoubleRep
1193 | VecRep Int PrimElemRep -- ^ A vector
1194 deriving( Eq, Show )
1195
1196 data PrimElemRep
1197 = Int8ElemRep
1198 | Int16ElemRep
1199 | Int32ElemRep
1200 | Int64ElemRep
1201 | Word8ElemRep
1202 | Word16ElemRep
1203 | Word32ElemRep
1204 | Word64ElemRep
1205 | FloatElemRep
1206 | DoubleElemRep
1207 deriving( Eq, Show )
1208
1209 instance Outputable PrimRep where
1210 ppr r = text (show r)
1211
1212 instance Outputable PrimElemRep where
1213 ppr r = text (show r)
1214
1215 isVoidRep :: PrimRep -> Bool
1216 isVoidRep VoidRep = True
1217 isVoidRep _other = False
1218
1219 isGcPtrRep :: PrimRep -> Bool
1220 isGcPtrRep PtrRep = True
1221 isGcPtrRep _ = False
1222
1223 -- | Find the size of a 'PrimRep', in words
1224 primRepSizeW :: DynFlags -> PrimRep -> Int
1225 primRepSizeW _ IntRep = 1
1226 primRepSizeW _ WordRep = 1
1227 primRepSizeW dflags Int64Rep = wORD64_SIZE `quot` wORD_SIZE dflags
1228 primRepSizeW dflags Word64Rep = wORD64_SIZE `quot` wORD_SIZE dflags
1229 primRepSizeW _ FloatRep = 1 -- NB. might not take a full word
1230 primRepSizeW dflags DoubleRep = dOUBLE_SIZE dflags `quot` wORD_SIZE dflags
1231 primRepSizeW _ AddrRep = 1
1232 primRepSizeW _ PtrRep = 1
1233 primRepSizeW _ VoidRep = 0
1234 primRepSizeW dflags (VecRep len rep) = len * primElemRepSizeB rep `quot` wORD_SIZE dflags
1235
1236 primElemRepSizeB :: PrimElemRep -> Int
1237 primElemRepSizeB Int8ElemRep = 1
1238 primElemRepSizeB Int16ElemRep = 2
1239 primElemRepSizeB Int32ElemRep = 4
1240 primElemRepSizeB Int64ElemRep = 8
1241 primElemRepSizeB Word8ElemRep = 1
1242 primElemRepSizeB Word16ElemRep = 2
1243 primElemRepSizeB Word32ElemRep = 4
1244 primElemRepSizeB Word64ElemRep = 8
1245 primElemRepSizeB FloatElemRep = 4
1246 primElemRepSizeB DoubleElemRep = 8
1247
1248 -- | Return if Rep stands for floating type,
1249 -- returns Nothing for vector types.
1250 primRepIsFloat :: PrimRep -> Maybe Bool
1251 primRepIsFloat FloatRep = Just True
1252 primRepIsFloat DoubleRep = Just True
1253 primRepIsFloat (VecRep _ _) = Nothing
1254 primRepIsFloat _ = Just False
1255
1256
1257 {-
1258 ************************************************************************
1259 * *
1260 Field labels
1261 * *
1262 ************************************************************************
1263 -}
1264
1265 -- | The labels for the fields of this particular 'TyCon'
1266 tyConFieldLabels :: TyCon -> [FieldLabel]
1267 tyConFieldLabels tc = dFsEnvElts $ tyConFieldLabelEnv tc
1268
1269 -- | The labels for the fields of this particular 'TyCon'
1270 tyConFieldLabelEnv :: TyCon -> FieldLabelEnv
1271 tyConFieldLabelEnv tc
1272 | isAlgTyCon tc = algTcFields tc
1273 | otherwise = emptyDFsEnv
1274
1275
1276 -- | Make a map from strings to FieldLabels from all the data
1277 -- constructors of this algebraic tycon
1278 fieldsOfAlgTcRhs :: AlgTyConRhs -> FieldLabelEnv
1279 fieldsOfAlgTcRhs rhs = mkDFsEnv [ (flLabel fl, fl)
1280 | fl <- dataConsFields (visibleDataCons rhs) ]
1281 where
1282 -- Duplicates in this list will be removed by 'mkFsEnv'
1283 dataConsFields dcs = concatMap dataConFieldLabels dcs
1284
1285
1286 {-
1287 ************************************************************************
1288 * *
1289 \subsection{TyCon Construction}
1290 * *
1291 ************************************************************************
1292
1293 Note: the TyCon constructors all take a Kind as one argument, even though
1294 they could, in principle, work out their Kind from their other arguments.
1295 But to do so they need functions from Types, and that makes a nasty
1296 module mutual-recursion. And they aren't called from many places.
1297 So we compromise, and move their Kind calculation to the call site.
1298 -}
1299
1300 -- | Given the name of the function type constructor and it's kind, create the
1301 -- corresponding 'TyCon'. It is reccomended to use 'TyCoRep.funTyCon' if you want
1302 -- this functionality
1303 mkFunTyCon :: Name -> [TyConBinder] -> Name -> TyCon
1304 mkFunTyCon name binders rep_nm
1305 = FunTyCon {
1306 tyConUnique = nameUnique name,
1307 tyConName = name,
1308 tyConBinders = binders,
1309 tyConResKind = liftedTypeKind,
1310 tyConKind = mkTyConKind binders liftedTypeKind,
1311 tyConArity = 2,
1312 tcRepName = rep_nm
1313 }
1314
1315 -- | This is the making of an algebraic 'TyCon'. Notably, you have to
1316 -- pass in the generic (in the -XGenerics sense) information about the
1317 -- type constructor - you can get hold of it easily (see Generics
1318 -- module)
1319 mkAlgTyCon :: Name
1320 -> [TyConBinder] -- ^ Binders of the 'TyCon'
1321 -> Kind -- ^ Result kind
1322 -> [Role] -- ^ The roles for each TyVar
1323 -> Maybe CType -- ^ The C type this type corresponds to
1324 -- when using the CAPI FFI
1325 -> [PredType] -- ^ Stupid theta: see 'algTcStupidTheta'
1326 -> AlgTyConRhs -- ^ Information about data constructors
1327 -> AlgTyConFlav -- ^ What flavour is it?
1328 -- (e.g. vanilla, type family)
1329 -> RecFlag -- ^ Is the 'TyCon' recursive?
1330 -> Bool -- ^ Was the 'TyCon' declared with GADT syntax?
1331 -> TyCon
1332 mkAlgTyCon name binders res_kind roles cType stupid rhs parent is_rec gadt_syn
1333 = AlgTyCon {
1334 tyConName = name,
1335 tyConUnique = nameUnique name,
1336 tyConBinders = binders,
1337 tyConResKind = res_kind,
1338 tyConKind = mkTyConKind binders res_kind,
1339 tyConArity = length binders,
1340 tyConTyVars = binderVars binders,
1341 tcRoles = roles,
1342 tyConCType = cType,
1343 algTcStupidTheta = stupid,
1344 algTcRhs = rhs,
1345 algTcFields = fieldsOfAlgTcRhs rhs,
1346 algTcParent = ASSERT2( okParent name parent, ppr name $$ ppr parent ) parent,
1347 algTcRec = is_rec,
1348 algTcGadtSyntax = gadt_syn
1349 }
1350
1351 -- | Simpler specialization of 'mkAlgTyCon' for classes
1352 mkClassTyCon :: Name -> [TyConBinder]
1353 -> [Role] -> AlgTyConRhs -> Class
1354 -> RecFlag -> Name -> TyCon
1355 mkClassTyCon name binders roles rhs clas is_rec tc_rep_name
1356 = mkAlgTyCon name binders constraintKind roles Nothing [] rhs
1357 (ClassTyCon clas tc_rep_name)
1358 is_rec False
1359
1360 mkTupleTyCon :: Name
1361 -> [TyConBinder]
1362 -> Kind -- ^ Result kind of the 'TyCon'
1363 -> Arity -- ^ Arity of the tuple
1364 -> DataCon
1365 -> TupleSort -- ^ Whether the tuple is boxed or unboxed
1366 -> AlgTyConFlav
1367 -> TyCon
1368 mkTupleTyCon name binders res_kind arity con sort parent
1369 = AlgTyCon {
1370 tyConName = name,
1371 tyConUnique = nameUnique name,
1372 tyConBinders = binders,
1373 tyConResKind = res_kind,
1374 tyConKind = mkTyConKind binders res_kind,
1375 tyConArity = arity,
1376 tyConTyVars = binderVars binders,
1377 tcRoles = replicate arity Representational,
1378 tyConCType = Nothing,
1379 algTcStupidTheta = [],
1380 algTcRhs = TupleTyCon { data_con = con,
1381 tup_sort = sort },
1382 algTcFields = emptyDFsEnv,
1383 algTcParent = parent,
1384 algTcRec = NonRecursive,
1385 algTcGadtSyntax = False
1386 }
1387
1388 -- | Makes a tycon suitable for use during type-checking.
1389 -- The only real need for this is for printing error messages during
1390 -- a recursive type/class type-checking knot. It has a kind because
1391 -- TcErrors sometimes calls typeKind.
1392 -- See also Note [Kind checking recursive type and class declarations]
1393 -- in TcTyClsDecls.
1394 mkTcTyCon :: Name
1395 -> [TyConBinder]
1396 -> Kind -- ^ /result/ kind only
1397 -> Bool -- ^ Can this be unsaturated?
1398 -> [TyVar] -- ^ Scoped type variables, see Note [TcTyCon]
1399 -> TyCon
1400 mkTcTyCon name binders res_kind unsat scoped_tvs
1401 = TcTyCon { tyConUnique = getUnique name
1402 , tyConName = name
1403 , tyConTyVars = binderVars binders
1404 , tyConBinders = binders
1405 , tyConResKind = res_kind
1406 , tyConKind = mkTyConKind binders res_kind
1407 , tyConUnsat = unsat
1408 , tyConArity = length binders
1409 , tcTyConScopedTyVars = scoped_tvs }
1410
1411 -- | Create an unlifted primitive 'TyCon', such as @Int#@
1412 mkPrimTyCon :: Name -> [TyConBinder]
1413 -> Kind -- ^ /result/ kind
1414 -> [Role] -> TyCon
1415 mkPrimTyCon name binders res_kind roles
1416 = mkPrimTyCon' name binders res_kind roles True (Just $ mkPrelTyConRepName name)
1417
1418 -- | Kind constructors
1419 mkKindTyCon :: Name -> [TyConBinder]
1420 -> Kind -- ^ /result/ kind
1421 -> [Role] -> Name -> TyCon
1422 mkKindTyCon name binders res_kind roles rep_nm
1423 = tc
1424 where
1425 tc = mkPrimTyCon' name binders res_kind roles False (Just rep_nm)
1426
1427 -- | Create a lifted primitive 'TyCon' such as @RealWorld@
1428 mkLiftedPrimTyCon :: Name -> [TyConBinder]
1429 -> Kind -- ^ /result/ kind
1430 -> [Role] -> TyCon
1431 mkLiftedPrimTyCon name binders res_kind roles
1432 = mkPrimTyCon' name binders res_kind roles False (Just rep_nm)
1433 where rep_nm = mkPrelTyConRepName name
1434
1435 mkPrimTyCon' :: Name -> [TyConBinder]
1436 -> Kind -- ^ /result/ kind
1437 -> [Role]
1438 -> Bool -> Maybe TyConRepName -> TyCon
1439 mkPrimTyCon' name binders res_kind roles is_unlifted rep_nm
1440 = PrimTyCon {
1441 tyConName = name,
1442 tyConUnique = nameUnique name,
1443 tyConBinders = binders,
1444 tyConResKind = res_kind,
1445 tyConKind = mkTyConKind binders res_kind,
1446 tyConArity = length roles,
1447 tcRoles = roles,
1448 isUnlifted = is_unlifted,
1449 primRepName = rep_nm
1450 }
1451
1452 -- | Create a type synonym 'TyCon'
1453 mkSynonymTyCon :: Name -> [TyConBinder] -> Kind -- ^ /result/ kind
1454 -> [Role] -> Type -> TyCon
1455 mkSynonymTyCon name binders res_kind roles rhs
1456 = SynonymTyCon {
1457 tyConName = name,
1458 tyConUnique = nameUnique name,
1459 tyConBinders = binders,
1460 tyConResKind = res_kind,
1461 tyConKind = mkTyConKind binders res_kind,
1462 tyConArity = length binders,
1463 tyConTyVars = binderVars binders,
1464 tcRoles = roles,
1465 synTcRhs = rhs
1466 }
1467
1468 -- | Create a type family 'TyCon'
1469 mkFamilyTyCon :: Name -> [TyConBinder] -> Kind -- ^ /result/ kind
1470 -> Maybe Name -> FamTyConFlav
1471 -> Maybe Class -> Injectivity -> TyCon
1472 mkFamilyTyCon name binders res_kind resVar flav parent inj
1473 = FamilyTyCon
1474 { tyConUnique = nameUnique name
1475 , tyConName = name
1476 , tyConBinders = binders
1477 , tyConResKind = res_kind
1478 , tyConKind = mkTyConKind binders res_kind
1479 , tyConArity = length binders
1480 , tyConTyVars = binderVars binders
1481 , famTcResVar = resVar
1482 , famTcFlav = flav
1483 , famTcParent = parent
1484 , famTcInj = inj
1485 }
1486
1487
1488 -- | Create a promoted data constructor 'TyCon'
1489 -- Somewhat dodgily, we give it the same Name
1490 -- as the data constructor itself; when we pretty-print
1491 -- the TyCon we add a quote; see the Outputable TyCon instance
1492 mkPromotedDataCon :: DataCon -> Name -> TyConRepName
1493 -> [TyConBinder] -> Kind -> [Role]
1494 -> RuntimeRepInfo -> TyCon
1495 mkPromotedDataCon con name rep_name binders res_kind roles rep_info
1496 = PromotedDataCon {
1497 tyConUnique = nameUnique name,
1498 tyConName = name,
1499 tyConArity = length roles,
1500 tcRoles = roles,
1501 tyConBinders = binders,
1502 tyConResKind = res_kind,
1503 tyConKind = mkTyConKind binders res_kind,
1504 dataCon = con,
1505 tcRepName = rep_name,
1506 promDcRepInfo = rep_info
1507 }
1508
1509 isFunTyCon :: TyCon -> Bool
1510 isFunTyCon (FunTyCon {}) = True
1511 isFunTyCon _ = False
1512
1513 -- | Test if the 'TyCon' is algebraic but abstract (invisible data constructors)
1514 isAbstractTyCon :: TyCon -> Bool
1515 isAbstractTyCon (AlgTyCon { algTcRhs = AbstractTyCon {} }) = True
1516 isAbstractTyCon _ = False
1517
1518 -- | Make an fake, abstract 'TyCon' from an existing one.
1519 -- Used when recovering from errors
1520 makeTyConAbstract :: TyCon -> TyCon
1521 makeTyConAbstract tc
1522 = mkTcTyCon (tyConName tc)
1523 (tyConBinders tc) (tyConResKind tc)
1524 (mightBeUnsaturatedTyCon tc) [{- no scoped vars -}]
1525
1526 -- | Does this 'TyCon' represent something that cannot be defined in Haskell?
1527 isPrimTyCon :: TyCon -> Bool
1528 isPrimTyCon (PrimTyCon {}) = True
1529 isPrimTyCon _ = False
1530
1531 -- | Is this 'TyCon' unlifted (i.e. cannot contain bottom)? Note that this can
1532 -- only be true for primitive and unboxed-tuple 'TyCon's
1533 isUnliftedTyCon :: TyCon -> Bool
1534 isUnliftedTyCon (PrimTyCon {isUnlifted = is_unlifted})
1535 = is_unlifted
1536 isUnliftedTyCon (AlgTyCon { algTcRhs = rhs } )
1537 | TupleTyCon { tup_sort = sort } <- rhs
1538 = not (isBoxed (tupleSortBoxity sort))
1539 isUnliftedTyCon _ = False
1540
1541 -- | Returns @True@ if the supplied 'TyCon' resulted from either a
1542 -- @data@ or @newtype@ declaration
1543 isAlgTyCon :: TyCon -> Bool
1544 isAlgTyCon (AlgTyCon {}) = True
1545 isAlgTyCon _ = False
1546
1547 -- | Returns @True@ for vanilla AlgTyCons -- that is, those created
1548 -- with a @data@ or @newtype@ declaration.
1549 isVanillaAlgTyCon :: TyCon -> Bool
1550 isVanillaAlgTyCon (AlgTyCon { algTcParent = VanillaAlgTyCon _ }) = True
1551 isVanillaAlgTyCon _ = False
1552
1553 isDataTyCon :: TyCon -> Bool
1554 -- ^ Returns @True@ for data types that are /definitely/ represented by
1555 -- heap-allocated constructors. These are scrutinised by Core-level
1556 -- @case@ expressions, and they get info tables allocated for them.
1557 --
1558 -- Generally, the function will be true for all @data@ types and false
1559 -- for @newtype@s, unboxed tuples and type family 'TyCon's. But it is
1560 -- not guaranteed to return @True@ in all cases that it could.
1561 --
1562 -- NB: for a data type family, only the /instance/ 'TyCon's
1563 -- get an info table. The family declaration 'TyCon' does not
1564 isDataTyCon (AlgTyCon {algTcRhs = rhs})
1565 = case rhs of
1566 TupleTyCon { tup_sort = sort }
1567 -> isBoxed (tupleSortBoxity sort)
1568 DataTyCon {} -> True
1569 NewTyCon {} -> False
1570 AbstractTyCon {} -> False -- We don't know, so return False
1571 isDataTyCon _ = False
1572
1573 -- | 'isInjectiveTyCon' is true of 'TyCon's for which this property holds
1574 -- (where X is the role passed in):
1575 -- If (T a1 b1 c1) ~X (T a2 b2 c2), then (a1 ~X1 a2), (b1 ~X2 b2), and (c1 ~X3 c2)
1576 -- (where X1, X2, and X3, are the roles given by tyConRolesX tc X)
1577 -- See also Note [Decomposing equality] in TcCanonical
1578 isInjectiveTyCon :: TyCon -> Role -> Bool
1579 isInjectiveTyCon _ Phantom = False
1580 isInjectiveTyCon (FunTyCon {}) _ = True
1581 isInjectiveTyCon (AlgTyCon {}) Nominal = True
1582 isInjectiveTyCon (AlgTyCon {algTcRhs = rhs}) Representational
1583 = isGenInjAlgRhs rhs
1584 isInjectiveTyCon (SynonymTyCon {}) _ = False
1585 isInjectiveTyCon (FamilyTyCon { famTcFlav = DataFamilyTyCon _ })
1586 Nominal = True
1587 isInjectiveTyCon (FamilyTyCon { famTcInj = Injective inj }) _ = and inj
1588 isInjectiveTyCon (FamilyTyCon {}) _ = False
1589 isInjectiveTyCon (PrimTyCon {}) _ = True
1590 isInjectiveTyCon (PromotedDataCon {}) _ = True
1591 isInjectiveTyCon tc@(TcTyCon {}) _
1592 = pprPanic "isInjectiveTyCon sees a TcTyCon" (ppr tc)
1593
1594 -- | 'isGenerativeTyCon' is true of 'TyCon's for which this property holds
1595 -- (where X is the role passed in):
1596 -- If (T tys ~X t), then (t's head ~X T).
1597 -- See also Note [Decomposing equality] in TcCanonical
1598 isGenerativeTyCon :: TyCon -> Role -> Bool
1599 isGenerativeTyCon (FamilyTyCon { famTcFlav = DataFamilyTyCon _ }) Nominal = True
1600 isGenerativeTyCon (FamilyTyCon {}) _ = False
1601 -- in all other cases, injectivity implies generativitiy
1602 isGenerativeTyCon tc r = isInjectiveTyCon tc r
1603
1604 -- | Is this an 'AlgTyConRhs' of a 'TyCon' that is generative and injective
1605 -- with respect to representational equality?
1606 isGenInjAlgRhs :: AlgTyConRhs -> Bool
1607 isGenInjAlgRhs (TupleTyCon {}) = True
1608 isGenInjAlgRhs (DataTyCon {}) = True
1609 isGenInjAlgRhs (AbstractTyCon distinct) = distinct
1610 isGenInjAlgRhs (NewTyCon {}) = False
1611
1612 -- | Is this 'TyCon' that for a @newtype@
1613 isNewTyCon :: TyCon -> Bool
1614 isNewTyCon (AlgTyCon {algTcRhs = NewTyCon {}}) = True
1615 isNewTyCon _ = False
1616
1617 -- | Take a 'TyCon' apart into the 'TyVar's it scopes over, the 'Type' it expands
1618 -- into, and (possibly) a coercion from the representation type to the @newtype@.
1619 -- Returns @Nothing@ if this is not possible.
1620 unwrapNewTyCon_maybe :: TyCon -> Maybe ([TyVar], Type, CoAxiom Unbranched)
1621 unwrapNewTyCon_maybe (AlgTyCon { tyConTyVars = tvs,
1622 algTcRhs = NewTyCon { nt_co = co,
1623 nt_rhs = rhs }})
1624 = Just (tvs, rhs, co)
1625 unwrapNewTyCon_maybe _ = Nothing
1626
1627 unwrapNewTyConEtad_maybe :: TyCon -> Maybe ([TyVar], Type, CoAxiom Unbranched)
1628 unwrapNewTyConEtad_maybe (AlgTyCon { algTcRhs = NewTyCon { nt_co = co,
1629 nt_etad_rhs = (tvs,rhs) }})
1630 = Just (tvs, rhs, co)
1631 unwrapNewTyConEtad_maybe _ = Nothing
1632
1633 isProductTyCon :: TyCon -> Bool
1634 -- True of datatypes or newtypes that have
1635 -- one, non-existential, data constructor
1636 -- See Note [Product types]
1637 isProductTyCon tc@(AlgTyCon {})
1638 = case algTcRhs tc of
1639 TupleTyCon {} -> True
1640 DataTyCon{ data_cons = [data_con] }
1641 -> null (dataConExTyVars data_con)
1642 NewTyCon {} -> True
1643 _ -> False
1644 isProductTyCon _ = False
1645
1646 isDataProductTyCon_maybe :: TyCon -> Maybe DataCon
1647 -- True of datatypes (not newtypes) with
1648 -- one, vanilla, data constructor
1649 -- See Note [Product types]
1650 isDataProductTyCon_maybe (AlgTyCon { algTcRhs = rhs })
1651 = case rhs of
1652 DataTyCon { data_cons = [con] }
1653 | null (dataConExTyVars con) -- non-existential
1654 -> Just con
1655 TupleTyCon { data_con = con }
1656 -> Just con
1657 _ -> Nothing
1658 isDataProductTyCon_maybe _ = Nothing
1659
1660 {- Note [Product types]
1661 ~~~~~~~~~~~~~~~~~~~~~~~
1662 A product type is
1663 * A data type (not a newtype)
1664 * With one, boxed data constructor
1665 * That binds no existential type variables
1666
1667 The main point is that product types are amenable to unboxing for
1668 * Strict function calls; we can transform
1669 f (D a b) = e
1670 to
1671 fw a b = e
1672 via the worker/wrapper transformation. (Question: couldn't this
1673 work for existentials too?)
1674
1675 * CPR for function results; we can transform
1676 f x y = let ... in D a b
1677 to
1678 fw x y = let ... in (# a, b #)
1679
1680 Note that the data constructor /can/ have evidence arguments: equality
1681 constraints, type classes etc. So it can be GADT. These evidence
1682 arguments are simply value arguments, and should not get in the way.
1683 -}
1684
1685
1686 -- | Is this a 'TyCon' representing a regular H98 type synonym (@type@)?
1687 isTypeSynonymTyCon :: TyCon -> Bool
1688 isTypeSynonymTyCon (SynonymTyCon {}) = True
1689 isTypeSynonymTyCon _ = False
1690
1691
1692 -- As for newtypes, it is in some contexts important to distinguish between
1693 -- closed synonyms and synonym families, as synonym families have no unique
1694 -- right hand side to which a synonym family application can expand.
1695 --
1696
1697 -- | True iff we can decompose (T a b c) into ((T a b) c)
1698 -- I.e. is it injective and generative w.r.t nominal equality?
1699 -- That is, if (T a b) ~N d e f, is it always the case that
1700 -- (T ~N d), (a ~N e) and (b ~N f)?
1701 -- Specifically NOT true of synonyms (open and otherwise)
1702 --
1703 -- It'd be unusual to call mightBeUnsaturatedTyCon on a regular H98
1704 -- type synonym, because you should probably have expanded it first
1705 -- But regardless, it's not decomposable
1706 mightBeUnsaturatedTyCon :: TyCon -> Bool
1707 mightBeUnsaturatedTyCon (SynonymTyCon {}) = False
1708 mightBeUnsaturatedTyCon (FamilyTyCon { famTcFlav = flav}) = isDataFamFlav flav
1709 mightBeUnsaturatedTyCon (TcTyCon { tyConUnsat = unsat }) = unsat
1710 mightBeUnsaturatedTyCon _other = True
1711
1712 -- | Is this an algebraic 'TyCon' declared with the GADT syntax?
1713 isGadtSyntaxTyCon :: TyCon -> Bool
1714 isGadtSyntaxTyCon (AlgTyCon { algTcGadtSyntax = res }) = res
1715 isGadtSyntaxTyCon _ = False
1716
1717 -- | Is this an algebraic 'TyCon' which is just an enumeration of values?
1718 isEnumerationTyCon :: TyCon -> Bool
1719 -- See Note [Enumeration types] in TyCon
1720 isEnumerationTyCon (AlgTyCon { tyConArity = arity, algTcRhs = rhs })
1721 = case rhs of
1722 DataTyCon { is_enum = res } -> res
1723 TupleTyCon {} -> arity == 0
1724 _ -> False
1725 isEnumerationTyCon _ = False
1726
1727 -- | Is this a 'TyCon', synonym or otherwise, that defines a family?
1728 isFamilyTyCon :: TyCon -> Bool
1729 isFamilyTyCon (FamilyTyCon {}) = True
1730 isFamilyTyCon _ = False
1731
1732 -- | Is this a 'TyCon', synonym or otherwise, that defines a family with
1733 -- instances?
1734 isOpenFamilyTyCon :: TyCon -> Bool
1735 isOpenFamilyTyCon (FamilyTyCon {famTcFlav = flav })
1736 | OpenSynFamilyTyCon <- flav = True
1737 | DataFamilyTyCon {} <- flav = True
1738 isOpenFamilyTyCon _ = False
1739
1740 -- | Is this a synonym 'TyCon' that can have may have further instances appear?
1741 isTypeFamilyTyCon :: TyCon -> Bool
1742 isTypeFamilyTyCon (FamilyTyCon { famTcFlav = flav }) = not (isDataFamFlav flav)
1743 isTypeFamilyTyCon _ = False
1744
1745 -- | Is this a synonym 'TyCon' that can have may have further instances appear?
1746 isDataFamilyTyCon :: TyCon -> Bool
1747 isDataFamilyTyCon (FamilyTyCon { famTcFlav = flav }) = isDataFamFlav flav
1748 isDataFamilyTyCon _ = False
1749
1750 -- | Is this an open type family TyCon?
1751 isOpenTypeFamilyTyCon :: TyCon -> Bool
1752 isOpenTypeFamilyTyCon (FamilyTyCon {famTcFlav = OpenSynFamilyTyCon }) = True
1753 isOpenTypeFamilyTyCon _ = False
1754
1755 -- | Is this a non-empty closed type family? Returns 'Nothing' for
1756 -- abstract or empty closed families.
1757 isClosedSynFamilyTyConWithAxiom_maybe :: TyCon -> Maybe (CoAxiom Branched)
1758 isClosedSynFamilyTyConWithAxiom_maybe
1759 (FamilyTyCon {famTcFlav = ClosedSynFamilyTyCon mb}) = mb
1760 isClosedSynFamilyTyConWithAxiom_maybe _ = Nothing
1761
1762 -- | Try to read the injectivity information from a FamilyTyCon.
1763 -- For every other TyCon this function panics.
1764 familyTyConInjectivityInfo :: TyCon -> Injectivity
1765 familyTyConInjectivityInfo (FamilyTyCon { famTcInj = inj }) = inj
1766 familyTyConInjectivityInfo _ = panic "familyTyConInjectivityInfo"
1767
1768 isBuiltInSynFamTyCon_maybe :: TyCon -> Maybe BuiltInSynFamily
1769 isBuiltInSynFamTyCon_maybe
1770 (FamilyTyCon {famTcFlav = BuiltInSynFamTyCon ops }) = Just ops
1771 isBuiltInSynFamTyCon_maybe _ = Nothing
1772
1773 isDataFamFlav :: FamTyConFlav -> Bool
1774 isDataFamFlav (DataFamilyTyCon {}) = True -- Data family
1775 isDataFamFlav _ = False -- Type synonym family
1776
1777 -- | Are we able to extract information 'TyVar' to class argument list
1778 -- mapping from a given 'TyCon'?
1779 isTyConAssoc :: TyCon -> Bool
1780 isTyConAssoc tc = isJust (tyConAssoc_maybe tc)
1781
1782 tyConAssoc_maybe :: TyCon -> Maybe Class
1783 tyConAssoc_maybe (FamilyTyCon { famTcParent = mb_cls }) = mb_cls
1784 tyConAssoc_maybe _ = Nothing
1785
1786 -- The unit tycon didn't used to be classed as a tuple tycon
1787 -- but I thought that was silly so I've undone it
1788 -- If it can't be for some reason, it should be a AlgTyCon
1789 isTupleTyCon :: TyCon -> Bool
1790 -- ^ Does this 'TyCon' represent a tuple?
1791 --
1792 -- NB: when compiling @Data.Tuple@, the tycons won't reply @True@ to
1793 -- 'isTupleTyCon', because they are built as 'AlgTyCons'. However they
1794 -- get spat into the interface file as tuple tycons, so I don't think
1795 -- it matters.
1796 isTupleTyCon (AlgTyCon { algTcRhs = TupleTyCon {} }) = True
1797 isTupleTyCon _ = False
1798
1799 tyConTuple_maybe :: TyCon -> Maybe TupleSort
1800 tyConTuple_maybe (AlgTyCon { algTcRhs = rhs })
1801 | TupleTyCon { tup_sort = sort} <- rhs = Just sort
1802 tyConTuple_maybe _ = Nothing
1803
1804 -- | Is this the 'TyCon' for an unboxed tuple?
1805 isUnboxedTupleTyCon :: TyCon -> Bool
1806 isUnboxedTupleTyCon (AlgTyCon { algTcRhs = rhs })
1807 | TupleTyCon { tup_sort = sort } <- rhs
1808 = not (isBoxed (tupleSortBoxity sort))
1809 isUnboxedTupleTyCon _ = False
1810
1811 -- | Is this the 'TyCon' for a boxed tuple?
1812 isBoxedTupleTyCon :: TyCon -> Bool
1813 isBoxedTupleTyCon (AlgTyCon { algTcRhs = rhs })
1814 | TupleTyCon { tup_sort = sort } <- rhs
1815 = isBoxed (tupleSortBoxity sort)
1816 isBoxedTupleTyCon _ = False
1817
1818 -- | Is this a recursive 'TyCon'?
1819 isRecursiveTyCon :: TyCon -> Bool
1820 isRecursiveTyCon (AlgTyCon {algTcRec = Recursive}) = True
1821 isRecursiveTyCon _ = False
1822
1823 -- | Is this a PromotedDataCon?
1824 isPromotedDataCon :: TyCon -> Bool
1825 isPromotedDataCon (PromotedDataCon {}) = True
1826 isPromotedDataCon _ = False
1827
1828 -- | Retrieves the promoted DataCon if this is a PromotedDataCon;
1829 isPromotedDataCon_maybe :: TyCon -> Maybe DataCon
1830 isPromotedDataCon_maybe (PromotedDataCon { dataCon = dc }) = Just dc
1831 isPromotedDataCon_maybe _ = Nothing
1832
1833 -- | Is this tycon really meant for use at the kind level? That is,
1834 -- should it be permitted without -XDataKinds?
1835 isKindTyCon :: TyCon -> Bool
1836 isKindTyCon tc = getUnique tc `elementOfUniqSet` kindTyConKeys
1837
1838 -- | These TyCons should be allowed at the kind level, even without
1839 -- -XDataKinds.
1840 kindTyConKeys :: UniqSet Unique
1841 kindTyConKeys = unionManyUniqSets
1842 ( mkUniqSet [ liftedTypeKindTyConKey, starKindTyConKey, unicodeStarKindTyConKey
1843 , constraintKindTyConKey, tYPETyConKey ]
1844 : map (mkUniqSet . tycon_with_datacons) [ runtimeRepTyCon
1845 , vecCountTyCon, vecElemTyCon ] )
1846 where
1847 tycon_with_datacons tc = getUnique tc : map getUnique (tyConDataCons tc)
1848
1849 isLiftedTypeKindTyConName :: Name -> Bool
1850 isLiftedTypeKindTyConName
1851 = (`hasKey` liftedTypeKindTyConKey) <||>
1852 (`hasKey` starKindTyConKey) <||>
1853 (`hasKey` unicodeStarKindTyConKey)
1854
1855 -- | Identifies implicit tycons that, in particular, do not go into interface
1856 -- files (because they are implicitly reconstructed when the interface is
1857 -- read).
1858 --
1859 -- Note that:
1860 --
1861 -- * Associated families are implicit, as they are re-constructed from
1862 -- the class declaration in which they reside, and
1863 --
1864 -- * Family instances are /not/ implicit as they represent the instance body
1865 -- (similar to a @dfun@ does that for a class instance).
1866 --
1867 -- * Tuples are implicit iff they have a wired-in name
1868 -- (namely: boxed and unboxed tupeles are wired-in and implicit,
1869 -- but constraint tuples are not)
1870 isImplicitTyCon :: TyCon -> Bool
1871 isImplicitTyCon (FunTyCon {}) = True
1872 isImplicitTyCon (PrimTyCon {}) = True
1873 isImplicitTyCon (PromotedDataCon {}) = True
1874 isImplicitTyCon (AlgTyCon { algTcRhs = rhs, tyConName = name })
1875 | TupleTyCon {} <- rhs = isWiredInName name
1876 | otherwise = False
1877 isImplicitTyCon (FamilyTyCon { famTcParent = parent }) = isJust parent
1878 isImplicitTyCon (SynonymTyCon {}) = False
1879 isImplicitTyCon tc@(TcTyCon {})
1880 = pprPanic "isImplicitTyCon sees a TcTyCon" (ppr tc)
1881
1882 tyConCType_maybe :: TyCon -> Maybe CType
1883 tyConCType_maybe tc@(AlgTyCon {}) = tyConCType tc
1884 tyConCType_maybe _ = Nothing
1885
1886 -- | Is this a TcTyCon? (That is, one only used during type-checking?)
1887 isTcTyCon :: TyCon -> Bool
1888 isTcTyCon (TcTyCon {}) = True
1889 isTcTyCon _ = False
1890
1891 {-
1892 -----------------------------------------------
1893 -- Expand type-constructor applications
1894 -----------------------------------------------
1895 -}
1896
1897 expandSynTyCon_maybe
1898 :: TyCon
1899 -> [tyco] -- ^ Arguments to 'TyCon'
1900 -> Maybe ([(TyVar,tyco)],
1901 Type,
1902 [tyco]) -- ^ Returns a 'TyVar' substitution, the body
1903 -- type of the synonym (not yet substituted)
1904 -- and any arguments remaining from the
1905 -- application
1906
1907 -- ^ Expand a type synonym application, if any
1908 expandSynTyCon_maybe tc tys
1909 | SynonymTyCon { tyConTyVars = tvs, synTcRhs = rhs, tyConArity = arity } <- tc
1910 = case arity `compare` length tys of
1911 LT -> Just (tvs `zip` tys, rhs, drop arity tys)
1912 EQ -> Just (tvs `zip` tys, rhs, [])
1913 GT -> Nothing
1914 | otherwise
1915 = Nothing
1916
1917 ----------------
1918
1919 -- | Check if the tycon actually refers to a proper `data` or `newtype`
1920 -- with user defined constructors rather than one from a class or other
1921 -- construction.
1922 isTyConWithSrcDataCons :: TyCon -> Bool
1923 isTyConWithSrcDataCons (AlgTyCon { algTcRhs = rhs, algTcParent = parent }) =
1924 case rhs of
1925 DataTyCon {} -> isSrcParent
1926 NewTyCon {} -> isSrcParent
1927 TupleTyCon {} -> isSrcParent
1928 _ -> False
1929 where
1930 isSrcParent = isNoParent parent
1931 isTyConWithSrcDataCons _ = False
1932
1933
1934 -- | As 'tyConDataCons_maybe', but returns the empty list of constructors if no
1935 -- constructors could be found
1936 tyConDataCons :: TyCon -> [DataCon]
1937 -- It's convenient for tyConDataCons to return the
1938 -- empty list for type synonyms etc
1939 tyConDataCons tycon = tyConDataCons_maybe tycon `orElse` []
1940
1941 -- | Determine the 'DataCon's originating from the given 'TyCon', if the 'TyCon'
1942 -- is the sort that can have any constructors (note: this does not include
1943 -- abstract algebraic types)
1944 tyConDataCons_maybe :: TyCon -> Maybe [DataCon]
1945 tyConDataCons_maybe (AlgTyCon {algTcRhs = rhs})
1946 = case rhs of
1947 DataTyCon { data_cons = cons } -> Just cons
1948 NewTyCon { data_con = con } -> Just [con]
1949 TupleTyCon { data_con = con } -> Just [con]
1950 _ -> Nothing
1951 tyConDataCons_maybe _ = Nothing
1952
1953 -- | If the given 'TyCon' has a /single/ data constructor, i.e. it is a @data@
1954 -- type with one alternative, a tuple type or a @newtype@ then that constructor
1955 -- is returned. If the 'TyCon' has more than one constructor, or represents a
1956 -- primitive or function type constructor then @Nothing@ is returned. In any
1957 -- other case, the function panics
1958 tyConSingleDataCon_maybe :: TyCon -> Maybe DataCon
1959 tyConSingleDataCon_maybe (AlgTyCon { algTcRhs = rhs })
1960 = case rhs of
1961 DataTyCon { data_cons = [c] } -> Just c
1962 TupleTyCon { data_con = c } -> Just c
1963 NewTyCon { data_con = c } -> Just c
1964 _ -> Nothing
1965 tyConSingleDataCon_maybe _ = Nothing
1966
1967 tyConSingleDataCon :: TyCon -> DataCon
1968 tyConSingleDataCon tc
1969 = case tyConSingleDataCon_maybe tc of
1970 Just c -> c
1971 Nothing -> pprPanic "tyConDataCon" (ppr tc)
1972
1973 tyConSingleAlgDataCon_maybe :: TyCon -> Maybe DataCon
1974 -- Returns (Just con) for single-constructor
1975 -- *algebraic* data types *not* newtypes
1976 tyConSingleAlgDataCon_maybe (AlgTyCon { algTcRhs = rhs })
1977 = case rhs of
1978 DataTyCon { data_cons = [c] } -> Just c
1979 TupleTyCon { data_con = c } -> Just c
1980 _ -> Nothing
1981 tyConSingleAlgDataCon_maybe _ = Nothing
1982
1983 -- | Determine the number of value constructors a 'TyCon' has. Panics if the
1984 -- 'TyCon' is not algebraic or a tuple
1985 tyConFamilySize :: TyCon -> Int
1986 tyConFamilySize tc@(AlgTyCon { algTcRhs = rhs })
1987 = case rhs of
1988 DataTyCon { data_cons = cons } -> length cons
1989 NewTyCon {} -> 1
1990 TupleTyCon {} -> 1
1991 _ -> pprPanic "tyConFamilySize 1" (ppr tc)
1992 tyConFamilySize tc = pprPanic "tyConFamilySize 2" (ppr tc)
1993
1994 -- | Extract an 'AlgTyConRhs' with information about data constructors from an
1995 -- algebraic or tuple 'TyCon'. Panics for any other sort of 'TyCon'
1996 algTyConRhs :: TyCon -> AlgTyConRhs
1997 algTyConRhs (AlgTyCon {algTcRhs = rhs}) = rhs
1998 algTyConRhs other = pprPanic "algTyConRhs" (ppr other)
1999
2000 -- | Extract type variable naming the result of injective type family
2001 tyConFamilyResVar_maybe :: TyCon -> Maybe Name
2002 tyConFamilyResVar_maybe (FamilyTyCon {famTcResVar = res}) = res
2003 tyConFamilyResVar_maybe _ = Nothing
2004
2005 -- | Get the list of roles for the type parameters of a TyCon
2006 tyConRoles :: TyCon -> [Role]
2007 -- See also Note [TyCon Role signatures]
2008 tyConRoles tc
2009 = case tc of
2010 { FunTyCon {} -> const_role Representational
2011 ; AlgTyCon { tcRoles = roles } -> roles
2012 ; SynonymTyCon { tcRoles = roles } -> roles
2013 ; FamilyTyCon {} -> const_role Nominal
2014 ; PrimTyCon { tcRoles = roles } -> roles
2015 ; PromotedDataCon { tcRoles = roles } -> roles
2016 ; TcTyCon {} -> pprPanic "tyConRoles sees a TcTyCon" (ppr tc)
2017 }
2018 where
2019 const_role r = replicate (tyConArity tc) r
2020
2021 -- | Extract the bound type variables and type expansion of a type synonym
2022 -- 'TyCon'. Panics if the 'TyCon' is not a synonym
2023 newTyConRhs :: TyCon -> ([TyVar], Type)
2024 newTyConRhs (AlgTyCon {tyConTyVars = tvs, algTcRhs = NewTyCon { nt_rhs = rhs }})
2025 = (tvs, rhs)
2026 newTyConRhs tycon = pprPanic "newTyConRhs" (ppr tycon)
2027
2028 -- | The number of type parameters that need to be passed to a newtype to
2029 -- resolve it. May be less than in the definition if it can be eta-contracted.
2030 newTyConEtadArity :: TyCon -> Int
2031 newTyConEtadArity (AlgTyCon {algTcRhs = NewTyCon { nt_etad_rhs = tvs_rhs }})
2032 = length (fst tvs_rhs)
2033 newTyConEtadArity tycon = pprPanic "newTyConEtadArity" (ppr tycon)
2034
2035 -- | Extract the bound type variables and type expansion of an eta-contracted
2036 -- type synonym 'TyCon'. Panics if the 'TyCon' is not a synonym
2037 newTyConEtadRhs :: TyCon -> ([TyVar], Type)
2038 newTyConEtadRhs (AlgTyCon {algTcRhs = NewTyCon { nt_etad_rhs = tvs_rhs }}) = tvs_rhs
2039 newTyConEtadRhs tycon = pprPanic "newTyConEtadRhs" (ppr tycon)
2040
2041 -- | Extracts the @newtype@ coercion from such a 'TyCon', which can be used to
2042 -- construct something with the @newtype@s type from its representation type
2043 -- (right hand side). If the supplied 'TyCon' is not a @newtype@, returns
2044 -- @Nothing@
2045 newTyConCo_maybe :: TyCon -> Maybe (CoAxiom Unbranched)
2046 newTyConCo_maybe (AlgTyCon {algTcRhs = NewTyCon { nt_co = co }}) = Just co
2047 newTyConCo_maybe _ = Nothing
2048
2049 newTyConCo :: TyCon -> CoAxiom Unbranched
2050 newTyConCo tc = case newTyConCo_maybe tc of
2051 Just co -> co
2052 Nothing -> pprPanic "newTyConCo" (ppr tc)
2053
2054 -- | Find the \"stupid theta\" of the 'TyCon'. A \"stupid theta\" is the context
2055 -- to the left of an algebraic type declaration, e.g. @Eq a@ in the declaration
2056 -- @data Eq a => T a ...@
2057 tyConStupidTheta :: TyCon -> [PredType]
2058 tyConStupidTheta (AlgTyCon {algTcStupidTheta = stupid}) = stupid
2059 tyConStupidTheta tycon = pprPanic "tyConStupidTheta" (ppr tycon)
2060
2061 -- | Extract the 'TyVar's bound by a vanilla type synonym
2062 -- and the corresponding (unsubstituted) right hand side.
2063 synTyConDefn_maybe :: TyCon -> Maybe ([TyVar], Type)
2064 synTyConDefn_maybe (SynonymTyCon {tyConTyVars = tyvars, synTcRhs = ty})
2065 = Just (tyvars, ty)
2066 synTyConDefn_maybe _ = Nothing
2067
2068 -- | Extract the information pertaining to the right hand side of a type synonym
2069 -- (@type@) declaration.
2070 synTyConRhs_maybe :: TyCon -> Maybe Type
2071 synTyConRhs_maybe (SynonymTyCon {synTcRhs = rhs}) = Just rhs
2072 synTyConRhs_maybe _ = Nothing
2073
2074 -- | Extract the flavour of a type family (with all the extra information that
2075 -- it carries)
2076 famTyConFlav_maybe :: TyCon -> Maybe FamTyConFlav
2077 famTyConFlav_maybe (FamilyTyCon {famTcFlav = flav}) = Just flav
2078 famTyConFlav_maybe _ = Nothing
2079
2080 -- | Is this 'TyCon' that for a class instance?
2081 isClassTyCon :: TyCon -> Bool
2082 isClassTyCon (AlgTyCon {algTcParent = ClassTyCon {}}) = True
2083 isClassTyCon _ = False
2084
2085 -- | If this 'TyCon' is that for a class instance, return the class it is for.
2086 -- Otherwise returns @Nothing@
2087 tyConClass_maybe :: TyCon -> Maybe Class
2088 tyConClass_maybe (AlgTyCon {algTcParent = ClassTyCon clas _}) = Just clas
2089 tyConClass_maybe _ = Nothing
2090
2091 -- | Return the associated types of the 'TyCon', if any
2092 tyConATs :: TyCon -> [TyCon]
2093 tyConATs (AlgTyCon {algTcParent = ClassTyCon clas _}) = classATs clas
2094 tyConATs _ = []
2095
2096 ----------------------------------------------------------------------------
2097 -- | Is this 'TyCon' that for a data family instance?
2098 isFamInstTyCon :: TyCon -> Bool
2099 isFamInstTyCon (AlgTyCon {algTcParent = DataFamInstTyCon {} })
2100 = True
2101 isFamInstTyCon _ = False
2102
2103 tyConFamInstSig_maybe :: TyCon -> Maybe (TyCon, [Type], CoAxiom Unbranched)
2104 tyConFamInstSig_maybe (AlgTyCon {algTcParent = DataFamInstTyCon ax f ts })
2105 = Just (f, ts, ax)
2106 tyConFamInstSig_maybe _ = Nothing
2107
2108 -- | If this 'TyCon' is that of a data family instance, return the family in question
2109 -- and the instance types. Otherwise, return @Nothing@
2110 tyConFamInst_maybe :: TyCon -> Maybe (TyCon, [Type])
2111 tyConFamInst_maybe (AlgTyCon {algTcParent = DataFamInstTyCon _ f ts })
2112 = Just (f, ts)
2113 tyConFamInst_maybe _ = Nothing
2114
2115 -- | If this 'TyCon' is that of a data family instance, return a 'TyCon' which
2116 -- represents a coercion identifying the representation type with the type
2117 -- instance family. Otherwise, return @Nothing@
2118 tyConFamilyCoercion_maybe :: TyCon -> Maybe (CoAxiom Unbranched)
2119 tyConFamilyCoercion_maybe (AlgTyCon {algTcParent = DataFamInstTyCon ax _ _ })
2120 = Just ax
2121 tyConFamilyCoercion_maybe _ = Nothing
2122
2123 -- | Extract any 'RuntimeRepInfo' from this TyCon
2124 tyConRuntimeRepInfo :: TyCon -> RuntimeRepInfo
2125 tyConRuntimeRepInfo (PromotedDataCon { promDcRepInfo = rri }) = rri
2126 tyConRuntimeRepInfo _ = NoRRI
2127 -- could panic in that second case. But Douglas Adams told me not to.
2128
2129 {-
2130 ************************************************************************
2131 * *
2132 \subsection[TyCon-instances]{Instance declarations for @TyCon@}
2133 * *
2134 ************************************************************************
2135
2136 @TyCon@s are compared by comparing their @Unique@s.
2137 -}
2138
2139 instance Eq TyCon where
2140 a == b = getUnique a == getUnique b
2141 a /= b = getUnique a /= getUnique b
2142
2143 instance Ord TyCon where
2144 a <= b = case (a `compare` b) of { LT -> True; EQ -> True; GT -> False }
2145 a < b = case (a `compare` b) of { LT -> True; EQ -> False; GT -> False }
2146 a >= b = case (a `compare` b) of { LT -> False; EQ -> True; GT -> True }
2147 a > b = case (a `compare` b) of { LT -> False; EQ -> False; GT -> True }
2148 compare a b = getUnique a `compare` getUnique b
2149
2150 instance Uniquable TyCon where
2151 getUnique tc = tyConUnique tc
2152
2153 instance Outputable TyCon where
2154 -- At the moment a promoted TyCon has the same Name as its
2155 -- corresponding TyCon, so we add the quote to distinguish it here
2156 ppr tc = pprPromotionQuote tc <> ppr (tyConName tc)
2157
2158 tyConFlavour :: TyCon -> String
2159 tyConFlavour (AlgTyCon { algTcParent = parent, algTcRhs = rhs })
2160 | ClassTyCon _ _ <- parent = "class"
2161 | otherwise = case rhs of
2162 TupleTyCon { tup_sort = sort }
2163 | isBoxed (tupleSortBoxity sort) -> "tuple"
2164 | otherwise -> "unboxed tuple"
2165 DataTyCon {} -> "data type"
2166 NewTyCon {} -> "newtype"
2167 AbstractTyCon {} -> "abstract type"
2168 tyConFlavour (FamilyTyCon { famTcFlav = flav })
2169 | isDataFamFlav flav = "data family"
2170 | otherwise = "type family"
2171 tyConFlavour (SynonymTyCon {}) = "type synonym"
2172 tyConFlavour (FunTyCon {}) = "built-in type"
2173 tyConFlavour (PrimTyCon {}) = "built-in type"
2174 tyConFlavour (PromotedDataCon {}) = "promoted data constructor"
2175 tyConFlavour tc@(TcTyCon {})
2176 = pprPanic "tyConFlavour sees a TcTyCon" (ppr tc)
2177
2178 pprPromotionQuote :: TyCon -> SDoc
2179 -- Promoted data constructors already have a tick in their OccName
2180 pprPromotionQuote tc
2181 = case tc of
2182 PromotedDataCon {} -> char '\'' -- Always quote promoted DataCons in types
2183 _ -> empty
2184
2185 instance NamedThing TyCon where
2186 getName = tyConName
2187
2188 instance Data.Data TyCon where
2189 -- don't traverse?
2190 toConstr _ = abstractConstr "TyCon"
2191 gunfold _ _ = error "gunfold"
2192 dataTypeOf _ = mkNoRepType "TyCon"
2193
2194 instance Binary Injectivity where
2195 put_ bh NotInjective = putByte bh 0
2196 put_ bh (Injective xs) = putByte bh 1 >> put_ bh xs
2197
2198 get bh = do { h <- getByte bh
2199 ; case h of
2200 0 -> return NotInjective
2201 _ -> do { xs <- get bh
2202 ; return (Injective xs) } }
2203
2204 {-
2205 ************************************************************************
2206 * *
2207 Walking over recursive TyCons
2208 * *
2209 ************************************************************************
2210
2211 Note [Expanding newtypes and products]
2212 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2213 When expanding a type to expose a data-type constructor, we need to be
2214 careful about newtypes, lest we fall into an infinite loop. Here are
2215 the key examples:
2216
2217 newtype Id x = MkId x
2218 newtype Fix f = MkFix (f (Fix f))
2219 newtype T = MkT (T -> T)
2220
2221 Type Expansion
2222 --------------------------
2223 T T -> T
2224 Fix Maybe Maybe (Fix Maybe)
2225 Id (Id Int) Int
2226 Fix Id NO NO NO
2227
2228 Notice that
2229 * We can expand T, even though it's recursive.
2230 * We can expand Id (Id Int), even though the Id shows up
2231 twice at the outer level, because Id is non-recursive
2232
2233 So, when expanding, we keep track of when we've seen a recursive
2234 newtype at outermost level; and bale out if we see it again.
2235
2236 We sometimes want to do the same for product types, so that the
2237 strictness analyser doesn't unbox infinitely deeply.
2238
2239 More precisely, we keep a *count* of how many times we've seen it.
2240 This is to account for
2241 data instance T (a,b) = MkT (T a) (T b)
2242 Then (Trac #10482) if we have a type like
2243 T (Int,(Int,(Int,(Int,Int))))
2244 we can still unbox deeply enough during strictness analysis.
2245 We have to treat T as potentially recursive, but it's still
2246 good to be able to unwrap multiple layers.
2247
2248 The function that manages all this is checkRecTc.
2249 -}
2250
2251 data RecTcChecker = RC !Int (NameEnv Int)
2252 -- The upper bound, and the number of times
2253 -- we have encountered each TyCon
2254
2255 initRecTc :: RecTcChecker
2256 -- Intialise with a fixed max bound of 100
2257 -- We should probably have a flag for this
2258 initRecTc = RC 100 emptyNameEnv
2259
2260 checkRecTc :: RecTcChecker -> TyCon -> Maybe RecTcChecker
2261 -- Nothing => Recursion detected
2262 -- Just rec_tcs => Keep going
2263 checkRecTc rc@(RC bound rec_nts) tc
2264 | not (isRecursiveTyCon tc)
2265 = Just rc -- Tuples are a common example here
2266 | otherwise
2267 = case lookupNameEnv rec_nts tc_name of
2268 Just n | n >= bound -> Nothing
2269 | otherwise -> Just (RC bound (extendNameEnv rec_nts tc_name (n+1)))
2270 Nothing -> Just (RC bound (extendNameEnv rec_nts tc_name 1))
2271 where
2272 tc_name = tyConName tc