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