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