2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
10 -- * Main TyCon data types
13 AlgTyConRhs(..), visibleDataCons,
17 AssocFamilyPermutation,
19 -- ** Constructing TyCons
33 -- ** Predicates on TyCons
35 isClassTyCon, isFamInstTyCon,
38 isTupleTyCon, isUnboxedTupleTyCon, isBoxedTupleTyCon,
39 isSynTyCon, isClosedSynTyCon, isOpenSynTyCon,
40 isSuperKindTyCon, isDecomposableTyCon,
41 isCoercionTyCon, isCoercionTyCon_maybe,
42 isForeignTyCon, isAnyTyCon, tyConHasKind,
45 isDataTyCon, isProductTyCon, isEnumerationTyCon,
46 isNewTyCon, isAbstractTyCon, isOpenTyCon,
52 isImplicitTyCon, tyConHasGenerics,
54 -- ** Extracting information out of TyCons
59 tyConDataCons, tyConDataCons_maybe, tyConSingleDataCon_maybe,
64 tyConFamInst_maybe, tyConFamilyCoercion_maybe,
65 synTyConDefn, synTyConRhs, synTyConType, synTyConResKind,
66 tyConExtName, -- External name for foreign types
68 newTyConRhs, newTyConEtadRhs, unwrapNewTyCon_maybe,
69 assocTyConArgPoss_maybe,
72 -- ** Manipulating TyCons
73 tcExpandTyCon_maybe, coreExpandTyCon_maybe,
78 -- * Primitive representations of Types
84 #include "HsVersions.h"
86 import {-# SOURCE #-} TypeRep ( Kind, Type, PredType )
87 import {-# SOURCE #-} DataCon ( DataCon, isVanillaDataCon )
98 import Data.List( elemIndex )
101 %************************************************************************
103 \subsection{The data type}
105 %************************************************************************
108 -- | TyCons represent type constructors. Type constructors are introduced by things such as:
110 -- 1) Data declarations: @data Foo = ...@ creates the @Foo@ type constructor of kind @*@
112 -- 2) Type synonyms: @type Foo = ...@ creates the @Foo@ type constructor
114 -- 3) Newtypes: @newtype Foo a = MkFoo ...@ creates the @Foo@ type constructor of kind @* -> *@
116 -- 4) Class declarations: @class Foo where@ creates the @Foo@ type constructor of kind @*@
118 -- 5) Type coercions! This is because we represent a coercion from @t1@ to @t2@ as a 'Type', where
119 -- that type has kind @t1 ~ t2@. See "Coercion" for more on this
121 -- This data type also encodes a number of primitive, built in type constructors such as those
122 -- for function and tuple types.
124 = -- | The function type constructor, @(->)@
126 tyConUnique :: Unique,
132 -- | Algebraic type constructors, which are defined to be those arising @data@ type and @newtype@ declarations.
133 -- All these constructors are lifted and boxed. See 'AlgTyConRhs' for more information.
135 tyConUnique :: Unique,
140 tyConTyVars :: [TyVar], -- ^ The type variables used in the type constructor.
141 -- Precisely, this list scopes over:
143 -- 1. The 'algTcStupidTheta'
145 -- 2. The cached types in 'algTyConRhs.NewTyCon'
147 -- 3. The family instance types if present
149 -- Note that it does /not/ scope over the data constructors.
151 algTcGadtSyntax :: Bool, -- ^ Was the data type declared with GADT syntax? If so,
152 -- that doesn't mean it's a true GADT; only that the "where"
153 -- form was used. This field is used only to guide
156 algTcStupidTheta :: [PredType], -- ^ The \"stupid theta\" for the data type (always empty for GADTs).
157 -- A \"stupid theta\" is the context to the left of an algebraic type
158 -- declaration, e.g. @Eq a@ in the declaration @data Eq a => T a ...@.
160 algTcRhs :: AlgTyConRhs, -- ^ Contains information about the data constructors of the algebraic type
162 algTcRec :: RecFlag, -- ^ Tells us whether the data type is part of a mutually-recursive group or not
164 hasGenerics :: Bool, -- ^ Whether generic (in the -XGenerics sense) to\/from functions are
165 -- available in the exports of the data type's source module.
167 algTcParent :: TyConParent -- ^ Gives the class or family declaration 'TyCon' for derived 'TyCon's
168 -- representing class or family instances, respectively. See also 'synTcParent'
171 -- | Represents the infinite family of tuple type constructors, @()@, @(a,b)@, @(# a, b #)@ etc.
173 tyConUnique :: Unique,
177 tyConBoxed :: Boxity,
178 tyConTyVars :: [TyVar],
179 dataCon :: DataCon, -- ^ Corresponding tuple data constructor
183 -- | Represents type synonyms
185 tyConUnique :: Unique,
190 tyConTyVars :: [TyVar], -- Bound tyvars
192 synTcRhs :: SynTyConRhs, -- ^ Contains information about the expansion of the synonym
194 synTcParent :: TyConParent -- ^ Gives the family declaration 'TyCon' of 'TyCon's representing family instances
198 -- | Primitive types; cannot be defined in Haskell. This includes the usual suspects (such as @Int#@)
199 -- as well as foreign-imported types and kinds
201 tyConUnique :: Unique,
204 tyConArity :: Arity, -- SLPJ Oct06: I'm not sure what the significance
205 -- of the arity of a primtycon is!
207 primTyConRep :: PrimRep, -- ^ Many primitive tycons are unboxed, but some are
208 -- boxed (represented by pointers). This 'PrimRep' holds
210 -- Only relevant if tc_kind = *
212 isUnLifted :: Bool, -- ^ Most primitive tycons are unlifted (may not contain bottom)
213 -- but foreign-imported ones may be lifted
215 tyConExtName :: Maybe FastString -- ^ @Just e@ for foreign-imported types,
216 -- holds the name of the imported thing
219 -- | Type coercions, such as @(~)@, @sym@, @trans@, @left@ and @right@.
220 -- INVARIANT: Coercion TyCons are always fully applied
221 -- But note that a CoTyCon can be *over*-saturated in a type.
222 -- E.g. (sym g1) Int will be represented as (TyConApp sym [g1,Int])
224 tyConUnique :: Unique,
227 coTcDesc :: CoTyConDesc
230 -- | Any types. Like tuples, this is a potentially-infinite family of TyCons
231 -- one for each distinct Kind. They have no values at all.
232 -- Because there are infinitely many of them (like tuples) they are
233 -- defined in GHC.Prim and have names like "Any(*->*)".
234 -- Their Unique is derived from the OccName.
235 -- See Note [Any types] in TysPrim
237 tyConUnique :: Unique,
239 tc_kind :: Kind -- Never = *; that is done via PrimTyCon
240 -- See Note [Any types] in TysPrim
243 -- | Super-kinds. These are "kinds-of-kinds" and are never seen in Haskell source programs.
244 -- There are only two super-kinds: TY (aka "box"), which is the super-kind of kinds that
245 -- construct types eventually, and CO (aka "diamond"), which is the super-kind of kinds
246 -- that just represent coercions.
248 -- Super-kinds have no kind themselves, and have arity zero
250 tyConUnique :: Unique,
254 -- | Names of the fields in an algebraic record type
255 type FieldLabel = Name
257 -- | Represents right-hand-sides of 'TyCon's for algebraic types
260 -- | Says that we know nothing about this data type, except that it's represented
261 -- by a pointer. Used when we export a data type abstractly into an .hi file.
264 -- | Represents an open type family without a fixed right hand
265 -- side. Additional instances can appear at any time.
267 -- These are introduced by either a top level declaration:
271 -- Or an assoicated data type declaration, within a class declaration:
273 -- > class C a b where
277 otArgPoss :: AssocFamilyPermutation
280 -- | Information about those 'TyCon's derived from a @data@ declaration. This includes
281 -- data types with no constructors at all.
283 data_cons :: [DataCon],
284 -- ^ The data type constructors; can be empty if the user declares
285 -- the type to have no constructors
287 -- INVARIANT: Kept in order of increasing 'DataCon' tag
289 -- (see the tag assignment in DataCon.mkDataCon)
290 is_enum :: Bool -- ^ Cached value: is this an enumeration type? (See 'isEnumerationTyCon')
293 -- | Information about those 'TyCon's derived from a @newtype@ declaration
295 data_con :: DataCon, -- ^ The unique constructor for the @newtype@. It has no existentials
297 nt_rhs :: Type, -- ^ Cached value: the argument type of the constructor, which
298 -- is just the representation type of the 'TyCon' (remember that
299 -- @newtype@s do not exist at runtime so need a different representation
302 -- The free 'TyVar's of this type are the 'tyConTyVars' from the corresponding
305 nt_etad_rhs :: ([TyVar], Type),
306 -- ^ Same as the 'nt_rhs', but this time eta-reduced. Hence the list of 'TyVar's in
307 -- this field may be shorter than the declared arity of the 'TyCon'.
309 -- See Note [Newtype eta]
311 nt_co :: Maybe TyCon -- ^ A 'TyCon' (which is always a 'CoTyCon') that can have a 'Coercion'
312 -- extracted from it to create the @newtype@ from the representation 'Type'.
314 -- This field is optional for non-recursive @newtype@s only.
316 -- See Note [Newtype coercions]
317 -- Invariant: arity = #tvs in nt_etad_rhs;
318 -- See Note [Newtype eta]
319 -- Watch out! If any newtypes become transparent
320 -- again check Trac #1072.
323 type AssocFamilyPermutation
324 = Maybe [Int] -- Nothing for *top-level* type families
325 -- For *associated* type families, gives the position
326 -- of that 'TyVar' in the class argument list (0-indexed)
327 -- e.g. class C a b c where { type F c a :: *->* }
328 -- Then we get Just [2,0]
329 -- For *synonyms*, the length of the list is identical to
331 -- For *data types*, the length may be smaller than the
332 -- TyCon's arity; e.g. class C a where { data D a :: *->* }
333 -- here D gets arity 2
335 -- | Extract those 'DataCon's that we are able to learn about. Note that visibility in this sense does not
336 -- correspond to visibility in the context of any particular user program!
337 visibleDataCons :: AlgTyConRhs -> [DataCon]
338 visibleDataCons AbstractTyCon = []
339 visibleDataCons OpenTyCon {} = []
340 visibleDataCons (DataTyCon{ data_cons = cs }) = cs
341 visibleDataCons (NewTyCon{ data_con = c }) = [c]
343 -- ^ Both type classes as well as family instances imply implicit
344 -- type constructors. These implicit type constructors refer to their parent
345 -- structure (ie, the class or family from which they derive) using a type of
346 -- the following form. We use 'TyConParent' for both algebraic and synonym
347 -- types, but the variant 'ClassTyCon' will only be used by algebraic 'TyCon's.
349 = -- | An ordinary type constructor has no parent.
352 -- | Type constructors representing a class dictionary.
354 Class -- INVARIANT: the classTyCon of this Class is the current tycon
356 -- | Type constructors representing an instance of a type family. Parameters:
358 -- 1) The type family in question
360 -- 2) Instance types; free variables are the 'tyConTyVars'
361 -- of the current 'TyCon' (not the family one). INVARIANT:
362 -- the number of types matches the arity of the family 'TyCon'
364 -- 3) A 'CoTyCon' identifying the representation
365 -- type with the type instance family
369 TyCon -- c.f. Note [Newtype coercions]
372 -- E.g. data intance T [a] = ...
373 -- gives a representation tycon:
375 -- axiom co a :: T [a] ~ :R7T a
376 -- with :R7T's algTcParent = FamilyTyCon T [a] co
378 -- | Checks the invariants of a 'TyConParent' given the appropriate type class name, if any
379 okParent :: Name -> TyConParent -> Bool
380 okParent _ NoParentTyCon = True
381 okParent tc_name (ClassTyCon cls) = tyConName (classTyCon cls) == tc_name
382 okParent _ (FamilyTyCon fam_tc tys _co_tc) = tyConArity fam_tc == length tys
386 -- | Information pertaining to the expansion of a type synonym (@type@)
388 = OpenSynTyCon -- e.g. type family F x y :: * -> *
389 Kind -- Kind of the "rhs"; ie *excluding type indices*
390 -- In the example, the kind is (*->*)
391 AssocFamilyPermutation
393 | SynonymTyCon Type -- ^ The synonym mentions head type variables. It acts as a
394 -- template for the expansion when the 'TyCon' is applied to some
401 | CoCsel1 | CoCsel2 | CoCselR
404 | CoAxiom -- C tvs : F lhs-tys ~ rhs-ty
405 { co_ax_tvs :: [TyVar]
407 , co_ax_rhs :: Type }
412 Note [Newtype coercions]
413 ~~~~~~~~~~~~~~~~~~~~~~~~
414 The NewTyCon field nt_co is a a TyCon (a coercion constructor in fact)
415 which is used for coercing from the representation type of the
416 newtype, to the newtype itself. For example,
418 newtype T a = MkT (a -> a)
420 the NewTyCon for T will contain nt_co = CoT where CoT t : T t ~ t ->
421 t. This TyCon is a CoTyCon, so it does not have a kind on its
422 own; it basically has its own typing rule for the fully-applied
423 version. If the newtype T has k type variables then CoT has arity at
424 most k. In the case that the right hand side is a type application
425 ending with the same type variables as the left hand side, we
426 "eta-contract" the coercion. So if we had
428 newtype S a = MkT [a]
430 then we would generate the arity 0 coercion CoS : S ~ []. The
431 primary reason we do this is to make newtype deriving cleaner.
433 In the paper we'd write
434 axiom CoT : (forall t. T t) ~ (forall t. [t])
435 and then when we used CoT at a particular type, s, we'd say
437 which encodes as (TyConApp instCoercionTyCon [TyConApp CoT [], s])
439 But in GHC we instead make CoT into a new piece of type syntax, CoTyCon,
440 (like instCoercionTyCon, symCoercionTyCon etc), which must always
441 be saturated, but which encodes as
443 In the vocabulary of the paper it's as if we had axiom declarations
445 axiom CoT t : T t ~ [t]
450 newtype Parser m a = MkParser (Foogle m a)
451 Are these two types equal (to Core)?
454 Well, yes. But to see that easily we eta-reduce the RHS type of
455 Parser, in this case to ([], Froogle), so that even unsaturated applications
456 of Parser will work right. This eta reduction is done when the type
457 constructor is built, and cached in NewTyCon. The cached field is
458 only used in coreExpandTyCon_maybe.
460 Here's an example that I think showed up in practice
462 newtype T a = MkT [a]
463 newtype Foo m = MkFoo (forall a. m a -> Int)
469 w2 = MkFoo (\(MkT x) -> case w1 of MkFoo f -> f x)
471 After desugaring, and discarding the data constructors for the newtypes,
475 And now Lint complains unless Foo T == Foo [], and that requires T==[]
477 This point carries over to the newtype coercion, because we need to
479 w2 = w1 `cast` Foo CoT
481 so the coercion tycon CoT must have
486 Note [Indexed data types] (aka data type families)
487 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
488 See also Note [Wrappers for data instance tycons] in MkId.lhs
493 data instance T (b,c) where
494 T1 :: b -> c -> T (b,c)
497 * T is the "family TyCon"
499 * We make "representation TyCon" :R1T, thus:
501 T1 :: forall b c. b -> c -> :R1T b c
503 * It has a top-level coercion connecting it to the family TyCon
505 axiom :Co:R1T b c : T (b,c) ~ :R1T b c
507 * The data contructor T1 has a wrapper (which is what the source-level
510 $WT1 :: forall b c. b -> c -> T (b,c)
511 $WT1 b c (x::b) (y::c) = T1 b c x y `cast` sym (:Co:R1T b c)
513 * The representation TyCon :R1T has an AlgTyConParent of
515 FamilyTyCon T [(b,c)] :Co:R1T
519 %************************************************************************
523 %************************************************************************
525 A PrimRep is somewhat similar to a CgRep (see codeGen/SMRep) and a
526 MachRep (see cmm/CmmExpr), although each of these types has a distinct
527 and clearly defined purpose:
529 - A PrimRep is a CgRep + information about signedness + information
530 about primitive pointers (AddrRep). Signedness and primitive
531 pointers are required when passing a primitive type to a foreign
532 function, but aren't needed for call/return conventions of Haskell
535 - A MachRep is a basic machine type (non-void, doesn't contain
536 information on pointerhood or signedness, but contains some
537 reps that don't have corresponding Haskell types).
540 -- | A 'PrimRep' is an abstraction of a type. It contains information that
541 -- the code generator needs in order to pass arguments, return results,
542 -- and store values of this type.
546 | IntRep -- ^ Signed, word-sized value
547 | WordRep -- ^ Unsigned, word-sized value
548 | Int64Rep -- ^ Signed, 64 bit value (with 32-bit words only)
549 | Word64Rep -- ^ Unsigned, 64 bit value (with 32-bit words only)
550 | AddrRep -- ^ A pointer, but /not/ to a Haskell value (use 'PtrRep')
555 instance Outputable PrimRep where
556 ppr r = text (show r)
558 -- | Find the size of a 'PrimRep', in words
559 primRepSizeW :: PrimRep -> Int
560 primRepSizeW IntRep = 1
561 primRepSizeW WordRep = 1
562 primRepSizeW Int64Rep = wORD64_SIZE `quot` wORD_SIZE
563 primRepSizeW Word64Rep= wORD64_SIZE `quot` wORD_SIZE
564 primRepSizeW FloatRep = 1 -- NB. might not take a full word
565 primRepSizeW DoubleRep= dOUBLE_SIZE `quot` wORD_SIZE
566 primRepSizeW AddrRep = 1
567 primRepSizeW PtrRep = 1
568 primRepSizeW VoidRep = 0
571 %************************************************************************
573 \subsection{TyCon Construction}
575 %************************************************************************
577 Note: the TyCon constructors all take a Kind as one argument, even though
578 they could, in principle, work out their Kind from their other arguments.
579 But to do so they need functions from Types, and that makes a nasty
580 module mutual-recursion. And they aren't called from many places.
581 So we compromise, and move their Kind calculation to the call site.
584 -- | Given the name of the function type constructor and it's kind, create the
585 -- corresponding 'TyCon'. It is reccomended to use 'TypeRep.funTyCon' if you want
586 -- this functionality
587 mkFunTyCon :: Name -> Kind -> TyCon
590 tyConUnique = nameUnique name,
596 -- | This is the making of an algebraic 'TyCon'. Notably, you have to pass in the generic (in the -XGenerics sense)
597 -- information about the type constructor - you can get hold of it easily (see Generics module)
599 -> Kind -- ^ Kind of the resulting 'TyCon'
600 -> [TyVar] -- ^ 'TyVar's scoped over: see 'tyConTyVars'. Arity is inferred from the length of this list
601 -> [PredType] -- ^ Stupid theta: see 'algTcStupidTheta'
602 -> AlgTyConRhs -- ^ Information about dat aconstructors
604 -> RecFlag -- ^ Is the 'TyCon' recursive?
605 -> Bool -- ^ Does it have generic functions? See 'hasGenerics'
606 -> Bool -- ^ Was the 'TyCon' declared with GADT syntax?
608 mkAlgTyCon name kind tyvars stupid rhs parent is_rec gen_info gadt_syn
611 tyConUnique = nameUnique name,
613 tyConArity = length tyvars,
614 tyConTyVars = tyvars,
615 algTcStupidTheta = stupid,
617 algTcParent = ASSERT( okParent name parent ) parent,
619 algTcGadtSyntax = gadt_syn,
620 hasGenerics = gen_info
623 -- | Simpler specialization of 'mkAlgTyCon' for classes
624 mkClassTyCon :: Name -> Kind -> [TyVar] -> AlgTyConRhs -> Class -> RecFlag -> TyCon
625 mkClassTyCon name kind tyvars rhs clas is_rec =
626 mkAlgTyCon name kind tyvars [] rhs (ClassTyCon clas) is_rec False False
629 -> Kind -- ^ Kind of the resulting 'TyCon'
630 -> Arity -- ^ Arity of the tuple
631 -> [TyVar] -- ^ 'TyVar's scoped over: see 'tyConTyVars'
633 -> Boxity -- ^ Whether the tuple is boxed or unboxed
634 -> Bool -- ^ Does it have generic functions? See 'hasGenerics'
636 mkTupleTyCon name kind arity tyvars con boxed gen_info
638 tyConUnique = nameUnique name,
643 tyConTyVars = tyvars,
645 hasGenerics = gen_info
648 -- ^ Foreign-imported (.NET) type constructors are represented
649 -- as primitive, but /lifted/, 'TyCons' for now. They are lifted
650 -- because the Haskell type @T@ representing the (foreign) .NET
651 -- type @T@ is actually implemented (in ILX) as a @thunk<T>@
652 mkForeignTyCon :: Name
653 -> Maybe FastString -- ^ Name of the foreign imported thing, maybe
657 mkForeignTyCon name ext_name kind arity
660 tyConUnique = nameUnique name,
663 primTyConRep = PtrRep, -- they all do
665 tyConExtName = ext_name
669 -- | Create an unlifted primitive 'TyCon', such as @Int#@
670 mkPrimTyCon :: Name -> Kind -> Arity -> PrimRep -> TyCon
671 mkPrimTyCon name kind arity rep
672 = mkPrimTyCon' name kind arity rep True
674 -- | Kind constructors
675 mkKindTyCon :: Name -> Kind -> TyCon
676 mkKindTyCon name kind
677 = mkPrimTyCon' name kind 0 VoidRep True
679 -- | Create a lifted primitive 'TyCon' such as @RealWorld@
680 mkLiftedPrimTyCon :: Name -> Kind -> Arity -> PrimRep -> TyCon
681 mkLiftedPrimTyCon name kind arity rep
682 = mkPrimTyCon' name kind arity rep False
684 mkPrimTyCon' :: Name -> Kind -> Arity -> PrimRep -> Bool -> TyCon
685 mkPrimTyCon' name kind arity rep is_unlifted
688 tyConUnique = nameUnique name,
692 isUnLifted = is_unlifted,
693 tyConExtName = Nothing
696 -- | Create a type synonym 'TyCon'
697 mkSynTyCon :: Name -> Kind -> [TyVar] -> SynTyConRhs -> TyConParent -> TyCon
698 mkSynTyCon name kind tyvars rhs parent
701 tyConUnique = nameUnique name,
703 tyConArity = length tyvars,
704 tyConTyVars = tyvars,
709 -- | Create a coercion 'TyCon'
710 mkCoercionTyCon :: Name -> Arity
713 mkCoercionTyCon name arity desc
716 tyConUnique = nameUnique name,
720 mkAnyTyCon :: Name -> Kind -> TyCon
722 = AnyTyCon { tyConName = name,
724 tyConUnique = nameUnique name }
726 -- | Create a super-kind 'TyCon'
727 mkSuperKindTyCon :: Name -> TyCon -- Super kinds always have arity zero
728 mkSuperKindTyCon name
731 tyConUnique = nameUnique name
736 isFunTyCon :: TyCon -> Bool
737 isFunTyCon (FunTyCon {}) = True
740 -- | Test if the 'TyCon' is algebraic but abstract (invisible data constructors)
741 isAbstractTyCon :: TyCon -> Bool
742 isAbstractTyCon (AlgTyCon { algTcRhs = AbstractTyCon }) = True
743 isAbstractTyCon _ = False
745 -- | Make an algebraic 'TyCon' abstract. Panics if the supplied 'TyCon' is not algebraic
746 makeTyConAbstract :: TyCon -> TyCon
747 makeTyConAbstract tc@(AlgTyCon {}) = tc { algTcRhs = AbstractTyCon }
748 makeTyConAbstract tc = pprPanic "makeTyConAbstract" (ppr tc)
750 -- | Does this 'TyCon' represent something that cannot be defined in Haskell?
751 isPrimTyCon :: TyCon -> Bool
752 isPrimTyCon (PrimTyCon {}) = True
753 isPrimTyCon _ = False
755 -- | Is this 'TyCon' unlifted (i.e. cannot contain bottom)? Note that this can only
756 -- be true for primitive and unboxed-tuple 'TyCon's
757 isUnLiftedTyCon :: TyCon -> Bool
758 isUnLiftedTyCon (PrimTyCon {isUnLifted = is_unlifted}) = is_unlifted
759 isUnLiftedTyCon (TupleTyCon {tyConBoxed = boxity}) = not (isBoxed boxity)
760 isUnLiftedTyCon _ = False
762 -- | Returns @True@ if the supplied 'TyCon' resulted from either a @data@ or @newtype@ declaration
763 isAlgTyCon :: TyCon -> Bool
764 isAlgTyCon (AlgTyCon {}) = True
765 isAlgTyCon (TupleTyCon {}) = True
768 isDataTyCon :: TyCon -> Bool
769 -- ^ Returns @True@ for data types that are /definitely/ represented by
770 -- heap-allocated constructors. These are scrutinised by Core-level
771 -- @case@ expressions, and they get info tables allocated for them.
773 -- Generally, the function will be true for all @data@ types and false
774 -- for @newtype@s, unboxed tuples and type family 'TyCon's. But it is
775 -- not guarenteed to return @True@ in all cases that it could.
777 -- NB: for a data type family, only the /instance/ 'TyCon's
778 -- get an info table. The family declaration 'TyCon' does not
779 isDataTyCon (AlgTyCon {algTcRhs = rhs})
781 OpenTyCon {} -> False
784 AbstractTyCon -> False -- We don't know, so return False
785 isDataTyCon (TupleTyCon {tyConBoxed = boxity}) = isBoxed boxity
786 isDataTyCon _ = False
788 -- | Is this 'TyCon' that for a @newtype@
789 isNewTyCon :: TyCon -> Bool
790 isNewTyCon (AlgTyCon {algTcRhs = NewTyCon {}}) = True
793 -- | Take a 'TyCon' apart into the 'TyVar's it scopes over, the 'Type' it expands
794 -- into, and (possibly) a coercion from the representation type to the @newtype@.
795 -- Returns @Nothing@ if this is not possible.
796 unwrapNewTyCon_maybe :: TyCon -> Maybe ([TyVar], Type, Maybe TyCon)
797 unwrapNewTyCon_maybe (AlgTyCon { tyConTyVars = tvs,
798 algTcRhs = NewTyCon { nt_co = mb_co,
800 = Just (tvs, rhs, mb_co)
801 unwrapNewTyCon_maybe _ = Nothing
803 isProductTyCon :: TyCon -> Bool
804 -- | A /product/ 'TyCon' must both:
806 -- 1. Have /one/ constructor
808 -- 2. /Not/ be existential
810 -- However other than this there are few restrictions: they may be @data@ or @newtype@
811 -- 'TyCon's of any boxity and may even be recursive.
812 isProductTyCon tc@(AlgTyCon {}) = case algTcRhs tc of
813 DataTyCon{ data_cons = [data_con] }
814 -> isVanillaDataCon data_con
817 isProductTyCon (TupleTyCon {}) = True
818 isProductTyCon _ = False
820 -- | Is this a 'TyCon' representing a type synonym (@type@)?
821 isSynTyCon :: TyCon -> Bool
822 isSynTyCon (SynTyCon {}) = True
825 -- As for newtypes, it is in some contexts important to distinguish between
826 -- closed synonyms and synonym families, as synonym families have no unique
827 -- right hand side to which a synonym family application can expand.
830 -- | Is this a synonym 'TyCon' that can have no further instances appear?
831 isClosedSynTyCon :: TyCon -> Bool
832 isClosedSynTyCon tycon = isSynTyCon tycon && not (isOpenTyCon tycon)
834 -- | Is this a synonym 'TyCon' that can have may have further instances appear?
835 isOpenSynTyCon :: TyCon -> Bool
836 isOpenSynTyCon tycon = isSynTyCon tycon && isOpenTyCon tycon
838 isDecomposableTyCon :: TyCon -> Bool
839 -- True iff we can decompose (T a b c) into ((T a b) c)
840 -- Specifically NOT true of synonyms (open and otherwise) and coercions
841 isDecomposableTyCon (SynTyCon {}) = False
842 isDecomposableTyCon (CoTyCon {}) = False
843 isDecomposableTyCon _other = True
845 -- | Is this an algebraic 'TyCon' declared with the GADT syntax?
846 isGadtSyntaxTyCon :: TyCon -> Bool
847 isGadtSyntaxTyCon (AlgTyCon { algTcGadtSyntax = res }) = res
848 isGadtSyntaxTyCon _ = False
850 -- | Is this an algebraic 'TyCon' which is just an enumeration of values?
851 isEnumerationTyCon :: TyCon -> Bool
852 isEnumerationTyCon (AlgTyCon {algTcRhs = DataTyCon { is_enum = res }}) = res
853 isEnumerationTyCon (TupleTyCon {tyConArity = arity}) = arity == 0
854 isEnumerationTyCon _ = False
856 -- | Is this a 'TyCon', synonym or otherwise, that may have further instances appear?
857 isOpenTyCon :: TyCon -> Bool
858 isOpenTyCon (SynTyCon {synTcRhs = OpenSynTyCon {}}) = True
859 isOpenTyCon (AlgTyCon {algTcRhs = OpenTyCon {}}) = True
860 isOpenTyCon _ = False
862 -- | Injective 'TyCon's can be decomposed, so that
863 -- T ty1 ~ T ty2 => ty1 ~ ty2
864 isInjectiveTyCon :: TyCon -> Bool
865 isInjectiveTyCon tc = not (isSynTyCon tc)
866 -- Ultimately we may have injective associated types
867 -- in which case this test will become more interesting
869 -- It'd be unusual to call isInjectiveTyCon on a regular H98
870 -- type synonym, because you should probably have expanded it first
871 -- But regardless, it's not injective!
873 -- | Extract the mapping from 'TyVar' indexes to indexes in the corresponding family
874 -- argument lists form an open 'TyCon' of any sort, if the given 'TyCon' is indeed
875 -- such a beast and that information is available
876 assocTyConArgPoss_maybe :: TyCon -> Maybe [Int]
877 assocTyConArgPoss_maybe (AlgTyCon {
878 algTcRhs = OpenTyCon {otArgPoss = poss}}) = poss
879 assocTyConArgPoss_maybe (SynTyCon { synTcRhs = OpenSynTyCon _ poss }) = poss
880 assocTyConArgPoss_maybe _ = Nothing
882 -- | Are we able to extract informationa 'TyVar' to class argument list
883 -- mappping from a given 'TyCon'?
884 isTyConAssoc :: TyCon -> Bool
885 isTyConAssoc = isJust . assocTyConArgPoss_maybe
887 -- | Set the AssocFamilyPermutation structure in an
888 -- associated data or type synonym. The [TyVar] are the
889 -- class type variables. Remember, the tyvars of an associated
890 -- data/type are a subset of the class tyvars; except that an
891 -- associated data type can have extra type variables at the
892 -- end (see Note [Avoid name clashes for associated data types] in TcHsType)
893 setTyConArgPoss :: [TyVar] -> TyCon -> TyCon
894 setTyConArgPoss clas_tvs tc
896 AlgTyCon { algTcRhs = rhs } -> tc { algTcRhs = rhs {otArgPoss = Just ps} }
897 SynTyCon { synTcRhs = OpenSynTyCon ki _ } -> tc { synTcRhs = OpenSynTyCon ki (Just ps) }
898 _ -> pprPanic "setTyConArgPoss" (ppr tc)
900 ps = catMaybes [tv `elemIndex` clas_tvs | tv <- tyConTyVars tc]
901 -- We will get Nothings for the "extra" type variables in an
902 -- associated data type
904 -- The unit tycon didn't used to be classed as a tuple tycon
905 -- but I thought that was silly so I've undone it
906 -- If it can't be for some reason, it should be a AlgTyCon
907 isTupleTyCon :: TyCon -> Bool
908 -- ^ Does this 'TyCon' represent a tuple?
910 -- NB: when compiling @Data.Tuple@, the tycons won't reply @True@ to
911 -- 'isTupleTyCon', becuase they are built as 'AlgTyCons'. However they
912 -- get spat into the interface file as tuple tycons, so I don't think
914 isTupleTyCon (TupleTyCon {}) = True
915 isTupleTyCon _ = False
917 -- | Is this the 'TyCon' for an unboxed tuple?
918 isUnboxedTupleTyCon :: TyCon -> Bool
919 isUnboxedTupleTyCon (TupleTyCon {tyConBoxed = boxity}) = not (isBoxed boxity)
920 isUnboxedTupleTyCon _ = False
922 -- | Is this the 'TyCon' for a boxed tuple?
923 isBoxedTupleTyCon :: TyCon -> Bool
924 isBoxedTupleTyCon (TupleTyCon {tyConBoxed = boxity}) = isBoxed boxity
925 isBoxedTupleTyCon _ = False
927 -- | Extract the boxity of the given 'TyCon', if it is a 'TupleTyCon'.
929 tupleTyConBoxity :: TyCon -> Boxity
930 tupleTyConBoxity tc = tyConBoxed tc
932 -- | Is this a recursive 'TyCon'?
933 isRecursiveTyCon :: TyCon -> Bool
934 isRecursiveTyCon (AlgTyCon {algTcRec = Recursive}) = True
935 isRecursiveTyCon _ = False
937 -- | Did this 'TyCon' originate from type-checking a .h*-boot file?
938 isHiBootTyCon :: TyCon -> Bool
939 -- Used for knot-tying in hi-boot files
940 isHiBootTyCon (AlgTyCon {algTcRhs = AbstractTyCon}) = True
941 isHiBootTyCon _ = False
943 -- | Is this the 'TyCon' of a foreign-imported type constructor?
944 isForeignTyCon :: TyCon -> Bool
945 isForeignTyCon (PrimTyCon {tyConExtName = Just _}) = True
946 isForeignTyCon _ = False
948 -- | Is this a super-kind 'TyCon'?
949 isSuperKindTyCon :: TyCon -> Bool
950 isSuperKindTyCon (SuperKindTyCon {}) = True
951 isSuperKindTyCon _ = False
953 -- | Is this an AnyTyCon?
954 isAnyTyCon :: TyCon -> Bool
955 isAnyTyCon (AnyTyCon {}) = True
958 -- | Attempt to pull a 'TyCon' apart into the arity and 'coKindFun' of
959 -- a coercion 'TyCon'. Returns @Nothing@ if the 'TyCon' is not of the
961 isCoercionTyCon_maybe :: TyCon -> Maybe (Arity, CoTyConDesc)
962 isCoercionTyCon_maybe (CoTyCon {tyConArity = ar, coTcDesc = desc})
964 isCoercionTyCon_maybe _ = Nothing
966 -- | Is this a 'TyCon' that represents a coercion?
967 isCoercionTyCon :: TyCon -> Bool
968 isCoercionTyCon (CoTyCon {}) = True
969 isCoercionTyCon _ = False
971 -- | Identifies implicit tycons that, in particular, do not go into interface
972 -- files (because they are implicitly reconstructed when the interface is
977 -- * Associated families are implicit, as they are re-constructed from
978 -- the class declaration in which they reside, and
980 -- * Family instances are /not/ implicit as they represent the instance body
981 -- (similar to a @dfun@ does that for a class instance).
982 isImplicitTyCon :: TyCon -> Bool
983 isImplicitTyCon tycon | isTyConAssoc tycon = True
984 | isSynTyCon tycon = False
985 | isAlgTyCon tycon = isClassTyCon tycon ||
987 isImplicitTyCon _other = True
988 -- catches: FunTyCon, PrimTyCon,
989 -- CoTyCon, SuperKindTyCon
993 -----------------------------------------------
994 -- Expand type-constructor applications
995 -----------------------------------------------
998 tcExpandTyCon_maybe, coreExpandTyCon_maybe
1000 -> [Type] -- ^ Arguments to 'TyCon'
1001 -> Maybe ([(TyVar,Type)],
1003 [Type]) -- ^ Returns a 'TyVar' substitution, the body type
1004 -- of the synonym (not yet substituted) and any arguments
1005 -- remaining from the application
1007 -- ^ Used to create the view the /typechecker/ has on 'TyCon's. We expand (closed) synonyms only, cf. 'coreExpandTyCon_maybe'
1008 tcExpandTyCon_maybe (SynTyCon {tyConTyVars = tvs,
1009 synTcRhs = SynonymTyCon rhs }) tys
1010 = expand tvs rhs tys
1011 tcExpandTyCon_maybe _ _ = Nothing
1015 -- ^ Used to create the view /Core/ has on 'TyCon's. We expand not only closed synonyms like 'tcExpandTyCon_maybe',
1016 -- but also non-recursive @newtype@s
1017 coreExpandTyCon_maybe (AlgTyCon {
1018 algTcRhs = NewTyCon { nt_etad_rhs = etad_rhs, nt_co = Nothing }}) tys
1019 = case etad_rhs of -- Don't do this in the pattern match, lest we accidentally
1020 -- match the etad_rhs of a *recursive* newtype
1021 (tvs,rhs) -> expand tvs rhs tys
1023 coreExpandTyCon_maybe tycon tys = tcExpandTyCon_maybe tycon tys
1027 expand :: [TyVar] -> Type -- Template
1029 -> Maybe ([(TyVar,Type)], Type, [Type]) -- Expansion
1031 = case n_tvs `compare` length tys of
1032 LT -> Just (tvs `zip` tys, rhs, drop n_tvs tys)
1033 EQ -> Just (tvs `zip` tys, rhs, [])
1040 -- | Does this 'TyCon' have any generic to\/from functions available? See also 'hasGenerics'
1041 tyConHasGenerics :: TyCon -> Bool
1042 tyConHasGenerics (AlgTyCon {hasGenerics = hg}) = hg
1043 tyConHasGenerics (TupleTyCon {hasGenerics = hg}) = hg
1044 tyConHasGenerics _ = False -- Synonyms
1046 tyConKind :: TyCon -> Kind
1047 tyConKind (FunTyCon { tc_kind = k }) = k
1048 tyConKind (AlgTyCon { tc_kind = k }) = k
1049 tyConKind (TupleTyCon { tc_kind = k }) = k
1050 tyConKind (SynTyCon { tc_kind = k }) = k
1051 tyConKind (PrimTyCon { tc_kind = k }) = k
1052 tyConKind (AnyTyCon { tc_kind = k }) = k
1053 tyConKind tc = pprPanic "tyConKind" (ppr tc) -- SuperKindTyCon and CoTyCon
1055 tyConHasKind :: TyCon -> Bool
1056 tyConHasKind (SuperKindTyCon {}) = False
1057 tyConHasKind (CoTyCon {}) = False
1058 tyConHasKind _ = True
1060 -- | As 'tyConDataCons_maybe', but returns the empty list of constructors if no constructors
1062 tyConDataCons :: TyCon -> [DataCon]
1063 -- It's convenient for tyConDataCons to return the
1064 -- empty list for type synonyms etc
1065 tyConDataCons tycon = tyConDataCons_maybe tycon `orElse` []
1067 -- | Determine the 'DataCon's originating from the given 'TyCon', if the 'TyCon' is the
1068 -- sort that can have any constructors (note: this does not include abstract algebraic types)
1069 tyConDataCons_maybe :: TyCon -> Maybe [DataCon]
1070 tyConDataCons_maybe (AlgTyCon {algTcRhs = DataTyCon { data_cons = cons }}) = Just cons
1071 tyConDataCons_maybe (AlgTyCon {algTcRhs = NewTyCon { data_con = con }}) = Just [con]
1072 tyConDataCons_maybe (TupleTyCon {dataCon = con}) = Just [con]
1073 tyConDataCons_maybe _ = Nothing
1075 -- | Determine the number of value constructors a 'TyCon' has. Panics if the 'TyCon'
1076 -- is not algebraic or a tuple
1077 tyConFamilySize :: TyCon -> Int
1078 tyConFamilySize (AlgTyCon {algTcRhs = DataTyCon {data_cons = cons}}) =
1080 tyConFamilySize (AlgTyCon {algTcRhs = NewTyCon {}}) = 1
1081 tyConFamilySize (AlgTyCon {algTcRhs = OpenTyCon {}}) = 0
1082 tyConFamilySize (TupleTyCon {}) = 1
1083 tyConFamilySize other = pprPanic "tyConFamilySize:" (ppr other)
1085 -- | Extract an 'AlgTyConRhs' with information about data constructors from an algebraic or tuple
1086 -- 'TyCon'. Panics for any other sort of 'TyCon'
1087 algTyConRhs :: TyCon -> AlgTyConRhs
1088 algTyConRhs (AlgTyCon {algTcRhs = rhs}) = rhs
1089 algTyConRhs (TupleTyCon {dataCon = con, tyConArity = arity})
1090 = DataTyCon { data_cons = [con], is_enum = arity == 0 }
1091 algTyConRhs other = pprPanic "algTyConRhs" (ppr other)
1095 -- | Extract the bound type variables and type expansion of a type synonym 'TyCon'. Panics if the
1096 -- 'TyCon' is not a synonym
1097 newTyConRhs :: TyCon -> ([TyVar], Type)
1098 newTyConRhs (AlgTyCon {tyConTyVars = tvs, algTcRhs = NewTyCon { nt_rhs = rhs }}) = (tvs, rhs)
1099 newTyConRhs tycon = pprPanic "newTyConRhs" (ppr tycon)
1101 -- | Extract the bound type variables and type expansion of an eta-contracted type synonym 'TyCon'.
1102 -- Panics if the 'TyCon' is not a synonym
1103 newTyConEtadRhs :: TyCon -> ([TyVar], Type)
1104 newTyConEtadRhs (AlgTyCon {algTcRhs = NewTyCon { nt_etad_rhs = tvs_rhs }}) = tvs_rhs
1105 newTyConEtadRhs tycon = pprPanic "newTyConEtadRhs" (ppr tycon)
1107 -- | Extracts the @newtype@ coercion from such a 'TyCon', which can be used to construct something
1108 -- with the @newtype@s type from its representation type (right hand side). If the supplied 'TyCon'
1109 -- is not a @newtype@, returns @Nothing@
1110 newTyConCo_maybe :: TyCon -> Maybe TyCon
1111 newTyConCo_maybe (AlgTyCon {algTcRhs = NewTyCon { nt_co = co }}) = co
1112 newTyConCo_maybe _ = Nothing
1114 -- | Find the primitive representation of a 'TyCon'
1115 tyConPrimRep :: TyCon -> PrimRep
1116 tyConPrimRep (PrimTyCon {primTyConRep = rep}) = rep
1117 tyConPrimRep tc = ASSERT(not (isUnboxedTupleTyCon tc)) PtrRep
1121 -- | Find the \"stupid theta\" of the 'TyCon'. A \"stupid theta\" is the context to the left of
1122 -- an algebraic type declaration, e.g. @Eq a@ in the declaration @data Eq a => T a ...@
1123 tyConStupidTheta :: TyCon -> [PredType]
1124 tyConStupidTheta (AlgTyCon {algTcStupidTheta = stupid}) = stupid
1125 tyConStupidTheta (TupleTyCon {}) = []
1126 tyConStupidTheta tycon = pprPanic "tyConStupidTheta" (ppr tycon)
1130 -- | Extract the 'TyVar's bound by a type synonym and the corresponding (unsubstituted) right hand side.
1131 -- If the given 'TyCon' is not a type synonym, panics
1132 synTyConDefn :: TyCon -> ([TyVar], Type)
1133 synTyConDefn (SynTyCon {tyConTyVars = tyvars, synTcRhs = SynonymTyCon ty})
1135 synTyConDefn tycon = pprPanic "getSynTyConDefn" (ppr tycon)
1137 -- | Extract the information pertaining to the right hand side of a type synonym (@type@) declaration. Panics
1138 -- if the given 'TyCon' is not a type synonym
1139 synTyConRhs :: TyCon -> SynTyConRhs
1140 synTyConRhs (SynTyCon {synTcRhs = rhs}) = rhs
1141 synTyConRhs tc = pprPanic "synTyConRhs" (ppr tc)
1143 -- | Find the expansion of the type synonym represented by the given 'TyCon'. The free variables of this
1144 -- type will typically include those 'TyVar's bound by the 'TyCon'. Panics if the 'TyCon' is not that of
1146 synTyConType :: TyCon -> Type
1147 synTyConType tc = case synTcRhs tc of
1149 _ -> pprPanic "synTyConType" (ppr tc)
1151 -- | Find the 'Kind' of an open type synonym. Panics if the 'TyCon' is not an open type synonym
1152 synTyConResKind :: TyCon -> Kind
1153 synTyConResKind (SynTyCon {synTcRhs = OpenSynTyCon kind _}) = kind
1154 synTyConResKind tycon = pprPanic "synTyConResKind" (ppr tycon)
1158 -- | If the given 'TyCon' has a /single/ data constructor, i.e. it is a @data@ type with one
1159 -- alternative, a tuple type or a @newtype@ then that constructor is returned. If the 'TyCon'
1160 -- has more than one constructor, or represents a primitive or function type constructor then
1161 -- @Nothing@ is returned. In any other case, the function panics
1162 tyConSingleDataCon_maybe :: TyCon -> Maybe DataCon
1163 tyConSingleDataCon_maybe (TupleTyCon {dataCon = c}) = Just c
1164 tyConSingleDataCon_maybe (AlgTyCon {algTcRhs = DataTyCon { data_cons = [c] }}) = Just c
1165 tyConSingleDataCon_maybe (AlgTyCon {algTcRhs = NewTyCon { data_con = c }}) = Just c
1166 tyConSingleDataCon_maybe _ = Nothing
1170 -- | Is this 'TyCon' that for a class instance?
1171 isClassTyCon :: TyCon -> Bool
1172 isClassTyCon (AlgTyCon {algTcParent = ClassTyCon _}) = True
1173 isClassTyCon _ = False
1175 -- | If this 'TyCon' is that for a class instance, return the class it is for.
1176 -- Otherwise returns @Nothing@
1177 tyConClass_maybe :: TyCon -> Maybe Class
1178 tyConClass_maybe (AlgTyCon {algTcParent = ClassTyCon clas}) = Just clas
1179 tyConClass_maybe _ = Nothing
1181 -- | Is this 'TyCon' that for a family instance, be that for a synonym or an
1182 -- algebraic family instance?
1183 isFamInstTyCon :: TyCon -> Bool
1184 isFamInstTyCon (AlgTyCon {algTcParent = FamilyTyCon _ _ _ }) = True
1185 isFamInstTyCon (SynTyCon {synTcParent = FamilyTyCon _ _ _ }) = True
1186 isFamInstTyCon _ = False
1188 -- | If this 'TyCon' is that of a family instance, return the family in question
1189 -- and the instance types. Otherwise, return @Nothing@
1190 tyConFamInst_maybe :: TyCon -> Maybe (TyCon, [Type])
1191 tyConFamInst_maybe (AlgTyCon {algTcParent = FamilyTyCon fam instTys _}) =
1193 tyConFamInst_maybe (SynTyCon {synTcParent = FamilyTyCon fam instTys _}) =
1195 tyConFamInst_maybe _ =
1198 -- | If this 'TyCon' is that of a family instance, return a 'TyCon' which represents
1199 -- a coercion identifying the representation type with the type instance family.
1200 -- Otherwise, return @Nothing@
1201 tyConFamilyCoercion_maybe :: TyCon -> Maybe TyCon
1202 tyConFamilyCoercion_maybe (AlgTyCon {algTcParent = FamilyTyCon _ _ coe}) =
1204 tyConFamilyCoercion_maybe (SynTyCon {synTcParent = FamilyTyCon _ _ coe}) =
1206 tyConFamilyCoercion_maybe _ =
1211 %************************************************************************
1213 \subsection[TyCon-instances]{Instance declarations for @TyCon@}
1215 %************************************************************************
1217 @TyCon@s are compared by comparing their @Unique@s.
1219 The strictness analyser needs @Ord@. It is a lexicographic order with
1220 the property @(a<=b) || (b<=a)@.
1223 instance Eq TyCon where
1224 a == b = case (a `compare` b) of { EQ -> True; _ -> False }
1225 a /= b = case (a `compare` b) of { EQ -> False; _ -> True }
1227 instance Ord TyCon where
1228 a <= b = case (a `compare` b) of { LT -> True; EQ -> True; GT -> False }
1229 a < b = case (a `compare` b) of { LT -> True; EQ -> False; GT -> False }
1230 a >= b = case (a `compare` b) of { LT -> False; EQ -> True; GT -> True }
1231 a > b = case (a `compare` b) of { LT -> False; EQ -> False; GT -> True }
1232 compare a b = getUnique a `compare` getUnique b
1234 instance Uniquable TyCon where
1235 getUnique tc = tyConUnique tc
1237 instance Outputable CoTyConDesc where
1238 ppr CoSym = ptext (sLit "SYM")
1239 ppr CoTrans = ptext (sLit "TRANS")
1240 ppr CoLeft = ptext (sLit "LEFT")
1241 ppr CoRight = ptext (sLit "RIGHT")
1242 ppr CoCsel1 = ptext (sLit "CSEL1")
1243 ppr CoCsel2 = ptext (sLit "CSEL2")
1244 ppr CoCselR = ptext (sLit "CSELR")
1245 ppr CoInst = ptext (sLit "INST")
1246 ppr CoUnsafe = ptext (sLit "UNSAFE")
1247 ppr (CoAxiom {}) = ptext (sLit "AXIOM")
1249 instance Outputable TyCon where
1250 ppr tc = ppr (getName tc)
1252 instance NamedThing TyCon where