465ccb14b6dd20ca58b64970612a80acafd6e8d8
[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,
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
1038 -- | Make a map from strings to FieldLabels from all the data
1039 -- constructors of this algebraic tycon
1040 fieldsOfAlgTcRhs :: AlgTyConRhs -> FieldLabelEnv
1041 fieldsOfAlgTcRhs rhs = mkFsEnv [ (flLabel fl, fl)
1042 | fl <- dataConsFields (visibleDataCons rhs) ]
1043 where
1044 -- Duplicates in this list will be removed by 'mkFsEnv'
1045 dataConsFields dcs = concatMap dataConFieldLabels dcs
1046
1047
1048 {-
1049 ************************************************************************
1050 * *
1051 \subsection{TyCon Construction}
1052 * *
1053 ************************************************************************
1054
1055 Note: the TyCon constructors all take a Kind as one argument, even though
1056 they could, in principle, work out their Kind from their other arguments.
1057 But to do so they need functions from Types, and that makes a nasty
1058 module mutual-recursion. And they aren't called from many places.
1059 So we compromise, and move their Kind calculation to the call site.
1060 -}
1061
1062 -- | Given the name of the function type constructor and it's kind, create the
1063 -- corresponding 'TyCon'. It is reccomended to use 'TypeRep.funTyCon' if you want
1064 -- this functionality
1065 mkFunTyCon :: Name -> Kind -> TyCon
1066 mkFunTyCon name kind
1067 = FunTyCon {
1068 tyConUnique = nameUnique name,
1069 tyConName = name,
1070 tyConKind = kind,
1071 tyConArity = 2
1072 }
1073
1074 -- | This is the making of an algebraic 'TyCon'. Notably, you have to
1075 -- pass in the generic (in the -XGenerics sense) information about the
1076 -- type constructor - you can get hold of it easily (see Generics
1077 -- module)
1078 mkAlgTyCon :: Name
1079 -> Kind -- ^ Kind of the resulting 'TyCon'
1080 -> [TyVar] -- ^ 'TyVar's scoped over: see 'tyConTyVars'.
1081 -- Arity is inferred from the length of this
1082 -- list
1083 -> [Role] -- ^ The roles for each TyVar
1084 -> Maybe CType -- ^ The C type this type corresponds to
1085 -- when using the CAPI FFI
1086 -> [PredType] -- ^ Stupid theta: see 'algTcStupidTheta'
1087 -> AlgTyConRhs -- ^ Information about dat aconstructors
1088 -> TyConParent
1089 -> RecFlag -- ^ Is the 'TyCon' recursive?
1090 -> Bool -- ^ Was the 'TyCon' declared with GADT syntax?
1091 -> Maybe TyCon -- ^ Promoted version
1092 -> TyCon
1093 mkAlgTyCon name kind tyvars roles cType stupid rhs parent is_rec gadt_syn prom_tc
1094 = AlgTyCon {
1095 tyConName = name,
1096 tyConUnique = nameUnique name,
1097 tyConKind = kind,
1098 tyConArity = length tyvars,
1099 tyConTyVars = tyvars,
1100 tcRoles = roles,
1101 tyConCType = cType,
1102 algTcStupidTheta = stupid,
1103 algTcRhs = rhs,
1104 algTcFields = fieldsOfAlgTcRhs rhs,
1105 algTcParent = ASSERT2( okParent name parent, ppr name $$ ppr parent ) parent,
1106 algTcRec = is_rec,
1107 algTcGadtSyntax = gadt_syn,
1108 tcPromoted = prom_tc
1109 }
1110
1111 -- | Simpler specialization of 'mkAlgTyCon' for classes
1112 mkClassTyCon :: Name -> Kind -> [TyVar] -> [Role] -> AlgTyConRhs -> Class
1113 -> RecFlag -> TyCon
1114 mkClassTyCon name kind tyvars roles rhs clas is_rec
1115 = mkAlgTyCon name kind tyvars roles Nothing [] rhs (ClassTyCon clas)
1116 is_rec False
1117 Nothing -- Class TyCons are not promoted
1118
1119 mkTupleTyCon :: Name
1120 -> Kind -- ^ Kind of the resulting 'TyCon'
1121 -> Arity -- ^ Arity of the tuple
1122 -> [TyVar] -- ^ 'TyVar's scoped over: see 'tyConTyVars'
1123 -> DataCon
1124 -> TupleSort -- ^ Whether the tuple is boxed or unboxed
1125 -> Maybe TyCon -- ^ Promoted version
1126 -> TyConParent
1127 -> TyCon
1128 mkTupleTyCon name kind arity tyvars con sort prom_tc parent
1129 = AlgTyCon {
1130 tyConName = name,
1131 tyConUnique = nameUnique name,
1132 tyConKind = kind,
1133 tyConArity = arity,
1134 tyConTyVars = tyvars,
1135 tcRoles = replicate arity Representational,
1136 tyConCType = Nothing,
1137 algTcStupidTheta = [],
1138 algTcRhs = TupleTyCon { data_con = con, tup_sort = sort },
1139 algTcFields = emptyFsEnv,
1140 algTcParent = parent,
1141 algTcRec = NonRecursive,
1142 algTcGadtSyntax = False,
1143 tcPromoted = prom_tc
1144 }
1145
1146 -- | Create an unlifted primitive 'TyCon', such as @Int#@
1147 mkPrimTyCon :: Name -> Kind -> [Role] -> PrimRep -> TyCon
1148 mkPrimTyCon name kind roles rep
1149 = mkPrimTyCon' name kind roles rep True
1150
1151 -- | Kind constructors
1152 mkKindTyCon :: Name -> Kind -> TyCon
1153 mkKindTyCon name kind
1154 = mkPrimTyCon' name kind [] VoidRep True
1155
1156 -- | Create a lifted primitive 'TyCon' such as @RealWorld@
1157 mkLiftedPrimTyCon :: Name -> Kind -> [Role] -> PrimRep -> TyCon
1158 mkLiftedPrimTyCon name kind roles rep
1159 = mkPrimTyCon' name kind roles rep False
1160
1161 mkPrimTyCon' :: Name -> Kind -> [Role] -> PrimRep -> Bool -> TyCon
1162 mkPrimTyCon' name kind roles rep is_unlifted
1163 = PrimTyCon {
1164 tyConName = name,
1165 tyConUnique = nameUnique name,
1166 tyConKind = kind,
1167 tyConArity = length roles,
1168 tcRoles = roles,
1169 primTyConRep = rep,
1170 isUnLifted = is_unlifted
1171 }
1172
1173 -- | Create a type synonym 'TyCon'
1174 mkSynonymTyCon :: Name -> Kind -> [TyVar] -> [Role] -> Type -> TyCon
1175 mkSynonymTyCon name kind tyvars roles rhs
1176 = SynonymTyCon {
1177 tyConName = name,
1178 tyConUnique = nameUnique name,
1179 tyConKind = kind,
1180 tyConArity = length tyvars,
1181 tyConTyVars = tyvars,
1182 tcRoles = roles,
1183 synTcRhs = rhs
1184 }
1185
1186 -- | Create a type family 'TyCon'
1187 mkFamilyTyCon:: Name -> Kind -> [TyVar] -> Maybe Name -> FamTyConFlav
1188 -> TyConParent -> Injectivity -> TyCon
1189 mkFamilyTyCon name kind tyvars resVar flav parent inj
1190 = FamilyTyCon
1191 { tyConUnique = nameUnique name
1192 , tyConName = name
1193 , tyConKind = kind
1194 , tyConArity = length tyvars
1195 , tyConTyVars = tyvars
1196 , famTcResVar = resVar
1197 , famTcFlav = flav
1198 , famTcParent = parent
1199 , famTcInj = inj
1200 }
1201
1202
1203 -- | Create a promoted data constructor 'TyCon'
1204 -- Somewhat dodgily, we give it the same Name
1205 -- as the data constructor itself; when we pretty-print
1206 -- the TyCon we add a quote; see the Outputable TyCon instance
1207 mkPromotedDataCon :: DataCon -> Name -> Unique -> Kind -> [Role] -> TyCon
1208 mkPromotedDataCon con name unique kind roles
1209 = PromotedDataCon {
1210 tyConName = name,
1211 tyConUnique = unique,
1212 tyConArity = arity,
1213 tcRoles = roles,
1214 tyConKind = kind,
1215 dataCon = con
1216 }
1217 where
1218 arity = length roles
1219
1220 -- | Create a promoted type constructor 'TyCon'
1221 -- Somewhat dodgily, we give it the same Name
1222 -- as the type constructor itself
1223 mkPromotedTyCon :: TyCon -> Kind -> TyCon
1224 mkPromotedTyCon tc kind
1225 = PromotedTyCon {
1226 tyConName = getName tc,
1227 tyConUnique = getUnique tc,
1228 tyConArity = tyConArity tc,
1229 tyConKind = kind,
1230 ty_con = tc
1231 }
1232
1233 isFunTyCon :: TyCon -> Bool
1234 isFunTyCon (FunTyCon {}) = True
1235 isFunTyCon _ = False
1236
1237 -- | Test if the 'TyCon' is algebraic but abstract (invisible data constructors)
1238 isAbstractTyCon :: TyCon -> Bool
1239 isAbstractTyCon (AlgTyCon { algTcRhs = AbstractTyCon {} }) = True
1240 isAbstractTyCon _ = False
1241
1242 -- | Make an algebraic 'TyCon' abstract. Panics if the supplied 'TyCon' is not
1243 -- algebraic
1244 makeTyConAbstract :: TyCon -> TyCon
1245 makeTyConAbstract tc@(AlgTyCon { algTcRhs = rhs })
1246 = tc { algTcRhs = AbstractTyCon (isGenInjAlgRhs rhs) }
1247 makeTyConAbstract tc = pprPanic "makeTyConAbstract" (ppr tc)
1248
1249 -- | Does this 'TyCon' represent something that cannot be defined in Haskell?
1250 isPrimTyCon :: TyCon -> Bool
1251 isPrimTyCon (PrimTyCon {}) = True
1252 isPrimTyCon _ = False
1253
1254 -- | Is this 'TyCon' unlifted (i.e. cannot contain bottom)? Note that this can
1255 -- only be true for primitive and unboxed-tuple 'TyCon's
1256 isUnLiftedTyCon :: TyCon -> Bool
1257 isUnLiftedTyCon (PrimTyCon {isUnLifted = is_unlifted})
1258 = is_unlifted
1259 isUnLiftedTyCon (AlgTyCon { algTcRhs = rhs } )
1260 | TupleTyCon { tup_sort = sort } <- rhs
1261 = not (isBoxed (tupleSortBoxity sort))
1262 isUnLiftedTyCon _ = False
1263
1264 -- | Returns @True@ if the supplied 'TyCon' resulted from either a
1265 -- @data@ or @newtype@ declaration
1266 isAlgTyCon :: TyCon -> Bool
1267 isAlgTyCon (AlgTyCon {}) = True
1268 isAlgTyCon _ = False
1269
1270 isDataTyCon :: TyCon -> Bool
1271 -- ^ Returns @True@ for data types that are /definitely/ represented by
1272 -- heap-allocated constructors. These are scrutinised by Core-level
1273 -- @case@ expressions, and they get info tables allocated for them.
1274 --
1275 -- Generally, the function will be true for all @data@ types and false
1276 -- for @newtype@s, unboxed tuples and type family 'TyCon's. But it is
1277 -- not guaranteed to return @True@ in all cases that it could.
1278 --
1279 -- NB: for a data type family, only the /instance/ 'TyCon's
1280 -- get an info table. The family declaration 'TyCon' does not
1281 isDataTyCon (AlgTyCon {algTcRhs = rhs})
1282 = case rhs of
1283 TupleTyCon { tup_sort = sort }
1284 -> isBoxed (tupleSortBoxity sort)
1285 DataTyCon {} -> True
1286 NewTyCon {} -> False
1287 DataFamilyTyCon {} -> False
1288 AbstractTyCon {} -> False -- We don't know, so return False
1289 isDataTyCon _ = False
1290
1291 -- | 'isInjectiveTyCon' is true of 'TyCon's for which this property holds
1292 -- (where X is the role passed in):
1293 -- If (T a1 b1 c1) ~X (T a2 b2 c2), then (a1 ~X1 a2), (b1 ~X2 b2), and (c1 ~X3 c2)
1294 -- (where X1, X2, and X3, are the roles given by tyConRolesX tc X)
1295 -- See also Note [Decomposing equalities] in TcCanonical
1296 isInjectiveTyCon :: TyCon -> Role -> Bool
1297 isInjectiveTyCon _ Phantom = False
1298 isInjectiveTyCon (FunTyCon {}) _ = True
1299 isInjectiveTyCon (AlgTyCon {}) Nominal = True
1300 isInjectiveTyCon (AlgTyCon {algTcRhs = rhs}) Representational
1301 = isGenInjAlgRhs rhs
1302 isInjectiveTyCon (SynonymTyCon {}) _ = False
1303 isInjectiveTyCon (FamilyTyCon {}) _ = False
1304 isInjectiveTyCon (PrimTyCon {}) _ = True
1305 isInjectiveTyCon (PromotedDataCon {}) _ = True
1306 isInjectiveTyCon (PromotedTyCon {ty_con = tc}) r
1307 = isInjectiveTyCon tc r
1308
1309 -- | 'isGenerativeTyCon' is true of 'TyCon's for which this property holds
1310 -- (where X is the role passed in):
1311 -- If (T tys ~X t), then (t's head ~X T).
1312 -- See also Note [Decomposing equalities] in TcCanonical
1313 isGenerativeTyCon :: TyCon -> Role -> Bool
1314 isGenerativeTyCon = isInjectiveTyCon
1315 -- as it happens, generativity and injectivity coincide, but there's
1316 -- no a priori reason this must be the case
1317
1318 -- | Is this an 'AlgTyConRhs' of a 'TyCon' that is generative and injective
1319 -- with respect to representational equality?
1320 isGenInjAlgRhs :: AlgTyConRhs -> Bool
1321 isGenInjAlgRhs (TupleTyCon {}) = True
1322 isGenInjAlgRhs (DataTyCon {}) = True
1323 isGenInjAlgRhs (DataFamilyTyCon {}) = False
1324 isGenInjAlgRhs (AbstractTyCon distinct) = distinct
1325 isGenInjAlgRhs (NewTyCon {}) = False
1326
1327 -- | Is this 'TyCon' that for a @newtype@
1328 isNewTyCon :: TyCon -> Bool
1329 isNewTyCon (AlgTyCon {algTcRhs = NewTyCon {}}) = True
1330 isNewTyCon _ = False
1331
1332 -- | Take a 'TyCon' apart into the 'TyVar's it scopes over, the 'Type' it expands
1333 -- into, and (possibly) a coercion from the representation type to the @newtype@.
1334 -- Returns @Nothing@ if this is not possible.
1335 unwrapNewTyCon_maybe :: TyCon -> Maybe ([TyVar], Type, CoAxiom Unbranched)
1336 unwrapNewTyCon_maybe (AlgTyCon { tyConTyVars = tvs,
1337 algTcRhs = NewTyCon { nt_co = co,
1338 nt_rhs = rhs }})
1339 = Just (tvs, rhs, co)
1340 unwrapNewTyCon_maybe _ = Nothing
1341
1342 unwrapNewTyConEtad_maybe :: TyCon -> Maybe ([TyVar], Type, CoAxiom Unbranched)
1343 unwrapNewTyConEtad_maybe (AlgTyCon { algTcRhs = NewTyCon { nt_co = co,
1344 nt_etad_rhs = (tvs,rhs) }})
1345 = Just (tvs, rhs, co)
1346 unwrapNewTyConEtad_maybe _ = Nothing
1347
1348 isProductTyCon :: TyCon -> Bool
1349 -- True of datatypes or newtypes that have
1350 -- one, non-existential, data constructor
1351 -- See Note [Product types]
1352 isProductTyCon tc@(AlgTyCon {})
1353 = case algTcRhs tc of
1354 TupleTyCon {} -> True
1355 DataTyCon{ data_cons = [data_con] }
1356 -> null (dataConExTyVars data_con)
1357 NewTyCon {} -> True
1358 _ -> False
1359 isProductTyCon _ = False
1360
1361 isDataProductTyCon_maybe :: TyCon -> Maybe DataCon
1362 -- True of datatypes (not newtypes) with
1363 -- one, vanilla, data constructor
1364 -- See Note [Product types]
1365 isDataProductTyCon_maybe (AlgTyCon { algTcRhs = rhs })
1366 = case rhs of
1367 DataTyCon { data_cons = [con] }
1368 | null (dataConExTyVars con) -- non-existential
1369 -> Just con
1370 TupleTyCon { data_con = con }
1371 -> Just con
1372 _ -> Nothing
1373 isDataProductTyCon_maybe _ = Nothing
1374
1375 {- Note [Product types]
1376 ~~~~~~~~~~~~~~~~~~~~~~~
1377 A product type is
1378 * A data type (not a newtype)
1379 * With one, boxed data constructor
1380 * That binds no existential type variables
1381
1382 The main point is that product types are amenable to unboxing for
1383 * Strict function calls; we can transform
1384 f (D a b) = e
1385 to
1386 fw a b = e
1387 via the worker/wrapper transformation. (Question: couldn't this
1388 work for existentials too?)
1389
1390 * CPR for function results; we can transform
1391 f x y = let ... in D a b
1392 to
1393 fw x y = let ... in (# a, b #)
1394
1395 Note that the data constructor /can/ have evidence arguments: equality
1396 constraints, type classes etc. So it can be GADT. These evidence
1397 arguments are simply value arguments, and should not get in the way.
1398 -}
1399
1400
1401 -- | Is this a 'TyCon' representing a regular H98 type synonym (@type@)?
1402 isTypeSynonymTyCon :: TyCon -> Bool
1403 isTypeSynonymTyCon (SynonymTyCon {}) = True
1404 isTypeSynonymTyCon _ = False
1405
1406
1407 -- As for newtypes, it is in some contexts important to distinguish between
1408 -- closed synonyms and synonym families, as synonym families have no unique
1409 -- right hand side to which a synonym family application can expand.
1410 --
1411
1412 mightBeUnsaturatedTyCon :: TyCon -> Bool
1413 -- True iff we can decompose (T a b c) into ((T a b) c)
1414 -- I.e. is it injective and generative w.r.t nominal equality?
1415 -- That is, if (T a b) ~N d e f, is it always the case that
1416 -- (T ~N d), (a ~N e) and (b ~N f)?
1417 -- Specifically NOT true of synonyms (open and otherwise)
1418 --
1419 -- It'd be unusual to call mightBeUnsaturatedTyCon on a regular H98
1420 -- type synonym, because you should probably have expanded it first
1421 -- But regardless, it's not decomposable
1422 mightBeUnsaturatedTyCon (SynonymTyCon {}) = False
1423 mightBeUnsaturatedTyCon (FamilyTyCon {}) = False
1424 mightBeUnsaturatedTyCon _other = True
1425
1426 -- | Is this an algebraic 'TyCon' declared with the GADT syntax?
1427 isGadtSyntaxTyCon :: TyCon -> Bool
1428 isGadtSyntaxTyCon (AlgTyCon { algTcGadtSyntax = res }) = res
1429 isGadtSyntaxTyCon _ = False
1430
1431 -- | Is this an algebraic 'TyCon' which is just an enumeration of values?
1432 isEnumerationTyCon :: TyCon -> Bool
1433 -- See Note [Enumeration types] in TyCon
1434 isEnumerationTyCon (AlgTyCon { tyConArity = arity, algTcRhs = rhs })
1435 = case rhs of
1436 DataTyCon { is_enum = res } -> res
1437 TupleTyCon {} -> arity == 0
1438 _ -> False
1439 isEnumerationTyCon _ = False
1440
1441 -- | Is this a 'TyCon', synonym or otherwise, that defines a family?
1442 isFamilyTyCon :: TyCon -> Bool
1443 isFamilyTyCon (FamilyTyCon {}) = True
1444 isFamilyTyCon (AlgTyCon {algTcRhs = DataFamilyTyCon {}}) = True
1445 isFamilyTyCon _ = False
1446
1447 -- | Is this a 'TyCon', synonym or otherwise, that defines a family with
1448 -- instances?
1449 isOpenFamilyTyCon :: TyCon -> Bool
1450 isOpenFamilyTyCon (FamilyTyCon {famTcFlav = OpenSynFamilyTyCon }) = True
1451 isOpenFamilyTyCon (AlgTyCon {algTcRhs = DataFamilyTyCon }) = True
1452 isOpenFamilyTyCon _ = False
1453
1454 -- | Is this a synonym 'TyCon' that can have may have further instances appear?
1455 isTypeFamilyTyCon :: TyCon -> Bool
1456 isTypeFamilyTyCon (FamilyTyCon {}) = True
1457 isTypeFamilyTyCon _ = False
1458
1459 -- | Is this an open type family TyCon?
1460 isOpenTypeFamilyTyCon :: TyCon -> Bool
1461 isOpenTypeFamilyTyCon (FamilyTyCon {famTcFlav = OpenSynFamilyTyCon }) = True
1462 isOpenTypeFamilyTyCon _ = False
1463
1464 -- | Is this a non-empty closed type family? Returns 'Nothing' for
1465 -- abstract or empty closed families.
1466 isClosedSynFamilyTyConWithAxiom_maybe :: TyCon -> Maybe (CoAxiom Branched)
1467 isClosedSynFamilyTyConWithAxiom_maybe
1468 (FamilyTyCon {famTcFlav = ClosedSynFamilyTyCon mb}) = mb
1469 isClosedSynFamilyTyConWithAxiom_maybe _ = Nothing
1470
1471 -- | Try to read the injectivity information from a FamilyTyCon. Only
1472 -- FamilyTyCons can be injective so for every other TyCon this function panics.
1473 familyTyConInjectivityInfo :: TyCon -> Injectivity
1474 familyTyConInjectivityInfo (FamilyTyCon { famTcInj = inj }) = inj
1475 familyTyConInjectivityInfo _ = panic "familyTyConInjectivityInfo"
1476
1477 isBuiltInSynFamTyCon_maybe :: TyCon -> Maybe BuiltInSynFamily
1478 isBuiltInSynFamTyCon_maybe
1479 (FamilyTyCon {famTcFlav = BuiltInSynFamTyCon ops }) = Just ops
1480 isBuiltInSynFamTyCon_maybe _ = Nothing
1481
1482 -- | Is this a synonym 'TyCon' that can have may have further instances appear?
1483 isDataFamilyTyCon :: TyCon -> Bool
1484 isDataFamilyTyCon (AlgTyCon {algTcRhs = DataFamilyTyCon {}}) = True
1485 isDataFamilyTyCon _ = False
1486
1487 -- | Are we able to extract information 'TyVar' to class argument list
1488 -- mapping from a given 'TyCon'?
1489 isTyConAssoc :: TyCon -> Bool
1490 isTyConAssoc tc = isJust (tyConAssoc_maybe tc)
1491
1492 tyConAssoc_maybe :: TyCon -> Maybe Class
1493 tyConAssoc_maybe tc = case tyConParent tc of
1494 AssocFamilyTyCon cls -> Just cls
1495 _ -> Nothing
1496
1497 -- The unit tycon didn't used to be classed as a tuple tycon
1498 -- but I thought that was silly so I've undone it
1499 -- If it can't be for some reason, it should be a AlgTyCon
1500 isTupleTyCon :: TyCon -> Bool
1501 -- ^ Does this 'TyCon' represent a tuple?
1502 --
1503 -- NB: when compiling @Data.Tuple@, the tycons won't reply @True@ to
1504 -- 'isTupleTyCon', because they are built as 'AlgTyCons'. However they
1505 -- get spat into the interface file as tuple tycons, so I don't think
1506 -- it matters.
1507 isTupleTyCon (AlgTyCon { algTcRhs = TupleTyCon {} }) = True
1508 isTupleTyCon _ = False
1509
1510 tyConTuple_maybe :: TyCon -> Maybe TupleSort
1511 tyConTuple_maybe (AlgTyCon { algTcRhs = rhs })
1512 | TupleTyCon { tup_sort = sort} <- rhs = Just sort
1513 tyConTuple_maybe _ = Nothing
1514
1515 -- | Is this the 'TyCon' for an unboxed tuple?
1516 isUnboxedTupleTyCon :: TyCon -> Bool
1517 isUnboxedTupleTyCon (AlgTyCon { algTcRhs = rhs })
1518 | TupleTyCon { tup_sort = sort } <- rhs
1519 = not (isBoxed (tupleSortBoxity sort))
1520 isUnboxedTupleTyCon _ = False
1521
1522 -- | Is this the 'TyCon' for a boxed tuple?
1523 isBoxedTupleTyCon :: TyCon -> Bool
1524 isBoxedTupleTyCon (AlgTyCon { algTcRhs = rhs })
1525 | TupleTyCon { tup_sort = sort } <- rhs
1526 = isBoxed (tupleSortBoxity sort)
1527 isBoxedTupleTyCon _ = False
1528
1529 -- | Is this a recursive 'TyCon'?
1530 isRecursiveTyCon :: TyCon -> Bool
1531 isRecursiveTyCon (AlgTyCon {algTcRec = Recursive}) = True
1532 isRecursiveTyCon _ = False
1533
1534 promotableTyCon_maybe :: TyCon -> Maybe TyCon
1535 promotableTyCon_maybe (AlgTyCon { tcPromoted = prom }) = prom
1536 promotableTyCon_maybe _ = Nothing
1537
1538 promoteTyCon :: TyCon -> TyCon
1539 promoteTyCon tc = case promotableTyCon_maybe tc of
1540 Just prom_tc -> prom_tc
1541 Nothing -> pprPanic "promoteTyCon" (ppr tc)
1542
1543 -- | Is this a PromotedTyCon?
1544 isPromotedTyCon :: TyCon -> Bool
1545 isPromotedTyCon (PromotedTyCon {}) = True
1546 isPromotedTyCon _ = False
1547
1548 -- | Retrieves the promoted TyCon if this is a PromotedTyCon;
1549 isPromotedTyCon_maybe :: TyCon -> Maybe TyCon
1550 isPromotedTyCon_maybe (PromotedTyCon { ty_con = tc }) = Just tc
1551 isPromotedTyCon_maybe _ = Nothing
1552
1553 -- | Is this a PromotedDataCon?
1554 isPromotedDataCon :: TyCon -> Bool
1555 isPromotedDataCon (PromotedDataCon {}) = True
1556 isPromotedDataCon _ = False
1557
1558 -- | Retrieves the promoted DataCon if this is a PromotedDataCon;
1559 isPromotedDataCon_maybe :: TyCon -> Maybe DataCon
1560 isPromotedDataCon_maybe (PromotedDataCon { dataCon = dc }) = Just dc
1561 isPromotedDataCon_maybe _ = Nothing
1562
1563 -- | Identifies implicit tycons that, in particular, do not go into interface
1564 -- files (because they are implicitly reconstructed when the interface is
1565 -- read).
1566 --
1567 -- Note that:
1568 --
1569 -- * Associated families are implicit, as they are re-constructed from
1570 -- the class declaration in which they reside, and
1571 --
1572 -- * Family instances are /not/ implicit as they represent the instance body
1573 -- (similar to a @dfun@ does that for a class instance).
1574 --
1575 -- * Tuples are implicit iff they have a wired-in name
1576 -- (namely: boxed and unboxed tupeles are wired-in and implicit,
1577 -- but constraint tuples are not)
1578 isImplicitTyCon :: TyCon -> Bool
1579 isImplicitTyCon (FunTyCon {}) = True
1580 isImplicitTyCon (PrimTyCon {}) = True
1581 isImplicitTyCon (PromotedDataCon {}) = True
1582 isImplicitTyCon (PromotedTyCon {}) = True
1583 isImplicitTyCon (AlgTyCon { algTcRhs = rhs, algTcParent = parent, tyConName = name })
1584 | TupleTyCon {} <- rhs = isWiredInName name
1585 | AssocFamilyTyCon {} <- parent = True
1586 | otherwise = False
1587 isImplicitTyCon (FamilyTyCon { famTcParent = parent })
1588 | AssocFamilyTyCon {} <- parent = True
1589 | otherwise = False
1590 isImplicitTyCon (SynonymTyCon {}) = False
1591
1592 tyConCType_maybe :: TyCon -> Maybe CType
1593 tyConCType_maybe tc@(AlgTyCon {}) = tyConCType tc
1594 tyConCType_maybe _ = Nothing
1595
1596 {-
1597 -----------------------------------------------
1598 -- Expand type-constructor applications
1599 -----------------------------------------------
1600 -}
1601
1602 expandSynTyCon_maybe
1603 :: TyCon
1604 -> [tyco] -- ^ Arguments to 'TyCon'
1605 -> Maybe ([(TyVar,tyco)],
1606 Type,
1607 [tyco]) -- ^ Returns a 'TyVar' substitution, the body
1608 -- type of the synonym (not yet substituted)
1609 -- and any arguments remaining from the
1610 -- application
1611
1612 -- ^ Expand a type synonym application, if any
1613 expandSynTyCon_maybe tc tys
1614 | SynonymTyCon { tyConTyVars = tvs, synTcRhs = rhs } <- tc
1615 , let n_tvs = length tvs
1616 = case n_tvs `compare` length tys of
1617 LT -> Just (tvs `zip` tys, rhs, drop n_tvs tys)
1618 EQ -> Just (tvs `zip` tys, rhs, [])
1619 GT -> Nothing
1620 | otherwise
1621 = Nothing
1622
1623 ----------------
1624
1625 -- | As 'tyConDataCons_maybe', but returns the empty list of constructors if no
1626 -- constructors could be found
1627 tyConDataCons :: TyCon -> [DataCon]
1628 -- It's convenient for tyConDataCons to return the
1629 -- empty list for type synonyms etc
1630 tyConDataCons tycon = tyConDataCons_maybe tycon `orElse` []
1631
1632 -- | Determine the 'DataCon's originating from the given 'TyCon', if the 'TyCon'
1633 -- is the sort that can have any constructors (note: this does not include
1634 -- abstract algebraic types)
1635 tyConDataCons_maybe :: TyCon -> Maybe [DataCon]
1636 tyConDataCons_maybe (AlgTyCon {algTcRhs = rhs})
1637 = case rhs of
1638 DataTyCon { data_cons = cons } -> Just cons
1639 NewTyCon { data_con = con } -> Just [con]
1640 TupleTyCon { data_con = con } -> Just [con]
1641 _ -> Nothing
1642 tyConDataCons_maybe _ = Nothing
1643
1644 -- | If the given 'TyCon' has a /single/ data constructor, i.e. it is a @data@
1645 -- type with one alternative, a tuple type or a @newtype@ then that constructor
1646 -- is returned. If the 'TyCon' has more than one constructor, or represents a
1647 -- primitive or function type constructor then @Nothing@ is returned. In any
1648 -- other case, the function panics
1649 tyConSingleDataCon_maybe :: TyCon -> Maybe DataCon
1650 tyConSingleDataCon_maybe (AlgTyCon { algTcRhs = rhs })
1651 = case rhs of
1652 DataTyCon { data_cons = [c] } -> Just c
1653 TupleTyCon { data_con = c } -> Just c
1654 NewTyCon { data_con = c } -> Just c
1655 _ -> Nothing
1656 tyConSingleDataCon_maybe _ = Nothing
1657
1658 tyConSingleDataCon :: TyCon -> DataCon
1659 tyConSingleDataCon tc
1660 = case tyConSingleDataCon_maybe tc of
1661 Just c -> c
1662 Nothing -> pprPanic "tyConDataCon" (ppr tc)
1663
1664 tyConSingleAlgDataCon_maybe :: TyCon -> Maybe DataCon
1665 -- Returns (Just con) for single-constructor
1666 -- *algebraic* data types *not* newtypes
1667 tyConSingleAlgDataCon_maybe (AlgTyCon { algTcRhs = rhs })
1668 = case rhs of
1669 DataTyCon { data_cons = [c] } -> Just c
1670 TupleTyCon { data_con = c } -> Just c
1671 _ -> Nothing
1672 tyConSingleAlgDataCon_maybe _ = Nothing
1673
1674 -- | Determine the number of value constructors a 'TyCon' has. Panics if the
1675 -- 'TyCon' is not algebraic or a tuple
1676 tyConFamilySize :: TyCon -> Int
1677 tyConFamilySize tc@(AlgTyCon { algTcRhs = rhs })
1678 = case rhs of
1679 DataTyCon { data_cons = cons } -> length cons
1680 NewTyCon {} -> 1
1681 TupleTyCon {} -> 1
1682 DataFamilyTyCon {} -> 0
1683 _ -> pprPanic "tyConFamilySize 1" (ppr tc)
1684 tyConFamilySize tc = pprPanic "tyConFamilySize 2" (ppr tc)
1685
1686 -- | Extract an 'AlgTyConRhs' with information about data constructors from an
1687 -- algebraic or tuple 'TyCon'. Panics for any other sort of 'TyCon'
1688 algTyConRhs :: TyCon -> AlgTyConRhs
1689 algTyConRhs (AlgTyCon {algTcRhs = rhs}) = rhs
1690 algTyConRhs other = pprPanic "algTyConRhs" (ppr other)
1691
1692 -- | Extract type variable naming the result of injective type family
1693 tyConFamilyResVar_maybe :: TyCon -> Maybe Name
1694 tyConFamilyResVar_maybe (FamilyTyCon {famTcResVar = res}) = res
1695 tyConFamilyResVar_maybe _ = Nothing
1696
1697 -- | Get the list of roles for the type parameters of a TyCon
1698 tyConRoles :: TyCon -> [Role]
1699 -- See also Note [TyCon Role signatures]
1700 tyConRoles tc
1701 = case tc of
1702 { FunTyCon {} -> const_role Representational
1703 ; AlgTyCon { tcRoles = roles } -> roles
1704 ; SynonymTyCon { tcRoles = roles } -> roles
1705 ; FamilyTyCon {} -> const_role Nominal
1706 ; PrimTyCon { tcRoles = roles } -> roles
1707 ; PromotedDataCon { tcRoles = roles } -> roles
1708 ; PromotedTyCon {} -> const_role Nominal
1709 }
1710 where
1711 const_role r = replicate (tyConArity tc) r
1712
1713 -- | Extract the bound type variables and type expansion of a type synonym
1714 -- 'TyCon'. Panics if the 'TyCon' is not a synonym
1715 newTyConRhs :: TyCon -> ([TyVar], Type)
1716 newTyConRhs (AlgTyCon {tyConTyVars = tvs, algTcRhs = NewTyCon { nt_rhs = rhs }})
1717 = (tvs, rhs)
1718 newTyConRhs tycon = pprPanic "newTyConRhs" (ppr tycon)
1719
1720 -- | The number of type parameters that need to be passed to a newtype to
1721 -- resolve it. May be less than in the definition if it can be eta-contracted.
1722 newTyConEtadArity :: TyCon -> Int
1723 newTyConEtadArity (AlgTyCon {algTcRhs = NewTyCon { nt_etad_rhs = tvs_rhs }})
1724 = length (fst tvs_rhs)
1725 newTyConEtadArity tycon = pprPanic "newTyConEtadArity" (ppr tycon)
1726
1727 -- | Extract the bound type variables and type expansion of an eta-contracted
1728 -- type synonym 'TyCon'. Panics if the 'TyCon' is not a synonym
1729 newTyConEtadRhs :: TyCon -> ([TyVar], Type)
1730 newTyConEtadRhs (AlgTyCon {algTcRhs = NewTyCon { nt_etad_rhs = tvs_rhs }}) = tvs_rhs
1731 newTyConEtadRhs tycon = pprPanic "newTyConEtadRhs" (ppr tycon)
1732
1733 -- | Extracts the @newtype@ coercion from such a 'TyCon', which can be used to
1734 -- construct something with the @newtype@s type from its representation type
1735 -- (right hand side). If the supplied 'TyCon' is not a @newtype@, returns
1736 -- @Nothing@
1737 newTyConCo_maybe :: TyCon -> Maybe (CoAxiom Unbranched)
1738 newTyConCo_maybe (AlgTyCon {algTcRhs = NewTyCon { nt_co = co }}) = Just co
1739 newTyConCo_maybe _ = Nothing
1740
1741 newTyConCo :: TyCon -> CoAxiom Unbranched
1742 newTyConCo tc = case newTyConCo_maybe tc of
1743 Just co -> co
1744 Nothing -> pprPanic "newTyConCo" (ppr tc)
1745
1746 -- | Find the primitive representation of a 'TyCon'
1747 tyConPrimRep :: TyCon -> PrimRep
1748 tyConPrimRep (PrimTyCon {primTyConRep = rep}) = rep
1749 tyConPrimRep tc = ASSERT(not (isUnboxedTupleTyCon tc)) PtrRep
1750
1751 -- | Find the \"stupid theta\" of the 'TyCon'. A \"stupid theta\" is the context
1752 -- to the left of an algebraic type declaration, e.g. @Eq a@ in the declaration
1753 -- @data Eq a => T a ...@
1754 tyConStupidTheta :: TyCon -> [PredType]
1755 tyConStupidTheta (AlgTyCon {algTcStupidTheta = stupid}) = stupid
1756 tyConStupidTheta tycon = pprPanic "tyConStupidTheta" (ppr tycon)
1757
1758 -- | Extract the 'TyVar's bound by a vanilla type synonym
1759 -- and the corresponding (unsubstituted) right hand side.
1760 synTyConDefn_maybe :: TyCon -> Maybe ([TyVar], Type)
1761 synTyConDefn_maybe (SynonymTyCon {tyConTyVars = tyvars, synTcRhs = ty})
1762 = Just (tyvars, ty)
1763 synTyConDefn_maybe _ = Nothing
1764
1765 -- | Extract the information pertaining to the right hand side of a type synonym
1766 -- (@type@) declaration.
1767 synTyConRhs_maybe :: TyCon -> Maybe Type
1768 synTyConRhs_maybe (SynonymTyCon {synTcRhs = rhs}) = Just rhs
1769 synTyConRhs_maybe _ = Nothing
1770
1771 -- | Extract the flavour of a type family (with all the extra information that
1772 -- it carries)
1773 famTyConFlav_maybe :: TyCon -> Maybe FamTyConFlav
1774 famTyConFlav_maybe (FamilyTyCon {famTcFlav = flav}) = Just flav
1775 famTyConFlav_maybe _ = Nothing
1776
1777 -- | Is this 'TyCon' that for a class instance?
1778 isClassTyCon :: TyCon -> Bool
1779 isClassTyCon (AlgTyCon {algTcParent = ClassTyCon _}) = True
1780 isClassTyCon _ = False
1781
1782 -- | If this 'TyCon' is that for a class instance, return the class it is for.
1783 -- Otherwise returns @Nothing@
1784 tyConClass_maybe :: TyCon -> Maybe Class
1785 tyConClass_maybe (AlgTyCon {algTcParent = ClassTyCon clas}) = Just clas
1786 tyConClass_maybe _ = Nothing
1787
1788 ----------------------------------------------------------------------------
1789 tyConParent :: TyCon -> TyConParent
1790 tyConParent (AlgTyCon {algTcParent = parent}) = parent
1791 tyConParent (FamilyTyCon {famTcParent = parent}) = parent
1792 tyConParent _ = NoParentTyCon
1793
1794 ----------------------------------------------------------------------------
1795 -- | Is this 'TyCon' that for a data family instance?
1796 isFamInstTyCon :: TyCon -> Bool
1797 isFamInstTyCon tc = case tyConParent tc of
1798 FamInstTyCon {} -> True
1799 _ -> False
1800
1801 tyConFamInstSig_maybe :: TyCon -> Maybe (TyCon, [Type], CoAxiom Unbranched)
1802 tyConFamInstSig_maybe tc
1803 = case tyConParent tc of
1804 FamInstTyCon ax f ts -> Just (f, ts, ax)
1805 _ -> Nothing
1806
1807 -- | If this 'TyCon' is that of a family instance, return the family in question
1808 -- and the instance types. Otherwise, return @Nothing@
1809 tyConFamInst_maybe :: TyCon -> Maybe (TyCon, [Type])
1810 tyConFamInst_maybe tc
1811 = case tyConParent tc of
1812 FamInstTyCon _ f ts -> Just (f, ts)
1813 _ -> Nothing
1814
1815 -- | If this 'TyCon' is that of a family instance, return a 'TyCon' which
1816 -- represents a coercion identifying the representation type with the type
1817 -- instance family. Otherwise, return @Nothing@
1818 tyConFamilyCoercion_maybe :: TyCon -> Maybe (CoAxiom Unbranched)
1819 tyConFamilyCoercion_maybe tc
1820 = case tyConParent tc of
1821 FamInstTyCon co _ _ -> Just co
1822 _ -> Nothing
1823
1824 {-
1825 ************************************************************************
1826 * *
1827 \subsection[TyCon-instances]{Instance declarations for @TyCon@}
1828 * *
1829 ************************************************************************
1830
1831 @TyCon@s are compared by comparing their @Unique@s.
1832
1833 The strictness analyser needs @Ord@. It is a lexicographic order with
1834 the property @(a<=b) || (b<=a)@.
1835 -}
1836
1837 instance Eq TyCon where
1838 a == b = case (a `compare` b) of { EQ -> True; _ -> False }
1839 a /= b = case (a `compare` b) of { EQ -> False; _ -> True }
1840
1841 instance Ord TyCon where
1842 a <= b = case (a `compare` b) of { LT -> True; EQ -> True; GT -> False }
1843 a < b = case (a `compare` b) of { LT -> True; EQ -> False; GT -> False }
1844 a >= b = case (a `compare` b) of { LT -> False; EQ -> True; GT -> True }
1845 a > b = case (a `compare` b) of { LT -> False; EQ -> False; GT -> True }
1846 compare a b = getUnique a `compare` getUnique b
1847
1848 instance Uniquable TyCon where
1849 getUnique tc = tyConUnique tc
1850
1851 instance Outputable TyCon where
1852 -- At the moment a promoted TyCon has the same Name as its
1853 -- corresponding TyCon, so we add the quote to distinguish it here
1854 ppr tc = pprPromotionQuote tc <> ppr (tyConName tc)
1855
1856 tyConFlavour :: TyCon -> String
1857 tyConFlavour (AlgTyCon { algTcParent = parent, algTcRhs = rhs })
1858 | ClassTyCon _ <- parent = "class"
1859 | otherwise = case rhs of
1860 TupleTyCon { tup_sort = sort }
1861 | isBoxed (tupleSortBoxity sort) -> "tuple"
1862 | otherwise -> "unboxed tuple"
1863 DataTyCon {} -> "data type"
1864 NewTyCon {} -> "newtype"
1865 DataFamilyTyCon {} -> "data family"
1866 AbstractTyCon {} -> "abstract type"
1867 tyConFlavour (FamilyTyCon {}) = "type family"
1868 tyConFlavour (SynonymTyCon {}) = "type synonym"
1869 tyConFlavour (FunTyCon {}) = "built-in type"
1870 tyConFlavour (PrimTyCon {}) = "built-in type"
1871 tyConFlavour (PromotedDataCon {}) = "promoted data constructor"
1872 tyConFlavour (PromotedTyCon {}) = "promoted type constructor"
1873
1874 pprPromotionQuote :: TyCon -> SDoc
1875 pprPromotionQuote (PromotedDataCon {}) = char '\'' -- Quote promoted DataCons
1876 -- in types
1877 pprPromotionQuote (PromotedTyCon {}) = ifPprDebug (char '\'')
1878 pprPromotionQuote _ = empty -- However, we don't quote TyCons
1879 -- in kinds e.g.
1880 -- type family T a :: Bool -> *
1881 -- cf Trac #5952.
1882 -- Except with -dppr-debug
1883
1884 instance NamedThing TyCon where
1885 getName = tyConName
1886
1887 instance Data.Data TyCon where
1888 -- don't traverse?
1889 toConstr _ = abstractConstr "TyCon"
1890 gunfold _ _ = error "gunfold"
1891 dataTypeOf _ = mkNoRepType "TyCon"
1892
1893 instance Binary Injectivity where
1894 put_ bh NotInjective = putByte bh 0
1895 put_ bh (Injective xs) = putByte bh 1 >> put_ bh xs
1896
1897 get bh = do { h <- getByte bh
1898 ; case h of
1899 0 -> return NotInjective
1900 _ -> do { xs <- get bh
1901 ; return (Injective xs) } }
1902
1903 {-
1904 ************************************************************************
1905 * *
1906 Walking over recursive TyCons
1907 * *
1908 ************************************************************************
1909
1910 Note [Expanding newtypes and products]
1911 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1912 When expanding a type to expose a data-type constructor, we need to be
1913 careful about newtypes, lest we fall into an infinite loop. Here are
1914 the key examples:
1915
1916 newtype Id x = MkId x
1917 newtype Fix f = MkFix (f (Fix f))
1918 newtype T = MkT (T -> T)
1919
1920 Type Expansion
1921 --------------------------
1922 T T -> T
1923 Fix Maybe Maybe (Fix Maybe)
1924 Id (Id Int) Int
1925 Fix Id NO NO NO
1926
1927 Notice that
1928 * We can expand T, even though it's recursive.
1929 * We can expand Id (Id Int), even though the Id shows up
1930 twice at the outer level, because Id is non-recursive
1931
1932 So, when expanding, we keep track of when we've seen a recursive
1933 newtype at outermost level; and bale out if we see it again.
1934
1935 We sometimes want to do the same for product types, so that the
1936 strictness analyser doesn't unbox infinitely deeply.
1937
1938 More precisely, we keep a *count* of how many times we've seen it.
1939 This is to account for
1940 data instance T (a,b) = MkT (T a) (T b)
1941 Then (Trac #10482) if we have a type like
1942 T (Int,(Int,(Int,(Int,Int))))
1943 we can still unbox deeply enough during strictness analysis.
1944 We have to treat T as potentially recursive, but it's still
1945 good to be able to unwrap multiple layers.
1946
1947 The function that manages all this is checkRecTc.
1948 -}
1949
1950 data RecTcChecker = RC !Int (NameEnv Int)
1951 -- The upper bound, and the number of times
1952 -- we have encountered each TyCon
1953
1954 initRecTc :: RecTcChecker
1955 -- Intialise with a fixed max bound of 100
1956 -- We should probably have a flag for this
1957 initRecTc = RC 100 emptyNameEnv
1958
1959 checkRecTc :: RecTcChecker -> TyCon -> Maybe RecTcChecker
1960 -- Nothing => Recursion detected
1961 -- Just rec_tcs => Keep going
1962 checkRecTc rc@(RC bound rec_nts) tc
1963 | not (isRecursiveTyCon tc)
1964 = Just rc -- Tuples are a common example here
1965 | otherwise
1966 = case lookupNameEnv rec_nts tc_name of
1967 Just n | n >= bound -> Nothing
1968 | otherwise -> Just (RC bound (extendNameEnv rec_nts tc_name (n+1)))
1969 Nothing -> Just (RC bound (extendNameEnv rec_nts tc_name 1))
1970 where
1971 tc_name = tyConName tc