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