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