Fix #11246.
[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 tyConUnsat :: Bool, -- ^ can this tycon be unsaturated?
602 tyConKind :: Kind
603 }
604 deriving Typeable
605
606
607 -- | Represents right-hand-sides of 'TyCon's for algebraic types
608 data AlgTyConRhs
609
610 -- | Says that we know nothing about this data type, except that
611 -- it's represented by a pointer. Used when we export a data type
612 -- abstractly into an .hi file.
613 = AbstractTyCon
614 Bool -- True <=> It's definitely a distinct data type,
615 -- equal only to itself; ie not a newtype
616 -- False <=> Not sure
617
618 -- | Information about those 'TyCon's derived from a @data@
619 -- declaration. This includes data types with no constructors at
620 -- all.
621 | DataTyCon {
622 data_cons :: [DataCon],
623 -- ^ The data type constructors; can be empty if the
624 -- user declares the type to have no constructors
625 --
626 -- INVARIANT: Kept in order of increasing 'DataCon'
627 -- tag (see the tag assignment in DataCon.mkDataCon)
628
629 is_enum :: Bool -- ^ Cached value: is this an enumeration type?
630 -- See Note [Enumeration types]
631 }
632
633 | TupleTyCon { -- A boxed, unboxed, or constraint tuple
634 data_con :: DataCon, -- NB: it can be an *unboxed* tuple
635 tup_sort :: TupleSort -- ^ Is this a boxed, unboxed or constraint
636 -- tuple?
637 }
638
639 -- | Information about those 'TyCon's derived from a @newtype@ declaration
640 | NewTyCon {
641 data_con :: DataCon, -- ^ The unique constructor for the @newtype@.
642 -- It has no existentials
643
644 nt_rhs :: Type, -- ^ Cached value: the argument type of the
645 -- constructor, which is just the representation
646 -- type of the 'TyCon' (remember that @newtype@s
647 -- do not exist at runtime so need a different
648 -- representation type).
649 --
650 -- The free 'TyVar's of this type are the
651 -- 'tyConTyVars' from the corresponding 'TyCon'
652
653 nt_etad_rhs :: ([TyVar], Type),
654 -- ^ Same as the 'nt_rhs', but this time eta-reduced.
655 -- Hence the list of 'TyVar's in this field may be
656 -- shorter than the declared arity of the 'TyCon'.
657
658 -- See Note [Newtype eta]
659 nt_co :: CoAxiom Unbranched
660 -- The axiom coercion that creates the @newtype@
661 -- from the representation 'Type'.
662
663 -- See Note [Newtype coercions]
664 -- Invariant: arity = #tvs in nt_etad_rhs;
665 -- See Note [Newtype eta]
666 -- Watch out! If any newtypes become transparent
667 -- again check Trac #1072.
668 }
669
670 -- | Extract those 'DataCon's that we are able to learn about. Note
671 -- that visibility in this sense does not correspond to visibility in
672 -- the context of any particular user program!
673 visibleDataCons :: AlgTyConRhs -> [DataCon]
674 visibleDataCons (AbstractTyCon {}) = []
675 visibleDataCons (DataTyCon{ data_cons = cs }) = cs
676 visibleDataCons (NewTyCon{ data_con = c }) = [c]
677 visibleDataCons (TupleTyCon{ data_con = c }) = [c]
678
679 -- ^ Both type classes as well as family instances imply implicit
680 -- type constructors. These implicit type constructors refer to their parent
681 -- structure (ie, the class or family from which they derive) using a type of
682 -- the following form.
683 data AlgTyConFlav
684 = -- | An ordinary type constructor has no parent.
685 VanillaAlgTyCon
686 TyConRepName
687
688 -- | An unboxed type constructor. Note that this carries no TyConRepName
689 -- as it is not representable.
690 | UnboxedAlgTyCon
691
692 -- | Type constructors representing a class dictionary.
693 -- See Note [ATyCon for classes] in TyCoRep
694 | ClassTyCon
695 Class -- INVARIANT: the classTyCon of this Class is the
696 -- current tycon
697 TyConRepName
698
699 -- | Type constructors representing an *instance* of a *data* family.
700 -- Parameters:
701 --
702 -- 1) The type family in question
703 --
704 -- 2) Instance types; free variables are the 'tyConTyVars'
705 -- of the current 'TyCon' (not the family one). INVARIANT:
706 -- the number of types matches the arity of the family 'TyCon'
707 --
708 -- 3) A 'CoTyCon' identifying the representation
709 -- type with the type instance family
710 | DataFamInstTyCon -- See Note [Data type families]
711 (CoAxiom Unbranched) -- The coercion axiom.
712 -- A *Representational* coercion,
713 -- of kind T ty1 ty2 ~R R:T a b c
714 -- where T is the family TyCon,
715 -- and R:T is the representation TyCon (ie this one)
716 -- and a,b,c are the tyConTyVars of this TyCon
717 --
718 -- BUT may be eta-reduced; see TcInstDcls
719 -- Note [Eta reduction for data family axioms]
720
721 -- Cached fields of the CoAxiom, but adjusted to
722 -- use the tyConTyVars of this TyCon
723 TyCon -- The family TyCon
724 [Type] -- Argument types (mentions the tyConTyVars of this TyCon)
725 -- Match in length the tyConTyVars of the family TyCon
726
727 -- E.g. data intance T [a] = ...
728 -- gives a representation tycon:
729 -- data R:TList a = ...
730 -- axiom co a :: T [a] ~ R:TList a
731 -- with R:TList's algTcParent = DataFamInstTyCon T [a] co
732
733 instance Outputable AlgTyConFlav where
734 ppr (VanillaAlgTyCon {}) = text "Vanilla ADT"
735 ppr (UnboxedAlgTyCon {}) = text "Unboxed ADT"
736 ppr (ClassTyCon cls _) = text "Class parent" <+> ppr cls
737 ppr (DataFamInstTyCon _ tc tys) =
738 text "Family parent (family instance)" <+> ppr tc <+> sep (map ppr tys)
739
740 -- | Checks the invariants of a 'AlgTyConFlav' given the appropriate type class
741 -- name, if any
742 okParent :: Name -> AlgTyConFlav -> Bool
743 okParent _ (VanillaAlgTyCon {}) = True
744 okParent _ (UnboxedAlgTyCon) = True
745 okParent tc_name (ClassTyCon cls _) = tc_name == tyConName (classTyCon cls)
746 okParent _ (DataFamInstTyCon _ fam_tc tys) = tyConArity fam_tc == length tys
747
748 isNoParent :: AlgTyConFlav -> Bool
749 isNoParent (VanillaAlgTyCon {}) = True
750 isNoParent _ = False
751
752 --------------------
753
754 data Injectivity
755 = NotInjective
756 | Injective [Bool] -- 1-1 with tyConTyVars (incl kind vars)
757 deriving( Eq )
758
759 -- | Information pertaining to the expansion of a type synonym (@type@)
760 data FamTyConFlav
761 = -- | Represents an open type family without a fixed right hand
762 -- side. Additional instances can appear at any time.
763 --
764 -- These are introduced by either a top level declaration:
765 --
766 -- > data family T a :: *
767 --
768 -- Or an associated data type declaration, within a class declaration:
769 --
770 -- > class C a b where
771 -- > data T b :: *
772 DataFamilyTyCon
773 TyConRepName
774
775 -- | An open type synonym family e.g. @type family F x y :: * -> *@
776 | OpenSynFamilyTyCon
777
778 -- | A closed type synonym family e.g.
779 -- @type family F x where { F Int = Bool }@
780 | ClosedSynFamilyTyCon (Maybe (CoAxiom Branched))
781 -- See Note [Closed type families]
782
783 -- | A closed type synonym family declared in an hs-boot file with
784 -- type family F a where ..
785 | AbstractClosedSynFamilyTyCon
786
787 -- | Built-in type family used by the TypeNats solver
788 | BuiltInSynFamTyCon BuiltInSynFamily
789
790 {-
791 Note [Closed type families]
792 ~~~~~~~~~~~~~~~~~~~~~~~~~
793 * In an open type family you can add new instances later. This is the
794 usual case.
795
796 * In a closed type family you can only put equations where the family
797 is defined.
798
799 A non-empty closed type family has a single axiom with multiple
800 branches, stored in the 'ClosedSynFamilyTyCon' constructor. A closed
801 type family with no equations does not have an axiom, because there is
802 nothing for the axiom to prove!
803
804
805 Note [Promoted data constructors]
806 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
807 All data constructors can be promoted to become a type constructor,
808 via the PromotedDataCon alternative in TyCon.
809
810 * The TyCon promoted from a DataCon has the *same* Name and Unique as
811 the DataCon. Eg. If the data constructor Data.Maybe.Just(unique 78,
812 say) is promoted to a TyCon whose name is Data.Maybe.Just(unique 78)
813
814 * Small note: We promote the *user* type of the DataCon. Eg
815 data T = MkT {-# UNPACK #-} !(Bool, Bool)
816 The promoted kind is
817 MkT :: (Bool,Bool) -> T
818 *not*
819 MkT :: Bool -> Bool -> T
820
821 Note [Enumeration types]
822 ~~~~~~~~~~~~~~~~~~~~~~~~
823 We define datatypes with no constructors to *not* be
824 enumerations; this fixes trac #2578, Otherwise we
825 end up generating an empty table for
826 <mod>_<type>_closure_tbl
827 which is used by tagToEnum# to map Int# to constructors
828 in an enumeration. The empty table apparently upset
829 the linker.
830
831 Moreover, all the data constructor must be enumerations, meaning
832 they have type (forall abc. T a b c). GADTs are not enumerations.
833 For example consider
834 data T a where
835 T1 :: T Int
836 T2 :: T Bool
837 T3 :: T a
838 What would [T1 ..] be? [T1,T3] :: T Int? Easiest thing is to exclude them.
839 See Trac #4528.
840
841 Note [Newtype coercions]
842 ~~~~~~~~~~~~~~~~~~~~~~~~
843 The NewTyCon field nt_co is a CoAxiom which is used for coercing from
844 the representation type of the newtype, to the newtype itself. For
845 example,
846
847 newtype T a = MkT (a -> a)
848
849 the NewTyCon for T will contain nt_co = CoT where CoT t : T t ~ t -> t.
850
851 In the case that the right hand side is a type application
852 ending with the same type variables as the left hand side, we
853 "eta-contract" the coercion. So if we had
854
855 newtype S a = MkT [a]
856
857 then we would generate the arity 0 axiom CoS : S ~ []. The
858 primary reason we do this is to make newtype deriving cleaner.
859
860 In the paper we'd write
861 axiom CoT : (forall t. T t) ~ (forall t. [t])
862 and then when we used CoT at a particular type, s, we'd say
863 CoT @ s
864 which encodes as (TyConApp instCoercionTyCon [TyConApp CoT [], s])
865
866 Note [Newtype eta]
867 ~~~~~~~~~~~~~~~~~~
868 Consider
869 newtype Parser a = MkParser (IO a) deriving Monad
870 Are these two types equal (to Core)?
871 Monad Parser
872 Monad IO
873 which we need to make the derived instance for Monad Parser.
874
875 Well, yes. But to see that easily we eta-reduce the RHS type of
876 Parser, in this case to ([], Froogle), so that even unsaturated applications
877 of Parser will work right. This eta reduction is done when the type
878 constructor is built, and cached in NewTyCon.
879
880 Here's an example that I think showed up in practice
881 Source code:
882 newtype T a = MkT [a]
883 newtype Foo m = MkFoo (forall a. m a -> Int)
884
885 w1 :: Foo []
886 w1 = ...
887
888 w2 :: Foo T
889 w2 = MkFoo (\(MkT x) -> case w1 of MkFoo f -> f x)
890
891 After desugaring, and discarding the data constructors for the newtypes,
892 we get:
893 w2 = w1 `cast` Foo CoT
894 so the coercion tycon CoT must have
895 kind: T ~ []
896 and arity: 0
897
898 ************************************************************************
899 * *
900 TyConRepName
901 * *
902 ********************************************************************* -}
903
904 type TyConRepName = Name -- The Name of the top-level declaration
905 -- $tcMaybe :: Data.Typeable.Internal.TyCon
906 -- $tcMaybe = TyCon { tyConName = "Maybe", ... }
907
908 tyConRepName_maybe :: TyCon -> Maybe TyConRepName
909 tyConRepName_maybe (FunTyCon { tcRepName = rep_nm })
910 = Just rep_nm
911 tyConRepName_maybe (PrimTyCon { primRepName = mb_rep_nm })
912 = mb_rep_nm
913 tyConRepName_maybe (AlgTyCon { algTcParent = parent })
914 | VanillaAlgTyCon rep_nm <- parent = Just rep_nm
915 | ClassTyCon _ rep_nm <- parent = Just rep_nm
916 tyConRepName_maybe (FamilyTyCon { famTcFlav = DataFamilyTyCon rep_nm })
917 = Just rep_nm
918 tyConRepName_maybe (PromotedDataCon { tcRepName = rep_nm })
919 = Just rep_nm
920 tyConRepName_maybe _ = Nothing
921
922 -- | Make a 'Name' for the 'Typeable' representation of the given wired-in type
923 mkPrelTyConRepName :: Name -> TyConRepName
924 -- See Note [Grand plan for Typeable] in 'TcTypeable' in TcTypeable.
925 mkPrelTyConRepName tc_name -- Prelude tc_name is always External,
926 -- so nameModule will work
927 = mkExternalName rep_uniq rep_mod rep_occ (nameSrcSpan tc_name)
928 where
929 name_occ = nameOccName tc_name
930 name_mod = nameModule tc_name
931 name_uniq = nameUnique tc_name
932 rep_uniq | isTcOcc name_occ = tyConRepNameUnique name_uniq
933 | otherwise = dataConRepNameUnique name_uniq
934 (rep_mod, rep_occ) = tyConRepModOcc name_mod name_occ
935
936 -- | The name (and defining module) for the Typeable representation (TyCon) of a
937 -- type constructor.
938 --
939 -- See Note [Grand plan for Typeable] in 'TcTypeable' in TcTypeable.
940 tyConRepModOcc :: Module -> OccName -> (Module, OccName)
941 tyConRepModOcc tc_module tc_occ = (rep_module, mkTyConRepOcc tc_occ)
942 where
943 rep_module
944 | tc_module == gHC_PRIM = gHC_TYPES
945 | otherwise = tc_module
946
947
948 {- *********************************************************************
949 * *
950 PrimRep
951 * *
952 ************************************************************************
953
954 Note [rep swamp]
955
956 GHC has a rich selection of types that represent "primitive types" of
957 one kind or another. Each of them makes a different set of
958 distinctions, and mostly the differences are for good reasons,
959 although it's probably true that we could merge some of these.
960
961 Roughly in order of "includes more information":
962
963 - A Width (cmm/CmmType) is simply a binary value with the specified
964 number of bits. It may represent a signed or unsigned integer, a
965 floating-point value, or an address.
966
967 data Width = W8 | W16 | W32 | W64 | W80 | W128
968
969 - Size, which is used in the native code generator, is Width +
970 floating point information.
971
972 data Size = II8 | II16 | II32 | II64 | FF32 | FF64 | FF80
973
974 it is necessary because e.g. the instruction to move a 64-bit float
975 on x86 (movsd) is different from the instruction to move a 64-bit
976 integer (movq), so the mov instruction is parameterised by Size.
977
978 - CmmType wraps Width with more information: GC ptr, float, or
979 other value.
980
981 data CmmType = CmmType CmmCat Width
982
983 data CmmCat -- "Category" (not exported)
984 = GcPtrCat -- GC pointer
985 | BitsCat -- Non-pointer
986 | FloatCat -- Float
987
988 It is important to have GcPtr information in Cmm, since we generate
989 info tables containing pointerhood for the GC from this. As for
990 why we have float (and not signed/unsigned) here, see Note [Signed
991 vs unsigned].
992
993 - ArgRep makes only the distinctions necessary for the call and
994 return conventions of the STG machine. It is essentially CmmType
995 + void.
996
997 - PrimRep makes a few more distinctions than ArgRep: it divides
998 non-GC-pointers into signed/unsigned and addresses, information
999 that is necessary for passing these values to foreign functions.
1000
1001 There's another tension here: whether the type encodes its size in
1002 bytes, or whether its size depends on the machine word size. Width
1003 and CmmType have the size built-in, whereas ArgRep and PrimRep do not.
1004
1005 This means to turn an ArgRep/PrimRep into a CmmType requires DynFlags.
1006
1007 On the other hand, CmmType includes some "nonsense" values, such as
1008 CmmType GcPtrCat W32 on a 64-bit machine.
1009 -}
1010
1011 -- | A 'PrimRep' is an abstraction of a type. It contains information that
1012 -- the code generator needs in order to pass arguments, return results,
1013 -- and store values of this type.
1014 data PrimRep
1015 = VoidRep
1016 | PtrRep
1017 | IntRep -- ^ Signed, word-sized value
1018 | WordRep -- ^ Unsigned, word-sized value
1019 | Int64Rep -- ^ Signed, 64 bit value (with 32-bit words only)
1020 | Word64Rep -- ^ Unsigned, 64 bit value (with 32-bit words only)
1021 | AddrRep -- ^ A pointer, but /not/ to a Haskell value (use 'PtrRep')
1022 | FloatRep
1023 | DoubleRep
1024 | VecRep Int PrimElemRep -- ^ A vector
1025 deriving( Eq, Show )
1026
1027 data PrimElemRep
1028 = Int8ElemRep
1029 | Int16ElemRep
1030 | Int32ElemRep
1031 | Int64ElemRep
1032 | Word8ElemRep
1033 | Word16ElemRep
1034 | Word32ElemRep
1035 | Word64ElemRep
1036 | FloatElemRep
1037 | DoubleElemRep
1038 deriving( Eq, Show )
1039
1040 instance Outputable PrimRep where
1041 ppr r = text (show r)
1042
1043 instance Outputable PrimElemRep where
1044 ppr r = text (show r)
1045
1046 isVoidRep :: PrimRep -> Bool
1047 isVoidRep VoidRep = True
1048 isVoidRep _other = False
1049
1050 isGcPtrRep :: PrimRep -> Bool
1051 isGcPtrRep PtrRep = True
1052 isGcPtrRep _ = False
1053
1054 -- | Find the size of a 'PrimRep', in words
1055 primRepSizeW :: DynFlags -> PrimRep -> Int
1056 primRepSizeW _ IntRep = 1
1057 primRepSizeW _ WordRep = 1
1058 primRepSizeW dflags Int64Rep = wORD64_SIZE `quot` wORD_SIZE dflags
1059 primRepSizeW dflags Word64Rep = wORD64_SIZE `quot` wORD_SIZE dflags
1060 primRepSizeW _ FloatRep = 1 -- NB. might not take a full word
1061 primRepSizeW dflags DoubleRep = dOUBLE_SIZE dflags `quot` wORD_SIZE dflags
1062 primRepSizeW _ AddrRep = 1
1063 primRepSizeW _ PtrRep = 1
1064 primRepSizeW _ VoidRep = 0
1065 primRepSizeW dflags (VecRep len rep) = len * primElemRepSizeB rep `quot` wORD_SIZE dflags
1066
1067 primElemRepSizeB :: PrimElemRep -> Int
1068 primElemRepSizeB Int8ElemRep = 1
1069 primElemRepSizeB Int16ElemRep = 2
1070 primElemRepSizeB Int32ElemRep = 4
1071 primElemRepSizeB Int64ElemRep = 8
1072 primElemRepSizeB Word8ElemRep = 1
1073 primElemRepSizeB Word16ElemRep = 2
1074 primElemRepSizeB Word32ElemRep = 4
1075 primElemRepSizeB Word64ElemRep = 8
1076 primElemRepSizeB FloatElemRep = 4
1077 primElemRepSizeB DoubleElemRep = 8
1078
1079 -- | Return if Rep stands for floating type,
1080 -- returns Nothing for vector types.
1081 primRepIsFloat :: PrimRep -> Maybe Bool
1082 primRepIsFloat FloatRep = Just True
1083 primRepIsFloat DoubleRep = Just True
1084 primRepIsFloat (VecRep _ _) = Nothing
1085 primRepIsFloat _ = Just False
1086
1087
1088 {-
1089 ************************************************************************
1090 * *
1091 Field labels
1092 * *
1093 ************************************************************************
1094 -}
1095
1096 -- | The labels for the fields of this particular 'TyCon'
1097 tyConFieldLabels :: TyCon -> [FieldLabel]
1098 tyConFieldLabels tc = fsEnvElts $ tyConFieldLabelEnv tc
1099
1100 -- | The labels for the fields of this particular 'TyCon'
1101 tyConFieldLabelEnv :: TyCon -> FieldLabelEnv
1102 tyConFieldLabelEnv tc
1103 | isAlgTyCon tc = algTcFields tc
1104 | otherwise = emptyFsEnv
1105
1106
1107 -- | Make a map from strings to FieldLabels from all the data
1108 -- constructors of this algebraic tycon
1109 fieldsOfAlgTcRhs :: AlgTyConRhs -> FieldLabelEnv
1110 fieldsOfAlgTcRhs rhs = mkFsEnv [ (flLabel fl, fl)
1111 | fl <- dataConsFields (visibleDataCons rhs) ]
1112 where
1113 -- Duplicates in this list will be removed by 'mkFsEnv'
1114 dataConsFields dcs = concatMap dataConFieldLabels dcs
1115
1116
1117 {-
1118 ************************************************************************
1119 * *
1120 \subsection{TyCon Construction}
1121 * *
1122 ************************************************************************
1123
1124 Note: the TyCon constructors all take a Kind as one argument, even though
1125 they could, in principle, work out their Kind from their other arguments.
1126 But to do so they need functions from Types, and that makes a nasty
1127 module mutual-recursion. And they aren't called from many places.
1128 So we compromise, and move their Kind calculation to the call site.
1129 -}
1130
1131 -- | Given the name of the function type constructor and it's kind, create the
1132 -- corresponding 'TyCon'. It is reccomended to use 'TyCoRep.funTyCon' if you want
1133 -- this functionality
1134 mkFunTyCon :: Name -> Kind -> Name -> TyCon
1135 mkFunTyCon name kind rep_nm
1136 = FunTyCon {
1137 tyConUnique = nameUnique name,
1138 tyConName = name,
1139 tyConKind = kind,
1140 tyConArity = 2,
1141 tcRepName = rep_nm
1142 }
1143
1144 -- | This is the making of an algebraic 'TyCon'. Notably, you have to
1145 -- pass in the generic (in the -XGenerics sense) information about the
1146 -- type constructor - you can get hold of it easily (see Generics
1147 -- module)
1148 mkAlgTyCon :: Name
1149 -> Kind -- ^ Kind of the resulting 'TyCon'
1150 -> [TyVar] -- ^ 'TyVar's scoped over: see 'tyConTyVars'.
1151 -- Arity is inferred from the length of this
1152 -- list
1153 -> [Role] -- ^ The roles for each TyVar
1154 -> Maybe CType -- ^ The C type this type corresponds to
1155 -- when using the CAPI FFI
1156 -> [PredType] -- ^ Stupid theta: see 'algTcStupidTheta'
1157 -> AlgTyConRhs -- ^ Information about data constructors
1158 -> AlgTyConFlav -- ^ What flavour is it?
1159 -- (e.g. vanilla, type family)
1160 -> RecFlag -- ^ Is the 'TyCon' recursive?
1161 -> Bool -- ^ Was the 'TyCon' declared with GADT syntax?
1162 -> TyCon
1163 mkAlgTyCon name kind tyvars roles cType stupid rhs parent is_rec gadt_syn
1164 = AlgTyCon {
1165 tyConName = name,
1166 tyConUnique = nameUnique name,
1167 tyConKind = kind,
1168 tyConArity = length tyvars,
1169 tyConTyVars = tyvars,
1170 tcRoles = roles,
1171 tyConCType = cType,
1172 algTcStupidTheta = stupid,
1173 algTcRhs = rhs,
1174 algTcFields = fieldsOfAlgTcRhs rhs,
1175 algTcParent = ASSERT2( okParent name parent, ppr name $$ ppr parent ) parent,
1176 algTcRec = is_rec,
1177 algTcGadtSyntax = gadt_syn
1178 }
1179
1180 -- | Simpler specialization of 'mkAlgTyCon' for classes
1181 mkClassTyCon :: Name -> Kind -> [TyVar] -> [Role] -> AlgTyConRhs -> Class
1182 -> RecFlag -> Name -> TyCon
1183 mkClassTyCon name kind tyvars roles rhs clas is_rec tc_rep_name
1184 = mkAlgTyCon name kind tyvars roles Nothing [] rhs
1185 (ClassTyCon clas tc_rep_name)
1186 is_rec False
1187
1188 mkTupleTyCon :: Name
1189 -> Kind -- ^ Kind of the resulting 'TyCon'
1190 -> Arity -- ^ Arity of the tuple
1191 -> [TyVar] -- ^ 'TyVar's scoped over: see 'tyConTyVars'
1192 -> DataCon
1193 -> TupleSort -- ^ Whether the tuple is boxed or unboxed
1194 -> AlgTyConFlav
1195 -> TyCon
1196 mkTupleTyCon name kind arity tyvars con sort parent
1197 = AlgTyCon {
1198 tyConName = name,
1199 tyConUnique = nameUnique name,
1200 tyConKind = kind,
1201 tyConArity = arity,
1202 tyConTyVars = tyvars,
1203 tcRoles = replicate arity Representational,
1204 tyConCType = Nothing,
1205 algTcStupidTheta = [],
1206 algTcRhs = TupleTyCon { data_con = con,
1207 tup_sort = sort },
1208 algTcFields = emptyFsEnv,
1209 algTcParent = parent,
1210 algTcRec = NonRecursive,
1211 algTcGadtSyntax = False
1212 }
1213
1214 -- | Makes a tycon suitable for use during type-checking.
1215 -- The only real need for this is for printing error messages during
1216 -- a recursive type/class type-checking knot. It has a kind because
1217 -- TcErrors sometimes calls typeKind.
1218 -- See also Note [Kind checking recursive type and class declarations]
1219 -- in TcTyClsDecls.
1220 mkTcTyCon :: Name -> Kind -> Bool -- ^ Can this be unsaturated?
1221 -> TyCon
1222 mkTcTyCon name kind unsat
1223 = TcTyCon { tyConUnique = getUnique name
1224 , tyConName = name
1225 , tyConKind = kind
1226 , tyConUnsat = unsat }
1227
1228 -- | Create an unlifted primitive 'TyCon', such as @Int#@
1229 mkPrimTyCon :: Name -> Kind -> [Role] -> PrimRep -> TyCon
1230 mkPrimTyCon name kind roles rep
1231 = mkPrimTyCon' name kind roles rep True (Just $ mkPrelTyConRepName name)
1232
1233 -- | Kind constructors
1234 mkKindTyCon :: Name -> Kind -> [Role] -> Name -> TyCon
1235 mkKindTyCon name kind roles rep_nm
1236 = tc
1237 where
1238 tc = mkPrimTyCon' name kind roles PtrRep False (Just rep_nm)
1239 -- PtrRep because kinds have kind *.
1240
1241 -- | Create a lifted primitive 'TyCon' such as @RealWorld@
1242 mkLiftedPrimTyCon :: Name -> Kind -> [Role] -> PrimRep -> TyCon
1243 mkLiftedPrimTyCon name kind roles rep
1244 = mkPrimTyCon' name kind roles rep False Nothing
1245
1246 mkPrimTyCon' :: Name -> Kind -> [Role] -> PrimRep
1247 -> Bool -> Maybe TyConRepName -> TyCon
1248 mkPrimTyCon' name kind roles rep is_unlifted rep_nm
1249 = PrimTyCon {
1250 tyConName = name,
1251 tyConUnique = nameUnique name,
1252 tyConKind = kind,
1253 tyConArity = length roles,
1254 tcRoles = roles,
1255 primTyConRep = rep,
1256 isUnlifted = is_unlifted,
1257 primRepName = rep_nm
1258 }
1259
1260 -- | Create a type synonym 'TyCon'
1261 mkSynonymTyCon :: Name -> Kind -> [TyVar] -> [Role] -> Type -> TyCon
1262 mkSynonymTyCon name kind tyvars roles rhs
1263 = SynonymTyCon {
1264 tyConName = name,
1265 tyConUnique = nameUnique name,
1266 tyConKind = kind,
1267 tyConArity = length tyvars,
1268 tyConTyVars = tyvars,
1269 tcRoles = roles,
1270 synTcRhs = rhs
1271 }
1272
1273 -- | Create a type family 'TyCon'
1274 mkFamilyTyCon:: Name -> Kind -> [TyVar] -> Maybe Name -> FamTyConFlav
1275 -> Maybe Class -> Injectivity -> TyCon
1276 mkFamilyTyCon name kind tyvars resVar flav parent inj
1277 = FamilyTyCon
1278 { tyConUnique = nameUnique name
1279 , tyConName = name
1280 , tyConKind = kind
1281 , tyConArity = length tyvars
1282 , tyConTyVars = tyvars
1283 , famTcResVar = resVar
1284 , famTcFlav = flav
1285 , famTcParent = parent
1286 , famTcInj = inj
1287 }
1288
1289
1290 -- | Create a promoted data constructor 'TyCon'
1291 -- Somewhat dodgily, we give it the same Name
1292 -- as the data constructor itself; when we pretty-print
1293 -- the TyCon we add a quote; see the Outputable TyCon instance
1294 mkPromotedDataCon :: DataCon -> Name -> TyConRepName -> Kind -> [Role] -> TyCon
1295 mkPromotedDataCon con name rep_name kind roles
1296 = PromotedDataCon {
1297 tyConUnique = nameUnique name,
1298 tyConName = name,
1299 tyConArity = arity,
1300 tcRoles = roles,
1301 tyConKind = kind,
1302 dataCon = con,
1303 tcRepName = rep_name
1304 }
1305 where
1306 arity = length roles
1307
1308 isFunTyCon :: TyCon -> Bool
1309 isFunTyCon (FunTyCon {}) = True
1310 isFunTyCon _ = False
1311
1312 -- | Test if the 'TyCon' is algebraic but abstract (invisible data constructors)
1313 isAbstractTyCon :: TyCon -> Bool
1314 isAbstractTyCon (AlgTyCon { algTcRhs = AbstractTyCon {} }) = True
1315 isAbstractTyCon _ = False
1316
1317 -- | Make an fake, abstract 'TyCon' from an existing one.
1318 -- Used when recovering from errors
1319 makeTyConAbstract :: TyCon -> TyCon
1320 makeTyConAbstract tc
1321 = PrimTyCon { tyConName = name,
1322 tyConUnique = nameUnique name,
1323 tyConKind = tyConKind tc,
1324 tyConArity = tyConArity tc,
1325 tcRoles = tyConRoles tc,
1326 primTyConRep = PtrRep,
1327 isUnlifted = False,
1328 primRepName = Nothing }
1329 where
1330 name = tyConName tc
1331
1332 -- | Does this 'TyCon' represent something that cannot be defined in Haskell?
1333 isPrimTyCon :: TyCon -> Bool
1334 isPrimTyCon (PrimTyCon {}) = True
1335 isPrimTyCon _ = False
1336
1337 -- | Is this 'TyCon' unlifted (i.e. cannot contain bottom)? Note that this can
1338 -- only be true for primitive and unboxed-tuple 'TyCon's
1339 isUnliftedTyCon :: TyCon -> Bool
1340 isUnliftedTyCon (PrimTyCon {isUnlifted = is_unlifted})
1341 = is_unlifted
1342 isUnliftedTyCon (AlgTyCon { algTcRhs = rhs } )
1343 | TupleTyCon { tup_sort = sort } <- rhs
1344 = not (isBoxed (tupleSortBoxity sort))
1345 isUnliftedTyCon _ = False
1346
1347 -- | Returns @True@ if the supplied 'TyCon' resulted from either a
1348 -- @data@ or @newtype@ declaration
1349 isAlgTyCon :: TyCon -> Bool
1350 isAlgTyCon (AlgTyCon {}) = True
1351 isAlgTyCon _ = False
1352
1353 -- | Returns @True@ for vanilla AlgTyCons -- that is, those created
1354 -- with a @data@ or @newtype@ declaration.
1355 isVanillaAlgTyCon :: TyCon -> Bool
1356 isVanillaAlgTyCon (AlgTyCon { algTcParent = VanillaAlgTyCon _ }) = True
1357 isVanillaAlgTyCon _ = False
1358
1359 isDataTyCon :: TyCon -> Bool
1360 -- ^ Returns @True@ for data types that are /definitely/ represented by
1361 -- heap-allocated constructors. These are scrutinised by Core-level
1362 -- @case@ expressions, and they get info tables allocated for them.
1363 --
1364 -- Generally, the function will be true for all @data@ types and false
1365 -- for @newtype@s, unboxed tuples and type family 'TyCon's. But it is
1366 -- not guaranteed to return @True@ in all cases that it could.
1367 --
1368 -- NB: for a data type family, only the /instance/ 'TyCon's
1369 -- get an info table. The family declaration 'TyCon' does not
1370 isDataTyCon (AlgTyCon {algTcRhs = rhs})
1371 = case rhs of
1372 TupleTyCon { tup_sort = sort }
1373 -> isBoxed (tupleSortBoxity sort)
1374 DataTyCon {} -> True
1375 NewTyCon {} -> False
1376 AbstractTyCon {} -> False -- We don't know, so return False
1377 isDataTyCon _ = False
1378
1379 -- | 'isInjectiveTyCon' is true of 'TyCon's for which this property holds
1380 -- (where X is the role passed in):
1381 -- If (T a1 b1 c1) ~X (T a2 b2 c2), then (a1 ~X1 a2), (b1 ~X2 b2), and (c1 ~X3 c2)
1382 -- (where X1, X2, and X3, are the roles given by tyConRolesX tc X)
1383 -- See also Note [Decomposing equalities] in TcCanonical
1384 isInjectiveTyCon :: TyCon -> Role -> Bool
1385 isInjectiveTyCon _ Phantom = False
1386 isInjectiveTyCon (FunTyCon {}) _ = True
1387 isInjectiveTyCon (AlgTyCon {}) Nominal = True
1388 isInjectiveTyCon (AlgTyCon {algTcRhs = rhs}) Representational
1389 = isGenInjAlgRhs rhs
1390 isInjectiveTyCon (SynonymTyCon {}) _ = False
1391 isInjectiveTyCon (FamilyTyCon { famTcFlav = DataFamilyTyCon _ })
1392 Nominal = True
1393 isInjectiveTyCon (FamilyTyCon { famTcInj = Injective inj }) _ = and inj
1394 isInjectiveTyCon (FamilyTyCon {}) _ = False
1395 isInjectiveTyCon (PrimTyCon {}) _ = True
1396 isInjectiveTyCon (PromotedDataCon {}) _ = True
1397 isInjectiveTyCon tc@(TcTyCon {}) _
1398 = pprPanic "isInjectiveTyCon sees a TcTyCon" (ppr tc)
1399
1400 -- | 'isGenerativeTyCon' is true of 'TyCon's for which this property holds
1401 -- (where X is the role passed in):
1402 -- If (T tys ~X t), then (t's head ~X T).
1403 -- See also Note [Decomposing equalities] in TcCanonical
1404 isGenerativeTyCon :: TyCon -> Role -> Bool
1405 isGenerativeTyCon (FamilyTyCon { famTcFlav = DataFamilyTyCon _ }) Nominal = True
1406 isGenerativeTyCon (FamilyTyCon {}) _ = False
1407 -- in all other cases, injectivity implies generativitiy
1408 isGenerativeTyCon tc r = isInjectiveTyCon tc r
1409
1410 -- | Is this an 'AlgTyConRhs' of a 'TyCon' that is generative and injective
1411 -- with respect to representational equality?
1412 isGenInjAlgRhs :: AlgTyConRhs -> Bool
1413 isGenInjAlgRhs (TupleTyCon {}) = True
1414 isGenInjAlgRhs (DataTyCon {}) = True
1415 isGenInjAlgRhs (AbstractTyCon distinct) = distinct
1416 isGenInjAlgRhs (NewTyCon {}) = False
1417
1418 -- | Is this 'TyCon' that for a @newtype@
1419 isNewTyCon :: TyCon -> Bool
1420 isNewTyCon (AlgTyCon {algTcRhs = NewTyCon {}}) = True
1421 isNewTyCon _ = False
1422
1423 -- | Take a 'TyCon' apart into the 'TyVar's it scopes over, the 'Type' it expands
1424 -- into, and (possibly) a coercion from the representation type to the @newtype@.
1425 -- Returns @Nothing@ if this is not possible.
1426 unwrapNewTyCon_maybe :: TyCon -> Maybe ([TyVar], Type, CoAxiom Unbranched)
1427 unwrapNewTyCon_maybe (AlgTyCon { tyConTyVars = tvs,
1428 algTcRhs = NewTyCon { nt_co = co,
1429 nt_rhs = rhs }})
1430 = Just (tvs, rhs, co)
1431 unwrapNewTyCon_maybe _ = Nothing
1432
1433 unwrapNewTyConEtad_maybe :: TyCon -> Maybe ([TyVar], Type, CoAxiom Unbranched)
1434 unwrapNewTyConEtad_maybe (AlgTyCon { algTcRhs = NewTyCon { nt_co = co,
1435 nt_etad_rhs = (tvs,rhs) }})
1436 = Just (tvs, rhs, co)
1437 unwrapNewTyConEtad_maybe _ = Nothing
1438
1439 isProductTyCon :: TyCon -> Bool
1440 -- True of datatypes or newtypes that have
1441 -- one, non-existential, data constructor
1442 -- See Note [Product types]
1443 isProductTyCon tc@(AlgTyCon {})
1444 = case algTcRhs tc of
1445 TupleTyCon {} -> True
1446 DataTyCon{ data_cons = [data_con] }
1447 -> null (dataConExTyVars data_con)
1448 NewTyCon {} -> True
1449 _ -> False
1450 isProductTyCon _ = False
1451
1452 isDataProductTyCon_maybe :: TyCon -> Maybe DataCon
1453 -- True of datatypes (not newtypes) with
1454 -- one, vanilla, data constructor
1455 -- See Note [Product types]
1456 isDataProductTyCon_maybe (AlgTyCon { algTcRhs = rhs })
1457 = case rhs of
1458 DataTyCon { data_cons = [con] }
1459 | null (dataConExTyVars con) -- non-existential
1460 -> Just con
1461 TupleTyCon { data_con = con }
1462 -> Just con
1463 _ -> Nothing
1464 isDataProductTyCon_maybe _ = Nothing
1465
1466 {- Note [Product types]
1467 ~~~~~~~~~~~~~~~~~~~~~~~
1468 A product type is
1469 * A data type (not a newtype)
1470 * With one, boxed data constructor
1471 * That binds no existential type variables
1472
1473 The main point is that product types are amenable to unboxing for
1474 * Strict function calls; we can transform
1475 f (D a b) = e
1476 to
1477 fw a b = e
1478 via the worker/wrapper transformation. (Question: couldn't this
1479 work for existentials too?)
1480
1481 * CPR for function results; we can transform
1482 f x y = let ... in D a b
1483 to
1484 fw x y = let ... in (# a, b #)
1485
1486 Note that the data constructor /can/ have evidence arguments: equality
1487 constraints, type classes etc. So it can be GADT. These evidence
1488 arguments are simply value arguments, and should not get in the way.
1489 -}
1490
1491
1492 -- | Is this a 'TyCon' representing a regular H98 type synonym (@type@)?
1493 isTypeSynonymTyCon :: TyCon -> Bool
1494 isTypeSynonymTyCon (SynonymTyCon {}) = True
1495 isTypeSynonymTyCon _ = False
1496
1497
1498 -- As for newtypes, it is in some contexts important to distinguish between
1499 -- closed synonyms and synonym families, as synonym families have no unique
1500 -- right hand side to which a synonym family application can expand.
1501 --
1502
1503 -- | True iff we can decompose (T a b c) into ((T a b) c)
1504 -- I.e. is it injective and generative w.r.t nominal equality?
1505 -- That is, if (T a b) ~N d e f, is it always the case that
1506 -- (T ~N d), (a ~N e) and (b ~N f)?
1507 -- Specifically NOT true of synonyms (open and otherwise)
1508 --
1509 -- It'd be unusual to call mightBeUnsaturatedTyCon on a regular H98
1510 -- type synonym, because you should probably have expanded it first
1511 -- But regardless, it's not decomposable
1512 mightBeUnsaturatedTyCon :: TyCon -> Bool
1513 mightBeUnsaturatedTyCon (SynonymTyCon {}) = False
1514 mightBeUnsaturatedTyCon (FamilyTyCon { famTcFlav = flav}) = isDataFamFlav flav
1515 mightBeUnsaturatedTyCon (TcTyCon { tyConUnsat = unsat }) = unsat
1516 mightBeUnsaturatedTyCon _other = True
1517
1518 -- | Is this an algebraic 'TyCon' declared with the GADT syntax?
1519 isGadtSyntaxTyCon :: TyCon -> Bool
1520 isGadtSyntaxTyCon (AlgTyCon { algTcGadtSyntax = res }) = res
1521 isGadtSyntaxTyCon _ = False
1522
1523 -- | Is this an algebraic 'TyCon' which is just an enumeration of values?
1524 isEnumerationTyCon :: TyCon -> Bool
1525 -- See Note [Enumeration types] in TyCon
1526 isEnumerationTyCon (AlgTyCon { tyConArity = arity, algTcRhs = rhs })
1527 = case rhs of
1528 DataTyCon { is_enum = res } -> res
1529 TupleTyCon {} -> arity == 0
1530 _ -> False
1531 isEnumerationTyCon _ = False
1532
1533 -- | Is this a 'TyCon', synonym or otherwise, that defines a family?
1534 isFamilyTyCon :: TyCon -> Bool
1535 isFamilyTyCon (FamilyTyCon {}) = True
1536 isFamilyTyCon _ = False
1537
1538 -- | Is this a 'TyCon', synonym or otherwise, that defines a family with
1539 -- instances?
1540 isOpenFamilyTyCon :: TyCon -> Bool
1541 isOpenFamilyTyCon (FamilyTyCon {famTcFlav = flav })
1542 | OpenSynFamilyTyCon <- flav = True
1543 | DataFamilyTyCon {} <- flav = True
1544 isOpenFamilyTyCon _ = False
1545
1546 -- | Is this a synonym 'TyCon' that can have may have further instances appear?
1547 isTypeFamilyTyCon :: TyCon -> Bool
1548 isTypeFamilyTyCon (FamilyTyCon { famTcFlav = flav }) = not (isDataFamFlav flav)
1549 isTypeFamilyTyCon _ = False
1550
1551 -- | Is this a synonym 'TyCon' that can have may have further instances appear?
1552 isDataFamilyTyCon :: TyCon -> Bool
1553 isDataFamilyTyCon (FamilyTyCon { famTcFlav = flav }) = isDataFamFlav flav
1554 isDataFamilyTyCon _ = False
1555
1556 -- | Is this an open type family TyCon?
1557 isOpenTypeFamilyTyCon :: TyCon -> Bool
1558 isOpenTypeFamilyTyCon (FamilyTyCon {famTcFlav = OpenSynFamilyTyCon }) = True
1559 isOpenTypeFamilyTyCon _ = False
1560
1561 -- | Is this a non-empty closed type family? Returns 'Nothing' for
1562 -- abstract or empty closed families.
1563 isClosedSynFamilyTyConWithAxiom_maybe :: TyCon -> Maybe (CoAxiom Branched)
1564 isClosedSynFamilyTyConWithAxiom_maybe
1565 (FamilyTyCon {famTcFlav = ClosedSynFamilyTyCon mb}) = mb
1566 isClosedSynFamilyTyConWithAxiom_maybe _ = Nothing
1567
1568 -- | Try to read the injectivity information from a FamilyTyCon.
1569 -- For every other TyCon this function panics.
1570 familyTyConInjectivityInfo :: TyCon -> Injectivity
1571 familyTyConInjectivityInfo (FamilyTyCon { famTcInj = inj }) = inj
1572 familyTyConInjectivityInfo _ = panic "familyTyConInjectivityInfo"
1573
1574 isBuiltInSynFamTyCon_maybe :: TyCon -> Maybe BuiltInSynFamily
1575 isBuiltInSynFamTyCon_maybe
1576 (FamilyTyCon {famTcFlav = BuiltInSynFamTyCon ops }) = Just ops
1577 isBuiltInSynFamTyCon_maybe _ = Nothing
1578
1579 isDataFamFlav :: FamTyConFlav -> Bool
1580 isDataFamFlav (DataFamilyTyCon {}) = True -- Data family
1581 isDataFamFlav _ = False -- Type synonym family
1582
1583 -- | Are we able to extract information 'TyVar' to class argument list
1584 -- mapping from a given 'TyCon'?
1585 isTyConAssoc :: TyCon -> Bool
1586 isTyConAssoc tc = isJust (tyConAssoc_maybe tc)
1587
1588 tyConAssoc_maybe :: TyCon -> Maybe Class
1589 tyConAssoc_maybe (FamilyTyCon { famTcParent = mb_cls }) = mb_cls
1590 tyConAssoc_maybe _ = Nothing
1591
1592 -- The unit tycon didn't used to be classed as a tuple tycon
1593 -- but I thought that was silly so I've undone it
1594 -- If it can't be for some reason, it should be a AlgTyCon
1595 isTupleTyCon :: TyCon -> Bool
1596 -- ^ Does this 'TyCon' represent a tuple?
1597 --
1598 -- NB: when compiling @Data.Tuple@, the tycons won't reply @True@ to
1599 -- 'isTupleTyCon', because they are built as 'AlgTyCons'. However they
1600 -- get spat into the interface file as tuple tycons, so I don't think
1601 -- it matters.
1602 isTupleTyCon (AlgTyCon { algTcRhs = TupleTyCon {} }) = True
1603 isTupleTyCon _ = False
1604
1605 tyConTuple_maybe :: TyCon -> Maybe TupleSort
1606 tyConTuple_maybe (AlgTyCon { algTcRhs = rhs })
1607 | TupleTyCon { tup_sort = sort} <- rhs = Just sort
1608 tyConTuple_maybe _ = Nothing
1609
1610 -- | Is this the 'TyCon' for an unboxed tuple?
1611 isUnboxedTupleTyCon :: TyCon -> Bool
1612 isUnboxedTupleTyCon (AlgTyCon { algTcRhs = rhs })
1613 | TupleTyCon { tup_sort = sort } <- rhs
1614 = not (isBoxed (tupleSortBoxity sort))
1615 isUnboxedTupleTyCon _ = False
1616
1617 -- | Is this the 'TyCon' for a boxed tuple?
1618 isBoxedTupleTyCon :: TyCon -> Bool
1619 isBoxedTupleTyCon (AlgTyCon { algTcRhs = rhs })
1620 | TupleTyCon { tup_sort = sort } <- rhs
1621 = isBoxed (tupleSortBoxity sort)
1622 isBoxedTupleTyCon _ = False
1623
1624 -- | Is this a recursive 'TyCon'?
1625 isRecursiveTyCon :: TyCon -> Bool
1626 isRecursiveTyCon (AlgTyCon {algTcRec = Recursive}) = True
1627 isRecursiveTyCon _ = False
1628
1629 -- | Is this a PromotedDataCon?
1630 isPromotedDataCon :: TyCon -> Bool
1631 isPromotedDataCon (PromotedDataCon {}) = True
1632 isPromotedDataCon _ = False
1633
1634 -- | Retrieves the promoted DataCon if this is a PromotedDataCon;
1635 isPromotedDataCon_maybe :: TyCon -> Maybe DataCon
1636 isPromotedDataCon_maybe (PromotedDataCon { dataCon = dc }) = Just dc
1637 isPromotedDataCon_maybe _ = Nothing
1638
1639 -- | Is this tycon really meant for use at the kind level? That is,
1640 -- should it be permitted without -XDataKinds?
1641 isKindTyCon :: TyCon -> Bool
1642 isKindTyCon tc = isLiftedTypeKindTyConName (tyConName tc) ||
1643 tc `hasKey` constraintKindTyConKey ||
1644 tc `hasKey` tYPETyConKey ||
1645 tc `hasKey` levityTyConKey ||
1646 tc `hasKey` liftedDataConKey ||
1647 tc `hasKey` unliftedDataConKey
1648
1649 isLiftedTypeKindTyConName :: Name -> Bool
1650 isLiftedTypeKindTyConName
1651 = (`hasKey` liftedTypeKindTyConKey) <||>
1652 (`hasKey` starKindTyConKey) <||>
1653 (`hasKey` unicodeStarKindTyConKey)
1654
1655 -- | Identifies implicit tycons that, in particular, do not go into interface
1656 -- files (because they are implicitly reconstructed when the interface is
1657 -- read).
1658 --
1659 -- Note that:
1660 --
1661 -- * Associated families are implicit, as they are re-constructed from
1662 -- the class declaration in which they reside, and
1663 --
1664 -- * Family instances are /not/ implicit as they represent the instance body
1665 -- (similar to a @dfun@ does that for a class instance).
1666 --
1667 -- * Tuples are implicit iff they have a wired-in name
1668 -- (namely: boxed and unboxed tupeles are wired-in and implicit,
1669 -- but constraint tuples are not)
1670 isImplicitTyCon :: TyCon -> Bool
1671 isImplicitTyCon (FunTyCon {}) = True
1672 isImplicitTyCon (PrimTyCon {}) = True
1673 isImplicitTyCon (PromotedDataCon {}) = True
1674 isImplicitTyCon (AlgTyCon { algTcRhs = rhs, tyConName = name })
1675 | TupleTyCon {} <- rhs = isWiredInName name
1676 | otherwise = False
1677 isImplicitTyCon (FamilyTyCon { famTcParent = parent }) = isJust parent
1678 isImplicitTyCon (SynonymTyCon {}) = False
1679 isImplicitTyCon tc@(TcTyCon {})
1680 = pprPanic "isImplicitTyCon sees a TcTyCon" (ppr tc)
1681
1682 tyConCType_maybe :: TyCon -> Maybe CType
1683 tyConCType_maybe tc@(AlgTyCon {}) = tyConCType tc
1684 tyConCType_maybe _ = Nothing
1685
1686 -- | Is this a TcTyCon? (That is, one only used during type-checking?)
1687 isTcTyCon :: TyCon -> Bool
1688 isTcTyCon (TcTyCon {}) = True
1689 isTcTyCon _ = False
1690
1691 {-
1692 -----------------------------------------------
1693 -- Expand type-constructor applications
1694 -----------------------------------------------
1695 -}
1696
1697 expandSynTyCon_maybe
1698 :: TyCon
1699 -> [tyco] -- ^ Arguments to 'TyCon'
1700 -> Maybe ([(TyVar,tyco)],
1701 Type,
1702 [tyco]) -- ^ Returns a 'TyVar' substitution, the body
1703 -- type of the synonym (not yet substituted)
1704 -- and any arguments remaining from the
1705 -- application
1706
1707 -- ^ Expand a type synonym application, if any
1708 expandSynTyCon_maybe tc tys
1709 | SynonymTyCon { tyConTyVars = tvs, synTcRhs = rhs } <- tc
1710 , let n_tvs = length tvs
1711 = case n_tvs `compare` length tys of
1712 LT -> Just (tvs `zip` tys, rhs, drop n_tvs tys)
1713 EQ -> Just (tvs `zip` tys, rhs, [])
1714 GT -> Nothing
1715 | otherwise
1716 = Nothing
1717
1718 ----------------
1719
1720 -- | Check if the tycon actually refers to a proper `data` or `newtype`
1721 -- with user defined constructors rather than one from a class or other
1722 -- construction.
1723 isTyConWithSrcDataCons :: TyCon -> Bool
1724 isTyConWithSrcDataCons (AlgTyCon { algTcRhs = rhs, algTcParent = parent }) =
1725 case rhs of
1726 DataTyCon {} -> isSrcParent
1727 NewTyCon {} -> isSrcParent
1728 TupleTyCon {} -> isSrcParent
1729 _ -> False
1730 where
1731 isSrcParent = isNoParent parent
1732 isTyConWithSrcDataCons _ = False
1733
1734
1735 -- | As 'tyConDataCons_maybe', but returns the empty list of constructors if no
1736 -- constructors could be found
1737 tyConDataCons :: TyCon -> [DataCon]
1738 -- It's convenient for tyConDataCons to return the
1739 -- empty list for type synonyms etc
1740 tyConDataCons tycon = tyConDataCons_maybe tycon `orElse` []
1741
1742 -- | Determine the 'DataCon's originating from the given 'TyCon', if the 'TyCon'
1743 -- is the sort that can have any constructors (note: this does not include
1744 -- abstract algebraic types)
1745 tyConDataCons_maybe :: TyCon -> Maybe [DataCon]
1746 tyConDataCons_maybe (AlgTyCon {algTcRhs = rhs})
1747 = case rhs of
1748 DataTyCon { data_cons = cons } -> Just cons
1749 NewTyCon { data_con = con } -> Just [con]
1750 TupleTyCon { data_con = con } -> Just [con]
1751 _ -> Nothing
1752 tyConDataCons_maybe _ = Nothing
1753
1754 -- | If the given 'TyCon' has a /single/ data constructor, i.e. it is a @data@
1755 -- type with one alternative, a tuple type or a @newtype@ then that constructor
1756 -- is returned. If the 'TyCon' has more than one constructor, or represents a
1757 -- primitive or function type constructor then @Nothing@ is returned. In any
1758 -- other case, the function panics
1759 tyConSingleDataCon_maybe :: TyCon -> Maybe DataCon
1760 tyConSingleDataCon_maybe (AlgTyCon { algTcRhs = rhs })
1761 = case rhs of
1762 DataTyCon { data_cons = [c] } -> Just c
1763 TupleTyCon { data_con = c } -> Just c
1764 NewTyCon { data_con = c } -> Just c
1765 _ -> Nothing
1766 tyConSingleDataCon_maybe _ = Nothing
1767
1768 tyConSingleDataCon :: TyCon -> DataCon
1769 tyConSingleDataCon tc
1770 = case tyConSingleDataCon_maybe tc of
1771 Just c -> c
1772 Nothing -> pprPanic "tyConDataCon" (ppr tc)
1773
1774 tyConSingleAlgDataCon_maybe :: TyCon -> Maybe DataCon
1775 -- Returns (Just con) for single-constructor
1776 -- *algebraic* data types *not* newtypes
1777 tyConSingleAlgDataCon_maybe (AlgTyCon { algTcRhs = rhs })
1778 = case rhs of
1779 DataTyCon { data_cons = [c] } -> Just c
1780 TupleTyCon { data_con = c } -> Just c
1781 _ -> Nothing
1782 tyConSingleAlgDataCon_maybe _ = Nothing
1783
1784 -- | Determine the number of value constructors a 'TyCon' has. Panics if the
1785 -- 'TyCon' is not algebraic or a tuple
1786 tyConFamilySize :: TyCon -> Int
1787 tyConFamilySize tc@(AlgTyCon { algTcRhs = rhs })
1788 = case rhs of
1789 DataTyCon { data_cons = cons } -> length cons
1790 NewTyCon {} -> 1
1791 TupleTyCon {} -> 1
1792 _ -> pprPanic "tyConFamilySize 1" (ppr tc)
1793 tyConFamilySize tc = pprPanic "tyConFamilySize 2" (ppr tc)
1794
1795 -- | Extract an 'AlgTyConRhs' with information about data constructors from an
1796 -- algebraic or tuple 'TyCon'. Panics for any other sort of 'TyCon'
1797 algTyConRhs :: TyCon -> AlgTyConRhs
1798 algTyConRhs (AlgTyCon {algTcRhs = rhs}) = rhs
1799 algTyConRhs other = pprPanic "algTyConRhs" (ppr other)
1800
1801 -- | Extract type variable naming the result of injective type family
1802 tyConFamilyResVar_maybe :: TyCon -> Maybe Name
1803 tyConFamilyResVar_maybe (FamilyTyCon {famTcResVar = res}) = res
1804 tyConFamilyResVar_maybe _ = Nothing
1805
1806 -- | Get the list of roles for the type parameters of a TyCon
1807 tyConRoles :: TyCon -> [Role]
1808 -- See also Note [TyCon Role signatures]
1809 tyConRoles tc
1810 = case tc of
1811 { FunTyCon {} -> const_role Representational
1812 ; AlgTyCon { tcRoles = roles } -> roles
1813 ; SynonymTyCon { tcRoles = roles } -> roles
1814 ; FamilyTyCon {} -> const_role Nominal
1815 ; PrimTyCon { tcRoles = roles } -> roles
1816 ; PromotedDataCon { tcRoles = roles } -> roles
1817 ; TcTyCon {} -> pprPanic "tyConRoles sees a TcTyCon" (ppr tc)
1818 }
1819 where
1820 const_role r = replicate (tyConArity tc) r
1821
1822 -- | Extract the bound type variables and type expansion of a type synonym
1823 -- 'TyCon'. Panics if the 'TyCon' is not a synonym
1824 newTyConRhs :: TyCon -> ([TyVar], Type)
1825 newTyConRhs (AlgTyCon {tyConTyVars = tvs, algTcRhs = NewTyCon { nt_rhs = rhs }})
1826 = (tvs, rhs)
1827 newTyConRhs tycon = pprPanic "newTyConRhs" (ppr tycon)
1828
1829 -- | The number of type parameters that need to be passed to a newtype to
1830 -- resolve it. May be less than in the definition if it can be eta-contracted.
1831 newTyConEtadArity :: TyCon -> Int
1832 newTyConEtadArity (AlgTyCon {algTcRhs = NewTyCon { nt_etad_rhs = tvs_rhs }})
1833 = length (fst tvs_rhs)
1834 newTyConEtadArity tycon = pprPanic "newTyConEtadArity" (ppr tycon)
1835
1836 -- | Extract the bound type variables and type expansion of an eta-contracted
1837 -- type synonym 'TyCon'. Panics if the 'TyCon' is not a synonym
1838 newTyConEtadRhs :: TyCon -> ([TyVar], Type)
1839 newTyConEtadRhs (AlgTyCon {algTcRhs = NewTyCon { nt_etad_rhs = tvs_rhs }}) = tvs_rhs
1840 newTyConEtadRhs tycon = pprPanic "newTyConEtadRhs" (ppr tycon)
1841
1842 -- | Extracts the @newtype@ coercion from such a 'TyCon', which can be used to
1843 -- construct something with the @newtype@s type from its representation type
1844 -- (right hand side). If the supplied 'TyCon' is not a @newtype@, returns
1845 -- @Nothing@
1846 newTyConCo_maybe :: TyCon -> Maybe (CoAxiom Unbranched)
1847 newTyConCo_maybe (AlgTyCon {algTcRhs = NewTyCon { nt_co = co }}) = Just co
1848 newTyConCo_maybe _ = Nothing
1849
1850 newTyConCo :: TyCon -> CoAxiom Unbranched
1851 newTyConCo tc = case newTyConCo_maybe tc of
1852 Just co -> co
1853 Nothing -> pprPanic "newTyConCo" (ppr tc)
1854
1855 -- | Find the primitive representation of a 'TyCon'
1856 tyConPrimRep :: TyCon -> PrimRep
1857 tyConPrimRep (PrimTyCon {primTyConRep = rep}) = rep
1858 tyConPrimRep tc = ASSERT(not (isUnboxedTupleTyCon tc)) PtrRep
1859
1860 -- | Find the \"stupid theta\" of the 'TyCon'. A \"stupid theta\" is the context
1861 -- to the left of an algebraic type declaration, e.g. @Eq a@ in the declaration
1862 -- @data Eq a => T a ...@
1863 tyConStupidTheta :: TyCon -> [PredType]
1864 tyConStupidTheta (AlgTyCon {algTcStupidTheta = stupid}) = stupid
1865 tyConStupidTheta tycon = pprPanic "tyConStupidTheta" (ppr tycon)
1866
1867 -- | Extract the 'TyVar's bound by a vanilla type synonym
1868 -- and the corresponding (unsubstituted) right hand side.
1869 synTyConDefn_maybe :: TyCon -> Maybe ([TyVar], Type)
1870 synTyConDefn_maybe (SynonymTyCon {tyConTyVars = tyvars, synTcRhs = ty})
1871 = Just (tyvars, ty)
1872 synTyConDefn_maybe _ = Nothing
1873
1874 -- | Extract the information pertaining to the right hand side of a type synonym
1875 -- (@type@) declaration.
1876 synTyConRhs_maybe :: TyCon -> Maybe Type
1877 synTyConRhs_maybe (SynonymTyCon {synTcRhs = rhs}) = Just rhs
1878 synTyConRhs_maybe _ = Nothing
1879
1880 -- | Extract the flavour of a type family (with all the extra information that
1881 -- it carries)
1882 famTyConFlav_maybe :: TyCon -> Maybe FamTyConFlav
1883 famTyConFlav_maybe (FamilyTyCon {famTcFlav = flav}) = Just flav
1884 famTyConFlav_maybe _ = Nothing
1885
1886 -- | Is this 'TyCon' that for a class instance?
1887 isClassTyCon :: TyCon -> Bool
1888 isClassTyCon (AlgTyCon {algTcParent = ClassTyCon {}}) = True
1889 isClassTyCon _ = False
1890
1891 -- | If this 'TyCon' is that for a class instance, return the class it is for.
1892 -- Otherwise returns @Nothing@
1893 tyConClass_maybe :: TyCon -> Maybe Class
1894 tyConClass_maybe (AlgTyCon {algTcParent = ClassTyCon clas _}) = Just clas
1895 tyConClass_maybe _ = Nothing
1896
1897 -- | Return the associated types of the 'TyCon', if any
1898 tyConATs :: TyCon -> [TyCon]
1899 tyConATs (AlgTyCon {algTcParent = ClassTyCon clas _}) = classATs clas
1900 tyConATs _ = []
1901
1902 ----------------------------------------------------------------------------
1903 -- | Is this 'TyCon' that for a data family instance?
1904 isFamInstTyCon :: TyCon -> Bool
1905 isFamInstTyCon (AlgTyCon {algTcParent = DataFamInstTyCon {} })
1906 = True
1907 isFamInstTyCon _ = False
1908
1909 tyConFamInstSig_maybe :: TyCon -> Maybe (TyCon, [Type], CoAxiom Unbranched)
1910 tyConFamInstSig_maybe (AlgTyCon {algTcParent = DataFamInstTyCon ax f ts })
1911 = Just (f, ts, ax)
1912 tyConFamInstSig_maybe _ = Nothing
1913
1914 -- | If this 'TyCon' is that of a data family instance, return the family in question
1915 -- and the instance types. Otherwise, return @Nothing@
1916 tyConFamInst_maybe :: TyCon -> Maybe (TyCon, [Type])
1917 tyConFamInst_maybe (AlgTyCon {algTcParent = DataFamInstTyCon _ f ts })
1918 = Just (f, ts)
1919 tyConFamInst_maybe _ = Nothing
1920
1921 -- | If this 'TyCon' is that of a data family instance, return a 'TyCon' which
1922 -- represents a coercion identifying the representation type with the type
1923 -- instance family. Otherwise, return @Nothing@
1924 tyConFamilyCoercion_maybe :: TyCon -> Maybe (CoAxiom Unbranched)
1925 tyConFamilyCoercion_maybe (AlgTyCon {algTcParent = DataFamInstTyCon ax _ _ })
1926 = Just ax
1927 tyConFamilyCoercion_maybe _ = Nothing
1928
1929 {-
1930 ************************************************************************
1931 * *
1932 \subsection[TyCon-instances]{Instance declarations for @TyCon@}
1933 * *
1934 ************************************************************************
1935
1936 @TyCon@s are compared by comparing their @Unique@s.
1937
1938 The strictness analyser needs @Ord@. It is a lexicographic order with
1939 the property @(a<=b) || (b<=a)@.
1940 -}
1941
1942 instance Eq TyCon where
1943 a == b = case (a `compare` b) of { EQ -> True; _ -> False }
1944 a /= b = case (a `compare` b) of { EQ -> False; _ -> True }
1945
1946 instance Ord TyCon where
1947 a <= b = case (a `compare` b) of { LT -> True; EQ -> True; GT -> False }
1948 a < b = case (a `compare` b) of { LT -> True; EQ -> False; GT -> False }
1949 a >= b = case (a `compare` b) of { LT -> False; EQ -> True; GT -> True }
1950 a > b = case (a `compare` b) of { LT -> False; EQ -> False; GT -> True }
1951 compare a b = getUnique a `compare` getUnique b
1952
1953 instance Uniquable TyCon where
1954 getUnique tc = tyConUnique tc
1955
1956 instance Outputable TyCon where
1957 -- At the moment a promoted TyCon has the same Name as its
1958 -- corresponding TyCon, so we add the quote to distinguish it here
1959 ppr tc = pprPromotionQuote tc <> ppr (tyConName tc)
1960
1961 tyConFlavour :: TyCon -> String
1962 tyConFlavour (AlgTyCon { algTcParent = parent, algTcRhs = rhs })
1963 | ClassTyCon _ _ <- parent = "class"
1964 | otherwise = case rhs of
1965 TupleTyCon { tup_sort = sort }
1966 | isBoxed (tupleSortBoxity sort) -> "tuple"
1967 | otherwise -> "unboxed tuple"
1968 DataTyCon {} -> "data type"
1969 NewTyCon {} -> "newtype"
1970 AbstractTyCon {} -> "abstract type"
1971 tyConFlavour (FamilyTyCon { famTcFlav = flav })
1972 | isDataFamFlav flav = "data family"
1973 | otherwise = "type family"
1974 tyConFlavour (SynonymTyCon {}) = "type synonym"
1975 tyConFlavour (FunTyCon {}) = "built-in type"
1976 tyConFlavour (PrimTyCon {}) = "built-in type"
1977 tyConFlavour (PromotedDataCon {}) = "promoted data constructor"
1978 tyConFlavour tc@(TcTyCon {})
1979 = pprPanic "tyConFlavour sees a TcTyCon" (ppr tc)
1980
1981 pprPromotionQuote :: TyCon -> SDoc
1982 -- Promoted data constructors already have a tick in their OccName
1983 pprPromotionQuote tc
1984 = case tc of
1985 PromotedDataCon {} -> char '\'' -- Always quote promoted DataCons in types
1986 _ -> empty
1987
1988 instance NamedThing TyCon where
1989 getName = tyConName
1990
1991 instance Data.Data TyCon where
1992 -- don't traverse?
1993 toConstr _ = abstractConstr "TyCon"
1994 gunfold _ _ = error "gunfold"
1995 dataTypeOf _ = mkNoRepType "TyCon"
1996
1997 instance Binary Injectivity where
1998 put_ bh NotInjective = putByte bh 0
1999 put_ bh (Injective xs) = putByte bh 1 >> put_ bh xs
2000
2001 get bh = do { h <- getByte bh
2002 ; case h of
2003 0 -> return NotInjective
2004 _ -> do { xs <- get bh
2005 ; return (Injective xs) } }
2006
2007 {-
2008 ************************************************************************
2009 * *
2010 Walking over recursive TyCons
2011 * *
2012 ************************************************************************
2013
2014 Note [Expanding newtypes and products]
2015 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2016 When expanding a type to expose a data-type constructor, we need to be
2017 careful about newtypes, lest we fall into an infinite loop. Here are
2018 the key examples:
2019
2020 newtype Id x = MkId x
2021 newtype Fix f = MkFix (f (Fix f))
2022 newtype T = MkT (T -> T)
2023
2024 Type Expansion
2025 --------------------------
2026 T T -> T
2027 Fix Maybe Maybe (Fix Maybe)
2028 Id (Id Int) Int
2029 Fix Id NO NO NO
2030
2031 Notice that
2032 * We can expand T, even though it's recursive.
2033 * We can expand Id (Id Int), even though the Id shows up
2034 twice at the outer level, because Id is non-recursive
2035
2036 So, when expanding, we keep track of when we've seen a recursive
2037 newtype at outermost level; and bale out if we see it again.
2038
2039 We sometimes want to do the same for product types, so that the
2040 strictness analyser doesn't unbox infinitely deeply.
2041
2042 More precisely, we keep a *count* of how many times we've seen it.
2043 This is to account for
2044 data instance T (a,b) = MkT (T a) (T b)
2045 Then (Trac #10482) if we have a type like
2046 T (Int,(Int,(Int,(Int,Int))))
2047 we can still unbox deeply enough during strictness analysis.
2048 We have to treat T as potentially recursive, but it's still
2049 good to be able to unwrap multiple layers.
2050
2051 The function that manages all this is checkRecTc.
2052 -}
2053
2054 data RecTcChecker = RC !Int (NameEnv Int)
2055 -- The upper bound, and the number of times
2056 -- we have encountered each TyCon
2057
2058 initRecTc :: RecTcChecker
2059 -- Intialise with a fixed max bound of 100
2060 -- We should probably have a flag for this
2061 initRecTc = RC 100 emptyNameEnv
2062
2063 checkRecTc :: RecTcChecker -> TyCon -> Maybe RecTcChecker
2064 -- Nothing => Recursion detected
2065 -- Just rec_tcs => Keep going
2066 checkRecTc rc@(RC bound rec_nts) tc
2067 | not (isRecursiveTyCon tc)
2068 = Just rc -- Tuples are a common example here
2069 | otherwise
2070 = case lookupNameEnv rec_nts tc_name of
2071 Just n | n >= bound -> Nothing
2072 | otherwise -> Just (RC bound (extendNameEnv rec_nts tc_name (n+1)))
2073 Nothing -> Just (RC bound (extendNameEnv rec_nts tc_name 1))
2074 where
2075 tc_name = tyConName tc