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