2 % (c) The GRASP/AQUA Project, Glasgow University, 1998
4 \section[Type]{Type - public interface}
9 -- re-exports from TypeRep
10 TyThing(..), Type, PredType(..), ThetaType,
14 Kind, SimpleKind, KindVar,
15 kindFunResult, splitKindFunTys,
17 liftedTypeKindTyCon, openTypeKindTyCon, unliftedTypeKindTyCon,
18 argTypeKindTyCon, ubxTupleKindTyCon,
20 liftedTypeKind, unliftedTypeKind, openTypeKind,
21 argTypeKind, ubxTupleKind,
23 tySuperKind, coSuperKind,
25 isLiftedTypeKind, isUnliftedTypeKind, isOpenTypeKind,
26 isUbxTupleKind, isArgTypeKind, isKind, isTySuperKind,
27 isCoSuperKind, isSuperKind, isCoercionKind, isEqPred,
28 mkArrowKind, mkArrowKinds,
30 isSubArgTypeKind, isSubOpenTypeKind, isSubKind, defaultKind, eqKind,
33 -- Re-exports from TyCon
36 mkTyVarTy, mkTyVarTys, getTyVar, getTyVar_maybe, isTyVarTy,
38 mkAppTy, mkAppTys, splitAppTy, splitAppTys,
39 splitAppTy_maybe, repSplitAppTy_maybe,
41 mkFunTy, mkFunTys, splitFunTy, splitFunTy_maybe,
42 splitFunTys, splitFunTysN,
43 funResultTy, funArgTy, zipFunTys, isFunTy,
45 mkTyConApp, mkTyConTy,
46 tyConAppTyCon, tyConAppArgs,
47 splitTyConApp_maybe, splitTyConApp,
48 splitNewTyConApp_maybe, splitNewTyConApp,
50 repType, typePrimRep, coreView, tcView, kindView,
52 mkForAllTy, mkForAllTys, splitForAllTy_maybe, splitForAllTys,
53 applyTy, applyTys, isForAllTy, dropForAlls,
56 predTypeRep, mkPredTy, mkPredTys,
59 splitRecNewType_maybe, newTyConInstRhs,
62 isUnLiftedType, isUnboxedTupleType, isAlgType, isPrimitiveType,
63 isStrictType, isStrictPred,
66 tyVarsOfType, tyVarsOfTypes, tyVarsOfPred, tyVarsOfTheta,
67 typeKind, addFreeTyVars,
69 -- Tidying up for printing
71 tidyOpenType, tidyOpenTypes,
72 tidyTyVarBndr, tidyFreeTyVars,
73 tidyOpenTyVar, tidyOpenTyVars,
74 tidyTopType, tidyPred,
78 coreEqType, tcEqType, tcEqTypes, tcCmpType, tcCmpTypes,
79 tcEqPred, tcCmpPred, tcEqTypeX,
85 TvSubstEnv, emptyTvSubstEnv, -- Representation widely visible
86 TvSubst(..), emptyTvSubst, -- Representation visible to a few friends
87 mkTvSubst, mkOpenTvSubst, zipOpenTvSubst, zipTopTvSubst, mkTopTvSubst, notElemTvSubst,
88 getTvSubstEnv, setTvSubstEnv, getTvInScope, extendTvInScope,
89 extendTvSubst, extendTvSubstList, isInScope, composeTvSubst, zipTyEnv,
91 -- Performing substitution on types
92 substTy, substTys, substTyWith, substTheta,
93 substPred, substTyVar, substTyVarBndr, deShadowTy, lookupTyVar,
96 pprType, pprParendType, pprTyThingCategory,
97 pprPred, pprTheta, pprThetaArrow, pprClassPred, pprKind, pprParendKind
100 #include "HsVersions.h"
102 -- We import the representation and primitive functions from TypeRep.
103 -- Many things are reexported, but not the representation!
108 import Var ( Var, TyVar, tyVarKind, tyVarName,
109 setTyVarName, setTyVarKind, mkWildCoVar )
113 import OccName ( tidyOccName )
114 import Name ( NamedThing(..), tidyNameOcc )
115 import Class ( Class, classTyCon )
116 import PrelNames( openTypeKindTyConKey, unliftedTypeKindTyConKey,
117 ubxTupleKindTyConKey, argTypeKindTyConKey )
118 import TyCon ( TyCon, isRecursiveTyCon, isPrimTyCon,
119 isUnboxedTupleTyCon, isUnLiftedTyCon,
120 isFunTyCon, isNewTyCon, newTyConRep, newTyConRhs,
121 isAlgTyCon, tyConArity, isSuperKindTyCon,
122 tcExpandTyCon_maybe, coreExpandTyCon_maybe,
123 tyConKind, PrimRep(..), tyConPrimRep, tyConUnique,
124 isCoercionTyCon_maybe, isCoercionTyCon
128 import StaticFlags ( opt_DictsStrict )
129 import Util ( mapAccumL, seqList, lengthIs, snocView, thenCmp, isEqual, all2 )
131 import UniqSet ( sizeUniqSet ) -- Should come via VarSet
132 import Maybe ( isJust )
136 %************************************************************************
140 %************************************************************************
142 In Core, we "look through" non-recursive newtypes and PredTypes.
145 {-# INLINE coreView #-}
146 coreView :: Type -> Maybe Type
147 -- Strips off the *top layer only* of a type to give
148 -- its underlying representation type.
149 -- Returns Nothing if there is nothing to look through.
151 -- In the case of newtypes, it returns
152 -- *either* a vanilla TyConApp (recursive newtype, or non-saturated)
153 -- *or* the newtype representation (otherwise), meaning the
154 -- type written in the RHS of the newtype decl,
155 -- which may itself be a newtype
157 -- Example: newtype R = MkR S
159 -- newtype T = MkT (T -> T)
160 -- expandNewTcApp on R gives Just S
162 -- on T gives Nothing (no expansion)
164 -- By being non-recursive and inlined, this case analysis gets efficiently
165 -- joined onto the case analysis that the caller is already doing
166 coreView (NoteTy _ ty) = Just ty
168 | isEqPred p = Nothing
169 | otherwise = Just (predTypeRep p)
170 coreView (TyConApp tc tys) | Just (tenv, rhs, tys') <- coreExpandTyCon_maybe tc tys
171 = Just (mkAppTys (substTy (mkTopTvSubst tenv) rhs) tys')
172 -- Its important to use mkAppTys, rather than (foldl AppTy),
173 -- because the function part might well return a
174 -- partially-applied type constructor; indeed, usually will!
175 coreView ty = Nothing
179 -----------------------------------------------
180 {-# INLINE tcView #-}
181 tcView :: Type -> Maybe Type
182 -- Same, but for the type checker, which just looks through synonyms
183 tcView (NoteTy _ ty) = Just ty
184 tcView (TyConApp tc tys) | Just (tenv, rhs, tys') <- tcExpandTyCon_maybe tc tys
185 = Just (mkAppTys (substTy (mkTopTvSubst tenv) rhs) tys')
188 -----------------------------------------------
189 {-# INLINE kindView #-}
190 kindView :: Kind -> Maybe Kind
191 -- C.f. coreView, tcView
192 -- For the moment, we don't even handle synonyms in kinds
193 kindView (NoteTy _ k) = Just k
194 kindView other = Nothing
198 %************************************************************************
200 \subsection{Constructor-specific functions}
202 %************************************************************************
205 ---------------------------------------------------------------------
209 mkTyVarTy :: TyVar -> Type
212 mkTyVarTys :: [TyVar] -> [Type]
213 mkTyVarTys = map mkTyVarTy -- a common use of mkTyVarTy
215 getTyVar :: String -> Type -> TyVar
216 getTyVar msg ty = case getTyVar_maybe ty of
218 Nothing -> panic ("getTyVar: " ++ msg)
220 isTyVarTy :: Type -> Bool
221 isTyVarTy ty = isJust (getTyVar_maybe ty)
223 getTyVar_maybe :: Type -> Maybe TyVar
224 getTyVar_maybe ty | Just ty' <- coreView ty = getTyVar_maybe ty'
225 getTyVar_maybe (TyVarTy tv) = Just tv
226 getTyVar_maybe other = Nothing
231 ---------------------------------------------------------------------
234 We need to be pretty careful with AppTy to make sure we obey the
235 invariant that a TyConApp is always visibly so. mkAppTy maintains the
239 mkAppTy orig_ty1 orig_ty2
242 mk_app (NoteTy _ ty1) = mk_app ty1
243 mk_app (TyConApp tc tys) = mkTyConApp tc (tys ++ [orig_ty2])
244 mk_app ty1 = AppTy orig_ty1 orig_ty2
245 -- Note that the TyConApp could be an
246 -- under-saturated type synonym. GHC allows that; e.g.
247 -- type Foo k = k a -> k a
249 -- foo :: Foo Id -> Foo Id
251 -- Here Id is partially applied in the type sig for Foo,
252 -- but once the type synonyms are expanded all is well
254 mkAppTys :: Type -> [Type] -> Type
255 mkAppTys orig_ty1 [] = orig_ty1
256 -- This check for an empty list of type arguments
257 -- avoids the needless loss of a type synonym constructor.
258 -- For example: mkAppTys Rational []
259 -- returns to (Ratio Integer), which has needlessly lost
260 -- the Rational part.
261 mkAppTys orig_ty1 orig_tys2
264 mk_app (NoteTy _ ty1) = mk_app ty1
265 mk_app (TyConApp tc tys) = mkTyConApp tc (tys ++ orig_tys2)
266 -- mkTyConApp: see notes with mkAppTy
267 mk_app ty1 = foldl AppTy orig_ty1 orig_tys2
270 splitAppTy_maybe :: Type -> Maybe (Type, Type)
271 splitAppTy_maybe ty | Just ty' <- coreView ty
272 = splitAppTy_maybe ty'
273 splitAppTy_maybe ty = repSplitAppTy_maybe ty
276 repSplitAppTy_maybe :: Type -> Maybe (Type,Type)
277 -- Does the AppTy split, but assumes that any view stuff is already done
278 repSplitAppTy_maybe (FunTy ty1 ty2) = Just (TyConApp funTyCon [ty1], ty2)
279 repSplitAppTy_maybe (AppTy ty1 ty2) = Just (ty1, ty2)
280 repSplitAppTy_maybe (TyConApp tc tys) = case snocView tys of
281 Just (tys', ty') -> Just (TyConApp tc tys', ty')
283 repSplitAppTy_maybe other = Nothing
285 splitAppTy :: Type -> (Type, Type)
286 splitAppTy ty = case splitAppTy_maybe ty of
288 Nothing -> panic "splitAppTy"
291 splitAppTys :: Type -> (Type, [Type])
292 splitAppTys ty = split ty ty []
294 split orig_ty ty args | Just ty' <- coreView ty = split orig_ty ty' args
295 split orig_ty (AppTy ty arg) args = split ty ty (arg:args)
296 split orig_ty (TyConApp tc tc_args) args = (TyConApp tc [], tc_args ++ args)
297 split orig_ty (FunTy ty1 ty2) args = ASSERT( null args )
298 (TyConApp funTyCon [], [ty1,ty2])
299 split orig_ty ty args = (orig_ty, args)
304 ---------------------------------------------------------------------
309 mkFunTy :: Type -> Type -> Type
310 mkFunTy (PredTy (EqPred ty1 ty2)) res = mkForAllTy (mkWildCoVar (PredTy (EqPred ty1 ty2))) res
311 mkFunTy arg res = FunTy arg res
313 mkFunTys :: [Type] -> Type -> Type
314 mkFunTys tys ty = foldr mkFunTy ty tys
316 isFunTy :: Type -> Bool
317 isFunTy ty = isJust (splitFunTy_maybe ty)
319 splitFunTy :: Type -> (Type, Type)
320 splitFunTy ty | Just ty' <- coreView ty = splitFunTy ty'
321 splitFunTy (FunTy arg res) = (arg, res)
322 splitFunTy other = pprPanic "splitFunTy" (ppr other)
324 splitFunTy_maybe :: Type -> Maybe (Type, Type)
325 splitFunTy_maybe ty | Just ty' <- coreView ty = splitFunTy_maybe ty'
326 splitFunTy_maybe (FunTy arg res) = Just (arg, res)
327 splitFunTy_maybe other = Nothing
329 splitFunTys :: Type -> ([Type], Type)
330 splitFunTys ty = split [] ty ty
332 split args orig_ty ty | Just ty' <- coreView ty = split args orig_ty ty'
333 split args orig_ty (FunTy arg res) = split (arg:args) res res
334 split args orig_ty ty = (reverse args, orig_ty)
336 splitFunTysN :: Int -> Type -> ([Type], Type)
337 -- Split off exactly n arg tys
338 splitFunTysN 0 ty = ([], ty)
339 splitFunTysN n ty = case splitFunTy ty of { (arg, res) ->
340 case splitFunTysN (n-1) res of { (args, res) ->
343 zipFunTys :: Outputable a => [a] -> Type -> ([(a,Type)], Type)
344 zipFunTys orig_xs orig_ty = split [] orig_xs orig_ty orig_ty
346 split acc [] nty ty = (reverse acc, nty)
348 | Just ty' <- coreView ty = split acc xs nty ty'
349 split acc (x:xs) nty (FunTy arg res) = split ((x,arg):acc) xs res res
350 split acc (x:xs) nty ty = pprPanic "zipFunTys" (ppr orig_xs <+> ppr orig_ty)
352 funResultTy :: Type -> Type
353 funResultTy ty | Just ty' <- coreView ty = funResultTy ty'
354 funResultTy (FunTy arg res) = res
355 funResultTy ty = pprPanic "funResultTy" (ppr ty)
357 funArgTy :: Type -> Type
358 funArgTy ty | Just ty' <- coreView ty = funArgTy ty'
359 funArgTy (FunTy arg res) = arg
360 funArgTy ty = pprPanic "funArgTy" (ppr ty)
364 ---------------------------------------------------------------------
367 @mkTyConApp@ is a key function, because it builds a TyConApp, FunTy or PredTy,
371 mkTyConApp :: TyCon -> [Type] -> Type
373 | isFunTyCon tycon, [ty1,ty2] <- tys
379 mkTyConTy :: TyCon -> Type
380 mkTyConTy tycon = mkTyConApp tycon []
382 -- splitTyConApp "looks through" synonyms, because they don't
383 -- mean a distinct type, but all other type-constructor applications
384 -- including functions are returned as Just ..
386 tyConAppTyCon :: Type -> TyCon
387 tyConAppTyCon ty = fst (splitTyConApp ty)
389 tyConAppArgs :: Type -> [Type]
390 tyConAppArgs ty = snd (splitTyConApp ty)
392 splitTyConApp :: Type -> (TyCon, [Type])
393 splitTyConApp ty = case splitTyConApp_maybe ty of
395 Nothing -> pprPanic "splitTyConApp" (ppr ty)
397 splitTyConApp_maybe :: Type -> Maybe (TyCon, [Type])
398 splitTyConApp_maybe ty | Just ty' <- coreView ty = splitTyConApp_maybe ty'
399 splitTyConApp_maybe (TyConApp tc tys) = Just (tc, tys)
400 splitTyConApp_maybe (FunTy arg res) = Just (funTyCon, [arg,res])
401 splitTyConApp_maybe other = Nothing
403 -- Sometimes we do NOT want to look throught a newtype. When case matching
404 -- on a newtype we want a convenient way to access the arguments of a newty
405 -- constructor so as to properly form a coercion.
406 splitNewTyConApp :: Type -> (TyCon, [Type])
407 splitNewTyConApp ty = case splitNewTyConApp_maybe ty of
409 Nothing -> pprPanic "splitNewTyConApp" (ppr ty)
410 splitNewTyConApp_maybe :: Type -> Maybe (TyCon, [Type])
411 splitNewTyConApp_maybe ty | Just ty' <- tcView ty = splitNewTyConApp_maybe ty'
412 splitNewTyConApp_maybe (TyConApp tc tys) = Just (tc, tys)
413 splitNewTyConApp_maybe (FunTy arg res) = Just (funTyCon, [arg,res])
414 splitNewTyConApp_maybe other = Nothing
416 -- get instantiated newtype rhs, the arguments had better saturate
418 newTyConInstRhs :: TyCon -> [Type] -> Type
419 newTyConInstRhs tycon tys =
420 let (tvs, ty) = newTyConRhs tycon in substTyWith tvs tys ty
425 ---------------------------------------------------------------------
429 Notes on type synonyms
430 ~~~~~~~~~~~~~~~~~~~~~~
431 The various "split" functions (splitFunTy, splitRhoTy, splitForAllTy) try
432 to return type synonyms whereever possible. Thus
437 splitFunTys (a -> Foo a) = ([a], Foo a)
440 The reason is that we then get better (shorter) type signatures in
441 interfaces. Notably this plays a role in tcTySigs in TcBinds.lhs.
446 repType looks through
450 (d) usage annotations
451 (e) all newtypes, including recursive ones
452 It's useful in the back end.
455 repType :: Type -> Type
456 -- Only applied to types of kind *; hence tycons are saturated
457 repType ty | Just ty' <- coreView ty = repType ty'
458 repType (ForAllTy _ ty) = repType ty
459 repType (TyConApp tc tys)
460 | isNewTyCon tc = -- Recursive newtypes are opaque to coreView
461 -- but we must expand them here. Sure to
462 -- be saturated because repType is only applied
463 -- to types of kind *
464 ASSERT( {- isRecursiveTyCon tc && -} tys `lengthIs` tyConArity tc )
465 repType (new_type_rep tc tys)
468 -- new_type_rep doesn't ask any questions:
469 -- it just expands newtype, whether recursive or not
470 new_type_rep new_tycon tys = ASSERT( tys `lengthIs` tyConArity new_tycon )
471 case newTyConRep new_tycon of
472 (tvs, rep_ty) -> substTyWith tvs tys rep_ty
474 -- ToDo: this could be moved to the code generator, using splitTyConApp instead
475 -- of inspecting the type directly.
476 typePrimRep :: Type -> PrimRep
477 typePrimRep ty = case repType ty of
478 TyConApp tc _ -> tyConPrimRep tc
480 AppTy _ _ -> PtrRep -- See note below
482 other -> pprPanic "typePrimRep" (ppr ty)
483 -- Types of the form 'f a' must be of kind *, not *#, so
484 -- we are guaranteed that they are represented by pointers.
485 -- The reason is that f must have kind *->*, not *->*#, because
486 -- (we claim) there is no way to constrain f's kind any other
492 ---------------------------------------------------------------------
497 mkForAllTy :: TyVar -> Type -> Type
499 = mkForAllTys [tyvar] ty
501 mkForAllTys :: [TyVar] -> Type -> Type
502 mkForAllTys tyvars ty = foldr ForAllTy ty tyvars
504 isForAllTy :: Type -> Bool
505 isForAllTy (NoteTy _ ty) = isForAllTy ty
506 isForAllTy (ForAllTy _ _) = True
507 isForAllTy other_ty = False
509 splitForAllTy_maybe :: Type -> Maybe (TyVar, Type)
510 splitForAllTy_maybe ty = splitFAT_m ty
512 splitFAT_m ty | Just ty' <- coreView ty = splitFAT_m ty'
513 splitFAT_m (ForAllTy tyvar ty) = Just(tyvar, ty)
514 splitFAT_m _ = Nothing
516 splitForAllTys :: Type -> ([TyVar], Type)
517 splitForAllTys ty = split ty ty []
519 split orig_ty ty tvs | Just ty' <- coreView ty = split orig_ty ty' tvs
520 split orig_ty (ForAllTy tv ty) tvs = split ty ty (tv:tvs)
521 split orig_ty t tvs = (reverse tvs, orig_ty)
523 dropForAlls :: Type -> Type
524 dropForAlls ty = snd (splitForAllTys ty)
527 -- (mkPiType now in CoreUtils)
531 Instantiate a for-all type with one or more type arguments.
532 Used when we have a polymorphic function applied to type args:
534 Then we use (applyTys type-of-f [t1,t2]) to compute the type of
538 applyTy :: Type -> Type -> Type
539 applyTy ty arg | Just ty' <- coreView ty = applyTy ty' arg
540 applyTy (ForAllTy tv ty) arg = substTyWith [tv] [arg] ty
541 applyTy other arg = panic "applyTy"
543 applyTys :: Type -> [Type] -> Type
544 -- This function is interesting because
545 -- a) the function may have more for-alls than there are args
546 -- b) less obviously, it may have fewer for-alls
547 -- For case (b) think of
548 -- applyTys (forall a.a) [forall b.b, Int]
549 -- This really can happen, via dressing up polymorphic types with newtype
550 -- clothing. Here's an example:
551 -- newtype R = R (forall a. a->a)
552 -- foo = case undefined :: R of
555 applyTys orig_fun_ty [] = orig_fun_ty
556 applyTys orig_fun_ty arg_tys
557 | n_tvs == n_args -- The vastly common case
558 = substTyWith tvs arg_tys rho_ty
559 | n_tvs > n_args -- Too many for-alls
560 = substTyWith (take n_args tvs) arg_tys
561 (mkForAllTys (drop n_args tvs) rho_ty)
562 | otherwise -- Too many type args
563 = ASSERT2( n_tvs > 0, ppr orig_fun_ty ) -- Zero case gives infnite loop!
564 applyTys (substTyWith tvs (take n_tvs arg_tys) rho_ty)
567 (tvs, rho_ty) = splitForAllTys orig_fun_ty
569 n_args = length arg_tys
573 %************************************************************************
575 \subsection{Source types}
577 %************************************************************************
579 A "source type" is a type that is a separate type as far as the type checker is
580 concerned, but which has low-level representation as far as the back end is concerned.
582 Source types are always lifted.
584 The key function is predTypeRep which gives the representation of a source type:
587 mkPredTy :: PredType -> Type
588 mkPredTy pred = PredTy pred
590 mkPredTys :: ThetaType -> [Type]
591 mkPredTys preds = map PredTy preds
593 predTypeRep :: PredType -> Type
594 -- Convert a PredType to its "representation type";
595 -- the post-type-checking type used by all the Core passes of GHC.
596 -- Unwraps only the outermost level; for example, the result might
597 -- be a newtype application
598 predTypeRep (IParam _ ty) = ty
599 predTypeRep (ClassP clas tys) = mkTyConApp (classTyCon clas) tys
600 -- Result might be a newtype application, but the consumer will
601 -- look through that too if necessary
602 predTypeRep (EqPred ty1 ty2) = pprPanic "predTypeRep" (ppr (EqPred ty1 ty2))
606 %************************************************************************
610 %************************************************************************
613 splitRecNewType_maybe :: Type -> Maybe Type
614 -- Sometimes we want to look through a recursive newtype, and that's what happens here
615 -- It only strips *one layer* off, so the caller will usually call itself recursively
616 -- Only applied to types of kind *, hence the newtype is always saturated
617 splitRecNewType_maybe ty | Just ty' <- coreView ty = splitRecNewType_maybe ty'
618 splitRecNewType_maybe (TyConApp tc tys)
620 = ASSERT( tys `lengthIs` tyConArity tc ) -- splitRecNewType_maybe only be applied
621 -- to *types* (of kind *)
622 ASSERT( isRecursiveTyCon tc ) -- Guaranteed by coreView
623 case newTyConRhs tc of
624 (tvs, rep_ty) -> ASSERT( length tvs == length tys )
625 Just (substTyWith tvs tys rep_ty)
627 splitRecNewType_maybe other = Nothing
634 %************************************************************************
636 \subsection{Kinds and free variables}
638 %************************************************************************
640 ---------------------------------------------------------------------
641 Finding the kind of a type
642 ~~~~~~~~~~~~~~~~~~~~~~~~~~
644 typeKind :: Type -> Kind
645 typeKind (TyConApp tycon tys) = ASSERT( not (isCoercionTyCon tycon) )
646 -- We should be looking for the coercion kind,
648 foldr (\_ k -> kindFunResult k) (tyConKind tycon) tys
649 typeKind (NoteTy _ ty) = typeKind ty
650 typeKind (PredTy pred) = predKind pred
651 typeKind (AppTy fun arg) = kindFunResult (typeKind fun)
652 typeKind (ForAllTy tv ty) = typeKind ty
653 typeKind (TyVarTy tyvar) = tyVarKind tyvar
654 typeKind (FunTy arg res)
655 -- Hack alert. The kind of (Int -> Int#) is liftedTypeKind (*),
656 -- not unliftedTypKind (#)
657 -- The only things that can be after a function arrow are
658 -- (a) types (of kind openTypeKind or its sub-kinds)
659 -- (b) kinds (of super-kind TY) (e.g. * -> (* -> *))
660 | isTySuperKind k = k
661 | otherwise = ASSERT( isSubOpenTypeKind k) liftedTypeKind
665 predKind :: PredType -> Kind
666 predKind (EqPred {}) = coSuperKind -- A coercion kind!
667 predKind (ClassP {}) = liftedTypeKind -- Class and implicitPredicates are
668 predKind (IParam {}) = liftedTypeKind -- always represented by lifted types
672 ---------------------------------------------------------------------
673 Free variables of a type
674 ~~~~~~~~~~~~~~~~~~~~~~~~
676 tyVarsOfType :: Type -> TyVarSet
677 -- NB: for type synonyms tyVarsOfType does *not* expand the synonym
678 tyVarsOfType (TyVarTy tv) = unitVarSet tv
679 tyVarsOfType (TyConApp tycon tys) = tyVarsOfTypes tys
680 tyVarsOfType (NoteTy (FTVNote tvs) ty2) = tvs
681 tyVarsOfType (PredTy sty) = tyVarsOfPred sty
682 tyVarsOfType (FunTy arg res) = tyVarsOfType arg `unionVarSet` tyVarsOfType res
683 tyVarsOfType (AppTy fun arg) = tyVarsOfType fun `unionVarSet` tyVarsOfType arg
684 tyVarsOfType (ForAllTy tyvar ty) = delVarSet (tyVarsOfType ty) tyvar
686 tyVarsOfTypes :: [Type] -> TyVarSet
687 tyVarsOfTypes tys = foldr (unionVarSet.tyVarsOfType) emptyVarSet tys
689 tyVarsOfPred :: PredType -> TyVarSet
690 tyVarsOfPred (IParam _ ty) = tyVarsOfType ty
691 tyVarsOfPred (ClassP _ tys) = tyVarsOfTypes tys
692 tyVarsOfPred (EqPred ty1 ty2) = tyVarsOfType ty1 `unionVarSet` tyVarsOfType ty2
694 tyVarsOfTheta :: ThetaType -> TyVarSet
695 tyVarsOfTheta = foldr (unionVarSet . tyVarsOfPred) emptyVarSet
697 -- Add a Note with the free tyvars to the top of the type
698 addFreeTyVars :: Type -> Type
699 addFreeTyVars ty@(NoteTy (FTVNote _) _) = ty
700 addFreeTyVars ty = NoteTy (FTVNote (tyVarsOfType ty)) ty
704 %************************************************************************
706 \subsection{TidyType}
708 %************************************************************************
710 tidyTy tidies up a type for printing in an error message, or in
713 It doesn't change the uniques at all, just the print names.
716 tidyTyVarBndr :: TidyEnv -> TyVar -> (TidyEnv, TyVar)
717 tidyTyVarBndr (tidy_env, subst) tyvar
718 = case tidyOccName tidy_env (getOccName name) of
719 (tidy', occ') -> ((tidy', subst'), tyvar')
721 subst' = extendVarEnv subst tyvar tyvar'
722 tyvar' = setTyVarName tyvar name'
723 name' = tidyNameOcc name occ'
725 name = tyVarName tyvar
727 tidyFreeTyVars :: TidyEnv -> TyVarSet -> TidyEnv
728 -- Add the free tyvars to the env in tidy form,
729 -- so that we can tidy the type they are free in
730 tidyFreeTyVars env tyvars = fst (tidyOpenTyVars env (varSetElems tyvars))
732 tidyOpenTyVars :: TidyEnv -> [TyVar] -> (TidyEnv, [TyVar])
733 tidyOpenTyVars env tyvars = mapAccumL tidyOpenTyVar env tyvars
735 tidyOpenTyVar :: TidyEnv -> TyVar -> (TidyEnv, TyVar)
736 -- Treat a new tyvar as a binder, and give it a fresh tidy name
737 tidyOpenTyVar env@(tidy_env, subst) tyvar
738 = case lookupVarEnv subst tyvar of
739 Just tyvar' -> (env, tyvar') -- Already substituted
740 Nothing -> tidyTyVarBndr env tyvar -- Treat it as a binder
742 tidyType :: TidyEnv -> Type -> Type
743 tidyType env@(tidy_env, subst) ty
746 go (TyVarTy tv) = case lookupVarEnv subst tv of
747 Nothing -> TyVarTy tv
748 Just tv' -> TyVarTy tv'
749 go (TyConApp tycon tys) = let args = map go tys
750 in args `seqList` TyConApp tycon args
751 go (NoteTy note ty) = (NoteTy $! (go_note note)) $! (go ty)
752 go (PredTy sty) = PredTy (tidyPred env sty)
753 go (AppTy fun arg) = (AppTy $! (go fun)) $! (go arg)
754 go (FunTy fun arg) = (FunTy $! (go fun)) $! (go arg)
755 go (ForAllTy tv ty) = ForAllTy tvp $! (tidyType envp ty)
757 (envp, tvp) = tidyTyVarBndr env tv
759 go_note note@(FTVNote ftvs) = note -- No need to tidy the free tyvars
761 tidyTypes env tys = map (tidyType env) tys
763 tidyPred :: TidyEnv -> PredType -> PredType
764 tidyPred env (IParam n ty) = IParam n (tidyType env ty)
765 tidyPred env (ClassP clas tys) = ClassP clas (tidyTypes env tys)
766 tidyPred env (EqPred ty1 ty2) = EqPred (tidyType env ty1) (tidyType env ty2)
770 @tidyOpenType@ grabs the free type variables, tidies them
771 and then uses @tidyType@ to work over the type itself
774 tidyOpenType :: TidyEnv -> Type -> (TidyEnv, Type)
776 = (env', tidyType env' ty)
778 env' = tidyFreeTyVars env (tyVarsOfType ty)
780 tidyOpenTypes :: TidyEnv -> [Type] -> (TidyEnv, [Type])
781 tidyOpenTypes env tys = mapAccumL tidyOpenType env tys
783 tidyTopType :: Type -> Type
784 tidyTopType ty = tidyType emptyTidyEnv ty
789 tidyKind :: TidyEnv -> Kind -> (TidyEnv, Kind)
790 tidyKind env k = tidyOpenType env k
795 %************************************************************************
797 \subsection{Liftedness}
799 %************************************************************************
802 isUnLiftedType :: Type -> Bool
803 -- isUnLiftedType returns True for forall'd unlifted types:
804 -- x :: forall a. Int#
805 -- I found bindings like these were getting floated to the top level.
806 -- They are pretty bogus types, mind you. It would be better never to
809 isUnLiftedType ty | Just ty' <- coreView ty = isUnLiftedType ty'
810 isUnLiftedType (ForAllTy tv ty) = isUnLiftedType ty
811 isUnLiftedType (TyConApp tc _) = isUnLiftedTyCon tc
812 isUnLiftedType other = False
814 isUnboxedTupleType :: Type -> Bool
815 isUnboxedTupleType ty = case splitTyConApp_maybe ty of
816 Just (tc, ty_args) -> isUnboxedTupleTyCon tc
819 -- Should only be applied to *types*; hence the assert
820 isAlgType :: Type -> Bool
821 isAlgType ty = case splitTyConApp_maybe ty of
822 Just (tc, ty_args) -> ASSERT( ty_args `lengthIs` tyConArity tc )
827 @isStrictType@ computes whether an argument (or let RHS) should
828 be computed strictly or lazily, based only on its type.
829 Works just like isUnLiftedType, except that it has a special case
830 for dictionaries. Since it takes account of ClassP, you might think
831 this function should be in TcType, but isStrictType is used by DataCon,
832 which is below TcType in the hierarchy, so it's convenient to put it here.
835 isStrictType (PredTy pred) = isStrictPred pred
836 isStrictType ty | Just ty' <- coreView ty = isStrictType ty'
837 isStrictType (ForAllTy tv ty) = isStrictType ty
838 isStrictType (TyConApp tc _) = isUnLiftedTyCon tc
839 isStrictType other = False
841 isStrictPred (ClassP clas _) = opt_DictsStrict && not (isNewTyCon (classTyCon clas))
842 isStrictPred other = False
843 -- We may be strict in dictionary types, but only if it
844 -- has more than one component.
845 -- [Being strict in a single-component dictionary risks
846 -- poking the dictionary component, which is wrong.]
850 isPrimitiveType :: Type -> Bool
851 -- Returns types that are opaque to Haskell.
852 -- Most of these are unlifted, but now that we interact with .NET, we
853 -- may have primtive (foreign-imported) types that are lifted
854 isPrimitiveType ty = case splitTyConApp_maybe ty of
855 Just (tc, ty_args) -> ASSERT( ty_args `lengthIs` tyConArity tc )
861 %************************************************************************
863 \subsection{Sequencing on types
865 %************************************************************************
868 seqType :: Type -> ()
869 seqType (TyVarTy tv) = tv `seq` ()
870 seqType (AppTy t1 t2) = seqType t1 `seq` seqType t2
871 seqType (FunTy t1 t2) = seqType t1 `seq` seqType t2
872 seqType (NoteTy note t2) = seqNote note `seq` seqType t2
873 seqType (PredTy p) = seqPred p
874 seqType (TyConApp tc tys) = tc `seq` seqTypes tys
875 seqType (ForAllTy tv ty) = tv `seq` seqType ty
877 seqTypes :: [Type] -> ()
879 seqTypes (ty:tys) = seqType ty `seq` seqTypes tys
881 seqNote :: TyNote -> ()
882 seqNote (FTVNote set) = sizeUniqSet set `seq` ()
884 seqPred :: PredType -> ()
885 seqPred (ClassP c tys) = c `seq` seqTypes tys
886 seqPred (IParam n ty) = n `seq` seqType ty
887 seqPred (EqPred ty1 ty2) = seqType ty1 `seq` seqType ty2
891 %************************************************************************
893 Equality for Core types
894 (We don't use instances so that we know where it happens)
896 %************************************************************************
898 Note that eqType works right even for partial applications of newtypes.
899 See Note [Newtype eta] in TyCon.lhs
902 coreEqType :: Type -> Type -> Bool
906 rn_env = mkRnEnv2 (mkInScopeSet (tyVarsOfType t1 `unionVarSet` tyVarsOfType t2))
908 eq env (TyVarTy tv1) (TyVarTy tv2) = rnOccL env tv1 == rnOccR env tv2
909 eq env (ForAllTy tv1 t1) (ForAllTy tv2 t2) = eq (rnBndr2 env tv1 tv2) t1 t2
910 eq env (AppTy s1 t1) (AppTy s2 t2) = eq env s1 s2 && eq env t1 t2
911 eq env (FunTy s1 t1) (FunTy s2 t2) = eq env s1 s2 && eq env t1 t2
912 eq env (TyConApp tc1 tys1) (TyConApp tc2 tys2)
913 | tc1 == tc2, all2 (eq env) tys1 tys2 = True
914 -- The lengths should be equal because
915 -- the two types have the same kind
916 -- NB: if the type constructors differ that does not
917 -- necessarily mean that the types aren't equal
918 -- (synonyms, newtypes)
919 -- Even if the type constructors are the same, but the arguments
920 -- differ, the two types could be the same (e.g. if the arg is just
921 -- ignored in the RHS). In both these cases we fall through to an
922 -- attempt to expand one side or the other.
924 -- Now deal with newtypes, synonyms, pred-tys
925 eq env t1 t2 | Just t1' <- coreView t1 = eq env t1' t2
926 | Just t2' <- coreView t2 = eq env t1 t2'
928 -- Fall through case; not equal!
933 %************************************************************************
935 Comparision for source types
936 (We don't use instances so that we know where it happens)
938 %************************************************************************
942 do *not* look through newtypes, PredTypes
945 tcEqType :: Type -> Type -> Bool
946 tcEqType t1 t2 = isEqual $ cmpType t1 t2
948 tcEqTypes :: [Type] -> [Type] -> Bool
949 tcEqTypes tys1 tys2 = isEqual $ cmpTypes tys1 tys2
951 tcCmpType :: Type -> Type -> Ordering
952 tcCmpType t1 t2 = cmpType t1 t2
954 tcCmpTypes :: [Type] -> [Type] -> Ordering
955 tcCmpTypes tys1 tys2 = cmpTypes tys1 tys2
957 tcEqPred :: PredType -> PredType -> Bool
958 tcEqPred p1 p2 = isEqual $ cmpPred p1 p2
960 tcCmpPred :: PredType -> PredType -> Ordering
961 tcCmpPred p1 p2 = cmpPred p1 p2
963 tcEqTypeX :: RnEnv2 -> Type -> Type -> Bool
964 tcEqTypeX env t1 t2 = isEqual $ cmpTypeX env t1 t2
967 Now here comes the real worker
970 cmpType :: Type -> Type -> Ordering
971 cmpType t1 t2 = cmpTypeX rn_env t1 t2
973 rn_env = mkRnEnv2 (mkInScopeSet (tyVarsOfType t1 `unionVarSet` tyVarsOfType t2))
975 cmpTypes :: [Type] -> [Type] -> Ordering
976 cmpTypes ts1 ts2 = cmpTypesX rn_env ts1 ts2
978 rn_env = mkRnEnv2 (mkInScopeSet (tyVarsOfTypes ts1 `unionVarSet` tyVarsOfTypes ts2))
980 cmpPred :: PredType -> PredType -> Ordering
981 cmpPred p1 p2 = cmpPredX rn_env p1 p2
983 rn_env = mkRnEnv2 (mkInScopeSet (tyVarsOfPred p1 `unionVarSet` tyVarsOfPred p2))
985 cmpTypeX :: RnEnv2 -> Type -> Type -> Ordering -- Main workhorse
986 cmpTypeX env t1 t2 | Just t1' <- tcView t1 = cmpTypeX env t1' t2
987 | Just t2' <- tcView t2 = cmpTypeX env t1 t2'
989 cmpTypeX env (TyVarTy tv1) (TyVarTy tv2) = rnOccL env tv1 `compare` rnOccR env tv2
990 cmpTypeX env (ForAllTy tv1 t1) (ForAllTy tv2 t2) = cmpTypeX (rnBndr2 env tv1 tv2) t1 t2
991 cmpTypeX env (AppTy s1 t1) (AppTy s2 t2) = cmpTypeX env s1 s2 `thenCmp` cmpTypeX env t1 t2
992 cmpTypeX env (FunTy s1 t1) (FunTy s2 t2) = cmpTypeX env s1 s2 `thenCmp` cmpTypeX env t1 t2
993 cmpTypeX env (PredTy p1) (PredTy p2) = cmpPredX env p1 p2
994 cmpTypeX env (TyConApp tc1 tys1) (TyConApp tc2 tys2) = (tc1 `compare` tc2) `thenCmp` cmpTypesX env tys1 tys2
995 cmpTypeX env t1 (NoteTy _ t2) = cmpTypeX env t1 t2
997 -- Deal with the rest: TyVarTy < AppTy < FunTy < TyConApp < ForAllTy < PredTy
998 cmpTypeX env (AppTy _ _) (TyVarTy _) = GT
1000 cmpTypeX env (FunTy _ _) (TyVarTy _) = GT
1001 cmpTypeX env (FunTy _ _) (AppTy _ _) = GT
1003 cmpTypeX env (TyConApp _ _) (TyVarTy _) = GT
1004 cmpTypeX env (TyConApp _ _) (AppTy _ _) = GT
1005 cmpTypeX env (TyConApp _ _) (FunTy _ _) = GT
1007 cmpTypeX env (ForAllTy _ _) (TyVarTy _) = GT
1008 cmpTypeX env (ForAllTy _ _) (AppTy _ _) = GT
1009 cmpTypeX env (ForAllTy _ _) (FunTy _ _) = GT
1010 cmpTypeX env (ForAllTy _ _) (TyConApp _ _) = GT
1012 cmpTypeX env (PredTy _) t2 = GT
1014 cmpTypeX env _ _ = LT
1017 cmpTypesX :: RnEnv2 -> [Type] -> [Type] -> Ordering
1018 cmpTypesX env [] [] = EQ
1019 cmpTypesX env (t1:tys1) (t2:tys2) = cmpTypeX env t1 t2 `thenCmp` cmpTypesX env tys1 tys2
1020 cmpTypesX env [] tys = LT
1021 cmpTypesX env ty [] = GT
1024 cmpPredX :: RnEnv2 -> PredType -> PredType -> Ordering
1025 cmpPredX env (IParam n1 ty1) (IParam n2 ty2) = (n1 `compare` n2) `thenCmp` cmpTypeX env ty1 ty2
1026 -- Compare types as well as names for implicit parameters
1027 -- This comparison is used exclusively (I think) for the
1028 -- finite map built in TcSimplify
1029 cmpPredX env (ClassP c1 tys1) (ClassP c2 tys2) = (c1 `compare` c2) `thenCmp` cmpTypesX env tys1 tys2
1030 cmpPredX env (IParam _ _) (ClassP _ _) = LT
1031 cmpPredX env (ClassP _ _) (IParam _ _) = GT
1032 cmpPredX env (EqPred ty1 ty2) (EqPred ty1' ty2') = (cmpTypeX env ty1 ty1') `thenCmp` (cmpTypeX env ty2 ty2')
1035 PredTypes are used as a FM key in TcSimplify,
1036 so we take the easy path and make them an instance of Ord
1039 instance Eq PredType where { (==) = tcEqPred }
1040 instance Ord PredType where { compare = tcCmpPred }
1044 %************************************************************************
1048 %************************************************************************
1052 = TvSubst InScopeSet -- The in-scope type variables
1053 TvSubstEnv -- The substitution itself
1054 -- See Note [Apply Once]
1056 {- ----------------------------------------------------------
1059 We use TvSubsts to instantiate things, and we might instantiate
1063 So the substition might go [a->b, b->a]. A similar situation arises in Core
1064 when we find a beta redex like
1065 (/\ a /\ b -> e) b a
1066 Then we also end up with a substition that permutes type variables. Other
1067 variations happen to; for example [a -> (a, b)].
1069 ***************************************************
1070 *** So a TvSubst must be applied precisely once ***
1071 ***************************************************
1073 A TvSubst is not idempotent, but, unlike the non-idempotent substitution
1074 we use during unifications, it must not be repeatedly applied.
1075 -------------------------------------------------------------- -}
1078 type TvSubstEnv = TyVarEnv Type
1079 -- A TvSubstEnv is used both inside a TvSubst (with the apply-once
1080 -- invariant discussed in Note [Apply Once]), and also independently
1081 -- in the middle of matching, and unification (see Types.Unify)
1082 -- So you have to look at the context to know if it's idempotent or
1083 -- apply-once or whatever
1084 emptyTvSubstEnv :: TvSubstEnv
1085 emptyTvSubstEnv = emptyVarEnv
1087 composeTvSubst :: InScopeSet -> TvSubstEnv -> TvSubstEnv -> TvSubstEnv
1088 -- (compose env1 env2)(x) is env1(env2(x)); i.e. apply env2 then env1
1089 -- It assumes that both are idempotent
1090 -- Typically, env1 is the refinement to a base substitution env2
1091 composeTvSubst in_scope env1 env2
1092 = env1 `plusVarEnv` mapVarEnv (substTy subst1) env2
1093 -- First apply env1 to the range of env2
1094 -- Then combine the two, making sure that env1 loses if
1095 -- both bind the same variable; that's why env1 is the
1096 -- *left* argument to plusVarEnv, because the right arg wins
1098 subst1 = TvSubst in_scope env1
1100 emptyTvSubst = TvSubst emptyInScopeSet emptyVarEnv
1102 isEmptyTvSubst :: TvSubst -> Bool
1103 isEmptyTvSubst (TvSubst _ env) = isEmptyVarEnv env
1105 mkTvSubst :: InScopeSet -> TvSubstEnv -> TvSubst
1108 getTvSubstEnv :: TvSubst -> TvSubstEnv
1109 getTvSubstEnv (TvSubst _ env) = env
1111 getTvInScope :: TvSubst -> InScopeSet
1112 getTvInScope (TvSubst in_scope _) = in_scope
1114 isInScope :: Var -> TvSubst -> Bool
1115 isInScope v (TvSubst in_scope _) = v `elemInScopeSet` in_scope
1117 notElemTvSubst :: TyVar -> TvSubst -> Bool
1118 notElemTvSubst tv (TvSubst _ env) = not (tv `elemVarEnv` env)
1120 setTvSubstEnv :: TvSubst -> TvSubstEnv -> TvSubst
1121 setTvSubstEnv (TvSubst in_scope _) env = TvSubst in_scope env
1123 extendTvInScope :: TvSubst -> [Var] -> TvSubst
1124 extendTvInScope (TvSubst in_scope env) vars = TvSubst (extendInScopeSetList in_scope vars) env
1126 extendTvSubst :: TvSubst -> TyVar -> Type -> TvSubst
1127 extendTvSubst (TvSubst in_scope env) tv ty = TvSubst in_scope (extendVarEnv env tv ty)
1129 extendTvSubstList :: TvSubst -> [TyVar] -> [Type] -> TvSubst
1130 extendTvSubstList (TvSubst in_scope env) tvs tys
1131 = TvSubst in_scope (extendVarEnvList env (tvs `zip` tys))
1133 -- mkOpenTvSubst and zipOpenTvSubst generate the in-scope set from
1134 -- the types given; but it's just a thunk so with a bit of luck
1135 -- it'll never be evaluated
1137 mkOpenTvSubst :: TvSubstEnv -> TvSubst
1138 mkOpenTvSubst env = TvSubst (mkInScopeSet (tyVarsOfTypes (varEnvElts env))) env
1140 zipOpenTvSubst :: [TyVar] -> [Type] -> TvSubst
1141 zipOpenTvSubst tyvars tys
1143 | length tyvars /= length tys
1144 = pprTrace "zipOpenTvSubst" (ppr tyvars $$ ppr tys) emptyTvSubst
1147 = TvSubst (mkInScopeSet (tyVarsOfTypes tys)) (zipTyEnv tyvars tys)
1149 -- mkTopTvSubst is called when doing top-level substitutions.
1150 -- Here we expect that the free vars of the range of the
1151 -- substitution will be empty.
1152 mkTopTvSubst :: [(TyVar, Type)] -> TvSubst
1153 mkTopTvSubst prs = TvSubst emptyInScopeSet (mkVarEnv prs)
1155 zipTopTvSubst :: [TyVar] -> [Type] -> TvSubst
1156 zipTopTvSubst tyvars tys
1158 | length tyvars /= length tys
1159 = pprTrace "zipOpenTvSubst" (ppr tyvars $$ ppr tys) emptyTvSubst
1162 = TvSubst emptyInScopeSet (zipTyEnv tyvars tys)
1164 zipTyEnv :: [TyVar] -> [Type] -> TvSubstEnv
1167 | length tyvars /= length tys
1168 = pprTrace "mkTopTvSubst" (ppr tyvars $$ ppr tys) emptyVarEnv
1171 = zip_ty_env tyvars tys emptyVarEnv
1173 -- Later substitutions in the list over-ride earlier ones,
1174 -- but there should be no loops
1175 zip_ty_env [] [] env = env
1176 zip_ty_env (tv:tvs) (ty:tys) env = zip_ty_env tvs tys (extendVarEnv env tv ty)
1177 -- There used to be a special case for when
1179 -- (a not-uncommon case) in which case the substitution was dropped.
1180 -- But the type-tidier changes the print-name of a type variable without
1181 -- changing the unique, and that led to a bug. Why? Pre-tidying, we had
1182 -- a type {Foo t}, where Foo is a one-method class. So Foo is really a newtype.
1183 -- And it happened that t was the type variable of the class. Post-tiding,
1184 -- it got turned into {Foo t2}. The ext-core printer expanded this using
1185 -- sourceTypeRep, but that said "Oh, t == t2" because they have the same unique,
1186 -- and so generated a rep type mentioning t not t2.
1188 -- Simplest fix is to nuke the "optimisation"
1189 zip_ty_env tvs tys env = pprTrace "Var/Type length mismatch: " (ppr tvs $$ ppr tys) env
1190 -- zip_ty_env _ _ env = env
1192 instance Outputable TvSubst where
1193 ppr (TvSubst ins env)
1194 = brackets $ sep[ ptext SLIT("TvSubst"),
1195 nest 2 (ptext SLIT("In scope:") <+> ppr ins),
1196 nest 2 (ptext SLIT("Env:") <+> ppr env) ]
1199 %************************************************************************
1201 Performing type substitutions
1203 %************************************************************************
1206 substTyWith :: [TyVar] -> [Type] -> Type -> Type
1207 substTyWith tvs tys = ASSERT( length tvs == length tys )
1208 substTy (zipOpenTvSubst tvs tys)
1210 substTy :: TvSubst -> Type -> Type
1211 substTy subst ty | isEmptyTvSubst subst = ty
1212 | otherwise = subst_ty subst ty
1214 substTys :: TvSubst -> [Type] -> [Type]
1215 substTys subst tys | isEmptyTvSubst subst = tys
1216 | otherwise = map (subst_ty subst) tys
1218 substTheta :: TvSubst -> ThetaType -> ThetaType
1219 substTheta subst theta
1220 | isEmptyTvSubst subst = theta
1221 | otherwise = map (substPred subst) theta
1223 substPred :: TvSubst -> PredType -> PredType
1224 substPred subst (IParam n ty) = IParam n (subst_ty subst ty)
1225 substPred subst (ClassP clas tys) = ClassP clas (map (subst_ty subst) tys)
1226 substPred subst (EqPred ty1 ty2) = EqPred (subst_ty subst ty1) (subst_ty subst ty2)
1228 deShadowTy :: TyVarSet -> Type -> Type -- Remove any nested binders mentioning tvs
1230 = subst_ty (mkTvSubst in_scope emptyTvSubstEnv) ty
1232 in_scope = mkInScopeSet tvs
1234 subst_ty :: TvSubst -> Type -> Type
1235 -- subst_ty is the main workhorse for type substitution
1237 -- Note that the in_scope set is poked only if we hit a forall
1238 -- so it may often never be fully computed
1242 go (TyVarTy tv) = substTyVar subst tv
1243 go (TyConApp tc tys) = let args = map go tys
1244 in args `seqList` TyConApp tc args
1246 go (PredTy p) = PredTy $! (substPred subst p)
1248 go (NoteTy (FTVNote _) ty2) = go ty2 -- Discard the free tyvar note
1250 go (FunTy arg res) = (FunTy $! (go arg)) $! (go res)
1251 go (AppTy fun arg) = mkAppTy (go fun) $! (go arg)
1252 -- The mkAppTy smart constructor is important
1253 -- we might be replacing (a Int), represented with App
1254 -- by [Int], represented with TyConApp
1255 go (ForAllTy tv ty) = case substTyVarBndr subst tv of
1256 (subst', tv') -> ForAllTy tv' $! (subst_ty subst' ty)
1258 substTyVar :: TvSubst -> TyVar -> Type
1259 substTyVar subst@(TvSubst in_scope env) tv
1260 = case lookupTyVar subst tv of {
1261 Nothing -> TyVarTy tv;
1262 Just ty -> ty -- See Note [Apply Once]
1265 lookupTyVar :: TvSubst -> TyVar -> Maybe Type
1266 lookupTyVar (TvSubst in_scope env) tv = lookupVarEnv env tv
1268 substTyVarBndr :: TvSubst -> TyVar -> (TvSubst, TyVar)
1269 substTyVarBndr subst@(TvSubst in_scope env) old_var
1270 = (TvSubst (in_scope `extendInScopeSet` new_var) new_env, new_var)
1273 new_env | no_change = delVarEnv env old_var
1274 | otherwise = extendVarEnv env old_var (TyVarTy new_var)
1276 no_change = new_var == old_var && not is_co_var
1277 -- no_change means that the new_var is identical in
1278 -- all respects to the old_var (same unique, same kind)
1280 -- In that case we don't need to extend the substitution
1281 -- to map old to new. But instead we must zap any
1282 -- current substitution for the variable. For example:
1283 -- (\x.e) with id_subst = [x |-> e']
1284 -- Here we must simply zap the substitution for x
1286 new_var = uniqAway in_scope subst_old_var
1287 -- The uniqAway part makes sure the new variable is not already in scope
1289 subst_old_var -- subst_old_var is old_var with the substitution applied to its kind
1290 -- It's only worth doing the substitution for coercions,
1291 -- becuase only they can have free type variables
1292 | is_co_var = setTyVarKind old_var (substTy subst kind)
1293 | otherwise = old_var
1294 kind = tyVarKind old_var
1295 is_co_var = isCoercionKind kind
1298 ----------------------------------------------------
1303 There's a little subtyping at the kind level:
1312 where * [LiftedTypeKind] means boxed type
1313 # [UnliftedTypeKind] means unboxed type
1314 (#) [UbxTupleKind] means unboxed tuple
1315 ?? [ArgTypeKind] is the lub of *,#
1316 ? [OpenTypeKind] means any type at all
1320 error :: forall a:?. String -> a
1321 (->) :: ?? -> ? -> *
1322 (\(x::t) -> ...) Here t::?? (i.e. not unboxed tuple)
1325 type KindVar = TyVar -- invariant: KindVar will always be a
1326 -- TcTyVar with details MetaTv TauTv ...
1327 -- kind var constructors and functions are in TcType
1329 type SimpleKind = Kind
1334 During kind inference, a kind variable unifies only with
1336 sk ::= * | sk1 -> sk2
1338 data T a = MkT a (T Int#)
1339 fails. We give T the kind (k -> *), and the kind variable k won't unify
1340 with # (the kind of Int#).
1344 When creating a fresh internal type variable, we give it a kind to express
1345 constraints on it. E.g. in (\x->e) we make up a fresh type variable for x,
1348 During unification we only bind an internal type variable to a type
1349 whose kind is lower in the sub-kind hierarchy than the kind of the tyvar.
1351 When unifying two internal type variables, we collect their kind constraints by
1352 finding the GLB of the two. Since the partial order is a tree, they only
1353 have a glb if one is a sub-kind of the other. In that case, we bind the
1354 less-informative one to the more informative one. Neat, eh?
1361 %************************************************************************
1363 Functions over Kinds
1365 %************************************************************************
1368 kindFunResult :: Kind -> Kind
1369 kindFunResult k = funResultTy k
1371 splitKindFunTys :: Kind -> ([Kind],Kind)
1372 splitKindFunTys k = splitFunTys k
1374 isUbxTupleKind, isOpenTypeKind, isArgTypeKind, isUnliftedTypeKind :: Kind -> Bool
1376 isOpenTypeKindCon tc = tyConUnique tc == openTypeKindTyConKey
1378 isOpenTypeKind (TyConApp tc _) = isOpenTypeKindCon tc
1379 isOpenTypeKind other = False
1381 isUbxTupleKindCon tc = tyConUnique tc == ubxTupleKindTyConKey
1383 isUbxTupleKind (TyConApp tc _) = isUbxTupleKindCon tc
1384 isUbxTupleKind other = False
1386 isArgTypeKindCon tc = tyConUnique tc == argTypeKindTyConKey
1388 isArgTypeKind (TyConApp tc _) = isArgTypeKindCon tc
1389 isArgTypeKind other = False
1391 isUnliftedTypeKindCon tc = tyConUnique tc == unliftedTypeKindTyConKey
1393 isUnliftedTypeKind (TyConApp tc _) = isUnliftedTypeKindCon tc
1394 isUnliftedTypeKind other = False
1396 isSubOpenTypeKind :: Kind -> Bool
1397 -- True of any sub-kind of OpenTypeKind (i.e. anything except arrow)
1398 isSubOpenTypeKind (FunTy k1 k2) = ASSERT2 ( isKind k1, text "isSubOpenTypeKind" <+> ppr k1 <+> text "::" <+> ppr (typeKind k1) )
1399 ASSERT2 ( isKind k2, text "isSubOpenTypeKind" <+> ppr k2 <+> text "::" <+> ppr (typeKind k2) )
1401 isSubOpenTypeKind (TyConApp kc []) = ASSERT( isKind (TyConApp kc []) ) True
1402 isSubOpenTypeKind other = ASSERT( isKind other ) False
1403 -- This is a conservative answer
1404 -- It matters in the call to isSubKind in
1405 -- checkExpectedKind.
1407 isSubArgTypeKindCon kc
1408 | isUnliftedTypeKindCon kc = True
1409 | isLiftedTypeKindCon kc = True
1410 | isArgTypeKindCon kc = True
1413 isSubArgTypeKind :: Kind -> Bool
1414 -- True of any sub-kind of ArgTypeKind
1415 isSubArgTypeKind (TyConApp kc []) = isSubArgTypeKindCon kc
1416 isSubArgTypeKind other = False
1418 isSuperKind :: Type -> Bool
1419 isSuperKind (TyConApp (skc) []) = isSuperKindTyCon skc
1420 isSuperKind other = False
1422 isKind :: Kind -> Bool
1423 isKind k = isSuperKind (typeKind k)
1427 isSubKind :: Kind -> Kind -> Bool
1428 -- (k1 `isSubKind` k2) checks that k1 <: k2
1429 isSubKind (TyConApp kc1 []) (TyConApp kc2 []) = kc1 `isSubKindCon` kc1
1430 isSubKind (FunTy a1 r1) (FunTy a2 r2) = (a2 `isSubKind` a1) && (r1 `isSubKind` r2)
1431 isSubKind (PredTy (EqPred ty1 ty2)) (PredTy (EqPred ty1' ty2'))
1432 = ty1 `tcEqType` ty1' && ty2 `tcEqType` ty2'
1433 isSubKind k1 k2 = False
1435 eqKind :: Kind -> Kind -> Bool
1438 isSubKindCon :: TyCon -> TyCon -> Bool
1439 -- (kc1 `isSubKindCon` kc2) checks that kc1 <: kc2
1440 isSubKindCon kc1 kc2
1441 | isLiftedTypeKindCon kc1 && isLiftedTypeKindCon kc2 = True
1442 | isUnliftedTypeKindCon kc1 && isUnliftedTypeKindCon kc2 = True
1443 | isUbxTupleKindCon kc1 && isUbxTupleKindCon kc2 = True
1444 | isOpenTypeKindCon kc2 = True
1445 -- we already know kc1 is not a fun, its a TyCon
1446 | isArgTypeKindCon kc2 && isSubArgTypeKindCon kc1 = True
1449 defaultKind :: Kind -> Kind
1450 -- Used when generalising: default kind '?' and '??' to '*'
1452 -- When we generalise, we make generic type variables whose kind is
1453 -- simple (* or *->* etc). So generic type variables (other than
1454 -- built-in constants like 'error') always have simple kinds. This is important;
1457 -- We want f to get type
1458 -- f :: forall (a::*). a -> Bool
1460 -- f :: forall (a::??). a -> Bool
1461 -- because that would allow a call like (f 3#) as well as (f True),
1462 --and the calling conventions differ. This defaulting is done in TcMType.zonkTcTyVarBndr.
1464 | isSubOpenTypeKind k = liftedTypeKind
1465 | isSubArgTypeKind k = liftedTypeKind
1468 isCoercionKind :: Kind -> Bool
1469 -- All coercions are of form (ty1 :=: ty2)
1470 -- This function is here rather than in Coercion,
1471 -- because it's used by substTy
1472 isCoercionKind k | Just k' <- kindView k = isCoercionKind k'
1473 isCoercionKind (PredTy (EqPred {})) = True
1474 isCoercionKind other = False
1476 isEqPred :: PredType -> Bool
1477 isEqPred (EqPred _ _) = True
1478 isEqPred other = False