2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1998
6 Type - public interface
9 {-# OPTIONS -fno-warn-incomplete-patterns #-}
10 -- The above warning supression flag is a temporary kludge.
11 -- While working on this module you are encouraged to remove it and fix
12 -- any warnings in the module. See
13 -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
16 -- | Main functions for manipulating types and type-related things
18 -- Note some of this is just re-exports from TyCon..
20 -- * Main data types representing Types
21 -- $type_classification
23 -- $representation_types
24 TyThing(..), Type, PredType(..), ThetaType,
26 -- ** Constructing and deconstructing types
27 mkTyVarTy, mkTyVarTys, getTyVar, getTyVar_maybe,
29 mkAppTy, mkAppTys, splitAppTy, splitAppTys,
30 splitAppTy_maybe, repSplitAppTy_maybe,
32 mkFunTy, mkFunTys, splitFunTy, splitFunTy_maybe,
33 splitFunTys, splitFunTysN,
34 funResultTy, funArgTy, zipFunTys,
36 mkTyConApp, mkTyConTy,
37 tyConAppTyCon, tyConAppArgs,
38 splitTyConApp_maybe, splitTyConApp,
40 mkForAllTy, mkForAllTys, splitForAllTy_maybe, splitForAllTys,
41 applyTy, applyTys, applyTysD, isForAllTy, dropForAlls,
50 mkPredTy, mkPredTys, mkFamilyTyConApp,
52 -- ** Common type constructors
55 -- ** Predicates on types
58 -- (Lifting and boxity)
59 isUnLiftedType, isUnboxedTupleType, isAlgType, isClosedAlgType,
60 isPrimitiveType, isStrictType, isStrictPred,
62 -- * Main data types representing Kinds
64 Kind, SimpleKind, KindVar,
66 -- ** Deconstructing Kinds
67 kindFunResult, splitKindFunTys, splitKindFunTysN,
69 -- ** Common Kinds and SuperKinds
70 liftedTypeKind, unliftedTypeKind, openTypeKind,
71 argTypeKind, ubxTupleKind,
73 tySuperKind, coSuperKind,
75 -- ** Common Kind type constructors
76 liftedTypeKindTyCon, openTypeKindTyCon, unliftedTypeKindTyCon,
77 argTypeKindTyCon, ubxTupleKindTyCon,
79 -- ** Predicates on Kinds
80 isLiftedTypeKind, isUnliftedTypeKind, isOpenTypeKind,
81 isUbxTupleKind, isArgTypeKind, isKind, isTySuperKind,
82 isCoSuperKind, isSuperKind, isCoercionKind, isEqPred,
83 mkArrowKind, mkArrowKinds,
85 isSubArgTypeKind, isSubOpenTypeKind, isSubKind, defaultKind, eqKind,
88 -- * Type free variables
89 tyVarsOfType, tyVarsOfTypes, tyVarsOfPred, tyVarsOfTheta,
92 -- * Tidying type related things up for printing
94 tidyOpenType, tidyOpenTypes,
95 tidyTyVarBndr, tidyFreeTyVars,
96 tidyOpenTyVar, tidyOpenTyVars,
97 tidyTopType, tidyPred,
101 coreEqType, tcEqType, tcEqTypes, tcCmpType, tcCmpTypes,
102 tcEqPred, tcEqPredX, tcCmpPred, tcEqTypeX, tcPartOfType, tcPartOfPred,
104 -- * Forcing evaluation of types
107 -- * Other views onto Types
108 coreView, tcView, kindView,
112 -- * Type representation for the code generator
115 typePrimRep, predTypeRep,
117 -- * Main type substitution data types
118 TvSubstEnv, -- Representation widely visible
119 TvSubst(..), -- Representation visible to a few friends
121 -- ** Manipulating type substitutions
122 emptyTvSubstEnv, emptyTvSubst,
124 mkTvSubst, mkOpenTvSubst, zipOpenTvSubst, zipTopTvSubst, mkTopTvSubst, notElemTvSubst,
125 getTvSubstEnv, setTvSubstEnv, getTvInScope, extendTvInScope,
126 extendTvSubst, extendTvSubstList, isInScope, composeTvSubst, zipTyEnv,
129 -- ** Performing substitution on types
130 substTy, substTys, substTyWith, substTysWith, substTheta,
131 substPred, substTyVar, substTyVars, substTyVarBndr, deShadowTy, lookupTyVar,
134 pprType, pprParendType, pprTypeApp, pprTyThingCategory, pprTyThing, pprForAll,
135 pprPred, pprTheta, pprThetaArrow, pprClassPred, pprKind, pprParendKind,
140 #include "HsVersions.h"
142 -- We import the representation and primitive functions from TypeRep.
143 -- Many things are reexported, but not the representation!
164 import Data.Maybe ( isJust )
168 -- $type_classification
169 -- #type_classification#
173 -- [Unboxed] Iff its representation is other than a pointer
174 -- Unboxed types are also unlifted.
176 -- [Lifted] Iff it has bottom as an element.
177 -- Closures always have lifted types: i.e. any
178 -- let-bound identifier in Core must have a lifted
179 -- type. Operationally, a lifted object is one that
181 -- Only lifted types may be unified with a type variable.
183 -- [Algebraic] Iff it is a type with one or more constructors, whether
184 -- declared with @data@ or @newtype@.
185 -- An algebraic type is one that can be deconstructed
186 -- with a case expression. This is /not/ the same as
187 -- lifted types, because we also include unboxed
188 -- tuples in this classification.
190 -- [Data] Iff it is a type declared with @data@, or a boxed tuple.
192 -- [Primitive] Iff it is a built-in type that can't be expressed in Haskell.
194 -- Currently, all primitive types are unlifted, but that's not necessarily
195 -- the case: for example, @Int@ could be primitive.
197 -- Some primitive types are unboxed, such as @Int#@, whereas some are boxed
198 -- but unlifted (such as @ByteArray#@). The only primitive types that we
199 -- classify as algebraic are the unboxed tuples.
201 -- Some examples of type classifications that may make this a bit clearer are:
204 -- Type primitive boxed lifted algebraic
205 -- -----------------------------------------------------------------------------
207 -- ByteArray# Yes Yes No No
208 -- (\# a, b \#) Yes No No Yes
209 -- ( a, b ) No Yes Yes Yes
210 -- [a] No Yes Yes Yes
213 -- $representation_types
214 -- A /source type/ is a type that is a separate type as far as the type checker is
215 -- concerned, but which has a more low-level representation as far as Core-to-Core
216 -- passes and the rest of the back end is concerned. Notably, 'PredTy's are removed
217 -- from the representation type while they do exist in the source types.
219 -- You don't normally have to worry about this, as the utility functions in
220 -- this module will automatically convert a source into a representation type
221 -- if they are spotted, to the best of it's abilities. If you don't want this
222 -- to happen, use the equivalent functions from the "TcType" module.
225 %************************************************************************
229 %************************************************************************
232 {-# INLINE coreView #-}
233 coreView :: Type -> Maybe Type
234 -- ^ In Core, we \"look through\" non-recursive newtypes and 'PredTypes': this
235 -- function tries to obtain a different view of the supplied type given this
237 -- Strips off the /top layer only/ of a type to give
238 -- its underlying representation type.
239 -- Returns Nothing if there is nothing to look through.
241 -- In the case of @newtype@s, it returns one of:
243 -- 1) A vanilla 'TyConApp' (recursive newtype, or non-saturated)
245 -- 2) The newtype representation (otherwise), meaning the
246 -- type written in the RHS of the newtype declaration,
247 -- which may itself be a newtype
249 -- For example, with:
251 -- > newtype R = MkR S
252 -- > newtype S = MkS T
253 -- > newtype T = MkT (T -> T)
255 -- 'expandNewTcApp' on:
257 -- * @R@ gives @Just S@
258 -- * @S@ gives @Just T@
259 -- * @T@ gives @Nothing@ (no expansion)
261 -- By being non-recursive and inlined, this case analysis gets efficiently
262 -- joined onto the case analysis that the caller is already doing
264 | isEqPred p = Nothing
265 | otherwise = Just (predTypeRep p)
266 coreView (TyConApp tc tys) | Just (tenv, rhs, tys') <- coreExpandTyCon_maybe tc tys
267 = Just (mkAppTys (substTy (mkTopTvSubst tenv) rhs) tys')
268 -- Its important to use mkAppTys, rather than (foldl AppTy),
269 -- because the function part might well return a
270 -- partially-applied type constructor; indeed, usually will!
275 -----------------------------------------------
276 {-# INLINE tcView #-}
277 tcView :: Type -> Maybe Type
278 -- ^ Similar to 'coreView', but for the type checker, which just looks through synonyms
279 tcView (TyConApp tc tys) | Just (tenv, rhs, tys') <- tcExpandTyCon_maybe tc tys
280 = Just (mkAppTys (substTy (mkTopTvSubst tenv) rhs) tys')
283 -----------------------------------------------
284 {-# INLINE kindView #-}
285 kindView :: Kind -> Maybe Kind
286 -- ^ Similar to 'coreView' or 'tcView', but works on 'Kind's
288 -- For the moment, we don't even handle synonyms in kinds
293 %************************************************************************
295 \subsection{Constructor-specific functions}
297 %************************************************************************
300 ---------------------------------------------------------------------
304 mkTyVarTy :: TyVar -> Type
307 mkTyVarTys :: [TyVar] -> [Type]
308 mkTyVarTys = map mkTyVarTy -- a common use of mkTyVarTy
310 -- | Attempts to obtain the type variable underlying a 'Type', and panics with the
311 -- given message if this is not a type variable type. See also 'getTyVar_maybe'
312 getTyVar :: String -> Type -> TyVar
313 getTyVar msg ty = case getTyVar_maybe ty of
315 Nothing -> panic ("getTyVar: " ++ msg)
317 isTyVarTy :: Type -> Bool
318 isTyVarTy ty = isJust (getTyVar_maybe ty)
320 -- | Attempts to obtain the type variable underlying a 'Type'
321 getTyVar_maybe :: Type -> Maybe TyVar
322 getTyVar_maybe ty | Just ty' <- coreView ty = getTyVar_maybe ty'
323 getTyVar_maybe (TyVarTy tv) = Just tv
324 getTyVar_maybe _ = Nothing
329 ---------------------------------------------------------------------
332 We need to be pretty careful with AppTy to make sure we obey the
333 invariant that a TyConApp is always visibly so. mkAppTy maintains the
337 -- | Applies a type to another, as in e.g. @k a@
338 mkAppTy :: Type -> Type -> Type
339 mkAppTy orig_ty1 orig_ty2
342 mk_app (TyConApp tc tys) = mkTyConApp tc (tys ++ [orig_ty2])
343 mk_app _ = AppTy orig_ty1 orig_ty2
344 -- Note that the TyConApp could be an
345 -- under-saturated type synonym. GHC allows that; e.g.
346 -- type Foo k = k a -> k a
348 -- foo :: Foo Id -> Foo Id
350 -- Here Id is partially applied in the type sig for Foo,
351 -- but once the type synonyms are expanded all is well
353 mkAppTys :: Type -> [Type] -> Type
354 mkAppTys orig_ty1 [] = orig_ty1
355 -- This check for an empty list of type arguments
356 -- avoids the needless loss of a type synonym constructor.
357 -- For example: mkAppTys Rational []
358 -- returns to (Ratio Integer), which has needlessly lost
359 -- the Rational part.
360 mkAppTys orig_ty1 orig_tys2
363 mk_app (TyConApp tc tys) = mkTyConApp tc (tys ++ orig_tys2)
364 -- mkTyConApp: see notes with mkAppTy
365 mk_app _ = foldl AppTy orig_ty1 orig_tys2
368 splitAppTy_maybe :: Type -> Maybe (Type, Type)
369 -- ^ Attempt to take a type application apart, whether it is a
370 -- function, type constructor, or plain type application. Note
371 -- that type family applications are NEVER unsaturated by this!
372 splitAppTy_maybe ty | Just ty' <- coreView ty
373 = splitAppTy_maybe ty'
374 splitAppTy_maybe ty = repSplitAppTy_maybe ty
377 repSplitAppTy_maybe :: Type -> Maybe (Type,Type)
378 -- ^ Does the AppTy split as in 'splitAppTy_maybe', but assumes that
379 -- any Core view stuff is already done
380 repSplitAppTy_maybe (FunTy ty1 ty2) = Just (TyConApp funTyCon [ty1], ty2)
381 repSplitAppTy_maybe (AppTy ty1 ty2) = Just (ty1, ty2)
382 repSplitAppTy_maybe (TyConApp tc tys)
383 | not (isOpenSynTyCon tc) || length tys > tyConArity tc
384 = case snocView tys of -- never create unsaturated type family apps
385 Just (tys', ty') -> Just (TyConApp tc tys', ty')
387 repSplitAppTy_maybe _other = Nothing
389 splitAppTy :: Type -> (Type, Type)
390 -- ^ Attempts to take a type application apart, as in 'splitAppTy_maybe',
391 -- and panics if this is not possible
392 splitAppTy ty = case splitAppTy_maybe ty of
394 Nothing -> panic "splitAppTy"
397 splitAppTys :: Type -> (Type, [Type])
398 -- ^ Recursively splits a type as far as is possible, leaving a residual
399 -- type being applied to and the type arguments applied to it. Never fails,
400 -- even if that means returning an empty list of type applications.
401 splitAppTys ty = split ty ty []
403 split orig_ty ty args | Just ty' <- coreView ty = split orig_ty ty' args
404 split _ (AppTy ty arg) args = split ty ty (arg:args)
405 split _ (TyConApp tc tc_args) args
406 = let -- keep type families saturated
407 n | isOpenSynTyCon tc = tyConArity tc
409 (tc_args1, tc_args2) = splitAt n tc_args
411 (TyConApp tc tc_args1, tc_args2 ++ args)
412 split _ (FunTy ty1 ty2) args = ASSERT( null args )
413 (TyConApp funTyCon [], [ty1,ty2])
414 split orig_ty _ args = (orig_ty, args)
419 ---------------------------------------------------------------------
424 mkFunTy :: Type -> Type -> Type
425 -- ^ Creates a function type from the given argument and result type
426 mkFunTy (PredTy (EqPred ty1 ty2)) res = mkForAllTy (mkWildCoVar (PredTy (EqPred ty1 ty2))) res
427 mkFunTy arg res = FunTy arg res
429 mkFunTys :: [Type] -> Type -> Type
430 mkFunTys tys ty = foldr mkFunTy ty tys
432 isFunTy :: Type -> Bool
433 isFunTy ty = isJust (splitFunTy_maybe ty)
435 splitFunTy :: Type -> (Type, Type)
436 -- ^ Attempts to extract the argument and result types from a type, and
437 -- panics if that is not possible. See also 'splitFunTy_maybe'
438 splitFunTy ty | Just ty' <- coreView ty = splitFunTy ty'
439 splitFunTy (FunTy arg res) = (arg, res)
440 splitFunTy other = pprPanic "splitFunTy" (ppr other)
442 splitFunTy_maybe :: Type -> Maybe (Type, Type)
443 -- ^ Attempts to extract the argument and result types from a type
444 splitFunTy_maybe ty | Just ty' <- coreView ty = splitFunTy_maybe ty'
445 splitFunTy_maybe (FunTy arg res) = Just (arg, res)
446 splitFunTy_maybe _ = Nothing
448 splitFunTys :: Type -> ([Type], Type)
449 splitFunTys ty = split [] ty ty
451 split args orig_ty ty | Just ty' <- coreView ty = split args orig_ty ty'
452 split args _ (FunTy arg res) = split (arg:args) res res
453 split args orig_ty _ = (reverse args, orig_ty)
455 splitFunTysN :: Int -> Type -> ([Type], Type)
456 -- ^ Split off exactly the given number argument types, and panics if that is not possible
457 splitFunTysN 0 ty = ([], ty)
458 splitFunTysN n ty = case splitFunTy ty of { (arg, res) ->
459 case splitFunTysN (n-1) res of { (args, res) ->
462 -- | Splits off argument types from the given type and associating
463 -- them with the things in the input list from left to right. The
464 -- final result type is returned, along with the resulting pairs of
465 -- objects and types, albeit with the list of pairs in reverse order.
466 -- Panics if there are not enough argument types for the input list.
467 zipFunTys :: Outputable a => [a] -> Type -> ([(a, Type)], Type)
468 zipFunTys orig_xs orig_ty = split [] orig_xs orig_ty orig_ty
470 split acc [] nty _ = (reverse acc, nty)
472 | Just ty' <- coreView ty = split acc xs nty ty'
473 split acc (x:xs) _ (FunTy arg res) = split ((x,arg):acc) xs res res
474 split _ _ _ _ = pprPanic "zipFunTys" (ppr orig_xs <+> ppr orig_ty)
476 funResultTy :: Type -> Type
477 -- ^ Extract the function result type and panic if that is not possible
478 funResultTy ty | Just ty' <- coreView ty = funResultTy ty'
479 funResultTy (FunTy _arg res) = res
480 funResultTy ty = pprPanic "funResultTy" (ppr ty)
482 funArgTy :: Type -> Type
483 -- ^ Extract the function argument type and panic if that is not possible
484 funArgTy ty | Just ty' <- coreView ty = funArgTy ty'
485 funArgTy (FunTy arg _res) = arg
486 funArgTy ty = pprPanic "funArgTy" (ppr ty)
489 ---------------------------------------------------------------------
494 -- | A key function: builds a 'TyConApp' or 'FunTy' as apppropriate to its arguments.
495 -- Applies its arguments to the constructor from left to right
496 mkTyConApp :: TyCon -> [Type] -> Type
498 | isFunTyCon tycon, [ty1,ty2] <- tys
504 -- | Create the plain type constructor type which has been applied to no type arguments at all.
505 mkTyConTy :: TyCon -> Type
506 mkTyConTy tycon = mkTyConApp tycon []
508 -- splitTyConApp "looks through" synonyms, because they don't
509 -- mean a distinct type, but all other type-constructor applications
510 -- including functions are returned as Just ..
512 -- | The same as @fst . splitTyConApp@
513 tyConAppTyCon :: Type -> TyCon
514 tyConAppTyCon ty = fst (splitTyConApp ty)
516 -- | The same as @snd . splitTyConApp@
517 tyConAppArgs :: Type -> [Type]
518 tyConAppArgs ty = snd (splitTyConApp ty)
520 -- | Attempts to tease a type apart into a type constructor and the application
521 -- of a number of arguments to that constructor. Panics if that is not possible.
522 -- See also 'splitTyConApp_maybe'
523 splitTyConApp :: Type -> (TyCon, [Type])
524 splitTyConApp ty = case splitTyConApp_maybe ty of
526 Nothing -> pprPanic "splitTyConApp" (ppr ty)
528 -- | Attempts to tease a type apart into a type constructor and the application
529 -- of a number of arguments to that constructor
530 splitTyConApp_maybe :: Type -> Maybe (TyCon, [Type])
531 splitTyConApp_maybe ty | Just ty' <- coreView ty = splitTyConApp_maybe ty'
532 splitTyConApp_maybe (TyConApp tc tys) = Just (tc, tys)
533 splitTyConApp_maybe (FunTy arg res) = Just (funTyCon, [arg,res])
534 splitTyConApp_maybe _ = Nothing
536 newTyConInstRhs :: TyCon -> [Type] -> Type
537 -- ^ Unwrap one 'layer' of newtype on a type constructor and it's arguments, using an
538 -- eta-reduced version of the @newtype@ if possible
539 newTyConInstRhs tycon tys
540 = ASSERT2( equalLength tvs tys1, ppr tycon $$ ppr tys $$ ppr tvs )
541 mkAppTys (substTyWith tvs tys1 ty) tys2
543 (tvs, ty) = newTyConEtadRhs tycon
544 (tys1, tys2) = splitAtList tvs tys
548 ---------------------------------------------------------------------
552 Notes on type synonyms
553 ~~~~~~~~~~~~~~~~~~~~~~
554 The various "split" functions (splitFunTy, splitRhoTy, splitForAllTy) try
555 to return type synonyms whereever possible. Thus
560 splitFunTys (a -> Foo a) = ([a], Foo a)
563 The reason is that we then get better (shorter) type signatures in
564 interfaces. Notably this plays a role in tcTySigs in TcBinds.lhs.
567 Note [Expanding newtypes]
568 ~~~~~~~~~~~~~~~~~~~~~~~~~
569 When expanding a type to expose a data-type constructor, we need to be
570 careful about newtypes, lest we fall into an infinite loop. Here are
573 newtype Id x = MkId x
574 newtype Fix f = MkFix (f (Fix f))
575 newtype T = MkT (T -> T)
578 --------------------------
580 Fix Maybe Maybe (Fix Maybe)
584 Notice that we can expand T, even though it's recursive.
585 And we can expand Id (Id Int), even though the Id shows up
586 twice at the outer level.
588 So, when expanding, we keep track of when we've seen a recursive
589 newtype at outermost level; and bale out if we see it again.
604 -- 4. Usage annotations
606 -- 5. All newtypes, including recursive ones, but not newtype families
608 -- It's useful in the back end of the compiler.
609 repType :: Type -> Type
610 -- Only applied to types of kind *; hence tycons are saturated
614 go :: [TyCon] -> Type -> Type
615 go rec_nts ty | Just ty' <- coreView ty -- Expand synonyms
618 go rec_nts (ForAllTy _ ty) -- Look through foralls
621 go rec_nts ty@(TyConApp tc tys) -- Expand newtypes
622 | Just _co_con <- newTyConCo_maybe tc -- See Note [Expanding newtypes]
623 = if tc `elem` rec_nts -- in Type.lhs
625 else go rec_nts' nt_rhs
627 nt_rhs = newTyConInstRhs tc tys
628 rec_nts' | isRecursiveTyCon tc = tc:rec_nts
629 | otherwise = rec_nts
634 -- ToDo: this could be moved to the code generator, using splitTyConApp instead
635 -- of inspecting the type directly.
637 -- | Discovers the primitive representation of a more abstract 'Type'
638 typePrimRep :: Type -> PrimRep
639 typePrimRep ty = case repType ty of
640 TyConApp tc _ -> tyConPrimRep tc
642 AppTy _ _ -> PtrRep -- See note below
644 _ -> pprPanic "typePrimRep" (ppr ty)
645 -- Types of the form 'f a' must be of kind *, not *#, so
646 -- we are guaranteed that they are represented by pointers.
647 -- The reason is that f must have kind *->*, not *->*#, because
648 -- (we claim) there is no way to constrain f's kind any other
653 ---------------------------------------------------------------------
658 mkForAllTy :: TyVar -> Type -> Type
660 = mkForAllTys [tyvar] ty
662 -- | Wraps foralls over the type using the provided 'TyVar's from left to right
663 mkForAllTys :: [TyVar] -> Type -> Type
664 mkForAllTys tyvars ty = foldr ForAllTy ty tyvars
666 isForAllTy :: Type -> Bool
667 isForAllTy (ForAllTy _ _) = True
670 -- | Attempts to take a forall type apart, returning the bound type variable
671 -- and the remainder of the type
672 splitForAllTy_maybe :: Type -> Maybe (TyVar, Type)
673 splitForAllTy_maybe ty = splitFAT_m ty
675 splitFAT_m ty | Just ty' <- coreView ty = splitFAT_m ty'
676 splitFAT_m (ForAllTy tyvar ty) = Just(tyvar, ty)
677 splitFAT_m _ = Nothing
679 -- | Attempts to take a forall type apart, returning all the immediate such bound
680 -- type variables and the remainder of the type. Always suceeds, even if that means
681 -- returning an empty list of 'TyVar's
682 splitForAllTys :: Type -> ([TyVar], Type)
683 splitForAllTys ty = split ty ty []
685 split orig_ty ty tvs | Just ty' <- coreView ty = split orig_ty ty' tvs
686 split _ (ForAllTy tv ty) tvs = split ty ty (tv:tvs)
687 split orig_ty _ tvs = (reverse tvs, orig_ty)
689 -- | Equivalent to @snd . splitForAllTys@
690 dropForAlls :: Type -> Type
691 dropForAlls ty = snd (splitForAllTys ty)
694 -- (mkPiType now in CoreUtils)
700 -- | Instantiate a forall type with one or more type arguments.
701 -- Used when we have a polymorphic function applied to type args:
705 -- We use @applyTys type-of-f [t1,t2]@ to compute the type of the expression.
706 -- Panics if no application is possible.
707 applyTy :: Type -> Type -> Type
708 applyTy ty arg | Just ty' <- coreView ty = applyTy ty' arg
709 applyTy (ForAllTy tv ty) arg = substTyWith [tv] [arg] ty
710 applyTy _ _ = panic "applyTy"
712 applyTys :: Type -> [Type] -> Type
713 -- ^ This function is interesting because:
715 -- 1. The function may have more for-alls than there are args
717 -- 2. Less obviously, it may have fewer for-alls
719 -- For case 2. think of:
721 -- > applyTys (forall a.a) [forall b.b, Int]
723 -- This really can happen, via dressing up polymorphic types with newtype
724 -- clothing. Here's an example:
726 -- > newtype R = R (forall a. a->a)
727 -- > foo = case undefined :: R of
730 applyTys ty args = applyTysD empty ty args
732 applyTysD :: SDoc -> Type -> [Type] -> Type -- Debug version
733 applyTysD _ orig_fun_ty [] = orig_fun_ty
734 applyTysD doc orig_fun_ty arg_tys
735 | n_tvs == n_args -- The vastly common case
736 = substTyWith tvs arg_tys rho_ty
737 | n_tvs > n_args -- Too many for-alls
738 = substTyWith (take n_args tvs) arg_tys
739 (mkForAllTys (drop n_args tvs) rho_ty)
740 | otherwise -- Too many type args
741 = ASSERT2( n_tvs > 0, doc $$ ppr orig_fun_ty ) -- Zero case gives infnite loop!
742 applyTys (substTyWith tvs (take n_tvs arg_tys) rho_ty)
745 (tvs, rho_ty) = splitForAllTys orig_fun_ty
747 n_args = length arg_tys
751 %************************************************************************
753 \subsection{Source types}
755 %************************************************************************
757 Source types are always lifted.
759 The key function is predTypeRep which gives the representation of a source type:
762 mkPredTy :: PredType -> Type
763 mkPredTy pred = PredTy pred
765 mkPredTys :: ThetaType -> [Type]
766 mkPredTys preds = map PredTy preds
768 predTypeRep :: PredType -> Type
769 -- ^ Convert a 'PredType' to its representation type. However, it unwraps
770 -- only the outermost level; for example, the result might be a newtype application
771 predTypeRep (IParam _ ty) = ty
772 predTypeRep (ClassP clas tys) = mkTyConApp (classTyCon clas) tys
773 -- Result might be a newtype application, but the consumer will
774 -- look through that too if necessary
775 predTypeRep (EqPred ty1 ty2) = pprPanic "predTypeRep" (ppr (EqPred ty1 ty2))
777 mkFamilyTyConApp :: TyCon -> [Type] -> Type
778 -- ^ Given a family instance TyCon and its arg types, return the
779 -- corresponding family type. E.g:
782 -- > data instance T (Maybe b) = MkT b
784 -- Where the instance tycon is :RTL, so:
786 -- > mkFamilyTyConApp :RTL Int = T (Maybe Int)
787 mkFamilyTyConApp tc tys
788 | Just (fam_tc, fam_tys) <- tyConFamInst_maybe tc
789 , let fam_subst = zipTopTvSubst (tyConTyVars tc) tys
790 = mkTyConApp fam_tc (substTys fam_subst fam_tys)
794 -- | Pretty prints a 'TyCon', using the family instance in case of a
795 -- representation tycon. For example:
797 -- > data T [a] = ...
799 -- In that case we want to print @T [a]@, where @T@ is the family 'TyCon'
800 pprSourceTyCon :: TyCon -> SDoc
802 | Just (fam_tc, tys) <- tyConFamInst_maybe tycon
803 = ppr $ fam_tc `TyConApp` tys -- can't be FunTyCon
809 %************************************************************************
811 \subsection{Kinds and free variables}
813 %************************************************************************
815 ---------------------------------------------------------------------
816 Finding the kind of a type
817 ~~~~~~~~~~~~~~~~~~~~~~~~~~
819 typeKind :: Type -> Kind
820 typeKind (TyConApp tycon tys) = ASSERT( not (isCoercionTyCon tycon) )
821 -- We should be looking for the coercion kind,
823 foldr (\_ k -> kindFunResult k) (tyConKind tycon) tys
824 typeKind (PredTy pred) = predKind pred
825 typeKind (AppTy fun _) = kindFunResult (typeKind fun)
826 typeKind (ForAllTy _ ty) = typeKind ty
827 typeKind (TyVarTy tyvar) = tyVarKind tyvar
828 typeKind (FunTy _arg res)
829 -- Hack alert. The kind of (Int -> Int#) is liftedTypeKind (*),
830 -- not unliftedTypKind (#)
831 -- The only things that can be after a function arrow are
832 -- (a) types (of kind openTypeKind or its sub-kinds)
833 -- (b) kinds (of super-kind TY) (e.g. * -> (* -> *))
834 | isTySuperKind k = k
835 | otherwise = ASSERT( isSubOpenTypeKind k) liftedTypeKind
839 predKind :: PredType -> Kind
840 predKind (EqPred {}) = coSuperKind -- A coercion kind!
841 predKind (ClassP {}) = liftedTypeKind -- Class and implicitPredicates are
842 predKind (IParam {}) = liftedTypeKind -- always represented by lifted types
846 ---------------------------------------------------------------------
847 Free variables of a type
848 ~~~~~~~~~~~~~~~~~~~~~~~~
850 tyVarsOfType :: Type -> TyVarSet
851 -- ^ NB: for type synonyms tyVarsOfType does /not/ expand the synonym
852 tyVarsOfType (TyVarTy tv) = unitVarSet tv
853 tyVarsOfType (TyConApp _ tys) = tyVarsOfTypes tys
854 tyVarsOfType (PredTy sty) = tyVarsOfPred sty
855 tyVarsOfType (FunTy arg res) = tyVarsOfType arg `unionVarSet` tyVarsOfType res
856 tyVarsOfType (AppTy fun arg) = tyVarsOfType fun `unionVarSet` tyVarsOfType arg
857 tyVarsOfType (ForAllTy tyvar ty) = delVarSet (tyVarsOfType ty) tyvar
859 tyVarsOfTypes :: [Type] -> TyVarSet
860 tyVarsOfTypes tys = foldr (unionVarSet.tyVarsOfType) emptyVarSet tys
862 tyVarsOfPred :: PredType -> TyVarSet
863 tyVarsOfPred (IParam _ ty) = tyVarsOfType ty
864 tyVarsOfPred (ClassP _ tys) = tyVarsOfTypes tys
865 tyVarsOfPred (EqPred ty1 ty2) = tyVarsOfType ty1 `unionVarSet` tyVarsOfType ty2
867 tyVarsOfTheta :: ThetaType -> TyVarSet
868 tyVarsOfTheta = foldr (unionVarSet . tyVarsOfPred) emptyVarSet
872 %************************************************************************
874 \subsection{Type families}
876 %************************************************************************
879 -- | Finds type family instances occuring in a type after expanding synonyms.
880 tyFamInsts :: Type -> [(TyCon, [Type])]
882 | Just exp_ty <- tcView ty = tyFamInsts exp_ty
883 tyFamInsts (TyVarTy _) = []
884 tyFamInsts (TyConApp tc tys)
885 | isOpenSynTyCon tc = [(tc, tys)]
886 | otherwise = concat (map tyFamInsts tys)
887 tyFamInsts (FunTy ty1 ty2) = tyFamInsts ty1 ++ tyFamInsts ty2
888 tyFamInsts (AppTy ty1 ty2) = tyFamInsts ty1 ++ tyFamInsts ty2
889 tyFamInsts (ForAllTy _ ty) = tyFamInsts ty
893 %************************************************************************
895 \subsection{TidyType}
897 %************************************************************************
900 -- | This tidies up a type for printing in an error message, or in
901 -- an interface file.
903 -- It doesn't change the uniques at all, just the print names.
904 tidyTyVarBndr :: TidyEnv -> TyVar -> (TidyEnv, TyVar)
905 tidyTyVarBndr env@(tidy_env, subst) tyvar
906 = case tidyOccName tidy_env (getOccName name) of
907 (tidy', occ') -> ((tidy', subst'), tyvar'')
909 subst' = extendVarEnv subst tyvar tyvar''
910 tyvar' = setTyVarName tyvar name'
911 name' = tidyNameOcc name occ'
912 -- Don't forget to tidy the kind for coercions!
913 tyvar'' | isCoVar tyvar = setTyVarKind tyvar' kind'
915 kind' = tidyType env (tyVarKind tyvar)
917 name = tyVarName tyvar
919 tidyFreeTyVars :: TidyEnv -> TyVarSet -> TidyEnv
920 -- ^ Add the free 'TyVar's to the env in tidy form,
921 -- so that we can tidy the type they are free in
922 tidyFreeTyVars env tyvars = fst (tidyOpenTyVars env (varSetElems tyvars))
924 tidyOpenTyVars :: TidyEnv -> [TyVar] -> (TidyEnv, [TyVar])
925 tidyOpenTyVars env tyvars = mapAccumL tidyOpenTyVar env tyvars
927 tidyOpenTyVar :: TidyEnv -> TyVar -> (TidyEnv, TyVar)
928 -- ^ Treat a new 'TyVar' as a binder, and give it a fresh tidy name
929 -- using the environment if one has not already been allocated. See
930 -- also 'tidyTyVarBndr'
931 tidyOpenTyVar env@(_, subst) tyvar
932 = case lookupVarEnv subst tyvar of
933 Just tyvar' -> (env, tyvar') -- Already substituted
934 Nothing -> tidyTyVarBndr env tyvar -- Treat it as a binder
936 tidyType :: TidyEnv -> Type -> Type
937 tidyType env@(_, subst) ty
940 go (TyVarTy tv) = case lookupVarEnv subst tv of
941 Nothing -> TyVarTy tv
942 Just tv' -> TyVarTy tv'
943 go (TyConApp tycon tys) = let args = map go tys
944 in args `seqList` TyConApp tycon args
945 go (PredTy sty) = PredTy (tidyPred env sty)
946 go (AppTy fun arg) = (AppTy $! (go fun)) $! (go arg)
947 go (FunTy fun arg) = (FunTy $! (go fun)) $! (go arg)
948 go (ForAllTy tv ty) = ForAllTy tvp $! (tidyType envp ty)
950 (envp, tvp) = tidyTyVarBndr env tv
952 tidyTypes :: TidyEnv -> [Type] -> [Type]
953 tidyTypes env tys = map (tidyType env) tys
955 tidyPred :: TidyEnv -> PredType -> PredType
956 tidyPred env (IParam n ty) = IParam n (tidyType env ty)
957 tidyPred env (ClassP clas tys) = ClassP clas (tidyTypes env tys)
958 tidyPred env (EqPred ty1 ty2) = EqPred (tidyType env ty1) (tidyType env ty2)
963 -- | Grabs the free type variables, tidies them
964 -- and then uses 'tidyType' to work over the type itself
965 tidyOpenType :: TidyEnv -> Type -> (TidyEnv, Type)
967 = (env', tidyType env' ty)
969 env' = tidyFreeTyVars env (tyVarsOfType ty)
971 tidyOpenTypes :: TidyEnv -> [Type] -> (TidyEnv, [Type])
972 tidyOpenTypes env tys = mapAccumL tidyOpenType env tys
974 -- | Calls 'tidyType' on a top-level type (i.e. with an empty tidying environment)
975 tidyTopType :: Type -> Type
976 tidyTopType ty = tidyType emptyTidyEnv ty
981 tidyKind :: TidyEnv -> Kind -> (TidyEnv, Kind)
982 tidyKind env k = tidyOpenType env k
987 %************************************************************************
989 \subsection{Liftedness}
991 %************************************************************************
994 -- | See "Type#type_classification" for what an unlifted type is
995 isUnLiftedType :: Type -> Bool
996 -- isUnLiftedType returns True for forall'd unlifted types:
997 -- x :: forall a. Int#
998 -- I found bindings like these were getting floated to the top level.
999 -- They are pretty bogus types, mind you. It would be better never to
1002 isUnLiftedType ty | Just ty' <- coreView ty = isUnLiftedType ty'
1003 isUnLiftedType (ForAllTy _ ty) = isUnLiftedType ty
1004 isUnLiftedType (TyConApp tc _) = isUnLiftedTyCon tc
1005 isUnLiftedType _ = False
1007 isUnboxedTupleType :: Type -> Bool
1008 isUnboxedTupleType ty = case splitTyConApp_maybe ty of
1009 Just (tc, _ty_args) -> isUnboxedTupleTyCon tc
1012 -- | See "Type#type_classification" for what an algebraic type is.
1013 -- Should only be applied to /types/, as opposed to e.g. partially
1014 -- saturated type constructors
1015 isAlgType :: Type -> Bool
1017 = case splitTyConApp_maybe ty of
1018 Just (tc, ty_args) -> ASSERT( ty_args `lengthIs` tyConArity tc )
1022 -- | See "Type#type_classification" for what an algebraic type is.
1023 -- Should only be applied to /types/, as opposed to e.g. partially
1024 -- saturated type constructors. Closed type constructors are those
1025 -- with a fixed right hand side, as opposed to e.g. associated types
1026 isClosedAlgType :: Type -> Bool
1028 = case splitTyConApp_maybe ty of
1029 Just (tc, ty_args) -> ASSERT( ty_args `lengthIs` tyConArity tc )
1030 isAlgTyCon tc && not (isOpenTyCon tc)
1035 -- | Computes whether an argument (or let right hand side) should
1036 -- be computed strictly or lazily, based only on its type.
1037 -- Works just like 'isUnLiftedType', except that it has a special case
1038 -- for dictionaries (i.e. does not work purely on representation types)
1040 -- Since it takes account of class 'PredType's, you might think
1041 -- this function should be in 'TcType', but 'isStrictType' is used by 'DataCon',
1042 -- which is below 'TcType' in the hierarchy, so it's convenient to put it here.
1043 isStrictType :: Type -> Bool
1044 isStrictType (PredTy pred) = isStrictPred pred
1045 isStrictType ty | Just ty' <- coreView ty = isStrictType ty'
1046 isStrictType (ForAllTy _ ty) = isStrictType ty
1047 isStrictType (TyConApp tc _) = isUnLiftedTyCon tc
1048 isStrictType _ = False
1050 -- | We may be strict in dictionary types, but only if it
1051 -- has more than one component.
1053 -- (Being strict in a single-component dictionary risks
1054 -- poking the dictionary component, which is wrong.)
1055 isStrictPred :: PredType -> Bool
1056 isStrictPred (ClassP clas _) = opt_DictsStrict && not (isNewTyCon (classTyCon clas))
1057 isStrictPred _ = False
1061 isPrimitiveType :: Type -> Bool
1062 -- ^ Returns true of types that are opaque to Haskell.
1063 -- Most of these are unlifted, but now that we interact with .NET, we
1064 -- may have primtive (foreign-imported) types that are lifted
1065 isPrimitiveType ty = case splitTyConApp_maybe ty of
1066 Just (tc, ty_args) -> ASSERT( ty_args `lengthIs` tyConArity tc )
1072 %************************************************************************
1074 \subsection{Sequencing on types}
1076 %************************************************************************
1079 seqType :: Type -> ()
1080 seqType (TyVarTy tv) = tv `seq` ()
1081 seqType (AppTy t1 t2) = seqType t1 `seq` seqType t2
1082 seqType (FunTy t1 t2) = seqType t1 `seq` seqType t2
1083 seqType (PredTy p) = seqPred p
1084 seqType (TyConApp tc tys) = tc `seq` seqTypes tys
1085 seqType (ForAllTy tv ty) = tv `seq` seqType ty
1087 seqTypes :: [Type] -> ()
1089 seqTypes (ty:tys) = seqType ty `seq` seqTypes tys
1091 seqPred :: PredType -> ()
1092 seqPred (ClassP c tys) = c `seq` seqTypes tys
1093 seqPred (IParam n ty) = n `seq` seqType ty
1094 seqPred (EqPred ty1 ty2) = seqType ty1 `seq` seqType ty2
1098 %************************************************************************
1100 Equality for Core types
1101 (We don't use instances so that we know where it happens)
1103 %************************************************************************
1105 Note that eqType works right even for partial applications of newtypes.
1106 See Note [Newtype eta] in TyCon.lhs
1109 -- | Type equality test for Core types (i.e. ignores predicate-types, synonyms etc.)
1110 coreEqType :: Type -> Type -> Bool
1114 rn_env = mkRnEnv2 (mkInScopeSet (tyVarsOfType t1 `unionVarSet` tyVarsOfType t2))
1116 eq env (TyVarTy tv1) (TyVarTy tv2) = rnOccL env tv1 == rnOccR env tv2
1117 eq env (ForAllTy tv1 t1) (ForAllTy tv2 t2) = eq (rnBndr2 env tv1 tv2) t1 t2
1118 eq env (AppTy s1 t1) (AppTy s2 t2) = eq env s1 s2 && eq env t1 t2
1119 eq env (FunTy s1 t1) (FunTy s2 t2) = eq env s1 s2 && eq env t1 t2
1120 eq env (TyConApp tc1 tys1) (TyConApp tc2 tys2)
1121 | tc1 == tc2, all2 (eq env) tys1 tys2 = True
1122 -- The lengths should be equal because
1123 -- the two types have the same kind
1124 -- NB: if the type constructors differ that does not
1125 -- necessarily mean that the types aren't equal
1126 -- (synonyms, newtypes)
1127 -- Even if the type constructors are the same, but the arguments
1128 -- differ, the two types could be the same (e.g. if the arg is just
1129 -- ignored in the RHS). In both these cases we fall through to an
1130 -- attempt to expand one side or the other.
1132 -- Now deal with newtypes, synonyms, pred-tys
1133 eq env t1 t2 | Just t1' <- coreView t1 = eq env t1' t2
1134 | Just t2' <- coreView t2 = eq env t1 t2'
1136 -- Fall through case; not equal!
1141 %************************************************************************
1143 Comparision for source types
1144 (We don't use instances so that we know where it happens)
1146 %************************************************************************
1149 tcEqType :: Type -> Type -> Bool
1150 -- ^ Type equality on source types. Does not look through @newtypes@ or 'PredType's
1151 tcEqType t1 t2 = isEqual $ cmpType t1 t2
1153 tcEqTypes :: [Type] -> [Type] -> Bool
1154 tcEqTypes tys1 tys2 = isEqual $ cmpTypes tys1 tys2
1156 tcCmpType :: Type -> Type -> Ordering
1157 -- ^ Type ordering on source types. Does not look through @newtypes@ or 'PredType's
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 extendTvInScope :: TvSubst -> [Var] -> TvSubst
1403 extendTvInScope (TvSubst in_scope env) vars = TvSubst (extendInScopeSetList in_scope vars) env
1405 extendTvSubst :: TvSubst -> TyVar -> Type -> TvSubst
1406 extendTvSubst (TvSubst in_scope env) tv ty = TvSubst in_scope (extendVarEnv env tv ty)
1408 extendTvSubstList :: TvSubst -> [TyVar] -> [Type] -> TvSubst
1409 extendTvSubstList (TvSubst in_scope env) tvs tys
1410 = TvSubst in_scope (extendVarEnvList env (tvs `zip` tys))
1412 -- mkOpenTvSubst and zipOpenTvSubst generate the in-scope set from
1413 -- the types given; but it's just a thunk so with a bit of luck
1414 -- it'll never be evaluated
1416 -- Note [Generating the in-scope set for a substitution]
1417 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1418 -- If we want to substitute [a -> ty1, b -> ty2] I used to
1419 -- think it was enough to generate an in-scope set that includes
1420 -- fv(ty1,ty2). But that's not enough; we really should also take the
1421 -- free vars of the type we are substituting into! Example:
1422 -- (forall b. (a,b,x)) [a -> List b]
1423 -- Then if we use the in-scope set {b}, there is a danger we will rename
1424 -- the forall'd variable to 'x' by mistake, getting this:
1425 -- (forall x. (List b, x, x)
1426 -- Urk! This means looking at all the calls to mkOpenTvSubst....
1429 -- | Generates the in-scope set for the 'TvSubst' from the types in the incoming
1430 -- environment, hence "open"
1431 mkOpenTvSubst :: TvSubstEnv -> TvSubst
1432 mkOpenTvSubst env = TvSubst (mkInScopeSet (tyVarsOfTypes (varEnvElts env))) env
1434 -- | Generates the in-scope set for the 'TvSubst' from the types in the incoming
1435 -- environment, hence "open"
1436 zipOpenTvSubst :: [TyVar] -> [Type] -> TvSubst
1437 zipOpenTvSubst tyvars tys
1438 | debugIsOn && (length tyvars /= length tys)
1439 = pprTrace "zipOpenTvSubst" (ppr tyvars $$ ppr tys) emptyTvSubst
1441 = TvSubst (mkInScopeSet (tyVarsOfTypes tys)) (zipTyEnv tyvars tys)
1443 -- | Called when doing top-level substitutions. Here we expect that the
1444 -- free vars of the range of the substitution will be empty.
1445 mkTopTvSubst :: [(TyVar, Type)] -> TvSubst
1446 mkTopTvSubst prs = TvSubst emptyInScopeSet (mkVarEnv prs)
1448 zipTopTvSubst :: [TyVar] -> [Type] -> TvSubst
1449 zipTopTvSubst tyvars tys
1450 | debugIsOn && (length tyvars /= length tys)
1451 = pprTrace "zipTopTvSubst" (ppr tyvars $$ ppr tys) emptyTvSubst
1453 = TvSubst emptyInScopeSet (zipTyEnv tyvars tys)
1455 zipTyEnv :: [TyVar] -> [Type] -> TvSubstEnv
1457 | debugIsOn && (length tyvars /= length tys)
1458 = pprTrace "mkTopTvSubst" (ppr tyvars $$ ppr tys) emptyVarEnv
1460 = zip_ty_env tyvars tys emptyVarEnv
1462 -- Later substitutions in the list over-ride earlier ones,
1463 -- but there should be no loops
1464 zip_ty_env :: [TyVar] -> [Type] -> TvSubstEnv -> TvSubstEnv
1465 zip_ty_env [] [] env = env
1466 zip_ty_env (tv:tvs) (ty:tys) env = zip_ty_env tvs tys (extendVarEnv env tv ty)
1467 -- There used to be a special case for when
1469 -- (a not-uncommon case) in which case the substitution was dropped.
1470 -- But the type-tidier changes the print-name of a type variable without
1471 -- changing the unique, and that led to a bug. Why? Pre-tidying, we had
1472 -- a type {Foo t}, where Foo is a one-method class. So Foo is really a newtype.
1473 -- And it happened that t was the type variable of the class. Post-tiding,
1474 -- it got turned into {Foo t2}. The ext-core printer expanded this using
1475 -- sourceTypeRep, but that said "Oh, t == t2" because they have the same unique,
1476 -- and so generated a rep type mentioning t not t2.
1478 -- Simplest fix is to nuke the "optimisation"
1479 zip_ty_env tvs tys env = pprTrace "Var/Type length mismatch: " (ppr tvs $$ ppr tys) env
1480 -- zip_ty_env _ _ env = env
1482 instance Outputable TvSubst where
1483 ppr (TvSubst ins env)
1484 = brackets $ sep[ ptext (sLit "TvSubst"),
1485 nest 2 (ptext (sLit "In scope:") <+> ppr ins),
1486 nest 2 (ptext (sLit "Env:") <+> ppr env) ]
1489 %************************************************************************
1491 Performing type substitutions
1493 %************************************************************************
1496 -- | Type substitution making use of an 'TvSubst' that
1497 -- is assumed to be open, see 'zipOpenTvSubst'
1498 substTyWith :: [TyVar] -> [Type] -> Type -> Type
1499 substTyWith tvs tys = ASSERT( length tvs == length tys )
1500 substTy (zipOpenTvSubst tvs tys)
1502 -- | Type substitution making use of an 'TvSubst' that
1503 -- is assumed to be open, see 'zipOpenTvSubst'
1504 substTysWith :: [TyVar] -> [Type] -> [Type] -> [Type]
1505 substTysWith tvs tys = ASSERT( length tvs == length tys )
1506 substTys (zipOpenTvSubst tvs tys)
1508 -- | Substitute within a 'Type'
1509 substTy :: TvSubst -> Type -> Type
1510 substTy subst ty | isEmptyTvSubst subst = ty
1511 | otherwise = subst_ty subst ty
1513 -- | Substitute within several 'Type's
1514 substTys :: TvSubst -> [Type] -> [Type]
1515 substTys subst tys | isEmptyTvSubst subst = tys
1516 | otherwise = map (subst_ty subst) tys
1518 -- | Substitute within a 'ThetaType'
1519 substTheta :: TvSubst -> ThetaType -> ThetaType
1520 substTheta subst theta
1521 | isEmptyTvSubst subst = theta
1522 | otherwise = map (substPred subst) theta
1524 -- | Substitute within a 'PredType'
1525 substPred :: TvSubst -> PredType -> PredType
1526 substPred subst (IParam n ty) = IParam n (subst_ty subst ty)
1527 substPred subst (ClassP clas tys) = ClassP clas (map (subst_ty subst) tys)
1528 substPred subst (EqPred ty1 ty2) = EqPred (subst_ty subst ty1) (subst_ty subst ty2)
1530 -- | Remove any nested binders mentioning the 'TyVar's in the 'TyVarSet'
1531 deShadowTy :: TyVarSet -> Type -> Type
1533 = subst_ty (mkTvSubst in_scope emptyTvSubstEnv) ty
1535 in_scope = mkInScopeSet tvs
1537 subst_ty :: TvSubst -> Type -> Type
1538 -- subst_ty is the main workhorse for type substitution
1540 -- Note that the in_scope set is poked only if we hit a forall
1541 -- so it may often never be fully computed
1545 go (TyVarTy tv) = substTyVar subst tv
1546 go (TyConApp tc tys) = let args = map go tys
1547 in args `seqList` TyConApp tc args
1549 go (PredTy p) = PredTy $! (substPred subst p)
1551 go (FunTy arg res) = (FunTy $! (go arg)) $! (go res)
1552 go (AppTy fun arg) = mkAppTy (go fun) $! (go arg)
1553 -- The mkAppTy smart constructor is important
1554 -- we might be replacing (a Int), represented with App
1555 -- by [Int], represented with TyConApp
1556 go (ForAllTy tv ty) = case substTyVarBndr subst tv of
1558 ForAllTy tv' $! (subst_ty subst' ty)
1560 substTyVar :: TvSubst -> TyVar -> Type
1561 substTyVar subst@(TvSubst _ _) tv
1562 = case lookupTyVar subst tv of {
1563 Nothing -> TyVarTy tv;
1564 Just ty -> ty -- See Note [Apply Once]
1567 substTyVars :: TvSubst -> [TyVar] -> [Type]
1568 substTyVars subst tvs = map (substTyVar subst) tvs
1570 lookupTyVar :: TvSubst -> TyVar -> Maybe Type
1571 -- See Note [Extending the TvSubst]
1572 lookupTyVar (TvSubst _ env) tv = lookupVarEnv env tv
1574 substTyVarBndr :: TvSubst -> TyVar -> (TvSubst, TyVar)
1575 substTyVarBndr subst@(TvSubst in_scope env) old_var
1576 = (TvSubst (in_scope `extendInScopeSet` new_var) new_env, new_var)
1578 is_co_var = isCoVar old_var
1580 new_env | no_change = delVarEnv env old_var
1581 | otherwise = extendVarEnv env old_var (TyVarTy new_var)
1583 no_change = new_var == old_var && not is_co_var
1584 -- no_change means that the new_var is identical in
1585 -- all respects to the old_var (same unique, same kind)
1586 -- See Note [Extending the TvSubst]
1588 -- In that case we don't need to extend the substitution
1589 -- to map old to new. But instead we must zap any
1590 -- current substitution for the variable. For example:
1591 -- (\x.e) with id_subst = [x |-> e']
1592 -- Here we must simply zap the substitution for x
1594 new_var = uniqAway in_scope subst_old_var
1595 -- The uniqAway part makes sure the new variable is not already in scope
1597 subst_old_var -- subst_old_var is old_var with the substitution applied to its kind
1598 -- It's only worth doing the substitution for coercions,
1599 -- becuase only they can have free type variables
1600 | is_co_var = setTyVarKind old_var (substTy subst (tyVarKind old_var))
1601 | otherwise = old_var
1604 ----------------------------------------------------
1613 -- There's a little subtyping at the kind level:
1623 -- Where: \* [LiftedTypeKind] means boxed type
1624 -- \# [UnliftedTypeKind] means unboxed type
1625 -- (\#) [UbxTupleKind] means unboxed tuple
1626 -- ?? [ArgTypeKind] is the lub of {\*, \#}
1627 -- ? [OpenTypeKind] means any type at all
1632 -- > error :: forall a:?. String -> a
1633 -- > (->) :: ?? -> ? -> \*
1634 -- > (\\(x::t) -> ...)
1636 -- Where in the last example @t :: ??@ (i.e. is not an unboxed tuple)
1638 type KindVar = TyVar -- invariant: KindVar will always be a
1639 -- TcTyVar with details MetaTv TauTv ...
1640 -- kind var constructors and functions are in TcType
1642 type SimpleKind = Kind
1647 During kind inference, a kind variable unifies only with
1649 sk ::= * | sk1 -> sk2
1651 data T a = MkT a (T Int#)
1652 fails. We give T the kind (k -> *), and the kind variable k won't unify
1653 with # (the kind of Int#).
1657 When creating a fresh internal type variable, we give it a kind to express
1658 constraints on it. E.g. in (\x->e) we make up a fresh type variable for x,
1661 During unification we only bind an internal type variable to a type
1662 whose kind is lower in the sub-kind hierarchy than the kind of the tyvar.
1664 When unifying two internal type variables, we collect their kind constraints by
1665 finding the GLB of the two. Since the partial order is a tree, they only
1666 have a glb if one is a sub-kind of the other. In that case, we bind the
1667 less-informative one to the more informative one. Neat, eh?
1674 %************************************************************************
1676 Functions over Kinds
1678 %************************************************************************
1681 -- | Essentially 'funResultTy' on kinds
1682 kindFunResult :: Kind -> Kind
1683 kindFunResult k = funResultTy k
1685 -- | Essentially 'splitFunTys' on kinds
1686 splitKindFunTys :: Kind -> ([Kind],Kind)
1687 splitKindFunTys k = splitFunTys k
1689 -- | Essentially 'splitFunTysN' on kinds
1690 splitKindFunTysN :: Int -> Kind -> ([Kind],Kind)
1691 splitKindFunTysN k = splitFunTysN k
1693 -- | See "Type#kind_subtyping" for details of the distinction between these 'Kind's
1694 isUbxTupleKind, isOpenTypeKind, isArgTypeKind, isUnliftedTypeKind :: Kind -> Bool
1695 isOpenTypeKindCon, isUbxTupleKindCon, isArgTypeKindCon,
1696 isUnliftedTypeKindCon, isSubArgTypeKindCon :: TyCon -> Bool
1698 isOpenTypeKindCon tc = tyConUnique tc == openTypeKindTyConKey
1700 isOpenTypeKind (TyConApp tc _) = isOpenTypeKindCon tc
1701 isOpenTypeKind _ = False
1703 isUbxTupleKindCon tc = tyConUnique tc == ubxTupleKindTyConKey
1705 isUbxTupleKind (TyConApp tc _) = isUbxTupleKindCon tc
1706 isUbxTupleKind _ = False
1708 isArgTypeKindCon tc = tyConUnique tc == argTypeKindTyConKey
1710 isArgTypeKind (TyConApp tc _) = isArgTypeKindCon tc
1711 isArgTypeKind _ = False
1713 isUnliftedTypeKindCon tc = tyConUnique tc == unliftedTypeKindTyConKey
1715 isUnliftedTypeKind (TyConApp tc _) = isUnliftedTypeKindCon tc
1716 isUnliftedTypeKind _ = False
1718 isSubOpenTypeKind :: Kind -> Bool
1719 -- ^ True of any sub-kind of OpenTypeKind (i.e. anything except arrow)
1720 isSubOpenTypeKind (FunTy k1 k2) = ASSERT2 ( isKind k1, text "isSubOpenTypeKind" <+> ppr k1 <+> text "::" <+> ppr (typeKind k1) )
1721 ASSERT2 ( isKind k2, text "isSubOpenTypeKind" <+> ppr k2 <+> text "::" <+> ppr (typeKind k2) )
1723 isSubOpenTypeKind (TyConApp kc []) = ASSERT( isKind (TyConApp kc []) ) True
1724 isSubOpenTypeKind other = ASSERT( isKind other ) False
1725 -- This is a conservative answer
1726 -- It matters in the call to isSubKind in
1727 -- checkExpectedKind.
1729 isSubArgTypeKindCon kc
1730 | isUnliftedTypeKindCon kc = True
1731 | isLiftedTypeKindCon kc = True
1732 | isArgTypeKindCon kc = True
1735 isSubArgTypeKind :: Kind -> Bool
1736 -- ^ True of any sub-kind of ArgTypeKind
1737 isSubArgTypeKind (TyConApp kc []) = isSubArgTypeKindCon kc
1738 isSubArgTypeKind _ = False
1740 -- | Is this a super-kind (i.e. a type-of-kinds)?
1741 isSuperKind :: Type -> Bool
1742 isSuperKind (TyConApp (skc) []) = isSuperKindTyCon skc
1743 isSuperKind _ = False
1745 -- | Is this a kind (i.e. a type-of-types)?
1746 isKind :: Kind -> Bool
1747 isKind k = isSuperKind (typeKind k)
1749 isSubKind :: Kind -> Kind -> Bool
1750 -- ^ @k1 \`isSubKind\` k2@ checks that @k1@ <: @k2@
1751 isSubKind (TyConApp kc1 []) (TyConApp kc2 []) = kc1 `isSubKindCon` kc2
1752 isSubKind (FunTy a1 r1) (FunTy a2 r2) = (a2 `isSubKind` a1) && (r1 `isSubKind` r2)
1753 isSubKind (PredTy (EqPred ty1 ty2)) (PredTy (EqPred ty1' ty2'))
1754 = ty1 `tcEqType` ty1' && ty2 `tcEqType` ty2'
1755 isSubKind _ _ = False
1757 eqKind :: Kind -> Kind -> Bool
1760 isSubKindCon :: TyCon -> TyCon -> Bool
1761 -- ^ @kc1 \`isSubKindCon\` kc2@ checks that @kc1@ <: @kc2@
1762 isSubKindCon kc1 kc2
1763 | isLiftedTypeKindCon kc1 && isLiftedTypeKindCon kc2 = True
1764 | isUnliftedTypeKindCon kc1 && isUnliftedTypeKindCon kc2 = True
1765 | isUbxTupleKindCon kc1 && isUbxTupleKindCon kc2 = True
1766 | isOpenTypeKindCon kc2 = True
1767 -- we already know kc1 is not a fun, its a TyCon
1768 | isArgTypeKindCon kc2 && isSubArgTypeKindCon kc1 = True
1771 defaultKind :: Kind -> Kind
1772 -- ^ Used when generalising: default kind ? and ?? to *. See "Type#kind_subtyping" for more
1773 -- information on what that means
1775 -- When we generalise, we make generic type variables whose kind is
1776 -- simple (* or *->* etc). So generic type variables (other than
1777 -- built-in constants like 'error') always have simple kinds. This is important;
1780 -- We want f to get type
1781 -- f :: forall (a::*). a -> Bool
1783 -- f :: forall (a::??). a -> Bool
1784 -- because that would allow a call like (f 3#) as well as (f True),
1785 --and the calling conventions differ. This defaulting is done in TcMType.zonkTcTyVarBndr.
1787 | isSubOpenTypeKind k = liftedTypeKind
1788 | isSubArgTypeKind k = liftedTypeKind
1791 isEqPred :: PredType -> Bool
1792 isEqPred (EqPred _ _) = True