Allow bundling pattern synonyms with exported data families
[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, FlexibleInstances #-}
10
11 module TyCon(
12 -- * Main TyCon data types
13 TyCon, AlgTyConRhs(..), visibleDataCons,
14 AlgTyConFlav(..), isNoParent,
15 FamTyConFlav(..), Role(..), Injectivity(..),
16 RuntimeRepInfo(..), TyConFlavour(..),
17
18 -- * TyConBinder
19 TyConBinder, TyConBndrVis(..),
20 mkNamedTyConBinder, mkNamedTyConBinders,
21 mkAnonTyConBinder, mkAnonTyConBinders,
22 tyConBinderArgFlag, isNamedTyConBinder,
23 isVisibleTyConBinder, isInvisibleTyConBinder,
24
25 -- ** Field labels
26 tyConFieldLabels, lookupTyConFieldLabel,
27
28 -- ** Constructing TyCons
29 mkAlgTyCon,
30 mkClassTyCon,
31 mkFunTyCon,
32 mkPrimTyCon,
33 mkKindTyCon,
34 mkLiftedPrimTyCon,
35 mkTupleTyCon,
36 mkSumTyCon,
37 mkSynonymTyCon,
38 mkFamilyTyCon,
39 mkPromotedDataCon,
40 mkTcTyCon,
41
42 -- ** Predicates on TyCons
43 isAlgTyCon, isVanillaAlgTyCon,
44 isClassTyCon, isFamInstTyCon,
45 isFunTyCon,
46 isPrimTyCon,
47 isTupleTyCon, isUnboxedTupleTyCon, isBoxedTupleTyCon,
48 isUnboxedSumTyCon, isPromotedTupleTyCon,
49 isTypeSynonymTyCon,
50 mightBeUnsaturatedTyCon,
51 isPromotedDataCon, isPromotedDataCon_maybe,
52 isKindTyCon, isLiftedTypeKindTyConName,
53 isTauTyCon, isFamFreeTyCon,
54
55 isDataTyCon, isProductTyCon, isDataProductTyCon_maybe,
56 isDataSumTyCon_maybe,
57 isEnumerationTyCon,
58 isNewTyCon, isAbstractTyCon,
59 isFamilyTyCon, isOpenFamilyTyCon,
60 isTypeFamilyTyCon, isDataFamilyTyCon,
61 isOpenTypeFamilyTyCon, isClosedSynFamilyTyConWithAxiom_maybe,
62 familyTyConInjectivityInfo,
63 isBuiltInSynFamTyCon_maybe,
64 isUnliftedTyCon,
65 isGadtSyntaxTyCon, isInjectiveTyCon, isGenerativeTyCon, isGenInjAlgRhs,
66 isTyConAssoc, tyConAssoc_maybe,
67 isImplicitTyCon,
68 isTyConWithSrcDataCons,
69 isTcTyCon, isTcLevPoly,
70
71 -- ** Extracting information out of TyCons
72 tyConName,
73 tyConSkolem,
74 tyConKind,
75 tyConUnique,
76 tyConTyVars,
77 tyConCType, tyConCType_maybe,
78 tyConDataCons, tyConDataCons_maybe,
79 tyConSingleDataCon_maybe, tyConSingleDataCon,
80 tyConSingleAlgDataCon_maybe,
81 tyConFamilySize,
82 tyConStupidTheta,
83 tyConArity,
84 tyConRoles,
85 tyConFlavour,
86 tyConTuple_maybe, tyConClass_maybe, tyConATs,
87 tyConFamInst_maybe, tyConFamInstSig_maybe, tyConFamilyCoercion_maybe,
88 tyConFamilyResVar_maybe,
89 synTyConDefn_maybe, synTyConRhs_maybe,
90 famTyConFlav_maybe, famTcResVar,
91 algTyConRhs,
92 newTyConRhs, newTyConEtadArity, newTyConEtadRhs,
93 unwrapNewTyCon_maybe, unwrapNewTyConEtad_maybe,
94 newTyConDataCon_maybe,
95 algTcFields,
96 tyConRuntimeRepInfo,
97 tyConBinders, tyConResKind, tyConTyVarBinders,
98 tcTyConScopedTyVars,
99
100 -- ** Manipulating TyCons
101 expandSynTyCon_maybe,
102 makeRecoveryTyCon,
103 newTyConCo, newTyConCo_maybe,
104 pprPromotionQuote, mkTyConKind,
105
106 -- ** Predicated on TyConFlavours
107 tcFlavourCanBeUnsaturated, tcFlavourIsOpen,
108
109 -- * Runtime type representation
110 TyConRepName, tyConRepName_maybe,
111 mkPrelTyConRepName,
112 tyConRepModOcc,
113
114 -- * Primitive representations of Types
115 PrimRep(..), PrimElemRep(..),
116 isVoidRep, isGcPtrRep,
117 primRepSizeW, primElemRepSizeB,
118 primRepIsFloat,
119
120 -- * Recursion breaking
121 RecTcChecker, initRecTc, checkRecTc
122
123 ) where
124
125 #include "HsVersions.h"
126
127 import {-# SOURCE #-} TyCoRep ( Kind, Type, PredType, pprType )
128 import {-# SOURCE #-} TysWiredIn ( runtimeRepTyCon, constraintKind
129 , vecCountTyCon, vecElemTyCon, liftedTypeKind
130 , mkFunKind, mkForAllKind )
131 import {-# SOURCE #-} DataCon ( DataCon, dataConExTyVars, dataConFieldLabels
132 , dataConTyCon )
133
134 import Binary
135 import Var
136 import Class
137 import BasicTypes
138 import DynFlags
139 import ForeignCall
140 import Name
141 import NameEnv
142 import CoAxiom
143 import PrelNames
144 import Maybes
145 import Outputable
146 import FastStringEnv
147 import FieldLabel
148 import Constants
149 import Util
150 import Unique( tyConRepNameUnique, dataConRepNameUnique )
151 import UniqSet
152 import Module
153
154 import qualified Data.Data as Data
155
156 {-
157 -----------------------------------------------
158 Notes about type families
159 -----------------------------------------------
160
161 Note [Type synonym families]
162 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
163 * Type synonym families, also known as "type functions", map directly
164 onto the type functions in FC:
165
166 type family F a :: *
167 type instance F Int = Bool
168 ..etc...
169
170 * Reply "yes" to isTypeFamilyTyCon, and isFamilyTyCon
171
172 * From the user's point of view (F Int) and Bool are simply
173 equivalent types.
174
175 * A Haskell 98 type synonym is a degenerate form of a type synonym
176 family.
177
178 * Type functions can't appear in the LHS of a type function:
179 type instance F (F Int) = ... -- BAD!
180
181 * Translation of type family decl:
182 type family F a :: *
183 translates to
184 a FamilyTyCon 'F', whose FamTyConFlav is OpenSynFamilyTyCon
185
186 type family G a :: * where
187 G Int = Bool
188 G Bool = Char
189 G a = ()
190 translates to
191 a FamilyTyCon 'G', whose FamTyConFlav is ClosedSynFamilyTyCon, with the
192 appropriate CoAxiom representing the equations
193
194 We also support injective type families -- see Note [Injective type families]
195
196 Note [Data type families]
197 ~~~~~~~~~~~~~~~~~~~~~~~~~
198 See also Note [Wrappers for data instance tycons] in MkId.hs
199
200 * Data type families are declared thus
201 data family T a :: *
202 data instance T Int = T1 | T2 Bool
203
204 Here T is the "family TyCon".
205
206 * Reply "yes" to isDataFamilyTyCon, and isFamilyTyCon
207
208 * The user does not see any "equivalent types" as he did with type
209 synonym families. He just sees constructors with types
210 T1 :: T Int
211 T2 :: Bool -> T Int
212
213 * Here's the FC version of the above declarations:
214
215 data T a
216 data R:TInt = T1 | T2 Bool
217 axiom ax_ti : T Int ~R R:TInt
218
219 Note that this is a *representational* coercion
220 The R:TInt is the "representation TyCons".
221 It has an AlgTyConFlav of
222 DataFamInstTyCon T [Int] ax_ti
223
224 * The axiom ax_ti may be eta-reduced; see
225 Note [Eta reduction for data family axioms] in FamInstEnv
226
227 * Data family instances may have a different arity than the data family.
228 See Note [Arity of data families] in FamInstEnv
229
230 * The data constructor T2 has a wrapper (which is what the
231 source-level "T2" invokes):
232
233 $WT2 :: Bool -> T Int
234 $WT2 b = T2 b `cast` sym ax_ti
235
236 * A data instance can declare a fully-fledged GADT:
237
238 data instance T (a,b) where
239 X1 :: T (Int,Bool)
240 X2 :: a -> b -> T (a,b)
241
242 Here's the FC version of the above declaration:
243
244 data R:TPair a where
245 X1 :: R:TPair Int Bool
246 X2 :: a -> b -> R:TPair a b
247 axiom ax_pr :: T (a,b) ~R R:TPair a b
248
249 $WX1 :: forall a b. a -> b -> T (a,b)
250 $WX1 a b (x::a) (y::b) = X2 a b x y `cast` sym (ax_pr a b)
251
252 The R:TPair are the "representation TyCons".
253 We have a bit of work to do, to unpick the result types of the
254 data instance declaration for T (a,b), to get the result type in the
255 representation; e.g. T (a,b) --> R:TPair a b
256
257 The representation TyCon R:TList, has an AlgTyConFlav of
258
259 DataFamInstTyCon T [(a,b)] ax_pr
260
261 * Notice that T is NOT translated to a FC type function; it just
262 becomes a "data type" with no constructors, which can be coerced inot
263 into R:TInt, R:TPair by the axioms. These axioms
264 axioms come into play when (and *only* when) you
265 - use a data constructor
266 - do pattern matching
267 Rather like newtype, in fact
268
269 As a result
270
271 - T behaves just like a data type so far as decomposition is concerned
272
273 - (T Int) is not implicitly converted to R:TInt during type inference.
274 Indeed the latter type is unknown to the programmer.
275
276 - There *is* an instance for (T Int) in the type-family instance
277 environment, but it is only used for overlap checking
278
279 - It's fine to have T in the LHS of a type function:
280 type instance F (T a) = [a]
281
282 It was this last point that confused me! The big thing is that you
283 should not think of a data family T as a *type function* at all, not
284 even an injective one! We can't allow even injective type functions
285 on the LHS of a type function:
286 type family injective G a :: *
287 type instance F (G Int) = Bool
288 is no good, even if G is injective, because consider
289 type instance G Int = Bool
290 type instance F Bool = Char
291
292 So a data type family is not an injective type function. It's just a
293 data type with some axioms that connect it to other data types.
294
295 * The tyConTyVars of the representation tycon are the tyvars that the
296 user wrote in the patterns. This is important in TcDeriv, where we
297 bring these tyvars into scope before type-checking the deriving
298 clause. This fact is arranged for in TcInstDecls.tcDataFamInstDecl.
299
300 Note [Associated families and their parent class]
301 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
302 *Associated* families are just like *non-associated* families, except
303 that they have a famTcParent field of (Just cls), which identifies the
304 parent class.
305
306 However there is an important sharing relationship between
307 * the tyConTyVars of the parent Class
308 * the tyConTyvars of the associated TyCon
309
310 class C a b where
311 data T p a
312 type F a q b
313
314 Here the 'a' and 'b' are shared with the 'Class'; that is, they have
315 the same Unique.
316
317 This is important. In an instance declaration we expect
318 * all the shared variables to be instantiated the same way
319 * the non-shared variables of the associated type should not
320 be instantiated at all
321
322 instance C [x] (Tree y) where
323 data T p [x] = T1 x | T2 p
324 type F [x] q (Tree y) = (x,y,q)
325
326 Note [TyCon Role signatures]
327 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
328 Every tycon has a role signature, assigning a role to each of the tyConTyVars
329 (or of equal length to the tyConArity, if there are no tyConTyVars). An
330 example demonstrates these best: say we have a tycon T, with parameters a at
331 nominal, b at representational, and c at phantom. Then, to prove
332 representational equality between T a1 b1 c1 and T a2 b2 c2, we need to have
333 nominal equality between a1 and a2, representational equality between b1 and
334 b2, and nothing in particular (i.e., phantom equality) between c1 and c2. This
335 might happen, say, with the following declaration:
336
337 data T a b c where
338 MkT :: b -> T Int b c
339
340 Data and class tycons have their roles inferred (see inferRoles in TcTyDecls),
341 as do vanilla synonym tycons. Family tycons have all parameters at role N,
342 though it is conceivable that we could relax this restriction. (->)'s and
343 tuples' parameters are at role R. Each primitive tycon declares its roles;
344 it's worth noting that (~#)'s parameters are at role N. Promoted data
345 constructors' type arguments are at role R. All kind arguments are at role
346 N.
347
348 Note [Unboxed tuple RuntimeRep vars]
349 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
350 The contents of an unboxed tuple may have any representation. Accordingly,
351 the kind of the unboxed tuple constructor is runtime-representation
352 polymorphic. For example,
353
354 (#,#) :: forall (q :: RuntimeRep) (r :: RuntimeRep). TYPE q -> TYPE r -> #
355
356 These extra tyvars (v and w) cause some delicate processing around tuples,
357 where we used to be able to assume that the tycon arity and the
358 datacon arity were the same.
359
360 Note [Injective type families]
361 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
362 We allow injectivity annotations for type families (both open and closed):
363
364 type family F (a :: k) (b :: k) = r | r -> a
365 type family G a b = res | res -> a b where ...
366
367 Injectivity information is stored in the `famTcInj` field of `FamilyTyCon`.
368 `famTcInj` maybe stores a list of Bools, where each entry corresponds to a
369 single element of `tyConTyVars` (both lists should have identical length). If no
370 injectivity annotation was provided `famTcInj` is Nothing. From this follows an
371 invariant that if `famTcInj` is a Just then at least one element in the list
372 must be True.
373
374 See also:
375 * [Injectivity annotation] in HsDecls
376 * [Renaming injectivity annotation] in RnSource
377 * [Verifying injectivity annotation] in FamInstEnv
378 * [Type inference for type families with injectivity] in TcInteract
379
380 ************************************************************************
381 * *
382 TyConBinder
383 * *
384 ************************************************************************
385 -}
386
387 type TyConBinder = TyVarBndr TyVar TyConBndrVis
388
389 data TyConBndrVis
390 = NamedTCB ArgFlag
391 | AnonTCB
392
393 mkAnonTyConBinder :: TyVar -> TyConBinder
394 mkAnonTyConBinder tv = TvBndr tv AnonTCB
395
396 mkAnonTyConBinders :: [TyVar] -> [TyConBinder]
397 mkAnonTyConBinders tvs = map mkAnonTyConBinder tvs
398
399 mkNamedTyConBinder :: ArgFlag -> TyVar -> TyConBinder
400 -- The odd argument order supports currying
401 mkNamedTyConBinder vis tv = TvBndr tv (NamedTCB vis)
402
403 mkNamedTyConBinders :: ArgFlag -> [TyVar] -> [TyConBinder]
404 -- The odd argument order supports currying
405 mkNamedTyConBinders vis tvs = map (mkNamedTyConBinder vis) tvs
406
407 tyConBinderArgFlag :: TyConBinder -> ArgFlag
408 tyConBinderArgFlag (TvBndr _ (NamedTCB vis)) = vis
409 tyConBinderArgFlag (TvBndr _ AnonTCB) = Required
410
411 isNamedTyConBinder :: TyConBinder -> Bool
412 -- Identifies kind variables
413 -- E.g. data T k (a:k) = blah
414 -- Here 'k' is a NamedTCB, a variable used in the kind of other binders
415 isNamedTyConBinder (TvBndr _ (NamedTCB {})) = True
416 isNamedTyConBinder _ = False
417
418 isVisibleTyConBinder :: TyVarBndr tv TyConBndrVis -> Bool
419 -- Works for IfaceTyConBinder too
420 isVisibleTyConBinder (TvBndr _ (NamedTCB vis)) = isVisibleArgFlag vis
421 isVisibleTyConBinder (TvBndr _ AnonTCB) = True
422
423 isInvisibleTyConBinder :: TyVarBndr tv TyConBndrVis -> Bool
424 -- Works for IfaceTyConBinder too
425 isInvisibleTyConBinder tcb = not (isVisibleTyConBinder tcb)
426
427 mkTyConKind :: [TyConBinder] -> Kind -> Kind
428 mkTyConKind bndrs res_kind = foldr mk res_kind bndrs
429 where
430 mk :: TyConBinder -> Kind -> Kind
431 mk (TvBndr tv AnonTCB) k = mkFunKind (tyVarKind tv) k
432 mk (TvBndr tv (NamedTCB vis)) k = mkForAllKind tv vis k
433
434 tyConTyVarBinders :: [TyConBinder] -- From the TyCon
435 -> [TyVarBinder] -- Suitable for the foralls of a term function
436 -- See Note [Building TyVarBinders from TyConBinders]
437 tyConTyVarBinders tc_bndrs
438 = map mk_binder tc_bndrs
439 where
440 mk_binder (TvBndr tv tc_vis) = mkTyVarBinder vis tv
441 where
442 vis = case tc_vis of
443 AnonTCB -> Specified
444 NamedTCB Required -> Specified
445 NamedTCB vis -> vis
446
447 {- Note [Building TyVarBinders from TyConBinders]
448 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
449 We sometimes need to build the quantified type of a value from
450 the TyConBinders of a type or class. For that we need not
451 TyConBinders but TyVarBinders (used in forall-type) E.g:
452
453 * From data T a = MkT (Maybe a)
454 we are going to make a data constructor with type
455 MkT :: forall a. Maybe a -> T a
456 See the TyVarBinders passed to buildDataCon
457
458 * From class C a where { op :: a -> Maybe a }
459 we are going to make a default method
460 $dmop :: forall a. C a => a -> Maybe a
461 See the TyVarBindres passed to mkSigmaTy in mkDefaultMethodType
462
463 Both of these are user-callable. (NB: default methods are not callable
464 directly by the user but rather via the code generated by 'deriving',
465 which uses visible type application; see mkDefMethBind.)
466
467 Since they are user-callable we must get their type-argument visibility
468 information right; and that info is in the TyConBinders.
469 Here is an example:
470
471 data App a b = MkApp (a b) -- App :: forall {k}. (k->*) -> k -> *
472
473 The TyCon has
474
475 tyConTyBinders = [ Named (TvBndr (k :: *) Inferred), Anon (k->*), Anon k ]
476
477 The TyConBinders for App line up with App's kind, given above.
478
479 But the DataCon MkApp has the type
480 MkApp :: forall {k} (a:k->*) (b:k). a b -> App k a b
481
482 That is, its TyVarBinders should be
483
484 dataConUnivTyVarBinders = [ TvBndr (k:*) Inferred
485 , TvBndr (a:k->*) Specified
486 , TvBndr (b:k) Specified ]
487
488 So tyConTyVarBinders converts TyCon's TyConBinders into TyVarBinders:
489 - variable names from the TyConBinders
490 - but changing Anon/Required to Specified
491
492 The last part about Required->Specified comes from this:
493 data T k (a:k) b = MkT (a b)
494 Here k is Required in T's kind, but we don't have Required binders in
495 the TyBinders for a term (see Note [No Required TyBinder in terms]
496 in TyCoRep), so we change it to Specified when making MkT's TyBinders
497 -}
498
499
500 {- Note [The binders/kind/arity fields of a TyCon]
501 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
502 All TyCons have this group of fields
503 tyConBinders :: [TyConBinder]
504 tyConResKind :: Kind
505 tyConTyVars :: [TyVar] -- Cached = binderVars tyConBinders
506 tyConKind :: Kind -- Cached = mkTyConKind tyConBinders tyConResKind
507 tyConArity :: Arity -- Cached = length tyConBinders
508
509 They fit together like so:
510
511 * tyConBinders gives the telescope of type variables on the LHS of the
512 type declaration. For example:
513
514 type App a (b :: k) = a b
515
516 tyConBinders = [ TvBndr (k::*) (NamedTCB Inferred)
517 , TvBndr (a:k->*) AnonTCB
518 , TvBndr (b:k) AnonTCB ]
519
520 Note that that are three binders here, including the
521 kind variable k.
522
523 - See Note [TyVarBndrs, TyVarBinders, TyConBinders, and visibility] in TyCoRep
524 for what the visibility flag means.
525
526 * Each TyConBinder tyConBinders has a TyVar, and that TyVar may
527 scope over some other part of the TyCon's definition. Eg
528 type T a = a->a
529 we have
530 tyConBinders = [ TvBndr (a:*) AnonTCB ]
531 synTcRhs = a->a
532 So the 'a' scopes over the synTcRhs
533
534 * From the tyConBinders and tyConResKind we can get the tyConKind
535 E.g for our App example:
536 App :: forall k. (k->*) -> k -> *
537
538 We get a 'forall' in the kind for each NamedTCB, and an arrow
539 for each AnonTCB
540
541 tyConKind is the full kind of the TyCon, not just the result kind
542
543 * tyConArity is the arguments this TyCon must be applied to, to be
544 considered saturated. Here we mean "applied to in the actual Type",
545 not surface syntax; i.e. including implicit kind variables.
546 So it's just (length tyConBinders)
547 -}
548
549 instance Outputable tv => Outputable (TyVarBndr tv TyConBndrVis) where
550 ppr (TvBndr v AnonTCB) = ppr v
551 ppr (TvBndr v (NamedTCB Required)) = ppr v
552 ppr (TvBndr v (NamedTCB Specified)) = char '@' <> ppr v
553 ppr (TvBndr v (NamedTCB Inferred)) = braces (ppr v)
554
555 instance Binary TyConBndrVis where
556 put_ bh AnonTCB = putByte bh 0
557 put_ bh (NamedTCB vis) = do { putByte bh 1; put_ bh vis }
558
559 get bh = do { h <- getByte bh
560 ; case h of
561 0 -> return AnonTCB
562 _ -> do { vis <- get bh; return (NamedTCB vis) } }
563
564
565 {- *********************************************************************
566 * *
567 The TyCon type
568 * *
569 ************************************************************************
570 -}
571
572
573 -- | TyCons represent type constructors. Type constructors are introduced by
574 -- things such as:
575 --
576 -- 1) Data declarations: @data Foo = ...@ creates the @Foo@ type constructor of
577 -- kind @*@
578 --
579 -- 2) Type synonyms: @type Foo = ...@ creates the @Foo@ type constructor
580 --
581 -- 3) Newtypes: @newtype Foo a = MkFoo ...@ creates the @Foo@ type constructor
582 -- of kind @* -> *@
583 --
584 -- 4) Class declarations: @class Foo where@ creates the @Foo@ type constructor
585 -- of kind @*@
586 --
587 -- This data type also encodes a number of primitive, built in type constructors
588 -- such as those for function and tuple types.
589
590 -- If you edit this type, you may need to update the GHC formalism
591 -- See Note [GHC Formalism] in coreSyn/CoreLint.hs
592 data TyCon
593 = -- | The function type constructor, @(->)@
594 FunTyCon {
595 tyConUnique :: Unique, -- ^ A Unique of this TyCon. Invariant:
596 -- identical to Unique of Name stored in
597 -- tyConName field.
598
599 tyConName :: Name, -- ^ Name of the constructor
600
601 -- See Note [The binders/kind/arity fields of a TyCon]
602 tyConBinders :: [TyConBinder], -- ^ Full binders
603 tyConResKind :: Kind, -- ^ Result kind
604 tyConKind :: Kind, -- ^ Kind of this TyCon
605 tyConArity :: Arity, -- ^ Arity
606
607 tcRepName :: TyConRepName
608 }
609
610 -- | Algebraic data types, from
611 -- - @data@ declarations
612 -- - @newtype@ declarations
613 -- - data instance declarations
614 -- - type instance declarations
615 -- - the TyCon generated by a class declaration
616 -- - boxed tuples
617 -- - unboxed tuples
618 -- - constraint tuples
619 -- All these constructors are lifted and boxed except unboxed tuples
620 -- which should have an 'UnboxedAlgTyCon' parent.
621 -- Data/newtype/type /families/ are handled by 'FamilyTyCon'.
622 -- See 'AlgTyConRhs' for more information.
623 | AlgTyCon {
624 tyConUnique :: Unique, -- ^ A Unique of this TyCon. Invariant:
625 -- identical to Unique of Name stored in
626 -- tyConName field.
627
628 tyConName :: Name, -- ^ Name of the constructor
629
630 -- See Note [The binders/kind/arity fields of a TyCon]
631 tyConBinders :: [TyConBinder], -- ^ Full binders
632 tyConTyVars :: [TyVar], -- ^ TyVar binders
633 tyConResKind :: Kind, -- ^ Result kind
634 tyConKind :: Kind, -- ^ Kind of this TyCon
635 tyConArity :: Arity, -- ^ Arity
636
637 -- The tyConTyVars scope over:
638 --
639 -- 1. The 'algTcStupidTheta'
640 -- 2. The cached types in algTyConRhs.NewTyCon
641 -- 3. The family instance types if present
642 --
643 -- Note that it does /not/ scope over the data
644 -- constructors.
645
646 tcRoles :: [Role], -- ^ The role for each type variable
647 -- This list has length = tyConArity
648 -- See also Note [TyCon Role signatures]
649
650 tyConCType :: Maybe CType,-- ^ The C type that should be used
651 -- for this type when using the FFI
652 -- and CAPI
653
654 algTcGadtSyntax :: Bool, -- ^ Was the data type declared with GADT
655 -- syntax? If so, that doesn't mean it's a
656 -- true GADT; only that the "where" form
657 -- was used. This field is used only to
658 -- guide pretty-printing
659
660 algTcStupidTheta :: [PredType], -- ^ The \"stupid theta\" for the data
661 -- type (always empty for GADTs). A
662 -- \"stupid theta\" is the context to
663 -- the left of an algebraic type
664 -- declaration, e.g. @Eq a@ in the
665 -- declaration @data Eq a => T a ...@.
666
667 algTcRhs :: AlgTyConRhs, -- ^ Contains information about the
668 -- data constructors of the algebraic type
669
670 algTcFields :: FieldLabelEnv, -- ^ Maps a label to information
671 -- about the field
672
673 algTcParent :: AlgTyConFlav -- ^ Gives the class or family declaration
674 -- 'TyCon' for derived 'TyCon's representing
675 -- class or family instances, respectively.
676
677 }
678
679 -- | Represents type synonyms
680 | SynonymTyCon {
681 tyConUnique :: Unique, -- ^ A Unique of this TyCon. Invariant:
682 -- identical to Unique of Name stored in
683 -- tyConName field.
684
685 tyConName :: Name, -- ^ Name of the constructor
686
687 -- See Note [The binders/kind/arity fields of a TyCon]
688 tyConBinders :: [TyConBinder], -- ^ Full binders
689 tyConTyVars :: [TyVar], -- ^ TyVar binders
690 tyConResKind :: Kind, -- ^ Result kind
691 tyConKind :: Kind, -- ^ Kind of this TyCon
692 tyConArity :: Arity, -- ^ Arity
693 -- tyConTyVars scope over: synTcRhs
694
695 tcRoles :: [Role], -- ^ The role for each type variable
696 -- This list has length = tyConArity
697 -- See also Note [TyCon Role signatures]
698
699 synTcRhs :: Type, -- ^ Contains information about the expansion
700 -- of the synonym
701
702 synIsTau :: Bool, -- True <=> the RHS of this synonym does not
703 -- have any foralls, after expanding any
704 -- nested synonyms
705 synIsFamFree :: Bool -- True <=> the RHS of this synonym does not mention
706 -- any type synonym families (data families
707 -- are fine), again after expanding any
708 -- nested synonyms
709 }
710
711 -- | Represents families (both type and data)
712 -- Argument roles are all Nominal
713 | FamilyTyCon {
714 tyConUnique :: Unique, -- ^ A Unique of this TyCon. Invariant:
715 -- identical to Unique of Name stored in
716 -- tyConName field.
717
718 tyConName :: Name, -- ^ Name of the constructor
719
720 -- See Note [The binders/kind/arity fields of a TyCon]
721 tyConBinders :: [TyConBinder], -- ^ Full binders
722 tyConTyVars :: [TyVar], -- ^ TyVar binders
723 tyConResKind :: Kind, -- ^ Result kind
724 tyConKind :: Kind, -- ^ Kind of this TyCon
725 tyConArity :: Arity, -- ^ Arity
726 -- tyConTyVars connect an associated family TyCon
727 -- with its parent class; see TcValidity.checkConsistentFamInst
728
729 famTcResVar :: Maybe Name, -- ^ Name of result type variable, used
730 -- for pretty-printing with --show-iface
731 -- and for reifying TyCon in Template
732 -- Haskell
733
734 famTcFlav :: FamTyConFlav, -- ^ Type family flavour: open, closed,
735 -- abstract, built-in. See comments for
736 -- FamTyConFlav
737
738 famTcParent :: Maybe Class, -- ^ For *associated* type/data families
739 -- The class in whose declaration the family is declared
740 -- See Note [Associated families and their parent class]
741
742 famTcInj :: Injectivity -- ^ is this a type family injective in
743 -- its type variables? Nothing if no
744 -- injectivity annotation was given
745 }
746
747 -- | Primitive types; cannot be defined in Haskell. This includes
748 -- the usual suspects (such as @Int#@) as well as foreign-imported
749 -- types and kinds (@*@, @#@, and @?@)
750 | PrimTyCon {
751 tyConUnique :: Unique, -- ^ A Unique of this TyCon. Invariant:
752 -- identical to Unique of Name stored in
753 -- tyConName field.
754
755 tyConName :: Name, -- ^ Name of the constructor
756
757 -- See Note [The binders/kind/arity fields of a TyCon]
758 tyConBinders :: [TyConBinder], -- ^ Full binders
759 tyConResKind :: Kind, -- ^ Result kind
760 tyConKind :: Kind, -- ^ Kind of this TyCon
761 tyConArity :: Arity, -- ^ Arity
762
763 tcRoles :: [Role], -- ^ The role for each type variable
764 -- This list has length = tyConArity
765 -- See also Note [TyCon Role signatures]
766
767 isUnlifted :: Bool, -- ^ Most primitive tycons are unlifted (may
768 -- not contain bottom) but other are lifted,
769 -- e.g. @RealWorld@
770 -- Only relevant if tyConKind = *
771
772 primRepName :: Maybe TyConRepName -- Only relevant for kind TyCons
773 -- i.e, *, #, ?
774 }
775
776 -- | Represents promoted data constructor.
777 | PromotedDataCon { -- See Note [Promoted data constructors]
778 tyConUnique :: Unique, -- ^ Same Unique as the data constructor
779 tyConName :: Name, -- ^ Same Name as the data constructor
780
781 -- See Note [The binders/kind/arity fields of a TyCon]
782 tyConBinders :: [TyConBinder], -- ^ Full binders
783 tyConResKind :: Kind, -- ^ Result kind
784 tyConKind :: Kind, -- ^ Kind of this TyCon
785 tyConArity :: Arity, -- ^ Arity
786
787 tcRoles :: [Role], -- ^ Roles: N for kind vars, R for type vars
788 dataCon :: DataCon, -- ^ Corresponding data constructor
789 tcRepName :: TyConRepName,
790 promDcRepInfo :: RuntimeRepInfo -- ^ See comments with 'RuntimeRepInfo'
791 }
792
793 -- | These exist only during a recursive type/class type-checking knot.
794 | TcTyCon {
795 tyConUnique :: Unique,
796 tyConName :: Name,
797
798 -- See Note [The binders/kind/arity fields of a TyCon]
799 tyConBinders :: [TyConBinder], -- ^ Full binders
800 tyConTyVars :: [TyVar], -- ^ TyVar binders
801 tyConResKind :: Kind, -- ^ Result kind
802 tyConKind :: Kind, -- ^ Kind of this TyCon
803 tyConArity :: Arity, -- ^ Arity
804
805 tcTyConScopedTyVars :: [TyVar], -- ^ Scoped tyvars over the
806 -- tycon's body. See Note [TcTyCon]
807 tcTyConFlavour :: TyConFlavour
808 -- ^ What sort of 'TyCon' this represents.
809 }
810
811 -- | Represents right-hand-sides of 'TyCon's for algebraic types
812 data AlgTyConRhs
813
814 -- | Says that we know nothing about this data type, except that
815 -- it's represented by a pointer. Used when we export a data type
816 -- abstractly into an .hi file.
817 = AbstractTyCon
818
819 -- | Information about those 'TyCon's derived from a @data@
820 -- declaration. This includes data types with no constructors at
821 -- all.
822 | DataTyCon {
823 data_cons :: [DataCon],
824 -- ^ The data type constructors; can be empty if the
825 -- user declares the type to have no constructors
826 --
827 -- INVARIANT: Kept in order of increasing 'DataCon'
828 -- tag (see the tag assignment in DataCon.mkDataCon)
829
830 is_enum :: Bool -- ^ Cached value: is this an enumeration type?
831 -- See Note [Enumeration types]
832 }
833
834 | TupleTyCon { -- A boxed, unboxed, or constraint tuple
835 data_con :: DataCon, -- NB: it can be an *unboxed* tuple
836 tup_sort :: TupleSort -- ^ Is this a boxed, unboxed or constraint
837 -- tuple?
838 }
839
840 | SumTyCon {
841 data_cons :: [DataCon]
842 }
843
844 -- | Information about those 'TyCon's derived from a @newtype@ declaration
845 | NewTyCon {
846 data_con :: DataCon, -- ^ The unique constructor for the @newtype@.
847 -- It has no existentials
848
849 nt_rhs :: Type, -- ^ Cached value: the argument type of the
850 -- constructor, which is just the representation
851 -- type of the 'TyCon' (remember that @newtype@s
852 -- do not exist at runtime so need a different
853 -- representation type).
854 --
855 -- The free 'TyVar's of this type are the
856 -- 'tyConTyVars' from the corresponding 'TyCon'
857
858 nt_etad_rhs :: ([TyVar], Type),
859 -- ^ Same as the 'nt_rhs', but this time eta-reduced.
860 -- Hence the list of 'TyVar's in this field may be
861 -- shorter than the declared arity of the 'TyCon'.
862
863 -- See Note [Newtype eta]
864 nt_co :: CoAxiom Unbranched
865 -- The axiom coercion that creates the @newtype@
866 -- from the representation 'Type'.
867
868 -- See Note [Newtype coercions]
869 -- Invariant: arity = #tvs in nt_etad_rhs;
870 -- See Note [Newtype eta]
871 -- Watch out! If any newtypes become transparent
872 -- again check Trac #1072.
873 }
874
875 -- | Some promoted datacons signify extra info relevant to GHC. For example,
876 -- the @IntRep@ constructor of @RuntimeRep@ corresponds to the 'IntRep'
877 -- constructor of 'PrimRep'. This data structure allows us to store this
878 -- information right in the 'TyCon'. The other approach would be to look
879 -- up things like @RuntimeRep@'s @PrimRep@ by known-key every time.
880 data RuntimeRepInfo
881 = NoRRI -- ^ an ordinary promoted data con
882 | RuntimeRep ([Type] -> [PrimRep])
883 -- ^ A constructor of @RuntimeRep@. The argument to the function should
884 -- be the list of arguments to the promoted datacon.
885 | VecCount Int -- ^ A constructor of @VecCount@
886 | VecElem PrimElemRep -- ^ A constructor of @VecElem@
887
888 -- | Extract those 'DataCon's that we are able to learn about. Note
889 -- that visibility in this sense does not correspond to visibility in
890 -- the context of any particular user program!
891 visibleDataCons :: AlgTyConRhs -> [DataCon]
892 visibleDataCons (AbstractTyCon {}) = []
893 visibleDataCons (DataTyCon{ data_cons = cs }) = cs
894 visibleDataCons (NewTyCon{ data_con = c }) = [c]
895 visibleDataCons (TupleTyCon{ data_con = c }) = [c]
896 visibleDataCons (SumTyCon{ data_cons = cs }) = cs
897
898 -- ^ Both type classes as well as family instances imply implicit
899 -- type constructors. These implicit type constructors refer to their parent
900 -- structure (ie, the class or family from which they derive) using a type of
901 -- the following form.
902 data AlgTyConFlav
903 = -- | An ordinary type constructor has no parent.
904 VanillaAlgTyCon
905 TyConRepName
906
907 -- | An unboxed type constructor. The TyConRepName is a Maybe since we
908 -- currently don't allow unboxed sums to be Typeable since there are too
909 -- many of them. See #13276.
910 | UnboxedAlgTyCon
911 (Maybe TyConRepName)
912
913 -- | Type constructors representing a class dictionary.
914 -- See Note [ATyCon for classes] in TyCoRep
915 | ClassTyCon
916 Class -- INVARIANT: the classTyCon of this Class is the
917 -- current tycon
918 TyConRepName
919
920 -- | Type constructors representing an *instance* of a *data* family.
921 -- Parameters:
922 --
923 -- 1) The type family in question
924 --
925 -- 2) Instance types; free variables are the 'tyConTyVars'
926 -- of the current 'TyCon' (not the family one). INVARIANT:
927 -- the number of types matches the arity of the family 'TyCon'
928 --
929 -- 3) A 'CoTyCon' identifying the representation
930 -- type with the type instance family
931 | DataFamInstTyCon -- See Note [Data type families]
932 (CoAxiom Unbranched) -- The coercion axiom.
933 -- A *Representational* coercion,
934 -- of kind T ty1 ty2 ~R R:T a b c
935 -- where T is the family TyCon,
936 -- and R:T is the representation TyCon (ie this one)
937 -- and a,b,c are the tyConTyVars of this TyCon
938 --
939 -- BUT may be eta-reduced; see TcInstDcls
940 -- Note [Eta reduction for data family axioms]
941
942 -- Cached fields of the CoAxiom, but adjusted to
943 -- use the tyConTyVars of this TyCon
944 TyCon -- The family TyCon
945 [Type] -- Argument types (mentions the tyConTyVars of this TyCon)
946 -- No shorter in length than the tyConTyVars of the family TyCon
947 -- How could it be longer? See [Arity of data families] in FamInstEnv
948
949 -- E.g. data instance T [a] = ...
950 -- gives a representation tycon:
951 -- data R:TList a = ...
952 -- axiom co a :: T [a] ~ R:TList a
953 -- with R:TList's algTcParent = DataFamInstTyCon T [a] co
954
955 instance Outputable AlgTyConFlav where
956 ppr (VanillaAlgTyCon {}) = text "Vanilla ADT"
957 ppr (UnboxedAlgTyCon {}) = text "Unboxed ADT"
958 ppr (ClassTyCon cls _) = text "Class parent" <+> ppr cls
959 ppr (DataFamInstTyCon _ tc tys) = text "Family parent (family instance)"
960 <+> ppr tc <+> sep (map pprType tys)
961
962 -- | Checks the invariants of a 'AlgTyConFlav' given the appropriate type class
963 -- name, if any
964 okParent :: Name -> AlgTyConFlav -> Bool
965 okParent _ (VanillaAlgTyCon {}) = True
966 okParent _ (UnboxedAlgTyCon {}) = True
967 okParent tc_name (ClassTyCon cls _) = tc_name == tyConName (classTyCon cls)
968 okParent _ (DataFamInstTyCon _ fam_tc tys) = tys `lengthAtLeast` tyConArity fam_tc
969
970 isNoParent :: AlgTyConFlav -> Bool
971 isNoParent (VanillaAlgTyCon {}) = True
972 isNoParent _ = False
973
974 --------------------
975
976 data Injectivity
977 = NotInjective
978 | Injective [Bool] -- 1-1 with tyConTyVars (incl kind vars)
979 deriving( Eq )
980
981 -- | Information pertaining to the expansion of a type synonym (@type@)
982 data FamTyConFlav
983 = -- | Represents an open type family without a fixed right hand
984 -- side. Additional instances can appear at any time.
985 --
986 -- These are introduced by either a top level declaration:
987 --
988 -- > data family T a :: *
989 --
990 -- Or an associated data type declaration, within a class declaration:
991 --
992 -- > class C a b where
993 -- > data T b :: *
994 DataFamilyTyCon
995 TyConRepName
996
997 -- | An open type synonym family e.g. @type family F x y :: * -> *@
998 | OpenSynFamilyTyCon
999
1000 -- | A closed type synonym family e.g.
1001 -- @type family F x where { F Int = Bool }@
1002 | ClosedSynFamilyTyCon (Maybe (CoAxiom Branched))
1003 -- See Note [Closed type families]
1004
1005 -- | A closed type synonym family declared in an hs-boot file with
1006 -- type family F a where ..
1007 | AbstractClosedSynFamilyTyCon
1008
1009 -- | Built-in type family used by the TypeNats solver
1010 | BuiltInSynFamTyCon BuiltInSynFamily
1011
1012 instance Outputable FamTyConFlav where
1013 ppr (DataFamilyTyCon n) = text "data family" <+> ppr n
1014 ppr OpenSynFamilyTyCon = text "open type family"
1015 ppr (ClosedSynFamilyTyCon Nothing) = text "closed type family"
1016 ppr (ClosedSynFamilyTyCon (Just coax)) = text "closed type family" <+> ppr coax
1017 ppr AbstractClosedSynFamilyTyCon = text "abstract closed type family"
1018 ppr (BuiltInSynFamTyCon _) = text "built-in type family"
1019
1020 {- Note [Closed type families]
1021 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1022 * In an open type family you can add new instances later. This is the
1023 usual case.
1024
1025 * In a closed type family you can only put equations where the family
1026 is defined.
1027
1028 A non-empty closed type family has a single axiom with multiple
1029 branches, stored in the 'ClosedSynFamilyTyCon' constructor. A closed
1030 type family with no equations does not have an axiom, because there is
1031 nothing for the axiom to prove!
1032
1033
1034 Note [Promoted data constructors]
1035 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1036 All data constructors can be promoted to become a type constructor,
1037 via the PromotedDataCon alternative in TyCon.
1038
1039 * The TyCon promoted from a DataCon has the *same* Name and Unique as
1040 the DataCon. Eg. If the data constructor Data.Maybe.Just(unique 78,
1041 say) is promoted to a TyCon whose name is Data.Maybe.Just(unique 78)
1042
1043 * Small note: We promote the *user* type of the DataCon. Eg
1044 data T = MkT {-# UNPACK #-} !(Bool, Bool)
1045 The promoted kind is
1046 MkT :: (Bool,Bool) -> T
1047 *not*
1048 MkT :: Bool -> Bool -> T
1049
1050 Note [Enumeration types]
1051 ~~~~~~~~~~~~~~~~~~~~~~~~
1052 We define datatypes with no constructors to *not* be
1053 enumerations; this fixes trac #2578, Otherwise we
1054 end up generating an empty table for
1055 <mod>_<type>_closure_tbl
1056 which is used by tagToEnum# to map Int# to constructors
1057 in an enumeration. The empty table apparently upset
1058 the linker.
1059
1060 Moreover, all the data constructor must be enumerations, meaning
1061 they have type (forall abc. T a b c). GADTs are not enumerations.
1062 For example consider
1063 data T a where
1064 T1 :: T Int
1065 T2 :: T Bool
1066 T3 :: T a
1067 What would [T1 ..] be? [T1,T3] :: T Int? Easiest thing is to exclude them.
1068 See Trac #4528.
1069
1070 Note [Newtype coercions]
1071 ~~~~~~~~~~~~~~~~~~~~~~~~
1072 The NewTyCon field nt_co is a CoAxiom which is used for coercing from
1073 the representation type of the newtype, to the newtype itself. For
1074 example,
1075
1076 newtype T a = MkT (a -> a)
1077
1078 the NewTyCon for T will contain nt_co = CoT where CoT t : T t ~ t -> t.
1079
1080 In the case that the right hand side is a type application
1081 ending with the same type variables as the left hand side, we
1082 "eta-contract" the coercion. So if we had
1083
1084 newtype S a = MkT [a]
1085
1086 then we would generate the arity 0 axiom CoS : S ~ []. The
1087 primary reason we do this is to make newtype deriving cleaner.
1088
1089 In the paper we'd write
1090 axiom CoT : (forall t. T t) ~ (forall t. [t])
1091 and then when we used CoT at a particular type, s, we'd say
1092 CoT @ s
1093 which encodes as (TyConApp instCoercionTyCon [TyConApp CoT [], s])
1094
1095 Note [Newtype eta]
1096 ~~~~~~~~~~~~~~~~~~
1097 Consider
1098 newtype Parser a = MkParser (IO a) deriving Monad
1099 Are these two types equal (to Core)?
1100 Monad Parser
1101 Monad IO
1102 which we need to make the derived instance for Monad Parser.
1103
1104 Well, yes. But to see that easily we eta-reduce the RHS type of
1105 Parser, in this case to ([], Froogle), so that even unsaturated applications
1106 of Parser will work right. This eta reduction is done when the type
1107 constructor is built, and cached in NewTyCon.
1108
1109 Here's an example that I think showed up in practice
1110 Source code:
1111 newtype T a = MkT [a]
1112 newtype Foo m = MkFoo (forall a. m a -> Int)
1113
1114 w1 :: Foo []
1115 w1 = ...
1116
1117 w2 :: Foo T
1118 w2 = MkFoo (\(MkT x) -> case w1 of MkFoo f -> f x)
1119
1120 After desugaring, and discarding the data constructors for the newtypes,
1121 we get:
1122 w2 = w1 `cast` Foo CoT
1123 so the coercion tycon CoT must have
1124 kind: T ~ []
1125 and arity: 0
1126
1127 Note [TcTyCon]
1128 ~~~~~~~~~~~~~~
1129 TcTyCons are used for two distinct purposes
1130
1131 1. When recovering from a type error in a type declaration,
1132 we want to put the erroneous TyCon in the environment in a
1133 way that won't lead to more errors. We use a TcTyCon for this;
1134 see makeRecoveryTyCon.
1135
1136 2. When checking a type/class declaration (in module TcTyClsDecls), we come
1137 upon knowledge of the eventual tycon in bits and pieces. First, we use
1138 getInitialKinds to look over the user-provided kind signature of a tycon
1139 (including, for example, the number of parameters written to the tycon)
1140 to get an initial shape of the tycon's kind. Then, using these initial
1141 kinds, we kind-check the body of the tycon (class methods, data constructors,
1142 etc.), filling in the metavariables in the tycon's initial kind.
1143 We then generalize to get the tycon's final, fixed kind. Finally, once
1144 this has happened for all tycons in a mutually recursive group, we
1145 can desugar the lot.
1146
1147 For convenience, we store partially-known tycons in TcTyCons, which
1148 might store meta-variables. These TcTyCons are stored in the local
1149 environment in TcTyClsDecls, until the real full TyCons can be created
1150 during desugaring. A desugared program should never have a TcTyCon.
1151
1152 A challenging piece in all of this is that we end up taking three separate
1153 passes over every declaration: one in getInitialKind (this pass look only
1154 at the head, not the body), one in kcTyClDecls (to kind-check the body),
1155 and a final one in tcTyClDecls (to desugar). In the latter two passes,
1156 we need to connect the user-written type variables in an LHsQTyVars
1157 with the variables in the tycon's inferred kind. Because the tycon might
1158 not have a CUSK, this matching up is, in general, quite hard to do.
1159 (Look through the git history between Dec 2015 and Apr 2016 for
1160 TcHsType.splitTelescopeTvs!) Instead of trying, we just store the list
1161 of type variables to bring into scope in the later passes when we create
1162 a TcTyCon in getInitialKinds. Much easier this way! These tyvars are
1163 brought into scope in kcTyClTyVars and tcTyClTyVars, both in TcHsType.
1164
1165 It is important that the scoped type variables not be zonked, as some
1166 scoped type variables come into existence as SigTvs. If we zonk, the
1167 Unique will change and the user-written occurrences won't match up with
1168 what we expect.
1169
1170 In a TcTyCon, everything is zonked (except the scoped vars) after
1171 the kind-checking pass.
1172
1173 ************************************************************************
1174 * *
1175 TyConRepName
1176 * *
1177 ********************************************************************* -}
1178
1179 type TyConRepName = Name -- The Name of the top-level declaration
1180 -- $tcMaybe :: Data.Typeable.Internal.TyCon
1181 -- $tcMaybe = TyCon { tyConName = "Maybe", ... }
1182
1183 tyConRepName_maybe :: TyCon -> Maybe TyConRepName
1184 tyConRepName_maybe (FunTyCon { tcRepName = rep_nm })
1185 = Just rep_nm
1186 tyConRepName_maybe (PrimTyCon { primRepName = mb_rep_nm })
1187 = mb_rep_nm
1188 tyConRepName_maybe (AlgTyCon { algTcParent = parent })
1189 | VanillaAlgTyCon rep_nm <- parent = Just rep_nm
1190 | ClassTyCon _ rep_nm <- parent = Just rep_nm
1191 | UnboxedAlgTyCon rep_nm <- parent = rep_nm
1192 tyConRepName_maybe (FamilyTyCon { famTcFlav = DataFamilyTyCon rep_nm })
1193 = Just rep_nm
1194 tyConRepName_maybe (PromotedDataCon { tcRepName = rep_nm })
1195 = Just rep_nm
1196 tyConRepName_maybe _ = Nothing
1197
1198 -- | Make a 'Name' for the 'Typeable' representation of the given wired-in type
1199 mkPrelTyConRepName :: Name -> TyConRepName
1200 -- See Note [Grand plan for Typeable] in 'TcTypeable' in TcTypeable.
1201 mkPrelTyConRepName tc_name -- Prelude tc_name is always External,
1202 -- so nameModule will work
1203 = mkExternalName rep_uniq rep_mod rep_occ (nameSrcSpan tc_name)
1204 where
1205 name_occ = nameOccName tc_name
1206 name_mod = nameModule tc_name
1207 name_uniq = nameUnique tc_name
1208 rep_uniq | isTcOcc name_occ = tyConRepNameUnique name_uniq
1209 | otherwise = dataConRepNameUnique name_uniq
1210 (rep_mod, rep_occ) = tyConRepModOcc name_mod name_occ
1211
1212 -- | The name (and defining module) for the Typeable representation (TyCon) of a
1213 -- type constructor.
1214 --
1215 -- See Note [Grand plan for Typeable] in 'TcTypeable' in TcTypeable.
1216 tyConRepModOcc :: Module -> OccName -> (Module, OccName)
1217 tyConRepModOcc tc_module tc_occ = (rep_module, mkTyConRepOcc tc_occ)
1218 where
1219 rep_module
1220 | tc_module == gHC_PRIM = gHC_TYPES
1221 | otherwise = tc_module
1222
1223
1224 {- *********************************************************************
1225 * *
1226 PrimRep
1227 * *
1228 ************************************************************************
1229
1230 Note [rep swamp]
1231
1232 GHC has a rich selection of types that represent "primitive types" of
1233 one kind or another. Each of them makes a different set of
1234 distinctions, and mostly the differences are for good reasons,
1235 although it's probably true that we could merge some of these.
1236
1237 Roughly in order of "includes more information":
1238
1239 - A Width (cmm/CmmType) is simply a binary value with the specified
1240 number of bits. It may represent a signed or unsigned integer, a
1241 floating-point value, or an address.
1242
1243 data Width = W8 | W16 | W32 | W64 | W80 | W128
1244
1245 - Size, which is used in the native code generator, is Width +
1246 floating point information.
1247
1248 data Size = II8 | II16 | II32 | II64 | FF32 | FF64 | FF80
1249
1250 it is necessary because e.g. the instruction to move a 64-bit float
1251 on x86 (movsd) is different from the instruction to move a 64-bit
1252 integer (movq), so the mov instruction is parameterised by Size.
1253
1254 - CmmType wraps Width with more information: GC ptr, float, or
1255 other value.
1256
1257 data CmmType = CmmType CmmCat Width
1258
1259 data CmmCat -- "Category" (not exported)
1260 = GcPtrCat -- GC pointer
1261 | BitsCat -- Non-pointer
1262 | FloatCat -- Float
1263
1264 It is important to have GcPtr information in Cmm, since we generate
1265 info tables containing pointerhood for the GC from this. As for
1266 why we have float (and not signed/unsigned) here, see Note [Signed
1267 vs unsigned].
1268
1269 - ArgRep makes only the distinctions necessary for the call and
1270 return conventions of the STG machine. It is essentially CmmType
1271 + void.
1272
1273 - PrimRep makes a few more distinctions than ArgRep: it divides
1274 non-GC-pointers into signed/unsigned and addresses, information
1275 that is necessary for passing these values to foreign functions.
1276
1277 There's another tension here: whether the type encodes its size in
1278 bytes, or whether its size depends on the machine word size. Width
1279 and CmmType have the size built-in, whereas ArgRep and PrimRep do not.
1280
1281 This means to turn an ArgRep/PrimRep into a CmmType requires DynFlags.
1282
1283 On the other hand, CmmType includes some "nonsense" values, such as
1284 CmmType GcPtrCat W32 on a 64-bit machine.
1285 -}
1286
1287 -- | A 'PrimRep' is an abstraction of a type. It contains information that
1288 -- the code generator needs in order to pass arguments, return results,
1289 -- and store values of this type.
1290 data PrimRep
1291 = VoidRep
1292 | LiftedRep
1293 | UnliftedRep -- ^ Unlifted pointer
1294 | IntRep -- ^ Signed, word-sized value
1295 | WordRep -- ^ Unsigned, word-sized value
1296 | Int64Rep -- ^ Signed, 64 bit value (with 32-bit words only)
1297 | Word64Rep -- ^ Unsigned, 64 bit value (with 32-bit words only)
1298 | AddrRep -- ^ A pointer, but /not/ to a Haskell value (use '(Un)liftedRep')
1299 | FloatRep
1300 | DoubleRep
1301 | VecRep Int PrimElemRep -- ^ A vector
1302 deriving( Eq, Show )
1303
1304 data PrimElemRep
1305 = Int8ElemRep
1306 | Int16ElemRep
1307 | Int32ElemRep
1308 | Int64ElemRep
1309 | Word8ElemRep
1310 | Word16ElemRep
1311 | Word32ElemRep
1312 | Word64ElemRep
1313 | FloatElemRep
1314 | DoubleElemRep
1315 deriving( Eq, Show )
1316
1317 instance Outputable PrimRep where
1318 ppr r = text (show r)
1319
1320 instance Outputable PrimElemRep where
1321 ppr r = text (show r)
1322
1323 isVoidRep :: PrimRep -> Bool
1324 isVoidRep VoidRep = True
1325 isVoidRep _other = False
1326
1327 isGcPtrRep :: PrimRep -> Bool
1328 isGcPtrRep LiftedRep = True
1329 isGcPtrRep UnliftedRep = True
1330 isGcPtrRep _ = False
1331
1332 -- | Find the size of a 'PrimRep', in words
1333 primRepSizeW :: DynFlags -> PrimRep -> Int
1334 primRepSizeW _ IntRep = 1
1335 primRepSizeW _ WordRep = 1
1336 primRepSizeW dflags Int64Rep = wORD64_SIZE `quot` wORD_SIZE dflags
1337 primRepSizeW dflags Word64Rep = wORD64_SIZE `quot` wORD_SIZE dflags
1338 primRepSizeW _ FloatRep = 1 -- NB. might not take a full word
1339 primRepSizeW dflags DoubleRep = dOUBLE_SIZE dflags `quot` wORD_SIZE dflags
1340 primRepSizeW _ AddrRep = 1
1341 primRepSizeW _ LiftedRep = 1
1342 primRepSizeW _ UnliftedRep = 1
1343 primRepSizeW _ VoidRep = 0
1344 primRepSizeW dflags (VecRep len rep) = len * primElemRepSizeB rep `quot` wORD_SIZE dflags
1345
1346 primElemRepSizeB :: PrimElemRep -> Int
1347 primElemRepSizeB Int8ElemRep = 1
1348 primElemRepSizeB Int16ElemRep = 2
1349 primElemRepSizeB Int32ElemRep = 4
1350 primElemRepSizeB Int64ElemRep = 8
1351 primElemRepSizeB Word8ElemRep = 1
1352 primElemRepSizeB Word16ElemRep = 2
1353 primElemRepSizeB Word32ElemRep = 4
1354 primElemRepSizeB Word64ElemRep = 8
1355 primElemRepSizeB FloatElemRep = 4
1356 primElemRepSizeB DoubleElemRep = 8
1357
1358 -- | Return if Rep stands for floating type,
1359 -- returns Nothing for vector types.
1360 primRepIsFloat :: PrimRep -> Maybe Bool
1361 primRepIsFloat FloatRep = Just True
1362 primRepIsFloat DoubleRep = Just True
1363 primRepIsFloat (VecRep _ _) = Nothing
1364 primRepIsFloat _ = Just False
1365
1366
1367 {-
1368 ************************************************************************
1369 * *
1370 Field labels
1371 * *
1372 ************************************************************************
1373 -}
1374
1375 -- | The labels for the fields of this particular 'TyCon'
1376 tyConFieldLabels :: TyCon -> [FieldLabel]
1377 tyConFieldLabels tc = dFsEnvElts $ tyConFieldLabelEnv tc
1378
1379 -- | The labels for the fields of this particular 'TyCon'
1380 tyConFieldLabelEnv :: TyCon -> FieldLabelEnv
1381 tyConFieldLabelEnv tc
1382 | isAlgTyCon tc = algTcFields tc
1383 | otherwise = emptyDFsEnv
1384
1385 -- | Look up a field label belonging to this 'TyCon'
1386 lookupTyConFieldLabel :: FieldLabelString -> TyCon -> Maybe FieldLabel
1387 lookupTyConFieldLabel lbl tc = lookupDFsEnv (tyConFieldLabelEnv tc) lbl
1388
1389 -- | Make a map from strings to FieldLabels from all the data
1390 -- constructors of this algebraic tycon
1391 fieldsOfAlgTcRhs :: AlgTyConRhs -> FieldLabelEnv
1392 fieldsOfAlgTcRhs rhs = mkDFsEnv [ (flLabel fl, fl)
1393 | fl <- dataConsFields (visibleDataCons rhs) ]
1394 where
1395 -- Duplicates in this list will be removed by 'mkFsEnv'
1396 dataConsFields dcs = concatMap dataConFieldLabels dcs
1397
1398
1399 {-
1400 ************************************************************************
1401 * *
1402 \subsection{TyCon Construction}
1403 * *
1404 ************************************************************************
1405
1406 Note: the TyCon constructors all take a Kind as one argument, even though
1407 they could, in principle, work out their Kind from their other arguments.
1408 But to do so they need functions from Types, and that makes a nasty
1409 module mutual-recursion. And they aren't called from many places.
1410 So we compromise, and move their Kind calculation to the call site.
1411 -}
1412
1413 -- | Given the name of the function type constructor and it's kind, create the
1414 -- corresponding 'TyCon'. It is recomended to use 'TyCoRep.funTyCon' if you want
1415 -- this functionality
1416 mkFunTyCon :: Name -> [TyConBinder] -> Name -> TyCon
1417 mkFunTyCon name binders rep_nm
1418 = FunTyCon {
1419 tyConUnique = nameUnique name,
1420 tyConName = name,
1421 tyConBinders = binders,
1422 tyConResKind = liftedTypeKind,
1423 tyConKind = mkTyConKind binders liftedTypeKind,
1424 tyConArity = length binders,
1425 tcRepName = rep_nm
1426 }
1427
1428 -- | This is the making of an algebraic 'TyCon'. Notably, you have to
1429 -- pass in the generic (in the -XGenerics sense) information about the
1430 -- type constructor - you can get hold of it easily (see Generics
1431 -- module)
1432 mkAlgTyCon :: Name
1433 -> [TyConBinder] -- ^ Binders of the 'TyCon'
1434 -> Kind -- ^ Result kind
1435 -> [Role] -- ^ The roles for each TyVar
1436 -> Maybe CType -- ^ The C type this type corresponds to
1437 -- when using the CAPI FFI
1438 -> [PredType] -- ^ Stupid theta: see 'algTcStupidTheta'
1439 -> AlgTyConRhs -- ^ Information about data constructors
1440 -> AlgTyConFlav -- ^ What flavour is it?
1441 -- (e.g. vanilla, type family)
1442 -> Bool -- ^ Was the 'TyCon' declared with GADT syntax?
1443 -> TyCon
1444 mkAlgTyCon name binders res_kind roles cType stupid rhs parent gadt_syn
1445 = AlgTyCon {
1446 tyConName = name,
1447 tyConUnique = nameUnique name,
1448 tyConBinders = binders,
1449 tyConResKind = res_kind,
1450 tyConKind = mkTyConKind binders res_kind,
1451 tyConArity = length binders,
1452 tyConTyVars = binderVars binders,
1453 tcRoles = roles,
1454 tyConCType = cType,
1455 algTcStupidTheta = stupid,
1456 algTcRhs = rhs,
1457 algTcFields = fieldsOfAlgTcRhs rhs,
1458 algTcParent = ASSERT2( okParent name parent, ppr name $$ ppr parent ) parent,
1459 algTcGadtSyntax = gadt_syn
1460 }
1461
1462 -- | Simpler specialization of 'mkAlgTyCon' for classes
1463 mkClassTyCon :: Name -> [TyConBinder]
1464 -> [Role] -> AlgTyConRhs -> Class
1465 -> Name -> TyCon
1466 mkClassTyCon name binders roles rhs clas tc_rep_name
1467 = mkAlgTyCon name binders constraintKind roles Nothing [] rhs
1468 (ClassTyCon clas tc_rep_name)
1469 False
1470
1471 mkTupleTyCon :: Name
1472 -> [TyConBinder]
1473 -> Kind -- ^ Result kind of the 'TyCon'
1474 -> Arity -- ^ Arity of the tuple 'TyCon'
1475 -> DataCon
1476 -> TupleSort -- ^ Whether the tuple is boxed or unboxed
1477 -> AlgTyConFlav
1478 -> TyCon
1479 mkTupleTyCon name binders res_kind arity con sort parent
1480 = AlgTyCon {
1481 tyConUnique = nameUnique name,
1482 tyConName = name,
1483 tyConBinders = binders,
1484 tyConTyVars = binderVars binders,
1485 tyConResKind = res_kind,
1486 tyConKind = mkTyConKind binders res_kind,
1487 tyConArity = arity,
1488 tcRoles = replicate arity Representational,
1489 tyConCType = Nothing,
1490 algTcGadtSyntax = False,
1491 algTcStupidTheta = [],
1492 algTcRhs = TupleTyCon { data_con = con,
1493 tup_sort = sort },
1494 algTcFields = emptyDFsEnv,
1495 algTcParent = parent
1496 }
1497
1498 mkSumTyCon :: Name
1499 -> [TyConBinder]
1500 -> Kind -- ^ Kind of the resulting 'TyCon'
1501 -> Arity -- ^ Arity of the sum
1502 -> [TyVar] -- ^ 'TyVar's scoped over: see 'tyConTyVars'
1503 -> [DataCon]
1504 -> AlgTyConFlav
1505 -> TyCon
1506 mkSumTyCon name binders res_kind arity tyvars cons parent
1507 = AlgTyCon {
1508 tyConUnique = nameUnique name,
1509 tyConName = name,
1510 tyConBinders = binders,
1511 tyConTyVars = tyvars,
1512 tyConResKind = res_kind,
1513 tyConKind = mkTyConKind binders res_kind,
1514 tyConArity = arity,
1515 tcRoles = replicate arity Representational,
1516 tyConCType = Nothing,
1517 algTcGadtSyntax = False,
1518 algTcStupidTheta = [],
1519 algTcRhs = SumTyCon { data_cons = cons },
1520 algTcFields = emptyDFsEnv,
1521 algTcParent = parent
1522 }
1523
1524 -- | Makes a tycon suitable for use during type-checking.
1525 -- The only real need for this is for printing error messages during
1526 -- a recursive type/class type-checking knot. It has a kind because
1527 -- TcErrors sometimes calls typeKind.
1528 -- See also Note [Kind checking recursive type and class declarations]
1529 -- in TcTyClsDecls.
1530 mkTcTyCon :: Name
1531 -> [TyConBinder]
1532 -> Kind -- ^ /result/ kind only
1533 -> [TyVar] -- ^ Scoped type variables, see Note [TcTyCon]
1534 -> TyConFlavour -- ^ What sort of 'TyCon' this represents
1535 -> TyCon
1536 mkTcTyCon name binders res_kind scoped_tvs flav
1537 = TcTyCon { tyConUnique = getUnique name
1538 , tyConName = name
1539 , tyConTyVars = binderVars binders
1540 , tyConBinders = binders
1541 , tyConResKind = res_kind
1542 , tyConKind = mkTyConKind binders res_kind
1543 , tyConArity = length binders
1544 , tcTyConScopedTyVars = scoped_tvs
1545 , tcTyConFlavour = flav }
1546
1547 -- | Create an unlifted primitive 'TyCon', such as @Int#@.
1548 mkPrimTyCon :: Name -> [TyConBinder]
1549 -> Kind -- ^ /result/ kind, never levity-polymorphic
1550 -> [Role] -> TyCon
1551 mkPrimTyCon name binders res_kind roles
1552 = mkPrimTyCon' name binders res_kind roles True (Just $ mkPrelTyConRepName name)
1553
1554 -- | Kind constructors
1555 mkKindTyCon :: Name -> [TyConBinder]
1556 -> Kind -- ^ /result/ kind
1557 -> [Role] -> Name -> TyCon
1558 mkKindTyCon name binders res_kind roles rep_nm
1559 = tc
1560 where
1561 tc = mkPrimTyCon' name binders res_kind roles False (Just rep_nm)
1562
1563 -- | Create a lifted primitive 'TyCon' such as @RealWorld@
1564 mkLiftedPrimTyCon :: Name -> [TyConBinder]
1565 -> Kind -- ^ /result/ kind
1566 -> [Role] -> TyCon
1567 mkLiftedPrimTyCon name binders res_kind roles
1568 = mkPrimTyCon' name binders res_kind roles False (Just rep_nm)
1569 where rep_nm = mkPrelTyConRepName name
1570
1571 mkPrimTyCon' :: Name -> [TyConBinder]
1572 -> Kind -- ^ /result/ kind, never levity-polymorphic
1573 -- (If you need a levity-polymorphic PrimTyCon, change
1574 -- isTcLevPoly.)
1575 -> [Role]
1576 -> Bool -> Maybe TyConRepName -> TyCon
1577 mkPrimTyCon' name binders res_kind roles is_unlifted rep_nm
1578 = PrimTyCon {
1579 tyConName = name,
1580 tyConUnique = nameUnique name,
1581 tyConBinders = binders,
1582 tyConResKind = res_kind,
1583 tyConKind = mkTyConKind binders res_kind,
1584 tyConArity = length roles,
1585 tcRoles = roles,
1586 isUnlifted = is_unlifted,
1587 primRepName = rep_nm
1588 }
1589
1590 -- | Create a type synonym 'TyCon'
1591 mkSynonymTyCon :: Name -> [TyConBinder] -> Kind -- ^ /result/ kind
1592 -> [Role] -> Type -> Bool -> Bool -> TyCon
1593 mkSynonymTyCon name binders res_kind roles rhs is_tau is_fam_free
1594 = SynonymTyCon {
1595 tyConName = name,
1596 tyConUnique = nameUnique name,
1597 tyConBinders = binders,
1598 tyConResKind = res_kind,
1599 tyConKind = mkTyConKind binders res_kind,
1600 tyConArity = length binders,
1601 tyConTyVars = binderVars binders,
1602 tcRoles = roles,
1603 synTcRhs = rhs,
1604 synIsTau = is_tau,
1605 synIsFamFree = is_fam_free
1606 }
1607
1608 -- | Create a type family 'TyCon'
1609 mkFamilyTyCon :: Name -> [TyConBinder] -> Kind -- ^ /result/ kind
1610 -> Maybe Name -> FamTyConFlav
1611 -> Maybe Class -> Injectivity -> TyCon
1612 mkFamilyTyCon name binders res_kind resVar flav parent inj
1613 = FamilyTyCon
1614 { tyConUnique = nameUnique name
1615 , tyConName = name
1616 , tyConBinders = binders
1617 , tyConResKind = res_kind
1618 , tyConKind = mkTyConKind binders res_kind
1619 , tyConArity = length binders
1620 , tyConTyVars = binderVars binders
1621 , famTcResVar = resVar
1622 , famTcFlav = flav
1623 , famTcParent = parent
1624 , famTcInj = inj
1625 }
1626
1627
1628 -- | Create a promoted data constructor 'TyCon'
1629 -- Somewhat dodgily, we give it the same Name
1630 -- as the data constructor itself; when we pretty-print
1631 -- the TyCon we add a quote; see the Outputable TyCon instance
1632 mkPromotedDataCon :: DataCon -> Name -> TyConRepName
1633 -> [TyConBinder] -> Kind -> [Role]
1634 -> RuntimeRepInfo -> TyCon
1635 mkPromotedDataCon con name rep_name binders res_kind roles rep_info
1636 = PromotedDataCon {
1637 tyConUnique = nameUnique name,
1638 tyConName = name,
1639 tyConArity = length roles,
1640 tcRoles = roles,
1641 tyConBinders = binders,
1642 tyConResKind = res_kind,
1643 tyConKind = mkTyConKind binders res_kind,
1644 dataCon = con,
1645 tcRepName = rep_name,
1646 promDcRepInfo = rep_info
1647 }
1648
1649 isFunTyCon :: TyCon -> Bool
1650 isFunTyCon (FunTyCon {}) = True
1651 isFunTyCon _ = False
1652
1653 -- | Test if the 'TyCon' is algebraic but abstract (invisible data constructors)
1654 isAbstractTyCon :: TyCon -> Bool
1655 isAbstractTyCon (AlgTyCon { algTcRhs = AbstractTyCon }) = True
1656 isAbstractTyCon _ = False
1657
1658 -- | Make an fake, recovery 'TyCon' from an existing one.
1659 -- Used when recovering from errors
1660 makeRecoveryTyCon :: TyCon -> TyCon
1661 makeRecoveryTyCon tc
1662 = mkTcTyCon (tyConName tc)
1663 (tyConBinders tc) (tyConResKind tc)
1664 [{- no scoped vars -}]
1665 (tyConFlavour tc)
1666
1667 -- | Does this 'TyCon' represent something that cannot be defined in Haskell?
1668 isPrimTyCon :: TyCon -> Bool
1669 isPrimTyCon (PrimTyCon {}) = True
1670 isPrimTyCon _ = False
1671
1672 -- | Is this 'TyCon' unlifted (i.e. cannot contain bottom)? Note that this can
1673 -- only be true for primitive and unboxed-tuple 'TyCon's
1674 isUnliftedTyCon :: TyCon -> Bool
1675 isUnliftedTyCon (PrimTyCon {isUnlifted = is_unlifted})
1676 = is_unlifted
1677 isUnliftedTyCon (AlgTyCon { algTcRhs = rhs } )
1678 | TupleTyCon { tup_sort = sort } <- rhs
1679 = not (isBoxed (tupleSortBoxity sort))
1680 isUnliftedTyCon (AlgTyCon { algTcRhs = rhs } )
1681 | SumTyCon {} <- rhs
1682 = True
1683 isUnliftedTyCon _ = False
1684
1685 -- | Returns @True@ if the supplied 'TyCon' resulted from either a
1686 -- @data@ or @newtype@ declaration
1687 isAlgTyCon :: TyCon -> Bool
1688 isAlgTyCon (AlgTyCon {}) = True
1689 isAlgTyCon _ = False
1690
1691 -- | Returns @True@ for vanilla AlgTyCons -- that is, those created
1692 -- with a @data@ or @newtype@ declaration.
1693 isVanillaAlgTyCon :: TyCon -> Bool
1694 isVanillaAlgTyCon (AlgTyCon { algTcParent = VanillaAlgTyCon _ }) = True
1695 isVanillaAlgTyCon _ = False
1696
1697 isDataTyCon :: TyCon -> Bool
1698 -- ^ Returns @True@ for data types that are /definitely/ represented by
1699 -- heap-allocated constructors. These are scrutinised by Core-level
1700 -- @case@ expressions, and they get info tables allocated for them.
1701 --
1702 -- Generally, the function will be true for all @data@ types and false
1703 -- for @newtype@s, unboxed tuples, unboxed sums and type family
1704 -- 'TyCon's. But it is not guaranteed to return @True@ in all cases
1705 -- that it could.
1706 --
1707 -- NB: for a data type family, only the /instance/ 'TyCon's
1708 -- get an info table. The family declaration 'TyCon' does not
1709 isDataTyCon (AlgTyCon {algTcRhs = rhs})
1710 = case rhs of
1711 TupleTyCon { tup_sort = sort }
1712 -> isBoxed (tupleSortBoxity sort)
1713 SumTyCon {} -> False
1714 DataTyCon {} -> True
1715 NewTyCon {} -> False
1716 AbstractTyCon {} -> False -- We don't know, so return False
1717 isDataTyCon _ = False
1718
1719 -- | 'isInjectiveTyCon' is true of 'TyCon's for which this property holds
1720 -- (where X is the role passed in):
1721 -- If (T a1 b1 c1) ~X (T a2 b2 c2), then (a1 ~X1 a2), (b1 ~X2 b2), and (c1 ~X3 c2)
1722 -- (where X1, X2, and X3, are the roles given by tyConRolesX tc X)
1723 -- See also Note [Decomposing equality] in TcCanonical
1724 isInjectiveTyCon :: TyCon -> Role -> Bool
1725 isInjectiveTyCon _ Phantom = False
1726 isInjectiveTyCon (FunTyCon {}) _ = True
1727 isInjectiveTyCon (AlgTyCon {}) Nominal = True
1728 isInjectiveTyCon (AlgTyCon {algTcRhs = rhs}) Representational
1729 = isGenInjAlgRhs rhs
1730 isInjectiveTyCon (SynonymTyCon {}) _ = False
1731 isInjectiveTyCon (FamilyTyCon { famTcFlav = DataFamilyTyCon _ })
1732 Nominal = True
1733 isInjectiveTyCon (FamilyTyCon { famTcInj = Injective inj }) Nominal = and inj
1734 isInjectiveTyCon (FamilyTyCon {}) _ = False
1735 isInjectiveTyCon (PrimTyCon {}) _ = True
1736 isInjectiveTyCon (PromotedDataCon {}) _ = True
1737 isInjectiveTyCon (TcTyCon {}) _ = True
1738 -- Reply True for TcTyCon to minimise knock on type errors
1739 -- See Note [TcTyCon] item (1)
1740
1741 -- | 'isGenerativeTyCon' is true of 'TyCon's for which this property holds
1742 -- (where X is the role passed in):
1743 -- If (T tys ~X t), then (t's head ~X T).
1744 -- See also Note [Decomposing equality] in TcCanonical
1745 isGenerativeTyCon :: TyCon -> Role -> Bool
1746 isGenerativeTyCon (FamilyTyCon { famTcFlav = DataFamilyTyCon _ }) Nominal = True
1747 isGenerativeTyCon (FamilyTyCon {}) _ = False
1748 -- in all other cases, injectivity implies generativity
1749 isGenerativeTyCon tc r = isInjectiveTyCon tc r
1750
1751 -- | Is this an 'AlgTyConRhs' of a 'TyCon' that is generative and injective
1752 -- with respect to representational equality?
1753 isGenInjAlgRhs :: AlgTyConRhs -> Bool
1754 isGenInjAlgRhs (TupleTyCon {}) = True
1755 isGenInjAlgRhs (SumTyCon {}) = True
1756 isGenInjAlgRhs (DataTyCon {}) = True
1757 isGenInjAlgRhs (AbstractTyCon {}) = False
1758 isGenInjAlgRhs (NewTyCon {}) = False
1759
1760 -- | Is this 'TyCon' that for a @newtype@
1761 isNewTyCon :: TyCon -> Bool
1762 isNewTyCon (AlgTyCon {algTcRhs = NewTyCon {}}) = True
1763 isNewTyCon _ = False
1764
1765 -- | Take a 'TyCon' apart into the 'TyVar's it scopes over, the 'Type' it expands
1766 -- into, and (possibly) a coercion from the representation type to the @newtype@.
1767 -- Returns @Nothing@ if this is not possible.
1768 unwrapNewTyCon_maybe :: TyCon -> Maybe ([TyVar], Type, CoAxiom Unbranched)
1769 unwrapNewTyCon_maybe (AlgTyCon { tyConTyVars = tvs,
1770 algTcRhs = NewTyCon { nt_co = co,
1771 nt_rhs = rhs }})
1772 = Just (tvs, rhs, co)
1773 unwrapNewTyCon_maybe _ = Nothing
1774
1775 unwrapNewTyConEtad_maybe :: TyCon -> Maybe ([TyVar], Type, CoAxiom Unbranched)
1776 unwrapNewTyConEtad_maybe (AlgTyCon { algTcRhs = NewTyCon { nt_co = co,
1777 nt_etad_rhs = (tvs,rhs) }})
1778 = Just (tvs, rhs, co)
1779 unwrapNewTyConEtad_maybe _ = Nothing
1780
1781 isProductTyCon :: TyCon -> Bool
1782 -- True of datatypes or newtypes that have
1783 -- one, non-existential, data constructor
1784 -- See Note [Product types]
1785 isProductTyCon tc@(AlgTyCon {})
1786 = case algTcRhs tc of
1787 TupleTyCon {} -> True
1788 DataTyCon{ data_cons = [data_con] }
1789 -> null (dataConExTyVars data_con)
1790 NewTyCon {} -> True
1791 _ -> False
1792 isProductTyCon _ = False
1793
1794 isDataProductTyCon_maybe :: TyCon -> Maybe DataCon
1795 -- True of datatypes (not newtypes) with
1796 -- one, vanilla, data constructor
1797 -- See Note [Product types]
1798 isDataProductTyCon_maybe (AlgTyCon { algTcRhs = rhs })
1799 = case rhs of
1800 DataTyCon { data_cons = [con] }
1801 | null (dataConExTyVars con) -- non-existential
1802 -> Just con
1803 TupleTyCon { data_con = con }
1804 -> Just con
1805 _ -> Nothing
1806 isDataProductTyCon_maybe _ = Nothing
1807
1808 isDataSumTyCon_maybe :: TyCon -> Maybe [DataCon]
1809 isDataSumTyCon_maybe (AlgTyCon { algTcRhs = rhs })
1810 = case rhs of
1811 DataTyCon { data_cons = cons }
1812 | cons `lengthExceeds` 1
1813 , all (null . dataConExTyVars) cons -- FIXME(osa): Why do we need this?
1814 -> Just cons
1815 SumTyCon { data_cons = cons }
1816 | all (null . dataConExTyVars) cons -- FIXME(osa): Why do we need this?
1817 -> Just cons
1818 _ -> Nothing
1819 isDataSumTyCon_maybe _ = Nothing
1820
1821 {- Note [Product types]
1822 ~~~~~~~~~~~~~~~~~~~~~~~
1823 A product type is
1824 * A data type (not a newtype)
1825 * With one, boxed data constructor
1826 * That binds no existential type variables
1827
1828 The main point is that product types are amenable to unboxing for
1829 * Strict function calls; we can transform
1830 f (D a b) = e
1831 to
1832 fw a b = e
1833 via the worker/wrapper transformation. (Question: couldn't this
1834 work for existentials too?)
1835
1836 * CPR for function results; we can transform
1837 f x y = let ... in D a b
1838 to
1839 fw x y = let ... in (# a, b #)
1840
1841 Note that the data constructor /can/ have evidence arguments: equality
1842 constraints, type classes etc. So it can be GADT. These evidence
1843 arguments are simply value arguments, and should not get in the way.
1844 -}
1845
1846
1847 -- | Is this a 'TyCon' representing a regular H98 type synonym (@type@)?
1848 isTypeSynonymTyCon :: TyCon -> Bool
1849 isTypeSynonymTyCon (SynonymTyCon {}) = True
1850 isTypeSynonymTyCon _ = False
1851
1852 isTauTyCon :: TyCon -> Bool
1853 isTauTyCon (SynonymTyCon { synIsTau = is_tau }) = is_tau
1854 isTauTyCon _ = True
1855
1856 isFamFreeTyCon :: TyCon -> Bool
1857 isFamFreeTyCon (SynonymTyCon { synIsFamFree = fam_free }) = fam_free
1858 isFamFreeTyCon (FamilyTyCon { famTcFlav = flav }) = isDataFamFlav flav
1859 isFamFreeTyCon _ = True
1860
1861 -- As for newtypes, it is in some contexts important to distinguish between
1862 -- closed synonyms and synonym families, as synonym families have no unique
1863 -- right hand side to which a synonym family application can expand.
1864 --
1865
1866 -- | True iff we can decompose (T a b c) into ((T a b) c)
1867 -- I.e. is it injective and generative w.r.t nominal equality?
1868 -- That is, if (T a b) ~N d e f, is it always the case that
1869 -- (T ~N d), (a ~N e) and (b ~N f)?
1870 -- Specifically NOT true of synonyms (open and otherwise)
1871 --
1872 -- It'd be unusual to call mightBeUnsaturatedTyCon on a regular H98
1873 -- type synonym, because you should probably have expanded it first
1874 -- But regardless, it's not decomposable
1875 mightBeUnsaturatedTyCon :: TyCon -> Bool
1876 mightBeUnsaturatedTyCon = tcFlavourCanBeUnsaturated . tyConFlavour
1877
1878 -- | Is this an algebraic 'TyCon' declared with the GADT syntax?
1879 isGadtSyntaxTyCon :: TyCon -> Bool
1880 isGadtSyntaxTyCon (AlgTyCon { algTcGadtSyntax = res }) = res
1881 isGadtSyntaxTyCon _ = False
1882
1883 -- | Is this an algebraic 'TyCon' which is just an enumeration of values?
1884 isEnumerationTyCon :: TyCon -> Bool
1885 -- See Note [Enumeration types] in TyCon
1886 isEnumerationTyCon (AlgTyCon { tyConArity = arity, algTcRhs = rhs })
1887 = case rhs of
1888 DataTyCon { is_enum = res } -> res
1889 TupleTyCon {} -> arity == 0
1890 _ -> False
1891 isEnumerationTyCon _ = False
1892
1893 -- | Is this a 'TyCon', synonym or otherwise, that defines a family?
1894 isFamilyTyCon :: TyCon -> Bool
1895 isFamilyTyCon (FamilyTyCon {}) = True
1896 isFamilyTyCon _ = False
1897
1898 -- | Is this a 'TyCon', synonym or otherwise, that defines a family with
1899 -- instances?
1900 isOpenFamilyTyCon :: TyCon -> Bool
1901 isOpenFamilyTyCon (FamilyTyCon {famTcFlav = flav })
1902 | OpenSynFamilyTyCon <- flav = True
1903 | DataFamilyTyCon {} <- flav = True
1904 isOpenFamilyTyCon _ = False
1905
1906 -- | Is this a synonym 'TyCon' that can have may have further instances appear?
1907 isTypeFamilyTyCon :: TyCon -> Bool
1908 isTypeFamilyTyCon (FamilyTyCon { famTcFlav = flav }) = not (isDataFamFlav flav)
1909 isTypeFamilyTyCon _ = False
1910
1911 -- | Is this a synonym 'TyCon' that can have may have further instances appear?
1912 isDataFamilyTyCon :: TyCon -> Bool
1913 isDataFamilyTyCon (FamilyTyCon { famTcFlav = flav }) = isDataFamFlav flav
1914 isDataFamilyTyCon _ = False
1915
1916 -- | Is this an open type family TyCon?
1917 isOpenTypeFamilyTyCon :: TyCon -> Bool
1918 isOpenTypeFamilyTyCon (FamilyTyCon {famTcFlav = OpenSynFamilyTyCon }) = True
1919 isOpenTypeFamilyTyCon _ = False
1920
1921 -- | Is this a non-empty closed type family? Returns 'Nothing' for
1922 -- abstract or empty closed families.
1923 isClosedSynFamilyTyConWithAxiom_maybe :: TyCon -> Maybe (CoAxiom Branched)
1924 isClosedSynFamilyTyConWithAxiom_maybe
1925 (FamilyTyCon {famTcFlav = ClosedSynFamilyTyCon mb}) = mb
1926 isClosedSynFamilyTyConWithAxiom_maybe _ = Nothing
1927
1928 -- | Try to read the injectivity information from a FamilyTyCon.
1929 -- For every other TyCon this function panics.
1930 familyTyConInjectivityInfo :: TyCon -> Injectivity
1931 familyTyConInjectivityInfo (FamilyTyCon { famTcInj = inj }) = inj
1932 familyTyConInjectivityInfo _ = panic "familyTyConInjectivityInfo"
1933
1934 isBuiltInSynFamTyCon_maybe :: TyCon -> Maybe BuiltInSynFamily
1935 isBuiltInSynFamTyCon_maybe
1936 (FamilyTyCon {famTcFlav = BuiltInSynFamTyCon ops }) = Just ops
1937 isBuiltInSynFamTyCon_maybe _ = Nothing
1938
1939 isDataFamFlav :: FamTyConFlav -> Bool
1940 isDataFamFlav (DataFamilyTyCon {}) = True -- Data family
1941 isDataFamFlav _ = False -- Type synonym family
1942
1943 -- | Are we able to extract information 'TyVar' to class argument list
1944 -- mapping from a given 'TyCon'?
1945 isTyConAssoc :: TyCon -> Bool
1946 isTyConAssoc tc = isJust (tyConAssoc_maybe tc)
1947
1948 tyConAssoc_maybe :: TyCon -> Maybe Class
1949 tyConAssoc_maybe (FamilyTyCon { famTcParent = mb_cls }) = mb_cls
1950 tyConAssoc_maybe _ = Nothing
1951
1952 -- The unit tycon didn't used to be classed as a tuple tycon
1953 -- but I thought that was silly so I've undone it
1954 -- If it can't be for some reason, it should be a AlgTyCon
1955 isTupleTyCon :: TyCon -> Bool
1956 -- ^ Does this 'TyCon' represent a tuple?
1957 --
1958 -- NB: when compiling @Data.Tuple@, the tycons won't reply @True@ to
1959 -- 'isTupleTyCon', because they are built as 'AlgTyCons'. However they
1960 -- get spat into the interface file as tuple tycons, so I don't think
1961 -- it matters.
1962 isTupleTyCon (AlgTyCon { algTcRhs = TupleTyCon {} }) = True
1963 isTupleTyCon _ = False
1964
1965 tyConTuple_maybe :: TyCon -> Maybe TupleSort
1966 tyConTuple_maybe (AlgTyCon { algTcRhs = rhs })
1967 | TupleTyCon { tup_sort = sort} <- rhs = Just sort
1968 tyConTuple_maybe _ = Nothing
1969
1970 -- | Is this the 'TyCon' for an unboxed tuple?
1971 isUnboxedTupleTyCon :: TyCon -> Bool
1972 isUnboxedTupleTyCon (AlgTyCon { algTcRhs = rhs })
1973 | TupleTyCon { tup_sort = sort } <- rhs
1974 = not (isBoxed (tupleSortBoxity sort))
1975 isUnboxedTupleTyCon _ = False
1976
1977 -- | Is this the 'TyCon' for a boxed tuple?
1978 isBoxedTupleTyCon :: TyCon -> Bool
1979 isBoxedTupleTyCon (AlgTyCon { algTcRhs = rhs })
1980 | TupleTyCon { tup_sort = sort } <- rhs
1981 = isBoxed (tupleSortBoxity sort)
1982 isBoxedTupleTyCon _ = False
1983
1984 -- | Is this the 'TyCon' for an unboxed sum?
1985 isUnboxedSumTyCon :: TyCon -> Bool
1986 isUnboxedSumTyCon (AlgTyCon { algTcRhs = rhs })
1987 | SumTyCon {} <- rhs
1988 = True
1989 isUnboxedSumTyCon _ = False
1990
1991 -- | Is this the 'TyCon' for a /promoted/ tuple?
1992 isPromotedTupleTyCon :: TyCon -> Bool
1993 isPromotedTupleTyCon tyCon
1994 | Just dataCon <- isPromotedDataCon_maybe tyCon
1995 , isTupleTyCon (dataConTyCon dataCon) = True
1996 | otherwise = False
1997
1998 -- | Is this a PromotedDataCon?
1999 isPromotedDataCon :: TyCon -> Bool
2000 isPromotedDataCon (PromotedDataCon {}) = True
2001 isPromotedDataCon _ = False
2002
2003 -- | Retrieves the promoted DataCon if this is a PromotedDataCon;
2004 isPromotedDataCon_maybe :: TyCon -> Maybe DataCon
2005 isPromotedDataCon_maybe (PromotedDataCon { dataCon = dc }) = Just dc
2006 isPromotedDataCon_maybe _ = Nothing
2007
2008 -- | Is this tycon really meant for use at the kind level? That is,
2009 -- should it be permitted without -XDataKinds?
2010 isKindTyCon :: TyCon -> Bool
2011 isKindTyCon tc = getUnique tc `elementOfUniqSet` kindTyConKeys
2012
2013 -- | These TyCons should be allowed at the kind level, even without
2014 -- -XDataKinds.
2015 kindTyConKeys :: UniqSet Unique
2016 kindTyConKeys = unionManyUniqSets
2017 ( mkUniqSet [ liftedTypeKindTyConKey, starKindTyConKey, unicodeStarKindTyConKey
2018 , constraintKindTyConKey, tYPETyConKey ]
2019 : map (mkUniqSet . tycon_with_datacons) [ runtimeRepTyCon
2020 , vecCountTyCon, vecElemTyCon ] )
2021 where
2022 tycon_with_datacons tc = getUnique tc : map getUnique (tyConDataCons tc)
2023
2024 isLiftedTypeKindTyConName :: Name -> Bool
2025 isLiftedTypeKindTyConName
2026 = (`hasKey` liftedTypeKindTyConKey) <||>
2027 (`hasKey` starKindTyConKey) <||>
2028 (`hasKey` unicodeStarKindTyConKey)
2029
2030 -- | Identifies implicit tycons that, in particular, do not go into interface
2031 -- files (because they are implicitly reconstructed when the interface is
2032 -- read).
2033 --
2034 -- Note that:
2035 --
2036 -- * Associated families are implicit, as they are re-constructed from
2037 -- the class declaration in which they reside, and
2038 --
2039 -- * Family instances are /not/ implicit as they represent the instance body
2040 -- (similar to a @dfun@ does that for a class instance).
2041 --
2042 -- * Tuples are implicit iff they have a wired-in name
2043 -- (namely: boxed and unboxed tupeles are wired-in and implicit,
2044 -- but constraint tuples are not)
2045 isImplicitTyCon :: TyCon -> Bool
2046 isImplicitTyCon (FunTyCon {}) = True
2047 isImplicitTyCon (PrimTyCon {}) = True
2048 isImplicitTyCon (PromotedDataCon {}) = True
2049 isImplicitTyCon (AlgTyCon { algTcRhs = rhs, tyConName = name })
2050 | TupleTyCon {} <- rhs = isWiredInName name
2051 | SumTyCon {} <- rhs = True
2052 | otherwise = False
2053 isImplicitTyCon (FamilyTyCon { famTcParent = parent }) = isJust parent
2054 isImplicitTyCon (SynonymTyCon {}) = False
2055 isImplicitTyCon (TcTyCon {}) = False
2056
2057 tyConCType_maybe :: TyCon -> Maybe CType
2058 tyConCType_maybe tc@(AlgTyCon {}) = tyConCType tc
2059 tyConCType_maybe _ = Nothing
2060
2061 -- | Is this a TcTyCon? (That is, one only used during type-checking?)
2062 isTcTyCon :: TyCon -> Bool
2063 isTcTyCon (TcTyCon {}) = True
2064 isTcTyCon _ = False
2065
2066 -- | Could this TyCon ever be levity-polymorphic when fully applied?
2067 -- True is safe. False means we're sure. Does only a quick check
2068 -- based on the TyCon's category.
2069 -- Precondition: The fully-applied TyCon has kind (TYPE blah)
2070 isTcLevPoly :: TyCon -> Bool
2071 isTcLevPoly FunTyCon{} = False
2072 isTcLevPoly (AlgTyCon { algTcParent = UnboxedAlgTyCon _ }) = True
2073 isTcLevPoly AlgTyCon{} = False
2074 isTcLevPoly SynonymTyCon{} = True
2075 isTcLevPoly FamilyTyCon{} = True
2076 isTcLevPoly PrimTyCon{} = False
2077 isTcLevPoly TcTyCon{} = False
2078 isTcLevPoly tc@PromotedDataCon{} = pprPanic "isTcLevPoly datacon" (ppr tc)
2079
2080 {-
2081 -----------------------------------------------
2082 -- Expand type-constructor applications
2083 -----------------------------------------------
2084 -}
2085
2086 expandSynTyCon_maybe
2087 :: TyCon
2088 -> [tyco] -- ^ Arguments to 'TyCon'
2089 -> Maybe ([(TyVar,tyco)],
2090 Type,
2091 [tyco]) -- ^ Returns a 'TyVar' substitution, the body
2092 -- type of the synonym (not yet substituted)
2093 -- and any arguments remaining from the
2094 -- application
2095
2096 -- ^ Expand a type synonym application, if any
2097 expandSynTyCon_maybe tc tys
2098 | SynonymTyCon { tyConTyVars = tvs, synTcRhs = rhs, tyConArity = arity } <- tc
2099 = case tys `listLengthCmp` arity of
2100 GT -> Just (tvs `zip` tys, rhs, drop arity tys)
2101 EQ -> Just (tvs `zip` tys, rhs, [])
2102 LT -> Nothing
2103 | otherwise
2104 = Nothing
2105
2106 ----------------
2107
2108 -- | Check if the tycon actually refers to a proper `data` or `newtype`
2109 -- with user defined constructors rather than one from a class or other
2110 -- construction.
2111
2112 -- NB: This is only used in TcRnExports.checkPatSynParent to determine if an
2113 -- exported tycon can have a pattern synonym bundled with it, e.g.,
2114 -- module Foo (TyCon(.., PatSyn)) where
2115 isTyConWithSrcDataCons :: TyCon -> Bool
2116 isTyConWithSrcDataCons (AlgTyCon { algTcRhs = rhs, algTcParent = parent }) =
2117 case rhs of
2118 DataTyCon {} -> isSrcParent
2119 NewTyCon {} -> isSrcParent
2120 TupleTyCon {} -> isSrcParent
2121 _ -> False
2122 where
2123 isSrcParent = isNoParent parent
2124 isTyConWithSrcDataCons (FamilyTyCon { famTcFlav = DataFamilyTyCon {} })
2125 = True -- #14058
2126 isTyConWithSrcDataCons _ = False
2127
2128
2129 -- | As 'tyConDataCons_maybe', but returns the empty list of constructors if no
2130 -- constructors could be found
2131 tyConDataCons :: TyCon -> [DataCon]
2132 -- It's convenient for tyConDataCons to return the
2133 -- empty list for type synonyms etc
2134 tyConDataCons tycon = tyConDataCons_maybe tycon `orElse` []
2135
2136 -- | Determine the 'DataCon's originating from the given 'TyCon', if the 'TyCon'
2137 -- is the sort that can have any constructors (note: this does not include
2138 -- abstract algebraic types)
2139 tyConDataCons_maybe :: TyCon -> Maybe [DataCon]
2140 tyConDataCons_maybe (AlgTyCon {algTcRhs = rhs})
2141 = case rhs of
2142 DataTyCon { data_cons = cons } -> Just cons
2143 NewTyCon { data_con = con } -> Just [con]
2144 TupleTyCon { data_con = con } -> Just [con]
2145 SumTyCon { data_cons = cons } -> Just cons
2146 _ -> Nothing
2147 tyConDataCons_maybe _ = Nothing
2148
2149 -- | If the given 'TyCon' has a /single/ data constructor, i.e. it is a @data@
2150 -- type with one alternative, a tuple type or a @newtype@ then that constructor
2151 -- is returned. If the 'TyCon' has more than one constructor, or represents a
2152 -- primitive or function type constructor then @Nothing@ is returned. In any
2153 -- other case, the function panics
2154 tyConSingleDataCon_maybe :: TyCon -> Maybe DataCon
2155 tyConSingleDataCon_maybe (AlgTyCon { algTcRhs = rhs })
2156 = case rhs of
2157 DataTyCon { data_cons = [c] } -> Just c
2158 TupleTyCon { data_con = c } -> Just c
2159 NewTyCon { data_con = c } -> Just c
2160 _ -> Nothing
2161 tyConSingleDataCon_maybe _ = Nothing
2162
2163 tyConSingleDataCon :: TyCon -> DataCon
2164 tyConSingleDataCon tc
2165 = case tyConSingleDataCon_maybe tc of
2166 Just c -> c
2167 Nothing -> pprPanic "tyConDataCon" (ppr tc)
2168
2169 tyConSingleAlgDataCon_maybe :: TyCon -> Maybe DataCon
2170 -- Returns (Just con) for single-constructor
2171 -- *algebraic* data types *not* newtypes
2172 tyConSingleAlgDataCon_maybe (AlgTyCon { algTcRhs = rhs })
2173 = case rhs of
2174 DataTyCon { data_cons = [c] } -> Just c
2175 TupleTyCon { data_con = c } -> Just c
2176 _ -> Nothing
2177 tyConSingleAlgDataCon_maybe _ = Nothing
2178
2179 -- | Determine the number of value constructors a 'TyCon' has. Panics if the
2180 -- 'TyCon' is not algebraic or a tuple
2181 tyConFamilySize :: TyCon -> Int
2182 tyConFamilySize tc@(AlgTyCon { algTcRhs = rhs })
2183 = case rhs of
2184 DataTyCon { data_cons = cons } -> length cons
2185 NewTyCon {} -> 1
2186 TupleTyCon {} -> 1
2187 SumTyCon { data_cons = cons } -> length cons
2188 _ -> pprPanic "tyConFamilySize 1" (ppr tc)
2189 tyConFamilySize tc = pprPanic "tyConFamilySize 2" (ppr tc)
2190
2191 -- | Extract an 'AlgTyConRhs' with information about data constructors from an
2192 -- algebraic or tuple 'TyCon'. Panics for any other sort of 'TyCon'
2193 algTyConRhs :: TyCon -> AlgTyConRhs
2194 algTyConRhs (AlgTyCon {algTcRhs = rhs}) = rhs
2195 algTyConRhs other = pprPanic "algTyConRhs" (ppr other)
2196
2197 -- | Extract type variable naming the result of injective type family
2198 tyConFamilyResVar_maybe :: TyCon -> Maybe Name
2199 tyConFamilyResVar_maybe (FamilyTyCon {famTcResVar = res}) = res
2200 tyConFamilyResVar_maybe _ = Nothing
2201
2202 -- | Get the list of roles for the type parameters of a TyCon
2203 tyConRoles :: TyCon -> [Role]
2204 -- See also Note [TyCon Role signatures]
2205 tyConRoles tc
2206 = case tc of
2207 { FunTyCon {} -> const_role Representational
2208 ; AlgTyCon { tcRoles = roles } -> roles
2209 ; SynonymTyCon { tcRoles = roles } -> roles
2210 ; FamilyTyCon {} -> const_role Nominal
2211 ; PrimTyCon { tcRoles = roles } -> roles
2212 ; PromotedDataCon { tcRoles = roles } -> roles
2213 ; TcTyCon {} -> const_role Nominal
2214 }
2215 where
2216 const_role r = replicate (tyConArity tc) r
2217
2218 -- | Extract the bound type variables and type expansion of a type synonym
2219 -- 'TyCon'. Panics if the 'TyCon' is not a synonym
2220 newTyConRhs :: TyCon -> ([TyVar], Type)
2221 newTyConRhs (AlgTyCon {tyConTyVars = tvs, algTcRhs = NewTyCon { nt_rhs = rhs }})
2222 = (tvs, rhs)
2223 newTyConRhs tycon = pprPanic "newTyConRhs" (ppr tycon)
2224
2225 -- | The number of type parameters that need to be passed to a newtype to
2226 -- resolve it. May be less than in the definition if it can be eta-contracted.
2227 newTyConEtadArity :: TyCon -> Int
2228 newTyConEtadArity (AlgTyCon {algTcRhs = NewTyCon { nt_etad_rhs = tvs_rhs }})
2229 = length (fst tvs_rhs)
2230 newTyConEtadArity tycon = pprPanic "newTyConEtadArity" (ppr tycon)
2231
2232 -- | Extract the bound type variables and type expansion of an eta-contracted
2233 -- type synonym 'TyCon'. Panics if the 'TyCon' is not a synonym
2234 newTyConEtadRhs :: TyCon -> ([TyVar], Type)
2235 newTyConEtadRhs (AlgTyCon {algTcRhs = NewTyCon { nt_etad_rhs = tvs_rhs }}) = tvs_rhs
2236 newTyConEtadRhs tycon = pprPanic "newTyConEtadRhs" (ppr tycon)
2237
2238 -- | Extracts the @newtype@ coercion from such a 'TyCon', which can be used to
2239 -- construct something with the @newtype@s type from its representation type
2240 -- (right hand side). If the supplied 'TyCon' is not a @newtype@, returns
2241 -- @Nothing@
2242 newTyConCo_maybe :: TyCon -> Maybe (CoAxiom Unbranched)
2243 newTyConCo_maybe (AlgTyCon {algTcRhs = NewTyCon { nt_co = co }}) = Just co
2244 newTyConCo_maybe _ = Nothing
2245
2246 newTyConCo :: TyCon -> CoAxiom Unbranched
2247 newTyConCo tc = case newTyConCo_maybe tc of
2248 Just co -> co
2249 Nothing -> pprPanic "newTyConCo" (ppr tc)
2250
2251 newTyConDataCon_maybe :: TyCon -> Maybe DataCon
2252 newTyConDataCon_maybe (AlgTyCon {algTcRhs = NewTyCon { data_con = con }}) = Just con
2253 newTyConDataCon_maybe _ = Nothing
2254
2255 -- | Find the \"stupid theta\" of the 'TyCon'. A \"stupid theta\" is the context
2256 -- to the left of an algebraic type declaration, e.g. @Eq a@ in the declaration
2257 -- @data Eq a => T a ...@
2258 tyConStupidTheta :: TyCon -> [PredType]
2259 tyConStupidTheta (AlgTyCon {algTcStupidTheta = stupid}) = stupid
2260 tyConStupidTheta tycon = pprPanic "tyConStupidTheta" (ppr tycon)
2261
2262 -- | Extract the 'TyVar's bound by a vanilla type synonym
2263 -- and the corresponding (unsubstituted) right hand side.
2264 synTyConDefn_maybe :: TyCon -> Maybe ([TyVar], Type)
2265 synTyConDefn_maybe (SynonymTyCon {tyConTyVars = tyvars, synTcRhs = ty})
2266 = Just (tyvars, ty)
2267 synTyConDefn_maybe _ = Nothing
2268
2269 -- | Extract the information pertaining to the right hand side of a type synonym
2270 -- (@type@) declaration.
2271 synTyConRhs_maybe :: TyCon -> Maybe Type
2272 synTyConRhs_maybe (SynonymTyCon {synTcRhs = rhs}) = Just rhs
2273 synTyConRhs_maybe _ = Nothing
2274
2275 -- | Extract the flavour of a type family (with all the extra information that
2276 -- it carries)
2277 famTyConFlav_maybe :: TyCon -> Maybe FamTyConFlav
2278 famTyConFlav_maybe (FamilyTyCon {famTcFlav = flav}) = Just flav
2279 famTyConFlav_maybe _ = Nothing
2280
2281 -- | Is this 'TyCon' that for a class instance?
2282 isClassTyCon :: TyCon -> Bool
2283 isClassTyCon (AlgTyCon {algTcParent = ClassTyCon {}}) = True
2284 isClassTyCon _ = False
2285
2286 -- | If this 'TyCon' is that for a class instance, return the class it is for.
2287 -- Otherwise returns @Nothing@
2288 tyConClass_maybe :: TyCon -> Maybe Class
2289 tyConClass_maybe (AlgTyCon {algTcParent = ClassTyCon clas _}) = Just clas
2290 tyConClass_maybe _ = Nothing
2291
2292 -- | Return the associated types of the 'TyCon', if any
2293 tyConATs :: TyCon -> [TyCon]
2294 tyConATs (AlgTyCon {algTcParent = ClassTyCon clas _}) = classATs clas
2295 tyConATs _ = []
2296
2297 ----------------------------------------------------------------------------
2298 -- | Is this 'TyCon' that for a data family instance?
2299 isFamInstTyCon :: TyCon -> Bool
2300 isFamInstTyCon (AlgTyCon {algTcParent = DataFamInstTyCon {} })
2301 = True
2302 isFamInstTyCon _ = False
2303
2304 tyConFamInstSig_maybe :: TyCon -> Maybe (TyCon, [Type], CoAxiom Unbranched)
2305 tyConFamInstSig_maybe (AlgTyCon {algTcParent = DataFamInstTyCon ax f ts })
2306 = Just (f, ts, ax)
2307 tyConFamInstSig_maybe _ = Nothing
2308
2309 -- | If this 'TyCon' is that of a data family instance, return the family in question
2310 -- and the instance types. Otherwise, return @Nothing@
2311 tyConFamInst_maybe :: TyCon -> Maybe (TyCon, [Type])
2312 tyConFamInst_maybe (AlgTyCon {algTcParent = DataFamInstTyCon _ f ts })
2313 = Just (f, ts)
2314 tyConFamInst_maybe _ = Nothing
2315
2316 -- | If this 'TyCon' is that of a data family instance, return a 'TyCon' which
2317 -- represents a coercion identifying the representation type with the type
2318 -- instance family. Otherwise, return @Nothing@
2319 tyConFamilyCoercion_maybe :: TyCon -> Maybe (CoAxiom Unbranched)
2320 tyConFamilyCoercion_maybe (AlgTyCon {algTcParent = DataFamInstTyCon ax _ _ })
2321 = Just ax
2322 tyConFamilyCoercion_maybe _ = Nothing
2323
2324 -- | Extract any 'RuntimeRepInfo' from this TyCon
2325 tyConRuntimeRepInfo :: TyCon -> RuntimeRepInfo
2326 tyConRuntimeRepInfo (PromotedDataCon { promDcRepInfo = rri }) = rri
2327 tyConRuntimeRepInfo _ = NoRRI
2328 -- could panic in that second case. But Douglas Adams told me not to.
2329
2330 {-
2331 ************************************************************************
2332 * *
2333 \subsection[TyCon-instances]{Instance declarations for @TyCon@}
2334 * *
2335 ************************************************************************
2336
2337 @TyCon@s are compared by comparing their @Unique@s.
2338 -}
2339
2340 instance Eq TyCon where
2341 a == b = getUnique a == getUnique b
2342 a /= b = getUnique a /= getUnique b
2343
2344 instance Uniquable TyCon where
2345 getUnique tc = tyConUnique tc
2346
2347 instance Outputable TyCon where
2348 -- At the moment a promoted TyCon has the same Name as its
2349 -- corresponding TyCon, so we add the quote to distinguish it here
2350 ppr tc = pprPromotionQuote tc <> ppr (tyConName tc)
2351
2352 -- | Paints a picture of what a 'TyCon' represents, in broad strokes.
2353 -- This is used towards more informative error messages.
2354 data TyConFlavour
2355 = ClassFlavour
2356 | TupleFlavour Boxity
2357 | SumFlavour
2358 | DataTypeFlavour
2359 | NewtypeFlavour
2360 | AbstractTypeFlavour
2361 | DataFamilyFlavour
2362 | OpenTypeFamilyFlavour
2363 | ClosedTypeFamilyFlavour
2364 | TypeSynonymFlavour
2365 | BuiltInTypeFlavour -- ^ e.g., the @(->)@ 'TyCon'.
2366 | PromotedDataConFlavour
2367 deriving Eq
2368
2369 instance Outputable TyConFlavour where
2370 ppr = text . go
2371 where
2372 go ClassFlavour = "class"
2373 go (TupleFlavour boxed) | isBoxed boxed = "tuple"
2374 | otherwise = "unboxed tuple"
2375 go SumFlavour = "unboxed sum"
2376 go DataTypeFlavour = "data type"
2377 go NewtypeFlavour = "newtype"
2378 go AbstractTypeFlavour = "abstract type"
2379 go DataFamilyFlavour = "data family"
2380 go OpenTypeFamilyFlavour = "type family"
2381 go ClosedTypeFamilyFlavour = "type family"
2382 go TypeSynonymFlavour = "type synonym"
2383 go BuiltInTypeFlavour = "built-in type"
2384 go PromotedDataConFlavour = "promoted data constructor"
2385
2386 tyConFlavour :: TyCon -> TyConFlavour
2387 tyConFlavour (AlgTyCon { algTcParent = parent, algTcRhs = rhs })
2388 | ClassTyCon _ _ <- parent = ClassFlavour
2389 | otherwise = case rhs of
2390 TupleTyCon { tup_sort = sort }
2391 -> TupleFlavour (tupleSortBoxity sort)
2392 SumTyCon {} -> SumFlavour
2393 DataTyCon {} -> DataTypeFlavour
2394 NewTyCon {} -> NewtypeFlavour
2395 AbstractTyCon {} -> AbstractTypeFlavour
2396 tyConFlavour (FamilyTyCon { famTcFlav = flav })
2397 = case flav of
2398 DataFamilyTyCon{} -> DataFamilyFlavour
2399 OpenSynFamilyTyCon -> OpenTypeFamilyFlavour
2400 ClosedSynFamilyTyCon{} -> ClosedTypeFamilyFlavour
2401 AbstractClosedSynFamilyTyCon -> ClosedTypeFamilyFlavour
2402 BuiltInSynFamTyCon{} -> ClosedTypeFamilyFlavour
2403 tyConFlavour (SynonymTyCon {}) = TypeSynonymFlavour
2404 tyConFlavour (FunTyCon {}) = BuiltInTypeFlavour
2405 tyConFlavour (PrimTyCon {}) = BuiltInTypeFlavour
2406 tyConFlavour (PromotedDataCon {}) = PromotedDataConFlavour
2407 tyConFlavour (TcTyCon { tcTyConFlavour = flav }) = flav
2408
2409 -- | Can this flavour of 'TyCon' appear unsaturated?
2410 tcFlavourCanBeUnsaturated :: TyConFlavour -> Bool
2411 tcFlavourCanBeUnsaturated ClassFlavour = True
2412 tcFlavourCanBeUnsaturated DataTypeFlavour = True
2413 tcFlavourCanBeUnsaturated NewtypeFlavour = True
2414 tcFlavourCanBeUnsaturated DataFamilyFlavour = True
2415 tcFlavourCanBeUnsaturated TupleFlavour{} = True
2416 tcFlavourCanBeUnsaturated SumFlavour = True
2417 tcFlavourCanBeUnsaturated AbstractTypeFlavour = True
2418 tcFlavourCanBeUnsaturated BuiltInTypeFlavour = True
2419 tcFlavourCanBeUnsaturated PromotedDataConFlavour = True
2420 tcFlavourCanBeUnsaturated TypeSynonymFlavour = False
2421 tcFlavourCanBeUnsaturated OpenTypeFamilyFlavour = False
2422 tcFlavourCanBeUnsaturated ClosedTypeFamilyFlavour = False
2423
2424 -- | Is this flavour of 'TyCon' an open type family or a data family?
2425 tcFlavourIsOpen :: TyConFlavour -> Bool
2426 tcFlavourIsOpen DataFamilyFlavour = True
2427 tcFlavourIsOpen OpenTypeFamilyFlavour = True
2428 tcFlavourIsOpen ClosedTypeFamilyFlavour = False
2429 tcFlavourIsOpen ClassFlavour = False
2430 tcFlavourIsOpen DataTypeFlavour = False
2431 tcFlavourIsOpen NewtypeFlavour = False
2432 tcFlavourIsOpen TupleFlavour{} = False
2433 tcFlavourIsOpen SumFlavour = False
2434 tcFlavourIsOpen AbstractTypeFlavour = False
2435 tcFlavourIsOpen BuiltInTypeFlavour = False
2436 tcFlavourIsOpen PromotedDataConFlavour = False
2437 tcFlavourIsOpen TypeSynonymFlavour = False
2438
2439 pprPromotionQuote :: TyCon -> SDoc
2440 -- Promoted data constructors already have a tick in their OccName
2441 pprPromotionQuote tc
2442 = case tc of
2443 PromotedDataCon {} -> char '\'' -- Always quote promoted DataCons in types
2444 _ -> empty
2445
2446 instance NamedThing TyCon where
2447 getName = tyConName
2448
2449 instance Data.Data TyCon where
2450 -- don't traverse?
2451 toConstr _ = abstractConstr "TyCon"
2452 gunfold _ _ = error "gunfold"
2453 dataTypeOf _ = mkNoRepType "TyCon"
2454
2455 instance Binary Injectivity where
2456 put_ bh NotInjective = putByte bh 0
2457 put_ bh (Injective xs) = putByte bh 1 >> put_ bh xs
2458
2459 get bh = do { h <- getByte bh
2460 ; case h of
2461 0 -> return NotInjective
2462 _ -> do { xs <- get bh
2463 ; return (Injective xs) } }
2464
2465 {-
2466 ************************************************************************
2467 * *
2468 Walking over recursive TyCons
2469 * *
2470 ************************************************************************
2471
2472 Note [Expanding newtypes and products]
2473 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2474 When expanding a type to expose a data-type constructor, we need to be
2475 careful about newtypes, lest we fall into an infinite loop. Here are
2476 the key examples:
2477
2478 newtype Id x = MkId x
2479 newtype Fix f = MkFix (f (Fix f))
2480 newtype T = MkT (T -> T)
2481
2482 Type Expansion
2483 --------------------------
2484 T T -> T
2485 Fix Maybe Maybe (Fix Maybe)
2486 Id (Id Int) Int
2487 Fix Id NO NO NO
2488
2489 Notice that
2490 * We can expand T, even though it's recursive.
2491 * We can expand Id (Id Int), even though the Id shows up
2492 twice at the outer level, because Id is non-recursive
2493
2494 So, when expanding, we keep track of when we've seen a recursive
2495 newtype at outermost level; and bail out if we see it again.
2496
2497 We sometimes want to do the same for product types, so that the
2498 strictness analyser doesn't unbox infinitely deeply.
2499
2500 More precisely, we keep a *count* of how many times we've seen it.
2501 This is to account for
2502 data instance T (a,b) = MkT (T a) (T b)
2503 Then (Trac #10482) if we have a type like
2504 T (Int,(Int,(Int,(Int,Int))))
2505 we can still unbox deeply enough during strictness analysis.
2506 We have to treat T as potentially recursive, but it's still
2507 good to be able to unwrap multiple layers.
2508
2509 The function that manages all this is checkRecTc.
2510 -}
2511
2512 data RecTcChecker = RC !Int (NameEnv Int)
2513 -- The upper bound, and the number of times
2514 -- we have encountered each TyCon
2515
2516 initRecTc :: RecTcChecker
2517 -- Intialise with a fixed max bound of 100
2518 -- We should probably have a flag for this
2519 initRecTc = RC 100 emptyNameEnv
2520
2521 checkRecTc :: RecTcChecker -> TyCon -> Maybe RecTcChecker
2522 -- Nothing => Recursion detected
2523 -- Just rec_tcs => Keep going
2524 checkRecTc (RC bound rec_nts) tc
2525 = case lookupNameEnv rec_nts tc_name of
2526 Just n | n >= bound -> Nothing
2527 | otherwise -> Just (RC bound (extendNameEnv rec_nts tc_name (n+1)))
2528 Nothing -> Just (RC bound (extendNameEnv rec_nts tc_name 1))
2529 where
2530 tc_name = tyConName tc
2531
2532 -- | Returns whether or not this 'TyCon' is definite, or a hole
2533 -- that may be filled in at some later point. See Note [Skolem abstract data]
2534 tyConSkolem :: TyCon -> Bool
2535 tyConSkolem = isHoleName . tyConName
2536
2537 -- Note [Skolem abstract data]
2538 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~
2539 -- Skolem abstract data arises from data declarations in an hsig file.
2540 --
2541 -- The best analogy is to interpret the types declared in signature files as
2542 -- elaborating to universally quantified type variables; e.g.,
2543 --
2544 -- unit p where
2545 -- signature H where
2546 -- data T
2547 -- data S
2548 -- module M where
2549 -- import H
2550 -- f :: (T ~ S) => a -> b
2551 -- f x = x
2552 --
2553 -- elaborates as (with some fake structural types):
2554 --
2555 -- p :: forall t s. { f :: forall a b. t ~ s => a -> b }
2556 -- p = { f = \x -> x } -- ill-typed
2557 --
2558 -- It is clear that inside p, t ~ s is not provable (and
2559 -- if we tried to write a function to cast t to s, that
2560 -- would not work), but if we call p @Int @Int, clearly Int ~ Int
2561 -- is provable. The skolem variables are all distinct from
2562 -- one another, but we can't make assumptions like "f is
2563 -- inaccessible", because the skolem variables will get
2564 -- instantiated eventually!
2565 --
2566 -- Skolem abstractness can apply to "non-abstract" data as well):
2567 --
2568 -- unit p where
2569 -- signature H1 where
2570 -- data T = MkT
2571 -- signature H2 where
2572 -- data T = MkT
2573 -- module M where
2574 -- import qualified H1
2575 -- import qualified H2
2576 -- f :: (H1.T ~ H2.T) => a -> b
2577 -- f x = x
2578 --
2579 -- This is why the test is on the original name of the TyCon,
2580 -- not whether it is abstract or not.