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