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