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, typeArity,
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!
144 import BasicTypes ( Arity )
153 import Data.Maybe ( isJust )
157 -- $type_classification
158 -- #type_classification#
162 -- [Unboxed] Iff its representation is other than a pointer
163 -- Unboxed types are also unlifted.
165 -- [Lifted] Iff it has bottom as an element.
166 -- Closures always have lifted types: i.e. any
167 -- let-bound identifier in Core must have a lifted
168 -- type. Operationally, a lifted object is one that
170 -- Only lifted types may be unified with a type variable.
172 -- [Algebraic] Iff it is a type with one or more constructors, whether
173 -- declared with @data@ or @newtype@.
174 -- An algebraic type is one that can be deconstructed
175 -- with a case expression. This is /not/ the same as
176 -- lifted types, because we also include unboxed
177 -- tuples in this classification.
179 -- [Data] Iff it is a type declared with @data@, or a boxed tuple.
181 -- [Primitive] Iff it is a built-in type that can't be expressed in Haskell.
183 -- Currently, all primitive types are unlifted, but that's not necessarily
184 -- the case: for example, @Int@ could be primitive.
186 -- Some primitive types are unboxed, such as @Int#@, whereas some are boxed
187 -- but unlifted (such as @ByteArray#@). The only primitive types that we
188 -- classify as algebraic are the unboxed tuples.
190 -- Some examples of type classifications that may make this a bit clearer are:
193 -- Type primitive boxed lifted algebraic
194 -- -----------------------------------------------------------------------------
196 -- ByteArray# Yes Yes No No
197 -- (\# a, b \#) Yes No No Yes
198 -- ( a, b ) No Yes Yes Yes
199 -- [a] No Yes Yes Yes
202 -- $representation_types
203 -- A /source type/ is a type that is a separate type as far as the type checker is
204 -- concerned, but which has a more low-level representation as far as Core-to-Core
205 -- passes and the rest of the back end is concerned. Notably, 'PredTy's are removed
206 -- from the representation type while they do exist in the source types.
208 -- You don't normally have to worry about this, as the utility functions in
209 -- this module will automatically convert a source into a representation type
210 -- if they are spotted, to the best of it's abilities. If you don't want this
211 -- to happen, use the equivalent functions from the "TcType" module.
214 %************************************************************************
218 %************************************************************************
221 {-# INLINE coreView #-}
222 coreView :: Type -> Maybe Type
223 -- ^ In Core, we \"look through\" non-recursive newtypes and 'PredTypes': this
224 -- function tries to obtain a different view of the supplied type given this
226 -- Strips off the /top layer only/ of a type to give
227 -- its underlying representation type.
228 -- Returns Nothing if there is nothing to look through.
230 -- In the case of @newtype@s, it returns one of:
232 -- 1) A vanilla 'TyConApp' (recursive newtype, or non-saturated)
234 -- 2) The newtype representation (otherwise), meaning the
235 -- type written in the RHS of the newtype declaration,
236 -- which may itself be a newtype
238 -- For example, with:
240 -- > newtype R = MkR S
241 -- > newtype S = MkS T
242 -- > newtype T = MkT (T -> T)
244 -- 'expandNewTcApp' on:
246 -- * @R@ gives @Just S@
247 -- * @S@ gives @Just T@
248 -- * @T@ gives @Nothing@ (no expansion)
250 -- By being non-recursive and inlined, this case analysis gets efficiently
251 -- joined onto the case analysis that the caller is already doing
253 | isEqPred p = Nothing
254 | otherwise = Just (predTypeRep p)
255 coreView (TyConApp tc tys) | Just (tenv, rhs, tys') <- coreExpandTyCon_maybe tc tys
256 = Just (mkAppTys (substTy (mkTopTvSubst tenv) rhs) tys')
257 -- Its important to use mkAppTys, rather than (foldl AppTy),
258 -- because the function part might well return a
259 -- partially-applied type constructor; indeed, usually will!
264 -----------------------------------------------
265 {-# INLINE tcView #-}
266 tcView :: Type -> Maybe Type
267 -- ^ Similar to 'coreView', but for the type checker, which just looks through synonyms
268 tcView (TyConApp tc tys) | Just (tenv, rhs, tys') <- tcExpandTyCon_maybe tc tys
269 = Just (mkAppTys (substTy (mkTopTvSubst tenv) rhs) tys')
272 -----------------------------------------------
273 expandTypeSynonyms :: Type -> Type
274 -- ^ Expand out all type synonyms. Actually, it'd suffice to expand out
275 -- just the ones that discard type variables (e.g. type Funny a = Int)
276 -- But we don't know which those are currently, so we just expand all.
277 expandTypeSynonyms ty
281 | Just (tenv, rhs, tys') <- tcExpandTyCon_maybe tc tys
282 = go (mkAppTys (substTy (mkTopTvSubst tenv) rhs) tys')
284 = TyConApp tc (map go tys)
285 go (TyVarTy tv) = TyVarTy tv
286 go (AppTy t1 t2) = AppTy (go t1) (go t2)
287 go (FunTy t1 t2) = FunTy (go t1) (go t2)
288 go (ForAllTy tv t) = ForAllTy tv (go t)
289 go (PredTy p) = PredTy (go_pred p)
291 go_pred (ClassP c ts) = ClassP c (map go ts)
292 go_pred (IParam ip t) = IParam ip (go t)
293 go_pred (EqPred t1 t2) = EqPred (go t1) (go t2)
295 -----------------------------------------------
296 {-# INLINE kindView #-}
297 kindView :: Kind -> Maybe Kind
298 -- ^ Similar to 'coreView' or 'tcView', but works on 'Kind's
300 -- For the moment, we don't even handle synonyms in kinds
305 %************************************************************************
307 \subsection{Constructor-specific functions}
309 %************************************************************************
312 ---------------------------------------------------------------------
316 mkTyVarTy :: TyVar -> Type
319 mkTyVarTys :: [TyVar] -> [Type]
320 mkTyVarTys = map mkTyVarTy -- a common use of mkTyVarTy
322 -- | Attempts to obtain the type variable underlying a 'Type', and panics with the
323 -- given message if this is not a type variable type. See also 'getTyVar_maybe'
324 getTyVar :: String -> Type -> TyVar
325 getTyVar msg ty = case getTyVar_maybe ty of
327 Nothing -> panic ("getTyVar: " ++ msg)
329 isTyVarTy :: Type -> Bool
330 isTyVarTy ty = isJust (getTyVar_maybe ty)
332 -- | Attempts to obtain the type variable underlying a 'Type'
333 getTyVar_maybe :: Type -> Maybe TyVar
334 getTyVar_maybe ty | Just ty' <- coreView ty = getTyVar_maybe ty'
335 getTyVar_maybe (TyVarTy tv) = Just tv
336 getTyVar_maybe _ = Nothing
341 ---------------------------------------------------------------------
344 We need to be pretty careful with AppTy to make sure we obey the
345 invariant that a TyConApp is always visibly so. mkAppTy maintains the
349 -- | Applies a type to another, as in e.g. @k a@
350 mkAppTy :: Type -> Type -> Type
351 mkAppTy orig_ty1 orig_ty2
354 mk_app (TyConApp tc tys) = mkTyConApp tc (tys ++ [orig_ty2])
355 mk_app _ = AppTy orig_ty1 orig_ty2
356 -- Note that the TyConApp could be an
357 -- under-saturated type synonym. GHC allows that; e.g.
358 -- type Foo k = k a -> k a
360 -- foo :: Foo Id -> Foo Id
362 -- Here Id is partially applied in the type sig for Foo,
363 -- but once the type synonyms are expanded all is well
365 mkAppTys :: Type -> [Type] -> Type
366 mkAppTys orig_ty1 [] = orig_ty1
367 -- This check for an empty list of type arguments
368 -- avoids the needless loss of a type synonym constructor.
369 -- For example: mkAppTys Rational []
370 -- returns to (Ratio Integer), which has needlessly lost
371 -- the Rational part.
372 mkAppTys orig_ty1 orig_tys2
375 mk_app (TyConApp tc tys) = mkTyConApp tc (tys ++ orig_tys2)
376 -- mkTyConApp: see notes with mkAppTy
377 mk_app _ = foldl AppTy orig_ty1 orig_tys2
380 splitAppTy_maybe :: Type -> Maybe (Type, Type)
381 -- ^ Attempt to take a type application apart, whether it is a
382 -- function, type constructor, or plain type application. Note
383 -- that type family applications are NEVER unsaturated by this!
384 splitAppTy_maybe ty | Just ty' <- coreView ty
385 = splitAppTy_maybe ty'
386 splitAppTy_maybe ty = repSplitAppTy_maybe ty
389 repSplitAppTy_maybe :: Type -> Maybe (Type,Type)
390 -- ^ Does the AppTy split as in 'splitAppTy_maybe', but assumes that
391 -- any Core view stuff is already done
392 repSplitAppTy_maybe (FunTy ty1 ty2) = Just (TyConApp funTyCon [ty1], ty2)
393 repSplitAppTy_maybe (AppTy ty1 ty2) = Just (ty1, ty2)
394 repSplitAppTy_maybe (TyConApp tc tys)
395 | isDecomposableTyCon tc || length tys > tyConArity tc
396 = case snocView tys of -- never create unsaturated type family apps
397 Just (tys', ty') -> Just (TyConApp tc tys', ty')
399 repSplitAppTy_maybe _other = Nothing
401 splitAppTy :: Type -> (Type, Type)
402 -- ^ Attempts to take a type application apart, as in 'splitAppTy_maybe',
403 -- and panics if this is not possible
404 splitAppTy ty = case splitAppTy_maybe ty of
406 Nothing -> panic "splitAppTy"
409 splitAppTys :: Type -> (Type, [Type])
410 -- ^ Recursively splits a type as far as is possible, leaving a residual
411 -- type being applied to and the type arguments applied to it. Never fails,
412 -- even if that means returning an empty list of type applications.
413 splitAppTys ty = split ty ty []
415 split orig_ty ty args | Just ty' <- coreView ty = split orig_ty ty' args
416 split _ (AppTy ty arg) args = split ty ty (arg:args)
417 split _ (TyConApp tc tc_args) args
418 = let -- keep type families saturated
419 n | isDecomposableTyCon tc = 0
420 | otherwise = tyConArity tc
421 (tc_args1, tc_args2) = splitAt n tc_args
423 (TyConApp tc tc_args1, tc_args2 ++ args)
424 split _ (FunTy ty1 ty2) args = ASSERT( null args )
425 (TyConApp funTyCon [], [ty1,ty2])
426 split orig_ty _ args = (orig_ty, args)
431 ---------------------------------------------------------------------
436 mkFunTy :: Type -> Type -> Type
437 -- ^ Creates a function type from the given argument and result type
438 mkFunTy arg@(PredTy (EqPred {})) res = ForAllTy (mkWildCoVar arg) res
439 mkFunTy arg res = FunTy arg res
441 mkFunTys :: [Type] -> Type -> Type
442 mkFunTys tys ty = foldr mkFunTy ty tys
444 isFunTy :: Type -> Bool
445 isFunTy ty = isJust (splitFunTy_maybe ty)
447 splitFunTy :: Type -> (Type, Type)
448 -- ^ Attempts to extract the argument and result types from a type, and
449 -- panics if that is not possible. See also 'splitFunTy_maybe'
450 splitFunTy ty | Just ty' <- coreView ty = splitFunTy ty'
451 splitFunTy (FunTy arg res) = (arg, res)
452 splitFunTy other = pprPanic "splitFunTy" (ppr other)
454 splitFunTy_maybe :: Type -> Maybe (Type, Type)
455 -- ^ Attempts to extract the argument and result types from a type
456 splitFunTy_maybe ty | Just ty' <- coreView ty = splitFunTy_maybe ty'
457 splitFunTy_maybe (FunTy arg res) = Just (arg, res)
458 splitFunTy_maybe _ = Nothing
460 splitFunTys :: Type -> ([Type], Type)
461 splitFunTys ty = split [] ty ty
463 split args orig_ty ty | Just ty' <- coreView ty = split args orig_ty ty'
464 split args _ (FunTy arg res) = split (arg:args) res res
465 split args orig_ty _ = (reverse args, orig_ty)
467 splitFunTysN :: Int -> Type -> ([Type], Type)
468 -- ^ Split off exactly the given number argument types, and panics if that is not possible
469 splitFunTysN 0 ty = ([], ty)
470 splitFunTysN n ty = case splitFunTy ty of { (arg, res) ->
471 case splitFunTysN (n-1) res of { (args, res) ->
474 -- | Splits off argument types from the given type and associating
475 -- them with the things in the input list from left to right. The
476 -- final result type is returned, along with the resulting pairs of
477 -- objects and types, albeit with the list of pairs in reverse order.
478 -- Panics if there are not enough argument types for the input list.
479 zipFunTys :: Outputable a => [a] -> Type -> ([(a, Type)], Type)
480 zipFunTys orig_xs orig_ty = split [] orig_xs orig_ty orig_ty
482 split acc [] nty _ = (reverse acc, nty)
484 | Just ty' <- coreView ty = split acc xs nty ty'
485 split acc (x:xs) _ (FunTy arg res) = split ((x,arg):acc) xs res res
486 split _ _ _ _ = pprPanic "zipFunTys" (ppr orig_xs <+> ppr orig_ty)
488 funResultTy :: Type -> Type
489 -- ^ Extract the function result type and panic if that is not possible
490 funResultTy ty | Just ty' <- coreView ty = funResultTy ty'
491 funResultTy (FunTy _arg res) = res
492 funResultTy ty = pprPanic "funResultTy" (ppr ty)
494 funArgTy :: Type -> Type
495 -- ^ Extract the function argument type and panic if that is not possible
496 funArgTy ty | Just ty' <- coreView ty = funArgTy ty'
497 funArgTy (FunTy arg _res) = arg
498 funArgTy ty = pprPanic "funArgTy" (ppr ty)
500 typeArity :: Type -> Arity
501 -- How many value arrows are visible in the type?
502 -- We look through foralls, but not through newtypes, dictionaries etc
503 typeArity ty | Just ty' <- coreView ty = typeArity ty'
504 typeArity (FunTy _ ty) = 1 + typeArity ty
505 typeArity (ForAllTy _ ty) = typeArity ty
509 ---------------------------------------------------------------------
514 -- | A key function: builds a 'TyConApp' or 'FunTy' as apppropriate to its arguments.
515 -- Applies its arguments to the constructor from left to right
516 mkTyConApp :: TyCon -> [Type] -> Type
518 | isFunTyCon tycon, [ty1,ty2] <- tys
524 -- | Create the plain type constructor type which has been applied to no type arguments at all.
525 mkTyConTy :: TyCon -> Type
526 mkTyConTy tycon = mkTyConApp tycon []
528 -- splitTyConApp "looks through" synonyms, because they don't
529 -- mean a distinct type, but all other type-constructor applications
530 -- including functions are returned as Just ..
532 -- | The same as @fst . splitTyConApp@
533 tyConAppTyCon :: Type -> TyCon
534 tyConAppTyCon ty = fst (splitTyConApp ty)
536 -- | The same as @snd . splitTyConApp@
537 tyConAppArgs :: Type -> [Type]
538 tyConAppArgs ty = snd (splitTyConApp ty)
540 -- | Attempts to tease a type apart into a type constructor and the application
541 -- of a number of arguments to that constructor. Panics if that is not possible.
542 -- See also 'splitTyConApp_maybe'
543 splitTyConApp :: Type -> (TyCon, [Type])
544 splitTyConApp ty = case splitTyConApp_maybe ty of
546 Nothing -> pprPanic "splitTyConApp" (ppr ty)
548 -- | Attempts to tease a type apart into a type constructor and the application
549 -- of a number of arguments to that constructor
550 splitTyConApp_maybe :: Type -> Maybe (TyCon, [Type])
551 splitTyConApp_maybe ty | Just ty' <- coreView ty = splitTyConApp_maybe ty'
552 splitTyConApp_maybe (TyConApp tc tys) = Just (tc, tys)
553 splitTyConApp_maybe (FunTy arg res) = Just (funTyCon, [arg,res])
554 splitTyConApp_maybe _ = Nothing
556 newTyConInstRhs :: TyCon -> [Type] -> Type
557 -- ^ Unwrap one 'layer' of newtype on a type constructor and its arguments, using an
558 -- eta-reduced version of the @newtype@ if possible
559 newTyConInstRhs tycon tys
560 = ASSERT2( equalLength tvs tys1, ppr tycon $$ ppr tys $$ ppr tvs )
561 mkAppTys (substTyWith tvs tys1 ty) tys2
563 (tvs, ty) = newTyConEtadRhs tycon
564 (tys1, tys2) = splitAtList tvs tys
568 ---------------------------------------------------------------------
572 Notes on type synonyms
573 ~~~~~~~~~~~~~~~~~~~~~~
574 The various "split" functions (splitFunTy, splitRhoTy, splitForAllTy) try
575 to return type synonyms whereever possible. Thus
580 splitFunTys (a -> Foo a) = ([a], Foo a)
583 The reason is that we then get better (shorter) type signatures in
584 interfaces. Notably this plays a role in tcTySigs in TcBinds.lhs.
587 Note [Expanding newtypes]
588 ~~~~~~~~~~~~~~~~~~~~~~~~~
589 When expanding a type to expose a data-type constructor, we need to be
590 careful about newtypes, lest we fall into an infinite loop. Here are
593 newtype Id x = MkId x
594 newtype Fix f = MkFix (f (Fix f))
595 newtype T = MkT (T -> T)
598 --------------------------
600 Fix Maybe Maybe (Fix Maybe)
604 Notice that we can expand T, even though it's recursive.
605 And we can expand Id (Id Int), even though the Id shows up
606 twice at the outer level.
608 So, when expanding, we keep track of when we've seen a recursive
609 newtype at outermost level; and bale out if we see it again.
621 -- 4. All newtypes, including recursive ones, but not newtype families
623 -- It's useful in the back end of the compiler.
624 repType :: Type -> Type
625 -- Only applied to types of kind *; hence tycons are saturated
629 go :: [TyCon] -> Type -> Type
630 go rec_nts ty | Just ty' <- coreView ty -- Expand synonyms
633 go rec_nts (ForAllTy _ ty) -- Look through foralls
636 go rec_nts (TyConApp tc tys) -- Expand newtypes
637 | Just (rec_nts', ty') <- carefullySplitNewType_maybe rec_nts tc tys
643 carefullySplitNewType_maybe :: [TyCon] -> TyCon -> [Type] -> Maybe ([TyCon],Type)
644 -- Return the representation of a newtype, unless
645 -- we've seen it already: see Note [Expanding newtypes]
646 carefullySplitNewType_maybe rec_nts tc tys
648 , not (tc `elem` rec_nts) = Just (rec_nts', newTyConInstRhs tc tys)
649 | otherwise = Nothing
651 rec_nts' | isRecursiveTyCon tc = tc:rec_nts
652 | otherwise = rec_nts
655 -- ToDo: this could be moved to the code generator, using splitTyConApp instead
656 -- of inspecting the type directly.
658 -- | Discovers the primitive representation of a more abstract 'Type'
659 typePrimRep :: Type -> PrimRep
660 typePrimRep ty = case repType ty of
661 TyConApp tc _ -> tyConPrimRep tc
663 AppTy _ _ -> PtrRep -- See note below
665 _ -> pprPanic "typePrimRep" (ppr ty)
666 -- Types of the form 'f a' must be of kind *, not *#, so
667 -- we are guaranteed that they are represented by pointers.
668 -- The reason is that f must have kind *->*, not *->*#, because
669 -- (we claim) there is no way to constrain f's kind any other
674 ---------------------------------------------------------------------
679 mkForAllTy :: TyVar -> Type -> Type
683 -- | Wraps foralls over the type using the provided 'TyVar's from left to right
684 mkForAllTys :: [TyVar] -> Type -> Type
685 mkForAllTys tyvars ty = foldr ForAllTy ty tyvars
687 isForAllTy :: Type -> Bool
688 isForAllTy (ForAllTy _ _) = True
691 -- | Attempts to take a forall type apart, returning the bound type variable
692 -- and the remainder of the type
693 splitForAllTy_maybe :: Type -> Maybe (TyVar, Type)
694 splitForAllTy_maybe ty = splitFAT_m ty
696 splitFAT_m ty | Just ty' <- coreView ty = splitFAT_m ty'
697 splitFAT_m (ForAllTy tyvar ty) = Just(tyvar, ty)
698 splitFAT_m _ = Nothing
700 -- | Attempts to take a forall type apart, returning all the immediate such bound
701 -- type variables and the remainder of the type. Always suceeds, even if that means
702 -- returning an empty list of 'TyVar's
703 splitForAllTys :: Type -> ([TyVar], Type)
704 splitForAllTys ty = split ty ty []
706 split orig_ty ty tvs | Just ty' <- coreView ty = split orig_ty ty' tvs
707 split _ (ForAllTy tv ty) tvs = split ty ty (tv:tvs)
708 split orig_ty _ tvs = (reverse tvs, orig_ty)
710 -- | Equivalent to @snd . splitForAllTys@
711 dropForAlls :: Type -> Type
712 dropForAlls ty = snd (splitForAllTys ty)
715 -- (mkPiType now in CoreUtils)
721 -- | Instantiate a forall type with one or more type arguments.
722 -- Used when we have a polymorphic function applied to type args:
726 -- We use @applyTys type-of-f [t1,t2]@ to compute the type of the expression.
727 -- Panics if no application is possible.
728 applyTy :: Type -> Type -> Type
729 applyTy ty arg | Just ty' <- coreView ty = applyTy ty' arg
730 applyTy (ForAllTy tv ty) arg = substTyWith [tv] [arg] ty
731 applyTy _ _ = panic "applyTy"
733 applyTys :: Type -> [Type] -> Type
734 -- ^ This function is interesting because:
736 -- 1. The function may have more for-alls than there are args
738 -- 2. Less obviously, it may have fewer for-alls
740 -- For case 2. think of:
742 -- > applyTys (forall a.a) [forall b.b, Int]
744 -- This really can happen, via dressing up polymorphic types with newtype
745 -- clothing. Here's an example:
747 -- > newtype R = R (forall a. a->a)
748 -- > foo = case undefined :: R of
751 applyTys ty args = applyTysD empty ty args
753 applyTysD :: SDoc -> Type -> [Type] -> Type -- Debug version
754 applyTysD _ orig_fun_ty [] = orig_fun_ty
755 applyTysD doc orig_fun_ty arg_tys
756 | n_tvs == n_args -- The vastly common case
757 = substTyWith tvs arg_tys rho_ty
758 | n_tvs > n_args -- Too many for-alls
759 = substTyWith (take n_args tvs) arg_tys
760 (mkForAllTys (drop n_args tvs) rho_ty)
761 | otherwise -- Too many type args
762 = ASSERT2( n_tvs > 0, doc $$ ppr orig_fun_ty ) -- Zero case gives infnite loop!
763 applyTysD doc (substTyWith tvs (take n_tvs arg_tys) rho_ty)
766 (tvs, rho_ty) = splitForAllTys orig_fun_ty
768 n_args = length arg_tys
772 %************************************************************************
774 \subsection{Source types}
776 %************************************************************************
778 Source types are always lifted.
780 The key function is predTypeRep which gives the representation of a source type:
783 mkPredTy :: PredType -> Type
784 mkPredTy pred = PredTy pred
786 mkPredTys :: ThetaType -> [Type]
787 mkPredTys preds = map PredTy preds
789 isEqPred :: PredType -> Bool
790 isEqPred (EqPred _ _) = True
793 predTypeRep :: PredType -> Type
794 -- ^ Convert a 'PredType' to its representation type. However, it unwraps
795 -- only the outermost level; for example, the result might be a newtype application
796 predTypeRep (IParam _ ty) = ty
797 predTypeRep (ClassP clas tys) = mkTyConApp (classTyCon clas) tys
798 -- Result might be a newtype application, but the consumer will
799 -- look through that too if necessary
800 predTypeRep (EqPred ty1 ty2) = pprPanic "predTypeRep" (ppr (EqPred ty1 ty2))
802 mkFamilyTyConApp :: TyCon -> [Type] -> Type
803 -- ^ Given a family instance TyCon and its arg types, return the
804 -- corresponding family type. E.g:
807 -- > data instance T (Maybe b) = MkT b
809 -- Where the instance tycon is :RTL, so:
811 -- > mkFamilyTyConApp :RTL Int = T (Maybe Int)
812 mkFamilyTyConApp tc tys
813 | Just (fam_tc, fam_tys) <- tyConFamInst_maybe tc
814 , let fam_subst = zipTopTvSubst (tyConTyVars tc) tys
815 = mkTyConApp fam_tc (substTys fam_subst fam_tys)
819 -- | Pretty prints a 'TyCon', using the family instance in case of a
820 -- representation tycon. For example:
822 -- > data T [a] = ...
824 -- In that case we want to print @T [a]@, where @T@ is the family 'TyCon'
825 pprSourceTyCon :: TyCon -> SDoc
827 | Just (fam_tc, tys) <- tyConFamInst_maybe tycon
828 = ppr $ fam_tc `TyConApp` tys -- can't be FunTyCon
832 isDictTy :: Type -> Bool
833 isDictTy ty = case splitTyConApp_maybe ty of
834 Just (tc, _) -> isClassTyCon tc
839 %************************************************************************
841 The free variables of a type
843 %************************************************************************
846 tyVarsOfType :: Type -> TyVarSet
847 -- ^ NB: for type synonyms tyVarsOfType does /not/ expand the synonym
848 tyVarsOfType (TyVarTy tv) = unitVarSet tv
849 tyVarsOfType (TyConApp _ tys) = tyVarsOfTypes tys
850 tyVarsOfType (PredTy sty) = tyVarsOfPred sty
851 tyVarsOfType (FunTy arg res) = tyVarsOfType arg `unionVarSet` tyVarsOfType res
852 tyVarsOfType (AppTy fun arg) = tyVarsOfType fun `unionVarSet` tyVarsOfType arg
853 tyVarsOfType (ForAllTy tyvar ty) = delVarSet (tyVarsOfType ty) tyvar
855 tyVarsOfTypes :: [Type] -> TyVarSet
856 tyVarsOfTypes tys = foldr (unionVarSet.tyVarsOfType) emptyVarSet tys
858 tyVarsOfPred :: PredType -> TyVarSet
859 tyVarsOfPred (IParam _ ty) = tyVarsOfType ty
860 tyVarsOfPred (ClassP _ tys) = tyVarsOfTypes tys
861 tyVarsOfPred (EqPred ty1 ty2) = tyVarsOfType ty1 `unionVarSet` tyVarsOfType ty2
863 tyVarsOfTheta :: ThetaType -> TyVarSet
864 tyVarsOfTheta = foldr (unionVarSet . tyVarsOfPred) emptyVarSet
868 %************************************************************************
870 \subsection{Type families}
872 %************************************************************************
875 -- | Finds type family instances occuring in a type after expanding synonyms.
876 tyFamInsts :: Type -> [(TyCon, [Type])]
878 | Just exp_ty <- tcView ty = tyFamInsts exp_ty
879 tyFamInsts (TyVarTy _) = []
880 tyFamInsts (TyConApp tc tys)
881 | isOpenSynTyCon tc = [(tc, tys)]
882 | otherwise = concat (map tyFamInsts tys)
883 tyFamInsts (FunTy ty1 ty2) = tyFamInsts ty1 ++ tyFamInsts ty2
884 tyFamInsts (AppTy ty1 ty2) = tyFamInsts ty1 ++ tyFamInsts ty2
885 tyFamInsts (ForAllTy _ ty) = tyFamInsts ty
886 tyFamInsts (PredTy pty) = predFamInsts pty
888 -- | Finds type family instances occuring in a predicate type after expanding
890 predFamInsts :: PredType -> [(TyCon, [Type])]
891 predFamInsts (ClassP _cla tys) = concat (map tyFamInsts tys)
892 predFamInsts (IParam _ ty) = tyFamInsts ty
893 predFamInsts (EqPred ty1 ty2) = tyFamInsts ty1 ++ tyFamInsts ty2
897 %************************************************************************
899 \subsection{TidyType}
901 %************************************************************************
904 -- | This tidies up a type for printing in an error message, or in
905 -- an interface file.
907 -- It doesn't change the uniques at all, just the print names.
908 tidyTyVarBndr :: TidyEnv -> TyVar -> (TidyEnv, TyVar)
909 tidyTyVarBndr env@(tidy_env, subst) tyvar
910 = case tidyOccName tidy_env (getOccName name) of
911 (tidy', occ') -> ((tidy', subst'), tyvar'')
913 subst' = extendVarEnv subst tyvar tyvar''
914 tyvar' = setTyVarName tyvar name'
915 name' = tidyNameOcc name occ'
916 -- Don't forget to tidy the kind for coercions!
917 tyvar'' | isCoVar tyvar = setTyVarKind tyvar' kind'
919 kind' = tidyType env (tyVarKind tyvar)
921 name = tyVarName tyvar
923 tidyFreeTyVars :: TidyEnv -> TyVarSet -> TidyEnv
924 -- ^ Add the free 'TyVar's to the env in tidy form,
925 -- so that we can tidy the type they are free in
926 tidyFreeTyVars env tyvars = fst (tidyOpenTyVars env (varSetElems tyvars))
928 tidyOpenTyVars :: TidyEnv -> [TyVar] -> (TidyEnv, [TyVar])
929 tidyOpenTyVars env tyvars = mapAccumL tidyOpenTyVar env tyvars
931 tidyOpenTyVar :: TidyEnv -> TyVar -> (TidyEnv, TyVar)
932 -- ^ Treat a new 'TyVar' as a binder, and give it a fresh tidy name
933 -- using the environment if one has not already been allocated. See
934 -- also 'tidyTyVarBndr'
935 tidyOpenTyVar env@(_, subst) tyvar
936 = case lookupVarEnv subst tyvar of
937 Just tyvar' -> (env, tyvar') -- Already substituted
938 Nothing -> tidyTyVarBndr env tyvar -- Treat it as a binder
940 tidyType :: TidyEnv -> Type -> Type
941 tidyType env@(_, subst) ty
944 go (TyVarTy tv) = case lookupVarEnv subst tv of
945 Nothing -> TyVarTy tv
946 Just tv' -> TyVarTy tv'
947 go (TyConApp tycon tys) = let args = map go tys
948 in args `seqList` TyConApp tycon args
949 go (PredTy sty) = PredTy (tidyPred env sty)
950 go (AppTy fun arg) = (AppTy $! (go fun)) $! (go arg)
951 go (FunTy fun arg) = (FunTy $! (go fun)) $! (go arg)
952 go (ForAllTy tv ty) = ForAllTy tvp $! (tidyType envp ty)
954 (envp, tvp) = tidyTyVarBndr env tv
956 tidyTypes :: TidyEnv -> [Type] -> [Type]
957 tidyTypes env tys = map (tidyType env) tys
959 tidyPred :: TidyEnv -> PredType -> PredType
960 tidyPred env (IParam n ty) = IParam n (tidyType env ty)
961 tidyPred env (ClassP clas tys) = ClassP clas (tidyTypes env tys)
962 tidyPred env (EqPred ty1 ty2) = EqPred (tidyType env ty1) (tidyType env ty2)
967 -- | Grabs the free type variables, tidies them
968 -- and then uses 'tidyType' to work over the type itself
969 tidyOpenType :: TidyEnv -> Type -> (TidyEnv, Type)
971 = (env', tidyType env' ty)
973 env' = tidyFreeTyVars env (tyVarsOfType ty)
975 tidyOpenTypes :: TidyEnv -> [Type] -> (TidyEnv, [Type])
976 tidyOpenTypes env tys = mapAccumL tidyOpenType env tys
978 -- | Calls 'tidyType' on a top-level type (i.e. with an empty tidying environment)
979 tidyTopType :: Type -> Type
980 tidyTopType ty = tidyType emptyTidyEnv ty
985 tidyKind :: TidyEnv -> Kind -> (TidyEnv, Kind)
986 tidyKind env k = tidyOpenType env k
991 %************************************************************************
993 \subsection{Liftedness}
995 %************************************************************************
998 -- | See "Type#type_classification" for what an unlifted type is
999 isUnLiftedType :: Type -> Bool
1000 -- isUnLiftedType returns True for forall'd unlifted types:
1001 -- x :: forall a. Int#
1002 -- I found bindings like these were getting floated to the top level.
1003 -- They are pretty bogus types, mind you. It would be better never to
1006 isUnLiftedType ty | Just ty' <- coreView ty = isUnLiftedType ty'
1007 isUnLiftedType (ForAllTy _ ty) = isUnLiftedType ty
1008 isUnLiftedType (TyConApp tc _) = isUnLiftedTyCon tc
1009 isUnLiftedType _ = False
1011 isUnboxedTupleType :: Type -> Bool
1012 isUnboxedTupleType ty = case splitTyConApp_maybe ty of
1013 Just (tc, _ty_args) -> isUnboxedTupleTyCon tc
1016 -- | See "Type#type_classification" for what an algebraic type is.
1017 -- Should only be applied to /types/, as opposed to e.g. partially
1018 -- saturated type constructors
1019 isAlgType :: Type -> Bool
1021 = case splitTyConApp_maybe ty of
1022 Just (tc, ty_args) -> ASSERT( ty_args `lengthIs` tyConArity tc )
1026 -- | See "Type#type_classification" for what an algebraic type is.
1027 -- Should only be applied to /types/, as opposed to e.g. partially
1028 -- saturated type constructors. Closed type constructors are those
1029 -- with a fixed right hand side, as opposed to e.g. associated types
1030 isClosedAlgType :: Type -> Bool
1032 = case splitTyConApp_maybe ty of
1033 Just (tc, ty_args) -> ASSERT( ty_args `lengthIs` tyConArity tc )
1034 isAlgTyCon tc && not (isOpenTyCon tc)
1039 -- | Computes whether an argument (or let right hand side) should
1040 -- be computed strictly or lazily, based only on its type.
1041 -- Works just like 'isUnLiftedType', except that it has a special case
1042 -- for dictionaries (i.e. does not work purely on representation types)
1044 -- Since it takes account of class 'PredType's, you might think
1045 -- this function should be in 'TcType', but 'isStrictType' is used by 'DataCon',
1046 -- which is below 'TcType' in the hierarchy, so it's convenient to put it here.
1047 isStrictType :: Type -> Bool
1048 isStrictType (PredTy pred) = isStrictPred pred
1049 isStrictType ty | Just ty' <- coreView ty = isStrictType ty'
1050 isStrictType (ForAllTy _ ty) = isStrictType ty
1051 isStrictType (TyConApp tc _) = isUnLiftedTyCon tc
1052 isStrictType _ = False
1054 -- | We may be strict in dictionary types, but only if it
1055 -- has more than one component.
1057 -- (Being strict in a single-component dictionary risks
1058 -- poking the dictionary component, which is wrong.)
1059 isStrictPred :: PredType -> Bool
1060 isStrictPred (ClassP clas _) = opt_DictsStrict && not (isNewTyCon (classTyCon clas))
1061 isStrictPred _ = False
1065 isPrimitiveType :: Type -> Bool
1066 -- ^ Returns true of types that are opaque to Haskell.
1067 -- Most of these are unlifted, but now that we interact with .NET, we
1068 -- may have primtive (foreign-imported) types that are lifted
1069 isPrimitiveType ty = case splitTyConApp_maybe ty of
1070 Just (tc, ty_args) -> ASSERT( ty_args `lengthIs` tyConArity tc )
1076 %************************************************************************
1078 \subsection{Sequencing on types}
1080 %************************************************************************
1083 seqType :: Type -> ()
1084 seqType (TyVarTy tv) = tv `seq` ()
1085 seqType (AppTy t1 t2) = seqType t1 `seq` seqType t2
1086 seqType (FunTy t1 t2) = seqType t1 `seq` seqType t2
1087 seqType (PredTy p) = seqPred p
1088 seqType (TyConApp tc tys) = tc `seq` seqTypes tys
1089 seqType (ForAllTy tv ty) = tv `seq` seqType ty
1091 seqTypes :: [Type] -> ()
1093 seqTypes (ty:tys) = seqType ty `seq` seqTypes tys
1095 seqPred :: PredType -> ()
1096 seqPred (ClassP c tys) = c `seq` seqTypes tys
1097 seqPred (IParam n ty) = n `seq` seqType ty
1098 seqPred (EqPred ty1 ty2) = seqType ty1 `seq` seqType ty2
1102 %************************************************************************
1104 Equality for Core types
1105 (We don't use instances so that we know where it happens)
1107 %************************************************************************
1109 Note that eqType works right even for partial applications of newtypes.
1110 See Note [Newtype eta] in TyCon.lhs
1113 -- | Type equality test for Core types (i.e. ignores predicate-types, synonyms etc.)
1114 coreEqType :: Type -> Type -> Bool
1115 coreEqType t1 t2 = coreEqType2 rn_env t1 t2
1117 rn_env = mkRnEnv2 (mkInScopeSet (tyVarsOfType t1 `unionVarSet` tyVarsOfType t2))
1119 coreEqType2 :: RnEnv2 -> Type -> Type -> Bool
1120 coreEqType2 rn_env t1 t2
1123 eq env (TyVarTy tv1) (TyVarTy tv2) = rnOccL env tv1 == rnOccR env tv2
1124 eq env (ForAllTy tv1 t1) (ForAllTy tv2 t2) = eq (rnBndr2 env tv1 tv2) t1 t2
1125 eq env (AppTy s1 t1) (AppTy s2 t2) = eq env s1 s2 && eq env t1 t2
1126 eq env (FunTy s1 t1) (FunTy s2 t2) = eq env s1 s2 && eq env t1 t2
1127 eq env (TyConApp tc1 tys1) (TyConApp tc2 tys2)
1128 | tc1 == tc2, all2 (eq env) tys1 tys2 = True
1129 -- The lengths should be equal because
1130 -- the two types have the same kind
1131 -- NB: if the type constructors differ that does not
1132 -- necessarily mean that the types aren't equal
1133 -- (synonyms, newtypes)
1134 -- Even if the type constructors are the same, but the arguments
1135 -- differ, the two types could be the same (e.g. if the arg is just
1136 -- ignored in the RHS). In both these cases we fall through to an
1137 -- attempt to expand one side or the other.
1139 -- Now deal with newtypes, synonyms, pred-tys
1140 eq env t1 t2 | Just t1' <- coreView t1 = eq env t1' t2
1141 | Just t2' <- coreView t2 = eq env t1 t2'
1143 -- Fall through case; not equal!
1148 %************************************************************************
1150 Comparision for source types
1151 (We don't use instances so that we know where it happens)
1153 %************************************************************************
1156 tcEqType :: Type -> Type -> Bool
1157 -- ^ Type equality on source types. Does not look through @newtypes@ or
1158 -- 'PredType's, but it does look through type synonyms.
1159 tcEqType t1 t2 = isEqual $ cmpType t1 t2
1161 tcEqTypes :: [Type] -> [Type] -> Bool
1162 tcEqTypes tys1 tys2 = isEqual $ cmpTypes tys1 tys2
1164 tcCmpType :: Type -> Type -> Ordering
1165 -- ^ Type ordering on source types. Does not look through @newtypes@ or
1166 -- 'PredType's, but it does look through type synonyms.
1167 tcCmpType t1 t2 = cmpType t1 t2
1169 tcCmpTypes :: [Type] -> [Type] -> Ordering
1170 tcCmpTypes tys1 tys2 = cmpTypes tys1 tys2
1172 tcEqPred :: PredType -> PredType -> Bool
1173 tcEqPred p1 p2 = isEqual $ cmpPred p1 p2
1175 tcEqPredX :: RnEnv2 -> PredType -> PredType -> Bool
1176 tcEqPredX env p1 p2 = isEqual $ cmpPredX env p1 p2
1178 tcCmpPred :: PredType -> PredType -> Ordering
1179 tcCmpPred p1 p2 = cmpPred p1 p2
1181 tcEqTypeX :: RnEnv2 -> Type -> Type -> Bool
1182 tcEqTypeX env t1 t2 = isEqual $ cmpTypeX env t1 t2
1186 -- | Checks whether the second argument is a subterm of the first. (We don't care
1187 -- about binders, as we are only interested in syntactic subterms.)
1188 tcPartOfType :: Type -> Type -> Bool
1190 | tcEqType t1 t2 = True
1192 | Just t2' <- tcView t2 = tcPartOfType t1 t2'
1193 tcPartOfType _ (TyVarTy _) = False
1194 tcPartOfType t1 (ForAllTy _ t2) = tcPartOfType t1 t2
1195 tcPartOfType t1 (AppTy s2 t2) = tcPartOfType t1 s2 || tcPartOfType t1 t2
1196 tcPartOfType t1 (FunTy s2 t2) = tcPartOfType t1 s2 || tcPartOfType t1 t2
1197 tcPartOfType t1 (PredTy p2) = tcPartOfPred t1 p2
1198 tcPartOfType t1 (TyConApp _ ts) = any (tcPartOfType t1) ts
1200 tcPartOfPred :: Type -> PredType -> Bool
1201 tcPartOfPred t1 (IParam _ t2) = tcPartOfType t1 t2
1202 tcPartOfPred t1 (ClassP _ ts) = any (tcPartOfType t1) ts
1203 tcPartOfPred t1 (EqPred s2 t2) = tcPartOfType t1 s2 || tcPartOfType t1 t2
1206 Now here comes the real worker
1209 cmpType :: Type -> Type -> Ordering
1210 cmpType t1 t2 = cmpTypeX rn_env t1 t2
1212 rn_env = mkRnEnv2 (mkInScopeSet (tyVarsOfType t1 `unionVarSet` tyVarsOfType t2))
1214 cmpTypes :: [Type] -> [Type] -> Ordering
1215 cmpTypes ts1 ts2 = cmpTypesX rn_env ts1 ts2
1217 rn_env = mkRnEnv2 (mkInScopeSet (tyVarsOfTypes ts1 `unionVarSet` tyVarsOfTypes ts2))
1219 cmpPred :: PredType -> PredType -> Ordering
1220 cmpPred p1 p2 = cmpPredX rn_env p1 p2
1222 rn_env = mkRnEnv2 (mkInScopeSet (tyVarsOfPred p1 `unionVarSet` tyVarsOfPred p2))
1224 cmpTypeX :: RnEnv2 -> Type -> Type -> Ordering -- Main workhorse
1225 cmpTypeX env t1 t2 | Just t1' <- tcView t1 = cmpTypeX env t1' t2
1226 | Just t2' <- tcView t2 = cmpTypeX env t1 t2'
1228 cmpTypeX env (TyVarTy tv1) (TyVarTy tv2) = rnOccL env tv1 `compare` rnOccR env tv2
1229 cmpTypeX env (ForAllTy tv1 t1) (ForAllTy tv2 t2) = cmpTypeX (rnBndr2 env tv1 tv2) t1 t2
1230 cmpTypeX env (AppTy s1 t1) (AppTy s2 t2) = cmpTypeX env s1 s2 `thenCmp` cmpTypeX env t1 t2
1231 cmpTypeX env (FunTy s1 t1) (FunTy s2 t2) = cmpTypeX env s1 s2 `thenCmp` cmpTypeX env t1 t2
1232 cmpTypeX env (PredTy p1) (PredTy p2) = cmpPredX env p1 p2
1233 cmpTypeX env (TyConApp tc1 tys1) (TyConApp tc2 tys2) = (tc1 `compare` tc2) `thenCmp` cmpTypesX env tys1 tys2
1235 -- Deal with the rest: TyVarTy < AppTy < FunTy < TyConApp < ForAllTy < PredTy
1236 cmpTypeX _ (AppTy _ _) (TyVarTy _) = GT
1238 cmpTypeX _ (FunTy _ _) (TyVarTy _) = GT
1239 cmpTypeX _ (FunTy _ _) (AppTy _ _) = GT
1241 cmpTypeX _ (TyConApp _ _) (TyVarTy _) = GT
1242 cmpTypeX _ (TyConApp _ _) (AppTy _ _) = GT
1243 cmpTypeX _ (TyConApp _ _) (FunTy _ _) = GT
1245 cmpTypeX _ (ForAllTy _ _) (TyVarTy _) = GT
1246 cmpTypeX _ (ForAllTy _ _) (AppTy _ _) = GT
1247 cmpTypeX _ (ForAllTy _ _) (FunTy _ _) = GT
1248 cmpTypeX _ (ForAllTy _ _) (TyConApp _ _) = GT
1250 cmpTypeX _ (PredTy _) _ = GT
1255 cmpTypesX :: RnEnv2 -> [Type] -> [Type] -> Ordering
1256 cmpTypesX _ [] [] = EQ
1257 cmpTypesX env (t1:tys1) (t2:tys2) = cmpTypeX env t1 t2 `thenCmp` cmpTypesX env tys1 tys2
1258 cmpTypesX _ [] _ = LT
1259 cmpTypesX _ _ [] = GT
1262 cmpPredX :: RnEnv2 -> PredType -> PredType -> Ordering
1263 cmpPredX env (IParam n1 ty1) (IParam n2 ty2) = (n1 `compare` n2) `thenCmp` cmpTypeX env ty1 ty2
1264 -- Compare names only for implicit parameters
1265 -- This comparison is used exclusively (I believe)
1266 -- for the Avails finite map built in TcSimplify
1267 -- If the types differ we keep them distinct so that we see
1268 -- a distinct pair to run improvement on
1269 cmpPredX env (ClassP c1 tys1) (ClassP c2 tys2) = (c1 `compare` c2) `thenCmp` (cmpTypesX env tys1 tys2)
1270 cmpPredX env (EqPred ty1 ty2) (EqPred ty1' ty2') = (cmpTypeX env ty1 ty1') `thenCmp` (cmpTypeX env ty2 ty2')
1272 -- Constructor order: IParam < ClassP < EqPred
1273 cmpPredX _ (IParam {}) _ = LT
1274 cmpPredX _ (ClassP {}) (IParam {}) = GT
1275 cmpPredX _ (ClassP {}) (EqPred {}) = LT
1276 cmpPredX _ (EqPred {}) _ = GT
1279 PredTypes are used as a FM key in TcSimplify,
1280 so we take the easy path and make them an instance of Ord
1283 instance Eq PredType where { (==) = tcEqPred }
1284 instance Ord PredType where { compare = tcCmpPred }
1288 %************************************************************************
1292 %************************************************************************
1295 -- | Type substitution
1297 -- #tvsubst_invariant#
1298 -- The following invariants must hold of a 'TvSubst':
1300 -- 1. The in-scope set is needed /only/ to
1301 -- guide the generation of fresh uniques
1303 -- 2. In particular, the /kind/ of the type variables in
1304 -- the in-scope set is not relevant
1306 -- 3. The substition is only applied ONCE! This is because
1307 -- in general such application will not reached a fixed point.
1309 = TvSubst InScopeSet -- The in-scope type variables
1310 TvSubstEnv -- The substitution itself
1311 -- See Note [Apply Once]
1312 -- and Note [Extending the TvSubstEnv]
1314 {- ----------------------------------------------------------
1318 We use TvSubsts to instantiate things, and we might instantiate
1322 So the substition might go [a->b, b->a]. A similar situation arises in Core
1323 when we find a beta redex like
1324 (/\ a /\ b -> e) b a
1325 Then we also end up with a substition that permutes type variables. Other
1326 variations happen to; for example [a -> (a, b)].
1328 ***************************************************
1329 *** So a TvSubst must be applied precisely once ***
1330 ***************************************************
1332 A TvSubst is not idempotent, but, unlike the non-idempotent substitution
1333 we use during unifications, it must not be repeatedly applied.
1335 Note [Extending the TvSubst]
1336 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1337 See #tvsubst_invariant# for the invariants that must hold.
1339 This invariant allows a short-cut when the TvSubstEnv is empty:
1340 if the TvSubstEnv is empty --- i.e. (isEmptyTvSubt subst) holds ---
1341 then (substTy subst ty) does nothing.
1343 For example, consider:
1344 (/\a. /\b:(a~Int). ...b..) Int
1345 We substitute Int for 'a'. The Unique of 'b' does not change, but
1346 nevertheless we add 'b' to the TvSubstEnv, because b's kind does change
1348 This invariant has several crucial consequences:
1350 * In substTyVarBndr, we need extend the TvSubstEnv
1351 - if the unique has changed
1352 - or if the kind has changed
1354 * In substTyVar, we do not need to consult the in-scope set;
1355 the TvSubstEnv is enough
1357 * In substTy, substTheta, we can short-circuit when the TvSubstEnv is empty
1360 -------------------------------------------------------------- -}
1362 -- | A substitition of 'Type's for 'TyVar's
1363 type TvSubstEnv = TyVarEnv Type
1364 -- A TvSubstEnv is used both inside a TvSubst (with the apply-once
1365 -- invariant discussed in Note [Apply Once]), and also independently
1366 -- in the middle of matching, and unification (see Types.Unify)
1367 -- So you have to look at the context to know if it's idempotent or
1368 -- apply-once or whatever
1370 emptyTvSubstEnv :: TvSubstEnv
1371 emptyTvSubstEnv = emptyVarEnv
1373 composeTvSubst :: InScopeSet -> TvSubstEnv -> TvSubstEnv -> TvSubstEnv
1374 -- ^ @(compose env1 env2)(x)@ is @env1(env2(x))@; i.e. apply @env2@ then @env1@.
1375 -- It assumes that both are idempotent.
1376 -- Typically, @env1@ is the refinement to a base substitution @env2@
1377 composeTvSubst in_scope env1 env2
1378 = env1 `plusVarEnv` mapVarEnv (substTy subst1) env2
1379 -- First apply env1 to the range of env2
1380 -- Then combine the two, making sure that env1 loses if
1381 -- both bind the same variable; that's why env1 is the
1382 -- *left* argument to plusVarEnv, because the right arg wins
1384 subst1 = TvSubst in_scope env1
1386 emptyTvSubst :: TvSubst
1387 emptyTvSubst = TvSubst emptyInScopeSet emptyVarEnv
1389 isEmptyTvSubst :: TvSubst -> Bool
1390 -- See Note [Extending the TvSubstEnv]
1391 isEmptyTvSubst (TvSubst _ env) = isEmptyVarEnv env
1393 mkTvSubst :: InScopeSet -> TvSubstEnv -> TvSubst
1396 getTvSubstEnv :: TvSubst -> TvSubstEnv
1397 getTvSubstEnv (TvSubst _ env) = env
1399 getTvInScope :: TvSubst -> InScopeSet
1400 getTvInScope (TvSubst in_scope _) = in_scope
1402 isInScope :: Var -> TvSubst -> Bool
1403 isInScope v (TvSubst in_scope _) = v `elemInScopeSet` in_scope
1405 notElemTvSubst :: TyVar -> TvSubst -> Bool
1406 notElemTvSubst tv (TvSubst _ env) = not (tv `elemVarEnv` env)
1408 setTvSubstEnv :: TvSubst -> TvSubstEnv -> TvSubst
1409 setTvSubstEnv (TvSubst in_scope _) env = TvSubst in_scope env
1411 zapTvSubstEnv :: TvSubst -> TvSubst
1412 zapTvSubstEnv (TvSubst in_scope _) = TvSubst in_scope emptyVarEnv
1414 extendTvInScope :: TvSubst -> Var -> TvSubst
1415 extendTvInScope (TvSubst in_scope env) var = TvSubst (extendInScopeSet in_scope var) env
1417 extendTvInScopeList :: TvSubst -> [Var] -> TvSubst
1418 extendTvInScopeList (TvSubst in_scope env) vars = TvSubst (extendInScopeSetList in_scope vars) env
1420 extendTvSubst :: TvSubst -> TyVar -> Type -> TvSubst
1421 extendTvSubst (TvSubst in_scope env) tv ty = TvSubst in_scope (extendVarEnv env tv ty)
1423 extendTvSubstList :: TvSubst -> [TyVar] -> [Type] -> TvSubst
1424 extendTvSubstList (TvSubst in_scope env) tvs tys
1425 = TvSubst in_scope (extendVarEnvList env (tvs `zip` tys))
1427 -- mkOpenTvSubst and zipOpenTvSubst generate the in-scope set from
1428 -- the types given; but it's just a thunk so with a bit of luck
1429 -- it'll never be evaluated
1431 -- Note [Generating the in-scope set for a substitution]
1432 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1433 -- If we want to substitute [a -> ty1, b -> ty2] I used to
1434 -- think it was enough to generate an in-scope set that includes
1435 -- fv(ty1,ty2). But that's not enough; we really should also take the
1436 -- free vars of the type we are substituting into! Example:
1437 -- (forall b. (a,b,x)) [a -> List b]
1438 -- Then if we use the in-scope set {b}, there is a danger we will rename
1439 -- the forall'd variable to 'x' by mistake, getting this:
1440 -- (forall x. (List b, x, x)
1441 -- Urk! This means looking at all the calls to mkOpenTvSubst....
1444 -- | Generates the in-scope set for the 'TvSubst' from the types in the incoming
1445 -- environment, hence "open"
1446 mkOpenTvSubst :: TvSubstEnv -> TvSubst
1447 mkOpenTvSubst env = TvSubst (mkInScopeSet (tyVarsOfTypes (varEnvElts env))) env
1449 -- | Generates the in-scope set for the 'TvSubst' from the types in the incoming
1450 -- environment, hence "open"
1451 zipOpenTvSubst :: [TyVar] -> [Type] -> TvSubst
1452 zipOpenTvSubst tyvars tys
1453 | debugIsOn && (length tyvars /= length tys)
1454 = pprTrace "zipOpenTvSubst" (ppr tyvars $$ ppr tys) emptyTvSubst
1456 = TvSubst (mkInScopeSet (tyVarsOfTypes tys)) (zipTyEnv tyvars tys)
1458 -- | Called when doing top-level substitutions. Here we expect that the
1459 -- free vars of the range of the substitution will be empty.
1460 mkTopTvSubst :: [(TyVar, Type)] -> TvSubst
1461 mkTopTvSubst prs = TvSubst emptyInScopeSet (mkVarEnv prs)
1463 zipTopTvSubst :: [TyVar] -> [Type] -> TvSubst
1464 zipTopTvSubst tyvars tys
1465 | debugIsOn && (length tyvars /= length tys)
1466 = pprTrace "zipTopTvSubst" (ppr tyvars $$ ppr tys) emptyTvSubst
1468 = TvSubst emptyInScopeSet (zipTyEnv tyvars tys)
1470 zipTyEnv :: [TyVar] -> [Type] -> TvSubstEnv
1472 | debugIsOn && (length tyvars /= length tys)
1473 = pprTrace "mkTopTvSubst" (ppr tyvars $$ ppr tys) emptyVarEnv
1475 = zip_ty_env tyvars tys emptyVarEnv
1477 -- Later substitutions in the list over-ride earlier ones,
1478 -- but there should be no loops
1479 zip_ty_env :: [TyVar] -> [Type] -> TvSubstEnv -> TvSubstEnv
1480 zip_ty_env [] [] env = env
1481 zip_ty_env (tv:tvs) (ty:tys) env = zip_ty_env tvs tys (extendVarEnv env tv ty)
1482 -- There used to be a special case for when
1484 -- (a not-uncommon case) in which case the substitution was dropped.
1485 -- But the type-tidier changes the print-name of a type variable without
1486 -- changing the unique, and that led to a bug. Why? Pre-tidying, we had
1487 -- a type {Foo t}, where Foo is a one-method class. So Foo is really a newtype.
1488 -- And it happened that t was the type variable of the class. Post-tiding,
1489 -- it got turned into {Foo t2}. The ext-core printer expanded this using
1490 -- sourceTypeRep, but that said "Oh, t == t2" because they have the same unique,
1491 -- and so generated a rep type mentioning t not t2.
1493 -- Simplest fix is to nuke the "optimisation"
1494 zip_ty_env tvs tys env = pprTrace "Var/Type length mismatch: " (ppr tvs $$ ppr tys) env
1495 -- zip_ty_env _ _ env = env
1497 instance Outputable TvSubst where
1498 ppr (TvSubst ins env)
1499 = brackets $ sep[ ptext (sLit "TvSubst"),
1500 nest 2 (ptext (sLit "In scope:") <+> ppr ins),
1501 nest 2 (ptext (sLit "Env:") <+> ppr env) ]
1504 %************************************************************************
1506 Performing type substitutions
1508 %************************************************************************
1511 -- | Type substitution making use of an 'TvSubst' that
1512 -- is assumed to be open, see 'zipOpenTvSubst'
1513 substTyWith :: [TyVar] -> [Type] -> Type -> Type
1514 substTyWith tvs tys = ASSERT( length tvs == length tys )
1515 substTy (zipOpenTvSubst tvs tys)
1517 -- | Type substitution making use of an 'TvSubst' that
1518 -- is assumed to be open, see 'zipOpenTvSubst'
1519 substTysWith :: [TyVar] -> [Type] -> [Type] -> [Type]
1520 substTysWith tvs tys = ASSERT( length tvs == length tys )
1521 substTys (zipOpenTvSubst tvs tys)
1523 -- | Substitute within a 'Type'
1524 substTy :: TvSubst -> Type -> Type
1525 substTy subst ty | isEmptyTvSubst subst = ty
1526 | otherwise = subst_ty subst ty
1528 -- | Substitute within several 'Type's
1529 substTys :: TvSubst -> [Type] -> [Type]
1530 substTys subst tys | isEmptyTvSubst subst = tys
1531 | otherwise = map (subst_ty subst) tys
1533 -- | Substitute within a 'ThetaType'
1534 substTheta :: TvSubst -> ThetaType -> ThetaType
1535 substTheta subst theta
1536 | isEmptyTvSubst subst = theta
1537 | otherwise = map (substPred subst) theta
1539 -- | Substitute within a 'PredType'
1540 substPred :: TvSubst -> PredType -> PredType
1541 substPred subst (IParam n ty) = IParam n (subst_ty subst ty)
1542 substPred subst (ClassP clas tys) = ClassP clas (map (subst_ty subst) tys)
1543 substPred subst (EqPred ty1 ty2) = EqPred (subst_ty subst ty1) (subst_ty subst ty2)
1545 -- | Remove any nested binders mentioning the 'TyVar's in the 'TyVarSet'
1546 deShadowTy :: TyVarSet -> Type -> Type
1548 = subst_ty (mkTvSubst in_scope emptyTvSubstEnv) ty
1550 in_scope = mkInScopeSet tvs
1552 subst_ty :: TvSubst -> Type -> Type
1553 -- subst_ty is the main workhorse for type substitution
1555 -- Note that the in_scope set is poked only if we hit a forall
1556 -- so it may often never be fully computed
1560 go (TyVarTy tv) = substTyVar subst tv
1561 go (TyConApp tc tys) = let args = map go tys
1562 in args `seqList` TyConApp tc args
1564 go (PredTy p) = PredTy $! (substPred subst p)
1566 go (FunTy arg res) = (FunTy $! (go arg)) $! (go res)
1567 go (AppTy fun arg) = mkAppTy (go fun) $! (go arg)
1568 -- The mkAppTy smart constructor is important
1569 -- we might be replacing (a Int), represented with App
1570 -- by [Int], represented with TyConApp
1571 go (ForAllTy tv ty) = case substTyVarBndr subst tv of
1573 ForAllTy tv' $! (subst_ty subst' ty)
1575 substTyVar :: TvSubst -> TyVar -> Type
1576 substTyVar subst@(TvSubst _ _) tv
1577 = case lookupTyVar subst tv of {
1578 Nothing -> TyVarTy tv;
1579 Just ty -> ty -- See Note [Apply Once]
1582 substTyVars :: TvSubst -> [TyVar] -> [Type]
1583 substTyVars subst tvs = map (substTyVar subst) tvs
1585 lookupTyVar :: TvSubst -> TyVar -> Maybe Type
1586 -- See Note [Extending the TvSubst]
1587 lookupTyVar (TvSubst _ env) tv = lookupVarEnv env tv
1589 substTyVarBndr :: TvSubst -> TyVar -> (TvSubst, TyVar)
1590 substTyVarBndr subst@(TvSubst in_scope env) old_var
1591 = (TvSubst (in_scope `extendInScopeSet` new_var) new_env, new_var)
1593 is_co_var = isCoVar old_var
1595 new_env | no_change = delVarEnv env old_var
1596 | otherwise = extendVarEnv env old_var (TyVarTy new_var)
1598 no_change = new_var == old_var && not is_co_var
1599 -- no_change means that the new_var is identical in
1600 -- all respects to the old_var (same unique, same kind)
1601 -- See Note [Extending the TvSubst]
1603 -- In that case we don't need to extend the substitution
1604 -- to map old to new. But instead we must zap any
1605 -- current substitution for the variable. For example:
1606 -- (\x.e) with id_subst = [x |-> e']
1607 -- Here we must simply zap the substitution for x
1609 new_var = uniqAway in_scope subst_old_var
1610 -- The uniqAway part makes sure the new variable is not already in scope
1612 subst_old_var -- subst_old_var is old_var with the substitution applied to its kind
1613 -- It's only worth doing the substitution for coercions,
1614 -- becuase only they can have free type variables
1615 | is_co_var = setTyVarKind old_var (substTy subst (tyVarKind old_var))
1616 | otherwise = old_var
1619 ----------------------------------------------------
1628 -- There's a little subtyping at the kind level:
1638 -- Where: \* [LiftedTypeKind] means boxed type
1639 -- \# [UnliftedTypeKind] means unboxed type
1640 -- (\#) [UbxTupleKind] means unboxed tuple
1641 -- ?? [ArgTypeKind] is the lub of {\*, \#}
1642 -- ? [OpenTypeKind] means any type at all
1647 -- > error :: forall a:?. String -> a
1648 -- > (->) :: ?? -> ? -> \*
1649 -- > (\\(x::t) -> ...)
1651 -- Where in the last example @t :: ??@ (i.e. is not an unboxed tuple)
1653 type KindVar = TyVar -- invariant: KindVar will always be a
1654 -- TcTyVar with details MetaTv TauTv ...
1655 -- kind var constructors and functions are in TcType
1657 type SimpleKind = Kind
1662 During kind inference, a kind variable unifies only with
1664 sk ::= * | sk1 -> sk2
1666 data T a = MkT a (T Int#)
1667 fails. We give T the kind (k -> *), and the kind variable k won't unify
1668 with # (the kind of Int#).
1672 When creating a fresh internal type variable, we give it a kind to express
1673 constraints on it. E.g. in (\x->e) we make up a fresh type variable for x,
1676 During unification we only bind an internal type variable to a type
1677 whose kind is lower in the sub-kind hierarchy than the kind of the tyvar.
1679 When unifying two internal type variables, we collect their kind constraints by
1680 finding the GLB of the two. Since the partial order is a tree, they only
1681 have a glb if one is a sub-kind of the other. In that case, we bind the
1682 less-informative one to the more informative one. Neat, eh?