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