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,
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,
79 -- * Tidying type related things up for printing
81 tidyOpenType, tidyOpenTypes,
82 tidyTyVarBndr, tidyFreeTyVars,
83 tidyOpenTyVar, tidyOpenTyVars,
84 tidyTopType, tidyPred,
88 coreEqType, coreEqType2,
89 tcEqType, tcEqTypes, tcCmpType, tcCmpTypes,
90 tcEqPred, tcEqPredX, tcCmpPred, tcEqTypeX, tcPartOfType, tcPartOfPred,
92 -- * Forcing evaluation of types
95 -- * Other views onto Types
96 coreView, tcView, kindView,
100 -- * Type representation for the code generator
103 typePrimRep, predTypeRep,
105 -- * Main type substitution data types
106 TvSubstEnv, -- Representation widely visible
107 TvSubst(..), -- Representation visible to a few friends
109 -- ** Manipulating type substitutions
110 emptyTvSubstEnv, emptyTvSubst,
112 mkTvSubst, mkOpenTvSubst, zipOpenTvSubst, zipTopTvSubst, mkTopTvSubst, notElemTvSubst,
113 getTvSubstEnv, setTvSubstEnv, zapTvSubstEnv, getTvInScope,
114 extendTvInScope, extendTvInScopeList,
115 extendTvSubst, extendTvSubstList, isInScope, composeTvSubst, zipTyEnv,
118 -- ** Performing substitution on types
119 substTy, substTys, substTyWith, substTysWith, substTheta,
120 substPred, substTyVar, substTyVars, substTyVarBndr, deShadowTy, lookupTyVar,
123 pprType, pprParendType, pprTypeApp, pprTyThingCategory, pprTyThing, pprForAll,
124 pprPred, pprEqPred, pprTheta, pprThetaArrow, pprClassPred, pprKind, pprParendKind,
129 #include "HsVersions.h"
131 -- We import the representation and primitive functions from TypeRep.
132 -- Many things are reexported, but not the representation!
152 import Data.Maybe ( isJust )
156 -- $type_classification
157 -- #type_classification#
161 -- [Unboxed] Iff its representation is other than a pointer
162 -- Unboxed types are also unlifted.
164 -- [Lifted] Iff it has bottom as an element.
165 -- Closures always have lifted types: i.e. any
166 -- let-bound identifier in Core must have a lifted
167 -- type. Operationally, a lifted object is one that
169 -- Only lifted types may be unified with a type variable.
171 -- [Algebraic] Iff it is a type with one or more constructors, whether
172 -- declared with @data@ or @newtype@.
173 -- An algebraic type is one that can be deconstructed
174 -- with a case expression. This is /not/ the same as
175 -- lifted types, because we also include unboxed
176 -- tuples in this classification.
178 -- [Data] Iff it is a type declared with @data@, or a boxed tuple.
180 -- [Primitive] Iff it is a built-in type that can't be expressed in Haskell.
182 -- Currently, all primitive types are unlifted, but that's not necessarily
183 -- the case: for example, @Int@ could be primitive.
185 -- Some primitive types are unboxed, such as @Int#@, whereas some are boxed
186 -- but unlifted (such as @ByteArray#@). The only primitive types that we
187 -- classify as algebraic are the unboxed tuples.
189 -- Some examples of type classifications that may make this a bit clearer are:
192 -- Type primitive boxed lifted algebraic
193 -- -----------------------------------------------------------------------------
195 -- ByteArray# Yes Yes No No
196 -- (\# a, b \#) Yes No No Yes
197 -- ( a, b ) No Yes Yes Yes
198 -- [a] No Yes Yes Yes
201 -- $representation_types
202 -- A /source type/ is a type that is a separate type as far as the type checker is
203 -- concerned, but which has a more low-level representation as far as Core-to-Core
204 -- passes and the rest of the back end is concerned. Notably, 'PredTy's are removed
205 -- from the representation type while they do exist in the source types.
207 -- You don't normally have to worry about this, as the utility functions in
208 -- this module will automatically convert a source into a representation type
209 -- if they are spotted, to the best of it's abilities. If you don't want this
210 -- to happen, use the equivalent functions from the "TcType" module.
213 %************************************************************************
217 %************************************************************************
220 {-# INLINE coreView #-}
221 coreView :: Type -> Maybe Type
222 -- ^ In Core, we \"look through\" non-recursive newtypes and 'PredTypes': this
223 -- function tries to obtain a different view of the supplied type given this
225 -- Strips off the /top layer only/ of a type to give
226 -- its underlying representation type.
227 -- Returns Nothing if there is nothing to look through.
229 -- In the case of @newtype@s, it returns one of:
231 -- 1) A vanilla 'TyConApp' (recursive newtype, or non-saturated)
233 -- 2) The newtype representation (otherwise), meaning the
234 -- type written in the RHS of the newtype declaration,
235 -- which may itself be a newtype
237 -- For example, with:
239 -- > newtype R = MkR S
240 -- > newtype S = MkS T
241 -- > newtype T = MkT (T -> T)
243 -- 'expandNewTcApp' on:
245 -- * @R@ gives @Just S@
246 -- * @S@ gives @Just T@
247 -- * @T@ gives @Nothing@ (no expansion)
249 -- By being non-recursive and inlined, this case analysis gets efficiently
250 -- joined onto the case analysis that the caller is already doing
252 | isEqPred p = Nothing
253 | otherwise = Just (predTypeRep p)
254 coreView (TyConApp tc tys) | Just (tenv, rhs, tys') <- coreExpandTyCon_maybe tc tys
255 = Just (mkAppTys (substTy (mkTopTvSubst tenv) rhs) tys')
256 -- Its important to use mkAppTys, rather than (foldl AppTy),
257 -- because the function part might well return a
258 -- partially-applied type constructor; indeed, usually will!
263 -----------------------------------------------
264 {-# INLINE tcView #-}
265 tcView :: Type -> Maybe Type
266 -- ^ Similar to 'coreView', but for the type checker, which just looks through synonyms
267 tcView (TyConApp tc tys) | Just (tenv, rhs, tys') <- tcExpandTyCon_maybe tc tys
268 = Just (mkAppTys (substTy (mkTopTvSubst tenv) rhs) tys')
271 -----------------------------------------------
272 expandTypeSynonyms :: Type -> Type
273 -- ^ Expand out all type synonyms. Actually, it'd suffice to expand out
274 -- just the ones that discard type variables (e.g. type Funny a = Int)
275 -- But we don't know which those are currently, so we just expand all.
276 expandTypeSynonyms ty
280 | Just (tenv, rhs, tys') <- tcExpandTyCon_maybe tc tys
281 = go (mkAppTys (substTy (mkTopTvSubst tenv) rhs) tys')
283 = TyConApp tc (map go tys)
284 go (TyVarTy tv) = TyVarTy tv
285 go (AppTy t1 t2) = AppTy (go t1) (go t2)
286 go (FunTy t1 t2) = FunTy (go t1) (go t2)
287 go (ForAllTy tv t) = ForAllTy tv (go t)
288 go (PredTy p) = PredTy (go_pred p)
290 go_pred (ClassP c ts) = ClassP c (map go ts)
291 go_pred (IParam ip t) = IParam ip (go t)
292 go_pred (EqPred t1 t2) = EqPred (go t1) (go t2)
294 -----------------------------------------------
295 {-# INLINE kindView #-}
296 kindView :: Kind -> Maybe Kind
297 -- ^ Similar to 'coreView' or 'tcView', but works on 'Kind's
299 -- For the moment, we don't even handle synonyms in kinds
304 %************************************************************************
306 \subsection{Constructor-specific functions}
308 %************************************************************************
311 ---------------------------------------------------------------------
315 mkTyVarTy :: TyVar -> Type
318 mkTyVarTys :: [TyVar] -> [Type]
319 mkTyVarTys = map mkTyVarTy -- a common use of mkTyVarTy
321 -- | Attempts to obtain the type variable underlying a 'Type', and panics with the
322 -- given message if this is not a type variable type. See also 'getTyVar_maybe'
323 getTyVar :: String -> Type -> TyVar
324 getTyVar msg ty = case getTyVar_maybe ty of
326 Nothing -> panic ("getTyVar: " ++ msg)
328 isTyVarTy :: Type -> Bool
329 isTyVarTy ty = isJust (getTyVar_maybe ty)
331 -- | Attempts to obtain the type variable underlying a 'Type'
332 getTyVar_maybe :: Type -> Maybe TyVar
333 getTyVar_maybe ty | Just ty' <- coreView ty = getTyVar_maybe ty'
334 getTyVar_maybe (TyVarTy tv) = Just tv
335 getTyVar_maybe _ = Nothing
340 ---------------------------------------------------------------------
343 We need to be pretty careful with AppTy to make sure we obey the
344 invariant that a TyConApp is always visibly so. mkAppTy maintains the
348 -- | Applies a type to another, as in e.g. @k a@
349 mkAppTy :: Type -> Type -> Type
350 mkAppTy orig_ty1 orig_ty2
353 mk_app (TyConApp tc tys) = mkTyConApp tc (tys ++ [orig_ty2])
354 mk_app _ = AppTy orig_ty1 orig_ty2
355 -- Note that the TyConApp could be an
356 -- under-saturated type synonym. GHC allows that; e.g.
357 -- type Foo k = k a -> k a
359 -- foo :: Foo Id -> Foo Id
361 -- Here Id is partially applied in the type sig for Foo,
362 -- but once the type synonyms are expanded all is well
364 mkAppTys :: Type -> [Type] -> Type
365 mkAppTys orig_ty1 [] = orig_ty1
366 -- This check for an empty list of type arguments
367 -- avoids the needless loss of a type synonym constructor.
368 -- For example: mkAppTys Rational []
369 -- returns to (Ratio Integer), which has needlessly lost
370 -- the Rational part.
371 mkAppTys orig_ty1 orig_tys2
374 mk_app (TyConApp tc tys) = mkTyConApp tc (tys ++ orig_tys2)
375 -- mkTyConApp: see notes with mkAppTy
376 mk_app _ = foldl AppTy orig_ty1 orig_tys2
379 splitAppTy_maybe :: Type -> Maybe (Type, Type)
380 -- ^ Attempt to take a type application apart, whether it is a
381 -- function, type constructor, or plain type application. Note
382 -- that type family applications are NEVER unsaturated by this!
383 splitAppTy_maybe ty | Just ty' <- coreView ty
384 = splitAppTy_maybe ty'
385 splitAppTy_maybe ty = repSplitAppTy_maybe ty
388 repSplitAppTy_maybe :: Type -> Maybe (Type,Type)
389 -- ^ Does the AppTy split as in 'splitAppTy_maybe', but assumes that
390 -- any Core view stuff is already done
391 repSplitAppTy_maybe (FunTy ty1 ty2) = Just (TyConApp funTyCon [ty1], ty2)
392 repSplitAppTy_maybe (AppTy ty1 ty2) = Just (ty1, ty2)
393 repSplitAppTy_maybe (TyConApp tc tys)
394 | isDecomposableTyCon tc || length tys > tyConArity tc
395 = case snocView tys of -- never create unsaturated type family apps
396 Just (tys', ty') -> Just (TyConApp tc tys', ty')
398 repSplitAppTy_maybe _other = Nothing
400 splitAppTy :: Type -> (Type, Type)
401 -- ^ Attempts to take a type application apart, as in 'splitAppTy_maybe',
402 -- and panics if this is not possible
403 splitAppTy ty = case splitAppTy_maybe ty of
405 Nothing -> panic "splitAppTy"
408 splitAppTys :: Type -> (Type, [Type])
409 -- ^ Recursively splits a type as far as is possible, leaving a residual
410 -- type being applied to and the type arguments applied to it. Never fails,
411 -- even if that means returning an empty list of type applications.
412 splitAppTys ty = split ty ty []
414 split orig_ty ty args | Just ty' <- coreView ty = split orig_ty ty' args
415 split _ (AppTy ty arg) args = split ty ty (arg:args)
416 split _ (TyConApp tc tc_args) args
417 = let -- keep type families saturated
418 n | isDecomposableTyCon tc = 0
419 | otherwise = tyConArity tc
420 (tc_args1, tc_args2) = splitAt n tc_args
422 (TyConApp tc tc_args1, tc_args2 ++ args)
423 split _ (FunTy ty1 ty2) args = ASSERT( null args )
424 (TyConApp funTyCon [], [ty1,ty2])
425 split orig_ty _ args = (orig_ty, args)
430 ---------------------------------------------------------------------
435 mkFunTy :: Type -> Type -> Type
436 -- ^ Creates a function type from the given argument and result type
437 mkFunTy arg@(PredTy (EqPred {})) res = ForAllTy (mkWildCoVar arg) res
438 mkFunTy arg res = FunTy arg res
440 mkFunTys :: [Type] -> Type -> Type
441 mkFunTys tys ty = foldr mkFunTy ty tys
443 isFunTy :: Type -> Bool
444 isFunTy ty = isJust (splitFunTy_maybe ty)
446 splitFunTy :: Type -> (Type, Type)
447 -- ^ Attempts to extract the argument and result types from a type, and
448 -- panics if that is not possible. See also 'splitFunTy_maybe'
449 splitFunTy ty | Just ty' <- coreView ty = splitFunTy ty'
450 splitFunTy (FunTy arg res) = (arg, res)
451 splitFunTy other = pprPanic "splitFunTy" (ppr other)
453 splitFunTy_maybe :: Type -> Maybe (Type, Type)
454 -- ^ Attempts to extract the argument and result types from a type
455 splitFunTy_maybe ty | Just ty' <- coreView ty = splitFunTy_maybe ty'
456 splitFunTy_maybe (FunTy arg res) = Just (arg, res)
457 splitFunTy_maybe _ = Nothing
459 splitFunTys :: Type -> ([Type], Type)
460 splitFunTys ty = split [] ty ty
462 split args orig_ty ty | Just ty' <- coreView ty = split args orig_ty ty'
463 split args _ (FunTy arg res) = split (arg:args) res res
464 split args orig_ty _ = (reverse args, orig_ty)
466 splitFunTysN :: Int -> Type -> ([Type], Type)
467 -- ^ Split off exactly the given number argument types, and panics if that is not possible
468 splitFunTysN 0 ty = ([], ty)
469 splitFunTysN n ty = case splitFunTy ty of { (arg, res) ->
470 case splitFunTysN (n-1) res of { (args, res) ->
473 -- | Splits off argument types from the given type and associating
474 -- them with the things in the input list from left to right. The
475 -- final result type is returned, along with the resulting pairs of
476 -- objects and types, albeit with the list of pairs in reverse order.
477 -- Panics if there are not enough argument types for the input list.
478 zipFunTys :: Outputable a => [a] -> Type -> ([(a, Type)], Type)
479 zipFunTys orig_xs orig_ty = split [] orig_xs orig_ty orig_ty
481 split acc [] nty _ = (reverse acc, nty)
483 | Just ty' <- coreView ty = split acc xs nty ty'
484 split acc (x:xs) _ (FunTy arg res) = split ((x,arg):acc) xs res res
485 split _ _ _ _ = pprPanic "zipFunTys" (ppr orig_xs <+> ppr orig_ty)
487 funResultTy :: Type -> Type
488 -- ^ Extract the function result type and panic if that is not possible
489 funResultTy ty | Just ty' <- coreView ty = funResultTy ty'
490 funResultTy (FunTy _arg res) = res
491 funResultTy ty = pprPanic "funResultTy" (ppr ty)
493 funArgTy :: Type -> Type
494 -- ^ Extract the function argument type and panic if that is not possible
495 funArgTy ty | Just ty' <- coreView ty = funArgTy ty'
496 funArgTy (FunTy arg _res) = arg
497 funArgTy ty = pprPanic "funArgTy" (ppr ty)
500 ---------------------------------------------------------------------
505 -- | A key function: builds a 'TyConApp' or 'FunTy' as apppropriate to its arguments.
506 -- Applies its arguments to the constructor from left to right
507 mkTyConApp :: TyCon -> [Type] -> Type
509 | isFunTyCon tycon, [ty1,ty2] <- tys
515 -- | Create the plain type constructor type which has been applied to no type arguments at all.
516 mkTyConTy :: TyCon -> Type
517 mkTyConTy tycon = mkTyConApp tycon []
519 -- splitTyConApp "looks through" synonyms, because they don't
520 -- mean a distinct type, but all other type-constructor applications
521 -- including functions are returned as Just ..
523 -- | The same as @fst . splitTyConApp@
524 tyConAppTyCon :: Type -> TyCon
525 tyConAppTyCon ty = fst (splitTyConApp ty)
527 -- | The same as @snd . splitTyConApp@
528 tyConAppArgs :: Type -> [Type]
529 tyConAppArgs ty = snd (splitTyConApp ty)
531 -- | Attempts to tease a type apart into a type constructor and the application
532 -- of a number of arguments to that constructor. Panics if that is not possible.
533 -- See also 'splitTyConApp_maybe'
534 splitTyConApp :: Type -> (TyCon, [Type])
535 splitTyConApp ty = case splitTyConApp_maybe ty of
537 Nothing -> pprPanic "splitTyConApp" (ppr ty)
539 -- | Attempts to tease a type apart into a type constructor and the application
540 -- of a number of arguments to that constructor
541 splitTyConApp_maybe :: Type -> Maybe (TyCon, [Type])
542 splitTyConApp_maybe ty | Just ty' <- coreView ty = splitTyConApp_maybe ty'
543 splitTyConApp_maybe (TyConApp tc tys) = Just (tc, tys)
544 splitTyConApp_maybe (FunTy arg res) = Just (funTyCon, [arg,res])
545 splitTyConApp_maybe _ = Nothing
547 newTyConInstRhs :: TyCon -> [Type] -> Type
548 -- ^ Unwrap one 'layer' of newtype on a type constructor and its arguments, using an
549 -- eta-reduced version of the @newtype@ if possible
550 newTyConInstRhs tycon tys
551 = ASSERT2( equalLength tvs tys1, ppr tycon $$ ppr tys $$ ppr tvs )
552 mkAppTys (substTyWith tvs tys1 ty) tys2
554 (tvs, ty) = newTyConEtadRhs tycon
555 (tys1, tys2) = splitAtList tvs tys
559 ---------------------------------------------------------------------
563 Notes on type synonyms
564 ~~~~~~~~~~~~~~~~~~~~~~
565 The various "split" functions (splitFunTy, splitRhoTy, splitForAllTy) try
566 to return type synonyms whereever possible. Thus
571 splitFunTys (a -> Foo a) = ([a], Foo a)
574 The reason is that we then get better (shorter) type signatures in
575 interfaces. Notably this plays a role in tcTySigs in TcBinds.lhs.
578 Note [Expanding newtypes]
579 ~~~~~~~~~~~~~~~~~~~~~~~~~
580 When expanding a type to expose a data-type constructor, we need to be
581 careful about newtypes, lest we fall into an infinite loop. Here are
584 newtype Id x = MkId x
585 newtype Fix f = MkFix (f (Fix f))
586 newtype T = MkT (T -> T)
589 --------------------------
591 Fix Maybe Maybe (Fix Maybe)
595 Notice that we can expand T, even though it's recursive.
596 And we can expand Id (Id Int), even though the Id shows up
597 twice at the outer level.
599 So, when expanding, we keep track of when we've seen a recursive
600 newtype at outermost level; and bale out if we see it again.
612 -- 4. All newtypes, including recursive ones, but not newtype families
614 -- It's useful in the back end of the compiler.
615 repType :: Type -> Type
616 -- Only applied to types of kind *; hence tycons are saturated
620 go :: [TyCon] -> Type -> Type
621 go rec_nts ty | Just ty' <- coreView ty -- Expand synonyms
624 go rec_nts (ForAllTy _ ty) -- Look through foralls
627 go rec_nts (TyConApp tc tys) -- Expand newtypes
628 | Just (rec_nts', ty') <- carefullySplitNewType_maybe rec_nts tc tys
634 carefullySplitNewType_maybe :: [TyCon] -> TyCon -> [Type] -> Maybe ([TyCon],Type)
635 -- Return the representation of a newtype, unless
636 -- we've seen it already: see Note [Expanding newtypes]
637 carefullySplitNewType_maybe rec_nts tc tys
639 , not (tc `elem` rec_nts) = Just (rec_nts', newTyConInstRhs tc tys)
640 | otherwise = Nothing
642 rec_nts' | isRecursiveTyCon tc = tc:rec_nts
643 | otherwise = rec_nts
646 -- ToDo: this could be moved to the code generator, using splitTyConApp instead
647 -- of inspecting the type directly.
649 -- | Discovers the primitive representation of a more abstract 'Type'
650 typePrimRep :: Type -> PrimRep
651 typePrimRep ty = case repType ty of
652 TyConApp tc _ -> tyConPrimRep tc
654 AppTy _ _ -> PtrRep -- See note below
656 _ -> pprPanic "typePrimRep" (ppr ty)
657 -- Types of the form 'f a' must be of kind *, not *#, so
658 -- we are guaranteed that they are represented by pointers.
659 -- The reason is that f must have kind *->*, not *->*#, because
660 -- (we claim) there is no way to constrain f's kind any other
665 ---------------------------------------------------------------------
670 mkForAllTy :: TyVar -> Type -> Type
674 -- | Wraps foralls over the type using the provided 'TyVar's from left to right
675 mkForAllTys :: [TyVar] -> Type -> Type
676 mkForAllTys tyvars ty = foldr ForAllTy ty tyvars
678 isForAllTy :: Type -> Bool
679 isForAllTy (ForAllTy _ _) = True
682 -- | Attempts to take a forall type apart, returning the bound type variable
683 -- and the remainder of the type
684 splitForAllTy_maybe :: Type -> Maybe (TyVar, Type)
685 splitForAllTy_maybe ty = splitFAT_m ty
687 splitFAT_m ty | Just ty' <- coreView ty = splitFAT_m ty'
688 splitFAT_m (ForAllTy tyvar ty) = Just(tyvar, ty)
689 splitFAT_m _ = Nothing
691 -- | Attempts to take a forall type apart, returning all the immediate such bound
692 -- type variables and the remainder of the type. Always suceeds, even if that means
693 -- returning an empty list of 'TyVar's
694 splitForAllTys :: Type -> ([TyVar], Type)
695 splitForAllTys ty = split ty ty []
697 split orig_ty ty tvs | Just ty' <- coreView ty = split orig_ty ty' tvs
698 split _ (ForAllTy tv ty) tvs = split ty ty (tv:tvs)
699 split orig_ty _ tvs = (reverse tvs, orig_ty)
701 -- | Equivalent to @snd . splitForAllTys@
702 dropForAlls :: Type -> Type
703 dropForAlls ty = snd (splitForAllTys ty)
706 -- (mkPiType now in CoreUtils)
712 -- | Instantiate a forall type with one or more type arguments.
713 -- Used when we have a polymorphic function applied to type args:
717 -- We use @applyTys type-of-f [t1,t2]@ to compute the type of the expression.
718 -- Panics if no application is possible.
719 applyTy :: Type -> Type -> Type
720 applyTy ty arg | Just ty' <- coreView ty = applyTy ty' arg
721 applyTy (ForAllTy tv ty) arg = substTyWith [tv] [arg] ty
722 applyTy _ _ = panic "applyTy"
724 applyTys :: Type -> [Type] -> Type
725 -- ^ This function is interesting because:
727 -- 1. The function may have more for-alls than there are args
729 -- 2. Less obviously, it may have fewer for-alls
731 -- For case 2. think of:
733 -- > applyTys (forall a.a) [forall b.b, Int]
735 -- This really can happen, via dressing up polymorphic types with newtype
736 -- clothing. Here's an example:
738 -- > newtype R = R (forall a. a->a)
739 -- > foo = case undefined :: R of
742 applyTys ty args = applyTysD empty ty args
744 applyTysD :: SDoc -> Type -> [Type] -> Type -- Debug version
745 applyTysD _ orig_fun_ty [] = orig_fun_ty
746 applyTysD doc orig_fun_ty arg_tys
747 | n_tvs == n_args -- The vastly common case
748 = substTyWith tvs arg_tys rho_ty
749 | n_tvs > n_args -- Too many for-alls
750 = substTyWith (take n_args tvs) arg_tys
751 (mkForAllTys (drop n_args tvs) rho_ty)
752 | otherwise -- Too many type args
753 = ASSERT2( n_tvs > 0, doc $$ ppr orig_fun_ty ) -- Zero case gives infnite loop!
754 applyTysD doc (substTyWith tvs (take n_tvs arg_tys) rho_ty)
757 (tvs, rho_ty) = splitForAllTys orig_fun_ty
759 n_args = length arg_tys
763 %************************************************************************
765 \subsection{Source types}
767 %************************************************************************
769 Source types are always lifted.
771 The key function is predTypeRep which gives the representation of a source type:
774 mkPredTy :: PredType -> Type
775 mkPredTy pred = PredTy pred
777 mkPredTys :: ThetaType -> [Type]
778 mkPredTys preds = map PredTy preds
780 isEqPred :: PredType -> Bool
781 isEqPred (EqPred _ _) = True
784 predTypeRep :: PredType -> Type
785 -- ^ Convert a 'PredType' to its representation type. However, it unwraps
786 -- only the outermost level; for example, the result might be a newtype application
787 predTypeRep (IParam _ ty) = ty
788 predTypeRep (ClassP clas tys) = mkTyConApp (classTyCon clas) tys
789 -- Result might be a newtype application, but the consumer will
790 -- look through that too if necessary
791 predTypeRep (EqPred ty1 ty2) = pprPanic "predTypeRep" (ppr (EqPred ty1 ty2))
793 mkFamilyTyConApp :: TyCon -> [Type] -> Type
794 -- ^ Given a family instance TyCon and its arg types, return the
795 -- corresponding family type. E.g:
798 -- > data instance T (Maybe b) = MkT b
800 -- Where the instance tycon is :RTL, so:
802 -- > mkFamilyTyConApp :RTL Int = T (Maybe Int)
803 mkFamilyTyConApp tc tys
804 | Just (fam_tc, fam_tys) <- tyConFamInst_maybe tc
805 , let fam_subst = zipTopTvSubst (tyConTyVars tc) tys
806 = mkTyConApp fam_tc (substTys fam_subst fam_tys)
810 -- | Pretty prints a 'TyCon', using the family instance in case of a
811 -- representation tycon. For example:
813 -- > data T [a] = ...
815 -- In that case we want to print @T [a]@, where @T@ is the family 'TyCon'
816 pprSourceTyCon :: TyCon -> SDoc
818 | Just (fam_tc, tys) <- tyConFamInst_maybe tycon
819 = ppr $ fam_tc `TyConApp` tys -- can't be FunTyCon
823 isDictTy :: Type -> Bool
824 isDictTy ty = case splitTyConApp_maybe ty of
825 Just (tc, _) -> isClassTyCon tc
830 %************************************************************************
832 The free variables of a type
834 %************************************************************************
837 tyVarsOfType :: Type -> TyVarSet
838 -- ^ NB: for type synonyms tyVarsOfType does /not/ expand the synonym
839 tyVarsOfType (TyVarTy tv) = unitVarSet tv
840 tyVarsOfType (TyConApp _ tys) = tyVarsOfTypes tys
841 tyVarsOfType (PredTy sty) = tyVarsOfPred sty
842 tyVarsOfType (FunTy arg res) = tyVarsOfType arg `unionVarSet` tyVarsOfType res
843 tyVarsOfType (AppTy fun arg) = tyVarsOfType fun `unionVarSet` tyVarsOfType arg
844 tyVarsOfType (ForAllTy tyvar ty) = delVarSet (tyVarsOfType ty) tyvar
846 tyVarsOfTypes :: [Type] -> TyVarSet
847 tyVarsOfTypes tys = foldr (unionVarSet.tyVarsOfType) emptyVarSet tys
849 tyVarsOfPred :: PredType -> TyVarSet
850 tyVarsOfPred (IParam _ ty) = tyVarsOfType ty
851 tyVarsOfPred (ClassP _ tys) = tyVarsOfTypes tys
852 tyVarsOfPred (EqPred ty1 ty2) = tyVarsOfType ty1 `unionVarSet` tyVarsOfType ty2
854 tyVarsOfTheta :: ThetaType -> TyVarSet
855 tyVarsOfTheta = foldr (unionVarSet . tyVarsOfPred) emptyVarSet
859 %************************************************************************
861 \subsection{Type families}
863 %************************************************************************
866 -- | Finds type family instances occuring in a type after expanding synonyms.
867 tyFamInsts :: Type -> [(TyCon, [Type])]
869 | Just exp_ty <- tcView ty = tyFamInsts exp_ty
870 tyFamInsts (TyVarTy _) = []
871 tyFamInsts (TyConApp tc tys)
872 | isOpenSynTyCon tc = [(tc, tys)]
873 | otherwise = concat (map tyFamInsts tys)
874 tyFamInsts (FunTy ty1 ty2) = tyFamInsts ty1 ++ tyFamInsts ty2
875 tyFamInsts (AppTy ty1 ty2) = tyFamInsts ty1 ++ tyFamInsts ty2
876 tyFamInsts (ForAllTy _ ty) = tyFamInsts ty
877 tyFamInsts (PredTy pty) = predFamInsts pty
879 -- | Finds type family instances occuring in a predicate type after expanding
881 predFamInsts :: PredType -> [(TyCon, [Type])]
882 predFamInsts (ClassP _cla tys) = concat (map tyFamInsts tys)
883 predFamInsts (IParam _ ty) = tyFamInsts ty
884 predFamInsts (EqPred ty1 ty2) = tyFamInsts ty1 ++ tyFamInsts ty2
888 %************************************************************************
890 \subsection{TidyType}
892 %************************************************************************
895 -- | This tidies up a type for printing in an error message, or in
896 -- an interface file.
898 -- It doesn't change the uniques at all, just the print names.
899 tidyTyVarBndr :: TidyEnv -> TyVar -> (TidyEnv, TyVar)
900 tidyTyVarBndr env@(tidy_env, subst) tyvar
901 = case tidyOccName tidy_env (getOccName name) of
902 (tidy', occ') -> ((tidy', subst'), tyvar'')
904 subst' = extendVarEnv subst tyvar tyvar''
905 tyvar' = setTyVarName tyvar name'
906 name' = tidyNameOcc name occ'
907 -- Don't forget to tidy the kind for coercions!
908 tyvar'' | isCoVar tyvar = setTyVarKind tyvar' kind'
910 kind' = tidyType env (tyVarKind tyvar)
912 name = tyVarName tyvar
914 tidyFreeTyVars :: TidyEnv -> TyVarSet -> TidyEnv
915 -- ^ Add the free 'TyVar's to the env in tidy form,
916 -- so that we can tidy the type they are free in
917 tidyFreeTyVars env tyvars = fst (tidyOpenTyVars env (varSetElems tyvars))
919 tidyOpenTyVars :: TidyEnv -> [TyVar] -> (TidyEnv, [TyVar])
920 tidyOpenTyVars env tyvars = mapAccumL tidyOpenTyVar env tyvars
922 tidyOpenTyVar :: TidyEnv -> TyVar -> (TidyEnv, TyVar)
923 -- ^ Treat a new 'TyVar' as a binder, and give it a fresh tidy name
924 -- using the environment if one has not already been allocated. See
925 -- also 'tidyTyVarBndr'
926 tidyOpenTyVar env@(_, subst) tyvar
927 = case lookupVarEnv subst tyvar of
928 Just tyvar' -> (env, tyvar') -- Already substituted
929 Nothing -> tidyTyVarBndr env tyvar -- Treat it as a binder
931 tidyType :: TidyEnv -> Type -> Type
932 tidyType env@(_, subst) ty
935 go (TyVarTy tv) = case lookupVarEnv subst tv of
936 Nothing -> TyVarTy tv
937 Just tv' -> TyVarTy tv'
938 go (TyConApp tycon tys) = let args = map go tys
939 in args `seqList` TyConApp tycon args
940 go (PredTy sty) = PredTy (tidyPred env sty)
941 go (AppTy fun arg) = (AppTy $! (go fun)) $! (go arg)
942 go (FunTy fun arg) = (FunTy $! (go fun)) $! (go arg)
943 go (ForAllTy tv ty) = ForAllTy tvp $! (tidyType envp ty)
945 (envp, tvp) = tidyTyVarBndr env tv
947 tidyTypes :: TidyEnv -> [Type] -> [Type]
948 tidyTypes env tys = map (tidyType env) tys
950 tidyPred :: TidyEnv -> PredType -> PredType
951 tidyPred env (IParam n ty) = IParam n (tidyType env ty)
952 tidyPred env (ClassP clas tys) = ClassP clas (tidyTypes env tys)
953 tidyPred env (EqPred ty1 ty2) = EqPred (tidyType env ty1) (tidyType env ty2)
958 -- | Grabs the free type variables, tidies them
959 -- and then uses 'tidyType' to work over the type itself
960 tidyOpenType :: TidyEnv -> Type -> (TidyEnv, Type)
962 = (env', tidyType env' ty)
964 env' = tidyFreeTyVars env (tyVarsOfType ty)
966 tidyOpenTypes :: TidyEnv -> [Type] -> (TidyEnv, [Type])
967 tidyOpenTypes env tys = mapAccumL tidyOpenType env tys
969 -- | Calls 'tidyType' on a top-level type (i.e. with an empty tidying environment)
970 tidyTopType :: Type -> Type
971 tidyTopType ty = tidyType emptyTidyEnv ty
976 tidyKind :: TidyEnv -> Kind -> (TidyEnv, Kind)
977 tidyKind env k = tidyOpenType env k
982 %************************************************************************
984 \subsection{Liftedness}
986 %************************************************************************
989 -- | See "Type#type_classification" for what an unlifted type is
990 isUnLiftedType :: Type -> Bool
991 -- isUnLiftedType returns True for forall'd unlifted types:
992 -- x :: forall a. Int#
993 -- I found bindings like these were getting floated to the top level.
994 -- They are pretty bogus types, mind you. It would be better never to
997 isUnLiftedType ty | Just ty' <- coreView ty = isUnLiftedType ty'
998 isUnLiftedType (ForAllTy _ ty) = isUnLiftedType ty
999 isUnLiftedType (TyConApp tc _) = isUnLiftedTyCon tc
1000 isUnLiftedType _ = False
1002 isUnboxedTupleType :: Type -> Bool
1003 isUnboxedTupleType ty = case splitTyConApp_maybe ty of
1004 Just (tc, _ty_args) -> isUnboxedTupleTyCon tc
1007 -- | See "Type#type_classification" for what an algebraic type is.
1008 -- Should only be applied to /types/, as opposed to e.g. partially
1009 -- saturated type constructors
1010 isAlgType :: Type -> Bool
1012 = case splitTyConApp_maybe ty of
1013 Just (tc, ty_args) -> ASSERT( ty_args `lengthIs` tyConArity tc )
1017 -- | See "Type#type_classification" for what an algebraic type is.
1018 -- Should only be applied to /types/, as opposed to e.g. partially
1019 -- saturated type constructors. Closed type constructors are those
1020 -- with a fixed right hand side, as opposed to e.g. associated types
1021 isClosedAlgType :: Type -> Bool
1023 = case splitTyConApp_maybe ty of
1024 Just (tc, ty_args) -> ASSERT( ty_args `lengthIs` tyConArity tc )
1025 isAlgTyCon tc && not (isOpenTyCon tc)
1030 -- | Computes whether an argument (or let right hand side) should
1031 -- be computed strictly or lazily, based only on its type.
1032 -- Works just like 'isUnLiftedType', except that it has a special case
1033 -- for dictionaries (i.e. does not work purely on representation types)
1035 -- Since it takes account of class 'PredType's, you might think
1036 -- this function should be in 'TcType', but 'isStrictType' is used by 'DataCon',
1037 -- which is below 'TcType' in the hierarchy, so it's convenient to put it here.
1038 isStrictType :: Type -> Bool
1039 isStrictType (PredTy pred) = isStrictPred pred
1040 isStrictType ty | Just ty' <- coreView ty = isStrictType ty'
1041 isStrictType (ForAllTy _ ty) = isStrictType ty
1042 isStrictType (TyConApp tc _) = isUnLiftedTyCon tc
1043 isStrictType _ = False
1045 -- | We may be strict in dictionary types, but only if it
1046 -- has more than one component.
1048 -- (Being strict in a single-component dictionary risks
1049 -- poking the dictionary component, which is wrong.)
1050 isStrictPred :: PredType -> Bool
1051 isStrictPred (ClassP clas _) = opt_DictsStrict && not (isNewTyCon (classTyCon clas))
1052 isStrictPred _ = False
1056 isPrimitiveType :: Type -> Bool
1057 -- ^ Returns true of types that are opaque to Haskell.
1058 -- Most of these are unlifted, but now that we interact with .NET, we
1059 -- may have primtive (foreign-imported) types that are lifted
1060 isPrimitiveType ty = case splitTyConApp_maybe ty of
1061 Just (tc, ty_args) -> ASSERT( ty_args `lengthIs` tyConArity tc )
1067 %************************************************************************
1069 \subsection{Sequencing on types}
1071 %************************************************************************
1074 seqType :: Type -> ()
1075 seqType (TyVarTy tv) = tv `seq` ()
1076 seqType (AppTy t1 t2) = seqType t1 `seq` seqType t2
1077 seqType (FunTy t1 t2) = seqType t1 `seq` seqType t2
1078 seqType (PredTy p) = seqPred p
1079 seqType (TyConApp tc tys) = tc `seq` seqTypes tys
1080 seqType (ForAllTy tv ty) = tv `seq` seqType ty
1082 seqTypes :: [Type] -> ()
1084 seqTypes (ty:tys) = seqType ty `seq` seqTypes tys
1086 seqPred :: PredType -> ()
1087 seqPred (ClassP c tys) = c `seq` seqTypes tys
1088 seqPred (IParam n ty) = n `seq` seqType ty
1089 seqPred (EqPred ty1 ty2) = seqType ty1 `seq` seqType ty2
1093 %************************************************************************
1095 Equality for Core types
1096 (We don't use instances so that we know where it happens)
1098 %************************************************************************
1100 Note that eqType works right even for partial applications of newtypes.
1101 See Note [Newtype eta] in TyCon.lhs
1104 -- | Type equality test for Core types (i.e. ignores predicate-types, synonyms etc.)
1105 coreEqType :: Type -> Type -> Bool
1106 coreEqType t1 t2 = coreEqType2 rn_env t1 t2
1108 rn_env = mkRnEnv2 (mkInScopeSet (tyVarsOfType t1 `unionVarSet` tyVarsOfType t2))
1110 coreEqType2 :: RnEnv2 -> Type -> Type -> Bool
1111 coreEqType2 rn_env t1 t2
1114 eq env (TyVarTy tv1) (TyVarTy tv2) = rnOccL env tv1 == rnOccR env tv2
1115 eq env (ForAllTy tv1 t1) (ForAllTy tv2 t2) = eq (rnBndr2 env tv1 tv2) t1 t2
1116 eq env (AppTy s1 t1) (AppTy s2 t2) = eq env s1 s2 && eq env t1 t2
1117 eq env (FunTy s1 t1) (FunTy s2 t2) = eq env s1 s2 && eq env t1 t2
1118 eq env (TyConApp tc1 tys1) (TyConApp tc2 tys2)
1119 | tc1 == tc2, all2 (eq env) tys1 tys2 = True
1120 -- The lengths should be equal because
1121 -- the two types have the same kind
1122 -- NB: if the type constructors differ that does not
1123 -- necessarily mean that the types aren't equal
1124 -- (synonyms, newtypes)
1125 -- Even if the type constructors are the same, but the arguments
1126 -- differ, the two types could be the same (e.g. if the arg is just
1127 -- ignored in the RHS). In both these cases we fall through to an
1128 -- attempt to expand one side or the other.
1130 -- Now deal with newtypes, synonyms, pred-tys
1131 eq env t1 t2 | Just t1' <- coreView t1 = eq env t1' t2
1132 | Just t2' <- coreView t2 = eq env t1 t2'
1134 -- Fall through case; not equal!
1139 %************************************************************************
1141 Comparision for source types
1142 (We don't use instances so that we know where it happens)
1144 %************************************************************************
1147 tcEqType :: Type -> Type -> Bool
1148 -- ^ Type equality on source types. Does not look through @newtypes@ or
1149 -- 'PredType's, but it does look through type synonyms.
1150 tcEqType t1 t2 = isEqual $ cmpType t1 t2
1152 tcEqTypes :: [Type] -> [Type] -> Bool
1153 tcEqTypes tys1 tys2 = isEqual $ cmpTypes tys1 tys2
1155 tcCmpType :: Type -> Type -> Ordering
1156 -- ^ Type ordering on source types. Does not look through @newtypes@ or
1157 -- 'PredType's, but it does look through type synonyms.
1158 tcCmpType t1 t2 = cmpType t1 t2
1160 tcCmpTypes :: [Type] -> [Type] -> Ordering
1161 tcCmpTypes tys1 tys2 = cmpTypes tys1 tys2
1163 tcEqPred :: PredType -> PredType -> Bool
1164 tcEqPred p1 p2 = isEqual $ cmpPred p1 p2
1166 tcEqPredX :: RnEnv2 -> PredType -> PredType -> Bool
1167 tcEqPredX env p1 p2 = isEqual $ cmpPredX env p1 p2
1169 tcCmpPred :: PredType -> PredType -> Ordering
1170 tcCmpPred p1 p2 = cmpPred p1 p2
1172 tcEqTypeX :: RnEnv2 -> Type -> Type -> Bool
1173 tcEqTypeX env t1 t2 = isEqual $ cmpTypeX env t1 t2
1177 -- | Checks whether the second argument is a subterm of the first. (We don't care
1178 -- about binders, as we are only interested in syntactic subterms.)
1179 tcPartOfType :: Type -> Type -> Bool
1181 | tcEqType t1 t2 = True
1183 | Just t2' <- tcView t2 = tcPartOfType t1 t2'
1184 tcPartOfType _ (TyVarTy _) = False
1185 tcPartOfType t1 (ForAllTy _ t2) = tcPartOfType t1 t2
1186 tcPartOfType t1 (AppTy s2 t2) = tcPartOfType t1 s2 || tcPartOfType t1 t2
1187 tcPartOfType t1 (FunTy s2 t2) = tcPartOfType t1 s2 || tcPartOfType t1 t2
1188 tcPartOfType t1 (PredTy p2) = tcPartOfPred t1 p2
1189 tcPartOfType t1 (TyConApp _ ts) = any (tcPartOfType t1) ts
1191 tcPartOfPred :: Type -> PredType -> Bool
1192 tcPartOfPred t1 (IParam _ t2) = tcPartOfType t1 t2
1193 tcPartOfPred t1 (ClassP _ ts) = any (tcPartOfType t1) ts
1194 tcPartOfPred t1 (EqPred s2 t2) = tcPartOfType t1 s2 || tcPartOfType t1 t2
1197 Now here comes the real worker
1200 cmpType :: Type -> Type -> Ordering
1201 cmpType t1 t2 = cmpTypeX rn_env t1 t2
1203 rn_env = mkRnEnv2 (mkInScopeSet (tyVarsOfType t1 `unionVarSet` tyVarsOfType t2))
1205 cmpTypes :: [Type] -> [Type] -> Ordering
1206 cmpTypes ts1 ts2 = cmpTypesX rn_env ts1 ts2
1208 rn_env = mkRnEnv2 (mkInScopeSet (tyVarsOfTypes ts1 `unionVarSet` tyVarsOfTypes ts2))
1210 cmpPred :: PredType -> PredType -> Ordering
1211 cmpPred p1 p2 = cmpPredX rn_env p1 p2
1213 rn_env = mkRnEnv2 (mkInScopeSet (tyVarsOfPred p1 `unionVarSet` tyVarsOfPred p2))
1215 cmpTypeX :: RnEnv2 -> Type -> Type -> Ordering -- Main workhorse
1216 cmpTypeX env t1 t2 | Just t1' <- tcView t1 = cmpTypeX env t1' t2
1217 | Just t2' <- tcView t2 = cmpTypeX env t1 t2'
1219 cmpTypeX env (TyVarTy tv1) (TyVarTy tv2) = rnOccL env tv1 `compare` rnOccR env tv2
1220 cmpTypeX env (ForAllTy tv1 t1) (ForAllTy tv2 t2) = cmpTypeX (rnBndr2 env tv1 tv2) t1 t2
1221 cmpTypeX env (AppTy s1 t1) (AppTy s2 t2) = cmpTypeX env s1 s2 `thenCmp` cmpTypeX env t1 t2
1222 cmpTypeX env (FunTy s1 t1) (FunTy s2 t2) = cmpTypeX env s1 s2 `thenCmp` cmpTypeX env t1 t2
1223 cmpTypeX env (PredTy p1) (PredTy p2) = cmpPredX env p1 p2
1224 cmpTypeX env (TyConApp tc1 tys1) (TyConApp tc2 tys2) = (tc1 `compare` tc2) `thenCmp` cmpTypesX env tys1 tys2
1226 -- Deal with the rest: TyVarTy < AppTy < FunTy < TyConApp < ForAllTy < PredTy
1227 cmpTypeX _ (AppTy _ _) (TyVarTy _) = GT
1229 cmpTypeX _ (FunTy _ _) (TyVarTy _) = GT
1230 cmpTypeX _ (FunTy _ _) (AppTy _ _) = GT
1232 cmpTypeX _ (TyConApp _ _) (TyVarTy _) = GT
1233 cmpTypeX _ (TyConApp _ _) (AppTy _ _) = GT
1234 cmpTypeX _ (TyConApp _ _) (FunTy _ _) = GT
1236 cmpTypeX _ (ForAllTy _ _) (TyVarTy _) = GT
1237 cmpTypeX _ (ForAllTy _ _) (AppTy _ _) = GT
1238 cmpTypeX _ (ForAllTy _ _) (FunTy _ _) = GT
1239 cmpTypeX _ (ForAllTy _ _) (TyConApp _ _) = GT
1241 cmpTypeX _ (PredTy _) _ = GT
1246 cmpTypesX :: RnEnv2 -> [Type] -> [Type] -> Ordering
1247 cmpTypesX _ [] [] = EQ
1248 cmpTypesX env (t1:tys1) (t2:tys2) = cmpTypeX env t1 t2 `thenCmp` cmpTypesX env tys1 tys2
1249 cmpTypesX _ [] _ = LT
1250 cmpTypesX _ _ [] = GT
1253 cmpPredX :: RnEnv2 -> PredType -> PredType -> Ordering
1254 cmpPredX env (IParam n1 ty1) (IParam n2 ty2) = (n1 `compare` n2) `thenCmp` cmpTypeX env ty1 ty2
1255 -- Compare names only for implicit parameters
1256 -- This comparison is used exclusively (I believe)
1257 -- for the Avails finite map built in TcSimplify
1258 -- If the types differ we keep them distinct so that we see
1259 -- a distinct pair to run improvement on
1260 cmpPredX env (ClassP c1 tys1) (ClassP c2 tys2) = (c1 `compare` c2) `thenCmp` (cmpTypesX env tys1 tys2)
1261 cmpPredX env (EqPred ty1 ty2) (EqPred ty1' ty2') = (cmpTypeX env ty1 ty1') `thenCmp` (cmpTypeX env ty2 ty2')
1263 -- Constructor order: IParam < ClassP < EqPred
1264 cmpPredX _ (IParam {}) _ = LT
1265 cmpPredX _ (ClassP {}) (IParam {}) = GT
1266 cmpPredX _ (ClassP {}) (EqPred {}) = LT
1267 cmpPredX _ (EqPred {}) _ = GT
1270 PredTypes are used as a FM key in TcSimplify,
1271 so we take the easy path and make them an instance of Ord
1274 instance Eq PredType where { (==) = tcEqPred }
1275 instance Ord PredType where { compare = tcCmpPred }
1279 %************************************************************************
1283 %************************************************************************
1286 -- | Type substitution
1288 -- #tvsubst_invariant#
1289 -- The following invariants must hold of a 'TvSubst':
1291 -- 1. The in-scope set is needed /only/ to
1292 -- guide the generation of fresh uniques
1294 -- 2. In particular, the /kind/ of the type variables in
1295 -- the in-scope set is not relevant
1297 -- 3. The substition is only applied ONCE! This is because
1298 -- in general such application will not reached a fixed point.
1300 = TvSubst InScopeSet -- The in-scope type variables
1301 TvSubstEnv -- The substitution itself
1302 -- See Note [Apply Once]
1303 -- and Note [Extending the TvSubstEnv]
1305 {- ----------------------------------------------------------
1309 We use TvSubsts to instantiate things, and we might instantiate
1313 So the substition might go [a->b, b->a]. A similar situation arises in Core
1314 when we find a beta redex like
1315 (/\ a /\ b -> e) b a
1316 Then we also end up with a substition that permutes type variables. Other
1317 variations happen to; for example [a -> (a, b)].
1319 ***************************************************
1320 *** So a TvSubst must be applied precisely once ***
1321 ***************************************************
1323 A TvSubst is not idempotent, but, unlike the non-idempotent substitution
1324 we use during unifications, it must not be repeatedly applied.
1326 Note [Extending the TvSubst]
1327 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1328 See #tvsubst_invariant# for the invariants that must hold.
1330 This invariant allows a short-cut when the TvSubstEnv is empty:
1331 if the TvSubstEnv is empty --- i.e. (isEmptyTvSubt subst) holds ---
1332 then (substTy subst ty) does nothing.
1334 For example, consider:
1335 (/\a. /\b:(a~Int). ...b..) Int
1336 We substitute Int for 'a'. The Unique of 'b' does not change, but
1337 nevertheless we add 'b' to the TvSubstEnv, because b's type does change
1339 This invariant has several crucial consequences:
1341 * In substTyVarBndr, we need extend the TvSubstEnv
1342 - if the unique has changed
1343 - or if the kind has changed
1345 * In substTyVar, we do not need to consult the in-scope set;
1346 the TvSubstEnv is enough
1348 * In substTy, substTheta, we can short-circuit when the TvSubstEnv is empty
1351 -------------------------------------------------------------- -}
1353 -- | A substitition of 'Type's for 'TyVar's
1354 type TvSubstEnv = TyVarEnv Type
1355 -- A TvSubstEnv is used both inside a TvSubst (with the apply-once
1356 -- invariant discussed in Note [Apply Once]), and also independently
1357 -- in the middle of matching, and unification (see Types.Unify)
1358 -- So you have to look at the context to know if it's idempotent or
1359 -- apply-once or whatever
1361 emptyTvSubstEnv :: TvSubstEnv
1362 emptyTvSubstEnv = emptyVarEnv
1364 composeTvSubst :: InScopeSet -> TvSubstEnv -> TvSubstEnv -> TvSubstEnv
1365 -- ^ @(compose env1 env2)(x)@ is @env1(env2(x))@; i.e. apply @env2@ then @env1@.
1366 -- It assumes that both are idempotent.
1367 -- Typically, @env1@ is the refinement to a base substitution @env2@
1368 composeTvSubst in_scope env1 env2
1369 = env1 `plusVarEnv` mapVarEnv (substTy subst1) env2
1370 -- First apply env1 to the range of env2
1371 -- Then combine the two, making sure that env1 loses if
1372 -- both bind the same variable; that's why env1 is the
1373 -- *left* argument to plusVarEnv, because the right arg wins
1375 subst1 = TvSubst in_scope env1
1377 emptyTvSubst :: TvSubst
1378 emptyTvSubst = TvSubst emptyInScopeSet emptyVarEnv
1380 isEmptyTvSubst :: TvSubst -> Bool
1381 -- See Note [Extending the TvSubstEnv]
1382 isEmptyTvSubst (TvSubst _ env) = isEmptyVarEnv env
1384 mkTvSubst :: InScopeSet -> TvSubstEnv -> TvSubst
1387 getTvSubstEnv :: TvSubst -> TvSubstEnv
1388 getTvSubstEnv (TvSubst _ env) = env
1390 getTvInScope :: TvSubst -> InScopeSet
1391 getTvInScope (TvSubst in_scope _) = in_scope
1393 isInScope :: Var -> TvSubst -> Bool
1394 isInScope v (TvSubst in_scope _) = v `elemInScopeSet` in_scope
1396 notElemTvSubst :: TyVar -> TvSubst -> Bool
1397 notElemTvSubst tv (TvSubst _ env) = not (tv `elemVarEnv` env)
1399 setTvSubstEnv :: TvSubst -> TvSubstEnv -> TvSubst
1400 setTvSubstEnv (TvSubst in_scope _) env = TvSubst in_scope env
1402 zapTvSubstEnv :: TvSubst -> TvSubst
1403 zapTvSubstEnv (TvSubst in_scope _) = TvSubst in_scope emptyVarEnv
1405 extendTvInScope :: TvSubst -> Var -> TvSubst
1406 extendTvInScope (TvSubst in_scope env) var = TvSubst (extendInScopeSet in_scope var) env
1408 extendTvInScopeList :: TvSubst -> [Var] -> TvSubst
1409 extendTvInScopeList (TvSubst in_scope env) vars = TvSubst (extendInScopeSetList in_scope vars) env
1411 extendTvSubst :: TvSubst -> TyVar -> Type -> TvSubst
1412 extendTvSubst (TvSubst in_scope env) tv ty = TvSubst in_scope (extendVarEnv env tv ty)
1414 extendTvSubstList :: TvSubst -> [TyVar] -> [Type] -> TvSubst
1415 extendTvSubstList (TvSubst in_scope env) tvs tys
1416 = TvSubst in_scope (extendVarEnvList env (tvs `zip` tys))
1418 -- mkOpenTvSubst and zipOpenTvSubst generate the in-scope set from
1419 -- the types given; but it's just a thunk so with a bit of luck
1420 -- it'll never be evaluated
1422 -- Note [Generating the in-scope set for a substitution]
1423 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1424 -- If we want to substitute [a -> ty1, b -> ty2] I used to
1425 -- think it was enough to generate an in-scope set that includes
1426 -- fv(ty1,ty2). But that's not enough; we really should also take the
1427 -- free vars of the type we are substituting into! Example:
1428 -- (forall b. (a,b,x)) [a -> List b]
1429 -- Then if we use the in-scope set {b}, there is a danger we will rename
1430 -- the forall'd variable to 'x' by mistake, getting this:
1431 -- (forall x. (List b, x, x)
1432 -- Urk! This means looking at all the calls to mkOpenTvSubst....
1435 -- | Generates the in-scope set for the 'TvSubst' from the types in the incoming
1436 -- environment, hence "open"
1437 mkOpenTvSubst :: TvSubstEnv -> TvSubst
1438 mkOpenTvSubst env = TvSubst (mkInScopeSet (tyVarsOfTypes (varEnvElts env))) env
1440 -- | Generates the in-scope set for the 'TvSubst' from the types in the incoming
1441 -- environment, hence "open"
1442 zipOpenTvSubst :: [TyVar] -> [Type] -> TvSubst
1443 zipOpenTvSubst tyvars tys
1444 | debugIsOn && (length tyvars /= length tys)
1445 = pprTrace "zipOpenTvSubst" (ppr tyvars $$ ppr tys) emptyTvSubst
1447 = TvSubst (mkInScopeSet (tyVarsOfTypes tys)) (zipTyEnv tyvars tys)
1449 -- | Called when doing top-level substitutions. Here we expect that the
1450 -- free vars of the range of the substitution will be empty.
1451 mkTopTvSubst :: [(TyVar, Type)] -> TvSubst
1452 mkTopTvSubst prs = TvSubst emptyInScopeSet (mkVarEnv prs)
1454 zipTopTvSubst :: [TyVar] -> [Type] -> TvSubst
1455 zipTopTvSubst tyvars tys
1456 | debugIsOn && (length tyvars /= length tys)
1457 = pprTrace "zipTopTvSubst" (ppr tyvars $$ ppr tys) emptyTvSubst
1459 = TvSubst emptyInScopeSet (zipTyEnv tyvars tys)
1461 zipTyEnv :: [TyVar] -> [Type] -> TvSubstEnv
1463 | debugIsOn && (length tyvars /= length tys)
1464 = pprTrace "mkTopTvSubst" (ppr tyvars $$ ppr tys) emptyVarEnv
1466 = zip_ty_env tyvars tys emptyVarEnv
1468 -- Later substitutions in the list over-ride earlier ones,
1469 -- but there should be no loops
1470 zip_ty_env :: [TyVar] -> [Type] -> TvSubstEnv -> TvSubstEnv
1471 zip_ty_env [] [] env = env
1472 zip_ty_env (tv:tvs) (ty:tys) env = zip_ty_env tvs tys (extendVarEnv env tv ty)
1473 -- There used to be a special case for when
1475 -- (a not-uncommon case) in which case the substitution was dropped.
1476 -- But the type-tidier changes the print-name of a type variable without
1477 -- changing the unique, and that led to a bug. Why? Pre-tidying, we had
1478 -- a type {Foo t}, where Foo is a one-method class. So Foo is really a newtype.
1479 -- And it happened that t was the type variable of the class. Post-tiding,
1480 -- it got turned into {Foo t2}. The ext-core printer expanded this using
1481 -- sourceTypeRep, but that said "Oh, t == t2" because they have the same unique,
1482 -- and so generated a rep type mentioning t not t2.
1484 -- Simplest fix is to nuke the "optimisation"
1485 zip_ty_env tvs tys env = pprTrace "Var/Type length mismatch: " (ppr tvs $$ ppr tys) env
1486 -- zip_ty_env _ _ env = env
1488 instance Outputable TvSubst where
1489 ppr (TvSubst ins env)
1490 = brackets $ sep[ ptext (sLit "TvSubst"),
1491 nest 2 (ptext (sLit "In scope:") <+> ppr ins),
1492 nest 2 (ptext (sLit "Env:") <+> ppr env) ]
1495 %************************************************************************
1497 Performing type substitutions
1499 %************************************************************************
1502 -- | Type substitution making use of an 'TvSubst' that
1503 -- is assumed to be open, see 'zipOpenTvSubst'
1504 substTyWith :: [TyVar] -> [Type] -> Type -> Type
1505 substTyWith tvs tys = ASSERT( length tvs == length tys )
1506 substTy (zipOpenTvSubst tvs tys)
1508 -- | Type substitution making use of an 'TvSubst' that
1509 -- is assumed to be open, see 'zipOpenTvSubst'
1510 substTysWith :: [TyVar] -> [Type] -> [Type] -> [Type]
1511 substTysWith tvs tys = ASSERT( length tvs == length tys )
1512 substTys (zipOpenTvSubst tvs tys)
1514 -- | Substitute within a 'Type'
1515 substTy :: TvSubst -> Type -> Type
1516 substTy subst ty | isEmptyTvSubst subst = ty
1517 | otherwise = subst_ty subst ty
1519 -- | Substitute within several 'Type's
1520 substTys :: TvSubst -> [Type] -> [Type]
1521 substTys subst tys | isEmptyTvSubst subst = tys
1522 | otherwise = map (subst_ty subst) tys
1524 -- | Substitute within a 'ThetaType'
1525 substTheta :: TvSubst -> ThetaType -> ThetaType
1526 substTheta subst theta
1527 | isEmptyTvSubst subst = theta
1528 | otherwise = map (substPred subst) theta
1530 -- | Substitute within a 'PredType'
1531 substPred :: TvSubst -> PredType -> PredType
1532 substPred subst (IParam n ty) = IParam n (subst_ty subst ty)
1533 substPred subst (ClassP clas tys) = ClassP clas (map (subst_ty subst) tys)
1534 substPred subst (EqPred ty1 ty2) = EqPred (subst_ty subst ty1) (subst_ty subst ty2)
1536 -- | Remove any nested binders mentioning the 'TyVar's in the 'TyVarSet'
1537 deShadowTy :: TyVarSet -> Type -> Type
1539 = subst_ty (mkTvSubst in_scope emptyTvSubstEnv) ty
1541 in_scope = mkInScopeSet tvs
1543 subst_ty :: TvSubst -> Type -> Type
1544 -- subst_ty is the main workhorse for type substitution
1546 -- Note that the in_scope set is poked only if we hit a forall
1547 -- so it may often never be fully computed
1551 go (TyVarTy tv) = substTyVar subst tv
1552 go (TyConApp tc tys) = let args = map go tys
1553 in args `seqList` TyConApp tc args
1555 go (PredTy p) = PredTy $! (substPred subst p)
1557 go (FunTy arg res) = (FunTy $! (go arg)) $! (go res)
1558 go (AppTy fun arg) = mkAppTy (go fun) $! (go arg)
1559 -- The mkAppTy smart constructor is important
1560 -- we might be replacing (a Int), represented with App
1561 -- by [Int], represented with TyConApp
1562 go (ForAllTy tv ty) = case substTyVarBndr subst tv of
1564 ForAllTy tv' $! (subst_ty subst' ty)
1566 substTyVar :: TvSubst -> TyVar -> Type
1567 substTyVar subst@(TvSubst _ _) tv
1568 = case lookupTyVar subst tv of {
1569 Nothing -> TyVarTy tv;
1570 Just ty -> ty -- See Note [Apply Once]
1573 substTyVars :: TvSubst -> [TyVar] -> [Type]
1574 substTyVars subst tvs = map (substTyVar subst) tvs
1576 lookupTyVar :: TvSubst -> TyVar -> Maybe Type
1577 -- See Note [Extending the TvSubst]
1578 lookupTyVar (TvSubst _ env) tv = lookupVarEnv env tv
1580 substTyVarBndr :: TvSubst -> TyVar -> (TvSubst, TyVar)
1581 substTyVarBndr subst@(TvSubst in_scope env) old_var
1582 = (TvSubst (in_scope `extendInScopeSet` new_var) new_env, new_var)
1584 is_co_var = isCoVar old_var
1586 new_env | no_change = delVarEnv env old_var
1587 | otherwise = extendVarEnv env old_var (TyVarTy new_var)
1589 no_change = new_var == old_var && not is_co_var
1590 -- no_change means that the new_var is identical in
1591 -- all respects to the old_var (same unique, same kind)
1592 -- See Note [Extending the TvSubst]
1594 -- In that case we don't need to extend the substitution
1595 -- to map old to new. But instead we must zap any
1596 -- current substitution for the variable. For example:
1597 -- (\x.e) with id_subst = [x |-> e']
1598 -- Here we must simply zap the substitution for x
1600 new_var = uniqAway in_scope subst_old_var
1601 -- The uniqAway part makes sure the new variable is not already in scope
1603 subst_old_var -- subst_old_var is old_var with the substitution applied to its kind
1604 -- It's only worth doing the substitution for coercions,
1605 -- becuase only they can have free type variables
1606 | is_co_var = setTyVarKind old_var (substTy subst (tyVarKind old_var))
1607 | otherwise = old_var
1610 ----------------------------------------------------
1619 -- There's a little subtyping at the kind level:
1629 -- Where: \* [LiftedTypeKind] means boxed type
1630 -- \# [UnliftedTypeKind] means unboxed type
1631 -- (\#) [UbxTupleKind] means unboxed tuple
1632 -- ?? [ArgTypeKind] is the lub of {\*, \#}
1633 -- ? [OpenTypeKind] means any type at all
1638 -- > error :: forall a:?. String -> a
1639 -- > (->) :: ?? -> ? -> \*
1640 -- > (\\(x::t) -> ...)
1642 -- Where in the last example @t :: ??@ (i.e. is not an unboxed tuple)
1644 type KindVar = TyVar -- invariant: KindVar will always be a
1645 -- TcTyVar with details MetaTv TauTv ...
1646 -- kind var constructors and functions are in TcType
1648 type SimpleKind = Kind
1653 During kind inference, a kind variable unifies only with
1655 sk ::= * | sk1 -> sk2
1657 data T a = MkT a (T Int#)
1658 fails. We give T the kind (k -> *), and the kind variable k won't unify
1659 with # (the kind of Int#).
1663 When creating a fresh internal type variable, we give it a kind to express
1664 constraints on it. E.g. in (\x->e) we make up a fresh type variable for x,
1667 During unification we only bind an internal type variable to a type
1668 whose kind is lower in the sub-kind hierarchy than the kind of the tyvar.
1670 When unifying two internal type variables, we collect their kind constraints by
1671 finding the GLB of the two. Since the partial order is a tree, they only
1672 have a glb if one is a sub-kind of the other. In that case, we bind the
1673 less-informative one to the more informative one. Neat, eh?