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