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