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