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