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