2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1998
6 Type - public interface
9 -- The above warning supression flag is a temporary kludge.
10 -- While working on this module you are encouraged to remove it and fix
11 -- any warnings in the module. See
12 -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
15 -- | Main functions for manipulating types and type-related things
17 -- Note some of this is just re-exports from TyCon..
19 -- * Main data types representing Types
20 -- $type_classification
22 -- $representation_types
23 TyThing(..), Type, PredType(..), ThetaType,
25 -- ** Constructing and deconstructing types
26 mkTyVarTy, mkTyVarTys, getTyVar, getTyVar_maybe,
28 mkAppTy, mkAppTys, splitAppTy, splitAppTys,
29 splitAppTy_maybe, repSplitAppTy_maybe,
31 mkFunTy, mkFunTys, splitFunTy, splitFunTy_maybe,
32 splitFunTys, splitFunTysN,
33 funResultTy, funArgTy, zipFunTys,
35 mkTyConApp, mkTyConTy,
36 tyConAppTyCon, tyConAppArgs,
37 splitTyConApp_maybe, splitTyConApp,
39 mkForAllTy, mkForAllTys, splitForAllTy_maybe, splitForAllTys,
40 applyTy, applyTys, applyTysD, isForAllTy, dropForAlls,
43 newTyConInstRhs, carefullySplitNewType_maybe,
46 tyFamInsts, predFamInsts,
49 mkPredTy, mkPredTys, mkFamilyTyConApp, isEqPred, coVarPred,
51 -- ** Common type constructors
54 -- ** Predicates on types
55 isTyVarTy, isFunTy, isDictTy,
57 -- (Lifting and boxity)
58 isUnLiftedType, isUnboxedTupleType, isAlgType, isClosedAlgType,
59 isPrimitiveType, isStrictType, isStrictPred,
61 -- * Main data types representing Kinds
63 Kind, SimpleKind, KindVar,
65 -- ** Common Kinds and SuperKinds
66 liftedTypeKind, unliftedTypeKind, openTypeKind,
67 argTypeKind, ubxTupleKind,
69 tySuperKind, coSuperKind,
71 -- ** Common Kind type constructors
72 liftedTypeKindTyCon, openTypeKindTyCon, unliftedTypeKindTyCon,
73 argTypeKindTyCon, ubxTupleKindTyCon,
75 -- * Type free variables
76 tyVarsOfType, tyVarsOfTypes, tyVarsOfPred, tyVarsOfTheta,
80 coreEqType, coreEqType2,
81 tcEqType, tcEqTypes, tcCmpType, tcCmpTypes,
82 tcEqPred, tcEqPredX, tcCmpPred, tcEqTypeX, tcPartOfType, tcPartOfPred,
84 -- * Forcing evaluation of types
87 -- * Other views onto Types
88 coreView, tcView, kindView,
92 -- * Type representation for the code generator
95 typePrimRep, predTypeRep,
97 -- * Main type substitution data types
98 TvSubstEnv, -- Representation widely visible
99 TvSubst(..), -- Representation visible to a few friends
101 -- ** Manipulating type substitutions
102 emptyTvSubstEnv, emptyTvSubst,
104 mkTvSubst, mkOpenTvSubst, zipOpenTvSubst, zipTopTvSubst, mkTopTvSubst, notElemTvSubst,
105 getTvSubstEnv, setTvSubstEnv, zapTvSubstEnv, getTvInScope,
106 extendTvInScope, extendTvInScopeList,
107 extendTvSubst, extendTvSubstList, isInScope, composeTvSubst, zipTyEnv,
110 -- ** Performing substitution on types
111 substTy, substTys, substTyWith, substTysWith, substTheta,
112 substPred, substTyVar, substTyVars, substTyVarBndr, deShadowTy, lookupTyVar,
115 pprType, pprParendType, pprTypeApp, pprTyThingCategory, pprTyThing, pprForAll,
116 pprPred, pprEqPred, pprTheta, pprThetaArrow, pprClassPred, pprKind, pprParendKind,
121 #include "HsVersions.h"
123 -- We import the representation and primitive functions from TypeRep.
124 -- Many things are reexported, but not the representation!
142 import Data.Maybe ( isJust )
144 infixr 3 `mkFunTy` -- Associates to the right
148 -- $type_classification
149 -- #type_classification#
153 -- [Unboxed] Iff its representation is other than a pointer
154 -- Unboxed types are also unlifted.
156 -- [Lifted] Iff it has bottom as an element.
157 -- Closures always have lifted types: i.e. any
158 -- let-bound identifier in Core must have a lifted
159 -- type. Operationally, a lifted object is one that
161 -- Only lifted types may be unified with a type variable.
163 -- [Algebraic] Iff it is a type with one or more constructors, whether
164 -- declared with @data@ or @newtype@.
165 -- An algebraic type is one that can be deconstructed
166 -- with a case expression. This is /not/ the same as
167 -- lifted types, because we also include unboxed
168 -- tuples in this classification.
170 -- [Data] Iff it is a type declared with @data@, or a boxed tuple.
172 -- [Primitive] Iff it is a built-in type that can't be expressed in Haskell.
174 -- Currently, all primitive types are unlifted, but that's not necessarily
175 -- the case: for example, @Int@ could be primitive.
177 -- Some primitive types are unboxed, such as @Int#@, whereas some are boxed
178 -- but unlifted (such as @ByteArray#@). The only primitive types that we
179 -- classify as algebraic are the unboxed tuples.
181 -- Some examples of type classifications that may make this a bit clearer are:
184 -- Type primitive boxed lifted algebraic
185 -- -----------------------------------------------------------------------------
187 -- ByteArray# Yes Yes No No
188 -- (\# a, b \#) Yes No No Yes
189 -- ( a, b ) No Yes Yes Yes
190 -- [a] No Yes Yes Yes
193 -- $representation_types
194 -- A /source type/ is a type that is a separate type as far as the type checker is
195 -- concerned, but which has a more low-level representation as far as Core-to-Core
196 -- passes and the rest of the back end is concerned. Notably, 'PredTy's are removed
197 -- from the representation type while they do exist in the source types.
199 -- You don't normally have to worry about this, as the utility functions in
200 -- this module will automatically convert a source into a representation type
201 -- if they are spotted, to the best of it's abilities. If you don't want this
202 -- to happen, use the equivalent functions from the "TcType" module.
205 %************************************************************************
209 %************************************************************************
212 {-# INLINE coreView #-}
213 coreView :: Type -> Maybe Type
214 -- ^ In Core, we \"look through\" non-recursive newtypes and 'PredTypes': this
215 -- function tries to obtain a different view of the supplied type given this
217 -- Strips off the /top layer only/ of a type to give
218 -- its underlying representation type.
219 -- Returns Nothing if there is nothing to look through.
221 -- In the case of @newtype@s, it returns one of:
223 -- 1) A vanilla 'TyConApp' (recursive newtype, or non-saturated)
225 -- 2) The newtype representation (otherwise), meaning the
226 -- type written in the RHS of the newtype declaration,
227 -- which may itself be a newtype
229 -- For example, with:
231 -- > newtype R = MkR S
232 -- > newtype S = MkS T
233 -- > newtype T = MkT (T -> T)
235 -- 'expandNewTcApp' on:
237 -- * @R@ gives @Just S@
238 -- * @S@ gives @Just T@
239 -- * @T@ gives @Nothing@ (no expansion)
241 -- By being non-recursive and inlined, this case analysis gets efficiently
242 -- joined onto the case analysis that the caller is already doing
244 | isEqPred p = Nothing
245 | otherwise = Just (predTypeRep p)
246 coreView (TyConApp tc tys) | Just (tenv, rhs, tys') <- coreExpandTyCon_maybe tc tys
247 = Just (mkAppTys (substTy (mkTopTvSubst tenv) rhs) tys')
248 -- Its important to use mkAppTys, rather than (foldl AppTy),
249 -- because the function part might well return a
250 -- partially-applied type constructor; indeed, usually will!
255 -----------------------------------------------
256 {-# INLINE tcView #-}
257 tcView :: Type -> Maybe Type
258 -- ^ Similar to 'coreView', but for the type checker, which just looks through synonyms
259 tcView (TyConApp tc tys) | Just (tenv, rhs, tys') <- tcExpandTyCon_maybe tc tys
260 = Just (mkAppTys (substTy (mkTopTvSubst tenv) rhs) tys')
263 -----------------------------------------------
264 expandTypeSynonyms :: Type -> Type
265 -- ^ Expand out all type synonyms. Actually, it'd suffice to expand out
266 -- just the ones that discard type variables (e.g. type Funny a = Int)
267 -- But we don't know which those are currently, so we just expand all.
268 expandTypeSynonyms ty
272 | Just (tenv, rhs, tys') <- tcExpandTyCon_maybe tc tys
273 = go (mkAppTys (substTy (mkTopTvSubst tenv) rhs) tys')
275 = TyConApp tc (map go tys)
276 go (TyVarTy tv) = TyVarTy tv
277 go (AppTy t1 t2) = AppTy (go t1) (go t2)
278 go (FunTy t1 t2) = FunTy (go t1) (go t2)
279 go (ForAllTy tv t) = ForAllTy tv (go t)
280 go (PredTy p) = PredTy (go_pred p)
282 go_pred (ClassP c ts) = ClassP c (map go ts)
283 go_pred (IParam ip t) = IParam ip (go t)
284 go_pred (EqPred t1 t2) = EqPred (go t1) (go t2)
286 -----------------------------------------------
287 {-# INLINE kindView #-}
288 kindView :: Kind -> Maybe Kind
289 -- ^ Similar to 'coreView' or 'tcView', but works on 'Kind's
291 -- For the moment, we don't even handle synonyms in kinds
296 %************************************************************************
298 \subsection{Constructor-specific functions}
300 %************************************************************************
303 ---------------------------------------------------------------------
307 mkTyVarTy :: TyVar -> Type
310 mkTyVarTys :: [TyVar] -> [Type]
311 mkTyVarTys = map mkTyVarTy -- a common use of mkTyVarTy
313 -- | Attempts to obtain the type variable underlying a 'Type', and panics with the
314 -- given message if this is not a type variable type. See also 'getTyVar_maybe'
315 getTyVar :: String -> Type -> TyVar
316 getTyVar msg ty = case getTyVar_maybe ty of
318 Nothing -> panic ("getTyVar: " ++ msg)
320 isTyVarTy :: Type -> Bool
321 isTyVarTy ty = isJust (getTyVar_maybe ty)
323 -- | Attempts to obtain the type variable underlying a 'Type'
324 getTyVar_maybe :: Type -> Maybe TyVar
325 getTyVar_maybe ty | Just ty' <- coreView ty = getTyVar_maybe ty'
326 getTyVar_maybe (TyVarTy tv) = Just tv
327 getTyVar_maybe _ = Nothing
332 ---------------------------------------------------------------------
335 We need to be pretty careful with AppTy to make sure we obey the
336 invariant that a TyConApp is always visibly so. mkAppTy maintains the
340 -- | Applies a type to another, as in e.g. @k a@
341 mkAppTy :: Type -> Type -> Type
342 mkAppTy orig_ty1 orig_ty2
345 mk_app (TyConApp tc tys) = mkTyConApp tc (tys ++ [orig_ty2])
346 mk_app _ = AppTy orig_ty1 orig_ty2
347 -- Note that the TyConApp could be an
348 -- under-saturated type synonym. GHC allows that; e.g.
349 -- type Foo k = k a -> k a
351 -- foo :: Foo Id -> Foo Id
353 -- Here Id is partially applied in the type sig for Foo,
354 -- but once the type synonyms are expanded all is well
356 mkAppTys :: Type -> [Type] -> Type
357 mkAppTys orig_ty1 [] = orig_ty1
358 -- This check for an empty list of type arguments
359 -- avoids the needless loss of a type synonym constructor.
360 -- For example: mkAppTys Rational []
361 -- returns to (Ratio Integer), which has needlessly lost
362 -- the Rational part.
363 mkAppTys orig_ty1 orig_tys2
366 mk_app (TyConApp tc tys) = mkTyConApp tc (tys ++ orig_tys2)
367 -- mkTyConApp: see notes with mkAppTy
368 mk_app _ = foldl AppTy orig_ty1 orig_tys2
371 splitAppTy_maybe :: Type -> Maybe (Type, Type)
372 -- ^ Attempt to take a type application apart, whether it is a
373 -- function, type constructor, or plain type application. Note
374 -- that type family applications are NEVER unsaturated by this!
375 splitAppTy_maybe ty | Just ty' <- coreView ty
376 = splitAppTy_maybe ty'
377 splitAppTy_maybe ty = repSplitAppTy_maybe ty
380 repSplitAppTy_maybe :: Type -> Maybe (Type,Type)
381 -- ^ Does the AppTy split as in 'splitAppTy_maybe', but assumes that
382 -- any Core view stuff is already done
383 repSplitAppTy_maybe (FunTy ty1 ty2) = Just (TyConApp funTyCon [ty1], ty2)
384 repSplitAppTy_maybe (AppTy ty1 ty2) = Just (ty1, ty2)
385 repSplitAppTy_maybe (TyConApp tc tys)
386 | isDecomposableTyCon tc || length tys > tyConArity tc
387 = case snocView tys of -- never create unsaturated type family apps
388 Just (tys', ty') -> Just (TyConApp tc tys', ty')
390 repSplitAppTy_maybe _other = Nothing
392 splitAppTy :: Type -> (Type, Type)
393 -- ^ Attempts to take a type application apart, as in 'splitAppTy_maybe',
394 -- and panics if this is not possible
395 splitAppTy ty = case splitAppTy_maybe ty of
397 Nothing -> panic "splitAppTy"
400 splitAppTys :: Type -> (Type, [Type])
401 -- ^ Recursively splits a type as far as is possible, leaving a residual
402 -- type being applied to and the type arguments applied to it. Never fails,
403 -- even if that means returning an empty list of type applications.
404 splitAppTys ty = split ty ty []
406 split orig_ty ty args | Just ty' <- coreView ty = split orig_ty ty' args
407 split _ (AppTy ty arg) args = split ty ty (arg:args)
408 split _ (TyConApp tc tc_args) args
409 = let -- keep type families saturated
410 n | isDecomposableTyCon tc = 0
411 | otherwise = tyConArity tc
412 (tc_args1, tc_args2) = splitAt n tc_args
414 (TyConApp tc tc_args1, tc_args2 ++ args)
415 split _ (FunTy ty1 ty2) args = ASSERT( null args )
416 (TyConApp funTyCon [], [ty1,ty2])
417 split orig_ty _ args = (orig_ty, args)
422 ---------------------------------------------------------------------
427 mkFunTy :: Type -> Type -> Type
428 -- ^ Creates a function type from the given argument and result type
429 mkFunTy arg@(PredTy (EqPred {})) res = ForAllTy (mkWildCoVar arg) res
430 mkFunTy arg res = FunTy arg res
432 mkFunTys :: [Type] -> Type -> Type
433 mkFunTys tys ty = foldr mkFunTy ty tys
435 isFunTy :: Type -> Bool
436 isFunTy ty = isJust (splitFunTy_maybe ty)
438 splitFunTy :: Type -> (Type, Type)
439 -- ^ Attempts to extract the argument and result types from a type, and
440 -- panics if that is not possible. See also 'splitFunTy_maybe'
441 splitFunTy ty | Just ty' <- coreView ty = splitFunTy ty'
442 splitFunTy (FunTy arg res) = (arg, res)
443 splitFunTy other = pprPanic "splitFunTy" (ppr other)
445 splitFunTy_maybe :: Type -> Maybe (Type, Type)
446 -- ^ Attempts to extract the argument and result types from a type
447 splitFunTy_maybe ty | Just ty' <- coreView ty = splitFunTy_maybe ty'
448 splitFunTy_maybe (FunTy arg res) = Just (arg, res)
449 splitFunTy_maybe _ = Nothing
451 splitFunTys :: Type -> ([Type], Type)
452 splitFunTys ty = split [] ty ty
454 split args orig_ty ty | Just ty' <- coreView ty = split args orig_ty ty'
455 split args _ (FunTy arg res) = split (arg:args) res res
456 split args orig_ty _ = (reverse args, orig_ty)
458 splitFunTysN :: Int -> Type -> ([Type], Type)
459 -- ^ Split off exactly the given number argument types, and panics if that is not possible
460 splitFunTysN 0 ty = ([], ty)
461 splitFunTysN n ty = ASSERT2( isFunTy ty, int n <+> ppr ty )
462 case splitFunTy ty of { (arg, res) ->
463 case splitFunTysN (n-1) res of { (args, res) ->
466 -- | Splits off argument types from the given type and associating
467 -- them with the things in the input list from left to right. The
468 -- final result type is returned, along with the resulting pairs of
469 -- objects and types, albeit with the list of pairs in reverse order.
470 -- Panics if there are not enough argument types for the input list.
471 zipFunTys :: Outputable a => [a] -> Type -> ([(a, Type)], Type)
472 zipFunTys orig_xs orig_ty = split [] orig_xs orig_ty orig_ty
474 split acc [] nty _ = (reverse acc, nty)
476 | Just ty' <- coreView ty = split acc xs nty ty'
477 split acc (x:xs) _ (FunTy arg res) = split ((x,arg):acc) xs res res
478 split _ _ _ _ = pprPanic "zipFunTys" (ppr orig_xs <+> ppr orig_ty)
480 funResultTy :: Type -> Type
481 -- ^ Extract the function result type and panic if that is not possible
482 funResultTy ty | Just ty' <- coreView ty = funResultTy ty'
483 funResultTy (FunTy _arg res) = res
484 funResultTy ty = pprPanic "funResultTy" (ppr ty)
486 funArgTy :: Type -> Type
487 -- ^ Extract the function argument type and panic if that is not possible
488 funArgTy ty | Just ty' <- coreView ty = funArgTy ty'
489 funArgTy (FunTy arg _res) = arg
490 funArgTy ty = pprPanic "funArgTy" (ppr ty)
493 ---------------------------------------------------------------------
498 -- | A key function: builds a 'TyConApp' or 'FunTy' as apppropriate to its arguments.
499 -- Applies its arguments to the constructor from left to right
500 mkTyConApp :: TyCon -> [Type] -> Type
502 | isFunTyCon tycon, [ty1,ty2] <- tys
508 -- | Create the plain type constructor type which has been applied to no type arguments at all.
509 mkTyConTy :: TyCon -> Type
510 mkTyConTy tycon = mkTyConApp tycon []
512 -- splitTyConApp "looks through" synonyms, because they don't
513 -- mean a distinct type, but all other type-constructor applications
514 -- including functions are returned as Just ..
516 -- | The same as @fst . splitTyConApp@
517 tyConAppTyCon :: Type -> TyCon
518 tyConAppTyCon ty = fst (splitTyConApp ty)
520 -- | The same as @snd . splitTyConApp@
521 tyConAppArgs :: Type -> [Type]
522 tyConAppArgs ty = snd (splitTyConApp ty)
524 -- | Attempts to tease a type apart into a type constructor and the application
525 -- of a number of arguments to that constructor. Panics if that is not possible.
526 -- See also 'splitTyConApp_maybe'
527 splitTyConApp :: Type -> (TyCon, [Type])
528 splitTyConApp ty = case splitTyConApp_maybe ty of
530 Nothing -> pprPanic "splitTyConApp" (ppr ty)
532 -- | Attempts to tease a type apart into a type constructor and the application
533 -- of a number of arguments to that constructor
534 splitTyConApp_maybe :: Type -> Maybe (TyCon, [Type])
535 splitTyConApp_maybe ty | Just ty' <- coreView ty = splitTyConApp_maybe ty'
536 splitTyConApp_maybe (TyConApp tc tys) = Just (tc, tys)
537 splitTyConApp_maybe (FunTy arg res) = Just (funTyCon, [arg,res])
538 splitTyConApp_maybe _ = Nothing
540 newTyConInstRhs :: TyCon -> [Type] -> Type
541 -- ^ Unwrap one 'layer' of newtype on a type constructor and its arguments, using an
542 -- eta-reduced version of the @newtype@ if possible
543 newTyConInstRhs tycon tys
544 = ASSERT2( equalLength tvs tys1, ppr tycon $$ ppr tys $$ ppr tvs )
545 mkAppTys (substTyWith tvs tys1 ty) tys2
547 (tvs, ty) = newTyConEtadRhs tycon
548 (tys1, tys2) = splitAtList tvs tys
552 ---------------------------------------------------------------------
556 Notes on type synonyms
557 ~~~~~~~~~~~~~~~~~~~~~~
558 The various "split" functions (splitFunTy, splitRhoTy, splitForAllTy) try
559 to return type synonyms whereever possible. Thus
564 splitFunTys (a -> Foo a) = ([a], Foo a)
567 The reason is that we then get better (shorter) type signatures in
568 interfaces. Notably this plays a role in tcTySigs in TcBinds.lhs.
571 Note [Expanding newtypes]
572 ~~~~~~~~~~~~~~~~~~~~~~~~~
573 When expanding a type to expose a data-type constructor, we need to be
574 careful about newtypes, lest we fall into an infinite loop. Here are
577 newtype Id x = MkId x
578 newtype Fix f = MkFix (f (Fix f))
579 newtype T = MkT (T -> T)
582 --------------------------
584 Fix Maybe Maybe (Fix Maybe)
588 Notice that we can expand T, even though it's recursive.
589 And we can expand Id (Id Int), even though the Id shows up
590 twice at the outer level.
592 So, when expanding, we keep track of when we've seen a recursive
593 newtype at outermost level; and bale out if we see it again.
605 -- 4. All newtypes, including recursive ones, but not newtype families
607 -- It's useful in the back end of the compiler.
608 repType :: Type -> Type
609 -- Only applied to types of kind *; hence tycons are saturated
613 go :: [TyCon] -> Type -> Type
614 go rec_nts ty | Just ty' <- coreView ty -- Expand synonyms
617 go rec_nts (ForAllTy _ ty) -- Look through foralls
620 go rec_nts (TyConApp tc tys) -- Expand newtypes
621 | Just (rec_nts', ty') <- carefullySplitNewType_maybe rec_nts tc tys
627 carefullySplitNewType_maybe :: [TyCon] -> TyCon -> [Type] -> Maybe ([TyCon],Type)
628 -- Return the representation of a newtype, unless
629 -- we've seen it already: see Note [Expanding newtypes]
630 carefullySplitNewType_maybe rec_nts tc tys
632 , not (tc `elem` rec_nts) = Just (rec_nts', newTyConInstRhs tc tys)
633 | otherwise = Nothing
635 rec_nts' | isRecursiveTyCon tc = tc:rec_nts
636 | otherwise = rec_nts
639 -- ToDo: this could be moved to the code generator, using splitTyConApp instead
640 -- of inspecting the type directly.
642 -- | Discovers the primitive representation of a more abstract 'Type'
643 typePrimRep :: Type -> PrimRep
644 typePrimRep ty = case repType ty of
645 TyConApp tc _ -> tyConPrimRep tc
647 AppTy _ _ -> PtrRep -- See note below
649 _ -> pprPanic "typePrimRep" (ppr ty)
650 -- Types of the form 'f a' must be of kind *, not *#, so
651 -- we are guaranteed that they are represented by pointers.
652 -- The reason is that f must have kind *->*, not *->*#, because
653 -- (we claim) there is no way to constrain f's kind any other
658 ---------------------------------------------------------------------
663 mkForAllTy :: TyVar -> Type -> Type
667 -- | Wraps foralls over the type using the provided 'TyVar's from left to right
668 mkForAllTys :: [TyVar] -> Type -> Type
669 mkForAllTys tyvars ty = foldr ForAllTy ty tyvars
671 isForAllTy :: Type -> Bool
672 isForAllTy (ForAllTy _ _) = True
675 -- | Attempts to take a forall type apart, returning the bound type variable
676 -- and the remainder of the type
677 splitForAllTy_maybe :: Type -> Maybe (TyVar, Type)
678 splitForAllTy_maybe ty = splitFAT_m ty
680 splitFAT_m ty | Just ty' <- coreView ty = splitFAT_m ty'
681 splitFAT_m (ForAllTy tyvar ty) = Just(tyvar, ty)
682 splitFAT_m _ = Nothing
684 -- | Attempts to take a forall type apart, returning all the immediate such bound
685 -- type variables and the remainder of the type. Always suceeds, even if that means
686 -- returning an empty list of 'TyVar's
687 splitForAllTys :: Type -> ([TyVar], Type)
688 splitForAllTys ty = split ty ty []
690 split orig_ty ty tvs | Just ty' <- coreView ty = split orig_ty ty' tvs
691 split _ (ForAllTy tv ty) tvs = split ty ty (tv:tvs)
692 split orig_ty _ tvs = (reverse tvs, orig_ty)
694 -- | Equivalent to @snd . splitForAllTys@
695 dropForAlls :: Type -> Type
696 dropForAlls ty = snd (splitForAllTys ty)
699 -- (mkPiType now in CoreUtils)
705 -- | Instantiate a forall type with one or more type arguments.
706 -- Used when we have a polymorphic function applied to type args:
710 -- We use @applyTys type-of-f [t1,t2]@ to compute the type of the expression.
711 -- Panics if no application is possible.
712 applyTy :: Type -> Type -> Type
713 applyTy ty arg | Just ty' <- coreView ty = applyTy ty' arg
714 applyTy (ForAllTy tv ty) arg = substTyWith [tv] [arg] ty
715 applyTy _ _ = panic "applyTy"
717 applyTys :: Type -> [Type] -> Type
718 -- ^ This function is interesting because:
720 -- 1. The function may have more for-alls than there are args
722 -- 2. Less obviously, it may have fewer for-alls
724 -- For case 2. think of:
726 -- > applyTys (forall a.a) [forall b.b, Int]
728 -- This really can happen, via dressing up polymorphic types with newtype
729 -- clothing. Here's an example:
731 -- > newtype R = R (forall a. a->a)
732 -- > foo = case undefined :: R of
735 applyTys ty args = applyTysD empty ty args
737 applyTysD :: SDoc -> Type -> [Type] -> Type -- Debug version
738 applyTysD _ orig_fun_ty [] = orig_fun_ty
739 applyTysD doc orig_fun_ty arg_tys
740 | n_tvs == n_args -- The vastly common case
741 = substTyWith tvs arg_tys rho_ty
742 | n_tvs > n_args -- Too many for-alls
743 = substTyWith (take n_args tvs) arg_tys
744 (mkForAllTys (drop n_args tvs) rho_ty)
745 | otherwise -- Too many type args
746 = ASSERT2( n_tvs > 0, doc $$ ppr orig_fun_ty ) -- Zero case gives infnite loop!
747 applyTysD doc (substTyWith tvs (take n_tvs arg_tys) rho_ty)
750 (tvs, rho_ty) = splitForAllTys orig_fun_ty
752 n_args = length arg_tys
756 %************************************************************************
758 \subsection{Source types}
760 %************************************************************************
762 Source types are always lifted.
764 The key function is predTypeRep which gives the representation of a source type:
767 mkPredTy :: PredType -> Type
768 mkPredTy pred = PredTy pred
770 mkPredTys :: ThetaType -> [Type]
771 mkPredTys preds = map PredTy preds
773 isEqPred :: PredType -> Bool
774 isEqPred (EqPred _ _) = True
777 predTypeRep :: PredType -> Type
778 -- ^ Convert a 'PredType' to its representation type. However, it unwraps
779 -- only the outermost level; for example, the result might be a newtype application
780 predTypeRep (IParam _ ty) = ty
781 predTypeRep (ClassP clas tys) = mkTyConApp (classTyCon clas) tys
782 -- Result might be a newtype application, but the consumer will
783 -- look through that too if necessary
784 predTypeRep (EqPred ty1 ty2) = pprPanic "predTypeRep" (ppr (EqPred ty1 ty2))
786 mkFamilyTyConApp :: TyCon -> [Type] -> Type
787 -- ^ Given a family instance TyCon and its arg types, return the
788 -- corresponding family type. E.g:
791 -- > data instance T (Maybe b) = MkT b
793 -- Where the instance tycon is :RTL, so:
795 -- > mkFamilyTyConApp :RTL Int = T (Maybe Int)
796 mkFamilyTyConApp tc tys
797 | Just (fam_tc, fam_tys) <- tyConFamInst_maybe tc
798 , let fam_subst = zipTopTvSubst (tyConTyVars tc) tys
799 = mkTyConApp fam_tc (substTys fam_subst fam_tys)
803 -- | Pretty prints a 'TyCon', using the family instance in case of a
804 -- representation tycon. For example:
806 -- > data T [a] = ...
808 -- In that case we want to print @T [a]@, where @T@ is the family 'TyCon'
809 pprSourceTyCon :: TyCon -> SDoc
811 | Just (fam_tc, tys) <- tyConFamInst_maybe tycon
812 = ppr $ fam_tc `TyConApp` tys -- can't be FunTyCon
816 isDictTy :: Type -> Bool
817 isDictTy ty = case splitTyConApp_maybe ty of
818 Just (tc, _) -> isClassTyCon tc
823 %************************************************************************
825 The free variables of a type
827 %************************************************************************
830 tyVarsOfType :: Type -> TyVarSet
831 -- ^ NB: for type synonyms tyVarsOfType does /not/ expand the synonym
832 tyVarsOfType (TyVarTy tv) = unitVarSet tv
833 tyVarsOfType (TyConApp _ tys) = tyVarsOfTypes tys
834 tyVarsOfType (PredTy sty) = tyVarsOfPred sty
835 tyVarsOfType (FunTy arg res) = tyVarsOfType arg `unionVarSet` tyVarsOfType res
836 tyVarsOfType (AppTy fun arg) = tyVarsOfType fun `unionVarSet` tyVarsOfType arg
837 tyVarsOfType (ForAllTy tv ty) -- The kind of a coercion binder
838 -- can mention type variables!
839 | isTyVar tv = inner_tvs `delVarSet` tv
840 | otherwise {- Coercion -} = -- ASSERT( not (tv `elemVarSet` inner_tvs) )
841 inner_tvs `unionVarSet` tyVarsOfType (tyVarKind tv)
843 inner_tvs = tyVarsOfType ty
845 tyVarsOfTypes :: [Type] -> TyVarSet
846 tyVarsOfTypes tys = foldr (unionVarSet.tyVarsOfType) emptyVarSet tys
848 tyVarsOfPred :: PredType -> TyVarSet
849 tyVarsOfPred (IParam _ ty) = tyVarsOfType ty
850 tyVarsOfPred (ClassP _ tys) = tyVarsOfTypes tys
851 tyVarsOfPred (EqPred ty1 ty2) = tyVarsOfType ty1 `unionVarSet` tyVarsOfType ty2
853 tyVarsOfTheta :: ThetaType -> TyVarSet
854 tyVarsOfTheta = foldr (unionVarSet . tyVarsOfPred) emptyVarSet
858 %************************************************************************
860 \subsection{Type families}
862 %************************************************************************
865 -- | Finds type family instances occuring in a type after expanding synonyms.
866 tyFamInsts :: Type -> [(TyCon, [Type])]
868 | Just exp_ty <- tcView ty = tyFamInsts exp_ty
869 tyFamInsts (TyVarTy _) = []
870 tyFamInsts (TyConApp tc tys)
871 | isSynFamilyTyCon tc = [(tc, tys)]
872 | otherwise = concat (map tyFamInsts tys)
873 tyFamInsts (FunTy ty1 ty2) = tyFamInsts ty1 ++ tyFamInsts ty2
874 tyFamInsts (AppTy ty1 ty2) = tyFamInsts ty1 ++ tyFamInsts ty2
875 tyFamInsts (ForAllTy _ ty) = tyFamInsts ty
876 tyFamInsts (PredTy pty) = predFamInsts pty
878 -- | Finds type family instances occuring in a predicate type after expanding
880 predFamInsts :: PredType -> [(TyCon, [Type])]
881 predFamInsts (ClassP _cla tys) = concat (map tyFamInsts tys)
882 predFamInsts (IParam _ ty) = tyFamInsts ty
883 predFamInsts (EqPred ty1 ty2) = tyFamInsts ty1 ++ tyFamInsts ty2
887 %************************************************************************
889 \subsection{Liftedness}
891 %************************************************************************
894 -- | See "Type#type_classification" for what an unlifted type is
895 isUnLiftedType :: Type -> Bool
896 -- isUnLiftedType returns True for forall'd unlifted types:
897 -- x :: forall a. Int#
898 -- I found bindings like these were getting floated to the top level.
899 -- They are pretty bogus types, mind you. It would be better never to
902 isUnLiftedType ty | Just ty' <- coreView ty = isUnLiftedType ty'
903 isUnLiftedType (ForAllTy _ ty) = isUnLiftedType ty
904 isUnLiftedType (TyConApp tc _) = isUnLiftedTyCon tc
905 isUnLiftedType _ = False
907 isUnboxedTupleType :: Type -> Bool
908 isUnboxedTupleType ty = case splitTyConApp_maybe ty of
909 Just (tc, _ty_args) -> isUnboxedTupleTyCon tc
912 -- | See "Type#type_classification" for what an algebraic type is.
913 -- Should only be applied to /types/, as opposed to e.g. partially
914 -- saturated type constructors
915 isAlgType :: Type -> Bool
917 = case splitTyConApp_maybe ty of
918 Just (tc, ty_args) -> ASSERT( ty_args `lengthIs` tyConArity tc )
922 -- | See "Type#type_classification" for what an algebraic type is.
923 -- Should only be applied to /types/, as opposed to e.g. partially
924 -- saturated type constructors. Closed type constructors are those
925 -- with a fixed right hand side, as opposed to e.g. associated types
926 isClosedAlgType :: Type -> Bool
928 = case splitTyConApp_maybe ty of
929 Just (tc, ty_args) -> ASSERT( ty_args `lengthIs` tyConArity tc )
930 isAlgTyCon tc && not (isFamilyTyCon tc)
935 -- | Computes whether an argument (or let right hand side) should
936 -- be computed strictly or lazily, based only on its type.
937 -- Works just like 'isUnLiftedType', except that it has a special case
938 -- for dictionaries (i.e. does not work purely on representation types)
940 -- Since it takes account of class 'PredType's, you might think
941 -- this function should be in 'TcType', but 'isStrictType' is used by 'DataCon',
942 -- which is below 'TcType' in the hierarchy, so it's convenient to put it here.
943 isStrictType :: Type -> Bool
944 isStrictType (PredTy pred) = isStrictPred pred
945 isStrictType ty | Just ty' <- coreView ty = isStrictType ty'
946 isStrictType (ForAllTy _ ty) = isStrictType ty
947 isStrictType (TyConApp tc _) = isUnLiftedTyCon tc
948 isStrictType _ = False
950 -- | We may be strict in dictionary types, but only if it
951 -- has more than one component.
953 -- (Being strict in a single-component dictionary risks
954 -- poking the dictionary component, which is wrong.)
955 isStrictPred :: PredType -> Bool
956 isStrictPred (ClassP clas _) = opt_DictsStrict && not (isNewTyCon (classTyCon clas))
957 isStrictPred _ = False
961 isPrimitiveType :: Type -> Bool
962 -- ^ Returns true of types that are opaque to Haskell.
963 -- Most of these are unlifted, but now that we interact with .NET, we
964 -- may have primtive (foreign-imported) types that are lifted
965 isPrimitiveType ty = case splitTyConApp_maybe ty of
966 Just (tc, ty_args) -> ASSERT( ty_args `lengthIs` tyConArity tc )
972 %************************************************************************
974 \subsection{Sequencing on types}
976 %************************************************************************
979 seqType :: Type -> ()
980 seqType (TyVarTy tv) = tv `seq` ()
981 seqType (AppTy t1 t2) = seqType t1 `seq` seqType t2
982 seqType (FunTy t1 t2) = seqType t1 `seq` seqType t2
983 seqType (PredTy p) = seqPred p
984 seqType (TyConApp tc tys) = tc `seq` seqTypes tys
985 seqType (ForAllTy tv ty) = tv `seq` seqType ty
987 seqTypes :: [Type] -> ()
989 seqTypes (ty:tys) = seqType ty `seq` seqTypes tys
991 seqPred :: PredType -> ()
992 seqPred (ClassP c tys) = c `seq` seqTypes tys
993 seqPred (IParam n ty) = n `seq` seqType ty
994 seqPred (EqPred ty1 ty2) = seqType ty1 `seq` seqType ty2
998 %************************************************************************
1000 Equality for Core types
1001 (We don't use instances so that we know where it happens)
1003 %************************************************************************
1005 Note that eqType works right even for partial applications of newtypes.
1006 See Note [Newtype eta] in TyCon.lhs
1009 -- | Type equality test for Core types (i.e. ignores predicate-types, synonyms etc.)
1010 coreEqType :: Type -> Type -> Bool
1011 coreEqType t1 t2 = coreEqType2 rn_env t1 t2
1013 rn_env = mkRnEnv2 (mkInScopeSet (tyVarsOfType t1 `unionVarSet` tyVarsOfType t2))
1015 coreEqType2 :: RnEnv2 -> Type -> Type -> Bool
1016 coreEqType2 rn_env t1 t2
1019 eq env (TyVarTy tv1) (TyVarTy tv2) = rnOccL env tv1 == rnOccR env tv2
1020 eq env (ForAllTy tv1 t1) (ForAllTy tv2 t2) = eq (rnBndr2 env tv1 tv2) t1 t2
1021 eq env (AppTy s1 t1) (AppTy s2 t2) = eq env s1 s2 && eq env t1 t2
1022 eq env (FunTy s1 t1) (FunTy s2 t2) = eq env s1 s2 && eq env t1 t2
1023 eq env (TyConApp tc1 tys1) (TyConApp tc2 tys2)
1024 | tc1 == tc2, all2 (eq env) tys1 tys2 = True
1025 -- The lengths should be equal because
1026 -- the two types have the same kind
1027 -- NB: if the type constructors differ that does not
1028 -- necessarily mean that the types aren't equal
1029 -- (synonyms, newtypes)
1030 -- Even if the type constructors are the same, but the arguments
1031 -- differ, the two types could be the same (e.g. if the arg is just
1032 -- ignored in the RHS). In both these cases we fall through to an
1033 -- attempt to expand one side or the other.
1035 -- Now deal with newtypes, synonyms, pred-tys
1036 eq env t1 t2 | Just t1' <- coreView t1 = eq env t1' t2
1037 | Just t2' <- coreView t2 = eq env t1 t2'
1039 -- Fall through case; not equal!
1044 %************************************************************************
1046 Comparision for source types
1047 (We don't use instances so that we know where it happens)
1049 %************************************************************************
1052 tcEqType :: Type -> Type -> Bool
1053 -- ^ Type equality on source types. Does not look through @newtypes@ or
1054 -- 'PredType's, but it does look through type synonyms.
1055 tcEqType t1 t2 = isEqual $ cmpType t1 t2
1057 tcEqTypes :: [Type] -> [Type] -> Bool
1058 tcEqTypes tys1 tys2 = isEqual $ cmpTypes tys1 tys2
1060 tcCmpType :: Type -> Type -> Ordering
1061 -- ^ Type ordering on source types. Does not look through @newtypes@ or
1062 -- 'PredType's, but it does look through type synonyms.
1063 tcCmpType t1 t2 = cmpType t1 t2
1065 tcCmpTypes :: [Type] -> [Type] -> Ordering
1066 tcCmpTypes tys1 tys2 = cmpTypes tys1 tys2
1068 tcEqPred :: PredType -> PredType -> Bool
1069 tcEqPred p1 p2 = isEqual $ cmpPred p1 p2
1071 tcEqPredX :: RnEnv2 -> PredType -> PredType -> Bool
1072 tcEqPredX env p1 p2 = isEqual $ cmpPredX env p1 p2
1074 tcCmpPred :: PredType -> PredType -> Ordering
1075 tcCmpPred p1 p2 = cmpPred p1 p2
1077 tcEqTypeX :: RnEnv2 -> Type -> Type -> Bool
1078 tcEqTypeX env t1 t2 = isEqual $ cmpTypeX env t1 t2
1082 -- | Checks whether the second argument is a subterm of the first. (We don't care
1083 -- about binders, as we are only interested in syntactic subterms.)
1084 tcPartOfType :: Type -> Type -> Bool
1086 | tcEqType t1 t2 = True
1088 | Just t2' <- tcView t2 = tcPartOfType t1 t2'
1089 tcPartOfType _ (TyVarTy _) = False
1090 tcPartOfType t1 (ForAllTy _ t2) = tcPartOfType t1 t2
1091 tcPartOfType t1 (AppTy s2 t2) = tcPartOfType t1 s2 || tcPartOfType t1 t2
1092 tcPartOfType t1 (FunTy s2 t2) = tcPartOfType t1 s2 || tcPartOfType t1 t2
1093 tcPartOfType t1 (PredTy p2) = tcPartOfPred t1 p2
1094 tcPartOfType t1 (TyConApp _ ts) = any (tcPartOfType t1) ts
1096 tcPartOfPred :: Type -> PredType -> Bool
1097 tcPartOfPred t1 (IParam _ t2) = tcPartOfType t1 t2
1098 tcPartOfPred t1 (ClassP _ ts) = any (tcPartOfType t1) ts
1099 tcPartOfPred t1 (EqPred s2 t2) = tcPartOfType t1 s2 || tcPartOfType t1 t2
1102 Now here comes the real worker
1105 cmpType :: Type -> Type -> Ordering
1106 cmpType t1 t2 = cmpTypeX rn_env t1 t2
1108 rn_env = mkRnEnv2 (mkInScopeSet (tyVarsOfType t1 `unionVarSet` tyVarsOfType t2))
1110 cmpTypes :: [Type] -> [Type] -> Ordering
1111 cmpTypes ts1 ts2 = cmpTypesX rn_env ts1 ts2
1113 rn_env = mkRnEnv2 (mkInScopeSet (tyVarsOfTypes ts1 `unionVarSet` tyVarsOfTypes ts2))
1115 cmpPred :: PredType -> PredType -> Ordering
1116 cmpPred p1 p2 = cmpPredX rn_env p1 p2
1118 rn_env = mkRnEnv2 (mkInScopeSet (tyVarsOfPred p1 `unionVarSet` tyVarsOfPred p2))
1120 cmpTypeX :: RnEnv2 -> Type -> Type -> Ordering -- Main workhorse
1121 cmpTypeX env t1 t2 | Just t1' <- tcView t1 = cmpTypeX env t1' t2
1122 | Just t2' <- tcView t2 = cmpTypeX env t1 t2'
1124 cmpTypeX env (TyVarTy tv1) (TyVarTy tv2) = rnOccL env tv1 `compare` rnOccR env tv2
1125 cmpTypeX env (ForAllTy tv1 t1) (ForAllTy tv2 t2) = cmpTypeX (rnBndr2 env tv1 tv2) t1 t2
1126 cmpTypeX env (AppTy s1 t1) (AppTy s2 t2) = cmpTypeX env s1 s2 `thenCmp` cmpTypeX env t1 t2
1127 cmpTypeX env (FunTy s1 t1) (FunTy s2 t2) = cmpTypeX env s1 s2 `thenCmp` cmpTypeX env t1 t2
1128 cmpTypeX env (PredTy p1) (PredTy p2) = cmpPredX env p1 p2
1129 cmpTypeX env (TyConApp tc1 tys1) (TyConApp tc2 tys2) = (tc1 `compare` tc2) `thenCmp` cmpTypesX env tys1 tys2
1131 -- Deal with the rest: TyVarTy < AppTy < FunTy < TyConApp < ForAllTy < PredTy
1132 cmpTypeX _ (AppTy _ _) (TyVarTy _) = GT
1134 cmpTypeX _ (FunTy _ _) (TyVarTy _) = GT
1135 cmpTypeX _ (FunTy _ _) (AppTy _ _) = GT
1137 cmpTypeX _ (TyConApp _ _) (TyVarTy _) = GT
1138 cmpTypeX _ (TyConApp _ _) (AppTy _ _) = GT
1139 cmpTypeX _ (TyConApp _ _) (FunTy _ _) = GT
1141 cmpTypeX _ (ForAllTy _ _) (TyVarTy _) = GT
1142 cmpTypeX _ (ForAllTy _ _) (AppTy _ _) = GT
1143 cmpTypeX _ (ForAllTy _ _) (FunTy _ _) = GT
1144 cmpTypeX _ (ForAllTy _ _) (TyConApp _ _) = GT
1146 cmpTypeX _ (PredTy _) _ = GT
1151 cmpTypesX :: RnEnv2 -> [Type] -> [Type] -> Ordering
1152 cmpTypesX _ [] [] = EQ
1153 cmpTypesX env (t1:tys1) (t2:tys2) = cmpTypeX env t1 t2 `thenCmp` cmpTypesX env tys1 tys2
1154 cmpTypesX _ [] _ = LT
1155 cmpTypesX _ _ [] = GT
1158 cmpPredX :: RnEnv2 -> PredType -> PredType -> Ordering
1159 cmpPredX env (IParam n1 ty1) (IParam n2 ty2) = (n1 `compare` n2) `thenCmp` cmpTypeX env ty1 ty2
1160 -- Compare names only for implicit parameters
1161 -- This comparison is used exclusively (I believe)
1162 -- for the Avails finite map built in TcSimplify
1163 -- If the types differ we keep them distinct so that we see
1164 -- a distinct pair to run improvement on
1165 cmpPredX env (ClassP c1 tys1) (ClassP c2 tys2) = (c1 `compare` c2) `thenCmp` (cmpTypesX env tys1 tys2)
1166 cmpPredX env (EqPred ty1 ty2) (EqPred ty1' ty2') = (cmpTypeX env ty1 ty1') `thenCmp` (cmpTypeX env ty2 ty2')
1168 -- Constructor order: IParam < ClassP < EqPred
1169 cmpPredX _ (IParam {}) _ = LT
1170 cmpPredX _ (ClassP {}) (IParam {}) = GT
1171 cmpPredX _ (ClassP {}) (EqPred {}) = LT
1172 cmpPredX _ (EqPred {}) _ = GT
1175 PredTypes are used as a FM key in TcSimplify,
1176 so we take the easy path and make them an instance of Ord
1179 instance Eq PredType where { (==) = tcEqPred }
1180 instance Ord PredType where { compare = tcCmpPred }
1184 %************************************************************************
1188 %************************************************************************
1191 -- | Type substitution
1193 -- #tvsubst_invariant#
1194 -- The following invariants must hold of a 'TvSubst':
1196 -- 1. The in-scope set is needed /only/ to
1197 -- guide the generation of fresh uniques
1199 -- 2. In particular, the /kind/ of the type variables in
1200 -- the in-scope set is not relevant
1202 -- 3. The substition is only applied ONCE! This is because
1203 -- in general such application will not reached a fixed point.
1205 = TvSubst InScopeSet -- The in-scope type variables
1206 TvSubstEnv -- The substitution itself
1207 -- See Note [Apply Once]
1208 -- and Note [Extending the TvSubstEnv]
1210 {- ----------------------------------------------------------
1214 We use TvSubsts to instantiate things, and we might instantiate
1218 So the substition might go [a->b, b->a]. A similar situation arises in Core
1219 when we find a beta redex like
1220 (/\ a /\ b -> e) b a
1221 Then we also end up with a substition that permutes type variables. Other
1222 variations happen to; for example [a -> (a, b)].
1224 ***************************************************
1225 *** So a TvSubst must be applied precisely once ***
1226 ***************************************************
1228 A TvSubst is not idempotent, but, unlike the non-idempotent substitution
1229 we use during unifications, it must not be repeatedly applied.
1231 Note [Extending the TvSubst]
1232 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1233 See #tvsubst_invariant# for the invariants that must hold.
1235 This invariant allows a short-cut when the TvSubstEnv is empty:
1236 if the TvSubstEnv is empty --- i.e. (isEmptyTvSubt subst) holds ---
1237 then (substTy subst ty) does nothing.
1239 For example, consider:
1240 (/\a. /\b:(a~Int). ...b..) Int
1241 We substitute Int for 'a'. The Unique of 'b' does not change, but
1242 nevertheless we add 'b' to the TvSubstEnv, because b's kind does change
1244 This invariant has several crucial consequences:
1246 * In substTyVarBndr, we need extend the TvSubstEnv
1247 - if the unique has changed
1248 - or if the kind has changed
1250 * In substTyVar, we do not need to consult the in-scope set;
1251 the TvSubstEnv is enough
1253 * In substTy, substTheta, we can short-circuit when the TvSubstEnv is empty
1256 -------------------------------------------------------------- -}
1258 -- | A substitition of 'Type's for 'TyVar's
1259 type TvSubstEnv = TyVarEnv Type
1260 -- A TvSubstEnv is used both inside a TvSubst (with the apply-once
1261 -- invariant discussed in Note [Apply Once]), and also independently
1262 -- in the middle of matching, and unification (see Types.Unify)
1263 -- So you have to look at the context to know if it's idempotent or
1264 -- apply-once or whatever
1266 emptyTvSubstEnv :: TvSubstEnv
1267 emptyTvSubstEnv = emptyVarEnv
1269 composeTvSubst :: InScopeSet -> TvSubstEnv -> TvSubstEnv -> TvSubstEnv
1270 -- ^ @(compose env1 env2)(x)@ is @env1(env2(x))@; i.e. apply @env2@ then @env1@.
1271 -- It assumes that both are idempotent.
1272 -- Typically, @env1@ is the refinement to a base substitution @env2@
1273 composeTvSubst in_scope env1 env2
1274 = env1 `plusVarEnv` mapVarEnv (substTy subst1) env2
1275 -- First apply env1 to the range of env2
1276 -- Then combine the two, making sure that env1 loses if
1277 -- both bind the same variable; that's why env1 is the
1278 -- *left* argument to plusVarEnv, because the right arg wins
1280 subst1 = TvSubst in_scope env1
1282 emptyTvSubst :: TvSubst
1283 emptyTvSubst = TvSubst emptyInScopeSet emptyVarEnv
1285 isEmptyTvSubst :: TvSubst -> Bool
1286 -- See Note [Extending the TvSubstEnv]
1287 isEmptyTvSubst (TvSubst _ env) = isEmptyVarEnv env
1289 mkTvSubst :: InScopeSet -> TvSubstEnv -> TvSubst
1292 getTvSubstEnv :: TvSubst -> TvSubstEnv
1293 getTvSubstEnv (TvSubst _ env) = env
1295 getTvInScope :: TvSubst -> InScopeSet
1296 getTvInScope (TvSubst in_scope _) = in_scope
1298 isInScope :: Var -> TvSubst -> Bool
1299 isInScope v (TvSubst in_scope _) = v `elemInScopeSet` in_scope
1301 notElemTvSubst :: TyVar -> TvSubst -> Bool
1302 notElemTvSubst tv (TvSubst _ env) = not (tv `elemVarEnv` env)
1304 setTvSubstEnv :: TvSubst -> TvSubstEnv -> TvSubst
1305 setTvSubstEnv (TvSubst in_scope _) env = TvSubst in_scope env
1307 zapTvSubstEnv :: TvSubst -> TvSubst
1308 zapTvSubstEnv (TvSubst in_scope _) = TvSubst in_scope emptyVarEnv
1310 extendTvInScope :: TvSubst -> Var -> TvSubst
1311 extendTvInScope (TvSubst in_scope env) var = TvSubst (extendInScopeSet in_scope var) env
1313 extendTvInScopeList :: TvSubst -> [Var] -> TvSubst
1314 extendTvInScopeList (TvSubst in_scope env) vars = TvSubst (extendInScopeSetList in_scope vars) env
1316 extendTvSubst :: TvSubst -> TyVar -> Type -> TvSubst
1317 extendTvSubst (TvSubst in_scope env) tv ty = TvSubst in_scope (extendVarEnv env tv ty)
1319 extendTvSubstList :: TvSubst -> [TyVar] -> [Type] -> TvSubst
1320 extendTvSubstList (TvSubst in_scope env) tvs tys
1321 = TvSubst in_scope (extendVarEnvList env (tvs `zip` tys))
1323 -- mkOpenTvSubst and zipOpenTvSubst generate the in-scope set from
1324 -- the types given; but it's just a thunk so with a bit of luck
1325 -- it'll never be evaluated
1327 -- Note [Generating the in-scope set for a substitution]
1328 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1329 -- If we want to substitute [a -> ty1, b -> ty2] I used to
1330 -- think it was enough to generate an in-scope set that includes
1331 -- fv(ty1,ty2). But that's not enough; we really should also take the
1332 -- free vars of the type we are substituting into! Example:
1333 -- (forall b. (a,b,x)) [a -> List b]
1334 -- Then if we use the in-scope set {b}, there is a danger we will rename
1335 -- the forall'd variable to 'x' by mistake, getting this:
1336 -- (forall x. (List b, x, x)
1337 -- Urk! This means looking at all the calls to mkOpenTvSubst....
1340 -- | Generates the in-scope set for the 'TvSubst' from the types in the incoming
1341 -- environment, hence "open"
1342 mkOpenTvSubst :: TvSubstEnv -> TvSubst
1343 mkOpenTvSubst env = TvSubst (mkInScopeSet (tyVarsOfTypes (varEnvElts env))) env
1345 -- | Generates the in-scope set for the 'TvSubst' from the types in the incoming
1346 -- environment, hence "open"
1347 zipOpenTvSubst :: [TyVar] -> [Type] -> TvSubst
1348 zipOpenTvSubst tyvars tys
1349 | debugIsOn && (length tyvars /= length tys)
1350 = pprTrace "zipOpenTvSubst" (ppr tyvars $$ ppr tys) emptyTvSubst
1352 = TvSubst (mkInScopeSet (tyVarsOfTypes tys)) (zipTyEnv tyvars tys)
1354 -- | Called when doing top-level substitutions. Here we expect that the
1355 -- free vars of the range of the substitution will be empty.
1356 mkTopTvSubst :: [(TyVar, Type)] -> TvSubst
1357 mkTopTvSubst prs = TvSubst emptyInScopeSet (mkVarEnv prs)
1359 zipTopTvSubst :: [TyVar] -> [Type] -> TvSubst
1360 zipTopTvSubst tyvars tys
1361 | debugIsOn && (length tyvars /= length tys)
1362 = pprTrace "zipTopTvSubst" (ppr tyvars $$ ppr tys) emptyTvSubst
1364 = TvSubst emptyInScopeSet (zipTyEnv tyvars tys)
1366 zipTyEnv :: [TyVar] -> [Type] -> TvSubstEnv
1368 | debugIsOn && (length tyvars /= length tys)
1369 = pprTrace "mkTopTvSubst" (ppr tyvars $$ ppr tys) emptyVarEnv
1371 = zip_ty_env tyvars tys emptyVarEnv
1373 -- Later substitutions in the list over-ride earlier ones,
1374 -- but there should be no loops
1375 zip_ty_env :: [TyVar] -> [Type] -> TvSubstEnv -> TvSubstEnv
1376 zip_ty_env [] [] env = env
1377 zip_ty_env (tv:tvs) (ty:tys) env = zip_ty_env tvs tys (extendVarEnv env tv ty)
1378 -- There used to be a special case for when
1380 -- (a not-uncommon case) in which case the substitution was dropped.
1381 -- But the type-tidier changes the print-name of a type variable without
1382 -- changing the unique, and that led to a bug. Why? Pre-tidying, we had
1383 -- a type {Foo t}, where Foo is a one-method class. So Foo is really a newtype.
1384 -- And it happened that t was the type variable of the class. Post-tiding,
1385 -- it got turned into {Foo t2}. The ext-core printer expanded this using
1386 -- sourceTypeRep, but that said "Oh, t == t2" because they have the same unique,
1387 -- and so generated a rep type mentioning t not t2.
1389 -- Simplest fix is to nuke the "optimisation"
1390 zip_ty_env tvs tys env = pprTrace "Var/Type length mismatch: " (ppr tvs $$ ppr tys) env
1391 -- zip_ty_env _ _ env = env
1393 instance Outputable TvSubst where
1394 ppr (TvSubst ins env)
1395 = brackets $ sep[ ptext (sLit "TvSubst"),
1396 nest 2 (ptext (sLit "In scope:") <+> ppr ins),
1397 nest 2 (ptext (sLit "Env:") <+> ppr env) ]
1400 %************************************************************************
1402 Performing type substitutions
1404 %************************************************************************
1407 -- | Type substitution making use of an 'TvSubst' that
1408 -- is assumed to be open, see 'zipOpenTvSubst'
1409 substTyWith :: [TyVar] -> [Type] -> Type -> Type
1410 substTyWith tvs tys = ASSERT( length tvs == length tys )
1411 substTy (zipOpenTvSubst tvs tys)
1413 -- | Type substitution making use of an 'TvSubst' that
1414 -- is assumed to be open, see 'zipOpenTvSubst'
1415 substTysWith :: [TyVar] -> [Type] -> [Type] -> [Type]
1416 substTysWith tvs tys = ASSERT( length tvs == length tys )
1417 substTys (zipOpenTvSubst tvs tys)
1419 -- | Substitute within a 'Type'
1420 substTy :: TvSubst -> Type -> Type
1421 substTy subst ty | isEmptyTvSubst subst = ty
1422 | otherwise = subst_ty subst ty
1424 -- | Substitute within several 'Type's
1425 substTys :: TvSubst -> [Type] -> [Type]
1426 substTys subst tys | isEmptyTvSubst subst = tys
1427 | otherwise = map (subst_ty subst) tys
1429 -- | Substitute within a 'ThetaType'
1430 substTheta :: TvSubst -> ThetaType -> ThetaType
1431 substTheta subst theta
1432 | isEmptyTvSubst subst = theta
1433 | otherwise = map (substPred subst) theta
1435 -- | Substitute within a 'PredType'
1436 substPred :: TvSubst -> PredType -> PredType
1437 substPred subst (IParam n ty) = IParam n (subst_ty subst ty)
1438 substPred subst (ClassP clas tys) = ClassP clas (map (subst_ty subst) tys)
1439 substPred subst (EqPred ty1 ty2) = EqPred (subst_ty subst ty1) (subst_ty subst ty2)
1441 -- | Remove any nested binders mentioning the 'TyVar's in the 'TyVarSet'
1442 deShadowTy :: TyVarSet -> Type -> Type
1444 = subst_ty (mkTvSubst in_scope emptyTvSubstEnv) ty
1446 in_scope = mkInScopeSet tvs
1448 subst_ty :: TvSubst -> Type -> Type
1449 -- subst_ty is the main workhorse for type substitution
1451 -- Note that the in_scope set is poked only if we hit a forall
1452 -- so it may often never be fully computed
1456 go (TyVarTy tv) = substTyVar subst tv
1457 go (TyConApp tc tys) = let args = map go tys
1458 in args `seqList` TyConApp tc args
1460 go (PredTy p) = PredTy $! (substPred subst p)
1462 go (FunTy arg res) = (FunTy $! (go arg)) $! (go res)
1463 go (AppTy fun arg) = mkAppTy (go fun) $! (go arg)
1464 -- The mkAppTy smart constructor is important
1465 -- we might be replacing (a Int), represented with App
1466 -- by [Int], represented with TyConApp
1467 go (ForAllTy tv ty) = case substTyVarBndr subst tv of
1469 ForAllTy tv' $! (subst_ty subst' ty)
1471 substTyVar :: TvSubst -> TyVar -> Type
1472 substTyVar subst@(TvSubst _ _) tv
1473 = case lookupTyVar subst tv of {
1474 Nothing -> TyVarTy tv;
1475 Just ty -> ty -- See Note [Apply Once]
1478 substTyVars :: TvSubst -> [TyVar] -> [Type]
1479 substTyVars subst tvs = map (substTyVar subst) tvs
1481 lookupTyVar :: TvSubst -> TyVar -> Maybe Type
1482 -- See Note [Extending the TvSubst]
1483 lookupTyVar (TvSubst _ env) tv = lookupVarEnv env tv
1485 substTyVarBndr :: TvSubst -> TyVar -> (TvSubst, TyVar)
1486 substTyVarBndr subst@(TvSubst in_scope env) old_var
1487 = (TvSubst (in_scope `extendInScopeSet` new_var) new_env, new_var)
1489 is_co_var = isCoVar old_var
1491 new_env | no_change = delVarEnv env old_var
1492 | otherwise = extendVarEnv env old_var (TyVarTy new_var)
1494 no_change = new_var == old_var && not is_co_var
1495 -- no_change means that the new_var is identical in
1496 -- all respects to the old_var (same unique, same kind)
1497 -- See Note [Extending the TvSubst]
1499 -- In that case we don't need to extend the substitution
1500 -- to map old to new. But instead we must zap any
1501 -- current substitution for the variable. For example:
1502 -- (\x.e) with id_subst = [x |-> e']
1503 -- Here we must simply zap the substitution for x
1505 new_var = uniqAway in_scope subst_old_var
1506 -- The uniqAway part makes sure the new variable is not already in scope
1508 subst_old_var -- subst_old_var is old_var with the substitution applied to its kind
1509 -- It's only worth doing the substitution for coercions,
1510 -- becuase only they can have free type variables
1511 | is_co_var = setTyVarKind old_var (substTy subst (tyVarKind old_var))
1512 | otherwise = old_var
1515 ----------------------------------------------------
1524 -- There's a little subtyping at the kind level:
1534 -- Where: \* [LiftedTypeKind] means boxed type
1535 -- \# [UnliftedTypeKind] means unboxed type
1536 -- (\#) [UbxTupleKind] means unboxed tuple
1537 -- ?? [ArgTypeKind] is the lub of {\*, \#}
1538 -- ? [OpenTypeKind] means any type at all
1543 -- > error :: forall a:?. String -> a
1544 -- > (->) :: ?? -> ? -> \*
1545 -- > (\\(x::t) -> ...)
1547 -- Where in the last example @t :: ??@ (i.e. is not an unboxed tuple)
1549 type KindVar = TyVar -- invariant: KindVar will always be a
1550 -- TcTyVar with details MetaTv TauTv ...
1551 -- kind var constructors and functions are in TcType
1553 type SimpleKind = Kind
1558 During kind inference, a kind variable unifies only with
1560 sk ::= * | sk1 -> sk2
1562 data T a = MkT a (T Int#)
1563 fails. We give T the kind (k -> *), and the kind variable k won't unify
1564 with # (the kind of Int#).
1568 When creating a fresh internal type variable, we give it a kind to express
1569 constraints on it. E.g. in (\x->e) we make up a fresh type variable for x,
1572 During unification we only bind an internal type variable to a type
1573 whose kind is lower in the sub-kind hierarchy than the kind of the tyvar.
1575 When unifying two internal type variables, we collect their kind constraints by
1576 finding the GLB of the two. Since the partial order is a tree, they only
1577 have a glb if one is a sub-kind of the other. In that case, we bind the
1578 less-informative one to the more informative one. Neat, eh?