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