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