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