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