Clarify some comments around injectivity.
[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 mightBeUnsaturatedTyCon,
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, isInjectiveTyCon, isGenerativeTyCon, isGenInjAlgRhs,
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 (isGenInjAlgRhs 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 -- | 'isInjectiveTyCon' is true of 'TyCon's for which this property holds
1214 -- (where X is the role passed in):
1215 -- If (T a1 b1 c1) ~X (T a2 b2 c2), then (a1 ~X1 a2), (b1 ~X2 b2), and (c1 ~X3 c2)
1216 -- (where X1, X2, and X3, are the roles given by tyConRolesX tc X)
1217 -- See also Note [Decomposing equalities] in TcCanonical
1218 isInjectiveTyCon :: TyCon -> Role -> Bool
1219 isInjectiveTyCon _ Phantom = False
1220 isInjectiveTyCon (FunTyCon {}) _ = True
1221 isInjectiveTyCon (AlgTyCon {}) Nominal = True
1222 isInjectiveTyCon (AlgTyCon {algTcRhs = rhs}) Representational
1223 = isGenInjAlgRhs rhs
1224 isInjectiveTyCon (SynonymTyCon {}) _ = False
1225 isInjectiveTyCon (FamilyTyCon {}) _ = False
1226 isInjectiveTyCon (PrimTyCon {}) _ = True
1227 isInjectiveTyCon (PromotedDataCon {}) _ = True
1228 isInjectiveTyCon (PromotedTyCon {ty_con = tc}) r
1229 = isInjectiveTyCon tc r
1230
1231 -- | 'isGenerativeTyCon' is true of 'TyCon's for which this property holds
1232 -- (where X is the role passed in):
1233 -- If (T tys ~X t), then (t's head ~X T).
1234 -- See also Note [Decomposing equalities] in TcCanonical
1235 isGenerativeTyCon :: TyCon -> Role -> Bool
1236 isGenerativeTyCon = isInjectiveTyCon
1237 -- as it happens, generativity and injectivity coincide, but there's
1238 -- no a priori reason this must be the case
1239
1240 -- | Is this an 'AlgTyConRhs' of a 'TyCon' that is generative and injective
1241 -- with respect to representational equality?
1242 isGenInjAlgRhs :: AlgTyConRhs -> Bool
1243 isGenInjAlgRhs (TupleTyCon {}) = True
1244 isGenInjAlgRhs (DataTyCon {}) = True
1245 isGenInjAlgRhs (DataFamilyTyCon {}) = False
1246 isGenInjAlgRhs (AbstractTyCon distinct) = distinct
1247 isGenInjAlgRhs (NewTyCon {}) = False
1248
1249 -- | Is this 'TyCon' that for a @newtype@
1250 isNewTyCon :: TyCon -> Bool
1251 isNewTyCon (AlgTyCon {algTcRhs = NewTyCon {}}) = True
1252 isNewTyCon _ = False
1253
1254 -- | Take a 'TyCon' apart into the 'TyVar's it scopes over, the 'Type' it expands
1255 -- into, and (possibly) a coercion from the representation type to the @newtype@.
1256 -- Returns @Nothing@ if this is not possible.
1257 unwrapNewTyCon_maybe :: TyCon -> Maybe ([TyVar], Type, CoAxiom Unbranched)
1258 unwrapNewTyCon_maybe (AlgTyCon { tyConTyVars = tvs,
1259 algTcRhs = NewTyCon { nt_co = co,
1260 nt_rhs = rhs }})
1261 = Just (tvs, rhs, co)
1262 unwrapNewTyCon_maybe _ = Nothing
1263
1264 unwrapNewTyConEtad_maybe :: TyCon -> Maybe ([TyVar], Type, CoAxiom Unbranched)
1265 unwrapNewTyConEtad_maybe (AlgTyCon { algTcRhs = NewTyCon { nt_co = co,
1266 nt_etad_rhs = (tvs,rhs) }})
1267 = Just (tvs, rhs, co)
1268 unwrapNewTyConEtad_maybe _ = Nothing
1269
1270 isProductTyCon :: TyCon -> Bool
1271 -- True of datatypes or newtypes that have
1272 -- one, non-existential, data constructor
1273 -- See Note [Product types]
1274 isProductTyCon tc@(AlgTyCon {})
1275 = case algTcRhs tc of
1276 TupleTyCon {} -> True
1277 DataTyCon{ data_cons = [data_con] }
1278 -> null (dataConExTyVars data_con)
1279 NewTyCon {} -> True
1280 _ -> False
1281 isProductTyCon _ = False
1282
1283 isDataProductTyCon_maybe :: TyCon -> Maybe DataCon
1284 -- True of datatypes (not newtypes) with
1285 -- one, vanilla, data constructor
1286 -- See Note [Product types]
1287 isDataProductTyCon_maybe (AlgTyCon { algTcRhs = rhs })
1288 = case rhs of
1289 DataTyCon { data_cons = [con] }
1290 | null (dataConExTyVars con) -- non-existential
1291 -> Just con
1292 TupleTyCon { data_con = con }
1293 -> Just con
1294 _ -> Nothing
1295 isDataProductTyCon_maybe _ = Nothing
1296
1297 {- Note [Product types]
1298 ~~~~~~~~~~~~~~~~~~~~~~~
1299 A product type is
1300 * A data type (not a newtype)
1301 * With one, boxed data constructor
1302 * That binds no existential type variables
1303
1304 The main point is that product types are amenable to unboxing for
1305 * Strict function calls; we can transform
1306 f (D a b) = e
1307 to
1308 fw a b = e
1309 via the worker/wrapper transformation. (Question: couldn't this
1310 work for existentials too?)
1311
1312 * CPR for function results; we can transform
1313 f x y = let ... in D a b
1314 to
1315 fw x y = let ... in (# a, b #)
1316
1317 Note that the data constructor /can/ have evidence arguments: equality
1318 constraints, type classes etc. So it can be GADT. These evidence
1319 arguments are simply value arguments, and should not get in the way.
1320 -}
1321
1322
1323 -- | Is this a 'TyCon' representing a regular H98 type synonym (@type@)?
1324 isTypeSynonymTyCon :: TyCon -> Bool
1325 isTypeSynonymTyCon (SynonymTyCon {}) = True
1326 isTypeSynonymTyCon _ = False
1327
1328
1329 -- As for newtypes, it is in some contexts important to distinguish between
1330 -- closed synonyms and synonym families, as synonym families have no unique
1331 -- right hand side to which a synonym family application can expand.
1332 --
1333
1334 mightBeUnsaturatedTyCon :: TyCon -> Bool
1335 -- True iff we can decompose (T a b c) into ((T a b) c)
1336 -- I.e. is it injective and generative w.r.t nominal equality?
1337 -- That is, if (T a b) ~N d e f, is it always the case that
1338 -- (T ~N d), (a ~N e) and (b ~N f)?
1339 -- Specifically NOT true of synonyms (open and otherwise)
1340 --
1341 -- It'd be unusual to call mightBeUnsaturatedTyCon on a regular H98
1342 -- type synonym, because you should probably have expanded it first
1343 -- But regardless, it's not decomposable
1344 mightBeUnsaturatedTyCon (SynonymTyCon {}) = False
1345 mightBeUnsaturatedTyCon (FamilyTyCon {}) = False
1346 mightBeUnsaturatedTyCon _other = True
1347
1348 -- | Is this an algebraic 'TyCon' declared with the GADT syntax?
1349 isGadtSyntaxTyCon :: TyCon -> Bool
1350 isGadtSyntaxTyCon (AlgTyCon { algTcGadtSyntax = res }) = res
1351 isGadtSyntaxTyCon _ = False
1352
1353 -- | Is this an algebraic 'TyCon' which is just an enumeration of values?
1354 isEnumerationTyCon :: TyCon -> Bool
1355 -- See Note [Enumeration types] in TyCon
1356 isEnumerationTyCon (AlgTyCon { tyConArity = arity, algTcRhs = rhs })
1357 = case rhs of
1358 DataTyCon { is_enum = res } -> res
1359 TupleTyCon {} -> arity == 0
1360 _ -> False
1361 isEnumerationTyCon _ = False
1362
1363 -- | Is this a 'TyCon', synonym or otherwise, that defines a family?
1364 isFamilyTyCon :: TyCon -> Bool
1365 isFamilyTyCon (FamilyTyCon {}) = True
1366 isFamilyTyCon (AlgTyCon {algTcRhs = DataFamilyTyCon {}}) = True
1367 isFamilyTyCon _ = False
1368
1369 -- | Is this a 'TyCon', synonym or otherwise, that defines a family with
1370 -- instances?
1371 isOpenFamilyTyCon :: TyCon -> Bool
1372 isOpenFamilyTyCon (FamilyTyCon {famTcFlav = OpenSynFamilyTyCon }) = True
1373 isOpenFamilyTyCon (AlgTyCon {algTcRhs = DataFamilyTyCon }) = True
1374 isOpenFamilyTyCon _ = False
1375
1376 -- | Is this a synonym 'TyCon' that can have may have further instances appear?
1377 isTypeFamilyTyCon :: TyCon -> Bool
1378 isTypeFamilyTyCon (FamilyTyCon {}) = True
1379 isTypeFamilyTyCon _ = False
1380
1381 isOpenTypeFamilyTyCon :: TyCon -> Bool
1382 isOpenTypeFamilyTyCon (FamilyTyCon {famTcFlav = OpenSynFamilyTyCon }) = True
1383 isOpenTypeFamilyTyCon _ = False
1384
1385 -- | Is this a non-empty closed type family? Returns 'Nothing' for
1386 -- abstract or empty closed families.
1387 isClosedSynFamilyTyConWithAxiom_maybe :: TyCon -> Maybe (CoAxiom Branched)
1388 isClosedSynFamilyTyConWithAxiom_maybe
1389 (FamilyTyCon {famTcFlav = ClosedSynFamilyTyCon mb}) = mb
1390 isClosedSynFamilyTyConWithAxiom_maybe _ = Nothing
1391
1392 isBuiltInSynFamTyCon_maybe :: TyCon -> Maybe BuiltInSynFamily
1393 isBuiltInSynFamTyCon_maybe
1394 (FamilyTyCon {famTcFlav = BuiltInSynFamTyCon ops }) = Just ops
1395 isBuiltInSynFamTyCon_maybe _ = Nothing
1396
1397 -- | Is this a synonym 'TyCon' that can have may have further instances appear?
1398 isDataFamilyTyCon :: TyCon -> Bool
1399 isDataFamilyTyCon (AlgTyCon {algTcRhs = DataFamilyTyCon {}}) = True
1400 isDataFamilyTyCon _ = False
1401
1402 -- | Are we able to extract informationa 'TyVar' to class argument list
1403 -- mappping from a given 'TyCon'?
1404 isTyConAssoc :: TyCon -> Bool
1405 isTyConAssoc tc = isJust (tyConAssoc_maybe tc)
1406
1407 tyConAssoc_maybe :: TyCon -> Maybe Class
1408 tyConAssoc_maybe tc = case tyConParent tc of
1409 AssocFamilyTyCon cls -> Just cls
1410 _ -> Nothing
1411
1412 -- The unit tycon didn't used to be classed as a tuple tycon
1413 -- but I thought that was silly so I've undone it
1414 -- If it can't be for some reason, it should be a AlgTyCon
1415 isTupleTyCon :: TyCon -> Bool
1416 -- ^ Does this 'TyCon' represent a tuple?
1417 --
1418 -- NB: when compiling @Data.Tuple@, the tycons won't reply @True@ to
1419 -- 'isTupleTyCon', because they are built as 'AlgTyCons'. However they
1420 -- get spat into the interface file as tuple tycons, so I don't think
1421 -- it matters.
1422 isTupleTyCon (AlgTyCon { algTcRhs = TupleTyCon {} }) = True
1423 isTupleTyCon _ = False
1424
1425 tyConTuple_maybe :: TyCon -> Maybe TupleSort
1426 tyConTuple_maybe (AlgTyCon { algTcRhs = rhs })
1427 | TupleTyCon { tup_sort = sort} <- rhs = Just sort
1428 tyConTuple_maybe _ = Nothing
1429
1430 -- | Is this the 'TyCon' for an unboxed tuple?
1431 isUnboxedTupleTyCon :: TyCon -> Bool
1432 isUnboxedTupleTyCon (AlgTyCon { algTcRhs = rhs })
1433 | TupleTyCon { tup_sort = sort } <- rhs
1434 = not (isBoxed (tupleSortBoxity sort))
1435 isUnboxedTupleTyCon _ = False
1436
1437 -- | Is this the 'TyCon' for a boxed tuple?
1438 isBoxedTupleTyCon :: TyCon -> Bool
1439 isBoxedTupleTyCon (AlgTyCon { algTcRhs = rhs })
1440 | TupleTyCon { tup_sort = sort } <- rhs
1441 = isBoxed (tupleSortBoxity sort)
1442 isBoxedTupleTyCon _ = False
1443
1444 -- | Is this a recursive 'TyCon'?
1445 isRecursiveTyCon :: TyCon -> Bool
1446 isRecursiveTyCon (AlgTyCon {algTcRec = Recursive}) = True
1447 isRecursiveTyCon _ = False
1448
1449 promotableTyCon_maybe :: TyCon -> Maybe TyCon
1450 promotableTyCon_maybe (AlgTyCon { tcPromoted = prom }) = prom
1451 promotableTyCon_maybe _ = Nothing
1452
1453 promoteTyCon :: TyCon -> TyCon
1454 promoteTyCon tc = case promotableTyCon_maybe tc of
1455 Just prom_tc -> prom_tc
1456 Nothing -> pprPanic "promoteTyCon" (ppr tc)
1457
1458 -- | Is this a PromotedTyCon?
1459 isPromotedTyCon :: TyCon -> Bool
1460 isPromotedTyCon (PromotedTyCon {}) = True
1461 isPromotedTyCon _ = False
1462
1463 -- | Retrieves the promoted TyCon if this is a PromotedTyCon;
1464 isPromotedTyCon_maybe :: TyCon -> Maybe TyCon
1465 isPromotedTyCon_maybe (PromotedTyCon { ty_con = tc }) = Just tc
1466 isPromotedTyCon_maybe _ = Nothing
1467
1468 -- | Is this a PromotedDataCon?
1469 isPromotedDataCon :: TyCon -> Bool
1470 isPromotedDataCon (PromotedDataCon {}) = True
1471 isPromotedDataCon _ = False
1472
1473 -- | Retrieves the promoted DataCon if this is a PromotedDataCon;
1474 isPromotedDataCon_maybe :: TyCon -> Maybe DataCon
1475 isPromotedDataCon_maybe (PromotedDataCon { dataCon = dc }) = Just dc
1476 isPromotedDataCon_maybe _ = Nothing
1477
1478 -- | Identifies implicit tycons that, in particular, do not go into interface
1479 -- files (because they are implicitly reconstructed when the interface is
1480 -- read).
1481 --
1482 -- Note that:
1483 --
1484 -- * Associated families are implicit, as they are re-constructed from
1485 -- the class declaration in which they reside, and
1486 --
1487 -- * Family instances are /not/ implicit as they represent the instance body
1488 -- (similar to a @dfun@ does that for a class instance).
1489 --
1490 -- * Tuples are implicit iff they have a wired-in name
1491 -- (namely: boxed and unboxed tupeles are wired-in and implicit,
1492 -- but constraint tuples are not)
1493 isImplicitTyCon :: TyCon -> Bool
1494 isImplicitTyCon (FunTyCon {}) = True
1495 isImplicitTyCon (PrimTyCon {}) = True
1496 isImplicitTyCon (PromotedDataCon {}) = True
1497 isImplicitTyCon (PromotedTyCon {}) = True
1498 isImplicitTyCon (AlgTyCon { algTcRhs = rhs, algTcParent = parent, tyConName = name })
1499 | TupleTyCon {} <- rhs = isWiredInName name
1500 | AssocFamilyTyCon {} <- parent = True
1501 | otherwise = False
1502 isImplicitTyCon (FamilyTyCon { famTcParent = parent })
1503 | AssocFamilyTyCon {} <- parent = True
1504 | otherwise = False
1505 isImplicitTyCon (SynonymTyCon {}) = False
1506
1507 tyConCType_maybe :: TyCon -> Maybe CType
1508 tyConCType_maybe tc@(AlgTyCon {}) = tyConCType tc
1509 tyConCType_maybe _ = Nothing
1510
1511 {-
1512 -----------------------------------------------
1513 -- Expand type-constructor applications
1514 -----------------------------------------------
1515 -}
1516
1517 expandSynTyCon_maybe
1518 :: TyCon
1519 -> [tyco] -- ^ Arguments to 'TyCon'
1520 -> Maybe ([(TyVar,tyco)],
1521 Type,
1522 [tyco]) -- ^ Returns a 'TyVar' substitution, the body
1523 -- type of the synonym (not yet substituted)
1524 -- and any arguments remaining from the
1525 -- application
1526
1527 -- ^ Expand a type synonym application, if any
1528 expandSynTyCon_maybe tc tys
1529 | SynonymTyCon { tyConTyVars = tvs, synTcRhs = rhs } <- tc
1530 , let n_tvs = length tvs
1531 = case n_tvs `compare` length tys of
1532 LT -> Just (tvs `zip` tys, rhs, drop n_tvs tys)
1533 EQ -> Just (tvs `zip` tys, rhs, [])
1534 GT -> Nothing
1535 | otherwise
1536 = Nothing
1537
1538 ----------------
1539
1540 -- | As 'tyConDataCons_maybe', but returns the empty list of constructors if no
1541 -- constructors could be found
1542 tyConDataCons :: TyCon -> [DataCon]
1543 -- It's convenient for tyConDataCons to return the
1544 -- empty list for type synonyms etc
1545 tyConDataCons tycon = tyConDataCons_maybe tycon `orElse` []
1546
1547 -- | Determine the 'DataCon's originating from the given 'TyCon', if the 'TyCon'
1548 -- is the sort that can have any constructors (note: this does not include
1549 -- abstract algebraic types)
1550 tyConDataCons_maybe :: TyCon -> Maybe [DataCon]
1551 tyConDataCons_maybe (AlgTyCon {algTcRhs = rhs})
1552 = case rhs of
1553 DataTyCon { data_cons = cons } -> Just cons
1554 NewTyCon { data_con = con } -> Just [con]
1555 TupleTyCon { data_con = con } -> Just [con]
1556 _ -> Nothing
1557 tyConDataCons_maybe _ = Nothing
1558
1559 -- | If the given 'TyCon' has a /single/ data constructor, i.e. it is a @data@
1560 -- type with one alternative, a tuple type or a @newtype@ then that constructor
1561 -- is returned. If the 'TyCon' has more than one constructor, or represents a
1562 -- primitive or function type constructor then @Nothing@ is returned. In any
1563 -- other case, the function panics
1564 tyConSingleDataCon_maybe :: TyCon -> Maybe DataCon
1565 tyConSingleDataCon_maybe (AlgTyCon { algTcRhs = rhs })
1566 = case rhs of
1567 DataTyCon { data_cons = [c] } -> Just c
1568 TupleTyCon { data_con = c } -> Just c
1569 NewTyCon { data_con = c } -> Just c
1570 _ -> Nothing
1571 tyConSingleDataCon_maybe _ = Nothing
1572
1573 tyConSingleDataCon :: TyCon -> DataCon
1574 tyConSingleDataCon tc
1575 = case tyConSingleDataCon_maybe tc of
1576 Just c -> c
1577 Nothing -> pprPanic "tyConDataCon" (ppr tc)
1578
1579 tyConSingleAlgDataCon_maybe :: TyCon -> Maybe DataCon
1580 -- Returns (Just con) for single-constructor
1581 -- *algebraic* data types *not* newtypes
1582 tyConSingleAlgDataCon_maybe (AlgTyCon { algTcRhs = rhs })
1583 = case rhs of
1584 DataTyCon { data_cons = [c] } -> Just c
1585 TupleTyCon { data_con = c } -> Just c
1586 _ -> Nothing
1587 tyConSingleAlgDataCon_maybe _ = Nothing
1588
1589 -- | Determine the number of value constructors a 'TyCon' has. Panics if the
1590 -- 'TyCon' is not algebraic or a tuple
1591 tyConFamilySize :: TyCon -> Int
1592 tyConFamilySize tc@(AlgTyCon { algTcRhs = rhs })
1593 = case rhs of
1594 DataTyCon { data_cons = cons } -> length cons
1595 NewTyCon {} -> 1
1596 TupleTyCon {} -> 1
1597 DataFamilyTyCon {} -> 0
1598 _ -> pprPanic "tyConFamilySize 1" (ppr tc)
1599 tyConFamilySize tc = pprPanic "tyConFamilySize 2" (ppr tc)
1600
1601 -- | Extract an 'AlgTyConRhs' with information about data constructors from an
1602 -- algebraic or tuple 'TyCon'. Panics for any other sort of 'TyCon'
1603 algTyConRhs :: TyCon -> AlgTyConRhs
1604 algTyConRhs (AlgTyCon {algTcRhs = rhs}) = rhs
1605 algTyConRhs other = pprPanic "algTyConRhs" (ppr other)
1606
1607 -- | Get the list of roles for the type parameters of a TyCon
1608 tyConRoles :: TyCon -> [Role]
1609 -- See also Note [TyCon Role signatures]
1610 tyConRoles tc
1611 = case tc of
1612 { FunTyCon {} -> const_role Representational
1613 ; AlgTyCon { tcRoles = roles } -> roles
1614 ; SynonymTyCon { tcRoles = roles } -> roles
1615 ; FamilyTyCon {} -> const_role Nominal
1616 ; PrimTyCon { tcRoles = roles } -> roles
1617 ; PromotedDataCon { tcRoles = roles } -> roles
1618 ; PromotedTyCon {} -> const_role Nominal
1619 }
1620 where
1621 const_role r = replicate (tyConArity tc) r
1622
1623 -- | Extract the bound type variables and type expansion of a type synonym
1624 -- 'TyCon'. Panics if the 'TyCon' is not a synonym
1625 newTyConRhs :: TyCon -> ([TyVar], Type)
1626 newTyConRhs (AlgTyCon {tyConTyVars = tvs, algTcRhs = NewTyCon { nt_rhs = rhs }})
1627 = (tvs, rhs)
1628 newTyConRhs tycon = pprPanic "newTyConRhs" (ppr tycon)
1629
1630 -- | The number of type parameters that need to be passed to a newtype to
1631 -- resolve it. May be less than in the definition if it can be eta-contracted.
1632 newTyConEtadArity :: TyCon -> Int
1633 newTyConEtadArity (AlgTyCon {algTcRhs = NewTyCon { nt_etad_rhs = tvs_rhs }})
1634 = length (fst tvs_rhs)
1635 newTyConEtadArity tycon = pprPanic "newTyConEtadArity" (ppr tycon)
1636
1637 -- | Extract the bound type variables and type expansion of an eta-contracted
1638 -- type synonym 'TyCon'. Panics if the 'TyCon' is not a synonym
1639 newTyConEtadRhs :: TyCon -> ([TyVar], Type)
1640 newTyConEtadRhs (AlgTyCon {algTcRhs = NewTyCon { nt_etad_rhs = tvs_rhs }}) = tvs_rhs
1641 newTyConEtadRhs tycon = pprPanic "newTyConEtadRhs" (ppr tycon)
1642
1643 -- | Extracts the @newtype@ coercion from such a 'TyCon', which can be used to
1644 -- construct something with the @newtype@s type from its representation type
1645 -- (right hand side). If the supplied 'TyCon' is not a @newtype@, returns
1646 -- @Nothing@
1647 newTyConCo_maybe :: TyCon -> Maybe (CoAxiom Unbranched)
1648 newTyConCo_maybe (AlgTyCon {algTcRhs = NewTyCon { nt_co = co }}) = Just co
1649 newTyConCo_maybe _ = Nothing
1650
1651 newTyConCo :: TyCon -> CoAxiom Unbranched
1652 newTyConCo tc = case newTyConCo_maybe tc of
1653 Just co -> co
1654 Nothing -> pprPanic "newTyConCo" (ppr tc)
1655
1656 -- | Find the primitive representation of a 'TyCon'
1657 tyConPrimRep :: TyCon -> PrimRep
1658 tyConPrimRep (PrimTyCon {primTyConRep = rep}) = rep
1659 tyConPrimRep tc = ASSERT(not (isUnboxedTupleTyCon tc)) PtrRep
1660
1661 -- | Find the \"stupid theta\" of the 'TyCon'. A \"stupid theta\" is the context
1662 -- to the left of an algebraic type declaration, e.g. @Eq a@ in the declaration
1663 -- @data Eq a => T a ...@
1664 tyConStupidTheta :: TyCon -> [PredType]
1665 tyConStupidTheta (AlgTyCon {algTcStupidTheta = stupid}) = stupid
1666 tyConStupidTheta tycon = pprPanic "tyConStupidTheta" (ppr tycon)
1667
1668 -- | Extract the 'TyVar's bound by a vanilla type synonym
1669 -- and the corresponding (unsubstituted) right hand side.
1670 synTyConDefn_maybe :: TyCon -> Maybe ([TyVar], Type)
1671 synTyConDefn_maybe (SynonymTyCon {tyConTyVars = tyvars, synTcRhs = ty})
1672 = Just (tyvars, ty)
1673 synTyConDefn_maybe _ = Nothing
1674
1675 -- | Extract the information pertaining to the right hand side of a type synonym
1676 -- (@type@) declaration.
1677 synTyConRhs_maybe :: TyCon -> Maybe Type
1678 synTyConRhs_maybe (SynonymTyCon {synTcRhs = rhs}) = Just rhs
1679 synTyConRhs_maybe _ = Nothing
1680
1681 -- | Extract the flavour of a type family (with all the extra information that
1682 -- it carries)
1683 famTyConFlav_maybe :: TyCon -> Maybe FamTyConFlav
1684 famTyConFlav_maybe (FamilyTyCon {famTcFlav = flav}) = Just flav
1685 famTyConFlav_maybe _ = Nothing
1686
1687 -- | Is this 'TyCon' that for a class instance?
1688 isClassTyCon :: TyCon -> Bool
1689 isClassTyCon (AlgTyCon {algTcParent = ClassTyCon _}) = True
1690 isClassTyCon _ = False
1691
1692 -- | If this 'TyCon' is that for a class instance, return the class it is for.
1693 -- Otherwise returns @Nothing@
1694 tyConClass_maybe :: TyCon -> Maybe Class
1695 tyConClass_maybe (AlgTyCon {algTcParent = ClassTyCon clas}) = Just clas
1696 tyConClass_maybe _ = Nothing
1697
1698 ----------------------------------------------------------------------------
1699 tyConParent :: TyCon -> TyConParent
1700 tyConParent (AlgTyCon {algTcParent = parent}) = parent
1701 tyConParent (FamilyTyCon {famTcParent = parent}) = parent
1702 tyConParent _ = NoParentTyCon
1703
1704 ----------------------------------------------------------------------------
1705 -- | Is this 'TyCon' that for a data family instance?
1706 isFamInstTyCon :: TyCon -> Bool
1707 isFamInstTyCon tc = case tyConParent tc of
1708 FamInstTyCon {} -> True
1709 _ -> False
1710
1711 tyConFamInstSig_maybe :: TyCon -> Maybe (TyCon, [Type], CoAxiom Unbranched)
1712 tyConFamInstSig_maybe tc
1713 = case tyConParent tc of
1714 FamInstTyCon ax f ts -> Just (f, ts, ax)
1715 _ -> Nothing
1716
1717 -- | If this 'TyCon' is that of a family instance, return the family in question
1718 -- and the instance types. Otherwise, return @Nothing@
1719 tyConFamInst_maybe :: TyCon -> Maybe (TyCon, [Type])
1720 tyConFamInst_maybe tc
1721 = case tyConParent tc of
1722 FamInstTyCon _ f ts -> Just (f, ts)
1723 _ -> Nothing
1724
1725 -- | If this 'TyCon' is that of a family instance, return a 'TyCon' which
1726 -- represents a coercion identifying the representation type with the type
1727 -- instance family. Otherwise, return @Nothing@
1728 tyConFamilyCoercion_maybe :: TyCon -> Maybe (CoAxiom Unbranched)
1729 tyConFamilyCoercion_maybe tc
1730 = case tyConParent tc of
1731 FamInstTyCon co _ _ -> Just co
1732 _ -> Nothing
1733
1734 {-
1735 ************************************************************************
1736 * *
1737 \subsection[TyCon-instances]{Instance declarations for @TyCon@}
1738 * *
1739 ************************************************************************
1740
1741 @TyCon@s are compared by comparing their @Unique@s.
1742
1743 The strictness analyser needs @Ord@. It is a lexicographic order with
1744 the property @(a<=b) || (b<=a)@.
1745 -}
1746
1747 instance Eq TyCon where
1748 a == b = case (a `compare` b) of { EQ -> True; _ -> False }
1749 a /= b = case (a `compare` b) of { EQ -> False; _ -> True }
1750
1751 instance Ord TyCon where
1752 a <= b = case (a `compare` b) of { LT -> True; EQ -> True; GT -> False }
1753 a < b = case (a `compare` b) of { LT -> True; EQ -> False; GT -> False }
1754 a >= b = case (a `compare` b) of { LT -> False; EQ -> True; GT -> True }
1755 a > b = case (a `compare` b) of { LT -> False; EQ -> False; GT -> True }
1756 compare a b = getUnique a `compare` getUnique b
1757
1758 instance Uniquable TyCon where
1759 getUnique tc = tyConUnique tc
1760
1761 instance Outputable TyCon where
1762 -- At the moment a promoted TyCon has the same Name as its
1763 -- corresponding TyCon, so we add the quote to distinguish it here
1764 ppr tc = pprPromotionQuote tc <> ppr (tyConName tc)
1765
1766 pprPromotionQuote :: TyCon -> SDoc
1767 pprPromotionQuote (PromotedDataCon {}) = char '\'' -- Quote promoted DataCons
1768 -- in types
1769 pprPromotionQuote (PromotedTyCon {}) = ifPprDebug (char '\'')
1770 pprPromotionQuote _ = empty -- However, we don't quote TyCons
1771 -- in kinds e.g.
1772 -- type family T a :: Bool -> *
1773 -- cf Trac #5952.
1774 -- Except with -dppr-debug
1775
1776 instance NamedThing TyCon where
1777 getName = tyConName
1778
1779 instance Data.Data TyCon where
1780 -- don't traverse?
1781 toConstr _ = abstractConstr "TyCon"
1782 gunfold _ _ = error "gunfold"
1783 dataTypeOf _ = mkNoRepType "TyCon"
1784
1785 {-
1786 ************************************************************************
1787 * *
1788 Walking over recursive TyCons
1789 * *
1790 ************************************************************************
1791
1792 Note [Expanding newtypes and products]
1793 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1794 When expanding a type to expose a data-type constructor, we need to be
1795 careful about newtypes, lest we fall into an infinite loop. Here are
1796 the key examples:
1797
1798 newtype Id x = MkId x
1799 newtype Fix f = MkFix (f (Fix f))
1800 newtype T = MkT (T -> T)
1801
1802 Type Expansion
1803 --------------------------
1804 T T -> T
1805 Fix Maybe Maybe (Fix Maybe)
1806 Id (Id Int) Int
1807 Fix Id NO NO NO
1808
1809 Notice that we can expand T, even though it's recursive.
1810 And we can expand Id (Id Int), even though the Id shows up
1811 twice at the outer level.
1812
1813 So, when expanding, we keep track of when we've seen a recursive
1814 newtype at outermost level; and bale out if we see it again.
1815
1816 We sometimes want to do the same for product types, so that the
1817 strictness analyser doesn't unbox infinitely deeply.
1818
1819 The function that manages this is checkRecTc.
1820 -}
1821
1822 newtype RecTcChecker = RC NameSet
1823
1824 initRecTc :: RecTcChecker
1825 initRecTc = RC emptyNameSet
1826
1827 checkRecTc :: RecTcChecker -> TyCon -> Maybe RecTcChecker
1828 -- Nothing => Recursion detected
1829 -- Just rec_tcs => Keep going
1830 checkRecTc (RC rec_nts) tc
1831 | not (isRecursiveTyCon tc) = Just (RC rec_nts)
1832 | tc_name `elemNameSet` rec_nts = Nothing
1833 | otherwise = Just (RC (extendNameSet rec_nts tc_name))
1834 where
1835 tc_name = tyConName tc