2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1998
6 Type - public interface
10 -- re-exports from TypeRep
11 TyThing(..), Type, PredType(..), ThetaType,
15 Kind, SimpleKind, KindVar,
16 kindFunResult, splitKindFunTys, splitKindFunTysN,
18 liftedTypeKindTyCon, openTypeKindTyCon, unliftedTypeKindTyCon,
19 argTypeKindTyCon, ubxTupleKindTyCon,
21 liftedTypeKind, unliftedTypeKind, openTypeKind,
22 argTypeKind, ubxTupleKind,
24 tySuperKind, coSuperKind,
26 isLiftedTypeKind, isUnliftedTypeKind, isOpenTypeKind,
27 isUbxTupleKind, isArgTypeKind, isKind, isTySuperKind,
28 isCoSuperKind, isSuperKind, isCoercionKind, isEqPred,
29 mkArrowKind, mkArrowKinds,
31 isSubArgTypeKind, isSubOpenTypeKind, isSubKind, defaultKind, eqKind,
34 -- Re-exports from TyCon
37 mkTyVarTy, mkTyVarTys, getTyVar, getTyVar_maybe, isTyVarTy,
39 mkAppTy, mkAppTys, splitAppTy, splitAppTys,
40 splitAppTy_maybe, repSplitAppTy_maybe,
42 mkFunTy, mkFunTys, splitFunTy, splitFunTy_maybe,
43 splitFunTys, splitFunTysN,
44 funResultTy, funArgTy, zipFunTys, isFunTy,
46 mkTyConApp, mkTyConTy,
47 tyConAppTyCon, tyConAppArgs,
48 splitTyConApp_maybe, splitTyConApp,
49 splitNewTyConApp_maybe, splitNewTyConApp,
51 repType, typePrimRep, coreView, tcView, kindView,
53 mkForAllTy, mkForAllTys, splitForAllTy_maybe, splitForAllTys,
54 applyTy, applyTys, isForAllTy, dropForAlls,
57 predTypeRep, mkPredTy, mkPredTys,
60 splitRecNewType_maybe, newTyConInstRhs,
63 isUnLiftedType, isUnboxedTupleType, isAlgType, isPrimitiveType,
64 isStrictType, isStrictPred,
67 tyVarsOfType, tyVarsOfTypes, tyVarsOfPred, tyVarsOfTheta,
68 typeKind, addFreeTyVars,
70 -- Tidying up for printing
72 tidyOpenType, tidyOpenTypes,
73 tidyTyVarBndr, tidyFreeTyVars,
74 tidyOpenTyVar, tidyOpenTyVars,
75 tidyTopType, tidyPred,
79 coreEqType, tcEqType, tcEqTypes, tcCmpType, tcCmpTypes,
80 tcEqPred, tcCmpPred, tcEqTypeX,
86 TvSubstEnv, emptyTvSubstEnv, -- Representation widely visible
87 TvSubst(..), emptyTvSubst, -- Representation visible to a few friends
88 mkTvSubst, mkOpenTvSubst, zipOpenTvSubst, zipTopTvSubst, mkTopTvSubst, notElemTvSubst,
89 getTvSubstEnv, setTvSubstEnv, getTvInScope, extendTvInScope,
90 extendTvSubst, extendTvSubstList, isInScope, composeTvSubst, zipTyEnv,
92 -- Performing substitution on types
93 substTy, substTys, substTyWith, substTheta,
94 substPred, substTyVar, substTyVarBndr, deShadowTy, lookupTyVar,
97 pprType, pprParendType, pprTyThingCategory, pprForAll,
98 pprPred, pprTheta, pprThetaArrow, pprClassPred, pprKind, pprParendKind
101 #include "HsVersions.h"
103 -- We import the representation and primitive functions from TypeRep.
104 -- Many things are reexported, but not the representation!
124 import Data.Maybe ( isJust )
128 %************************************************************************
132 %************************************************************************
134 In Core, we "look through" non-recursive newtypes and PredTypes.
137 {-# INLINE coreView #-}
138 coreView :: Type -> Maybe Type
139 -- Strips off the *top layer only* of a type to give
140 -- its underlying representation type.
141 -- Returns Nothing if there is nothing to look through.
143 -- In the case of newtypes, it returns
144 -- *either* a vanilla TyConApp (recursive newtype, or non-saturated)
145 -- *or* the newtype representation (otherwise), meaning the
146 -- type written in the RHS of the newtype decl,
147 -- which may itself be a newtype
149 -- Example: newtype R = MkR S
151 -- newtype T = MkT (T -> T)
152 -- expandNewTcApp on R gives Just S
154 -- on T gives Nothing (no expansion)
156 -- By being non-recursive and inlined, this case analysis gets efficiently
157 -- joined onto the case analysis that the caller is already doing
158 coreView (NoteTy _ ty) = Just ty
160 | isEqPred p = Nothing
161 | otherwise = Just (predTypeRep p)
162 coreView (TyConApp tc tys) | Just (tenv, rhs, tys') <- coreExpandTyCon_maybe tc tys
163 = Just (mkAppTys (substTy (mkTopTvSubst tenv) rhs) tys')
164 -- Its important to use mkAppTys, rather than (foldl AppTy),
165 -- because the function part might well return a
166 -- partially-applied type constructor; indeed, usually will!
167 coreView ty = Nothing
171 -----------------------------------------------
172 {-# INLINE tcView #-}
173 tcView :: Type -> Maybe Type
174 -- Same, but for the type checker, which just looks through synonyms
175 tcView (NoteTy _ ty) = Just ty
176 tcView (TyConApp tc tys) | Just (tenv, rhs, tys') <- tcExpandTyCon_maybe tc tys
177 = Just (mkAppTys (substTy (mkTopTvSubst tenv) rhs) tys')
180 -----------------------------------------------
181 {-# INLINE kindView #-}
182 kindView :: Kind -> Maybe Kind
183 -- C.f. coreView, tcView
184 -- For the moment, we don't even handle synonyms in kinds
185 kindView (NoteTy _ k) = Just k
186 kindView other = Nothing
190 %************************************************************************
192 \subsection{Constructor-specific functions}
194 %************************************************************************
197 ---------------------------------------------------------------------
201 mkTyVarTy :: TyVar -> Type
204 mkTyVarTys :: [TyVar] -> [Type]
205 mkTyVarTys = map mkTyVarTy -- a common use of mkTyVarTy
207 getTyVar :: String -> Type -> TyVar
208 getTyVar msg ty = case getTyVar_maybe ty of
210 Nothing -> panic ("getTyVar: " ++ msg)
212 isTyVarTy :: Type -> Bool
213 isTyVarTy ty = isJust (getTyVar_maybe ty)
215 getTyVar_maybe :: Type -> Maybe TyVar
216 getTyVar_maybe ty | Just ty' <- coreView ty = getTyVar_maybe ty'
217 getTyVar_maybe (TyVarTy tv) = Just tv
218 getTyVar_maybe other = Nothing
223 ---------------------------------------------------------------------
226 We need to be pretty careful with AppTy to make sure we obey the
227 invariant that a TyConApp is always visibly so. mkAppTy maintains the
231 mkAppTy orig_ty1 orig_ty2
234 mk_app (NoteTy _ ty1) = mk_app ty1
235 mk_app (TyConApp tc tys) = mkTyConApp tc (tys ++ [orig_ty2])
236 mk_app ty1 = AppTy orig_ty1 orig_ty2
237 -- Note that the TyConApp could be an
238 -- under-saturated type synonym. GHC allows that; e.g.
239 -- type Foo k = k a -> k a
241 -- foo :: Foo Id -> Foo Id
243 -- Here Id is partially applied in the type sig for Foo,
244 -- but once the type synonyms are expanded all is well
246 mkAppTys :: Type -> [Type] -> Type
247 mkAppTys orig_ty1 [] = orig_ty1
248 -- This check for an empty list of type arguments
249 -- avoids the needless loss of a type synonym constructor.
250 -- For example: mkAppTys Rational []
251 -- returns to (Ratio Integer), which has needlessly lost
252 -- the Rational part.
253 mkAppTys orig_ty1 orig_tys2
256 mk_app (NoteTy _ ty1) = mk_app ty1
257 mk_app (TyConApp tc tys) = mkTyConApp tc (tys ++ orig_tys2)
258 -- mkTyConApp: see notes with mkAppTy
259 mk_app ty1 = foldl AppTy orig_ty1 orig_tys2
262 splitAppTy_maybe :: Type -> Maybe (Type, Type)
263 splitAppTy_maybe ty | Just ty' <- coreView ty
264 = splitAppTy_maybe ty'
265 splitAppTy_maybe ty = repSplitAppTy_maybe ty
268 repSplitAppTy_maybe :: Type -> Maybe (Type,Type)
269 -- Does the AppTy split, but assumes that any view stuff is already done
270 repSplitAppTy_maybe (FunTy ty1 ty2) = Just (TyConApp funTyCon [ty1], ty2)
271 repSplitAppTy_maybe (AppTy ty1 ty2) = Just (ty1, ty2)
272 repSplitAppTy_maybe (TyConApp tc tys) = case snocView tys of
273 Just (tys', ty') -> Just (TyConApp tc tys', ty')
275 repSplitAppTy_maybe other = Nothing
277 splitAppTy :: Type -> (Type, Type)
278 splitAppTy ty = case splitAppTy_maybe ty of
280 Nothing -> panic "splitAppTy"
283 splitAppTys :: Type -> (Type, [Type])
284 splitAppTys ty = split ty ty []
286 split orig_ty ty args | Just ty' <- coreView ty = split orig_ty ty' args
287 split orig_ty (AppTy ty arg) args = split ty ty (arg:args)
288 split orig_ty (TyConApp tc tc_args) args = (TyConApp tc [], tc_args ++ args)
289 split orig_ty (FunTy ty1 ty2) args = ASSERT( null args )
290 (TyConApp funTyCon [], [ty1,ty2])
291 split orig_ty ty args = (orig_ty, args)
296 ---------------------------------------------------------------------
301 mkFunTy :: Type -> Type -> Type
302 mkFunTy (PredTy (EqPred ty1 ty2)) res = mkForAllTy (mkWildCoVar (PredTy (EqPred ty1 ty2))) res
303 mkFunTy arg res = FunTy arg res
305 mkFunTys :: [Type] -> Type -> Type
306 mkFunTys tys ty = foldr mkFunTy ty tys
308 isFunTy :: Type -> Bool
309 isFunTy ty = isJust (splitFunTy_maybe ty)
311 splitFunTy :: Type -> (Type, Type)
312 splitFunTy ty | Just ty' <- coreView ty = splitFunTy ty'
313 splitFunTy (FunTy arg res) = (arg, res)
314 splitFunTy other = pprPanic "splitFunTy" (ppr other)
316 splitFunTy_maybe :: Type -> Maybe (Type, Type)
317 splitFunTy_maybe ty | Just ty' <- coreView ty = splitFunTy_maybe ty'
318 splitFunTy_maybe (FunTy arg res) = Just (arg, res)
319 splitFunTy_maybe other = Nothing
321 splitFunTys :: Type -> ([Type], Type)
322 splitFunTys ty = split [] ty ty
324 split args orig_ty ty | Just ty' <- coreView ty = split args orig_ty ty'
325 split args orig_ty (FunTy arg res) = split (arg:args) res res
326 split args orig_ty ty = (reverse args, orig_ty)
328 splitFunTysN :: Int -> Type -> ([Type], Type)
329 -- Split off exactly n arg tys
330 splitFunTysN 0 ty = ([], ty)
331 splitFunTysN n ty = case splitFunTy ty of { (arg, res) ->
332 case splitFunTysN (n-1) res of { (args, res) ->
335 zipFunTys :: Outputable a => [a] -> Type -> ([(a,Type)], Type)
336 zipFunTys orig_xs orig_ty = split [] orig_xs orig_ty orig_ty
338 split acc [] nty ty = (reverse acc, nty)
340 | Just ty' <- coreView ty = split acc xs nty ty'
341 split acc (x:xs) nty (FunTy arg res) = split ((x,arg):acc) xs res res
342 split acc (x:xs) nty ty = pprPanic "zipFunTys" (ppr orig_xs <+> ppr orig_ty)
344 funResultTy :: Type -> Type
345 funResultTy ty | Just ty' <- coreView ty = funResultTy ty'
346 funResultTy (FunTy arg res) = res
347 funResultTy ty = pprPanic "funResultTy" (ppr ty)
349 funArgTy :: Type -> Type
350 funArgTy ty | Just ty' <- coreView ty = funArgTy ty'
351 funArgTy (FunTy arg res) = arg
352 funArgTy ty = pprPanic "funArgTy" (ppr ty)
356 ---------------------------------------------------------------------
359 @mkTyConApp@ is a key function, because it builds a TyConApp, FunTy or PredTy,
363 mkTyConApp :: TyCon -> [Type] -> Type
365 | isFunTyCon tycon, [ty1,ty2] <- tys
371 mkTyConTy :: TyCon -> Type
372 mkTyConTy tycon = mkTyConApp tycon []
374 -- splitTyConApp "looks through" synonyms, because they don't
375 -- mean a distinct type, but all other type-constructor applications
376 -- including functions are returned as Just ..
378 tyConAppTyCon :: Type -> TyCon
379 tyConAppTyCon ty = fst (splitTyConApp ty)
381 tyConAppArgs :: Type -> [Type]
382 tyConAppArgs ty = snd (splitTyConApp ty)
384 splitTyConApp :: Type -> (TyCon, [Type])
385 splitTyConApp ty = case splitTyConApp_maybe ty of
387 Nothing -> pprPanic "splitTyConApp" (ppr ty)
389 splitTyConApp_maybe :: Type -> Maybe (TyCon, [Type])
390 splitTyConApp_maybe ty | Just ty' <- coreView ty = splitTyConApp_maybe ty'
391 splitTyConApp_maybe (TyConApp tc tys) = Just (tc, tys)
392 splitTyConApp_maybe (FunTy arg res) = Just (funTyCon, [arg,res])
393 splitTyConApp_maybe other = Nothing
395 -- Sometimes we do NOT want to look throught a newtype. When case matching
396 -- on a newtype we want a convenient way to access the arguments of a newty
397 -- constructor so as to properly form a coercion.
398 splitNewTyConApp :: Type -> (TyCon, [Type])
399 splitNewTyConApp ty = case splitNewTyConApp_maybe ty of
401 Nothing -> pprPanic "splitNewTyConApp" (ppr ty)
402 splitNewTyConApp_maybe :: Type -> Maybe (TyCon, [Type])
403 splitNewTyConApp_maybe ty | Just ty' <- tcView ty = splitNewTyConApp_maybe ty'
404 splitNewTyConApp_maybe (TyConApp tc tys) = Just (tc, tys)
405 splitNewTyConApp_maybe (FunTy arg res) = Just (funTyCon, [arg,res])
406 splitNewTyConApp_maybe other = Nothing
408 -- get instantiated newtype rhs, the arguments had better saturate
410 newTyConInstRhs :: TyCon -> [Type] -> Type
411 newTyConInstRhs tycon tys =
412 let (tvs, ty) = newTyConRhs tycon in substTyWith tvs tys ty
417 ---------------------------------------------------------------------
421 Notes on type synonyms
422 ~~~~~~~~~~~~~~~~~~~~~~
423 The various "split" functions (splitFunTy, splitRhoTy, splitForAllTy) try
424 to return type synonyms whereever possible. Thus
429 splitFunTys (a -> Foo a) = ([a], Foo a)
432 The reason is that we then get better (shorter) type signatures in
433 interfaces. Notably this plays a role in tcTySigs in TcBinds.lhs.
438 repType looks through
442 (d) usage annotations
443 (e) all newtypes, including recursive ones, but not newtype families
444 It's useful in the back end.
447 repType :: Type -> Type
448 -- Only applied to types of kind *; hence tycons are saturated
449 repType ty | Just ty' <- coreView ty = repType ty'
450 repType (ForAllTy _ ty) = repType ty
451 repType (TyConApp tc tys)
452 | isClosedNewTyCon tc = -- Recursive newtypes are opaque to coreView
453 -- but we must expand them here. Sure to
454 -- be saturated because repType is only applied
455 -- to types of kind *
456 ASSERT( {- isRecursiveTyCon tc && -} tys `lengthIs` tyConArity tc )
457 repType (new_type_rep tc tys)
460 -- new_type_rep doesn't ask any questions:
461 -- it just expands newtype, whether recursive or not
462 new_type_rep new_tycon tys = ASSERT( tys `lengthIs` tyConArity new_tycon )
463 case newTyConRep new_tycon of
464 (tvs, rep_ty) -> substTyWith tvs tys rep_ty
466 -- ToDo: this could be moved to the code generator, using splitTyConApp instead
467 -- of inspecting the type directly.
468 typePrimRep :: Type -> PrimRep
469 typePrimRep ty = case repType ty of
470 TyConApp tc _ -> tyConPrimRep tc
472 AppTy _ _ -> PtrRep -- See note below
474 other -> pprPanic "typePrimRep" (ppr ty)
475 -- Types of the form 'f a' must be of kind *, not *#, so
476 -- we are guaranteed that they are represented by pointers.
477 -- The reason is that f must have kind *->*, not *->*#, because
478 -- (we claim) there is no way to constrain f's kind any other
484 ---------------------------------------------------------------------
489 mkForAllTy :: TyVar -> Type -> Type
491 = mkForAllTys [tyvar] ty
493 mkForAllTys :: [TyVar] -> Type -> Type
494 mkForAllTys tyvars ty = foldr ForAllTy ty tyvars
496 isForAllTy :: Type -> Bool
497 isForAllTy (NoteTy _ ty) = isForAllTy ty
498 isForAllTy (ForAllTy _ _) = True
499 isForAllTy other_ty = False
501 splitForAllTy_maybe :: Type -> Maybe (TyVar, Type)
502 splitForAllTy_maybe ty = splitFAT_m ty
504 splitFAT_m ty | Just ty' <- coreView ty = splitFAT_m ty'
505 splitFAT_m (ForAllTy tyvar ty) = Just(tyvar, ty)
506 splitFAT_m _ = Nothing
508 splitForAllTys :: Type -> ([TyVar], Type)
509 splitForAllTys ty = split ty ty []
511 split orig_ty ty tvs | Just ty' <- coreView ty = split orig_ty ty' tvs
512 split orig_ty (ForAllTy tv ty) tvs = split ty ty (tv:tvs)
513 split orig_ty t tvs = (reverse tvs, orig_ty)
515 dropForAlls :: Type -> Type
516 dropForAlls ty = snd (splitForAllTys ty)
519 -- (mkPiType now in CoreUtils)
523 Instantiate a for-all type with one or more type arguments.
524 Used when we have a polymorphic function applied to type args:
526 Then we use (applyTys type-of-f [t1,t2]) to compute the type of
530 applyTy :: Type -> Type -> Type
531 applyTy ty arg | Just ty' <- coreView ty = applyTy ty' arg
532 applyTy (ForAllTy tv ty) arg = substTyWith [tv] [arg] ty
533 applyTy other arg = panic "applyTy"
535 applyTys :: Type -> [Type] -> Type
536 -- This function is interesting because
537 -- a) the function may have more for-alls than there are args
538 -- b) less obviously, it may have fewer for-alls
539 -- For case (b) think of
540 -- applyTys (forall a.a) [forall b.b, Int]
541 -- This really can happen, via dressing up polymorphic types with newtype
542 -- clothing. Here's an example:
543 -- newtype R = R (forall a. a->a)
544 -- foo = case undefined :: R of
547 applyTys orig_fun_ty [] = orig_fun_ty
548 applyTys orig_fun_ty arg_tys
549 | n_tvs == n_args -- The vastly common case
550 = substTyWith tvs arg_tys rho_ty
551 | n_tvs > n_args -- Too many for-alls
552 = substTyWith (take n_args tvs) arg_tys
553 (mkForAllTys (drop n_args tvs) rho_ty)
554 | otherwise -- Too many type args
555 = ASSERT2( n_tvs > 0, ppr orig_fun_ty ) -- Zero case gives infnite loop!
556 applyTys (substTyWith tvs (take n_tvs arg_tys) rho_ty)
559 (tvs, rho_ty) = splitForAllTys orig_fun_ty
561 n_args = length arg_tys
565 %************************************************************************
567 \subsection{Source types}
569 %************************************************************************
571 A "source type" is a type that is a separate type as far as the type checker is
572 concerned, but which has low-level representation as far as the back end is concerned.
574 Source types are always lifted.
576 The key function is predTypeRep which gives the representation of a source type:
579 mkPredTy :: PredType -> Type
580 mkPredTy pred = PredTy pred
582 mkPredTys :: ThetaType -> [Type]
583 mkPredTys preds = map PredTy preds
585 predTypeRep :: PredType -> Type
586 -- Convert a PredType to its "representation type";
587 -- the post-type-checking type used by all the Core passes of GHC.
588 -- Unwraps only the outermost level; for example, the result might
589 -- be a newtype application
590 predTypeRep (IParam _ ty) = ty
591 predTypeRep (ClassP clas tys) = mkTyConApp (classTyCon clas) tys
592 -- Result might be a newtype application, but the consumer will
593 -- look through that too if necessary
594 predTypeRep (EqPred ty1 ty2) = pprPanic "predTypeRep" (ppr (EqPred ty1 ty2))
598 %************************************************************************
602 %************************************************************************
605 splitRecNewType_maybe :: Type -> Maybe Type
606 -- Sometimes we want to look through a recursive newtype, and that's what happens here
607 -- It only strips *one layer* off, so the caller will usually call itself recursively
608 -- Only applied to types of kind *, hence the newtype is always saturated
609 splitRecNewType_maybe ty | Just ty' <- coreView ty = splitRecNewType_maybe ty'
610 splitRecNewType_maybe (TyConApp tc tys)
611 | isClosedNewTyCon tc
612 = ASSERT( tys `lengthIs` tyConArity tc ) -- splitRecNewType_maybe only be applied
613 -- to *types* (of kind *)
614 ASSERT( isRecursiveTyCon tc ) -- Guaranteed by coreView
615 case newTyConRhs tc of
616 (tvs, rep_ty) -> ASSERT( length tvs == length tys )
617 Just (substTyWith tvs tys rep_ty)
619 splitRecNewType_maybe other = Nothing
626 %************************************************************************
628 \subsection{Kinds and free variables}
630 %************************************************************************
632 ---------------------------------------------------------------------
633 Finding the kind of a type
634 ~~~~~~~~~~~~~~~~~~~~~~~~~~
636 typeKind :: Type -> Kind
637 typeKind (TyConApp tycon tys) = ASSERT( not (isCoercionTyCon tycon) )
638 -- We should be looking for the coercion kind,
640 foldr (\_ k -> kindFunResult k) (tyConKind tycon) tys
641 typeKind (NoteTy _ ty) = typeKind ty
642 typeKind (PredTy pred) = predKind pred
643 typeKind (AppTy fun arg) = kindFunResult (typeKind fun)
644 typeKind (ForAllTy tv ty) = typeKind ty
645 typeKind (TyVarTy tyvar) = tyVarKind tyvar
646 typeKind (FunTy arg res)
647 -- Hack alert. The kind of (Int -> Int#) is liftedTypeKind (*),
648 -- not unliftedTypKind (#)
649 -- The only things that can be after a function arrow are
650 -- (a) types (of kind openTypeKind or its sub-kinds)
651 -- (b) kinds (of super-kind TY) (e.g. * -> (* -> *))
652 | isTySuperKind k = k
653 | otherwise = ASSERT( isSubOpenTypeKind k) liftedTypeKind
657 predKind :: PredType -> Kind
658 predKind (EqPred {}) = coSuperKind -- A coercion kind!
659 predKind (ClassP {}) = liftedTypeKind -- Class and implicitPredicates are
660 predKind (IParam {}) = liftedTypeKind -- always represented by lifted types
664 ---------------------------------------------------------------------
665 Free variables of a type
666 ~~~~~~~~~~~~~~~~~~~~~~~~
668 tyVarsOfType :: Type -> TyVarSet
669 -- NB: for type synonyms tyVarsOfType does *not* expand the synonym
670 tyVarsOfType (TyVarTy tv) = unitVarSet tv
671 tyVarsOfType (TyConApp tycon tys) = tyVarsOfTypes tys
672 tyVarsOfType (NoteTy (FTVNote tvs) ty2) = tvs
673 tyVarsOfType (PredTy sty) = tyVarsOfPred sty
674 tyVarsOfType (FunTy arg res) = tyVarsOfType arg `unionVarSet` tyVarsOfType res
675 tyVarsOfType (AppTy fun arg) = tyVarsOfType fun `unionVarSet` tyVarsOfType arg
676 tyVarsOfType (ForAllTy tyvar ty) = delVarSet (tyVarsOfType ty) tyvar
678 tyVarsOfTypes :: [Type] -> TyVarSet
679 tyVarsOfTypes tys = foldr (unionVarSet.tyVarsOfType) emptyVarSet tys
681 tyVarsOfPred :: PredType -> TyVarSet
682 tyVarsOfPred (IParam _ ty) = tyVarsOfType ty
683 tyVarsOfPred (ClassP _ tys) = tyVarsOfTypes tys
684 tyVarsOfPred (EqPred ty1 ty2) = tyVarsOfType ty1 `unionVarSet` tyVarsOfType ty2
686 tyVarsOfTheta :: ThetaType -> TyVarSet
687 tyVarsOfTheta = foldr (unionVarSet . tyVarsOfPred) emptyVarSet
689 -- Add a Note with the free tyvars to the top of the type
690 addFreeTyVars :: Type -> Type
691 addFreeTyVars ty@(NoteTy (FTVNote _) _) = ty
692 addFreeTyVars ty = NoteTy (FTVNote (tyVarsOfType ty)) ty
696 %************************************************************************
698 \subsection{TidyType}
700 %************************************************************************
702 tidyTy tidies up a type for printing in an error message, or in
705 It doesn't change the uniques at all, just the print names.
708 tidyTyVarBndr :: TidyEnv -> TyVar -> (TidyEnv, TyVar)
709 tidyTyVarBndr (tidy_env, subst) tyvar
710 = case tidyOccName tidy_env (getOccName name) of
711 (tidy', occ') -> ((tidy', subst'), tyvar')
713 subst' = extendVarEnv subst tyvar tyvar'
714 tyvar' = setTyVarName tyvar name'
715 name' = tidyNameOcc name occ'
717 name = tyVarName tyvar
719 tidyFreeTyVars :: TidyEnv -> TyVarSet -> TidyEnv
720 -- Add the free tyvars to the env in tidy form,
721 -- so that we can tidy the type they are free in
722 tidyFreeTyVars env tyvars = fst (tidyOpenTyVars env (varSetElems tyvars))
724 tidyOpenTyVars :: TidyEnv -> [TyVar] -> (TidyEnv, [TyVar])
725 tidyOpenTyVars env tyvars = mapAccumL tidyOpenTyVar env tyvars
727 tidyOpenTyVar :: TidyEnv -> TyVar -> (TidyEnv, TyVar)
728 -- Treat a new tyvar as a binder, and give it a fresh tidy name
729 tidyOpenTyVar env@(tidy_env, subst) tyvar
730 = case lookupVarEnv subst tyvar of
731 Just tyvar' -> (env, tyvar') -- Already substituted
732 Nothing -> tidyTyVarBndr env tyvar -- Treat it as a binder
734 tidyType :: TidyEnv -> Type -> Type
735 tidyType env@(tidy_env, subst) ty
738 go (TyVarTy tv) = case lookupVarEnv subst tv of
739 Nothing -> TyVarTy tv
740 Just tv' -> TyVarTy tv'
741 go (TyConApp tycon tys) = let args = map go tys
742 in args `seqList` TyConApp tycon args
743 go (NoteTy note ty) = (NoteTy $! (go_note note)) $! (go ty)
744 go (PredTy sty) = PredTy (tidyPred env sty)
745 go (AppTy fun arg) = (AppTy $! (go fun)) $! (go arg)
746 go (FunTy fun arg) = (FunTy $! (go fun)) $! (go arg)
747 go (ForAllTy tv ty) = ForAllTy tvp $! (tidyType envp ty)
749 (envp, tvp) = tidyTyVarBndr env tv
751 go_note note@(FTVNote ftvs) = note -- No need to tidy the free tyvars
753 tidyTypes env tys = map (tidyType env) tys
755 tidyPred :: TidyEnv -> PredType -> PredType
756 tidyPred env (IParam n ty) = IParam n (tidyType env ty)
757 tidyPred env (ClassP clas tys) = ClassP clas (tidyTypes env tys)
758 tidyPred env (EqPred ty1 ty2) = EqPred (tidyType env ty1) (tidyType env ty2)
762 @tidyOpenType@ grabs the free type variables, tidies them
763 and then uses @tidyType@ to work over the type itself
766 tidyOpenType :: TidyEnv -> Type -> (TidyEnv, Type)
768 = (env', tidyType env' ty)
770 env' = tidyFreeTyVars env (tyVarsOfType ty)
772 tidyOpenTypes :: TidyEnv -> [Type] -> (TidyEnv, [Type])
773 tidyOpenTypes env tys = mapAccumL tidyOpenType env tys
775 tidyTopType :: Type -> Type
776 tidyTopType ty = tidyType emptyTidyEnv ty
781 tidyKind :: TidyEnv -> Kind -> (TidyEnv, Kind)
782 tidyKind env k = tidyOpenType env k
787 %************************************************************************
789 \subsection{Liftedness}
791 %************************************************************************
794 isUnLiftedType :: Type -> Bool
795 -- isUnLiftedType returns True for forall'd unlifted types:
796 -- x :: forall a. Int#
797 -- I found bindings like these were getting floated to the top level.
798 -- They are pretty bogus types, mind you. It would be better never to
801 isUnLiftedType ty | Just ty' <- coreView ty = isUnLiftedType ty'
802 isUnLiftedType (ForAllTy tv ty) = isUnLiftedType ty
803 isUnLiftedType (TyConApp tc _) = isUnLiftedTyCon tc
804 isUnLiftedType other = False
806 isUnboxedTupleType :: Type -> Bool
807 isUnboxedTupleType ty = case splitTyConApp_maybe ty of
808 Just (tc, ty_args) -> isUnboxedTupleTyCon tc
811 -- Should only be applied to *types*; hence the assert
812 isAlgType :: Type -> Bool
813 isAlgType ty = case splitTyConApp_maybe ty of
814 Just (tc, ty_args) -> ASSERT( ty_args `lengthIs` tyConArity tc )
819 @isStrictType@ computes whether an argument (or let RHS) should
820 be computed strictly or lazily, based only on its type.
821 Works just like isUnLiftedType, except that it has a special case
822 for dictionaries. Since it takes account of ClassP, you might think
823 this function should be in TcType, but isStrictType is used by DataCon,
824 which is below TcType in the hierarchy, so it's convenient to put it here.
827 isStrictType (PredTy pred) = isStrictPred pred
828 isStrictType ty | Just ty' <- coreView ty = isStrictType ty'
829 isStrictType (ForAllTy tv ty) = isStrictType ty
830 isStrictType (TyConApp tc _) = isUnLiftedTyCon tc
831 isStrictType other = False
833 isStrictPred (ClassP clas _) = opt_DictsStrict && not (isNewTyCon (classTyCon clas))
834 isStrictPred other = False
835 -- We may be strict in dictionary types, but only if it
836 -- has more than one component.
837 -- [Being strict in a single-component dictionary risks
838 -- poking the dictionary component, which is wrong.]
842 isPrimitiveType :: Type -> Bool
843 -- Returns types that are opaque to Haskell.
844 -- Most of these are unlifted, but now that we interact with .NET, we
845 -- may have primtive (foreign-imported) types that are lifted
846 isPrimitiveType ty = case splitTyConApp_maybe ty of
847 Just (tc, ty_args) -> ASSERT( ty_args `lengthIs` tyConArity tc )
853 %************************************************************************
855 \subsection{Sequencing on types
857 %************************************************************************
860 seqType :: Type -> ()
861 seqType (TyVarTy tv) = tv `seq` ()
862 seqType (AppTy t1 t2) = seqType t1 `seq` seqType t2
863 seqType (FunTy t1 t2) = seqType t1 `seq` seqType t2
864 seqType (NoteTy note t2) = seqNote note `seq` seqType t2
865 seqType (PredTy p) = seqPred p
866 seqType (TyConApp tc tys) = tc `seq` seqTypes tys
867 seqType (ForAllTy tv ty) = tv `seq` seqType ty
869 seqTypes :: [Type] -> ()
871 seqTypes (ty:tys) = seqType ty `seq` seqTypes tys
873 seqNote :: TyNote -> ()
874 seqNote (FTVNote set) = sizeUniqSet set `seq` ()
876 seqPred :: PredType -> ()
877 seqPred (ClassP c tys) = c `seq` seqTypes tys
878 seqPred (IParam n ty) = n `seq` seqType ty
879 seqPred (EqPred ty1 ty2) = seqType ty1 `seq` seqType ty2
883 %************************************************************************
885 Equality for Core types
886 (We don't use instances so that we know where it happens)
888 %************************************************************************
890 Note that eqType works right even for partial applications of newtypes.
891 See Note [Newtype eta] in TyCon.lhs
894 coreEqType :: Type -> Type -> Bool
898 rn_env = mkRnEnv2 (mkInScopeSet (tyVarsOfType t1 `unionVarSet` tyVarsOfType t2))
900 eq env (TyVarTy tv1) (TyVarTy tv2) = rnOccL env tv1 == rnOccR env tv2
901 eq env (ForAllTy tv1 t1) (ForAllTy tv2 t2) = eq (rnBndr2 env tv1 tv2) t1 t2
902 eq env (AppTy s1 t1) (AppTy s2 t2) = eq env s1 s2 && eq env t1 t2
903 eq env (FunTy s1 t1) (FunTy s2 t2) = eq env s1 s2 && eq env t1 t2
904 eq env (TyConApp tc1 tys1) (TyConApp tc2 tys2)
905 | tc1 == tc2, all2 (eq env) tys1 tys2 = True
906 -- The lengths should be equal because
907 -- the two types have the same kind
908 -- NB: if the type constructors differ that does not
909 -- necessarily mean that the types aren't equal
910 -- (synonyms, newtypes)
911 -- Even if the type constructors are the same, but the arguments
912 -- differ, the two types could be the same (e.g. if the arg is just
913 -- ignored in the RHS). In both these cases we fall through to an
914 -- attempt to expand one side or the other.
916 -- Now deal with newtypes, synonyms, pred-tys
917 eq env t1 t2 | Just t1' <- coreView t1 = eq env t1' t2
918 | Just t2' <- coreView t2 = eq env t1 t2'
920 -- Fall through case; not equal!
925 %************************************************************************
927 Comparision for source types
928 (We don't use instances so that we know where it happens)
930 %************************************************************************
934 do *not* look through newtypes, PredTypes
937 tcEqType :: Type -> Type -> Bool
938 tcEqType t1 t2 = isEqual $ cmpType t1 t2
940 tcEqTypes :: [Type] -> [Type] -> Bool
941 tcEqTypes tys1 tys2 = isEqual $ cmpTypes tys1 tys2
943 tcCmpType :: Type -> Type -> Ordering
944 tcCmpType t1 t2 = cmpType t1 t2
946 tcCmpTypes :: [Type] -> [Type] -> Ordering
947 tcCmpTypes tys1 tys2 = cmpTypes tys1 tys2
949 tcEqPred :: PredType -> PredType -> Bool
950 tcEqPred p1 p2 = isEqual $ cmpPred p1 p2
952 tcCmpPred :: PredType -> PredType -> Ordering
953 tcCmpPred p1 p2 = cmpPred p1 p2
955 tcEqTypeX :: RnEnv2 -> Type -> Type -> Bool
956 tcEqTypeX env t1 t2 = isEqual $ cmpTypeX env t1 t2
959 Now here comes the real worker
962 cmpType :: Type -> Type -> Ordering
963 cmpType t1 t2 = cmpTypeX rn_env t1 t2
965 rn_env = mkRnEnv2 (mkInScopeSet (tyVarsOfType t1 `unionVarSet` tyVarsOfType t2))
967 cmpTypes :: [Type] -> [Type] -> Ordering
968 cmpTypes ts1 ts2 = cmpTypesX rn_env ts1 ts2
970 rn_env = mkRnEnv2 (mkInScopeSet (tyVarsOfTypes ts1 `unionVarSet` tyVarsOfTypes ts2))
972 cmpPred :: PredType -> PredType -> Ordering
973 cmpPred p1 p2 = cmpPredX rn_env p1 p2
975 rn_env = mkRnEnv2 (mkInScopeSet (tyVarsOfPred p1 `unionVarSet` tyVarsOfPred p2))
977 cmpTypeX :: RnEnv2 -> Type -> Type -> Ordering -- Main workhorse
978 cmpTypeX env t1 t2 | Just t1' <- tcView t1 = cmpTypeX env t1' t2
979 | Just t2' <- tcView t2 = cmpTypeX env t1 t2'
981 cmpTypeX env (TyVarTy tv1) (TyVarTy tv2) = rnOccL env tv1 `compare` rnOccR env tv2
982 cmpTypeX env (ForAllTy tv1 t1) (ForAllTy tv2 t2) = cmpTypeX (rnBndr2 env tv1 tv2) t1 t2
983 cmpTypeX env (AppTy s1 t1) (AppTy s2 t2) = cmpTypeX env s1 s2 `thenCmp` cmpTypeX env t1 t2
984 cmpTypeX env (FunTy s1 t1) (FunTy s2 t2) = cmpTypeX env s1 s2 `thenCmp` cmpTypeX env t1 t2
985 cmpTypeX env (PredTy p1) (PredTy p2) = cmpPredX env p1 p2
986 cmpTypeX env (TyConApp tc1 tys1) (TyConApp tc2 tys2) = (tc1 `compare` tc2) `thenCmp` cmpTypesX env tys1 tys2
987 cmpTypeX env t1 (NoteTy _ t2) = cmpTypeX env t1 t2
989 -- Deal with the rest: TyVarTy < AppTy < FunTy < TyConApp < ForAllTy < PredTy
990 cmpTypeX env (AppTy _ _) (TyVarTy _) = GT
992 cmpTypeX env (FunTy _ _) (TyVarTy _) = GT
993 cmpTypeX env (FunTy _ _) (AppTy _ _) = GT
995 cmpTypeX env (TyConApp _ _) (TyVarTy _) = GT
996 cmpTypeX env (TyConApp _ _) (AppTy _ _) = GT
997 cmpTypeX env (TyConApp _ _) (FunTy _ _) = GT
999 cmpTypeX env (ForAllTy _ _) (TyVarTy _) = GT
1000 cmpTypeX env (ForAllTy _ _) (AppTy _ _) = GT
1001 cmpTypeX env (ForAllTy _ _) (FunTy _ _) = GT
1002 cmpTypeX env (ForAllTy _ _) (TyConApp _ _) = GT
1004 cmpTypeX env (PredTy _) t2 = GT
1006 cmpTypeX env _ _ = LT
1009 cmpTypesX :: RnEnv2 -> [Type] -> [Type] -> Ordering
1010 cmpTypesX env [] [] = EQ
1011 cmpTypesX env (t1:tys1) (t2:tys2) = cmpTypeX env t1 t2 `thenCmp` cmpTypesX env tys1 tys2
1012 cmpTypesX env [] tys = LT
1013 cmpTypesX env ty [] = GT
1016 cmpPredX :: RnEnv2 -> PredType -> PredType -> Ordering
1017 cmpPredX env (IParam n1 ty1) (IParam n2 ty2) = (n1 `compare` n2) `thenCmp` cmpTypeX env ty1 ty2
1018 -- Compare names only for implicit parameters
1019 -- This comparison is used exclusively (I believe)
1020 -- for the Avails finite map built in TcSimplify
1021 -- If the types differ we keep them distinct so that we see
1022 -- a distinct pair to run improvement on
1023 cmpPredX env (ClassP c1 tys1) (ClassP c2 tys2) = (c1 `compare` c2) `thenCmp` (cmpTypesX env tys1 tys2)
1024 cmpPredX env (EqPred ty1 ty2) (EqPred ty1' ty2') = (cmpTypeX env ty1 ty1') `thenCmp` (cmpTypeX env ty2 ty2')
1026 -- Constructor order: IParam < ClassP < EqPred
1027 cmpPredX env (IParam {}) _ = LT
1028 cmpPredX env (ClassP {}) (IParam {}) = GT
1029 cmpPredX env (ClassP {}) (EqPred {}) = LT
1030 cmpPredX env (EqPred {}) _ = GT
1033 PredTypes are used as a FM key in TcSimplify,
1034 so we take the easy path and make them an instance of Ord
1037 instance Eq PredType where { (==) = tcEqPred }
1038 instance Ord PredType where { compare = tcCmpPred }
1042 %************************************************************************
1046 %************************************************************************
1050 = TvSubst InScopeSet -- The in-scope type variables
1051 TvSubstEnv -- The substitution itself
1052 -- See Note [Apply Once]
1053 -- and Note [Extending the TvSubstEnv]
1055 {- ----------------------------------------------------------
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.
1076 Note [Extending the TvSubst]
1077 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1078 The following invariant should hold of a TvSubst
1080 The in-scope set is needed *only* to
1081 guide the generation of fresh uniques
1083 In particular, the *kind* of the type variables in
1084 the in-scope set is not relevant
1086 This invariant allows a short-cut when the TvSubstEnv is empty:
1087 if the TvSubstEnv is empty --- i.e. (isEmptyTvSubt subst) holds ---
1088 then (substTy subst ty) does nothing.
1090 For example, consider:
1091 (/\a. /\b:(a~Int). ...b..) Int
1092 We substitute Int for 'a'. The Unique of 'b' does not change, but
1093 nevertheless we add 'b' to the TvSubstEnv, because b's type does change
1095 This invariant has several crucial consequences:
1097 * In substTyVarBndr, we need extend the TvSubstEnv
1098 - if the unique has changed
1099 - or if the kind has changed
1101 * In substTyVar, we do not need to consult the in-scope set;
1102 the TvSubstEnv is enough
1104 * In substTy, substTheta, we can short-circuit when the TvSubstEnv is empty
1107 -------------------------------------------------------------- -}
1110 type TvSubstEnv = TyVarEnv Type
1111 -- A TvSubstEnv is used both inside a TvSubst (with the apply-once
1112 -- invariant discussed in Note [Apply Once]), and also independently
1113 -- in the middle of matching, and unification (see Types.Unify)
1114 -- So you have to look at the context to know if it's idempotent or
1115 -- apply-once or whatever
1116 emptyTvSubstEnv :: TvSubstEnv
1117 emptyTvSubstEnv = emptyVarEnv
1119 composeTvSubst :: InScopeSet -> TvSubstEnv -> TvSubstEnv -> TvSubstEnv
1120 -- (compose env1 env2)(x) is env1(env2(x)); i.e. apply env2 then env1
1121 -- It assumes that both are idempotent
1122 -- Typically, env1 is the refinement to a base substitution env2
1123 composeTvSubst in_scope env1 env2
1124 = env1 `plusVarEnv` mapVarEnv (substTy subst1) env2
1125 -- First apply env1 to the range of env2
1126 -- Then combine the two, making sure that env1 loses if
1127 -- both bind the same variable; that's why env1 is the
1128 -- *left* argument to plusVarEnv, because the right arg wins
1130 subst1 = TvSubst in_scope env1
1132 emptyTvSubst = TvSubst emptyInScopeSet emptyVarEnv
1134 isEmptyTvSubst :: TvSubst -> Bool
1135 -- See Note [Extending the TvSubstEnv]
1136 isEmptyTvSubst (TvSubst _ env) = isEmptyVarEnv env
1138 mkTvSubst :: InScopeSet -> TvSubstEnv -> TvSubst
1141 getTvSubstEnv :: TvSubst -> TvSubstEnv
1142 getTvSubstEnv (TvSubst _ env) = env
1144 getTvInScope :: TvSubst -> InScopeSet
1145 getTvInScope (TvSubst in_scope _) = in_scope
1147 isInScope :: Var -> TvSubst -> Bool
1148 isInScope v (TvSubst in_scope _) = v `elemInScopeSet` in_scope
1150 notElemTvSubst :: TyVar -> TvSubst -> Bool
1151 notElemTvSubst tv (TvSubst _ env) = not (tv `elemVarEnv` env)
1153 setTvSubstEnv :: TvSubst -> TvSubstEnv -> TvSubst
1154 setTvSubstEnv (TvSubst in_scope _) env = TvSubst in_scope env
1156 extendTvInScope :: TvSubst -> [Var] -> TvSubst
1157 extendTvInScope (TvSubst in_scope env) vars = TvSubst (extendInScopeSetList in_scope vars) env
1159 extendTvSubst :: TvSubst -> TyVar -> Type -> TvSubst
1160 extendTvSubst (TvSubst in_scope env) tv ty = TvSubst in_scope (extendVarEnv env tv ty)
1162 extendTvSubstList :: TvSubst -> [TyVar] -> [Type] -> TvSubst
1163 extendTvSubstList (TvSubst in_scope env) tvs tys
1164 = TvSubst in_scope (extendVarEnvList env (tvs `zip` tys))
1166 -- mkOpenTvSubst and zipOpenTvSubst generate the in-scope set from
1167 -- the types given; but it's just a thunk so with a bit of luck
1168 -- it'll never be evaluated
1170 mkOpenTvSubst :: TvSubstEnv -> TvSubst
1171 mkOpenTvSubst env = TvSubst (mkInScopeSet (tyVarsOfTypes (varEnvElts env))) env
1173 zipOpenTvSubst :: [TyVar] -> [Type] -> TvSubst
1174 zipOpenTvSubst tyvars tys
1176 | length tyvars /= length tys
1177 = pprTrace "zipOpenTvSubst" (ppr tyvars $$ ppr tys) emptyTvSubst
1180 = TvSubst (mkInScopeSet (tyVarsOfTypes tys)) (zipTyEnv tyvars tys)
1182 -- mkTopTvSubst is called when doing top-level substitutions.
1183 -- Here we expect that the free vars of the range of the
1184 -- substitution will be empty.
1185 mkTopTvSubst :: [(TyVar, Type)] -> TvSubst
1186 mkTopTvSubst prs = TvSubst emptyInScopeSet (mkVarEnv prs)
1188 zipTopTvSubst :: [TyVar] -> [Type] -> TvSubst
1189 zipTopTvSubst tyvars tys
1191 | length tyvars /= length tys
1192 = pprTrace "zipOpenTvSubst" (ppr tyvars $$ ppr tys) emptyTvSubst
1195 = TvSubst emptyInScopeSet (zipTyEnv tyvars tys)
1197 zipTyEnv :: [TyVar] -> [Type] -> TvSubstEnv
1200 | length tyvars /= length tys
1201 = pprTrace "mkTopTvSubst" (ppr tyvars $$ ppr tys) emptyVarEnv
1204 = zip_ty_env tyvars tys emptyVarEnv
1206 -- Later substitutions in the list over-ride earlier ones,
1207 -- but there should be no loops
1208 zip_ty_env [] [] env = env
1209 zip_ty_env (tv:tvs) (ty:tys) env = zip_ty_env tvs tys (extendVarEnv env tv ty)
1210 -- There used to be a special case for when
1212 -- (a not-uncommon case) in which case the substitution was dropped.
1213 -- But the type-tidier changes the print-name of a type variable without
1214 -- changing the unique, and that led to a bug. Why? Pre-tidying, we had
1215 -- a type {Foo t}, where Foo is a one-method class. So Foo is really a newtype.
1216 -- And it happened that t was the type variable of the class. Post-tiding,
1217 -- it got turned into {Foo t2}. The ext-core printer expanded this using
1218 -- sourceTypeRep, but that said "Oh, t == t2" because they have the same unique,
1219 -- and so generated a rep type mentioning t not t2.
1221 -- Simplest fix is to nuke the "optimisation"
1222 zip_ty_env tvs tys env = pprTrace "Var/Type length mismatch: " (ppr tvs $$ ppr tys) env
1223 -- zip_ty_env _ _ env = env
1225 instance Outputable TvSubst where
1226 ppr (TvSubst ins env)
1227 = brackets $ sep[ ptext SLIT("TvSubst"),
1228 nest 2 (ptext SLIT("In scope:") <+> ppr ins),
1229 nest 2 (ptext SLIT("Env:") <+> ppr env) ]
1232 %************************************************************************
1234 Performing type substitutions
1236 %************************************************************************
1239 substTyWith :: [TyVar] -> [Type] -> Type -> Type
1240 substTyWith tvs tys = ASSERT( length tvs == length tys )
1241 substTy (zipOpenTvSubst tvs tys)
1243 substTy :: TvSubst -> Type -> Type
1244 substTy subst ty | isEmptyTvSubst subst = ty
1245 | otherwise = subst_ty subst ty
1247 substTys :: TvSubst -> [Type] -> [Type]
1248 substTys subst tys | isEmptyTvSubst subst = tys
1249 | otherwise = map (subst_ty subst) tys
1251 substTheta :: TvSubst -> ThetaType -> ThetaType
1252 substTheta subst theta
1253 | isEmptyTvSubst subst = theta
1254 | otherwise = map (substPred subst) theta
1256 substPred :: TvSubst -> PredType -> PredType
1257 substPred subst (IParam n ty) = IParam n (subst_ty subst ty)
1258 substPred subst (ClassP clas tys) = ClassP clas (map (subst_ty subst) tys)
1259 substPred subst (EqPred ty1 ty2) = EqPred (subst_ty subst ty1) (subst_ty subst ty2)
1261 deShadowTy :: TyVarSet -> Type -> Type -- Remove any nested binders mentioning tvs
1263 = subst_ty (mkTvSubst in_scope emptyTvSubstEnv) ty
1265 in_scope = mkInScopeSet tvs
1267 subst_ty :: TvSubst -> Type -> Type
1268 -- subst_ty is the main workhorse for type substitution
1270 -- Note that the in_scope set is poked only if we hit a forall
1271 -- so it may often never be fully computed
1275 go (TyVarTy tv) = substTyVar subst tv
1276 go (TyConApp tc tys) = let args = map go tys
1277 in args `seqList` TyConApp tc args
1279 go (PredTy p) = PredTy $! (substPred subst p)
1281 go (NoteTy (FTVNote _) ty2) = go ty2 -- Discard the free tyvar note
1283 go (FunTy arg res) = (FunTy $! (go arg)) $! (go res)
1284 go (AppTy fun arg) = mkAppTy (go fun) $! (go arg)
1285 -- The mkAppTy smart constructor is important
1286 -- we might be replacing (a Int), represented with App
1287 -- by [Int], represented with TyConApp
1288 go (ForAllTy tv ty) = case substTyVarBndr subst tv of
1289 (subst', tv') -> ForAllTy tv' $! (subst_ty subst' ty)
1291 substTyVar :: TvSubst -> TyVar -> Type
1292 substTyVar subst@(TvSubst in_scope env) tv
1293 = case lookupTyVar subst tv of {
1294 Nothing -> TyVarTy tv;
1295 Just ty -> ty -- See Note [Apply Once]
1298 lookupTyVar :: TvSubst -> TyVar -> Maybe Type
1299 -- See Note [Extending the TvSubst]
1300 lookupTyVar (TvSubst in_scope env) tv = lookupVarEnv env tv
1302 substTyVarBndr :: TvSubst -> TyVar -> (TvSubst, TyVar)
1303 substTyVarBndr subst@(TvSubst in_scope env) old_var
1304 = (TvSubst (in_scope `extendInScopeSet` new_var) new_env, new_var)
1306 is_co_var = isCoVar old_var
1308 new_env | no_change = delVarEnv env old_var
1309 | otherwise = extendVarEnv env old_var (TyVarTy new_var)
1311 no_change = new_var == old_var && not is_co_var
1312 -- no_change means that the new_var is identical in
1313 -- all respects to the old_var (same unique, same kind)
1314 -- See Note [Extending the TvSubst]
1316 -- In that case we don't need to extend the substitution
1317 -- to map old to new. But instead we must zap any
1318 -- current substitution for the variable. For example:
1319 -- (\x.e) with id_subst = [x |-> e']
1320 -- Here we must simply zap the substitution for x
1322 new_var = uniqAway in_scope subst_old_var
1323 -- The uniqAway part makes sure the new variable is not already in scope
1325 subst_old_var -- subst_old_var is old_var with the substitution applied to its kind
1326 -- It's only worth doing the substitution for coercions,
1327 -- becuase only they can have free type variables
1328 | is_co_var = setTyVarKind old_var (substTy subst (tyVarKind old_var))
1329 | otherwise = old_var
1332 ----------------------------------------------------
1337 There's a little subtyping at the kind level:
1346 where * [LiftedTypeKind] means boxed type
1347 # [UnliftedTypeKind] means unboxed type
1348 (#) [UbxTupleKind] means unboxed tuple
1349 ?? [ArgTypeKind] is the lub of *,#
1350 ? [OpenTypeKind] means any type at all
1354 error :: forall a:?. String -> a
1355 (->) :: ?? -> ? -> *
1356 (\(x::t) -> ...) Here t::?? (i.e. not unboxed tuple)
1359 type KindVar = TyVar -- invariant: KindVar will always be a
1360 -- TcTyVar with details MetaTv TauTv ...
1361 -- kind var constructors and functions are in TcType
1363 type SimpleKind = Kind
1368 During kind inference, a kind variable unifies only with
1370 sk ::= * | sk1 -> sk2
1372 data T a = MkT a (T Int#)
1373 fails. We give T the kind (k -> *), and the kind variable k won't unify
1374 with # (the kind of Int#).
1378 When creating a fresh internal type variable, we give it a kind to express
1379 constraints on it. E.g. in (\x->e) we make up a fresh type variable for x,
1382 During unification we only bind an internal type variable to a type
1383 whose kind is lower in the sub-kind hierarchy than the kind of the tyvar.
1385 When unifying two internal type variables, we collect their kind constraints by
1386 finding the GLB of the two. Since the partial order is a tree, they only
1387 have a glb if one is a sub-kind of the other. In that case, we bind the
1388 less-informative one to the more informative one. Neat, eh?
1395 %************************************************************************
1397 Functions over Kinds
1399 %************************************************************************
1402 kindFunResult :: Kind -> Kind
1403 kindFunResult k = funResultTy k
1405 splitKindFunTys :: Kind -> ([Kind],Kind)
1406 splitKindFunTys k = splitFunTys k
1408 splitKindFunTysN :: Int -> Kind -> ([Kind],Kind)
1409 splitKindFunTysN k = splitFunTysN k
1411 isUbxTupleKind, isOpenTypeKind, isArgTypeKind, isUnliftedTypeKind :: Kind -> Bool
1413 isOpenTypeKindCon tc = tyConUnique tc == openTypeKindTyConKey
1415 isOpenTypeKind (TyConApp tc _) = isOpenTypeKindCon tc
1416 isOpenTypeKind other = False
1418 isUbxTupleKindCon tc = tyConUnique tc == ubxTupleKindTyConKey
1420 isUbxTupleKind (TyConApp tc _) = isUbxTupleKindCon tc
1421 isUbxTupleKind other = False
1423 isArgTypeKindCon tc = tyConUnique tc == argTypeKindTyConKey
1425 isArgTypeKind (TyConApp tc _) = isArgTypeKindCon tc
1426 isArgTypeKind other = False
1428 isUnliftedTypeKindCon tc = tyConUnique tc == unliftedTypeKindTyConKey
1430 isUnliftedTypeKind (TyConApp tc _) = isUnliftedTypeKindCon tc
1431 isUnliftedTypeKind other = False
1433 isSubOpenTypeKind :: Kind -> Bool
1434 -- True of any sub-kind of OpenTypeKind (i.e. anything except arrow)
1435 isSubOpenTypeKind (FunTy k1 k2) = ASSERT2 ( isKind k1, text "isSubOpenTypeKind" <+> ppr k1 <+> text "::" <+> ppr (typeKind k1) )
1436 ASSERT2 ( isKind k2, text "isSubOpenTypeKind" <+> ppr k2 <+> text "::" <+> ppr (typeKind k2) )
1438 isSubOpenTypeKind (TyConApp kc []) = ASSERT( isKind (TyConApp kc []) ) True
1439 isSubOpenTypeKind other = ASSERT( isKind other ) False
1440 -- This is a conservative answer
1441 -- It matters in the call to isSubKind in
1442 -- checkExpectedKind.
1444 isSubArgTypeKindCon kc
1445 | isUnliftedTypeKindCon kc = True
1446 | isLiftedTypeKindCon kc = True
1447 | isArgTypeKindCon kc = True
1450 isSubArgTypeKind :: Kind -> Bool
1451 -- True of any sub-kind of ArgTypeKind
1452 isSubArgTypeKind (TyConApp kc []) = isSubArgTypeKindCon kc
1453 isSubArgTypeKind other = False
1455 isSuperKind :: Type -> Bool
1456 isSuperKind (TyConApp (skc) []) = isSuperKindTyCon skc
1457 isSuperKind other = False
1459 isKind :: Kind -> Bool
1460 isKind k = isSuperKind (typeKind k)
1464 isSubKind :: Kind -> Kind -> Bool
1465 -- (k1 `isSubKind` k2) checks that k1 <: k2
1466 isSubKind (TyConApp kc1 []) (TyConApp kc2 []) = kc1 `isSubKindCon` kc2
1467 isSubKind (FunTy a1 r1) (FunTy a2 r2) = (a2 `isSubKind` a1) && (r1 `isSubKind` r2)
1468 isSubKind (PredTy (EqPred ty1 ty2)) (PredTy (EqPred ty1' ty2'))
1469 = ty1 `tcEqType` ty1' && ty2 `tcEqType` ty2'
1470 isSubKind k1 k2 = False
1472 eqKind :: Kind -> Kind -> Bool
1475 isSubKindCon :: TyCon -> TyCon -> Bool
1476 -- (kc1 `isSubKindCon` kc2) checks that kc1 <: kc2
1477 isSubKindCon kc1 kc2
1478 | isLiftedTypeKindCon kc1 && isLiftedTypeKindCon kc2 = True
1479 | isUnliftedTypeKindCon kc1 && isUnliftedTypeKindCon kc2 = True
1480 | isUbxTupleKindCon kc1 && isUbxTupleKindCon kc2 = True
1481 | isOpenTypeKindCon kc2 = True
1482 -- we already know kc1 is not a fun, its a TyCon
1483 | isArgTypeKindCon kc2 && isSubArgTypeKindCon kc1 = True
1486 defaultKind :: Kind -> Kind
1487 -- Used when generalising: default kind '?' and '??' to '*'
1489 -- When we generalise, we make generic type variables whose kind is
1490 -- simple (* or *->* etc). So generic type variables (other than
1491 -- built-in constants like 'error') always have simple kinds. This is important;
1494 -- We want f to get type
1495 -- f :: forall (a::*). a -> Bool
1497 -- f :: forall (a::??). a -> Bool
1498 -- because that would allow a call like (f 3#) as well as (f True),
1499 --and the calling conventions differ. This defaulting is done in TcMType.zonkTcTyVarBndr.
1501 | isSubOpenTypeKind k = liftedTypeKind
1502 | isSubArgTypeKind k = liftedTypeKind
1505 isEqPred :: PredType -> Bool
1506 isEqPred (EqPred _ _) = True
1507 isEqPred other = False