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,
16 AssocFamilyPermutation,
18 -- ** Constructing TyCons
31 -- ** Predicates on TyCons
33 isClassTyCon, isFamInstTyCon,
36 isTupleTyCon, isUnboxedTupleTyCon, isBoxedTupleTyCon,
37 isSynTyCon, isClosedSynTyCon, isOpenSynTyCon,
39 isCoercionTyCon, isCoercionTyCon_maybe,
42 isDataTyCon, isProductTyCon, isEnumerationTyCon,
43 isNewTyCon, isAbstractTyCon, isOpenTyCon,
49 isImplicitTyCon, tyConHasGenerics,
51 -- ** Extracting information out of TyCons
56 tyConDataCons, tyConDataCons_maybe, tyConSingleDataCon_maybe,
61 tyConFamInst_maybe, tyConFamilyCoercion_maybe,
62 synTyConDefn, synTyConRhs, synTyConType, synTyConResKind,
63 tyConExtName, -- External name for foreign types
65 newTyConRhs, newTyConEtadRhs, unwrapNewTyCon_maybe,
66 assocTyConArgPoss_maybe,
69 -- ** Manipulating TyCons
70 tcExpandTyCon_maybe, coreExpandTyCon_maybe,
75 -- * Primitive representations of Types
81 #include "HsVersions.h"
83 import {-# SOURCE #-} TypeRep ( Kind, Type, PredType )
84 import {-# SOURCE #-} DataCon ( DataCon, isVanillaDataCon )
95 import Data.List( elemIndex )
98 %************************************************************************
100 \subsection{The data type}
102 %************************************************************************
105 -- | Represents type constructors. Type constructors are introduced by things such as:
107 -- 1) Data declarations: @data Foo = ...@ creates the @Foo@ type constructor of kind @*@
109 -- 2) Type synonyms: @type Foo = ...@ creates the @Foo@ type constructor
111 -- 3) Newtypes: @newtype Foo a = MkFoo ...@ creates the @Foo@ type constructor of kind @* -> *@
113 -- 4) Class declarations: @class Foo where@ creates the @Foo@ type constructor of kind @*@
115 -- 5) Type coercions! This is because we represent a coercion from @t1@ to @t2@ as a 'Type', where
116 -- that type has kind @t1 ~ t2@. See "Coercion" for more on this
118 -- This data type also encodes a number of primitive, built in type constructors such as those
119 -- for function and tuple types.
121 = -- | The function type constructor, @(->)@
123 tyConUnique :: Unique,
129 -- | Algebraic type constructors, which are defined to be those arising @data@ type and @newtype@ declarations.
130 -- All these constructors are lifted and boxed. See 'AlgTyConRhs' for more information.
132 tyConUnique :: Unique,
137 tyConTyVars :: [TyVar], -- ^ The type variables used in the type constructor.
138 -- Precisely, this list scopes over:
140 -- 1. The 'algTcStupidTheta'
142 -- 2. The cached types in 'algTyConRhs.NewTyCon'
144 -- 3. The family instance types if present
146 -- Note that it does /not/ scope over the data constructors.
148 algTcGadtSyntax :: Bool, -- ^ Was the data type declared with GADT syntax? If so,
149 -- that doesn't mean it's a true GADT; only that the "where"
150 -- form was used. This field is used only to guide
152 algTcStupidTheta :: [PredType], -- ^ The \"stupid theta\" for the data type (always empty for GADTs).
153 -- A \"stupid theta\" is the context to the left of an algebraic type
154 -- declaration, e.g. @Eq a@ in the declaration @data Eq a => T a ...@.
156 algTcRhs :: AlgTyConRhs, -- ^ Contains information about the data constructors of the algebraic type
158 algTcRec :: RecFlag, -- ^ Tells us whether the data type is part of a mutually-recursive group or not
160 hasGenerics :: Bool, -- ^ Whether generic (in the -XGenerics sense) to\/from functions are
161 -- available in the exports of the data type's source module.
163 algTcParent :: TyConParent -- ^ Gives the class or family declaration 'TyCon' for derived 'TyCon's
164 -- representing class or family instances, respectively. See also 'synTcParent'
167 -- | Represents the infinite family of tuple type constructors, @()@, @(a,b)@, @(# a, b #)@ etc.
169 tyConUnique :: Unique,
173 tyConBoxed :: Boxity,
174 tyConTyVars :: [TyVar],
175 dataCon :: DataCon, -- ^ Corresponding tuple data constructor
179 -- | Represents type synonyms
181 tyConUnique :: Unique,
186 tyConTyVars :: [TyVar], -- Bound tyvars
188 synTcRhs :: SynTyConRhs, -- ^ Contains information about the expansion of the synonym
190 synTcParent :: TyConParent -- ^ Gives the family declaration 'TyCon' of 'TyCon's representing family instances
194 -- | Primitive types; cannot be defined in Haskell. This includes the usual suspects (such as @Int#@)
195 -- as well as foreign-imported types and kinds
197 tyConUnique :: Unique,
200 tyConArity :: Arity, -- SLPJ Oct06: I'm not sure what the significance
201 -- of the arity of a primtycon is!
203 primTyConRep :: PrimRep,
204 -- ^ Many primitive tycons are unboxed, but some are
205 -- boxed (represented by pointers). This 'PrimRep' holds
208 isUnLifted :: Bool, -- ^ Most primitive tycons are unlifted (may not contain bottom)
209 -- but foreign-imported ones may be lifted
210 tyConExtName :: Maybe FastString -- ^ @Just e@ for foreign-imported types, holds the name of the imported thing
213 -- | Type coercions, such as @(~)@, @sym@, @trans@, @left@ and @right@.
214 -- INVARIANT: coercions are always fully applied
216 tyConUnique :: Unique,
219 coKindFun :: [Type] -> (Type,Type)
220 -- ^ Function that when given a list of the type arguments to the 'TyCon'
221 -- constructs the types that the resulting coercion relates.
223 -- INVARIANT: 'coKindFun' is always applied to exactly 'tyConArity' args
224 -- E.g. for @trans (c1 :: ta=tb) (c2 :: tb=tc)@, the 'coKindFun' returns
225 -- the kind as a pair of types: @(ta, tc)@
228 -- | Super-kinds. These are "kinds-of-kinds" and are never seen in Haskell source programs.
229 -- There are only two super-kinds: TY (aka "box"), which is the super-kind of kinds that
230 -- construct types eventually, and CO (aka "diamond"), which is the super-kind of kinds
231 -- that just represent coercions.
233 -- Super-kinds have no kind themselves, and have arity zero
235 tyConUnique :: Unique,
239 -- | Names of the fields in an algebraic record type
240 type FieldLabel = Name
242 -- | Represents right-hand-sides of 'TyCon's for algebraic types
245 -- | Says that we know nothing about this data type, except that it's represented
246 -- by a pointer. Used when we export a data type abstractly into an .hi file.
249 -- | Represents an open type family without a fixed right hand
250 -- side. Additional instances can appear at any time.
252 -- These are introduced by either a top level declaration:
256 -- Or an assoicated data type declaration, within a class declaration:
258 -- > class C a b where
262 otArgPoss :: AssocFamilyPermutation
265 -- | Information about those 'TyCon's derived from a @data@ declaration. This includes
266 -- data types with no constructors at all.
268 data_cons :: [DataCon],
269 -- ^ The data type constructors; can be empty if the user declares
270 -- the type to have no constructors
272 -- INVARIANT: Kept in order of increasing 'DataCon' tag
274 -- (see the tag assignment in DataCon.mkDataCon)
275 is_enum :: Bool -- ^ Cached value: is this an enumeration type? (See 'isEnumerationTyCon')
278 -- | Information about those 'TyCon's derived from a @newtype@ declaration
280 data_con :: DataCon, -- ^ The unique constructor for the @newtype@. It has no existentials
282 nt_rhs :: Type, -- ^ Cached value: the argument type of the constructor, which
283 -- is just the representation type of the 'TyCon' (remember that
284 -- @newtype@s do not exist at runtime so need a different representation
287 -- The free 'TyVar's of this type are the 'tyConTyVars' from the corresponding
290 nt_etad_rhs :: ([TyVar], Type),
291 -- ^ Same as the 'nt_rhs', but this time eta-reduced. Hence the list of 'TyVar's in
292 -- this field may be shorter than the declared arity of the 'TyCon'.
294 -- See Note [Newtype eta]
296 nt_co :: Maybe TyCon -- ^ A 'TyCon' (which is always a 'CoercionTyCon') that can have a 'Coercion'
297 -- extracted from it to create the @newtype@ from the representation 'Type'.
299 -- This field is optional for non-recursive @newtype@s only.
301 -- See Note [Newtype coercions]
302 -- Invariant: arity = #tvs in nt_etad_rhs;
303 -- See Note [Newtype eta]
304 -- Watch out! If any newtypes become transparent
305 -- again check Trac #1072.
308 type AssocFamilyPermutation
309 = Maybe [Int] -- Nothing for *top-level* type families
310 -- For *associated* type families, gives the position
311 -- of that 'TyVar' in the class argument list (0-indexed)
312 -- e.g. class C a b c where { type F c a :: *->* }
313 -- Then we get Just [2,0]
314 -- For *synonyms*, the length of the list is identical to
316 -- For *data types*, the length may be smaller than the
317 -- TyCon's arity; e.g. class C a where { data D a :: *->* }
318 -- here D gets arity 2
320 -- | Extract those 'DataCon's that we are able to learn about. Note that visibility in this sense does not
321 -- correspond to visibility in the context of any particular user program!
322 visibleDataCons :: AlgTyConRhs -> [DataCon]
323 visibleDataCons AbstractTyCon = []
324 visibleDataCons OpenTyCon {} = []
325 visibleDataCons (DataTyCon{ data_cons = cs }) = cs
326 visibleDataCons (NewTyCon{ data_con = c }) = [c]
328 -- ^ Both type classes as well as family instances imply implicit
329 -- type constructors. These implicit type constructors refer to their parent
330 -- structure (ie, the class or family from which they derive) using a type of
331 -- the following form. We use 'TyConParent' for both algebraic and synonym
332 -- types, but the variant 'ClassTyCon' will only be used by algebraic 'TyCon's.
334 = -- | An ordinary type constructor has no parent.
337 -- | Type constructors representing a class dictionary.
339 Class -- INVARIANT: the classTyCon of this Class is the current tycon
341 -- | Type constructors representing an instance of a type family. Parameters:
343 -- 1) The type family in question
345 -- 2) Instance types; free variables are the 'tyConTyVars'
346 -- of the current 'TyCon' (not the family one). INVARIANT:
347 -- the number of types matches the arity of the family 'TyCon'
349 -- 3) A 'CoercionTyCon' identifying the representation
350 -- type with the type instance family
354 TyCon -- c.f. Note [Newtype coercions]
357 -- E.g. data intance T [a] = ...
358 -- gives a representation tycon:
360 -- axiom co a :: T [a] ~ :R7T a
361 -- with :R7T's algTcParent = FamilyTyCon T [a] co
363 -- | Checks the invariants of a 'TyConParent' given the appropriate type class name, if any
364 okParent :: Name -> TyConParent -> Bool
365 okParent _ NoParentTyCon = True
366 okParent tc_name (ClassTyCon cls) = tyConName (classTyCon cls) == tc_name
367 okParent _ (FamilyTyCon fam_tc tys _co_tc) = tyConArity fam_tc == length tys
371 -- | Information pertaining to the expansion of a type synonym (@type@)
373 = OpenSynTyCon -- e.g. type family F x y :: * -> *
374 Kind -- Kind of the "rhs"; ie *excluding type indices*
375 -- In the example, the kind is (*->*)
376 AssocFamilyPermutation
378 | SynonymTyCon Type -- ^ The synonym mentions head type variables. It acts as a
379 -- template for the expansion when the 'TyCon' is applied to some
383 Note [Newtype coercions]
384 ~~~~~~~~~~~~~~~~~~~~~~~~
385 The NewTyCon field nt_co is a a TyCon (a coercion constructor in fact)
386 which is used for coercing from the representation type of the
387 newtype, to the newtype itself. For example,
389 newtype T a = MkT (a -> a)
391 the NewTyCon for T will contain nt_co = CoT where CoT t : T t ~ t ->
392 t. This TyCon is a CoercionTyCon, so it does not have a kind on its
393 own; it basically has its own typing rule for the fully-applied
394 version. If the newtype T has k type variables then CoT has arity at
395 most k. In the case that the right hand side is a type application
396 ending with the same type variables as the left hand side, we
397 "eta-contract" the coercion. So if we had
399 newtype S a = MkT [a]
401 then we would generate the arity 0 coercion CoS : S ~ []. The
402 primary reason we do this is to make newtype deriving cleaner.
404 In the paper we'd write
405 axiom CoT : (forall t. T t) ~ (forall t. [t])
406 and then when we used CoT at a particular type, s, we'd say
408 which encodes as (TyConApp instCoercionTyCon [TyConApp CoT [], s])
410 But in GHC we instead make CoT into a new piece of type syntax, CoercionTyCon,
411 (like instCoercionTyCon, symCoercionTyCon etc), which must always
412 be saturated, but which encodes as
414 In the vocabulary of the paper it's as if we had axiom declarations
416 axiom CoT t : T t ~ [t]
421 newtype Parser m a = MkParser (Foogle m a)
422 Are these two types equal (to Core)?
425 Well, yes. But to see that easily we eta-reduce the RHS type of
426 Parser, in this case to ([], Froogle), so that even unsaturated applications
427 of Parser will work right. This eta reduction is done when the type
428 constructor is built, and cached in NewTyCon. The cached field is
429 only used in coreExpandTyCon_maybe.
431 Here's an example that I think showed up in practice
433 newtype T a = MkT [a]
434 newtype Foo m = MkFoo (forall a. m a -> Int)
440 w2 = MkFoo (\(MkT x) -> case w1 of MkFoo f -> f x)
442 After desugaring, and discarding the data constructors for the newtypes,
446 And now Lint complains unless Foo T == Foo [], and that requires T==[]
448 This point carries over to the newtype coercion, because we need to
450 w2 = w1 `cast` Foo CoT
452 so the coercion tycon CoT must have
457 Note [Indexed data types] (aka data type families)
458 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
459 See also Note [Wrappers for data instance tycons] in MkId.lhs
464 data instance T (b,c) where
465 T1 :: b -> c -> T (b,c)
468 * T is the "family TyCon"
470 * We make "representation TyCon" :R1T, thus:
472 T1 :: forall b c. b -> c -> :R1T b c
474 * It has a top-level coercion connecting it to the family TyCon
476 axiom :Co:R1T b c : T (b,c) ~ :R1T b c
478 * The data contructor T1 has a wrapper (which is what the source-level
481 $WT1 :: forall b c. b -> c -> T (b,c)
482 $WT1 b c (x::b) (y::c) = T1 b c x y `cast` sym (:Co:R1T b c)
484 * The representation TyCon :R1T has an AlgTyConParent of
486 FamilyTyCon T [(b,c)] :Co:R1T
490 %************************************************************************
494 %************************************************************************
496 A PrimRep is somewhat similar to a CgRep (see codeGen/SMRep) and a
497 MachRep (see cmm/MachOp), although each of these types has a distinct
498 and clearly defined purpose:
500 - A PrimRep is a CgRep + information about signedness + information
501 about primitive pointers (AddrRep). Signedness and primitive
502 pointers are required when passing a primitive type to a foreign
503 function, but aren't needed for call/return conventions of Haskell
506 - A MachRep is a basic machine type (non-void, doesn't contain
507 information on pointerhood or signedness, but contains some
508 reps that don't have corresponding Haskell types).
511 -- | A 'PrimRep' is an abstraction of a type. It contains information that
512 -- the code generator needs in order to pass arguments, return results,
513 -- and store values of this type.
517 | IntRep -- ^ Signed, word-sized value
518 | WordRep -- ^ Unsigned, word-sized value
519 | Int64Rep -- ^ Signed, 64 bit value (with 32-bit words only)
520 | Word64Rep -- ^ Unsigned, 64 bit value (with 32-bit words only)
521 | AddrRep -- ^ A pointer, but /not/ to a Haskell value (use 'PtrRep')
526 instance Outputable PrimRep where
527 ppr r = text (show r)
529 -- | Find the size of a 'PrimRep', in words
530 primRepSizeW :: PrimRep -> Int
531 primRepSizeW IntRep = 1
532 primRepSizeW WordRep = 1
533 primRepSizeW Int64Rep = wORD64_SIZE `quot` wORD_SIZE
534 primRepSizeW Word64Rep= wORD64_SIZE `quot` wORD_SIZE
535 primRepSizeW FloatRep = 1 -- NB. might not take a full word
536 primRepSizeW DoubleRep= dOUBLE_SIZE `quot` wORD_SIZE
537 primRepSizeW AddrRep = 1
538 primRepSizeW PtrRep = 1
539 primRepSizeW VoidRep = 0
542 %************************************************************************
544 \subsection{TyCon Construction}
546 %************************************************************************
548 Note: the TyCon constructors all take a Kind as one argument, even though
549 they could, in principle, work out their Kind from their other arguments.
550 But to do so they need functions from Types, and that makes a nasty
551 module mutual-recursion. And they aren't called from many places.
552 So we compromise, and move their Kind calculation to the call site.
555 -- | Given the name of the function type constructor and it's kind, create the
556 -- corresponding 'TyCon'. It is reccomended to use 'TypeRep.funTyCon' if you want
557 -- this functionality
558 mkFunTyCon :: Name -> Kind -> TyCon
561 tyConUnique = nameUnique name,
567 -- | This is the making of an algebraic 'TyCon'. Notably, you have to pass in the generic (in the -XGenerics sense)
568 -- information about the type constructor - you can get hold of it easily (see Generics module)
570 -> Kind -- ^ Kind of the resulting 'TyCon'
571 -> [TyVar] -- ^ 'TyVar's scoped over: see 'tyConTyVars'. Arity is inferred from the length of this list
572 -> [PredType] -- ^ Stupid theta: see 'algTcStupidTheta'
573 -> AlgTyConRhs -- ^ Information about dat aconstructors
575 -> RecFlag -- ^ Is the 'TyCon' recursive?
576 -> Bool -- ^ Does it have generic functions? See 'hasGenerics'
577 -> Bool -- ^ Was the 'TyCon' declared with GADT syntax?
579 mkAlgTyCon name kind tyvars stupid rhs parent is_rec gen_info gadt_syn
582 tyConUnique = nameUnique name,
584 tyConArity = length tyvars,
585 tyConTyVars = tyvars,
586 algTcStupidTheta = stupid,
588 algTcParent = ASSERT( okParent name parent ) parent,
590 algTcGadtSyntax = gadt_syn,
591 hasGenerics = gen_info
594 -- | Simpler specialization of 'mkAlgTyCon' for classes
595 mkClassTyCon :: Name -> Kind -> [TyVar] -> AlgTyConRhs -> Class -> RecFlag -> TyCon
596 mkClassTyCon name kind tyvars rhs clas is_rec =
597 mkAlgTyCon name kind tyvars [] rhs (ClassTyCon clas) is_rec False False
600 -> Kind -- ^ Kind of the resulting 'TyCon'
601 -> Arity -- ^ Arity of the tuple
602 -> [TyVar] -- ^ 'TyVar's scoped over: see 'tyConTyVars'
604 -> Boxity -- ^ Whether the tuple is boxed or unboxed
605 -> Bool -- ^ Does it have generic functions? See 'hasGenerics'
607 mkTupleTyCon name kind arity tyvars con boxed gen_info
609 tyConUnique = nameUnique name,
614 tyConTyVars = tyvars,
616 hasGenerics = gen_info
619 -- ^ Foreign-imported (.NET) type constructors are represented
620 -- as primitive, but /lifted/, 'TyCons' for now. They are lifted
621 -- because the Haskell type @T@ representing the (foreign) .NET
622 -- type @T@ is actually implemented (in ILX) as a @thunk<T>@
623 mkForeignTyCon :: Name
624 -> Maybe FastString -- ^ Name of the foreign imported thing, maybe
628 mkForeignTyCon name ext_name kind arity
631 tyConUnique = nameUnique name,
634 primTyConRep = PtrRep, -- they all do
636 tyConExtName = ext_name
640 -- | Create an unlifted primitive 'TyCon', such as @Int#@
641 mkPrimTyCon :: Name -> Kind -> Arity -> PrimRep -> TyCon
642 mkPrimTyCon name kind arity rep
643 = mkPrimTyCon' name kind arity rep True
645 -- | Create the special void 'TyCon' which is unlifted and has 'VoidRep'
646 mkVoidPrimTyCon :: Name -> Kind -> Arity -> TyCon
647 mkVoidPrimTyCon name kind arity
648 = mkPrimTyCon' name kind arity VoidRep True
650 -- | Create a lifted primitive 'TyCon' such as @RealWorld@
651 mkLiftedPrimTyCon :: Name -> Kind -> Arity -> PrimRep -> TyCon
652 mkLiftedPrimTyCon name kind arity rep
653 = mkPrimTyCon' name kind arity rep False
655 mkPrimTyCon' :: Name -> Kind -> Arity -> PrimRep -> Bool -> TyCon
656 mkPrimTyCon' name kind arity rep is_unlifted
659 tyConUnique = nameUnique name,
663 isUnLifted = is_unlifted,
664 tyConExtName = Nothing
667 -- | Create a type synonym 'TyCon'
668 mkSynTyCon :: Name -> Kind -> [TyVar] -> SynTyConRhs -> TyConParent -> TyCon
669 mkSynTyCon name kind tyvars rhs parent
672 tyConUnique = nameUnique name,
674 tyConArity = length tyvars,
675 tyConTyVars = tyvars,
680 -- | Create a coercion 'TyCon'
681 mkCoercionTyCon :: Name -> Arity -> ([Type] -> (Type,Type)) -> TyCon
682 mkCoercionTyCon name arity kindRule
685 tyConUnique = nameUnique name,
690 -- | Create a super-kind 'TyCon'
691 mkSuperKindTyCon :: Name -> TyCon -- Super kinds always have arity zero
692 mkSuperKindTyCon name
695 tyConUnique = nameUnique name
700 isFunTyCon :: TyCon -> Bool
701 isFunTyCon (FunTyCon {}) = True
704 -- | Test if the 'TyCon' is algebraic but abstract (invisible data constructors)
705 isAbstractTyCon :: TyCon -> Bool
706 isAbstractTyCon (AlgTyCon { algTcRhs = AbstractTyCon }) = True
707 isAbstractTyCon _ = False
709 -- | Make an algebraic 'TyCon' abstract. Panics if the supplied 'TyCon' is not algebraic
710 makeTyConAbstract :: TyCon -> TyCon
711 makeTyConAbstract tc@(AlgTyCon {}) = tc { algTcRhs = AbstractTyCon }
712 makeTyConAbstract tc = pprPanic "makeTyConAbstract" (ppr tc)
714 -- | Does this 'TyCon' represent something that cannot be defined in Haskell?
715 isPrimTyCon :: TyCon -> Bool
716 isPrimTyCon (PrimTyCon {}) = True
717 isPrimTyCon _ = False
719 -- | Is this 'TyCon' unlifted (i.e. cannot contain bottom)? Note that this can only
720 -- be true for primitive and unboxed-tuple 'TyCon's
721 isUnLiftedTyCon :: TyCon -> Bool
722 isUnLiftedTyCon (PrimTyCon {isUnLifted = is_unlifted}) = is_unlifted
723 isUnLiftedTyCon (TupleTyCon {tyConBoxed = boxity}) = not (isBoxed boxity)
724 isUnLiftedTyCon _ = False
726 -- | Returns @True@ if the supplied 'TyCon' resulted from either a @data@ or @newtype@ declaration
727 isAlgTyCon :: TyCon -> Bool
728 isAlgTyCon (AlgTyCon {}) = True
729 isAlgTyCon (TupleTyCon {}) = True
732 isDataTyCon :: TyCon -> Bool
733 -- ^ Returns @True@ for data types that are /definitely/ represented by
734 -- heap-allocated constructors. These are scrutinised by Core-level
735 -- @case@ expressions, and they get info tables allocated for them.
737 -- Generally, the function will be true for all @data@ types and false
738 -- for @newtype@s, unboxed tuples and type family 'TyCon's. But it is
739 -- not guarenteed to return @True@ in all cases that it could.
741 -- NB: for a data type family, only the /instance/ 'TyCon's
742 -- get an info table. The family declaration 'TyCon' does not
743 isDataTyCon (AlgTyCon {algTcRhs = rhs})
745 OpenTyCon {} -> False
748 AbstractTyCon -> False -- We don't know, so return False
749 isDataTyCon (TupleTyCon {tyConBoxed = boxity}) = isBoxed boxity
750 isDataTyCon _ = False
752 -- | Is this 'TyCon' that for a @newtype@
753 isNewTyCon :: TyCon -> Bool
754 isNewTyCon (AlgTyCon {algTcRhs = NewTyCon {}}) = True
757 -- | Take a 'TyCon' apart into the 'TyVar's it scopes over, the 'Type' it expands
758 -- into, and (possibly) a coercion from the representation type to the @newtype@.
759 -- Returns @Nothing@ if this is not possible.
760 unwrapNewTyCon_maybe :: TyCon -> Maybe ([TyVar], Type, Maybe TyCon)
761 unwrapNewTyCon_maybe (AlgTyCon { tyConTyVars = tvs,
762 algTcRhs = NewTyCon { nt_co = mb_co,
764 = Just (tvs, rhs, mb_co)
765 unwrapNewTyCon_maybe _ = Nothing
767 isProductTyCon :: TyCon -> Bool
768 -- | A /product/ 'TyCon' must both:
770 -- 1. Have /one/ constructor
772 -- 2. /Not/ be existential
774 -- However other than this there are few restrictions: they may be @data@ or @newtype@
775 -- 'TyCon's of any boxity and may even be recursive.
776 isProductTyCon tc@(AlgTyCon {}) = case algTcRhs tc of
777 DataTyCon{ data_cons = [data_con] }
778 -> isVanillaDataCon data_con
781 isProductTyCon (TupleTyCon {}) = True
782 isProductTyCon _ = False
784 -- | Is this a 'TyCon' representing a type synonym (@type@)?
785 isSynTyCon :: TyCon -> Bool
786 isSynTyCon (SynTyCon {}) = True
789 -- As for newtypes, it is in some contexts important to distinguish between
790 -- closed synonyms and synonym families, as synonym families have no unique
791 -- right hand side to which a synonym family application can expand.
794 -- | Is this a synonym 'TyCon' that can have no further instances appear?
795 isClosedSynTyCon :: TyCon -> Bool
796 isClosedSynTyCon tycon = isSynTyCon tycon && not (isOpenTyCon tycon)
798 -- | Is this a synonym 'TyCon' that can have may have further instances appear?
799 isOpenSynTyCon :: TyCon -> Bool
800 isOpenSynTyCon tycon = isSynTyCon tycon && isOpenTyCon tycon
802 -- | Is this an algebraic 'TyCon' declared with the GADT syntax?
803 isGadtSyntaxTyCon :: TyCon -> Bool
804 isGadtSyntaxTyCon (AlgTyCon { algTcGadtSyntax = res }) = res
805 isGadtSyntaxTyCon _ = False
807 -- | Is this an algebraic 'TyCon' which is just an enumeration of values?
808 isEnumerationTyCon :: TyCon -> Bool
809 isEnumerationTyCon (AlgTyCon {algTcRhs = DataTyCon { is_enum = res }}) = res
810 isEnumerationTyCon _ = False
812 -- | Is this a 'TyCon', synonym or otherwise, that may have further instances appear?
813 isOpenTyCon :: TyCon -> Bool
814 isOpenTyCon (SynTyCon {synTcRhs = OpenSynTyCon _ _}) = True
815 isOpenTyCon (AlgTyCon {algTcRhs = OpenTyCon {} }) = True
816 isOpenTyCon _ = False
818 -- | Extract the mapping from 'TyVar' indexes to indexes in the corresponding family
819 -- argument lists form an open 'TyCon' of any sort, if the given 'TyCon' is indeed
820 -- such a beast and that information is available
821 assocTyConArgPoss_maybe :: TyCon -> Maybe [Int]
822 assocTyConArgPoss_maybe (AlgTyCon {
823 algTcRhs = OpenTyCon {otArgPoss = poss}}) = poss
824 assocTyConArgPoss_maybe (SynTyCon { synTcRhs = OpenSynTyCon _ poss }) = poss
825 assocTyConArgPoss_maybe _ = Nothing
827 -- | Are we able to extract informationa 'TyVar' to class argument list
828 -- mappping from a given 'TyCon'?
829 isTyConAssoc :: TyCon -> Bool
830 isTyConAssoc = isJust . assocTyConArgPoss_maybe
832 -- | Set the AssocFamilyPermutation structure in an
833 -- associated data or type synonym. The [TyVar] are the
834 -- class type variables. Remember, the tyvars of an associated
835 -- data/type are a subset of the class tyvars; except that an
836 -- associated data type can have extra type variables at the
837 -- end (see Note [Avoid name clashes for associated data types] in TcHsType)
838 setTyConArgPoss :: [TyVar] -> TyCon -> TyCon
839 setTyConArgPoss clas_tvs tc
841 AlgTyCon { algTcRhs = rhs } -> tc { algTcRhs = rhs {otArgPoss = Just ps} }
842 SynTyCon { synTcRhs = OpenSynTyCon ki _ } -> tc { synTcRhs = OpenSynTyCon ki (Just ps) }
843 _ -> pprPanic "setTyConArgPoss" (ppr tc)
845 ps = catMaybes [tv `elemIndex` clas_tvs | tv <- tyConTyVars tc]
846 -- We will get Nothings for the "extra" type variables in an
847 -- associated data type
849 -- The unit tycon didn't used to be classed as a tuple tycon
850 -- but I thought that was silly so I've undone it
851 -- If it can't be for some reason, it should be a AlgTyCon
852 isTupleTyCon :: TyCon -> Bool
853 -- ^ Does this 'TyCon' represent a tuple?
855 -- NB: when compiling @Data.Tuple@, the tycons won't reply @True@ to
856 -- 'isTupleTyCon', becuase they are built as 'AlgTyCons'. However they
857 -- get spat into the interface file as tuple tycons, so I don't think
859 isTupleTyCon (TupleTyCon {}) = True
860 isTupleTyCon _ = False
862 -- | Is this the 'TyCon' for an unboxed tuple?
863 isUnboxedTupleTyCon :: TyCon -> Bool
864 isUnboxedTupleTyCon (TupleTyCon {tyConBoxed = boxity}) = not (isBoxed boxity)
865 isUnboxedTupleTyCon _ = False
867 -- | Is this the 'TyCon' for a boxed tuple?
868 isBoxedTupleTyCon :: TyCon -> Bool
869 isBoxedTupleTyCon (TupleTyCon {tyConBoxed = boxity}) = isBoxed boxity
870 isBoxedTupleTyCon _ = False
872 -- | Extract the boxity of the given 'TyCon', if it is a 'TupleTyCon'.
874 tupleTyConBoxity :: TyCon -> Boxity
875 tupleTyConBoxity tc = tyConBoxed tc
877 -- | Is this a recursive 'TyCon'?
878 isRecursiveTyCon :: TyCon -> Bool
879 isRecursiveTyCon (AlgTyCon {algTcRec = Recursive}) = True
880 isRecursiveTyCon _ = False
882 -- | Did this 'TyCon' originate from type-checking a .h*-boot file?
883 isHiBootTyCon :: TyCon -> Bool
884 -- Used for knot-tying in hi-boot files
885 isHiBootTyCon (AlgTyCon {algTcRhs = AbstractTyCon}) = True
886 isHiBootTyCon _ = False
888 -- | Is this the 'TyCon' of a foreign-imported type constructor?
889 isForeignTyCon :: TyCon -> Bool
890 isForeignTyCon (PrimTyCon {tyConExtName = Just _}) = True
891 isForeignTyCon _ = False
893 -- | Is this a super-kind 'TyCon'?
894 isSuperKindTyCon :: TyCon -> Bool
895 isSuperKindTyCon (SuperKindTyCon {}) = True
896 isSuperKindTyCon _ = False
898 -- | Attempt to pull a 'TyCon' apart into the arity and 'coKindFun' of
899 -- a coercion 'TyCon'. Returns @Nothing@ if the 'TyCon' is not of the
901 isCoercionTyCon_maybe :: TyCon -> Maybe (Arity, [Type] -> (Type,Type))
902 isCoercionTyCon_maybe (CoercionTyCon {tyConArity = ar, coKindFun = rule})
904 isCoercionTyCon_maybe _ = Nothing
906 -- | Is this a 'TyCon' that represents a coercion?
907 isCoercionTyCon :: TyCon -> Bool
908 isCoercionTyCon (CoercionTyCon {}) = True
909 isCoercionTyCon _ = False
911 -- | Identifies implicit tycons that, in particular, do not go into interface
912 -- files (because they are implicitly reconstructed when the interface is
917 -- * Associated families are implicit, as they are re-constructed from
918 -- the class declaration in which they reside, and
920 -- * Family instances are /not/ implicit as they represent the instance body
921 -- (similar to a @dfun@ does that for a class instance).
922 isImplicitTyCon :: TyCon -> Bool
923 isImplicitTyCon tycon | isTyConAssoc tycon = True
924 | isSynTyCon tycon = False
925 | isAlgTyCon tycon = isClassTyCon tycon ||
927 isImplicitTyCon _other = True
928 -- catches: FunTyCon, PrimTyCon,
929 -- CoercionTyCon, SuperKindTyCon
933 -----------------------------------------------
934 -- Expand type-constructor applications
935 -----------------------------------------------
938 tcExpandTyCon_maybe, coreExpandTyCon_maybe
940 -> [Type] -- ^ Arguments to 'TyCon'
941 -> Maybe ([(TyVar,Type)],
943 [Type]) -- ^ Returns a 'TyVar' substitution, the body type
944 -- of the synonym (not yet substituted) and any arguments
945 -- remaining from the application
947 -- ^ Used to create the view the /typechecker/ has on 'TyCon's. We expand (closed) synonyms only, cf. 'coreExpandTyCon_maybe'
948 tcExpandTyCon_maybe (SynTyCon {tyConTyVars = tvs,
949 synTcRhs = SynonymTyCon rhs }) tys
951 tcExpandTyCon_maybe _ _ = Nothing
955 -- ^ Used to create the view /Core/ has on 'TyCon's. We expand not only closed synonyms like 'tcExpandTyCon_maybe',
956 -- but also non-recursive @newtype@s
957 coreExpandTyCon_maybe (AlgTyCon {algTcRec = NonRecursive, -- Not recursive
958 algTcRhs = NewTyCon { nt_etad_rhs = etad_rhs, nt_co = Nothing }}) tys
959 = case etad_rhs of -- Don't do this in the pattern match, lest we accidentally
960 -- match the etad_rhs of a *recursive* newtype
961 (tvs,rhs) -> expand tvs rhs tys
963 coreExpandTyCon_maybe tycon tys = tcExpandTyCon_maybe tycon tys
967 expand :: [TyVar] -> Type -- Template
969 -> Maybe ([(TyVar,Type)], Type, [Type]) -- Expansion
971 = case n_tvs `compare` length tys of
972 LT -> Just (tvs `zip` tys, rhs, drop n_tvs tys)
973 EQ -> Just (tvs `zip` tys, rhs, [])
980 -- | Does this 'TyCon' have any generic to\/from functions available? See also 'hasGenerics'
981 tyConHasGenerics :: TyCon -> Bool
982 tyConHasGenerics (AlgTyCon {hasGenerics = hg}) = hg
983 tyConHasGenerics (TupleTyCon {hasGenerics = hg}) = hg
984 tyConHasGenerics _ = False -- Synonyms
986 -- | As 'tyConDataCons_maybe', but returns the empty list of constructors if no constructors
988 tyConDataCons :: TyCon -> [DataCon]
989 -- It's convenient for tyConDataCons to return the
990 -- empty list for type synonyms etc
991 tyConDataCons tycon = tyConDataCons_maybe tycon `orElse` []
993 -- | Determine the 'DataCon's originating from the given 'TyCon', if the 'TyCon' is the
994 -- sort that can have any constructors (note: this does not include abstract algebraic types)
995 tyConDataCons_maybe :: TyCon -> Maybe [DataCon]
996 tyConDataCons_maybe (AlgTyCon {algTcRhs = DataTyCon { data_cons = cons }}) = Just cons
997 tyConDataCons_maybe (AlgTyCon {algTcRhs = NewTyCon { data_con = con }}) = Just [con]
998 tyConDataCons_maybe (TupleTyCon {dataCon = con}) = Just [con]
999 tyConDataCons_maybe _ = Nothing
1001 -- | Determine the number of value constructors a 'TyCon' has. Panics if the 'TyCon'
1002 -- is not algebraic or a tuple
1003 tyConFamilySize :: TyCon -> Int
1004 tyConFamilySize (AlgTyCon {algTcRhs = DataTyCon {data_cons = cons}}) =
1006 tyConFamilySize (AlgTyCon {algTcRhs = NewTyCon {}}) = 1
1007 tyConFamilySize (AlgTyCon {algTcRhs = OpenTyCon {}}) = 0
1008 tyConFamilySize (TupleTyCon {}) = 1
1009 tyConFamilySize other = pprPanic "tyConFamilySize:" (ppr other)
1011 -- | Extract an 'AlgTyConRhs' with information about data constructors from an algebraic or tuple
1012 -- 'TyCon'. Panics for any other sort of 'TyCon'
1013 algTyConRhs :: TyCon -> AlgTyConRhs
1014 algTyConRhs (AlgTyCon {algTcRhs = rhs}) = rhs
1015 algTyConRhs (TupleTyCon {dataCon = con}) = DataTyCon { data_cons = [con], is_enum = False }
1016 algTyConRhs other = pprPanic "algTyConRhs" (ppr other)
1020 -- | Extract the bound type variables and type expansion of a type synonym 'TyCon'. Panics if the
1021 -- 'TyCon' is not a synonym
1022 newTyConRhs :: TyCon -> ([TyVar], Type)
1023 newTyConRhs (AlgTyCon {tyConTyVars = tvs, algTcRhs = NewTyCon { nt_rhs = rhs }}) = (tvs, rhs)
1024 newTyConRhs tycon = pprPanic "newTyConRhs" (ppr tycon)
1026 -- | Extract the bound type variables and type expansion of an eta-contracted type synonym 'TyCon'.
1027 -- Panics if the 'TyCon' is not a synonym
1028 newTyConEtadRhs :: TyCon -> ([TyVar], Type)
1029 newTyConEtadRhs (AlgTyCon {algTcRhs = NewTyCon { nt_etad_rhs = tvs_rhs }}) = tvs_rhs
1030 newTyConEtadRhs tycon = pprPanic "newTyConEtadRhs" (ppr tycon)
1032 -- | Extracts the @newtype@ coercion from such a 'TyCon', which can be used to construct something
1033 -- with the @newtype@s type from its representation type (right hand side). If the supplied 'TyCon'
1034 -- is not a @newtype@, returns @Nothing@
1035 newTyConCo_maybe :: TyCon -> Maybe TyCon
1036 newTyConCo_maybe (AlgTyCon {algTcRhs = NewTyCon { nt_co = co }}) = co
1037 newTyConCo_maybe _ = Nothing
1039 -- | Find the primitive representation of a 'TyCon'
1040 tyConPrimRep :: TyCon -> PrimRep
1041 tyConPrimRep (PrimTyCon {primTyConRep = rep}) = rep
1042 tyConPrimRep tc = ASSERT(not (isUnboxedTupleTyCon tc)) PtrRep
1046 -- | Find the \"stupid theta\" of the 'TyCon'. A \"stupid theta\" is the context to the left of
1047 -- an algebraic type declaration, e.g. @Eq a@ in the declaration @data Eq a => T a ...@
1048 tyConStupidTheta :: TyCon -> [PredType]
1049 tyConStupidTheta (AlgTyCon {algTcStupidTheta = stupid}) = stupid
1050 tyConStupidTheta (TupleTyCon {}) = []
1051 tyConStupidTheta tycon = pprPanic "tyConStupidTheta" (ppr tycon)
1055 -- | Extract the 'TyVar's bound by a type synonym and the corresponding (unsubstituted) right hand side.
1056 -- If the given 'TyCon' is not a type synonym, panics
1057 synTyConDefn :: TyCon -> ([TyVar], Type)
1058 synTyConDefn (SynTyCon {tyConTyVars = tyvars, synTcRhs = SynonymTyCon ty})
1060 synTyConDefn tycon = pprPanic "getSynTyConDefn" (ppr tycon)
1062 -- | Extract the information pertaining to the right hand side of a type synonym (@type@) declaration. Panics
1063 -- if the given 'TyCon' is not a type synonym
1064 synTyConRhs :: TyCon -> SynTyConRhs
1065 synTyConRhs (SynTyCon {synTcRhs = rhs}) = rhs
1066 synTyConRhs tc = pprPanic "synTyConRhs" (ppr tc)
1068 -- | Find the expansion of the type synonym represented by the given 'TyCon'. The free variables of this
1069 -- type will typically include those 'TyVar's bound by the 'TyCon'. Panics if the 'TyCon' is not that of
1071 synTyConType :: TyCon -> Type
1072 synTyConType tc = case synTcRhs tc of
1074 _ -> pprPanic "synTyConType" (ppr tc)
1076 -- | Find the 'Kind' of an open type synonym. Panics if the 'TyCon' is not an open type synonym
1077 synTyConResKind :: TyCon -> Kind
1078 synTyConResKind (SynTyCon {synTcRhs = OpenSynTyCon kind _}) = kind
1079 synTyConResKind tycon = pprPanic "synTyConResKind" (ppr tycon)
1083 -- | If the given 'TyCon' has a /single/ data constructor, i.e. it is a @data@ type with one
1084 -- alternative, a tuple type or a @newtype@ then that constructor is returned. If the 'TyCon'
1085 -- has more than one constructor, or represents a primitive or function type constructor then
1086 -- @Nothing@ is returned. In any other case, the function panics
1087 tyConSingleDataCon_maybe :: TyCon -> Maybe DataCon
1088 tyConSingleDataCon_maybe (AlgTyCon {algTcRhs = DataTyCon {data_cons = [c] }}) = Just c
1089 tyConSingleDataCon_maybe (AlgTyCon {algTcRhs = NewTyCon { data_con = c }}) = Just c
1090 tyConSingleDataCon_maybe (AlgTyCon {}) = Nothing
1091 tyConSingleDataCon_maybe (TupleTyCon {dataCon = con}) = Just con
1092 tyConSingleDataCon_maybe (PrimTyCon {}) = Nothing
1093 tyConSingleDataCon_maybe (FunTyCon {}) = Nothing -- case at funty
1094 tyConSingleDataCon_maybe tc = pprPanic "tyConSingleDataCon_maybe: unexpected tycon " $ ppr tc
1098 -- | Is this 'TyCon' that for a class instance?
1099 isClassTyCon :: TyCon -> Bool
1100 isClassTyCon (AlgTyCon {algTcParent = ClassTyCon _}) = True
1101 isClassTyCon _ = False
1103 -- | If this 'TyCon' is that for a class instance, return the class it is for.
1104 -- Otherwise returns @Nothing@
1105 tyConClass_maybe :: TyCon -> Maybe Class
1106 tyConClass_maybe (AlgTyCon {algTcParent = ClassTyCon clas}) = Just clas
1107 tyConClass_maybe _ = Nothing
1109 -- | Is this 'TyCon' that for a family instance, be that for a synonym or an
1110 -- algebraic family instance?
1111 isFamInstTyCon :: TyCon -> Bool
1112 isFamInstTyCon (AlgTyCon {algTcParent = FamilyTyCon _ _ _ }) = True
1113 isFamInstTyCon (SynTyCon {synTcParent = FamilyTyCon _ _ _ }) = True
1114 isFamInstTyCon _ = False
1116 -- | If this 'TyCon' is that of a family instance, return the family in question
1117 -- and the instance types. Otherwise, return @Nothing@
1118 tyConFamInst_maybe :: TyCon -> Maybe (TyCon, [Type])
1119 tyConFamInst_maybe (AlgTyCon {algTcParent = FamilyTyCon fam instTys _}) =
1121 tyConFamInst_maybe (SynTyCon {synTcParent = FamilyTyCon fam instTys _}) =
1123 tyConFamInst_maybe _ =
1126 -- | If this 'TyCon' is that of a family instance, return a 'TyCon' which represents
1127 -- a coercion identifying the representation type with the type instance family.
1128 -- Otherwise, return @Nothing@
1129 tyConFamilyCoercion_maybe :: TyCon -> Maybe TyCon
1130 tyConFamilyCoercion_maybe (AlgTyCon {algTcParent = FamilyTyCon _ _ coe}) =
1132 tyConFamilyCoercion_maybe (SynTyCon {synTcParent = FamilyTyCon _ _ coe}) =
1134 tyConFamilyCoercion_maybe _ =
1139 %************************************************************************
1141 \subsection[TyCon-instances]{Instance declarations for @TyCon@}
1143 %************************************************************************
1145 @TyCon@s are compared by comparing their @Unique@s.
1147 The strictness analyser needs @Ord@. It is a lexicographic order with
1148 the property @(a<=b) || (b<=a)@.
1151 instance Eq TyCon where
1152 a == b = case (a `compare` b) of { EQ -> True; _ -> False }
1153 a /= b = case (a `compare` b) of { EQ -> False; _ -> True }
1155 instance Ord TyCon where
1156 a <= b = case (a `compare` b) of { LT -> True; EQ -> True; GT -> False }
1157 a < b = case (a `compare` b) of { LT -> True; EQ -> False; GT -> False }
1158 a >= b = case (a `compare` b) of { LT -> False; EQ -> True; GT -> True }
1159 a > b = case (a `compare` b) of { LT -> False; EQ -> False; GT -> True }
1160 compare a b = getUnique a `compare` getUnique b
1162 instance Uniquable TyCon where
1163 getUnique tc = tyConUnique tc
1165 instance Outputable TyCon where
1166 ppr tc = ppr (getName tc)
1168 instance NamedThing TyCon where