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