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