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