2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1998
6 Type - public interface
9 {-# OPTIONS -fno-warn-incomplete-patterns #-}
10 -- The above warning supression flag is a temporary kludge.
11 -- While working on this module you are encouraged to remove it and fix
12 -- any warnings in the module. See
13 -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
16 -- | Main functions for manipulating types and type-related things
18 -- Note some of this is just re-exports from TyCon..
20 -- * Main data types representing Types
21 -- $type_classification
23 -- $representation_types
24 TyThing(..), Type, PredType(..), ThetaType,
26 -- ** Constructing and deconstructing types
27 mkTyVarTy, mkTyVarTys, getTyVar, getTyVar_maybe,
29 mkAppTy, mkAppTys, splitAppTy, splitAppTys,
30 splitAppTy_maybe, repSplitAppTy_maybe,
32 mkFunTy, mkFunTys, splitFunTy, splitFunTy_maybe,
33 splitFunTys, splitFunTysN,
34 funResultTy, funArgTy, zipFunTys,
36 mkTyConApp, mkTyConTy,
37 tyConAppTyCon, tyConAppArgs,
38 splitTyConApp_maybe, splitTyConApp,
40 mkForAllTy, mkForAllTys, splitForAllTy_maybe, splitForAllTys,
41 applyTy, applyTys, applyTysD, isForAllTy, dropForAlls,
44 newTyConInstRhs, carefullySplitNewType_maybe,
47 tyFamInsts, predFamInsts,
50 mkPredTy, mkPredTys, mkFamilyTyConApp,
52 -- ** Common type constructors
55 -- ** Predicates on types
58 -- (Lifting and boxity)
59 isUnLiftedType, isUnboxedTupleType, isAlgType, isClosedAlgType,
60 isPrimitiveType, isStrictType, isStrictPred,
62 -- * Main data types representing Kinds
64 Kind, SimpleKind, KindVar,
66 -- ** Deconstructing Kinds
67 kindFunResult, splitKindFunTys, splitKindFunTysN,
69 -- ** Common Kinds and SuperKinds
70 liftedTypeKind, unliftedTypeKind, openTypeKind,
71 argTypeKind, ubxTupleKind,
73 tySuperKind, coSuperKind,
75 -- ** Common Kind type constructors
76 liftedTypeKindTyCon, openTypeKindTyCon, unliftedTypeKindTyCon,
77 argTypeKindTyCon, ubxTupleKindTyCon,
79 -- ** Predicates on Kinds
80 isLiftedTypeKind, isUnliftedTypeKind, isOpenTypeKind,
81 isUbxTupleKind, isArgTypeKind, isKind, isTySuperKind,
82 isCoSuperKind, isSuperKind, isCoercionKind, isEqPred,
83 mkArrowKind, mkArrowKinds,
85 isSubArgTypeKind, isSubOpenTypeKind, isSubKind, defaultKind, eqKind,
88 -- * Type free variables
89 tyVarsOfType, tyVarsOfTypes, tyVarsOfPred, tyVarsOfTheta,
90 typeKind, expandTypeSynonyms,
92 -- * Tidying type related things up for printing
94 tidyOpenType, tidyOpenTypes,
95 tidyTyVarBndr, tidyFreeTyVars,
96 tidyOpenTyVar, tidyOpenTyVars,
97 tidyTopType, tidyPred,
101 coreEqType, tcEqType, tcEqTypes, tcCmpType, tcCmpTypes,
102 tcEqPred, tcEqPredX, tcCmpPred, tcEqTypeX, tcPartOfType, tcPartOfPred,
104 -- * Forcing evaluation of types
107 -- * Other views onto Types
108 coreView, tcView, kindView,
112 -- * Type representation for the code generator
115 typePrimRep, predTypeRep,
117 -- * Main type substitution data types
118 TvSubstEnv, -- Representation widely visible
119 TvSubst(..), -- Representation visible to a few friends
121 -- ** Manipulating type substitutions
122 emptyTvSubstEnv, emptyTvSubst,
124 mkTvSubst, mkOpenTvSubst, zipOpenTvSubst, zipTopTvSubst, mkTopTvSubst, notElemTvSubst,
125 getTvSubstEnv, setTvSubstEnv, getTvInScope, extendTvInScope,
126 extendTvSubst, extendTvSubstList, isInScope, composeTvSubst, zipTyEnv,
129 -- ** Performing substitution on types
130 substTy, substTys, substTyWith, substTysWith, substTheta,
131 substPred, substTyVar, substTyVars, substTyVarBndr, deShadowTy, lookupTyVar,
134 pprType, pprParendType, pprTypeApp, pprTyThingCategory, pprTyThing, pprForAll,
135 pprPred, pprTheta, pprThetaArrow, pprClassPred, pprKind, pprParendKind,
140 #include "HsVersions.h"
142 -- We import the representation and primitive functions from TypeRep.
143 -- Many things are reexported, but not the representation!
164 import Data.Maybe ( isJust )
168 -- $type_classification
169 -- #type_classification#
173 -- [Unboxed] Iff its representation is other than a pointer
174 -- Unboxed types are also unlifted.
176 -- [Lifted] Iff it has bottom as an element.
177 -- Closures always have lifted types: i.e. any
178 -- let-bound identifier in Core must have a lifted
179 -- type. Operationally, a lifted object is one that
181 -- Only lifted types may be unified with a type variable.
183 -- [Algebraic] Iff it is a type with one or more constructors, whether
184 -- declared with @data@ or @newtype@.
185 -- An algebraic type is one that can be deconstructed
186 -- with a case expression. This is /not/ the same as
187 -- lifted types, because we also include unboxed
188 -- tuples in this classification.
190 -- [Data] Iff it is a type declared with @data@, or a boxed tuple.
192 -- [Primitive] Iff it is a built-in type that can't be expressed in Haskell.
194 -- Currently, all primitive types are unlifted, but that's not necessarily
195 -- the case: for example, @Int@ could be primitive.
197 -- Some primitive types are unboxed, such as @Int#@, whereas some are boxed
198 -- but unlifted (such as @ByteArray#@). The only primitive types that we
199 -- classify as algebraic are the unboxed tuples.
201 -- Some examples of type classifications that may make this a bit clearer are:
204 -- Type primitive boxed lifted algebraic
205 -- -----------------------------------------------------------------------------
207 -- ByteArray# Yes Yes No No
208 -- (\# a, b \#) Yes No No Yes
209 -- ( a, b ) No Yes Yes Yes
210 -- [a] No Yes Yes Yes
213 -- $representation_types
214 -- A /source type/ is a type that is a separate type as far as the type checker is
215 -- concerned, but which has a more low-level representation as far as Core-to-Core
216 -- passes and the rest of the back end is concerned. Notably, 'PredTy's are removed
217 -- from the representation type while they do exist in the source types.
219 -- You don't normally have to worry about this, as the utility functions in
220 -- this module will automatically convert a source into a representation type
221 -- if they are spotted, to the best of it's abilities. If you don't want this
222 -- to happen, use the equivalent functions from the "TcType" module.
225 %************************************************************************
229 %************************************************************************
232 {-# INLINE coreView #-}
233 coreView :: Type -> Maybe Type
234 -- ^ In Core, we \"look through\" non-recursive newtypes and 'PredTypes': this
235 -- function tries to obtain a different view of the supplied type given this
237 -- Strips off the /top layer only/ of a type to give
238 -- its underlying representation type.
239 -- Returns Nothing if there is nothing to look through.
241 -- In the case of @newtype@s, it returns one of:
243 -- 1) A vanilla 'TyConApp' (recursive newtype, or non-saturated)
245 -- 2) The newtype representation (otherwise), meaning the
246 -- type written in the RHS of the newtype declaration,
247 -- which may itself be a newtype
249 -- For example, with:
251 -- > newtype R = MkR S
252 -- > newtype S = MkS T
253 -- > newtype T = MkT (T -> T)
255 -- 'expandNewTcApp' on:
257 -- * @R@ gives @Just S@
258 -- * @S@ gives @Just T@
259 -- * @T@ gives @Nothing@ (no expansion)
261 -- By being non-recursive and inlined, this case analysis gets efficiently
262 -- joined onto the case analysis that the caller is already doing
264 | isEqPred p = Nothing
265 | otherwise = Just (predTypeRep p)
266 coreView (TyConApp tc tys) | Just (tenv, rhs, tys') <- coreExpandTyCon_maybe tc tys
267 = Just (mkAppTys (substTy (mkTopTvSubst tenv) rhs) tys')
268 -- Its important to use mkAppTys, rather than (foldl AppTy),
269 -- because the function part might well return a
270 -- partially-applied type constructor; indeed, usually will!
275 -----------------------------------------------
276 {-# INLINE tcView #-}
277 tcView :: Type -> Maybe Type
278 -- ^ Similar to 'coreView', but for the type checker, which just looks through synonyms
279 tcView (TyConApp tc tys) | Just (tenv, rhs, tys') <- tcExpandTyCon_maybe tc tys
280 = Just (mkAppTys (substTy (mkTopTvSubst tenv) rhs) tys')
283 -----------------------------------------------
284 expandTypeSynonyms :: Type -> Type
285 -- ^ Expand out all type synonyms. Actually, it'd suffice to expand out
286 -- just the ones that discard type variables (e.g. type Funny a = Int)
287 -- But we don't know which those are currently, so we just expand all.
288 expandTypeSynonyms ty
292 | Just (tenv, rhs, tys') <- tcExpandTyCon_maybe tc tys
293 = go (mkAppTys (substTy (mkTopTvSubst tenv) rhs) tys')
295 = TyConApp tc (map go tys)
296 go (TyVarTy tv) = TyVarTy tv
297 go (AppTy t1 t2) = AppTy (go t1) (go t2)
298 go (FunTy t1 t2) = FunTy (go t1) (go t2)
299 go (ForAllTy tv t) = ForAllTy tv (go t)
300 go (PredTy p) = PredTy (go_pred p)
302 go_pred (ClassP c ts) = ClassP c (map go ts)
303 go_pred (IParam ip t) = IParam ip (go t)
304 go_pred (EqPred t1 t2) = EqPred (go t1) (go t2)
306 -----------------------------------------------
307 {-# INLINE kindView #-}
308 kindView :: Kind -> Maybe Kind
309 -- ^ Similar to 'coreView' or 'tcView', but works on 'Kind's
311 -- For the moment, we don't even handle synonyms in kinds
316 %************************************************************************
318 \subsection{Constructor-specific functions}
320 %************************************************************************
323 ---------------------------------------------------------------------
327 mkTyVarTy :: TyVar -> Type
330 mkTyVarTys :: [TyVar] -> [Type]
331 mkTyVarTys = map mkTyVarTy -- a common use of mkTyVarTy
333 -- | Attempts to obtain the type variable underlying a 'Type', and panics with the
334 -- given message if this is not a type variable type. See also 'getTyVar_maybe'
335 getTyVar :: String -> Type -> TyVar
336 getTyVar msg ty = case getTyVar_maybe ty of
338 Nothing -> panic ("getTyVar: " ++ msg)
340 isTyVarTy :: Type -> Bool
341 isTyVarTy ty = isJust (getTyVar_maybe ty)
343 -- | Attempts to obtain the type variable underlying a 'Type'
344 getTyVar_maybe :: Type -> Maybe TyVar
345 getTyVar_maybe ty | Just ty' <- coreView ty = getTyVar_maybe ty'
346 getTyVar_maybe (TyVarTy tv) = Just tv
347 getTyVar_maybe _ = Nothing
352 ---------------------------------------------------------------------
355 We need to be pretty careful with AppTy to make sure we obey the
356 invariant that a TyConApp is always visibly so. mkAppTy maintains the
360 -- | Applies a type to another, as in e.g. @k a@
361 mkAppTy :: Type -> Type -> Type
362 mkAppTy orig_ty1 orig_ty2
365 mk_app (TyConApp tc tys) = mkTyConApp tc (tys ++ [orig_ty2])
366 mk_app _ = AppTy orig_ty1 orig_ty2
367 -- Note that the TyConApp could be an
368 -- under-saturated type synonym. GHC allows that; e.g.
369 -- type Foo k = k a -> k a
371 -- foo :: Foo Id -> Foo Id
373 -- Here Id is partially applied in the type sig for Foo,
374 -- but once the type synonyms are expanded all is well
376 mkAppTys :: Type -> [Type] -> Type
377 mkAppTys orig_ty1 [] = orig_ty1
378 -- This check for an empty list of type arguments
379 -- avoids the needless loss of a type synonym constructor.
380 -- For example: mkAppTys Rational []
381 -- returns to (Ratio Integer), which has needlessly lost
382 -- the Rational part.
383 mkAppTys orig_ty1 orig_tys2
386 mk_app (TyConApp tc tys) = mkTyConApp tc (tys ++ orig_tys2)
387 -- mkTyConApp: see notes with mkAppTy
388 mk_app _ = foldl AppTy orig_ty1 orig_tys2
391 splitAppTy_maybe :: Type -> Maybe (Type, Type)
392 -- ^ Attempt to take a type application apart, whether it is a
393 -- function, type constructor, or plain type application. Note
394 -- that type family applications are NEVER unsaturated by this!
395 splitAppTy_maybe ty | Just ty' <- coreView ty
396 = splitAppTy_maybe ty'
397 splitAppTy_maybe ty = repSplitAppTy_maybe ty
400 repSplitAppTy_maybe :: Type -> Maybe (Type,Type)
401 -- ^ Does the AppTy split as in 'splitAppTy_maybe', but assumes that
402 -- any Core view stuff is already done
403 repSplitAppTy_maybe (FunTy ty1 ty2) = Just (TyConApp funTyCon [ty1], ty2)
404 repSplitAppTy_maybe (AppTy ty1 ty2) = Just (ty1, ty2)
405 repSplitAppTy_maybe (TyConApp tc tys)
406 | not (isOpenSynTyCon tc) || length tys > tyConArity tc
407 = case snocView tys of -- never create unsaturated type family apps
408 Just (tys', ty') -> Just (TyConApp tc tys', ty')
410 repSplitAppTy_maybe _other = Nothing
412 splitAppTy :: Type -> (Type, Type)
413 -- ^ Attempts to take a type application apart, as in 'splitAppTy_maybe',
414 -- and panics if this is not possible
415 splitAppTy ty = case splitAppTy_maybe ty of
417 Nothing -> panic "splitAppTy"
420 splitAppTys :: Type -> (Type, [Type])
421 -- ^ Recursively splits a type as far as is possible, leaving a residual
422 -- type being applied to and the type arguments applied to it. Never fails,
423 -- even if that means returning an empty list of type applications.
424 splitAppTys ty = split ty ty []
426 split orig_ty ty args | Just ty' <- coreView ty = split orig_ty ty' args
427 split _ (AppTy ty arg) args = split ty ty (arg:args)
428 split _ (TyConApp tc tc_args) args
429 = let -- keep type families saturated
430 n | isOpenSynTyCon tc = tyConArity tc
432 (tc_args1, tc_args2) = splitAt n tc_args
434 (TyConApp tc tc_args1, tc_args2 ++ args)
435 split _ (FunTy ty1 ty2) args = ASSERT( null args )
436 (TyConApp funTyCon [], [ty1,ty2])
437 split orig_ty _ args = (orig_ty, args)
442 ---------------------------------------------------------------------
447 mkFunTy :: Type -> Type -> Type
448 -- ^ Creates a function type from the given argument and result type
449 mkFunTy (PredTy (EqPred ty1 ty2)) res = mkForAllTy (mkWildCoVar (PredTy (EqPred ty1 ty2))) res
450 mkFunTy arg res = FunTy arg res
452 mkFunTys :: [Type] -> Type -> Type
453 mkFunTys tys ty = foldr mkFunTy ty tys
455 isFunTy :: Type -> Bool
456 isFunTy ty = isJust (splitFunTy_maybe ty)
458 splitFunTy :: Type -> (Type, Type)
459 -- ^ Attempts to extract the argument and result types from a type, and
460 -- panics if that is not possible. See also 'splitFunTy_maybe'
461 splitFunTy ty | Just ty' <- coreView ty = splitFunTy ty'
462 splitFunTy (FunTy arg res) = (arg, res)
463 splitFunTy other = pprPanic "splitFunTy" (ppr other)
465 splitFunTy_maybe :: Type -> Maybe (Type, Type)
466 -- ^ Attempts to extract the argument and result types from a type
467 splitFunTy_maybe ty | Just ty' <- coreView ty = splitFunTy_maybe ty'
468 splitFunTy_maybe (FunTy arg res) = Just (arg, res)
469 splitFunTy_maybe _ = Nothing
471 splitFunTys :: Type -> ([Type], Type)
472 splitFunTys ty = split [] ty ty
474 split args orig_ty ty | Just ty' <- coreView ty = split args orig_ty ty'
475 split args _ (FunTy arg res) = split (arg:args) res res
476 split args orig_ty _ = (reverse args, orig_ty)
478 splitFunTysN :: Int -> Type -> ([Type], Type)
479 -- ^ Split off exactly the given number argument types, and panics if that is not possible
480 splitFunTysN 0 ty = ([], ty)
481 splitFunTysN n ty = case splitFunTy ty of { (arg, res) ->
482 case splitFunTysN (n-1) res of { (args, res) ->
485 -- | Splits off argument types from the given type and associating
486 -- them with the things in the input list from left to right. The
487 -- final result type is returned, along with the resulting pairs of
488 -- objects and types, albeit with the list of pairs in reverse order.
489 -- Panics if there are not enough argument types for the input list.
490 zipFunTys :: Outputable a => [a] -> Type -> ([(a, Type)], Type)
491 zipFunTys orig_xs orig_ty = split [] orig_xs orig_ty orig_ty
493 split acc [] nty _ = (reverse acc, nty)
495 | Just ty' <- coreView ty = split acc xs nty ty'
496 split acc (x:xs) _ (FunTy arg res) = split ((x,arg):acc) xs res res
497 split _ _ _ _ = pprPanic "zipFunTys" (ppr orig_xs <+> ppr orig_ty)
499 funResultTy :: Type -> Type
500 -- ^ Extract the function result type and panic if that is not possible
501 funResultTy ty | Just ty' <- coreView ty = funResultTy ty'
502 funResultTy (FunTy _arg res) = res
503 funResultTy ty = pprPanic "funResultTy" (ppr ty)
505 funArgTy :: Type -> Type
506 -- ^ Extract the function argument type and panic if that is not possible
507 funArgTy ty | Just ty' <- coreView ty = funArgTy ty'
508 funArgTy (FunTy arg _res) = arg
509 funArgTy ty = pprPanic "funArgTy" (ppr ty)
512 ---------------------------------------------------------------------
517 -- | A key function: builds a 'TyConApp' or 'FunTy' as apppropriate to its arguments.
518 -- Applies its arguments to the constructor from left to right
519 mkTyConApp :: TyCon -> [Type] -> Type
521 | isFunTyCon tycon, [ty1,ty2] <- tys
527 -- | Create the plain type constructor type which has been applied to no type arguments at all.
528 mkTyConTy :: TyCon -> Type
529 mkTyConTy tycon = mkTyConApp tycon []
531 -- splitTyConApp "looks through" synonyms, because they don't
532 -- mean a distinct type, but all other type-constructor applications
533 -- including functions are returned as Just ..
535 -- | The same as @fst . splitTyConApp@
536 tyConAppTyCon :: Type -> TyCon
537 tyConAppTyCon ty = fst (splitTyConApp ty)
539 -- | The same as @snd . splitTyConApp@
540 tyConAppArgs :: Type -> [Type]
541 tyConAppArgs ty = snd (splitTyConApp ty)
543 -- | Attempts to tease a type apart into a type constructor and the application
544 -- of a number of arguments to that constructor. Panics if that is not possible.
545 -- See also 'splitTyConApp_maybe'
546 splitTyConApp :: Type -> (TyCon, [Type])
547 splitTyConApp ty = case splitTyConApp_maybe ty of
549 Nothing -> pprPanic "splitTyConApp" (ppr ty)
551 -- | Attempts to tease a type apart into a type constructor and the application
552 -- of a number of arguments to that constructor
553 splitTyConApp_maybe :: Type -> Maybe (TyCon, [Type])
554 splitTyConApp_maybe ty | Just ty' <- coreView ty = splitTyConApp_maybe ty'
555 splitTyConApp_maybe (TyConApp tc tys) = Just (tc, tys)
556 splitTyConApp_maybe (FunTy arg res) = Just (funTyCon, [arg,res])
557 splitTyConApp_maybe _ = Nothing
559 newTyConInstRhs :: TyCon -> [Type] -> Type
560 -- ^ Unwrap one 'layer' of newtype on a type constructor and its arguments, using an
561 -- eta-reduced version of the @newtype@ if possible
562 newTyConInstRhs tycon tys
563 = ASSERT2( equalLength tvs tys1, ppr tycon $$ ppr tys $$ ppr tvs )
564 mkAppTys (substTyWith tvs tys1 ty) tys2
566 (tvs, ty) = newTyConEtadRhs tycon
567 (tys1, tys2) = splitAtList tvs tys
571 ---------------------------------------------------------------------
575 Notes on type synonyms
576 ~~~~~~~~~~~~~~~~~~~~~~
577 The various "split" functions (splitFunTy, splitRhoTy, splitForAllTy) try
578 to return type synonyms whereever possible. Thus
583 splitFunTys (a -> Foo a) = ([a], Foo a)
586 The reason is that we then get better (shorter) type signatures in
587 interfaces. Notably this plays a role in tcTySigs in TcBinds.lhs.
590 Note [Expanding newtypes]
591 ~~~~~~~~~~~~~~~~~~~~~~~~~
592 When expanding a type to expose a data-type constructor, we need to be
593 careful about newtypes, lest we fall into an infinite loop. Here are
596 newtype Id x = MkId x
597 newtype Fix f = MkFix (f (Fix f))
598 newtype T = MkT (T -> T)
601 --------------------------
603 Fix Maybe Maybe (Fix Maybe)
607 Notice that we can expand T, even though it's recursive.
608 And we can expand Id (Id Int), even though the Id shows up
609 twice at the outer level.
611 So, when expanding, we keep track of when we've seen a recursive
612 newtype at outermost level; and bale out if we see it again.
624 -- 4. All newtypes, including recursive ones, but not newtype families
626 -- It's useful in the back end of the compiler.
627 repType :: Type -> Type
628 -- Only applied to types of kind *; hence tycons are saturated
632 go :: [TyCon] -> Type -> Type
633 go rec_nts ty | Just ty' <- coreView ty -- Expand synonyms
636 go rec_nts (ForAllTy _ ty) -- Look through foralls
639 go rec_nts (TyConApp tc tys) -- Expand newtypes
640 | Just (rec_nts', ty') <- carefullySplitNewType_maybe rec_nts tc tys
646 carefullySplitNewType_maybe :: [TyCon] -> TyCon -> [Type] -> Maybe ([TyCon],Type)
647 -- Return the representation of a newtype, unless
648 -- we've seen it already: see Note [Expanding newtypes]
649 carefullySplitNewType_maybe rec_nts tc tys
651 , not (tc `elem` rec_nts) = Just (rec_nts', newTyConInstRhs tc tys)
652 | otherwise = Nothing
654 rec_nts' | isRecursiveTyCon tc = tc:rec_nts
655 | otherwise = rec_nts
658 -- ToDo: this could be moved to the code generator, using splitTyConApp instead
659 -- of inspecting the type directly.
661 -- | Discovers the primitive representation of a more abstract 'Type'
662 typePrimRep :: Type -> PrimRep
663 typePrimRep ty = case repType ty of
664 TyConApp tc _ -> tyConPrimRep tc
666 AppTy _ _ -> PtrRep -- See note below
668 _ -> pprPanic "typePrimRep" (ppr ty)
669 -- Types of the form 'f a' must be of kind *, not *#, so
670 -- we are guaranteed that they are represented by pointers.
671 -- The reason is that f must have kind *->*, not *->*#, because
672 -- (we claim) there is no way to constrain f's kind any other
677 ---------------------------------------------------------------------
682 mkForAllTy :: TyVar -> Type -> Type
686 -- | Wraps foralls over the type using the provided 'TyVar's from left to right
687 mkForAllTys :: [TyVar] -> Type -> Type
688 mkForAllTys tyvars ty = foldr ForAllTy ty tyvars
690 isForAllTy :: Type -> Bool
691 isForAllTy (ForAllTy _ _) = True
694 -- | Attempts to take a forall type apart, returning the bound type variable
695 -- and the remainder of the type
696 splitForAllTy_maybe :: Type -> Maybe (TyVar, Type)
697 splitForAllTy_maybe ty = splitFAT_m ty
699 splitFAT_m ty | Just ty' <- coreView ty = splitFAT_m ty'
700 splitFAT_m (ForAllTy tyvar ty) = Just(tyvar, ty)
701 splitFAT_m _ = Nothing
703 -- | Attempts to take a forall type apart, returning all the immediate such bound
704 -- type variables and the remainder of the type. Always suceeds, even if that means
705 -- returning an empty list of 'TyVar's
706 splitForAllTys :: Type -> ([TyVar], Type)
707 splitForAllTys ty = split ty ty []
709 split orig_ty ty tvs | Just ty' <- coreView ty = split orig_ty ty' tvs
710 split _ (ForAllTy tv ty) tvs = split ty ty (tv:tvs)
711 split orig_ty _ tvs = (reverse tvs, orig_ty)
713 -- | Equivalent to @snd . splitForAllTys@
714 dropForAlls :: Type -> Type
715 dropForAlls ty = snd (splitForAllTys ty)
718 -- (mkPiType now in CoreUtils)
724 -- | Instantiate a forall type with one or more type arguments.
725 -- Used when we have a polymorphic function applied to type args:
729 -- We use @applyTys type-of-f [t1,t2]@ to compute the type of the expression.
730 -- Panics if no application is possible.
731 applyTy :: Type -> Type -> Type
732 applyTy ty arg | Just ty' <- coreView ty = applyTy ty' arg
733 applyTy (ForAllTy tv ty) arg = substTyWith [tv] [arg] ty
734 applyTy _ _ = panic "applyTy"
736 applyTys :: Type -> [Type] -> Type
737 -- ^ This function is interesting because:
739 -- 1. The function may have more for-alls than there are args
741 -- 2. Less obviously, it may have fewer for-alls
743 -- For case 2. think of:
745 -- > applyTys (forall a.a) [forall b.b, Int]
747 -- This really can happen, via dressing up polymorphic types with newtype
748 -- clothing. Here's an example:
750 -- > newtype R = R (forall a. a->a)
751 -- > foo = case undefined :: R of
754 applyTys ty args = applyTysD empty ty args
756 applyTysD :: SDoc -> Type -> [Type] -> Type -- Debug version
757 applyTysD _ orig_fun_ty [] = orig_fun_ty
758 applyTysD doc orig_fun_ty arg_tys
759 | n_tvs == n_args -- The vastly common case
760 = substTyWith tvs arg_tys rho_ty
761 | n_tvs > n_args -- Too many for-alls
762 = substTyWith (take n_args tvs) arg_tys
763 (mkForAllTys (drop n_args tvs) rho_ty)
764 | otherwise -- Too many type args
765 = ASSERT2( n_tvs > 0, doc $$ ppr orig_fun_ty ) -- Zero case gives infnite loop!
766 applyTysD doc (substTyWith tvs (take n_tvs arg_tys) rho_ty)
769 (tvs, rho_ty) = splitForAllTys orig_fun_ty
771 n_args = length arg_tys
775 %************************************************************************
777 \subsection{Source types}
779 %************************************************************************
781 Source types are always lifted.
783 The key function is predTypeRep which gives the representation of a source type:
786 mkPredTy :: PredType -> Type
787 mkPredTy pred = PredTy pred
789 mkPredTys :: ThetaType -> [Type]
790 mkPredTys preds = map PredTy preds
792 predTypeRep :: PredType -> Type
793 -- ^ Convert a 'PredType' to its representation type. However, it unwraps
794 -- only the outermost level; for example, the result might be a newtype application
795 predTypeRep (IParam _ ty) = ty
796 predTypeRep (ClassP clas tys) = mkTyConApp (classTyCon clas) tys
797 -- Result might be a newtype application, but the consumer will
798 -- look through that too if necessary
799 predTypeRep (EqPred ty1 ty2) = pprPanic "predTypeRep" (ppr (EqPred ty1 ty2))
801 mkFamilyTyConApp :: TyCon -> [Type] -> Type
802 -- ^ Given a family instance TyCon and its arg types, return the
803 -- corresponding family type. E.g:
806 -- > data instance T (Maybe b) = MkT b
808 -- Where the instance tycon is :RTL, so:
810 -- > mkFamilyTyConApp :RTL Int = T (Maybe Int)
811 mkFamilyTyConApp tc tys
812 | Just (fam_tc, fam_tys) <- tyConFamInst_maybe tc
813 , let fam_subst = zipTopTvSubst (tyConTyVars tc) tys
814 = mkTyConApp fam_tc (substTys fam_subst fam_tys)
818 -- | Pretty prints a 'TyCon', using the family instance in case of a
819 -- representation tycon. For example:
821 -- > data T [a] = ...
823 -- In that case we want to print @T [a]@, where @T@ is the family 'TyCon'
824 pprSourceTyCon :: TyCon -> SDoc
826 | Just (fam_tc, tys) <- tyConFamInst_maybe tycon
827 = ppr $ fam_tc `TyConApp` tys -- can't be FunTyCon
833 %************************************************************************
835 \subsection{Kinds and free variables}
837 %************************************************************************
839 ---------------------------------------------------------------------
840 Finding the kind of a type
841 ~~~~~~~~~~~~~~~~~~~~~~~~~~
843 typeKind :: Type -> Kind
844 typeKind (TyConApp tycon tys) = ASSERT( not (isCoercionTyCon tycon) )
845 -- We should be looking for the coercion kind,
847 foldr (\_ k -> kindFunResult k) (tyConKind tycon) tys
848 typeKind (PredTy pred) = predKind pred
849 typeKind (AppTy fun _) = kindFunResult (typeKind fun)
850 typeKind (ForAllTy _ ty) = typeKind ty
851 typeKind (TyVarTy tyvar) = tyVarKind tyvar
852 typeKind (FunTy _arg res)
853 -- Hack alert. The kind of (Int -> Int#) is liftedTypeKind (*),
854 -- not unliftedTypKind (#)
855 -- The only things that can be after a function arrow are
856 -- (a) types (of kind openTypeKind or its sub-kinds)
857 -- (b) kinds (of super-kind TY) (e.g. * -> (* -> *))
858 | isTySuperKind k = k
859 | otherwise = ASSERT( isSubOpenTypeKind k) liftedTypeKind
863 predKind :: PredType -> Kind
864 predKind (EqPred {}) = coSuperKind -- A coercion kind!
865 predKind (ClassP {}) = liftedTypeKind -- Class and implicitPredicates are
866 predKind (IParam {}) = liftedTypeKind -- always represented by lifted types
870 ---------------------------------------------------------------------
871 Free variables of a type
872 ~~~~~~~~~~~~~~~~~~~~~~~~
874 tyVarsOfType :: Type -> TyVarSet
875 -- ^ NB: for type synonyms tyVarsOfType does /not/ expand the synonym
876 tyVarsOfType (TyVarTy tv) = unitVarSet tv
877 tyVarsOfType (TyConApp _ tys) = tyVarsOfTypes tys
878 tyVarsOfType (PredTy sty) = tyVarsOfPred sty
879 tyVarsOfType (FunTy arg res) = tyVarsOfType arg `unionVarSet` tyVarsOfType res
880 tyVarsOfType (AppTy fun arg) = tyVarsOfType fun `unionVarSet` tyVarsOfType arg
881 tyVarsOfType (ForAllTy tyvar ty) = delVarSet (tyVarsOfType ty) tyvar
883 tyVarsOfTypes :: [Type] -> TyVarSet
884 tyVarsOfTypes tys = foldr (unionVarSet.tyVarsOfType) emptyVarSet tys
886 tyVarsOfPred :: PredType -> TyVarSet
887 tyVarsOfPred (IParam _ ty) = tyVarsOfType ty
888 tyVarsOfPred (ClassP _ tys) = tyVarsOfTypes tys
889 tyVarsOfPred (EqPred ty1 ty2) = tyVarsOfType ty1 `unionVarSet` tyVarsOfType ty2
891 tyVarsOfTheta :: ThetaType -> TyVarSet
892 tyVarsOfTheta = foldr (unionVarSet . tyVarsOfPred) emptyVarSet
896 %************************************************************************
898 \subsection{Type families}
900 %************************************************************************
903 -- | Finds type family instances occuring in a type after expanding synonyms.
904 tyFamInsts :: Type -> [(TyCon, [Type])]
906 | Just exp_ty <- tcView ty = tyFamInsts exp_ty
907 tyFamInsts (TyVarTy _) = []
908 tyFamInsts (TyConApp tc tys)
909 | isOpenSynTyCon tc = [(tc, tys)]
910 | otherwise = concat (map tyFamInsts tys)
911 tyFamInsts (FunTy ty1 ty2) = tyFamInsts ty1 ++ tyFamInsts ty2
912 tyFamInsts (AppTy ty1 ty2) = tyFamInsts ty1 ++ tyFamInsts ty2
913 tyFamInsts (ForAllTy _ ty) = tyFamInsts ty
914 tyFamInsts (PredTy pty) = predFamInsts pty
916 -- | Finds type family instances occuring in a predicate type after expanding
918 predFamInsts :: PredType -> [(TyCon, [Type])]
919 predFamInsts (ClassP _cla tys) = concat (map tyFamInsts tys)
920 predFamInsts (IParam _ ty) = tyFamInsts ty
921 predFamInsts (EqPred ty1 ty2) = tyFamInsts ty1 ++ tyFamInsts ty2
925 %************************************************************************
927 \subsection{TidyType}
929 %************************************************************************
932 -- | This tidies up a type for printing in an error message, or in
933 -- an interface file.
935 -- It doesn't change the uniques at all, just the print names.
936 tidyTyVarBndr :: TidyEnv -> TyVar -> (TidyEnv, TyVar)
937 tidyTyVarBndr env@(tidy_env, subst) tyvar
938 = case tidyOccName tidy_env (getOccName name) of
939 (tidy', occ') -> ((tidy', subst'), tyvar'')
941 subst' = extendVarEnv subst tyvar tyvar''
942 tyvar' = setTyVarName tyvar name'
943 name' = tidyNameOcc name occ'
944 -- Don't forget to tidy the kind for coercions!
945 tyvar'' | isCoVar tyvar = setTyVarKind tyvar' kind'
947 kind' = tidyType env (tyVarKind tyvar)
949 name = tyVarName tyvar
951 tidyFreeTyVars :: TidyEnv -> TyVarSet -> TidyEnv
952 -- ^ Add the free 'TyVar's to the env in tidy form,
953 -- so that we can tidy the type they are free in
954 tidyFreeTyVars env tyvars = fst (tidyOpenTyVars env (varSetElems tyvars))
956 tidyOpenTyVars :: TidyEnv -> [TyVar] -> (TidyEnv, [TyVar])
957 tidyOpenTyVars env tyvars = mapAccumL tidyOpenTyVar env tyvars
959 tidyOpenTyVar :: TidyEnv -> TyVar -> (TidyEnv, TyVar)
960 -- ^ Treat a new 'TyVar' as a binder, and give it a fresh tidy name
961 -- using the environment if one has not already been allocated. See
962 -- also 'tidyTyVarBndr'
963 tidyOpenTyVar env@(_, subst) tyvar
964 = case lookupVarEnv subst tyvar of
965 Just tyvar' -> (env, tyvar') -- Already substituted
966 Nothing -> tidyTyVarBndr env tyvar -- Treat it as a binder
968 tidyType :: TidyEnv -> Type -> Type
969 tidyType env@(_, subst) ty
972 go (TyVarTy tv) = case lookupVarEnv subst tv of
973 Nothing -> TyVarTy tv
974 Just tv' -> TyVarTy tv'
975 go (TyConApp tycon tys) = let args = map go tys
976 in args `seqList` TyConApp tycon args
977 go (PredTy sty) = PredTy (tidyPred env sty)
978 go (AppTy fun arg) = (AppTy $! (go fun)) $! (go arg)
979 go (FunTy fun arg) = (FunTy $! (go fun)) $! (go arg)
980 go (ForAllTy tv ty) = ForAllTy tvp $! (tidyType envp ty)
982 (envp, tvp) = tidyTyVarBndr env tv
984 tidyTypes :: TidyEnv -> [Type] -> [Type]
985 tidyTypes env tys = map (tidyType env) tys
987 tidyPred :: TidyEnv -> PredType -> PredType
988 tidyPred env (IParam n ty) = IParam n (tidyType env ty)
989 tidyPred env (ClassP clas tys) = ClassP clas (tidyTypes env tys)
990 tidyPred env (EqPred ty1 ty2) = EqPred (tidyType env ty1) (tidyType env ty2)
995 -- | Grabs the free type variables, tidies them
996 -- and then uses 'tidyType' to work over the type itself
997 tidyOpenType :: TidyEnv -> Type -> (TidyEnv, Type)
999 = (env', tidyType env' ty)
1001 env' = tidyFreeTyVars env (tyVarsOfType ty)
1003 tidyOpenTypes :: TidyEnv -> [Type] -> (TidyEnv, [Type])
1004 tidyOpenTypes env tys = mapAccumL tidyOpenType env tys
1006 -- | Calls 'tidyType' on a top-level type (i.e. with an empty tidying environment)
1007 tidyTopType :: Type -> Type
1008 tidyTopType ty = tidyType emptyTidyEnv ty
1013 tidyKind :: TidyEnv -> Kind -> (TidyEnv, Kind)
1014 tidyKind env k = tidyOpenType env k
1019 %************************************************************************
1021 \subsection{Liftedness}
1023 %************************************************************************
1026 -- | See "Type#type_classification" for what an unlifted type is
1027 isUnLiftedType :: Type -> Bool
1028 -- isUnLiftedType returns True for forall'd unlifted types:
1029 -- x :: forall a. Int#
1030 -- I found bindings like these were getting floated to the top level.
1031 -- They are pretty bogus types, mind you. It would be better never to
1034 isUnLiftedType ty | Just ty' <- coreView ty = isUnLiftedType ty'
1035 isUnLiftedType (ForAllTy _ ty) = isUnLiftedType ty
1036 isUnLiftedType (TyConApp tc _) = isUnLiftedTyCon tc
1037 isUnLiftedType _ = False
1039 isUnboxedTupleType :: Type -> Bool
1040 isUnboxedTupleType ty = case splitTyConApp_maybe ty of
1041 Just (tc, _ty_args) -> isUnboxedTupleTyCon tc
1044 -- | See "Type#type_classification" for what an algebraic type is.
1045 -- Should only be applied to /types/, as opposed to e.g. partially
1046 -- saturated type constructors
1047 isAlgType :: Type -> Bool
1049 = case splitTyConApp_maybe ty of
1050 Just (tc, ty_args) -> ASSERT( ty_args `lengthIs` tyConArity tc )
1054 -- | See "Type#type_classification" for what an algebraic type is.
1055 -- Should only be applied to /types/, as opposed to e.g. partially
1056 -- saturated type constructors. Closed type constructors are those
1057 -- with a fixed right hand side, as opposed to e.g. associated types
1058 isClosedAlgType :: Type -> Bool
1060 = case splitTyConApp_maybe ty of
1061 Just (tc, ty_args) -> ASSERT( ty_args `lengthIs` tyConArity tc )
1062 isAlgTyCon tc && not (isOpenTyCon tc)
1067 -- | Computes whether an argument (or let right hand side) should
1068 -- be computed strictly or lazily, based only on its type.
1069 -- Works just like 'isUnLiftedType', except that it has a special case
1070 -- for dictionaries (i.e. does not work purely on representation types)
1072 -- Since it takes account of class 'PredType's, you might think
1073 -- this function should be in 'TcType', but 'isStrictType' is used by 'DataCon',
1074 -- which is below 'TcType' in the hierarchy, so it's convenient to put it here.
1075 isStrictType :: Type -> Bool
1076 isStrictType (PredTy pred) = isStrictPred pred
1077 isStrictType ty | Just ty' <- coreView ty = isStrictType ty'
1078 isStrictType (ForAllTy _ ty) = isStrictType ty
1079 isStrictType (TyConApp tc _) = isUnLiftedTyCon tc
1080 isStrictType _ = False
1082 -- | We may be strict in dictionary types, but only if it
1083 -- has more than one component.
1085 -- (Being strict in a single-component dictionary risks
1086 -- poking the dictionary component, which is wrong.)
1087 isStrictPred :: PredType -> Bool
1088 isStrictPred (ClassP clas _) = opt_DictsStrict && not (isNewTyCon (classTyCon clas))
1089 isStrictPred _ = False
1093 isPrimitiveType :: Type -> Bool
1094 -- ^ Returns true of types that are opaque to Haskell.
1095 -- Most of these are unlifted, but now that we interact with .NET, we
1096 -- may have primtive (foreign-imported) types that are lifted
1097 isPrimitiveType ty = case splitTyConApp_maybe ty of
1098 Just (tc, ty_args) -> ASSERT( ty_args `lengthIs` tyConArity tc )
1104 %************************************************************************
1106 \subsection{Sequencing on types}
1108 %************************************************************************
1111 seqType :: Type -> ()
1112 seqType (TyVarTy tv) = tv `seq` ()
1113 seqType (AppTy t1 t2) = seqType t1 `seq` seqType t2
1114 seqType (FunTy t1 t2) = seqType t1 `seq` seqType t2
1115 seqType (PredTy p) = seqPred p
1116 seqType (TyConApp tc tys) = tc `seq` seqTypes tys
1117 seqType (ForAllTy tv ty) = tv `seq` seqType ty
1119 seqTypes :: [Type] -> ()
1121 seqTypes (ty:tys) = seqType ty `seq` seqTypes tys
1123 seqPred :: PredType -> ()
1124 seqPred (ClassP c tys) = c `seq` seqTypes tys
1125 seqPred (IParam n ty) = n `seq` seqType ty
1126 seqPred (EqPred ty1 ty2) = seqType ty1 `seq` seqType ty2
1130 %************************************************************************
1132 Equality for Core types
1133 (We don't use instances so that we know where it happens)
1135 %************************************************************************
1137 Note that eqType works right even for partial applications of newtypes.
1138 See Note [Newtype eta] in TyCon.lhs
1141 -- | Type equality test for Core types (i.e. ignores predicate-types, synonyms etc.)
1142 coreEqType :: Type -> Type -> Bool
1146 rn_env = mkRnEnv2 (mkInScopeSet (tyVarsOfType t1 `unionVarSet` tyVarsOfType t2))
1148 eq env (TyVarTy tv1) (TyVarTy tv2) = rnOccL env tv1 == rnOccR env tv2
1149 eq env (ForAllTy tv1 t1) (ForAllTy tv2 t2) = eq (rnBndr2 env tv1 tv2) t1 t2
1150 eq env (AppTy s1 t1) (AppTy s2 t2) = eq env s1 s2 && eq env t1 t2
1151 eq env (FunTy s1 t1) (FunTy s2 t2) = eq env s1 s2 && eq env t1 t2
1152 eq env (TyConApp tc1 tys1) (TyConApp tc2 tys2)
1153 | tc1 == tc2, all2 (eq env) tys1 tys2 = True
1154 -- The lengths should be equal because
1155 -- the two types have the same kind
1156 -- NB: if the type constructors differ that does not
1157 -- necessarily mean that the types aren't equal
1158 -- (synonyms, newtypes)
1159 -- Even if the type constructors are the same, but the arguments
1160 -- differ, the two types could be the same (e.g. if the arg is just
1161 -- ignored in the RHS). In both these cases we fall through to an
1162 -- attempt to expand one side or the other.
1164 -- Now deal with newtypes, synonyms, pred-tys
1165 eq env t1 t2 | Just t1' <- coreView t1 = eq env t1' t2
1166 | Just t2' <- coreView t2 = eq env t1 t2'
1168 -- Fall through case; not equal!
1173 %************************************************************************
1175 Comparision for source types
1176 (We don't use instances so that we know where it happens)
1178 %************************************************************************
1181 tcEqType :: Type -> Type -> Bool
1182 -- ^ Type equality on source types. Does not look through @newtypes@ or
1183 -- 'PredType's, but it does look through type synonyms.
1184 tcEqType t1 t2 = isEqual $ cmpType t1 t2
1186 tcEqTypes :: [Type] -> [Type] -> Bool
1187 tcEqTypes tys1 tys2 = isEqual $ cmpTypes tys1 tys2
1189 tcCmpType :: Type -> Type -> Ordering
1190 -- ^ Type ordering on source types. Does not look through @newtypes@ or
1191 -- 'PredType's, but it does look through type synonyms.
1192 tcCmpType t1 t2 = cmpType t1 t2
1194 tcCmpTypes :: [Type] -> [Type] -> Ordering
1195 tcCmpTypes tys1 tys2 = cmpTypes tys1 tys2
1197 tcEqPred :: PredType -> PredType -> Bool
1198 tcEqPred p1 p2 = isEqual $ cmpPred p1 p2
1200 tcEqPredX :: RnEnv2 -> PredType -> PredType -> Bool
1201 tcEqPredX env p1 p2 = isEqual $ cmpPredX env p1 p2
1203 tcCmpPred :: PredType -> PredType -> Ordering
1204 tcCmpPred p1 p2 = cmpPred p1 p2
1206 tcEqTypeX :: RnEnv2 -> Type -> Type -> Bool
1207 tcEqTypeX env t1 t2 = isEqual $ cmpTypeX env t1 t2
1211 -- | Checks whether the second argument is a subterm of the first. (We don't care
1212 -- about binders, as we are only interested in syntactic subterms.)
1213 tcPartOfType :: Type -> Type -> Bool
1215 | tcEqType t1 t2 = True
1217 | Just t2' <- tcView t2 = tcPartOfType t1 t2'
1218 tcPartOfType _ (TyVarTy _) = False
1219 tcPartOfType t1 (ForAllTy _ t2) = tcPartOfType t1 t2
1220 tcPartOfType t1 (AppTy s2 t2) = tcPartOfType t1 s2 || tcPartOfType t1 t2
1221 tcPartOfType t1 (FunTy s2 t2) = tcPartOfType t1 s2 || tcPartOfType t1 t2
1222 tcPartOfType t1 (PredTy p2) = tcPartOfPred t1 p2
1223 tcPartOfType t1 (TyConApp _ ts) = any (tcPartOfType t1) ts
1225 tcPartOfPred :: Type -> PredType -> Bool
1226 tcPartOfPred t1 (IParam _ t2) = tcPartOfType t1 t2
1227 tcPartOfPred t1 (ClassP _ ts) = any (tcPartOfType t1) ts
1228 tcPartOfPred t1 (EqPred s2 t2) = tcPartOfType t1 s2 || tcPartOfType t1 t2
1231 Now here comes the real worker
1234 cmpType :: Type -> Type -> Ordering
1235 cmpType t1 t2 = cmpTypeX rn_env t1 t2
1237 rn_env = mkRnEnv2 (mkInScopeSet (tyVarsOfType t1 `unionVarSet` tyVarsOfType t2))
1239 cmpTypes :: [Type] -> [Type] -> Ordering
1240 cmpTypes ts1 ts2 = cmpTypesX rn_env ts1 ts2
1242 rn_env = mkRnEnv2 (mkInScopeSet (tyVarsOfTypes ts1 `unionVarSet` tyVarsOfTypes ts2))
1244 cmpPred :: PredType -> PredType -> Ordering
1245 cmpPred p1 p2 = cmpPredX rn_env p1 p2
1247 rn_env = mkRnEnv2 (mkInScopeSet (tyVarsOfPred p1 `unionVarSet` tyVarsOfPred p2))
1249 cmpTypeX :: RnEnv2 -> Type -> Type -> Ordering -- Main workhorse
1250 cmpTypeX env t1 t2 | Just t1' <- tcView t1 = cmpTypeX env t1' t2
1251 | Just t2' <- tcView t2 = cmpTypeX env t1 t2'
1253 cmpTypeX env (TyVarTy tv1) (TyVarTy tv2) = rnOccL env tv1 `compare` rnOccR env tv2
1254 cmpTypeX env (ForAllTy tv1 t1) (ForAllTy tv2 t2) = cmpTypeX (rnBndr2 env tv1 tv2) t1 t2
1255 cmpTypeX env (AppTy s1 t1) (AppTy s2 t2) = cmpTypeX env s1 s2 `thenCmp` cmpTypeX env t1 t2
1256 cmpTypeX env (FunTy s1 t1) (FunTy s2 t2) = cmpTypeX env s1 s2 `thenCmp` cmpTypeX env t1 t2
1257 cmpTypeX env (PredTy p1) (PredTy p2) = cmpPredX env p1 p2
1258 cmpTypeX env (TyConApp tc1 tys1) (TyConApp tc2 tys2) = (tc1 `compare` tc2) `thenCmp` cmpTypesX env tys1 tys2
1260 -- Deal with the rest: TyVarTy < AppTy < FunTy < TyConApp < ForAllTy < PredTy
1261 cmpTypeX _ (AppTy _ _) (TyVarTy _) = GT
1263 cmpTypeX _ (FunTy _ _) (TyVarTy _) = GT
1264 cmpTypeX _ (FunTy _ _) (AppTy _ _) = GT
1266 cmpTypeX _ (TyConApp _ _) (TyVarTy _) = GT
1267 cmpTypeX _ (TyConApp _ _) (AppTy _ _) = GT
1268 cmpTypeX _ (TyConApp _ _) (FunTy _ _) = GT
1270 cmpTypeX _ (ForAllTy _ _) (TyVarTy _) = GT
1271 cmpTypeX _ (ForAllTy _ _) (AppTy _ _) = GT
1272 cmpTypeX _ (ForAllTy _ _) (FunTy _ _) = GT
1273 cmpTypeX _ (ForAllTy _ _) (TyConApp _ _) = GT
1275 cmpTypeX _ (PredTy _) _ = GT
1280 cmpTypesX :: RnEnv2 -> [Type] -> [Type] -> Ordering
1281 cmpTypesX _ [] [] = EQ
1282 cmpTypesX env (t1:tys1) (t2:tys2) = cmpTypeX env t1 t2 `thenCmp` cmpTypesX env tys1 tys2
1283 cmpTypesX _ [] _ = LT
1284 cmpTypesX _ _ [] = GT
1287 cmpPredX :: RnEnv2 -> PredType -> PredType -> Ordering
1288 cmpPredX env (IParam n1 ty1) (IParam n2 ty2) = (n1 `compare` n2) `thenCmp` cmpTypeX env ty1 ty2
1289 -- Compare names only for implicit parameters
1290 -- This comparison is used exclusively (I believe)
1291 -- for the Avails finite map built in TcSimplify
1292 -- If the types differ we keep them distinct so that we see
1293 -- a distinct pair to run improvement on
1294 cmpPredX env (ClassP c1 tys1) (ClassP c2 tys2) = (c1 `compare` c2) `thenCmp` (cmpTypesX env tys1 tys2)
1295 cmpPredX env (EqPred ty1 ty2) (EqPred ty1' ty2') = (cmpTypeX env ty1 ty1') `thenCmp` (cmpTypeX env ty2 ty2')
1297 -- Constructor order: IParam < ClassP < EqPred
1298 cmpPredX _ (IParam {}) _ = LT
1299 cmpPredX _ (ClassP {}) (IParam {}) = GT
1300 cmpPredX _ (ClassP {}) (EqPred {}) = LT
1301 cmpPredX _ (EqPred {}) _ = GT
1304 PredTypes are used as a FM key in TcSimplify,
1305 so we take the easy path and make them an instance of Ord
1308 instance Eq PredType where { (==) = tcEqPred }
1309 instance Ord PredType where { compare = tcCmpPred }
1313 %************************************************************************
1317 %************************************************************************
1320 -- | Type substitution
1322 -- #tvsubst_invariant#
1323 -- The following invariants must hold of a 'TvSubst':
1325 -- 1. The in-scope set is needed /only/ to
1326 -- guide the generation of fresh uniques
1328 -- 2. In particular, the /kind/ of the type variables in
1329 -- the in-scope set is not relevant
1331 -- 3. The substition is only applied ONCE! This is because
1332 -- in general such application will not reached a fixed point.
1334 = TvSubst InScopeSet -- The in-scope type variables
1335 TvSubstEnv -- The substitution itself
1336 -- See Note [Apply Once]
1337 -- and Note [Extending the TvSubstEnv]
1339 {- ----------------------------------------------------------
1343 We use TvSubsts to instantiate things, and we might instantiate
1347 So the substition might go [a->b, b->a]. A similar situation arises in Core
1348 when we find a beta redex like
1349 (/\ a /\ b -> e) b a
1350 Then we also end up with a substition that permutes type variables. Other
1351 variations happen to; for example [a -> (a, b)].
1353 ***************************************************
1354 *** So a TvSubst must be applied precisely once ***
1355 ***************************************************
1357 A TvSubst is not idempotent, but, unlike the non-idempotent substitution
1358 we use during unifications, it must not be repeatedly applied.
1360 Note [Extending the TvSubst]
1361 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1362 See #tvsubst_invariant# for the invariants that must hold.
1364 This invariant allows a short-cut when the TvSubstEnv is empty:
1365 if the TvSubstEnv is empty --- i.e. (isEmptyTvSubt subst) holds ---
1366 then (substTy subst ty) does nothing.
1368 For example, consider:
1369 (/\a. /\b:(a~Int). ...b..) Int
1370 We substitute Int for 'a'. The Unique of 'b' does not change, but
1371 nevertheless we add 'b' to the TvSubstEnv, because b's type does change
1373 This invariant has several crucial consequences:
1375 * In substTyVarBndr, we need extend the TvSubstEnv
1376 - if the unique has changed
1377 - or if the kind has changed
1379 * In substTyVar, we do not need to consult the in-scope set;
1380 the TvSubstEnv is enough
1382 * In substTy, substTheta, we can short-circuit when the TvSubstEnv is empty
1385 -------------------------------------------------------------- -}
1387 -- | A substitition of 'Type's for 'TyVar's
1388 type TvSubstEnv = TyVarEnv Type
1389 -- A TvSubstEnv is used both inside a TvSubst (with the apply-once
1390 -- invariant discussed in Note [Apply Once]), and also independently
1391 -- in the middle of matching, and unification (see Types.Unify)
1392 -- So you have to look at the context to know if it's idempotent or
1393 -- apply-once or whatever
1395 emptyTvSubstEnv :: TvSubstEnv
1396 emptyTvSubstEnv = emptyVarEnv
1398 composeTvSubst :: InScopeSet -> TvSubstEnv -> TvSubstEnv -> TvSubstEnv
1399 -- ^ @(compose env1 env2)(x)@ is @env1(env2(x))@; i.e. apply @env2@ then @env1@.
1400 -- It assumes that both are idempotent.
1401 -- Typically, @env1@ is the refinement to a base substitution @env2@
1402 composeTvSubst in_scope env1 env2
1403 = env1 `plusVarEnv` mapVarEnv (substTy subst1) env2
1404 -- First apply env1 to the range of env2
1405 -- Then combine the two, making sure that env1 loses if
1406 -- both bind the same variable; that's why env1 is the
1407 -- *left* argument to plusVarEnv, because the right arg wins
1409 subst1 = TvSubst in_scope env1
1411 emptyTvSubst :: TvSubst
1412 emptyTvSubst = TvSubst emptyInScopeSet emptyVarEnv
1414 isEmptyTvSubst :: TvSubst -> Bool
1415 -- See Note [Extending the TvSubstEnv]
1416 isEmptyTvSubst (TvSubst _ env) = isEmptyVarEnv env
1418 mkTvSubst :: InScopeSet -> TvSubstEnv -> TvSubst
1421 getTvSubstEnv :: TvSubst -> TvSubstEnv
1422 getTvSubstEnv (TvSubst _ env) = env
1424 getTvInScope :: TvSubst -> InScopeSet
1425 getTvInScope (TvSubst in_scope _) = in_scope
1427 isInScope :: Var -> TvSubst -> Bool
1428 isInScope v (TvSubst in_scope _) = v `elemInScopeSet` in_scope
1430 notElemTvSubst :: TyVar -> TvSubst -> Bool
1431 notElemTvSubst tv (TvSubst _ env) = not (tv `elemVarEnv` env)
1433 setTvSubstEnv :: TvSubst -> TvSubstEnv -> TvSubst
1434 setTvSubstEnv (TvSubst in_scope _) env = TvSubst in_scope env
1436 extendTvInScope :: TvSubst -> [Var] -> TvSubst
1437 extendTvInScope (TvSubst in_scope env) vars = TvSubst (extendInScopeSetList in_scope vars) env
1439 extendTvSubst :: TvSubst -> TyVar -> Type -> TvSubst
1440 extendTvSubst (TvSubst in_scope env) tv ty = TvSubst in_scope (extendVarEnv env tv ty)
1442 extendTvSubstList :: TvSubst -> [TyVar] -> [Type] -> TvSubst
1443 extendTvSubstList (TvSubst in_scope env) tvs tys
1444 = TvSubst in_scope (extendVarEnvList env (tvs `zip` tys))
1446 -- mkOpenTvSubst and zipOpenTvSubst generate the in-scope set from
1447 -- the types given; but it's just a thunk so with a bit of luck
1448 -- it'll never be evaluated
1450 -- Note [Generating the in-scope set for a substitution]
1451 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1452 -- If we want to substitute [a -> ty1, b -> ty2] I used to
1453 -- think it was enough to generate an in-scope set that includes
1454 -- fv(ty1,ty2). But that's not enough; we really should also take the
1455 -- free vars of the type we are substituting into! Example:
1456 -- (forall b. (a,b,x)) [a -> List b]
1457 -- Then if we use the in-scope set {b}, there is a danger we will rename
1458 -- the forall'd variable to 'x' by mistake, getting this:
1459 -- (forall x. (List b, x, x)
1460 -- Urk! This means looking at all the calls to mkOpenTvSubst....
1463 -- | Generates the in-scope set for the 'TvSubst' from the types in the incoming
1464 -- environment, hence "open"
1465 mkOpenTvSubst :: TvSubstEnv -> TvSubst
1466 mkOpenTvSubst env = TvSubst (mkInScopeSet (tyVarsOfTypes (varEnvElts env))) env
1468 -- | Generates the in-scope set for the 'TvSubst' from the types in the incoming
1469 -- environment, hence "open"
1470 zipOpenTvSubst :: [TyVar] -> [Type] -> TvSubst
1471 zipOpenTvSubst tyvars tys
1472 | debugIsOn && (length tyvars /= length tys)
1473 = pprTrace "zipOpenTvSubst" (ppr tyvars $$ ppr tys) emptyTvSubst
1475 = TvSubst (mkInScopeSet (tyVarsOfTypes tys)) (zipTyEnv tyvars tys)
1477 -- | Called when doing top-level substitutions. Here we expect that the
1478 -- free vars of the range of the substitution will be empty.
1479 mkTopTvSubst :: [(TyVar, Type)] -> TvSubst
1480 mkTopTvSubst prs = TvSubst emptyInScopeSet (mkVarEnv prs)
1482 zipTopTvSubst :: [TyVar] -> [Type] -> TvSubst
1483 zipTopTvSubst tyvars tys
1484 | debugIsOn && (length tyvars /= length tys)
1485 = pprTrace "zipTopTvSubst" (ppr tyvars $$ ppr tys) emptyTvSubst
1487 = TvSubst emptyInScopeSet (zipTyEnv tyvars tys)
1489 zipTyEnv :: [TyVar] -> [Type] -> TvSubstEnv
1491 | debugIsOn && (length tyvars /= length tys)
1492 = pprTrace "mkTopTvSubst" (ppr tyvars $$ ppr tys) emptyVarEnv
1494 = zip_ty_env tyvars tys emptyVarEnv
1496 -- Later substitutions in the list over-ride earlier ones,
1497 -- but there should be no loops
1498 zip_ty_env :: [TyVar] -> [Type] -> TvSubstEnv -> TvSubstEnv
1499 zip_ty_env [] [] env = env
1500 zip_ty_env (tv:tvs) (ty:tys) env = zip_ty_env tvs tys (extendVarEnv env tv ty)
1501 -- There used to be a special case for when
1503 -- (a not-uncommon case) in which case the substitution was dropped.
1504 -- But the type-tidier changes the print-name of a type variable without
1505 -- changing the unique, and that led to a bug. Why? Pre-tidying, we had
1506 -- a type {Foo t}, where Foo is a one-method class. So Foo is really a newtype.
1507 -- And it happened that t was the type variable of the class. Post-tiding,
1508 -- it got turned into {Foo t2}. The ext-core printer expanded this using
1509 -- sourceTypeRep, but that said "Oh, t == t2" because they have the same unique,
1510 -- and so generated a rep type mentioning t not t2.
1512 -- Simplest fix is to nuke the "optimisation"
1513 zip_ty_env tvs tys env = pprTrace "Var/Type length mismatch: " (ppr tvs $$ ppr tys) env
1514 -- zip_ty_env _ _ env = env
1516 instance Outputable TvSubst where
1517 ppr (TvSubst ins env)
1518 = brackets $ sep[ ptext (sLit "TvSubst"),
1519 nest 2 (ptext (sLit "In scope:") <+> ppr ins),
1520 nest 2 (ptext (sLit "Env:") <+> ppr env) ]
1523 %************************************************************************
1525 Performing type substitutions
1527 %************************************************************************
1530 -- | Type substitution making use of an 'TvSubst' that
1531 -- is assumed to be open, see 'zipOpenTvSubst'
1532 substTyWith :: [TyVar] -> [Type] -> Type -> Type
1533 substTyWith tvs tys = ASSERT( length tvs == length tys )
1534 substTy (zipOpenTvSubst tvs tys)
1536 -- | Type substitution making use of an 'TvSubst' that
1537 -- is assumed to be open, see 'zipOpenTvSubst'
1538 substTysWith :: [TyVar] -> [Type] -> [Type] -> [Type]
1539 substTysWith tvs tys = ASSERT( length tvs == length tys )
1540 substTys (zipOpenTvSubst tvs tys)
1542 -- | Substitute within a 'Type'
1543 substTy :: TvSubst -> Type -> Type
1544 substTy subst ty | isEmptyTvSubst subst = ty
1545 | otherwise = subst_ty subst ty
1547 -- | Substitute within several 'Type's
1548 substTys :: TvSubst -> [Type] -> [Type]
1549 substTys subst tys | isEmptyTvSubst subst = tys
1550 | otherwise = map (subst_ty subst) tys
1552 -- | Substitute within a 'ThetaType'
1553 substTheta :: TvSubst -> ThetaType -> ThetaType
1554 substTheta subst theta
1555 | isEmptyTvSubst subst = theta
1556 | otherwise = map (substPred subst) theta
1558 -- | Substitute within a 'PredType'
1559 substPred :: TvSubst -> PredType -> PredType
1560 substPred subst (IParam n ty) = IParam n (subst_ty subst ty)
1561 substPred subst (ClassP clas tys) = ClassP clas (map (subst_ty subst) tys)
1562 substPred subst (EqPred ty1 ty2) = EqPred (subst_ty subst ty1) (subst_ty subst ty2)
1564 -- | Remove any nested binders mentioning the 'TyVar's in the 'TyVarSet'
1565 deShadowTy :: TyVarSet -> Type -> Type
1567 = subst_ty (mkTvSubst in_scope emptyTvSubstEnv) ty
1569 in_scope = mkInScopeSet tvs
1571 subst_ty :: TvSubst -> Type -> Type
1572 -- subst_ty is the main workhorse for type substitution
1574 -- Note that the in_scope set is poked only if we hit a forall
1575 -- so it may often never be fully computed
1579 go (TyVarTy tv) = substTyVar subst tv
1580 go (TyConApp tc tys) = let args = map go tys
1581 in args `seqList` TyConApp tc args
1583 go (PredTy p) = PredTy $! (substPred subst p)
1585 go (FunTy arg res) = (FunTy $! (go arg)) $! (go res)
1586 go (AppTy fun arg) = mkAppTy (go fun) $! (go arg)
1587 -- The mkAppTy smart constructor is important
1588 -- we might be replacing (a Int), represented with App
1589 -- by [Int], represented with TyConApp
1590 go (ForAllTy tv ty) = case substTyVarBndr subst tv of
1592 ForAllTy tv' $! (subst_ty subst' ty)
1594 substTyVar :: TvSubst -> TyVar -> Type
1595 substTyVar subst@(TvSubst _ _) tv
1596 = case lookupTyVar subst tv of {
1597 Nothing -> TyVarTy tv;
1598 Just ty -> ty -- See Note [Apply Once]
1601 substTyVars :: TvSubst -> [TyVar] -> [Type]
1602 substTyVars subst tvs = map (substTyVar subst) tvs
1604 lookupTyVar :: TvSubst -> TyVar -> Maybe Type
1605 -- See Note [Extending the TvSubst]
1606 lookupTyVar (TvSubst _ env) tv = lookupVarEnv env tv
1608 substTyVarBndr :: TvSubst -> TyVar -> (TvSubst, TyVar)
1609 substTyVarBndr subst@(TvSubst in_scope env) old_var
1610 = (TvSubst (in_scope `extendInScopeSet` new_var) new_env, new_var)
1612 is_co_var = isCoVar old_var
1614 new_env | no_change = delVarEnv env old_var
1615 | otherwise = extendVarEnv env old_var (TyVarTy new_var)
1617 no_change = new_var == old_var && not is_co_var
1618 -- no_change means that the new_var is identical in
1619 -- all respects to the old_var (same unique, same kind)
1620 -- See Note [Extending the TvSubst]
1622 -- In that case we don't need to extend the substitution
1623 -- to map old to new. But instead we must zap any
1624 -- current substitution for the variable. For example:
1625 -- (\x.e) with id_subst = [x |-> e']
1626 -- Here we must simply zap the substitution for x
1628 new_var = uniqAway in_scope subst_old_var
1629 -- The uniqAway part makes sure the new variable is not already in scope
1631 subst_old_var -- subst_old_var is old_var with the substitution applied to its kind
1632 -- It's only worth doing the substitution for coercions,
1633 -- becuase only they can have free type variables
1634 | is_co_var = setTyVarKind old_var (substTy subst (tyVarKind old_var))
1635 | otherwise = old_var
1638 ----------------------------------------------------
1647 -- There's a little subtyping at the kind level:
1657 -- Where: \* [LiftedTypeKind] means boxed type
1658 -- \# [UnliftedTypeKind] means unboxed type
1659 -- (\#) [UbxTupleKind] means unboxed tuple
1660 -- ?? [ArgTypeKind] is the lub of {\*, \#}
1661 -- ? [OpenTypeKind] means any type at all
1666 -- > error :: forall a:?. String -> a
1667 -- > (->) :: ?? -> ? -> \*
1668 -- > (\\(x::t) -> ...)
1670 -- Where in the last example @t :: ??@ (i.e. is not an unboxed tuple)
1672 type KindVar = TyVar -- invariant: KindVar will always be a
1673 -- TcTyVar with details MetaTv TauTv ...
1674 -- kind var constructors and functions are in TcType
1676 type SimpleKind = Kind
1681 During kind inference, a kind variable unifies only with
1683 sk ::= * | sk1 -> sk2
1685 data T a = MkT a (T Int#)
1686 fails. We give T the kind (k -> *), and the kind variable k won't unify
1687 with # (the kind of Int#).
1691 When creating a fresh internal type variable, we give it a kind to express
1692 constraints on it. E.g. in (\x->e) we make up a fresh type variable for x,
1695 During unification we only bind an internal type variable to a type
1696 whose kind is lower in the sub-kind hierarchy than the kind of the tyvar.
1698 When unifying two internal type variables, we collect their kind constraints by
1699 finding the GLB of the two. Since the partial order is a tree, they only
1700 have a glb if one is a sub-kind of the other. In that case, we bind the
1701 less-informative one to the more informative one. Neat, eh?
1708 %************************************************************************
1710 Functions over Kinds
1712 %************************************************************************
1715 -- | Essentially 'funResultTy' on kinds
1716 kindFunResult :: Kind -> Kind
1717 kindFunResult k = funResultTy k
1719 -- | Essentially 'splitFunTys' on kinds
1720 splitKindFunTys :: Kind -> ([Kind],Kind)
1721 splitKindFunTys k = splitFunTys k
1723 -- | Essentially 'splitFunTysN' on kinds
1724 splitKindFunTysN :: Int -> Kind -> ([Kind],Kind)
1725 splitKindFunTysN k = splitFunTysN k
1727 -- | See "Type#kind_subtyping" for details of the distinction between these 'Kind's
1728 isUbxTupleKind, isOpenTypeKind, isArgTypeKind, isUnliftedTypeKind :: Kind -> Bool
1729 isOpenTypeKindCon, isUbxTupleKindCon, isArgTypeKindCon,
1730 isUnliftedTypeKindCon, isSubArgTypeKindCon :: TyCon -> Bool
1732 isOpenTypeKindCon tc = tyConUnique tc == openTypeKindTyConKey
1734 isOpenTypeKind (TyConApp tc _) = isOpenTypeKindCon tc
1735 isOpenTypeKind _ = False
1737 isUbxTupleKindCon tc = tyConUnique tc == ubxTupleKindTyConKey
1739 isUbxTupleKind (TyConApp tc _) = isUbxTupleKindCon tc
1740 isUbxTupleKind _ = False
1742 isArgTypeKindCon tc = tyConUnique tc == argTypeKindTyConKey
1744 isArgTypeKind (TyConApp tc _) = isArgTypeKindCon tc
1745 isArgTypeKind _ = False
1747 isUnliftedTypeKindCon tc = tyConUnique tc == unliftedTypeKindTyConKey
1749 isUnliftedTypeKind (TyConApp tc _) = isUnliftedTypeKindCon tc
1750 isUnliftedTypeKind _ = False
1752 isSubOpenTypeKind :: Kind -> Bool
1753 -- ^ True of any sub-kind of OpenTypeKind (i.e. anything except arrow)
1754 isSubOpenTypeKind (FunTy k1 k2) = ASSERT2 ( isKind k1, text "isSubOpenTypeKind" <+> ppr k1 <+> text "::" <+> ppr (typeKind k1) )
1755 ASSERT2 ( isKind k2, text "isSubOpenTypeKind" <+> ppr k2 <+> text "::" <+> ppr (typeKind k2) )
1757 isSubOpenTypeKind (TyConApp kc []) = ASSERT( isKind (TyConApp kc []) ) True
1758 isSubOpenTypeKind other = ASSERT( isKind other ) False
1759 -- This is a conservative answer
1760 -- It matters in the call to isSubKind in
1761 -- checkExpectedKind.
1763 isSubArgTypeKindCon kc
1764 | isUnliftedTypeKindCon kc = True
1765 | isLiftedTypeKindCon kc = True
1766 | isArgTypeKindCon kc = True
1769 isSubArgTypeKind :: Kind -> Bool
1770 -- ^ True of any sub-kind of ArgTypeKind
1771 isSubArgTypeKind (TyConApp kc []) = isSubArgTypeKindCon kc
1772 isSubArgTypeKind _ = False
1774 -- | Is this a super-kind (i.e. a type-of-kinds)?
1775 isSuperKind :: Type -> Bool
1776 isSuperKind (TyConApp (skc) []) = isSuperKindTyCon skc
1777 isSuperKind _ = False
1779 -- | Is this a kind (i.e. a type-of-types)?
1780 isKind :: Kind -> Bool
1781 isKind k = isSuperKind (typeKind k)
1783 isSubKind :: Kind -> Kind -> Bool
1784 -- ^ @k1 \`isSubKind\` k2@ checks that @k1@ <: @k2@
1785 isSubKind (TyConApp kc1 []) (TyConApp kc2 []) = kc1 `isSubKindCon` kc2
1786 isSubKind (FunTy a1 r1) (FunTy a2 r2) = (a2 `isSubKind` a1) && (r1 `isSubKind` r2)
1787 isSubKind (PredTy (EqPred ty1 ty2)) (PredTy (EqPred ty1' ty2'))
1788 = ty1 `tcEqType` ty1' && ty2 `tcEqType` ty2'
1789 isSubKind _ _ = False
1791 eqKind :: Kind -> Kind -> Bool
1794 isSubKindCon :: TyCon -> TyCon -> Bool
1795 -- ^ @kc1 \`isSubKindCon\` kc2@ checks that @kc1@ <: @kc2@
1796 isSubKindCon kc1 kc2
1797 | isLiftedTypeKindCon kc1 && isLiftedTypeKindCon kc2 = True
1798 | isUnliftedTypeKindCon kc1 && isUnliftedTypeKindCon kc2 = True
1799 | isUbxTupleKindCon kc1 && isUbxTupleKindCon kc2 = True
1800 | isOpenTypeKindCon kc2 = True
1801 -- we already know kc1 is not a fun, its a TyCon
1802 | isArgTypeKindCon kc2 && isSubArgTypeKindCon kc1 = True
1805 defaultKind :: Kind -> Kind
1806 -- ^ Used when generalising: default kind ? and ?? to *. See "Type#kind_subtyping" for more
1807 -- information on what that means
1809 -- When we generalise, we make generic type variables whose kind is
1810 -- simple (* or *->* etc). So generic type variables (other than
1811 -- built-in constants like 'error') always have simple kinds. This is important;
1814 -- We want f to get type
1815 -- f :: forall (a::*). a -> Bool
1817 -- f :: forall (a::??). a -> Bool
1818 -- because that would allow a call like (f 3#) as well as (f True),
1819 --and the calling conventions differ. This defaulting is done in TcMType.zonkTcTyVarBndr.
1821 | isSubOpenTypeKind k = liftedTypeKind
1822 | isSubArgTypeKind k = liftedTypeKind
1825 isEqPred :: PredType -> Bool
1826 isEqPred (EqPred _ _) = True