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