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