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