2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1998
6 Type - public interface
10 -- The above warning supression flag is a temporary kludge.
11 -- While working on this module you are encouraged to remove it and fix
12 -- any warnings in the module. See
13 -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
17 -- re-exports from TypeRep
18 TyThing(..), Type, PredType(..), ThetaType,
22 Kind, SimpleKind, KindVar,
23 kindFunResult, splitKindFunTys, splitKindFunTysN,
25 liftedTypeKindTyCon, openTypeKindTyCon, unliftedTypeKindTyCon,
26 argTypeKindTyCon, ubxTupleKindTyCon,
28 liftedTypeKind, unliftedTypeKind, openTypeKind,
29 argTypeKind, ubxTupleKind,
31 tySuperKind, coSuperKind,
33 isLiftedTypeKind, isUnliftedTypeKind, isOpenTypeKind,
34 isUbxTupleKind, isArgTypeKind, isKind, isTySuperKind,
35 isCoSuperKind, isSuperKind, isCoercionKind, isEqPred,
36 mkArrowKind, mkArrowKinds,
38 isSubArgTypeKind, isSubOpenTypeKind, isSubKind, defaultKind, eqKind,
41 -- Re-exports from TyCon
44 mkTyVarTy, mkTyVarTys, getTyVar, getTyVar_maybe, isTyVarTy,
46 mkAppTy, mkAppTys, splitAppTy, splitAppTys,
47 splitAppTy_maybe, repSplitAppTy_maybe,
49 mkFunTy, mkFunTys, splitFunTy, splitFunTy_maybe,
50 splitFunTys, splitFunTysN,
51 funResultTy, funArgTy, zipFunTys, isFunTy,
53 mkTyConApp, mkTyConTy,
54 tyConAppTyCon, tyConAppArgs,
55 splitTyConApp_maybe, splitTyConApp,
56 splitNewTyConApp_maybe, splitNewTyConApp,
58 repType, typePrimRep, coreView, tcView, kindView, rttiView,
60 mkForAllTy, mkForAllTys, splitForAllTy_maybe, splitForAllTys,
61 applyTy, applyTys, isForAllTy, dropForAlls,
64 predTypeRep, mkPredTy, mkPredTys, pprSourceTyCon, mkFamilyTyConApp,
70 isUnLiftedType, isUnboxedTupleType, isAlgType, isClosedAlgType,
71 isPrimitiveType, isStrictType, isStrictPred,
74 tyVarsOfType, tyVarsOfTypes, tyVarsOfPred, tyVarsOfTheta,
75 typeKind, addFreeTyVars,
80 -- Tidying up for printing
82 tidyOpenType, tidyOpenTypes,
83 tidyTyVarBndr, tidyFreeTyVars,
84 tidyOpenTyVar, tidyOpenTyVars,
85 tidyTopType, tidyPred,
89 coreEqType, tcEqType, tcEqTypes, tcCmpType, tcCmpTypes,
90 tcEqPred, tcCmpPred, tcEqTypeX, tcPartOfType, tcPartOfPred,
96 TvSubstEnv, emptyTvSubstEnv, -- Representation widely visible
97 TvSubst(..), emptyTvSubst, -- Representation visible to a few friends
98 mkTvSubst, mkOpenTvSubst, zipOpenTvSubst, zipTopTvSubst, mkTopTvSubst, notElemTvSubst,
99 getTvSubstEnv, setTvSubstEnv, getTvInScope, extendTvInScope,
100 extendTvSubst, extendTvSubstList, isInScope, composeTvSubst, zipTyEnv,
103 -- Performing substitution on types
104 substTy, substTys, substTyWith, substTheta,
105 substPred, substTyVar, substTyVars, substTyVarBndr, deShadowTy, lookupTyVar,
108 pprType, pprParendType, pprTypeApp, pprTyThingCategory, pprTyThing, pprForAll,
109 pprPred, pprTheta, pprThetaArrow, pprClassPred, pprKind, pprParendKind
112 #include "HsVersions.h"
114 -- We import the representation and primitive functions from TypeRep.
115 -- Many things are reexported, but not the representation!
136 import Data.Maybe ( isJust )
140 %************************************************************************
144 %************************************************************************
146 In Core, we "look through" non-recursive newtypes and PredTypes.
149 {-# INLINE coreView #-}
150 coreView :: Type -> Maybe Type
151 -- Strips off the *top layer only* of a type to give
152 -- its underlying representation type.
153 -- Returns Nothing if there is nothing to look through.
155 -- In the case of newtypes, it returns
156 -- *either* a vanilla TyConApp (recursive newtype, or non-saturated)
157 -- *or* the newtype representation (otherwise), meaning the
158 -- type written in the RHS of the newtype decl,
159 -- which may itself be a newtype
161 -- Example: newtype R = MkR S
163 -- newtype T = MkT (T -> T)
164 -- expandNewTcApp on R gives Just S
166 -- on T gives Nothing (no expansion)
168 -- By being non-recursive and inlined, this case analysis gets efficiently
169 -- joined onto the case analysis that the caller is already doing
170 coreView (NoteTy _ ty) = Just ty
172 | isEqPred p = Nothing
173 | otherwise = Just (predTypeRep p)
174 coreView (TyConApp tc tys) | Just (tenv, rhs, tys') <- coreExpandTyCon_maybe tc tys
175 = Just (mkAppTys (substTy (mkTopTvSubst tenv) rhs) tys')
176 -- Its important to use mkAppTys, rather than (foldl AppTy),
177 -- because the function part might well return a
178 -- partially-applied type constructor; indeed, usually will!
179 coreView ty = Nothing
183 -----------------------------------------------
184 {-# INLINE tcView #-}
185 tcView :: Type -> Maybe Type
186 -- Same, but for the type checker, which just looks through synonyms
187 tcView (NoteTy _ ty) = Just ty
188 tcView (TyConApp tc tys) | Just (tenv, rhs, tys') <- tcExpandTyCon_maybe tc tys
189 = Just (mkAppTys (substTy (mkTopTvSubst tenv) rhs) tys')
192 -----------------------------------------------
193 rttiView :: Type -> Type
194 -- Same, but for the RTTI system, which cannot deal with predicates nor polymorphism
195 rttiView (ForAllTy _ ty) = rttiView ty
196 rttiView (NoteTy _ ty) = rttiView ty
197 rttiView (FunTy PredTy{} ty) = rttiView ty
198 rttiView (FunTy NoteTy{} ty) = rttiView ty
199 rttiView ty@TyConApp{} | Just ty' <- coreView ty
201 rttiView (TyConApp tc tys) = mkTyConApp tc (map rttiView tys)
204 -----------------------------------------------
205 {-# INLINE kindView #-}
206 kindView :: Kind -> Maybe Kind
207 -- C.f. coreView, tcView
208 -- For the moment, we don't even handle synonyms in kinds
209 kindView (NoteTy _ k) = Just k
210 kindView other = Nothing
214 %************************************************************************
216 \subsection{Constructor-specific functions}
218 %************************************************************************
221 ---------------------------------------------------------------------
225 mkTyVarTy :: TyVar -> Type
228 mkTyVarTys :: [TyVar] -> [Type]
229 mkTyVarTys = map mkTyVarTy -- a common use of mkTyVarTy
231 getTyVar :: String -> Type -> TyVar
232 getTyVar msg ty = case getTyVar_maybe ty of
234 Nothing -> panic ("getTyVar: " ++ msg)
236 isTyVarTy :: Type -> Bool
237 isTyVarTy ty = isJust (getTyVar_maybe ty)
239 getTyVar_maybe :: Type -> Maybe TyVar
240 getTyVar_maybe ty | Just ty' <- coreView ty = getTyVar_maybe ty'
241 getTyVar_maybe (TyVarTy tv) = Just tv
242 getTyVar_maybe other = Nothing
247 ---------------------------------------------------------------------
250 We need to be pretty careful with AppTy to make sure we obey the
251 invariant that a TyConApp is always visibly so. mkAppTy maintains the
255 mkAppTy orig_ty1 orig_ty2
258 mk_app (NoteTy _ ty1) = mk_app ty1
259 mk_app (TyConApp tc tys) = mkTyConApp tc (tys ++ [orig_ty2])
260 mk_app ty1 = AppTy orig_ty1 orig_ty2
261 -- Note that the TyConApp could be an
262 -- under-saturated type synonym. GHC allows that; e.g.
263 -- type Foo k = k a -> k a
265 -- foo :: Foo Id -> Foo Id
267 -- Here Id is partially applied in the type sig for Foo,
268 -- but once the type synonyms are expanded all is well
270 mkAppTys :: Type -> [Type] -> Type
271 mkAppTys orig_ty1 [] = orig_ty1
272 -- This check for an empty list of type arguments
273 -- avoids the needless loss of a type synonym constructor.
274 -- For example: mkAppTys Rational []
275 -- returns to (Ratio Integer), which has needlessly lost
276 -- the Rational part.
277 mkAppTys orig_ty1 orig_tys2
280 mk_app (NoteTy _ ty1) = mk_app ty1
281 mk_app (TyConApp tc tys) = mkTyConApp tc (tys ++ orig_tys2)
282 -- mkTyConApp: see notes with mkAppTy
283 mk_app ty1 = foldl AppTy orig_ty1 orig_tys2
286 splitAppTy_maybe :: Type -> Maybe (Type, Type)
287 splitAppTy_maybe ty | Just ty' <- coreView ty
288 = splitAppTy_maybe ty'
289 splitAppTy_maybe ty = repSplitAppTy_maybe ty
292 repSplitAppTy_maybe :: Type -> Maybe (Type,Type)
293 -- Does the AppTy split, but assumes that any view stuff is already done
294 repSplitAppTy_maybe (FunTy ty1 ty2) = Just (TyConApp funTyCon [ty1], ty2)
295 repSplitAppTy_maybe (AppTy ty1 ty2) = Just (ty1, ty2)
296 repSplitAppTy_maybe (TyConApp tc tys)
297 | not (isOpenSynTyCon tc) || length tys > tyConArity tc
298 = case snocView tys of -- never create unsaturated type family apps
299 Just (tys', ty') -> Just (TyConApp tc tys', ty')
301 repSplitAppTy_maybe _other = Nothing
303 splitAppTy :: Type -> (Type, Type)
304 splitAppTy ty = case splitAppTy_maybe ty of
306 Nothing -> panic "splitAppTy"
309 splitAppTys :: Type -> (Type, [Type])
310 splitAppTys ty = split ty ty []
312 split orig_ty ty args | Just ty' <- coreView ty = split orig_ty ty' args
313 split orig_ty (AppTy ty arg) args = split ty ty (arg:args)
314 split orig_ty (TyConApp tc tc_args) args
315 = let -- keep type families saturated
316 n | isOpenSynTyCon tc = tyConArity tc
318 (tc_args1, tc_args2) = splitAt n tc_args
320 (TyConApp tc tc_args1, tc_args2 ++ args)
321 split orig_ty (FunTy ty1 ty2) args = ASSERT( null args )
322 (TyConApp funTyCon [], [ty1,ty2])
323 split orig_ty ty args = (orig_ty, args)
328 ---------------------------------------------------------------------
333 mkFunTy :: Type -> Type -> Type
334 mkFunTy (PredTy (EqPred ty1 ty2)) res = mkForAllTy (mkWildCoVar (PredTy (EqPred ty1 ty2))) res
335 mkFunTy arg res = FunTy arg res
337 mkFunTys :: [Type] -> Type -> Type
338 mkFunTys tys ty = foldr mkFunTy ty tys
340 isFunTy :: Type -> Bool
341 isFunTy ty = isJust (splitFunTy_maybe ty)
343 splitFunTy :: Type -> (Type, Type)
344 splitFunTy ty | Just ty' <- coreView ty = splitFunTy ty'
345 splitFunTy (FunTy arg res) = (arg, res)
346 splitFunTy other = pprPanic "splitFunTy" (ppr other)
348 splitFunTy_maybe :: Type -> Maybe (Type, Type)
349 splitFunTy_maybe ty | Just ty' <- coreView ty = splitFunTy_maybe ty'
350 splitFunTy_maybe (FunTy arg res) = Just (arg, res)
351 splitFunTy_maybe other = Nothing
353 splitFunTys :: Type -> ([Type], Type)
354 splitFunTys ty = split [] ty ty
356 split args orig_ty ty | Just ty' <- coreView ty = split args orig_ty ty'
357 split args orig_ty (FunTy arg res) = split (arg:args) res res
358 split args orig_ty ty = (reverse args, orig_ty)
360 splitFunTysN :: Int -> Type -> ([Type], Type)
361 -- Split off exactly n arg tys
362 splitFunTysN 0 ty = ([], ty)
363 splitFunTysN n ty = case splitFunTy ty of { (arg, res) ->
364 case splitFunTysN (n-1) res of { (args, res) ->
367 zipFunTys :: Outputable a => [a] -> Type -> ([(a,Type)], Type)
368 zipFunTys orig_xs orig_ty = split [] orig_xs orig_ty orig_ty
370 split acc [] nty ty = (reverse acc, nty)
372 | Just ty' <- coreView ty = split acc xs nty ty'
373 split acc (x:xs) nty (FunTy arg res) = split ((x,arg):acc) xs res res
374 split acc (x:xs) nty ty = pprPanic "zipFunTys" (ppr orig_xs <+> ppr orig_ty)
376 funResultTy :: Type -> Type
377 funResultTy ty | Just ty' <- coreView ty = funResultTy ty'
378 funResultTy (FunTy arg res) = res
379 funResultTy ty = pprPanic "funResultTy" (ppr ty)
381 funArgTy :: Type -> Type
382 funArgTy ty | Just ty' <- coreView ty = funArgTy ty'
383 funArgTy (FunTy arg res) = arg
384 funArgTy ty = pprPanic "funArgTy" (ppr ty)
388 ---------------------------------------------------------------------
391 @mkTyConApp@ is a key function, because it builds a TyConApp, FunTy or PredTy,
395 mkTyConApp :: TyCon -> [Type] -> Type
397 | isFunTyCon tycon, [ty1,ty2] <- tys
403 mkTyConTy :: TyCon -> Type
404 mkTyConTy tycon = mkTyConApp tycon []
406 -- splitTyConApp "looks through" synonyms, because they don't
407 -- mean a distinct type, but all other type-constructor applications
408 -- including functions are returned as Just ..
410 tyConAppTyCon :: Type -> TyCon
411 tyConAppTyCon ty = fst (splitTyConApp ty)
413 tyConAppArgs :: Type -> [Type]
414 tyConAppArgs ty = snd (splitTyConApp ty)
416 splitTyConApp :: Type -> (TyCon, [Type])
417 splitTyConApp ty = case splitTyConApp_maybe ty of
419 Nothing -> pprPanic "splitTyConApp" (ppr ty)
421 splitTyConApp_maybe :: Type -> Maybe (TyCon, [Type])
422 splitTyConApp_maybe ty | Just ty' <- coreView ty = splitTyConApp_maybe ty'
423 splitTyConApp_maybe (TyConApp tc tys) = Just (tc, tys)
424 splitTyConApp_maybe (FunTy arg res) = Just (funTyCon, [arg,res])
425 splitTyConApp_maybe other = Nothing
427 -- Sometimes we do NOT want to look throught a newtype. When case matching
428 -- on a newtype we want a convenient way to access the arguments of a newty
429 -- constructor so as to properly form a coercion.
430 splitNewTyConApp :: Type -> (TyCon, [Type])
431 splitNewTyConApp ty = case splitNewTyConApp_maybe ty of
433 Nothing -> pprPanic "splitNewTyConApp" (ppr ty)
434 splitNewTyConApp_maybe :: Type -> Maybe (TyCon, [Type])
435 splitNewTyConApp_maybe ty | Just ty' <- tcView ty = splitNewTyConApp_maybe ty'
436 splitNewTyConApp_maybe (TyConApp tc tys) = Just (tc, tys)
437 splitNewTyConApp_maybe (FunTy arg res) = Just (funTyCon, [arg,res])
438 splitNewTyConApp_maybe other = Nothing
440 newTyConInstRhs :: TyCon -> [Type] -> Type
441 -- Unwrap one 'layer' of newtype
442 -- Use the eta'd version if possible
443 newTyConInstRhs tycon tys
444 = ASSERT2( equalLength tvs tys1, ppr tycon $$ ppr tys $$ ppr tvs )
445 mkAppTys (substTyWith tvs tys1 ty) tys2
447 (tvs, ty) = newTyConEtadRhs tycon
448 (tys1, tys2) = splitAtList tvs tys
452 ---------------------------------------------------------------------
456 Notes on type synonyms
457 ~~~~~~~~~~~~~~~~~~~~~~
458 The various "split" functions (splitFunTy, splitRhoTy, splitForAllTy) try
459 to return type synonyms whereever possible. Thus
464 splitFunTys (a -> Foo a) = ([a], Foo a)
467 The reason is that we then get better (shorter) type signatures in
468 interfaces. Notably this plays a role in tcTySigs in TcBinds.lhs.
471 Note [Expanding newtypes]
472 ~~~~~~~~~~~~~~~~~~~~~~~~~
473 When expanding a type to expose a data-type constructor, we need to be
474 careful about newtypes, lest we fall into an infinite loop. Here are
477 newtype Id x = MkId x
478 newtype Fix f = MkFix (f (Fix f))
479 newtype T = MkT (T -> T)
482 --------------------------
484 Fix Maybe Maybe (Fix Maybe)
488 Notice that we can expand T, even though it's recursive.
489 And we can expand Id (Id Int), even though the Id shows up
490 twice at the outer level.
492 So, when expanding, we keep track of when we've seen a recursive
493 newtype at outermost level; and bale out if we see it again.
498 repType looks through
502 (d) usage annotations
503 (e) all newtypes, including recursive ones, but not newtype families
504 It's useful in the back end.
507 repType :: Type -> Type
508 -- Only applied to types of kind *; hence tycons are saturated
512 go :: [TyCon] -> Type -> Type
513 go rec_nts ty | Just ty' <- coreView ty -- Expand synonyms
516 go rec_nts (ForAllTy _ ty) -- Look through foralls
519 go rec_nts ty@(TyConApp tc tys) -- Expand newtypes
520 | Just co_con <- newTyConCo_maybe tc -- See Note [Expanding newtypes]
521 = if tc `elem` rec_nts -- in Type.lhs
523 else go rec_nts' nt_rhs
525 nt_rhs = newTyConInstRhs tc tys
526 rec_nts' | isRecursiveTyCon tc = tc:rec_nts
527 | otherwise = rec_nts
532 -- ToDo: this could be moved to the code generator, using splitTyConApp instead
533 -- of inspecting the type directly.
534 typePrimRep :: Type -> PrimRep
535 typePrimRep ty = case repType ty of
536 TyConApp tc _ -> tyConPrimRep tc
538 AppTy _ _ -> PtrRep -- See note below
540 other -> pprPanic "typePrimRep" (ppr ty)
541 -- Types of the form 'f a' must be of kind *, not *#, so
542 -- we are guaranteed that they are represented by pointers.
543 -- The reason is that f must have kind *->*, not *->*#, because
544 -- (we claim) there is no way to constrain f's kind any other
549 ---------------------------------------------------------------------
554 mkForAllTy :: TyVar -> Type -> Type
556 = mkForAllTys [tyvar] ty
558 mkForAllTys :: [TyVar] -> Type -> Type
559 mkForAllTys tyvars ty = foldr ForAllTy ty tyvars
561 isForAllTy :: Type -> Bool
562 isForAllTy (NoteTy _ ty) = isForAllTy ty
563 isForAllTy (ForAllTy _ _) = True
564 isForAllTy other_ty = False
566 splitForAllTy_maybe :: Type -> Maybe (TyVar, Type)
567 splitForAllTy_maybe ty = splitFAT_m ty
569 splitFAT_m ty | Just ty' <- coreView ty = splitFAT_m ty'
570 splitFAT_m (ForAllTy tyvar ty) = Just(tyvar, ty)
571 splitFAT_m _ = Nothing
573 splitForAllTys :: Type -> ([TyVar], Type)
574 splitForAllTys ty = split ty ty []
576 split orig_ty ty tvs | Just ty' <- coreView ty = split orig_ty ty' tvs
577 split orig_ty (ForAllTy tv ty) tvs = split ty ty (tv:tvs)
578 split orig_ty t tvs = (reverse tvs, orig_ty)
580 dropForAlls :: Type -> Type
581 dropForAlls ty = snd (splitForAllTys ty)
584 -- (mkPiType now in CoreUtils)
588 Instantiate a for-all type with one or more type arguments.
589 Used when we have a polymorphic function applied to type args:
591 Then we use (applyTys type-of-f [t1,t2]) to compute the type of
595 applyTy :: Type -> Type -> Type
596 applyTy ty arg | Just ty' <- coreView ty = applyTy ty' arg
597 applyTy (ForAllTy tv ty) arg = substTyWith [tv] [arg] ty
598 applyTy other arg = panic "applyTy"
600 applyTys :: Type -> [Type] -> Type
601 -- This function is interesting because
602 -- a) the function may have more for-alls than there are args
603 -- b) less obviously, it may have fewer for-alls
604 -- For case (b) think of
605 -- applyTys (forall a.a) [forall b.b, Int]
606 -- This really can happen, via dressing up polymorphic types with newtype
607 -- clothing. Here's an example:
608 -- newtype R = R (forall a. a->a)
609 -- foo = case undefined :: R of
612 applyTys orig_fun_ty [] = orig_fun_ty
613 applyTys orig_fun_ty arg_tys
614 | n_tvs == n_args -- The vastly common case
615 = substTyWith tvs arg_tys rho_ty
616 | n_tvs > n_args -- Too many for-alls
617 = substTyWith (take n_args tvs) arg_tys
618 (mkForAllTys (drop n_args tvs) rho_ty)
619 | otherwise -- Too many type args
620 = ASSERT2( n_tvs > 0, ppr orig_fun_ty ) -- Zero case gives infnite loop!
621 applyTys (substTyWith tvs (take n_tvs arg_tys) rho_ty)
624 (tvs, rho_ty) = splitForAllTys orig_fun_ty
626 n_args = length arg_tys
630 %************************************************************************
632 \subsection{Source types}
634 %************************************************************************
636 A "source type" is a type that is a separate type as far as the type checker is
637 concerned, but which has low-level representation as far as the back end is concerned.
639 Source types are always lifted.
641 The key function is predTypeRep which gives the representation of a source type:
644 mkPredTy :: PredType -> Type
645 mkPredTy pred = PredTy pred
647 mkPredTys :: ThetaType -> [Type]
648 mkPredTys preds = map PredTy preds
650 predTypeRep :: PredType -> Type
651 -- Convert a PredType to its "representation type";
652 -- the post-type-checking type used by all the Core passes of GHC.
653 -- Unwraps only the outermost level; for example, the result might
654 -- be a newtype application
655 predTypeRep (IParam _ ty) = ty
656 predTypeRep (ClassP clas tys) = mkTyConApp (classTyCon clas) tys
657 -- Result might be a newtype application, but the consumer will
658 -- look through that too if necessary
659 predTypeRep (EqPred ty1 ty2) = pprPanic "predTypeRep" (ppr (EqPred ty1 ty2))
661 mkFamilyTyConApp :: TyCon -> [Type] -> Type
662 -- Given a family instance TyCon and its arg types, return the
663 -- corresponding family type. E.g.
665 -- data instance T (Maybe b) = MkT b -- Instance tycon :RTL
667 -- mkFamilyTyConApp :RTL Int = T (Maybe Int)
668 mkFamilyTyConApp tc tys
669 | Just (fam_tc, fam_tys) <- tyConFamInst_maybe tc
670 , let fam_subst = zipTopTvSubst (tyConTyVars tc) tys
671 = mkTyConApp fam_tc (substTys fam_subst fam_tys)
675 -- Pretty prints a tycon, using the family instance in case of a
676 -- representation tycon. For example
677 -- e.g. data T [a] = ...
678 -- In that case we want to print `T [a]', where T is the family TyCon
680 | Just (fam_tc, tys) <- tyConFamInst_maybe tycon
681 = ppr $ fam_tc `TyConApp` tys -- can't be FunTyCon
687 %************************************************************************
689 \subsection{Kinds and free variables}
691 %************************************************************************
693 ---------------------------------------------------------------------
694 Finding the kind of a type
695 ~~~~~~~~~~~~~~~~~~~~~~~~~~
697 typeKind :: Type -> Kind
698 typeKind (TyConApp tycon tys) = ASSERT( not (isCoercionTyCon tycon) )
699 -- We should be looking for the coercion kind,
701 foldr (\_ k -> kindFunResult k) (tyConKind tycon) tys
702 typeKind (NoteTy _ ty) = typeKind ty
703 typeKind (PredTy pred) = predKind pred
704 typeKind (AppTy fun arg) = kindFunResult (typeKind fun)
705 typeKind (ForAllTy tv ty) = typeKind ty
706 typeKind (TyVarTy tyvar) = tyVarKind tyvar
707 typeKind (FunTy arg res)
708 -- Hack alert. The kind of (Int -> Int#) is liftedTypeKind (*),
709 -- not unliftedTypKind (#)
710 -- The only things that can be after a function arrow are
711 -- (a) types (of kind openTypeKind or its sub-kinds)
712 -- (b) kinds (of super-kind TY) (e.g. * -> (* -> *))
713 | isTySuperKind k = k
714 | otherwise = ASSERT( isSubOpenTypeKind k) liftedTypeKind
718 predKind :: PredType -> Kind
719 predKind (EqPred {}) = coSuperKind -- A coercion kind!
720 predKind (ClassP {}) = liftedTypeKind -- Class and implicitPredicates are
721 predKind (IParam {}) = liftedTypeKind -- always represented by lifted types
725 ---------------------------------------------------------------------
726 Free variables of a type
727 ~~~~~~~~~~~~~~~~~~~~~~~~
729 tyVarsOfType :: Type -> TyVarSet
730 -- NB: for type synonyms tyVarsOfType does *not* expand the synonym
731 tyVarsOfType (TyVarTy tv) = unitVarSet tv
732 tyVarsOfType (TyConApp tycon tys) = tyVarsOfTypes tys
733 tyVarsOfType (NoteTy (FTVNote tvs) ty2) = tvs
734 tyVarsOfType (PredTy sty) = tyVarsOfPred sty
735 tyVarsOfType (FunTy arg res) = tyVarsOfType arg `unionVarSet` tyVarsOfType res
736 tyVarsOfType (AppTy fun arg) = tyVarsOfType fun `unionVarSet` tyVarsOfType arg
737 tyVarsOfType (ForAllTy tyvar ty) = delVarSet (tyVarsOfType ty) tyvar
739 tyVarsOfTypes :: [Type] -> TyVarSet
740 tyVarsOfTypes tys = foldr (unionVarSet.tyVarsOfType) emptyVarSet tys
742 tyVarsOfPred :: PredType -> TyVarSet
743 tyVarsOfPred (IParam _ ty) = tyVarsOfType ty
744 tyVarsOfPred (ClassP _ tys) = tyVarsOfTypes tys
745 tyVarsOfPred (EqPred ty1 ty2) = tyVarsOfType ty1 `unionVarSet` tyVarsOfType ty2
747 tyVarsOfTheta :: ThetaType -> TyVarSet
748 tyVarsOfTheta = foldr (unionVarSet . tyVarsOfPred) emptyVarSet
750 -- Add a Note with the free tyvars to the top of the type
751 addFreeTyVars :: Type -> Type
752 addFreeTyVars ty@(NoteTy (FTVNote _) _) = ty
753 addFreeTyVars ty = NoteTy (FTVNote (tyVarsOfType ty)) ty
757 %************************************************************************
759 \subsection{Type families}
761 %************************************************************************
763 Type family instances occuring in a type after expanding synonyms.
766 tyFamInsts :: Type -> [(TyCon, [Type])]
768 | Just exp_ty <- tcView ty = tyFamInsts exp_ty
769 tyFamInsts (TyVarTy _) = []
770 tyFamInsts (TyConApp tc tys)
771 | isOpenSynTyCon tc = [(tc, tys)]
772 | otherwise = concat (map tyFamInsts tys)
773 tyFamInsts (FunTy ty1 ty2) = tyFamInsts ty1 ++ tyFamInsts ty2
774 tyFamInsts (AppTy ty1 ty2) = tyFamInsts ty1 ++ tyFamInsts ty2
775 tyFamInsts (ForAllTy _ ty) = tyFamInsts ty
779 %************************************************************************
781 \subsection{TidyType}
783 %************************************************************************
785 tidyTy tidies up a type for printing in an error message, or in
788 It doesn't change the uniques at all, just the print names.
791 tidyTyVarBndr :: TidyEnv -> TyVar -> (TidyEnv, TyVar)
792 tidyTyVarBndr env@(tidy_env, subst) tyvar
793 = case tidyOccName tidy_env (getOccName name) of
794 (tidy', occ') -> ((tidy', subst'), tyvar'')
796 subst' = extendVarEnv subst tyvar tyvar''
797 tyvar' = setTyVarName tyvar name'
798 name' = tidyNameOcc name occ'
799 -- Don't forget to tidy the kind for coercions!
800 tyvar'' | isCoVar tyvar = setTyVarKind tyvar' kind'
802 kind' = tidyType env (tyVarKind tyvar)
804 name = tyVarName tyvar
806 tidyFreeTyVars :: TidyEnv -> TyVarSet -> TidyEnv
807 -- Add the free tyvars to the env in tidy form,
808 -- so that we can tidy the type they are free in
809 tidyFreeTyVars env tyvars = fst (tidyOpenTyVars env (varSetElems tyvars))
811 tidyOpenTyVars :: TidyEnv -> [TyVar] -> (TidyEnv, [TyVar])
812 tidyOpenTyVars env tyvars = mapAccumL tidyOpenTyVar env tyvars
814 tidyOpenTyVar :: TidyEnv -> TyVar -> (TidyEnv, TyVar)
815 -- Treat a new tyvar as a binder, and give it a fresh tidy name
816 tidyOpenTyVar env@(tidy_env, subst) tyvar
817 = case lookupVarEnv subst tyvar of
818 Just tyvar' -> (env, tyvar') -- Already substituted
819 Nothing -> tidyTyVarBndr env tyvar -- Treat it as a binder
821 tidyType :: TidyEnv -> Type -> Type
822 tidyType env@(tidy_env, subst) ty
825 go (TyVarTy tv) = case lookupVarEnv subst tv of
826 Nothing -> TyVarTy tv
827 Just tv' -> TyVarTy tv'
828 go (TyConApp tycon tys) = let args = map go tys
829 in args `seqList` TyConApp tycon args
830 go (NoteTy note ty) = (NoteTy $! (go_note note)) $! (go ty)
831 go (PredTy sty) = PredTy (tidyPred env sty)
832 go (AppTy fun arg) = (AppTy $! (go fun)) $! (go arg)
833 go (FunTy fun arg) = (FunTy $! (go fun)) $! (go arg)
834 go (ForAllTy tv ty) = ForAllTy tvp $! (tidyType envp ty)
836 (envp, tvp) = tidyTyVarBndr env tv
838 go_note note@(FTVNote ftvs) = note -- No need to tidy the free tyvars
840 tidyTypes env tys = map (tidyType env) tys
842 tidyPred :: TidyEnv -> PredType -> PredType
843 tidyPred env (IParam n ty) = IParam n (tidyType env ty)
844 tidyPred env (ClassP clas tys) = ClassP clas (tidyTypes env tys)
845 tidyPred env (EqPred ty1 ty2) = EqPred (tidyType env ty1) (tidyType env ty2)
849 @tidyOpenType@ grabs the free type variables, tidies them
850 and then uses @tidyType@ to work over the type itself
853 tidyOpenType :: TidyEnv -> Type -> (TidyEnv, Type)
855 = (env', tidyType env' ty)
857 env' = tidyFreeTyVars env (tyVarsOfType ty)
859 tidyOpenTypes :: TidyEnv -> [Type] -> (TidyEnv, [Type])
860 tidyOpenTypes env tys = mapAccumL tidyOpenType env tys
862 tidyTopType :: Type -> Type
863 tidyTopType ty = tidyType emptyTidyEnv ty
868 tidyKind :: TidyEnv -> Kind -> (TidyEnv, Kind)
869 tidyKind env k = tidyOpenType env k
874 %************************************************************************
876 \subsection{Liftedness}
878 %************************************************************************
881 isUnLiftedType :: Type -> Bool
882 -- isUnLiftedType returns True for forall'd unlifted types:
883 -- x :: forall a. Int#
884 -- I found bindings like these were getting floated to the top level.
885 -- They are pretty bogus types, mind you. It would be better never to
888 isUnLiftedType ty | Just ty' <- coreView ty = isUnLiftedType ty'
889 isUnLiftedType (ForAllTy tv ty) = isUnLiftedType ty
890 isUnLiftedType (TyConApp tc _) = isUnLiftedTyCon tc
891 isUnLiftedType other = False
893 isUnboxedTupleType :: Type -> Bool
894 isUnboxedTupleType ty = case splitTyConApp_maybe ty of
895 Just (tc, ty_args) -> isUnboxedTupleTyCon tc
898 -- Should only be applied to *types*; hence the assert
899 isAlgType :: Type -> Bool
901 = case splitTyConApp_maybe ty of
902 Just (tc, ty_args) -> ASSERT( ty_args `lengthIs` tyConArity tc )
906 -- Should only be applied to *types*; hence the assert
907 isClosedAlgType :: Type -> Bool
909 = case splitTyConApp_maybe ty of
910 Just (tc, ty_args) -> ASSERT( ty_args `lengthIs` tyConArity tc )
911 isAlgTyCon tc && not (isOpenTyCon tc)
915 @isStrictType@ computes whether an argument (or let RHS) should
916 be computed strictly or lazily, based only on its type.
917 Works just like isUnLiftedType, except that it has a special case
918 for dictionaries. Since it takes account of ClassP, you might think
919 this function should be in TcType, but isStrictType is used by DataCon,
920 which is below TcType in the hierarchy, so it's convenient to put it here.
923 isStrictType (PredTy pred) = isStrictPred pred
924 isStrictType ty | Just ty' <- coreView ty = isStrictType ty'
925 isStrictType (ForAllTy tv ty) = isStrictType ty
926 isStrictType (TyConApp tc _) = isUnLiftedTyCon tc
927 isStrictType other = False
929 isStrictPred (ClassP clas _) = opt_DictsStrict && not (isNewTyCon (classTyCon clas))
930 isStrictPred other = False
931 -- We may be strict in dictionary types, but only if it
932 -- has more than one component.
933 -- [Being strict in a single-component dictionary risks
934 -- poking the dictionary component, which is wrong.]
938 isPrimitiveType :: Type -> Bool
939 -- Returns types that are opaque to Haskell.
940 -- Most of these are unlifted, but now that we interact with .NET, we
941 -- may have primtive (foreign-imported) types that are lifted
942 isPrimitiveType ty = case splitTyConApp_maybe ty of
943 Just (tc, ty_args) -> ASSERT( ty_args `lengthIs` tyConArity tc )
949 %************************************************************************
951 \subsection{Sequencing on types
953 %************************************************************************
956 seqType :: Type -> ()
957 seqType (TyVarTy tv) = tv `seq` ()
958 seqType (AppTy t1 t2) = seqType t1 `seq` seqType t2
959 seqType (FunTy t1 t2) = seqType t1 `seq` seqType t2
960 seqType (NoteTy note t2) = seqNote note `seq` seqType t2
961 seqType (PredTy p) = seqPred p
962 seqType (TyConApp tc tys) = tc `seq` seqTypes tys
963 seqType (ForAllTy tv ty) = tv `seq` seqType ty
965 seqTypes :: [Type] -> ()
967 seqTypes (ty:tys) = seqType ty `seq` seqTypes tys
969 seqNote :: TyNote -> ()
970 seqNote (FTVNote set) = sizeUniqSet set `seq` ()
972 seqPred :: PredType -> ()
973 seqPred (ClassP c tys) = c `seq` seqTypes tys
974 seqPred (IParam n ty) = n `seq` seqType ty
975 seqPred (EqPred ty1 ty2) = seqType ty1 `seq` seqType ty2
979 %************************************************************************
981 Equality for Core types
982 (We don't use instances so that we know where it happens)
984 %************************************************************************
986 Note that eqType works right even for partial applications of newtypes.
987 See Note [Newtype eta] in TyCon.lhs
990 coreEqType :: Type -> Type -> Bool
994 rn_env = mkRnEnv2 (mkInScopeSet (tyVarsOfType t1 `unionVarSet` tyVarsOfType t2))
996 eq env (TyVarTy tv1) (TyVarTy tv2) = rnOccL env tv1 == rnOccR env tv2
997 eq env (ForAllTy tv1 t1) (ForAllTy tv2 t2) = eq (rnBndr2 env tv1 tv2) t1 t2
998 eq env (AppTy s1 t1) (AppTy s2 t2) = eq env s1 s2 && eq env t1 t2
999 eq env (FunTy s1 t1) (FunTy s2 t2) = eq env s1 s2 && eq env t1 t2
1000 eq env (TyConApp tc1 tys1) (TyConApp tc2 tys2)
1001 | tc1 == tc2, all2 (eq env) tys1 tys2 = True
1002 -- The lengths should be equal because
1003 -- the two types have the same kind
1004 -- NB: if the type constructors differ that does not
1005 -- necessarily mean that the types aren't equal
1006 -- (synonyms, newtypes)
1007 -- Even if the type constructors are the same, but the arguments
1008 -- differ, the two types could be the same (e.g. if the arg is just
1009 -- ignored in the RHS). In both these cases we fall through to an
1010 -- attempt to expand one side or the other.
1012 -- Now deal with newtypes, synonyms, pred-tys
1013 eq env t1 t2 | Just t1' <- coreView t1 = eq env t1' t2
1014 | Just t2' <- coreView t2 = eq env t1 t2'
1016 -- Fall through case; not equal!
1017 eq env t1 t2 = False
1021 %************************************************************************
1023 Comparision for source types
1024 (We don't use instances so that we know where it happens)
1026 %************************************************************************
1030 do *not* look through newtypes, PredTypes
1033 tcEqType :: Type -> Type -> Bool
1034 tcEqType t1 t2 = isEqual $ cmpType t1 t2
1036 tcEqTypes :: [Type] -> [Type] -> Bool
1037 tcEqTypes tys1 tys2 = isEqual $ cmpTypes tys1 tys2
1039 tcCmpType :: Type -> Type -> Ordering
1040 tcCmpType t1 t2 = cmpType t1 t2
1042 tcCmpTypes :: [Type] -> [Type] -> Ordering
1043 tcCmpTypes tys1 tys2 = cmpTypes tys1 tys2
1045 tcEqPred :: PredType -> PredType -> Bool
1046 tcEqPred p1 p2 = isEqual $ cmpPred p1 p2
1048 tcCmpPred :: PredType -> PredType -> Ordering
1049 tcCmpPred p1 p2 = cmpPred p1 p2
1051 tcEqTypeX :: RnEnv2 -> Type -> Type -> Bool
1052 tcEqTypeX env t1 t2 = isEqual $ cmpTypeX env t1 t2
1055 Checks whether the second argument is a subterm of the first. (We don't care
1056 about binders, as we are only interested in syntactic subterms.)
1059 tcPartOfType :: Type -> Type -> Bool
1061 | tcEqType t1 t2 = True
1063 | Just t2' <- tcView t2 = tcPartOfType t1 t2'
1064 tcPartOfType _ (TyVarTy _) = False
1065 tcPartOfType t1 (ForAllTy _ t2) = tcPartOfType t1 t2
1066 tcPartOfType t1 (AppTy s2 t2) = tcPartOfType t1 s2 || tcPartOfType t1 t2
1067 tcPartOfType t1 (FunTy s2 t2) = tcPartOfType t1 s2 || tcPartOfType t1 t2
1068 tcPartOfType t1 (PredTy p2) = tcPartOfPred t1 p2
1069 tcPartOfType t1 (TyConApp _ ts) = any (tcPartOfType t1) ts
1070 tcPartOfType t1 (NoteTy _ t2) = tcPartOfType t1 t2
1072 tcPartOfPred :: Type -> PredType -> Bool
1073 tcPartOfPred t1 (IParam _ t2) = tcPartOfType t1 t2
1074 tcPartOfPred t1 (ClassP _ ts) = any (tcPartOfType t1) ts
1075 tcPartOfPred t1 (EqPred s2 t2) = tcPartOfType t1 s2 || tcPartOfType t1 t2
1078 Now here comes the real worker
1081 cmpType :: Type -> Type -> Ordering
1082 cmpType t1 t2 = cmpTypeX rn_env t1 t2
1084 rn_env = mkRnEnv2 (mkInScopeSet (tyVarsOfType t1 `unionVarSet` tyVarsOfType t2))
1086 cmpTypes :: [Type] -> [Type] -> Ordering
1087 cmpTypes ts1 ts2 = cmpTypesX rn_env ts1 ts2
1089 rn_env = mkRnEnv2 (mkInScopeSet (tyVarsOfTypes ts1 `unionVarSet` tyVarsOfTypes ts2))
1091 cmpPred :: PredType -> PredType -> Ordering
1092 cmpPred p1 p2 = cmpPredX rn_env p1 p2
1094 rn_env = mkRnEnv2 (mkInScopeSet (tyVarsOfPred p1 `unionVarSet` tyVarsOfPred p2))
1096 cmpTypeX :: RnEnv2 -> Type -> Type -> Ordering -- Main workhorse
1097 cmpTypeX env t1 t2 | Just t1' <- tcView t1 = cmpTypeX env t1' t2
1098 | Just t2' <- tcView t2 = cmpTypeX env t1 t2'
1100 cmpTypeX env (TyVarTy tv1) (TyVarTy tv2) = rnOccL env tv1 `compare` rnOccR env tv2
1101 cmpTypeX env (ForAllTy tv1 t1) (ForAllTy tv2 t2) = cmpTypeX (rnBndr2 env tv1 tv2) t1 t2
1102 cmpTypeX env (AppTy s1 t1) (AppTy s2 t2) = cmpTypeX env s1 s2 `thenCmp` cmpTypeX env t1 t2
1103 cmpTypeX env (FunTy s1 t1) (FunTy s2 t2) = cmpTypeX env s1 s2 `thenCmp` cmpTypeX env t1 t2
1104 cmpTypeX env (PredTy p1) (PredTy p2) = cmpPredX env p1 p2
1105 cmpTypeX env (TyConApp tc1 tys1) (TyConApp tc2 tys2) = (tc1 `compare` tc2) `thenCmp` cmpTypesX env tys1 tys2
1106 cmpTypeX env t1 (NoteTy _ t2) = cmpTypeX env t1 t2
1108 -- Deal with the rest: TyVarTy < AppTy < FunTy < TyConApp < ForAllTy < PredTy
1109 cmpTypeX env (AppTy _ _) (TyVarTy _) = GT
1111 cmpTypeX env (FunTy _ _) (TyVarTy _) = GT
1112 cmpTypeX env (FunTy _ _) (AppTy _ _) = GT
1114 cmpTypeX env (TyConApp _ _) (TyVarTy _) = GT
1115 cmpTypeX env (TyConApp _ _) (AppTy _ _) = GT
1116 cmpTypeX env (TyConApp _ _) (FunTy _ _) = GT
1118 cmpTypeX env (ForAllTy _ _) (TyVarTy _) = GT
1119 cmpTypeX env (ForAllTy _ _) (AppTy _ _) = GT
1120 cmpTypeX env (ForAllTy _ _) (FunTy _ _) = GT
1121 cmpTypeX env (ForAllTy _ _) (TyConApp _ _) = GT
1123 cmpTypeX env (PredTy _) t2 = GT
1125 cmpTypeX env _ _ = LT
1128 cmpTypesX :: RnEnv2 -> [Type] -> [Type] -> Ordering
1129 cmpTypesX env [] [] = EQ
1130 cmpTypesX env (t1:tys1) (t2:tys2) = cmpTypeX env t1 t2 `thenCmp` cmpTypesX env tys1 tys2
1131 cmpTypesX env [] tys = LT
1132 cmpTypesX env ty [] = GT
1135 cmpPredX :: RnEnv2 -> PredType -> PredType -> Ordering
1136 cmpPredX env (IParam n1 ty1) (IParam n2 ty2) = (n1 `compare` n2) `thenCmp` cmpTypeX env ty1 ty2
1137 -- Compare names only for implicit parameters
1138 -- This comparison is used exclusively (I believe)
1139 -- for the Avails finite map built in TcSimplify
1140 -- If the types differ we keep them distinct so that we see
1141 -- a distinct pair to run improvement on
1142 cmpPredX env (ClassP c1 tys1) (ClassP c2 tys2) = (c1 `compare` c2) `thenCmp` (cmpTypesX env tys1 tys2)
1143 cmpPredX env (EqPred ty1 ty2) (EqPred ty1' ty2') = (cmpTypeX env ty1 ty1') `thenCmp` (cmpTypeX env ty2 ty2')
1145 -- Constructor order: IParam < ClassP < EqPred
1146 cmpPredX env (IParam {}) _ = LT
1147 cmpPredX env (ClassP {}) (IParam {}) = GT
1148 cmpPredX env (ClassP {}) (EqPred {}) = LT
1149 cmpPredX env (EqPred {}) _ = GT
1152 PredTypes are used as a FM key in TcSimplify,
1153 so we take the easy path and make them an instance of Ord
1156 instance Eq PredType where { (==) = tcEqPred }
1157 instance Ord PredType where { compare = tcCmpPred }
1161 %************************************************************************
1165 %************************************************************************
1169 = TvSubst InScopeSet -- The in-scope type variables
1170 TvSubstEnv -- The substitution itself
1171 -- See Note [Apply Once]
1172 -- and Note [Extending the TvSubstEnv]
1174 {- ----------------------------------------------------------
1178 We use TvSubsts to instantiate things, and we might instantiate
1182 So the substition might go [a->b, b->a]. A similar situation arises in Core
1183 when we find a beta redex like
1184 (/\ a /\ b -> e) b a
1185 Then we also end up with a substition that permutes type variables. Other
1186 variations happen to; for example [a -> (a, b)].
1188 ***************************************************
1189 *** So a TvSubst must be applied precisely once ***
1190 ***************************************************
1192 A TvSubst is not idempotent, but, unlike the non-idempotent substitution
1193 we use during unifications, it must not be repeatedly applied.
1195 Note [Extending the TvSubst]
1196 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1197 The following invariant should hold of a TvSubst
1199 The in-scope set is needed *only* to
1200 guide the generation of fresh uniques
1202 In particular, the *kind* of the type variables in
1203 the in-scope set is not relevant
1205 This invariant allows a short-cut when the TvSubstEnv is empty:
1206 if the TvSubstEnv is empty --- i.e. (isEmptyTvSubt subst) holds ---
1207 then (substTy subst ty) does nothing.
1209 For example, consider:
1210 (/\a. /\b:(a~Int). ...b..) Int
1211 We substitute Int for 'a'. The Unique of 'b' does not change, but
1212 nevertheless we add 'b' to the TvSubstEnv, because b's type does change
1214 This invariant has several crucial consequences:
1216 * In substTyVarBndr, we need extend the TvSubstEnv
1217 - if the unique has changed
1218 - or if the kind has changed
1220 * In substTyVar, we do not need to consult the in-scope set;
1221 the TvSubstEnv is enough
1223 * In substTy, substTheta, we can short-circuit when the TvSubstEnv is empty
1226 -------------------------------------------------------------- -}
1229 type TvSubstEnv = TyVarEnv Type
1230 -- A TvSubstEnv is used both inside a TvSubst (with the apply-once
1231 -- invariant discussed in Note [Apply Once]), and also independently
1232 -- in the middle of matching, and unification (see Types.Unify)
1233 -- So you have to look at the context to know if it's idempotent or
1234 -- apply-once or whatever
1235 emptyTvSubstEnv :: TvSubstEnv
1236 emptyTvSubstEnv = emptyVarEnv
1238 composeTvSubst :: InScopeSet -> TvSubstEnv -> TvSubstEnv -> TvSubstEnv
1239 -- (compose env1 env2)(x) is env1(env2(x)); i.e. apply env2 then env1
1240 -- It assumes that both are idempotent
1241 -- Typically, env1 is the refinement to a base substitution env2
1242 composeTvSubst in_scope env1 env2
1243 = env1 `plusVarEnv` mapVarEnv (substTy subst1) env2
1244 -- First apply env1 to the range of env2
1245 -- Then combine the two, making sure that env1 loses if
1246 -- both bind the same variable; that's why env1 is the
1247 -- *left* argument to plusVarEnv, because the right arg wins
1249 subst1 = TvSubst in_scope env1
1251 emptyTvSubst = TvSubst emptyInScopeSet emptyVarEnv
1253 isEmptyTvSubst :: TvSubst -> Bool
1254 -- See Note [Extending the TvSubstEnv]
1255 isEmptyTvSubst (TvSubst _ env) = isEmptyVarEnv env
1257 mkTvSubst :: InScopeSet -> TvSubstEnv -> TvSubst
1260 getTvSubstEnv :: TvSubst -> TvSubstEnv
1261 getTvSubstEnv (TvSubst _ env) = env
1263 getTvInScope :: TvSubst -> InScopeSet
1264 getTvInScope (TvSubst in_scope _) = in_scope
1266 isInScope :: Var -> TvSubst -> Bool
1267 isInScope v (TvSubst in_scope _) = v `elemInScopeSet` in_scope
1269 notElemTvSubst :: TyVar -> TvSubst -> Bool
1270 notElemTvSubst tv (TvSubst _ env) = not (tv `elemVarEnv` env)
1272 setTvSubstEnv :: TvSubst -> TvSubstEnv -> TvSubst
1273 setTvSubstEnv (TvSubst in_scope _) env = TvSubst in_scope env
1275 extendTvInScope :: TvSubst -> [Var] -> TvSubst
1276 extendTvInScope (TvSubst in_scope env) vars = TvSubst (extendInScopeSetList in_scope vars) env
1278 extendTvSubst :: TvSubst -> TyVar -> Type -> TvSubst
1279 extendTvSubst (TvSubst in_scope env) tv ty = TvSubst in_scope (extendVarEnv env tv ty)
1281 extendTvSubstList :: TvSubst -> [TyVar] -> [Type] -> TvSubst
1282 extendTvSubstList (TvSubst in_scope env) tvs tys
1283 = TvSubst in_scope (extendVarEnvList env (tvs `zip` tys))
1285 -- mkOpenTvSubst and zipOpenTvSubst generate the in-scope set from
1286 -- the types given; but it's just a thunk so with a bit of luck
1287 -- it'll never be evaluated
1289 mkOpenTvSubst :: TvSubstEnv -> TvSubst
1290 mkOpenTvSubst env = TvSubst (mkInScopeSet (tyVarsOfTypes (varEnvElts env))) env
1292 zipOpenTvSubst :: [TyVar] -> [Type] -> TvSubst
1293 zipOpenTvSubst tyvars tys
1295 | length tyvars /= length tys
1296 = pprTrace "zipOpenTvSubst" (ppr tyvars $$ ppr tys) emptyTvSubst
1299 = TvSubst (mkInScopeSet (tyVarsOfTypes tys)) (zipTyEnv tyvars tys)
1301 -- mkTopTvSubst is called when doing top-level substitutions.
1302 -- Here we expect that the free vars of the range of the
1303 -- substitution will be empty.
1304 mkTopTvSubst :: [(TyVar, Type)] -> TvSubst
1305 mkTopTvSubst prs = TvSubst emptyInScopeSet (mkVarEnv prs)
1307 zipTopTvSubst :: [TyVar] -> [Type] -> TvSubst
1308 zipTopTvSubst tyvars tys
1310 | length tyvars /= length tys
1311 = pprTrace "zipTopTvSubst" (ppr tyvars $$ ppr tys) emptyTvSubst
1314 = TvSubst emptyInScopeSet (zipTyEnv tyvars tys)
1316 zipTyEnv :: [TyVar] -> [Type] -> TvSubstEnv
1319 | length tyvars /= length tys
1320 = pprTrace "mkTopTvSubst" (ppr tyvars $$ ppr tys) emptyVarEnv
1323 = zip_ty_env tyvars tys emptyVarEnv
1325 -- Later substitutions in the list over-ride earlier ones,
1326 -- but there should be no loops
1327 zip_ty_env [] [] env = env
1328 zip_ty_env (tv:tvs) (ty:tys) env = zip_ty_env tvs tys (extendVarEnv env tv ty)
1329 -- There used to be a special case for when
1331 -- (a not-uncommon case) in which case the substitution was dropped.
1332 -- But the type-tidier changes the print-name of a type variable without
1333 -- changing the unique, and that led to a bug. Why? Pre-tidying, we had
1334 -- a type {Foo t}, where Foo is a one-method class. So Foo is really a newtype.
1335 -- And it happened that t was the type variable of the class. Post-tiding,
1336 -- it got turned into {Foo t2}. The ext-core printer expanded this using
1337 -- sourceTypeRep, but that said "Oh, t == t2" because they have the same unique,
1338 -- and so generated a rep type mentioning t not t2.
1340 -- Simplest fix is to nuke the "optimisation"
1341 zip_ty_env tvs tys env = pprTrace "Var/Type length mismatch: " (ppr tvs $$ ppr tys) env
1342 -- zip_ty_env _ _ env = env
1344 instance Outputable TvSubst where
1345 ppr (TvSubst ins env)
1346 = brackets $ sep[ ptext SLIT("TvSubst"),
1347 nest 2 (ptext SLIT("In scope:") <+> ppr ins),
1348 nest 2 (ptext SLIT("Env:") <+> ppr env) ]
1351 %************************************************************************
1353 Performing type substitutions
1355 %************************************************************************
1358 substTyWith :: [TyVar] -> [Type] -> Type -> Type
1359 substTyWith tvs tys = ASSERT( length tvs == length tys )
1360 substTy (zipOpenTvSubst tvs tys)
1362 substTy :: TvSubst -> Type -> Type
1363 substTy subst ty | isEmptyTvSubst subst = ty
1364 | otherwise = subst_ty subst ty
1366 substTys :: TvSubst -> [Type] -> [Type]
1367 substTys subst tys | isEmptyTvSubst subst = tys
1368 | otherwise = map (subst_ty subst) tys
1370 substTheta :: TvSubst -> ThetaType -> ThetaType
1371 substTheta subst theta
1372 | isEmptyTvSubst subst = theta
1373 | otherwise = map (substPred subst) theta
1375 substPred :: TvSubst -> PredType -> PredType
1376 substPred subst (IParam n ty) = IParam n (subst_ty subst ty)
1377 substPred subst (ClassP clas tys) = ClassP clas (map (subst_ty subst) tys)
1378 substPred subst (EqPred ty1 ty2) = EqPred (subst_ty subst ty1) (subst_ty subst ty2)
1380 deShadowTy :: TyVarSet -> Type -> Type -- Remove any nested binders mentioning tvs
1382 = subst_ty (mkTvSubst in_scope emptyTvSubstEnv) ty
1384 in_scope = mkInScopeSet tvs
1386 subst_ty :: TvSubst -> Type -> Type
1387 -- subst_ty is the main workhorse for type substitution
1389 -- Note that the in_scope set is poked only if we hit a forall
1390 -- so it may often never be fully computed
1394 go (TyVarTy tv) = substTyVar subst tv
1395 go (TyConApp tc tys) = let args = map go tys
1396 in args `seqList` TyConApp tc args
1398 go (PredTy p) = PredTy $! (substPred subst p)
1400 go (NoteTy (FTVNote _) ty2) = go ty2 -- Discard the free tyvar note
1402 go (FunTy arg res) = (FunTy $! (go arg)) $! (go res)
1403 go (AppTy fun arg) = mkAppTy (go fun) $! (go arg)
1404 -- The mkAppTy smart constructor is important
1405 -- we might be replacing (a Int), represented with App
1406 -- by [Int], represented with TyConApp
1407 go (ForAllTy tv ty) = case substTyVarBndr subst tv of
1408 (subst', tv') -> ForAllTy tv' $! (subst_ty subst' ty)
1410 substTyVar :: TvSubst -> TyVar -> Type
1411 substTyVar subst@(TvSubst in_scope env) tv
1412 = case lookupTyVar subst tv of {
1413 Nothing -> TyVarTy tv;
1414 Just ty -> ty -- See Note [Apply Once]
1417 substTyVars :: TvSubst -> [TyVar] -> [Type]
1418 substTyVars subst tvs = map (substTyVar subst) tvs
1420 lookupTyVar :: TvSubst -> TyVar -> Maybe Type
1421 -- See Note [Extending the TvSubst]
1422 lookupTyVar (TvSubst in_scope env) tv = lookupVarEnv env tv
1424 substTyVarBndr :: TvSubst -> TyVar -> (TvSubst, TyVar)
1425 substTyVarBndr subst@(TvSubst in_scope env) old_var
1426 = (TvSubst (in_scope `extendInScopeSet` new_var) new_env, new_var)
1428 is_co_var = isCoVar old_var
1430 new_env | no_change = delVarEnv env old_var
1431 | otherwise = extendVarEnv env old_var (TyVarTy new_var)
1433 no_change = new_var == old_var && not is_co_var
1434 -- no_change means that the new_var is identical in
1435 -- all respects to the old_var (same unique, same kind)
1436 -- See Note [Extending the TvSubst]
1438 -- In that case we don't need to extend the substitution
1439 -- to map old to new. But instead we must zap any
1440 -- current substitution for the variable. For example:
1441 -- (\x.e) with id_subst = [x |-> e']
1442 -- Here we must simply zap the substitution for x
1444 new_var = uniqAway in_scope subst_old_var
1445 -- The uniqAway part makes sure the new variable is not already in scope
1447 subst_old_var -- subst_old_var is old_var with the substitution applied to its kind
1448 -- It's only worth doing the substitution for coercions,
1449 -- becuase only they can have free type variables
1450 | is_co_var = setTyVarKind old_var (substTy subst (tyVarKind old_var))
1451 | otherwise = old_var
1454 ----------------------------------------------------
1459 There's a little subtyping at the kind level:
1468 where * [LiftedTypeKind] means boxed type
1469 # [UnliftedTypeKind] means unboxed type
1470 (#) [UbxTupleKind] means unboxed tuple
1471 ?? [ArgTypeKind] is the lub of *,#
1472 ? [OpenTypeKind] means any type at all
1476 error :: forall a:?. String -> a
1477 (->) :: ?? -> ? -> *
1478 (\(x::t) -> ...) Here t::?? (i.e. not unboxed tuple)
1481 type KindVar = TyVar -- invariant: KindVar will always be a
1482 -- TcTyVar with details MetaTv TauTv ...
1483 -- kind var constructors and functions are in TcType
1485 type SimpleKind = Kind
1490 During kind inference, a kind variable unifies only with
1492 sk ::= * | sk1 -> sk2
1494 data T a = MkT a (T Int#)
1495 fails. We give T the kind (k -> *), and the kind variable k won't unify
1496 with # (the kind of Int#).
1500 When creating a fresh internal type variable, we give it a kind to express
1501 constraints on it. E.g. in (\x->e) we make up a fresh type variable for x,
1504 During unification we only bind an internal type variable to a type
1505 whose kind is lower in the sub-kind hierarchy than the kind of the tyvar.
1507 When unifying two internal type variables, we collect their kind constraints by
1508 finding the GLB of the two. Since the partial order is a tree, they only
1509 have a glb if one is a sub-kind of the other. In that case, we bind the
1510 less-informative one to the more informative one. Neat, eh?
1517 %************************************************************************
1519 Functions over Kinds
1521 %************************************************************************
1524 kindFunResult :: Kind -> Kind
1525 kindFunResult k = funResultTy k
1527 splitKindFunTys :: Kind -> ([Kind],Kind)
1528 splitKindFunTys k = splitFunTys k
1530 splitKindFunTysN :: Int -> Kind -> ([Kind],Kind)
1531 splitKindFunTysN k = splitFunTysN k
1533 isUbxTupleKind, isOpenTypeKind, isArgTypeKind, isUnliftedTypeKind :: Kind -> Bool
1535 isOpenTypeKindCon tc = tyConUnique tc == openTypeKindTyConKey
1537 isOpenTypeKind (TyConApp tc _) = isOpenTypeKindCon tc
1538 isOpenTypeKind other = False
1540 isUbxTupleKindCon tc = tyConUnique tc == ubxTupleKindTyConKey
1542 isUbxTupleKind (TyConApp tc _) = isUbxTupleKindCon tc
1543 isUbxTupleKind other = False
1545 isArgTypeKindCon tc = tyConUnique tc == argTypeKindTyConKey
1547 isArgTypeKind (TyConApp tc _) = isArgTypeKindCon tc
1548 isArgTypeKind other = False
1550 isUnliftedTypeKindCon tc = tyConUnique tc == unliftedTypeKindTyConKey
1552 isUnliftedTypeKind (TyConApp tc _) = isUnliftedTypeKindCon tc
1553 isUnliftedTypeKind other = False
1555 isSubOpenTypeKind :: Kind -> Bool
1556 -- True of any sub-kind of OpenTypeKind (i.e. anything except arrow)
1557 isSubOpenTypeKind (FunTy k1 k2) = ASSERT2 ( isKind k1, text "isSubOpenTypeKind" <+> ppr k1 <+> text "::" <+> ppr (typeKind k1) )
1558 ASSERT2 ( isKind k2, text "isSubOpenTypeKind" <+> ppr k2 <+> text "::" <+> ppr (typeKind k2) )
1560 isSubOpenTypeKind (TyConApp kc []) = ASSERT( isKind (TyConApp kc []) ) True
1561 isSubOpenTypeKind other = ASSERT( isKind other ) False
1562 -- This is a conservative answer
1563 -- It matters in the call to isSubKind in
1564 -- checkExpectedKind.
1566 isSubArgTypeKindCon kc
1567 | isUnliftedTypeKindCon kc = True
1568 | isLiftedTypeKindCon kc = True
1569 | isArgTypeKindCon kc = True
1572 isSubArgTypeKind :: Kind -> Bool
1573 -- True of any sub-kind of ArgTypeKind
1574 isSubArgTypeKind (TyConApp kc []) = isSubArgTypeKindCon kc
1575 isSubArgTypeKind other = False
1577 isSuperKind :: Type -> Bool
1578 isSuperKind (TyConApp (skc) []) = isSuperKindTyCon skc
1579 isSuperKind other = False
1581 isKind :: Kind -> Bool
1582 isKind k = isSuperKind (typeKind k)
1584 isSubKind :: Kind -> Kind -> Bool
1585 -- (k1 `isSubKind` k2) checks that k1 <: k2
1586 isSubKind (TyConApp kc1 []) (TyConApp kc2 []) = kc1 `isSubKindCon` kc2
1587 isSubKind (FunTy a1 r1) (FunTy a2 r2) = (a2 `isSubKind` a1) && (r1 `isSubKind` r2)
1588 isSubKind (PredTy (EqPred ty1 ty2)) (PredTy (EqPred ty1' ty2'))
1589 = ty1 `tcEqType` ty1' && ty2 `tcEqType` ty2'
1590 isSubKind k1 k2 = False
1592 eqKind :: Kind -> Kind -> Bool
1595 isSubKindCon :: TyCon -> TyCon -> Bool
1596 -- (kc1 `isSubKindCon` kc2) checks that kc1 <: kc2
1597 isSubKindCon kc1 kc2
1598 | isLiftedTypeKindCon kc1 && isLiftedTypeKindCon kc2 = True
1599 | isUnliftedTypeKindCon kc1 && isUnliftedTypeKindCon kc2 = True
1600 | isUbxTupleKindCon kc1 && isUbxTupleKindCon kc2 = True
1601 | isOpenTypeKindCon kc2 = True
1602 -- we already know kc1 is not a fun, its a TyCon
1603 | isArgTypeKindCon kc2 && isSubArgTypeKindCon kc1 = True
1606 defaultKind :: Kind -> Kind
1607 -- Used when generalising: default kind '?' and '??' to '*'
1609 -- When we generalise, we make generic type variables whose kind is
1610 -- simple (* or *->* etc). So generic type variables (other than
1611 -- built-in constants like 'error') always have simple kinds. This is important;
1614 -- We want f to get type
1615 -- f :: forall (a::*). a -> Bool
1617 -- f :: forall (a::??). a -> Bool
1618 -- because that would allow a call like (f 3#) as well as (f True),
1619 --and the calling conventions differ. This defaulting is done in TcMType.zonkTcTyVarBndr.
1621 | isSubOpenTypeKind k = liftedTypeKind
1622 | isSubArgTypeKind k = liftedTypeKind
1625 isEqPred :: PredType -> Bool
1626 isEqPred (EqPred _ _) = True
1627 isEqPred other = False