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