2 % (c) The GRASP/AQUA Project, Glasgow University, 1998
4 \section[Type]{Type - public interface}
9 -- re-exports from TypeRep
10 TyThing(..), Type, PredType(..), ThetaType,
14 Kind, SimpleKind, KindVar,
15 kindFunResult, splitKindFunTys,
17 liftedTypeKindTyCon, openTypeKindTyCon, unliftedTypeKindTyCon,
18 argTypeKindTyCon, ubxTupleKindTyCon,
20 liftedTypeKind, unliftedTypeKind, openTypeKind,
21 argTypeKind, ubxTupleKind,
23 tySuperKind, coSuperKind,
25 isLiftedTypeKind, isUnliftedTypeKind, isOpenTypeKind,
26 isUbxTupleKind, isArgTypeKind, isKind, isTySuperKind,
27 isCoSuperKind, isSuperKind, isCoercionKind,
28 mkArrowKind, mkArrowKinds,
30 isSubArgTypeKind, isSubOpenTypeKind, isSubKind, defaultKind, eqKind,
33 -- Re-exports from TyCon
36 mkTyVarTy, mkTyVarTys, getTyVar, getTyVar_maybe, isTyVarTy,
38 mkAppTy, mkAppTys, splitAppTy, splitAppTys,
39 splitAppTy_maybe, repSplitAppTy_maybe,
41 mkFunTy, mkFunTys, splitFunTy, splitFunTy_maybe,
42 splitFunTys, splitFunTysN,
43 funResultTy, funArgTy, zipFunTys, isFunTy,
45 mkTyConApp, mkTyConTy,
46 tyConAppTyCon, tyConAppArgs,
47 splitTyConApp_maybe, splitTyConApp,
48 splitNewTyConApp_maybe, splitNewTyConApp,
50 repType, typePrimRep, coreView, tcView, kindView,
52 mkForAllTy, mkForAllTys, splitForAllTy_maybe, splitForAllTys,
53 applyTy, applyTys, isForAllTy, dropForAlls,
56 predTypeRep, mkPredTy, mkPredTys,
59 splitRecNewType_maybe,
62 isUnLiftedType, isUnboxedTupleType, isAlgType, isPrimitiveType,
63 isStrictType, isStrictPred,
66 tyVarsOfType, tyVarsOfTypes, tyVarsOfPred, tyVarsOfTheta,
67 typeKind, addFreeTyVars,
69 -- Tidying up for printing
71 tidyOpenType, tidyOpenTypes,
72 tidyTyVarBndr, tidyFreeTyVars,
73 tidyOpenTyVar, tidyOpenTyVars,
74 tidyTopType, tidyPred,
78 coreEqType, tcEqType, tcEqTypes, tcCmpType, tcCmpTypes,
79 tcEqPred, tcCmpPred, tcEqTypeX,
85 TvSubstEnv, emptyTvSubstEnv, -- Representation widely visible
86 TvSubst(..), emptyTvSubst, -- Representation visible to a few friends
87 mkTvSubst, mkOpenTvSubst, zipOpenTvSubst, zipTopTvSubst, mkTopTvSubst, notElemTvSubst,
88 getTvSubstEnv, setTvSubstEnv, getTvInScope, extendTvInScope,
89 extendTvSubst, extendTvSubstList, isInScope, composeTvSubst, zipTyEnv,
91 -- Performing substitution on types
92 substTy, substTys, substTyWith, substTheta,
93 substPred, substTyVar, substTyVarBndr, deShadowTy, lookupTyVar,
96 pprType, pprParendType, pprTyThingCategory,
97 pprPred, pprTheta, pprThetaArrow, pprClassPred, pprKind, pprParendKind
100 #include "HsVersions.h"
102 -- We import the representation and primitive functions from TypeRep.
103 -- Many things are reexported, but not the representation!
108 import Var ( Var, TyVar, tyVarKind, tyVarName,
109 setTyVarName, setTyVarKind, mkTyVar, isTyVar )
110 import Name ( Name(..) )
111 import Unique ( Unique )
115 import OccName ( tidyOccName )
116 import Name ( NamedThing(..), mkInternalName, tidyNameOcc )
117 import Class ( Class, classTyCon )
118 import PrelNames( openTypeKindTyConKey, unliftedTypeKindTyConKey,
119 ubxTupleKindTyConKey, argTypeKindTyConKey,
120 eqCoercionKindTyConKey )
121 import TyCon ( TyCon, isRecursiveTyCon, isPrimTyCon,
122 isUnboxedTupleTyCon, isUnLiftedTyCon,
123 isFunTyCon, isNewTyCon, newTyConRep, newTyConRhs,
124 isAlgTyCon, tyConArity, isSuperKindTyCon,
125 tcExpandTyCon_maybe, coreExpandTyCon_maybe,
126 tyConKind, PrimRep(..), tyConPrimRep, tyConUnique,
127 isCoercionTyCon_maybe, isCoercionTyCon
131 import StaticFlags ( opt_DictsStrict )
132 import SrcLoc ( noSrcLoc )
133 import Util ( mapAccumL, seqList, lengthIs, snocView, thenCmp, isEqual, all2 )
135 import UniqSet ( sizeUniqSet ) -- Should come via VarSet
136 import 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
171 coreView (PredTy p) = Just (predTypeRep p)
172 coreView (TyConApp tc tys) | Just (tenv, rhs, tys') <- coreExpandTyCon_maybe tc tys
173 = Just (mkAppTys (substTy (mkTopTvSubst tenv) rhs) tys')
174 -- Its important to use mkAppTys, rather than (foldl AppTy),
175 -- because the function part might well return a
176 -- partially-applied type constructor; indeed, usually will!
177 coreView ty = Nothing
181 -----------------------------------------------
182 {-# INLINE tcView #-}
183 tcView :: Type -> Maybe Type
184 -- Same, but for the type checker, which just looks through synonyms
185 tcView (NoteTy _ ty) = Just ty
186 tcView (TyConApp tc tys) | Just (tenv, rhs, tys') <- tcExpandTyCon_maybe tc tys
187 = Just (mkAppTys (substTy (mkTopTvSubst tenv) rhs) tys')
190 -----------------------------------------------
191 {-# INLINE kindView #-}
192 kindView :: Kind -> Maybe Kind
193 -- C.f. coreView, tcView
194 -- For the moment, we don't even handle synonyms in kinds
195 kindView (NoteTy _ k) = Just k
196 kindView other = Nothing
200 %************************************************************************
202 \subsection{Constructor-specific functions}
204 %************************************************************************
207 ---------------------------------------------------------------------
211 mkTyVarTy :: TyVar -> Type
214 mkTyVarTys :: [TyVar] -> [Type]
215 mkTyVarTys = map mkTyVarTy -- a common use of mkTyVarTy
217 getTyVar :: String -> Type -> TyVar
218 getTyVar msg ty = case getTyVar_maybe ty of
220 Nothing -> panic ("getTyVar: " ++ msg)
222 isTyVarTy :: Type -> Bool
223 isTyVarTy ty = isJust (getTyVar_maybe ty)
225 getTyVar_maybe :: Type -> Maybe TyVar
226 getTyVar_maybe ty | Just ty' <- coreView ty = getTyVar_maybe ty'
227 getTyVar_maybe (TyVarTy tv) = Just tv
228 getTyVar_maybe other = Nothing
233 ---------------------------------------------------------------------
236 We need to be pretty careful with AppTy to make sure we obey the
237 invariant that a TyConApp is always visibly so. mkAppTy maintains the
241 mkAppTy orig_ty1 orig_ty2
244 mk_app (NoteTy _ ty1) = mk_app ty1
245 mk_app (TyConApp tc tys) = mkTyConApp tc (tys ++ [orig_ty2])
246 mk_app ty1 = AppTy orig_ty1 orig_ty2
247 -- Note that the TyConApp could be an
248 -- under-saturated type synonym. GHC allows that; e.g.
249 -- type Foo k = k a -> k a
251 -- foo :: Foo Id -> Foo Id
253 -- Here Id is partially applied in the type sig for Foo,
254 -- but once the type synonyms are expanded all is well
256 mkAppTys :: Type -> [Type] -> Type
257 mkAppTys orig_ty1 [] = orig_ty1
258 -- This check for an empty list of type arguments
259 -- avoids the needless loss of a type synonym constructor.
260 -- For example: mkAppTys Rational []
261 -- returns to (Ratio Integer), which has needlessly lost
262 -- the Rational part.
263 mkAppTys orig_ty1 orig_tys2
266 mk_app (NoteTy _ ty1) = mk_app ty1
267 mk_app (TyConApp tc tys) = mkTyConApp tc (tys ++ orig_tys2)
268 -- mkTyConApp: see notes with mkAppTy
269 mk_app ty1 = foldl AppTy orig_ty1 orig_tys2
272 splitAppTy_maybe :: Type -> Maybe (Type, Type)
273 splitAppTy_maybe ty | Just ty' <- coreView ty
274 = splitAppTy_maybe ty'
275 splitAppTy_maybe ty = repSplitAppTy_maybe ty
278 repSplitAppTy_maybe :: Type -> Maybe (Type,Type)
279 -- Does the AppTy split, but assumes that any view stuff is already done
280 repSplitAppTy_maybe (FunTy ty1 ty2) = Just (TyConApp funTyCon [ty1], ty2)
281 repSplitAppTy_maybe (AppTy ty1 ty2) = Just (ty1, ty2)
282 repSplitAppTy_maybe (TyConApp tc tys) = case snocView tys of
283 Just (tys', ty') -> Just (TyConApp tc tys', ty')
285 repSplitAppTy_maybe other = Nothing
287 splitAppTy :: Type -> (Type, Type)
288 splitAppTy ty = case splitAppTy_maybe ty of
290 Nothing -> panic "splitAppTy"
293 splitAppTys :: Type -> (Type, [Type])
294 splitAppTys ty = split ty ty []
296 split orig_ty ty args | Just ty' <- coreView ty = split orig_ty ty' args
297 split orig_ty (AppTy ty arg) args = split ty ty (arg:args)
298 split orig_ty (TyConApp tc tc_args) args = (TyConApp tc [], tc_args ++ args)
299 split orig_ty (FunTy ty1 ty2) args = ASSERT( null args )
300 (TyConApp funTyCon [], [ty1,ty2])
301 split orig_ty ty args = (orig_ty, args)
306 ---------------------------------------------------------------------
311 mkFunTy :: Type -> Type -> Type
312 mkFunTy arg res = FunTy arg res
314 mkFunTys :: [Type] -> Type -> Type
315 mkFunTys tys ty = foldr FunTy ty tys
317 isFunTy :: Type -> Bool
318 isFunTy ty = isJust (splitFunTy_maybe ty)
320 splitFunTy :: Type -> (Type, Type)
321 splitFunTy ty | Just ty' <- coreView ty = splitFunTy ty'
322 splitFunTy (FunTy arg res) = (arg, res)
323 splitFunTy other = pprPanic "splitFunTy" (ppr other)
325 splitFunTy_maybe :: Type -> Maybe (Type, Type)
326 splitFunTy_maybe ty | Just ty' <- coreView ty = splitFunTy_maybe ty'
327 splitFunTy_maybe (FunTy arg res) = Just (arg, res)
328 splitFunTy_maybe other = Nothing
330 splitFunTys :: Type -> ([Type], Type)
331 splitFunTys ty = split [] ty ty
333 split args orig_ty ty | Just ty' <- coreView ty = split args orig_ty ty'
334 split args orig_ty (FunTy arg res) = split (arg:args) res res
335 split args orig_ty ty = (reverse args, orig_ty)
337 splitFunTysN :: Int -> Type -> ([Type], Type)
338 -- Split off exactly n arg tys
339 splitFunTysN 0 ty = ([], ty)
340 splitFunTysN n ty = case splitFunTy ty of { (arg, res) ->
341 case splitFunTysN (n-1) res of { (args, res) ->
344 zipFunTys :: Outputable a => [a] -> Type -> ([(a,Type)], Type)
345 zipFunTys orig_xs orig_ty = split [] orig_xs orig_ty orig_ty
347 split acc [] nty ty = (reverse acc, nty)
349 | Just ty' <- coreView ty = split acc xs nty ty'
350 split acc (x:xs) nty (FunTy arg res) = split ((x,arg):acc) xs res res
351 split acc (x:xs) nty ty = pprPanic "zipFunTys" (ppr orig_xs <+> ppr orig_ty)
353 funResultTy :: Type -> Type
354 funResultTy ty | Just ty' <- coreView ty = funResultTy ty'
355 funResultTy (FunTy arg res) = res
356 funResultTy ty = pprPanic "funResultTy" (ppr ty)
358 funArgTy :: Type -> Type
359 funArgTy ty | Just ty' <- coreView ty = funArgTy ty'
360 funArgTy (FunTy arg res) = arg
361 funArgTy ty = pprPanic "funArgTy" (ppr ty)
365 ---------------------------------------------------------------------
368 @mkTyConApp@ is a key function, because it builds a TyConApp, FunTy or PredTy,
372 mkTyConApp :: TyCon -> [Type] -> Type
374 | isFunTyCon tycon, [ty1,ty2] <- tys
380 mkTyConTy :: TyCon -> Type
381 mkTyConTy tycon = mkTyConApp tycon []
383 -- splitTyConApp "looks through" synonyms, because they don't
384 -- mean a distinct type, but all other type-constructor applications
385 -- including functions are returned as Just ..
387 tyConAppTyCon :: Type -> TyCon
388 tyConAppTyCon ty = fst (splitTyConApp ty)
390 tyConAppArgs :: Type -> [Type]
391 tyConAppArgs ty = snd (splitTyConApp ty)
393 splitTyConApp :: Type -> (TyCon, [Type])
394 splitTyConApp ty = case splitTyConApp_maybe ty of
396 Nothing -> pprPanic "splitTyConApp" (ppr ty)
398 splitTyConApp_maybe :: Type -> Maybe (TyCon, [Type])
399 splitTyConApp_maybe ty | Just ty' <- coreView ty = splitTyConApp_maybe ty'
400 splitTyConApp_maybe (TyConApp tc tys) = Just (tc, tys)
401 splitTyConApp_maybe (FunTy arg res) = Just (funTyCon, [arg,res])
402 splitTyConApp_maybe other = Nothing
404 -- Sometimes we do NOT want to look throught a newtype. When case matching
405 -- on a newtype we want a convenient way to access the arguments of a newty
406 -- constructor so as to properly form a coercion.
407 splitNewTyConApp :: Type -> (TyCon, [Type])
408 splitNewTyConApp ty = case splitNewTyConApp_maybe ty of
410 Nothing -> pprPanic "splitNewTyConApp" (ppr ty)
411 splitNewTyConApp_maybe :: Type -> Maybe (TyCon, [Type])
412 splitNewTyConApp_maybe ty | Just ty' <- tcView ty = splitNewTyConApp_maybe ty'
413 splitNewTyConApp_maybe (TyConApp tc tys) = Just (tc, tys)
414 splitNewTyConApp_maybe (FunTy arg res) = Just (funTyCon, [arg,res])
415 splitNewTyConApp_maybe other = Nothing
420 ---------------------------------------------------------------------
424 Notes on type synonyms
425 ~~~~~~~~~~~~~~~~~~~~~~
426 The various "split" functions (splitFunTy, splitRhoTy, splitForAllTy) try
427 to return type synonyms whereever possible. Thus
432 splitFunTys (a -> Foo a) = ([a], Foo a)
435 The reason is that we then get better (shorter) type signatures in
436 interfaces. Notably this plays a role in tcTySigs in TcBinds.lhs.
441 repType looks through
445 (d) usage annotations
446 (e) all newtypes, including recursive ones
447 It's useful in the back end.
450 repType :: Type -> Type
451 -- Only applied to types of kind *; hence tycons are saturated
452 repType ty | Just ty' <- coreView ty = repType ty'
453 repType (ForAllTy _ ty) = repType ty
454 repType (TyConApp tc tys)
455 | isNewTyCon tc = -- Recursive newtypes are opaque to coreView
456 -- but we must expand them here. Sure to
457 -- be saturated because repType is only applied
458 -- to types of kind *
459 ASSERT( {- isRecursiveTyCon tc && -} tys `lengthIs` tyConArity tc )
460 repType (new_type_rep tc tys)
463 -- new_type_rep doesn't ask any questions:
464 -- it just expands newtype, whether recursive or not
465 new_type_rep new_tycon tys = ASSERT( tys `lengthIs` tyConArity new_tycon )
466 case newTyConRep new_tycon of
467 (tvs, rep_ty) -> substTyWith tvs tys rep_ty
469 -- ToDo: this could be moved to the code generator, using splitTyConApp instead
470 -- of inspecting the type directly.
471 typePrimRep :: Type -> PrimRep
472 typePrimRep ty = case repType ty of
473 TyConApp tc _ -> tyConPrimRep tc
475 AppTy _ _ -> PtrRep -- See note below
477 other -> pprPanic "typePrimRep" (ppr ty)
478 -- Types of the form 'f a' must be of kind *, not *#, so
479 -- we are guaranteed that they are represented by pointers.
480 -- The reason is that f must have kind *->*, not *->*#, because
481 -- (we claim) there is no way to constrain f's kind any other
487 ---------------------------------------------------------------------
492 mkForAllTy :: TyVar -> Type -> Type
494 = mkForAllTys [tyvar] ty
496 mkForAllTys :: [TyVar] -> Type -> Type
497 mkForAllTys tyvars ty = foldr ForAllTy ty tyvars
499 isForAllTy :: Type -> Bool
500 isForAllTy (NoteTy _ ty) = isForAllTy ty
501 isForAllTy (ForAllTy _ _) = True
502 isForAllTy other_ty = False
504 splitForAllTy_maybe :: Type -> Maybe (TyVar, Type)
505 splitForAllTy_maybe ty = splitFAT_m ty
507 splitFAT_m ty | Just ty' <- coreView ty = splitFAT_m ty'
508 splitFAT_m (ForAllTy tyvar ty) = Just(tyvar, ty)
509 splitFAT_m _ = Nothing
511 splitForAllTys :: Type -> ([TyVar], Type)
512 splitForAllTys ty = split ty ty []
514 split orig_ty ty tvs | Just ty' <- coreView ty = split orig_ty ty' tvs
515 split orig_ty (ForAllTy tv ty) tvs = split ty ty (tv:tvs)
516 split orig_ty t tvs = (reverse tvs, orig_ty)
518 dropForAlls :: Type -> Type
519 dropForAlls ty = snd (splitForAllTys ty)
522 -- (mkPiType now in CoreUtils)
526 Instantiate a for-all type with one or more type arguments.
527 Used when we have a polymorphic function applied to type args:
529 Then we use (applyTys type-of-f [t1,t2]) to compute the type of
533 applyTy :: Type -> Type -> Type
534 applyTy ty arg | Just ty' <- coreView ty = applyTy ty' arg
535 applyTy (ForAllTy tv ty) arg = substTyWith [tv] [arg] ty
536 applyTy other arg = panic "applyTy"
538 applyTys :: Type -> [Type] -> Type
539 -- This function is interesting because
540 -- a) the function may have more for-alls than there are args
541 -- b) less obviously, it may have fewer for-alls
542 -- For case (b) think of
543 -- applyTys (forall a.a) [forall b.b, Int]
544 -- This really can happen, via dressing up polymorphic types with newtype
545 -- clothing. Here's an example:
546 -- newtype R = R (forall a. a->a)
547 -- foo = case undefined :: R of
550 applyTys orig_fun_ty [] = orig_fun_ty
551 applyTys orig_fun_ty arg_tys
552 | n_tvs == n_args -- The vastly common case
553 = substTyWith tvs arg_tys rho_ty
554 | n_tvs > n_args -- Too many for-alls
555 = substTyWith (take n_args tvs) arg_tys
556 (mkForAllTys (drop n_args tvs) rho_ty)
557 | otherwise -- Too many type args
558 = ASSERT2( n_tvs > 0, ppr orig_fun_ty ) -- Zero case gives infnite loop!
559 applyTys (substTyWith tvs (take n_tvs arg_tys) rho_ty)
562 (tvs, rho_ty) = splitForAllTys orig_fun_ty
564 n_args = length arg_tys
568 %************************************************************************
570 \subsection{Source types}
572 %************************************************************************
574 A "source type" is a type that is a separate type as far as the type checker is
575 concerned, but which has low-level representation as far as the back end is concerned.
577 Source types are always lifted.
579 The key function is predTypeRep which gives the representation of a source type:
582 mkPredTy :: PredType -> Type
583 mkPredTy pred = PredTy pred
585 mkPredTys :: ThetaType -> [Type]
586 mkPredTys preds = map PredTy preds
588 predTypeRep :: PredType -> Type
589 -- Convert a PredType to its "representation type";
590 -- the post-type-checking type used by all the Core passes of GHC.
591 -- Unwraps only the outermost level; for example, the result might
592 -- be a newtype application
593 predTypeRep (IParam _ ty) = ty
594 predTypeRep (ClassP clas tys) = mkTyConApp (classTyCon clas) tys
595 -- Result might be a newtype application, but the consumer will
596 -- look through that too if necessary
600 %************************************************************************
604 %************************************************************************
607 splitRecNewType_maybe :: Type -> Maybe Type
608 -- Sometimes we want to look through a recursive newtype, and that's what happens here
609 -- It only strips *one layer* off, so the caller will usually call itself recursively
610 -- Only applied to types of kind *, hence the newtype is always saturated
611 splitRecNewType_maybe ty | Just ty' <- coreView ty = splitRecNewType_maybe ty'
612 splitRecNewType_maybe (TyConApp tc tys)
614 = ASSERT( tys `lengthIs` tyConArity tc ) -- splitRecNewType_maybe only be applied
615 -- to *types* (of kind *)
616 ASSERT( isRecursiveTyCon tc ) -- Guaranteed by coreView
617 case newTyConRhs tc of
618 (tvs, rep_ty) -> ASSERT( length tvs == length tys )
619 Just (substTyWith tvs tys rep_ty)
621 splitRecNewType_maybe other = Nothing
628 %************************************************************************
630 \subsection{Kinds and free variables}
632 %************************************************************************
634 ---------------------------------------------------------------------
635 Finding the kind of a type
636 ~~~~~~~~~~~~~~~~~~~~~~~~~~
638 typeKind :: Type -> Kind
639 typeKind (TyConApp tycon tys) = ASSERT( not (isCoercionTyCon tycon) )
640 -- We should be looking for the coercion kind,
642 foldr (\_ k -> kindFunResult k) (tyConKind tycon) tys
643 typeKind (NoteTy _ ty) = typeKind ty
644 typeKind (PredTy pred) = predKind pred
645 typeKind (AppTy fun arg) = kindFunResult (typeKind fun)
646 typeKind (ForAllTy tv ty) = typeKind ty
647 typeKind (TyVarTy tyvar) = tyVarKind tyvar
648 typeKind (FunTy arg res)
649 -- Hack alert. The kind of (Int -> Int#) is liftedTypeKind (*),
650 -- not unliftedTypKind (#)
651 -- The only things that can be after a function arrow are
652 -- (a) types (of kind openTypeKind or its sub-kinds)
653 -- (b) kinds (of super-kind TY) (e.g. * -> (* -> *))
654 | isTySuperKind k = k
655 | otherwise = ASSERT( isSubOpenTypeKind k) liftedTypeKind
659 predKind :: PredType -> Kind
660 predKind (EqPred {}) = coSuperKind -- A coercion kind!
661 predKind (ClassP {}) = liftedTypeKind -- Class and implicitPredicates are
662 predKind (IParam {}) = liftedTypeKind -- always represented by lifted types
666 ---------------------------------------------------------------------
667 Free variables of a type
668 ~~~~~~~~~~~~~~~~~~~~~~~~
670 tyVarsOfType :: Type -> TyVarSet
671 -- NB: for type synonyms tyVarsOfType does *not* expand the synonym
672 tyVarsOfType (TyVarTy tv) = unitVarSet tv
673 tyVarsOfType (TyConApp tycon tys) = tyVarsOfTypes tys
674 tyVarsOfType (NoteTy (FTVNote tvs) ty2) = tvs
675 tyVarsOfType (PredTy sty) = tyVarsOfPred sty
676 tyVarsOfType (FunTy arg res) = tyVarsOfType arg `unionVarSet` tyVarsOfType res
677 tyVarsOfType (AppTy fun arg) = tyVarsOfType fun `unionVarSet` tyVarsOfType arg
678 tyVarsOfType (ForAllTy tyvar ty) = delVarSet (tyVarsOfType ty) tyvar
680 tyVarsOfTypes :: [Type] -> TyVarSet
681 tyVarsOfTypes tys = foldr (unionVarSet.tyVarsOfType) emptyVarSet tys
683 tyVarsOfPred :: PredType -> TyVarSet
684 tyVarsOfPred (IParam _ ty) = tyVarsOfType ty
685 tyVarsOfPred (ClassP _ tys) = tyVarsOfTypes tys
687 tyVarsOfTheta :: ThetaType -> TyVarSet
688 tyVarsOfTheta = foldr (unionVarSet . tyVarsOfPred) emptyVarSet
690 -- Add a Note with the free tyvars to the top of the type
691 addFreeTyVars :: Type -> Type
692 addFreeTyVars ty@(NoteTy (FTVNote _) _) = ty
693 addFreeTyVars ty = NoteTy (FTVNote (tyVarsOfType ty)) ty
697 %************************************************************************
699 \subsection{TidyType}
701 %************************************************************************
703 tidyTy tidies up a type for printing in an error message, or in
706 It doesn't change the uniques at all, just the print names.
709 tidyTyVarBndr :: TidyEnv -> TyVar -> (TidyEnv, TyVar)
710 tidyTyVarBndr (tidy_env, subst) tyvar
711 = case tidyOccName tidy_env (getOccName name) of
712 (tidy', occ') -> ((tidy', subst'), tyvar')
714 subst' = extendVarEnv subst tyvar tyvar'
715 tyvar' = setTyVarName tyvar name'
716 name' = tidyNameOcc name occ'
718 name = tyVarName tyvar
720 tidyFreeTyVars :: TidyEnv -> TyVarSet -> TidyEnv
721 -- Add the free tyvars to the env in tidy form,
722 -- so that we can tidy the type they are free in
723 tidyFreeTyVars env tyvars = fst (tidyOpenTyVars env (varSetElems tyvars))
725 tidyOpenTyVars :: TidyEnv -> [TyVar] -> (TidyEnv, [TyVar])
726 tidyOpenTyVars env tyvars = mapAccumL tidyOpenTyVar env tyvars
728 tidyOpenTyVar :: TidyEnv -> TyVar -> (TidyEnv, TyVar)
729 -- Treat a new tyvar as a binder, and give it a fresh tidy name
730 tidyOpenTyVar env@(tidy_env, subst) tyvar
731 = case lookupVarEnv subst tyvar of
732 Just tyvar' -> (env, tyvar') -- Already substituted
733 Nothing -> tidyTyVarBndr env tyvar -- Treat it as a binder
735 tidyType :: TidyEnv -> Type -> Type
736 tidyType env@(tidy_env, subst) ty
739 go (TyVarTy tv) = case lookupVarEnv subst tv of
740 Nothing -> TyVarTy tv
741 Just tv' -> TyVarTy tv'
742 go (TyConApp tycon tys) = let args = map go tys
743 in args `seqList` TyConApp tycon args
744 go (NoteTy note ty) = (NoteTy $! (go_note note)) $! (go ty)
745 go (PredTy sty) = PredTy (tidyPred env sty)
746 go (AppTy fun arg) = (AppTy $! (go fun)) $! (go arg)
747 go (FunTy fun arg) = (FunTy $! (go fun)) $! (go arg)
748 go (ForAllTy tv ty) = ForAllTy tvp $! (tidyType envp ty)
750 (envp, tvp) = tidyTyVarBndr env tv
752 go_note note@(FTVNote ftvs) = note -- No need to tidy the free tyvars
754 tidyTypes env tys = map (tidyType env) tys
756 tidyPred :: TidyEnv -> PredType -> PredType
757 tidyPred env (IParam n ty) = IParam n (tidyType env ty)
758 tidyPred env (ClassP clas tys) = ClassP clas (tidyTypes env tys)
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
882 %************************************************************************
884 Equality for Core types
885 (We don't use instances so that we know where it happens)
887 %************************************************************************
889 Note that eqType works right even for partial applications of newtypes.
890 See Note [Newtype eta] in TyCon.lhs
893 coreEqType :: Type -> Type -> Bool
897 rn_env = mkRnEnv2 (mkInScopeSet (tyVarsOfType t1 `unionVarSet` tyVarsOfType t2))
899 eq env (TyVarTy tv1) (TyVarTy tv2) = rnOccL env tv1 == rnOccR env tv2
900 eq env (ForAllTy tv1 t1) (ForAllTy tv2 t2) = eq (rnBndr2 env tv1 tv2) t1 t2
901 eq env (AppTy s1 t1) (AppTy s2 t2) = eq env s1 s2 && eq env t1 t2
902 eq env (FunTy s1 t1) (FunTy s2 t2) = eq env s1 s2 && eq env t1 t2
903 eq env (TyConApp tc1 tys1) (TyConApp tc2 tys2)
904 | tc1 == tc2, all2 (eq env) tys1 tys2 = True
905 -- The lengths should be equal because
906 -- the two types have the same kind
907 -- NB: if the type constructors differ that does not
908 -- necessarily mean that the types aren't equal
909 -- (synonyms, newtypes)
910 -- Even if the type constructors are the same, but the arguments
911 -- differ, the two types could be the same (e.g. if the arg is just
912 -- ignored in the RHS). In both these cases we fall through to an
913 -- attempt to expand one side or the other.
915 -- Now deal with newtypes, synonyms, pred-tys
916 eq env t1 t2 | Just t1' <- coreView t1 = eq env t1' t2
917 | Just t2' <- coreView t2 = eq env t1 t2'
919 -- Fall through case; not equal!
924 %************************************************************************
926 Comparision for source types
927 (We don't use instances so that we know where it happens)
929 %************************************************************************
933 do *not* look through newtypes, PredTypes
936 tcEqType :: Type -> Type -> Bool
937 tcEqType t1 t2 = isEqual $ cmpType t1 t2
939 tcEqTypes :: [Type] -> [Type] -> Bool
940 tcEqTypes tys1 tys2 = isEqual $ cmpTypes tys1 tys2
942 tcCmpType :: Type -> Type -> Ordering
943 tcCmpType t1 t2 = cmpType t1 t2
945 tcCmpTypes :: [Type] -> [Type] -> Ordering
946 tcCmpTypes tys1 tys2 = cmpTypes tys1 tys2
948 tcEqPred :: PredType -> PredType -> Bool
949 tcEqPred p1 p2 = isEqual $ cmpPred p1 p2
951 tcCmpPred :: PredType -> PredType -> Ordering
952 tcCmpPred p1 p2 = cmpPred p1 p2
954 tcEqTypeX :: RnEnv2 -> Type -> Type -> Bool
955 tcEqTypeX env t1 t2 = isEqual $ cmpTypeX env t1 t2
958 Now here comes the real worker
961 cmpType :: Type -> Type -> Ordering
962 cmpType t1 t2 = cmpTypeX rn_env t1 t2
964 rn_env = mkRnEnv2 (mkInScopeSet (tyVarsOfType t1 `unionVarSet` tyVarsOfType t2))
966 cmpTypes :: [Type] -> [Type] -> Ordering
967 cmpTypes ts1 ts2 = cmpTypesX rn_env ts1 ts2
969 rn_env = mkRnEnv2 (mkInScopeSet (tyVarsOfTypes ts1 `unionVarSet` tyVarsOfTypes ts2))
971 cmpPred :: PredType -> PredType -> Ordering
972 cmpPred p1 p2 = cmpPredX rn_env p1 p2
974 rn_env = mkRnEnv2 (mkInScopeSet (tyVarsOfPred p1 `unionVarSet` tyVarsOfPred p2))
976 cmpTypeX :: RnEnv2 -> Type -> Type -> Ordering -- Main workhorse
977 cmpTypeX env t1 t2 | Just t1' <- tcView t1 = cmpTypeX env t1' t2
978 | Just t2' <- tcView t2 = cmpTypeX env t1 t2'
980 cmpTypeX env (TyVarTy tv1) (TyVarTy tv2) = rnOccL env tv1 `compare` rnOccR env tv2
981 cmpTypeX env (ForAllTy tv1 t1) (ForAllTy tv2 t2) = cmpTypeX (rnBndr2 env tv1 tv2) t1 t2
982 cmpTypeX env (AppTy s1 t1) (AppTy s2 t2) = cmpTypeX env s1 s2 `thenCmp` cmpTypeX env t1 t2
983 cmpTypeX env (FunTy s1 t1) (FunTy s2 t2) = cmpTypeX env s1 s2 `thenCmp` cmpTypeX env t1 t2
984 cmpTypeX env (PredTy p1) (PredTy p2) = cmpPredX env p1 p2
985 cmpTypeX env (TyConApp tc1 tys1) (TyConApp tc2 tys2) = (tc1 `compare` tc2) `thenCmp` cmpTypesX env tys1 tys2
986 cmpTypeX env t1 (NoteTy _ t2) = cmpTypeX env t1 t2
988 -- Deal with the rest: TyVarTy < AppTy < FunTy < TyConApp < ForAllTy < PredTy
989 cmpTypeX env (AppTy _ _) (TyVarTy _) = GT
991 cmpTypeX env (FunTy _ _) (TyVarTy _) = GT
992 cmpTypeX env (FunTy _ _) (AppTy _ _) = GT
994 cmpTypeX env (TyConApp _ _) (TyVarTy _) = GT
995 cmpTypeX env (TyConApp _ _) (AppTy _ _) = GT
996 cmpTypeX env (TyConApp _ _) (FunTy _ _) = GT
998 cmpTypeX env (ForAllTy _ _) (TyVarTy _) = GT
999 cmpTypeX env (ForAllTy _ _) (AppTy _ _) = GT
1000 cmpTypeX env (ForAllTy _ _) (FunTy _ _) = GT
1001 cmpTypeX env (ForAllTy _ _) (TyConApp _ _) = GT
1003 cmpTypeX env (PredTy _) t2 = GT
1005 cmpTypeX env _ _ = LT
1008 cmpTypesX :: RnEnv2 -> [Type] -> [Type] -> Ordering
1009 cmpTypesX env [] [] = EQ
1010 cmpTypesX env (t1:tys1) (t2:tys2) = cmpTypeX env t1 t2 `thenCmp` cmpTypesX env tys1 tys2
1011 cmpTypesX env [] tys = LT
1012 cmpTypesX env ty [] = GT
1015 cmpPredX :: RnEnv2 -> PredType -> PredType -> Ordering
1016 cmpPredX env (IParam n1 ty1) (IParam n2 ty2) = (n1 `compare` n2) `thenCmp` cmpTypeX env ty1 ty2
1017 -- Compare types as well as names for implicit parameters
1018 -- This comparison is used exclusively (I think) for the
1019 -- finite map built in TcSimplify
1020 cmpPredX env (ClassP c1 tys1) (ClassP c2 tys2) = (c1 `compare` c2) `thenCmp` cmpTypesX env tys1 tys2
1021 cmpPredX env (IParam _ _) (ClassP _ _) = LT
1022 cmpPredX env (ClassP _ _) (IParam _ _) = GT
1025 PredTypes are used as a FM key in TcSimplify,
1026 so we take the easy path and make them an instance of Ord
1029 instance Eq PredType where { (==) = tcEqPred }
1030 instance Ord PredType where { compare = tcCmpPred }
1034 %************************************************************************
1038 %************************************************************************
1042 = TvSubst InScopeSet -- The in-scope type variables
1043 TvSubstEnv -- The substitution itself
1044 -- See Note [Apply Once]
1046 {- ----------------------------------------------------------
1049 We use TvSubsts to instantiate things, and we might instantiate
1053 So the substition might go [a->b, b->a]. A similar situation arises in Core
1054 when we find a beta redex like
1055 (/\ a /\ b -> e) b a
1056 Then we also end up with a substition that permutes type variables. Other
1057 variations happen to; for example [a -> (a, b)].
1059 ***************************************************
1060 *** So a TvSubst must be applied precisely once ***
1061 ***************************************************
1063 A TvSubst is not idempotent, but, unlike the non-idempotent substitution
1064 we use during unifications, it must not be repeatedly applied.
1065 -------------------------------------------------------------- -}
1068 type TvSubstEnv = TyVarEnv Type
1069 -- A TvSubstEnv is used both inside a TvSubst (with the apply-once
1070 -- invariant discussed in Note [Apply Once]), and also independently
1071 -- in the middle of matching, and unification (see Types.Unify)
1072 -- So you have to look at the context to know if it's idempotent or
1073 -- apply-once or whatever
1074 emptyTvSubstEnv :: TvSubstEnv
1075 emptyTvSubstEnv = emptyVarEnv
1077 composeTvSubst :: InScopeSet -> TvSubstEnv -> TvSubstEnv -> TvSubstEnv
1078 -- (compose env1 env2)(x) is env1(env2(x)); i.e. apply env2 then env1
1079 -- It assumes that both are idempotent
1080 -- Typically, env1 is the refinement to a base substitution env2
1081 composeTvSubst in_scope env1 env2
1082 = env1 `plusVarEnv` mapVarEnv (substTy subst1) env2
1083 -- First apply env1 to the range of env2
1084 -- Then combine the two, making sure that env1 loses if
1085 -- both bind the same variable; that's why env1 is the
1086 -- *left* argument to plusVarEnv, because the right arg wins
1088 subst1 = TvSubst in_scope env1
1090 emptyTvSubst = TvSubst emptyInScopeSet emptyVarEnv
1092 isEmptyTvSubst :: TvSubst -> Bool
1093 isEmptyTvSubst (TvSubst _ env) = isEmptyVarEnv env
1095 mkTvSubst :: InScopeSet -> TvSubstEnv -> TvSubst
1098 getTvSubstEnv :: TvSubst -> TvSubstEnv
1099 getTvSubstEnv (TvSubst _ env) = env
1101 getTvInScope :: TvSubst -> InScopeSet
1102 getTvInScope (TvSubst in_scope _) = in_scope
1104 isInScope :: Var -> TvSubst -> Bool
1105 isInScope v (TvSubst in_scope _) = v `elemInScopeSet` in_scope
1107 notElemTvSubst :: TyVar -> TvSubst -> Bool
1108 notElemTvSubst tv (TvSubst _ env) = not (tv `elemVarEnv` env)
1110 setTvSubstEnv :: TvSubst -> TvSubstEnv -> TvSubst
1111 setTvSubstEnv (TvSubst in_scope _) env = TvSubst in_scope env
1113 extendTvInScope :: TvSubst -> [Var] -> TvSubst
1114 extendTvInScope (TvSubst in_scope env) vars = TvSubst (extendInScopeSetList in_scope vars) env
1116 extendTvSubst :: TvSubst -> TyVar -> Type -> TvSubst
1117 extendTvSubst (TvSubst in_scope env) tv ty = TvSubst in_scope (extendVarEnv env tv ty)
1119 extendTvSubstList :: TvSubst -> [TyVar] -> [Type] -> TvSubst
1120 extendTvSubstList (TvSubst in_scope env) tvs tys
1121 = TvSubst in_scope (extendVarEnvList env (tvs `zip` tys))
1123 -- mkOpenTvSubst and zipOpenTvSubst generate the in-scope set from
1124 -- the types given; but it's just a thunk so with a bit of luck
1125 -- it'll never be evaluated
1127 mkOpenTvSubst :: TvSubstEnv -> TvSubst
1128 mkOpenTvSubst env = TvSubst (mkInScopeSet (tyVarsOfTypes (varEnvElts env))) env
1130 zipOpenTvSubst :: [TyVar] -> [Type] -> TvSubst
1131 zipOpenTvSubst tyvars tys
1133 | length tyvars /= length tys
1134 = pprTrace "zipOpenTvSubst" (ppr tyvars $$ ppr tys) emptyTvSubst
1137 = TvSubst (mkInScopeSet (tyVarsOfTypes tys)) (zipTyEnv tyvars tys)
1139 -- mkTopTvSubst is called when doing top-level substitutions.
1140 -- Here we expect that the free vars of the range of the
1141 -- substitution will be empty.
1142 mkTopTvSubst :: [(TyVar, Type)] -> TvSubst
1143 mkTopTvSubst prs = TvSubst emptyInScopeSet (mkVarEnv prs)
1145 zipTopTvSubst :: [TyVar] -> [Type] -> TvSubst
1146 zipTopTvSubst tyvars tys
1148 | length tyvars /= length tys
1149 = pprTrace "zipOpenTvSubst" (ppr tyvars $$ ppr tys) emptyTvSubst
1152 = TvSubst emptyInScopeSet (zipTyEnv tyvars tys)
1154 zipTyEnv :: [TyVar] -> [Type] -> TvSubstEnv
1157 | length tyvars /= length tys
1158 = pprTrace "mkTopTvSubst" (ppr tyvars $$ ppr tys) emptyVarEnv
1161 = zip_ty_env tyvars tys emptyVarEnv
1163 -- Later substitutions in the list over-ride earlier ones,
1164 -- but there should be no loops
1165 zip_ty_env [] [] env = env
1166 zip_ty_env (tv:tvs) (ty:tys) env = zip_ty_env tvs tys (extendVarEnv env tv ty)
1167 -- There used to be a special case for when
1169 -- (a not-uncommon case) in which case the substitution was dropped.
1170 -- But the type-tidier changes the print-name of a type variable without
1171 -- changing the unique, and that led to a bug. Why? Pre-tidying, we had
1172 -- a type {Foo t}, where Foo is a one-method class. So Foo is really a newtype.
1173 -- And it happened that t was the type variable of the class. Post-tiding,
1174 -- it got turned into {Foo t2}. The ext-core printer expanded this using
1175 -- sourceTypeRep, but that said "Oh, t == t2" because they have the same unique,
1176 -- and so generated a rep type mentioning t not t2.
1178 -- Simplest fix is to nuke the "optimisation"
1179 zip_ty_env tvs tys env = pprTrace "Var/Type length mismatch: " (ppr tvs $$ ppr tys) env
1180 -- zip_ty_env _ _ env = env
1182 instance Outputable TvSubst where
1183 ppr (TvSubst ins env)
1184 = brackets $ sep[ ptext SLIT("TvSubst"),
1185 nest 2 (ptext SLIT("In scope:") <+> ppr ins),
1186 nest 2 (ptext SLIT("Env:") <+> ppr env) ]
1189 %************************************************************************
1191 Performing type substitutions
1193 %************************************************************************
1196 substTyWith :: [TyVar] -> [Type] -> Type -> Type
1197 substTyWith tvs tys = ASSERT( length tvs == length tys )
1198 substTy (zipOpenTvSubst tvs tys)
1200 substTy :: TvSubst -> Type -> Type
1201 substTy subst ty | isEmptyTvSubst subst = ty
1202 | otherwise = subst_ty subst ty
1204 substTys :: TvSubst -> [Type] -> [Type]
1205 substTys subst tys | isEmptyTvSubst subst = tys
1206 | otherwise = map (subst_ty subst) tys
1208 substTheta :: TvSubst -> ThetaType -> ThetaType
1209 substTheta subst theta
1210 | isEmptyTvSubst subst = theta
1211 | otherwise = map (substPred subst) theta
1213 substPred :: TvSubst -> PredType -> PredType
1214 substPred subst (IParam n ty) = IParam n (subst_ty subst ty)
1215 substPred subst (ClassP clas tys) = ClassP clas (map (subst_ty subst) tys)
1216 substPred subst (EqPred ty1 ty2) = EqPred (subst_ty subst ty1) (subst_ty subst ty2)
1218 deShadowTy :: TyVarSet -> Type -> Type -- Remove any nested binders mentioning tvs
1220 = subst_ty (mkTvSubst in_scope emptyTvSubstEnv) ty
1222 in_scope = mkInScopeSet tvs
1224 subst_ty :: TvSubst -> Type -> Type
1225 -- subst_ty is the main workhorse for type substitution
1227 -- Note that the in_scope set is poked only if we hit a forall
1228 -- so it may often never be fully computed
1232 go (TyVarTy tv) = substTyVar subst tv
1233 go (TyConApp tc tys) = let args = map go tys
1234 in args `seqList` TyConApp tc args
1236 go (PredTy p) = PredTy $! (substPred subst p)
1238 go (NoteTy (FTVNote _) ty2) = go ty2 -- Discard the free tyvar note
1240 go (FunTy arg res) = (FunTy $! (go arg)) $! (go res)
1241 go (AppTy fun arg) = mkAppTy (go fun) $! (go arg)
1242 -- The mkAppTy smart constructor is important
1243 -- we might be replacing (a Int), represented with App
1244 -- by [Int], represented with TyConApp
1245 go (ForAllTy tv ty) = case substTyVarBndr subst tv of
1246 (subst', tv') -> ForAllTy tv' $! (subst_ty subst' ty)
1248 substTyVar :: TvSubst -> TyVar -> Type
1249 substTyVar subst@(TvSubst in_scope env) tv
1250 = case lookupTyVar subst tv of {
1251 Nothing -> TyVarTy tv;
1252 Just ty -> ty -- See Note [Apply Once]
1255 lookupTyVar :: TvSubst -> TyVar -> Maybe Type
1256 lookupTyVar (TvSubst in_scope env) tv = lookupVarEnv env tv
1258 substTyVarBndr :: TvSubst -> TyVar -> (TvSubst, TyVar)
1259 substTyVarBndr subst@(TvSubst in_scope env) old_var
1260 = (TvSubst (in_scope `extendInScopeSet` new_var) new_env, new_var)
1263 new_env | no_change = delVarEnv env old_var
1264 | otherwise = extendVarEnv env old_var (TyVarTy new_var)
1266 no_change = new_var == old_var && not is_co_var
1267 -- no_change means that the new_var is identical in
1268 -- all respects to the old_var (same unique, same kind)
1270 -- In that case we don't need to extend the substitution
1271 -- to map old to new. But instead we must zap any
1272 -- current substitution for the variable. For example:
1273 -- (\x.e) with id_subst = [x |-> e']
1274 -- Here we must simply zap the substitution for x
1276 new_var = uniqAway in_scope subst_old_var
1277 -- The uniqAway part makes sure the new variable is not already in scope
1279 subst_old_var -- subst_old_var is old_var with the substitution applied to its kind
1280 -- It's only worth doing the substitution for coercions,
1281 -- becuase only they can have free type variables
1282 | is_co_var = setTyVarKind old_var (substTy subst kind)
1283 | otherwise = old_var
1284 kind = tyVarKind old_var
1285 is_co_var = isCoercionKind kind
1288 ----------------------------------------------------
1293 There's a little subtyping at the kind level:
1302 where * [LiftedTypeKind] means boxed type
1303 # [UnliftedTypeKind] means unboxed type
1304 (#) [UbxTupleKind] means unboxed tuple
1305 ?? [ArgTypeKind] is the lub of *,#
1306 ? [OpenTypeKind] means any type at all
1310 error :: forall a:?. String -> a
1311 (->) :: ?? -> ? -> *
1312 (\(x::t) -> ...) Here t::?? (i.e. not unboxed tuple)
1315 type KindVar = TyVar -- invariant: KindVar will always be a
1316 -- TcTyVar with details MetaTv TauTv ...
1317 -- kind var constructors and functions are in TcType
1319 type SimpleKind = Kind
1324 During kind inference, a kind variable unifies only with
1326 sk ::= * | sk1 -> sk2
1328 data T a = MkT a (T Int#)
1329 fails. We give T the kind (k -> *), and the kind variable k won't unify
1330 with # (the kind of Int#).
1334 When creating a fresh internal type variable, we give it a kind to express
1335 constraints on it. E.g. in (\x->e) we make up a fresh type variable for x,
1338 During unification we only bind an internal type variable to a type
1339 whose kind is lower in the sub-kind hierarchy than the kind of the tyvar.
1341 When unifying two internal type variables, we collect their kind constraints by
1342 finding the GLB of the two. Since the partial order is a tree, they only
1343 have a glb if one is a sub-kind of the other. In that case, we bind the
1344 less-informative one to the more informative one. Neat, eh?
1351 %************************************************************************
1353 Functions over Kinds
1355 %************************************************************************
1358 kindFunResult :: Kind -> Kind
1359 kindFunResult k = funResultTy k
1361 splitKindFunTys :: Kind -> ([Kind],Kind)
1362 splitKindFunTys k = splitFunTys k
1364 isUbxTupleKind, isOpenTypeKind, isArgTypeKind, isUnliftedTypeKind :: Kind -> Bool
1366 isOpenTypeKindCon tc = tyConUnique tc == openTypeKindTyConKey
1368 isOpenTypeKind (TyConApp tc _) = isOpenTypeKindCon tc
1369 isOpenTypeKind other = False
1371 isUbxTupleKindCon tc = tyConUnique tc == ubxTupleKindTyConKey
1373 isUbxTupleKind (TyConApp tc _) = isUbxTupleKindCon tc
1374 isUbxTupleKind other = False
1376 isArgTypeKindCon tc = tyConUnique tc == argTypeKindTyConKey
1378 isArgTypeKind (TyConApp tc _) = isArgTypeKindCon tc
1379 isArgTypeKind other = False
1381 isUnliftedTypeKindCon tc = tyConUnique tc == unliftedTypeKindTyConKey
1383 isUnliftedTypeKind (TyConApp tc _) = isUnliftedTypeKindCon tc
1384 isUnliftedTypeKind other = False
1386 isSubOpenTypeKind :: Kind -> Bool
1387 -- True of any sub-kind of OpenTypeKind (i.e. anything except arrow)
1388 isSubOpenTypeKind (FunTy k1 k2) = ASSERT2 ( isKind k1, text "isSubOpenTypeKind" <+> ppr k1 <+> text "::" <+> ppr (typeKind k1) )
1389 ASSERT2 ( isKind k2, text "isSubOpenTypeKind" <+> ppr k2 <+> text "::" <+> ppr (typeKind k2) )
1391 isSubOpenTypeKind (TyConApp kc []) = ASSERT( isKind (TyConApp kc []) ) True
1392 isSubOpenTypeKind other = ASSERT( isKind other ) False
1393 -- This is a conservative answer
1394 -- It matters in the call to isSubKind in
1395 -- checkExpectedKind.
1397 isSubArgTypeKindCon kc
1398 | isUnliftedTypeKindCon kc = True
1399 | isLiftedTypeKindCon kc = True
1400 | isArgTypeKindCon kc = True
1403 isSubArgTypeKind :: Kind -> Bool
1404 -- True of any sub-kind of ArgTypeKind
1405 isSubArgTypeKind (TyConApp kc []) = isSubArgTypeKindCon kc
1406 isSubArgTypeKind other = False
1408 isSuperKind :: Type -> Bool
1409 isSuperKind (TyConApp (skc) []) = isSuperKindTyCon skc
1410 isSuperKind other = False
1412 isKind :: Kind -> Bool
1413 isKind k = isSuperKind (typeKind k)
1417 isSubKind :: Kind -> Kind -> Bool
1418 -- (k1 `isSubKind` k2) checks that k1 <: k2
1419 isSubKind (TyConApp kc1 []) (TyConApp kc2 []) = kc1 `isSubKindCon` kc1
1420 isSubKind (FunTy a1 r1) (FunTy a2 r2) = (a2 `isSubKind` a1) && (r1 `isSubKind` r2)
1421 isSubKind k1 k2 = False
1423 eqKind :: Kind -> Kind -> Bool
1426 isSubKindCon :: TyCon -> TyCon -> Bool
1427 -- (kc1 `isSubKindCon` kc2) checks that kc1 <: kc2
1428 isSubKindCon kc1 kc2
1429 | isLiftedTypeKindCon kc1 && isLiftedTypeKindCon kc2 = True
1430 | isUnliftedTypeKindCon kc1 && isUnliftedTypeKindCon kc2 = True
1431 | isUbxTupleKindCon kc1 && isUbxTupleKindCon kc2 = True
1432 | isOpenTypeKindCon kc2 = True
1433 -- we already know kc1 is not a fun, its a TyCon
1434 | isArgTypeKindCon kc2 && isSubArgTypeKindCon kc1 = True
1437 defaultKind :: Kind -> Kind
1438 -- Used when generalising: default kind '?' and '??' to '*'
1440 -- When we generalise, we make generic type variables whose kind is
1441 -- simple (* or *->* etc). So generic type variables (other than
1442 -- built-in constants like 'error') always have simple kinds. This is important;
1445 -- We want f to get type
1446 -- f :: forall (a::*). a -> Bool
1448 -- f :: forall (a::??). a -> Bool
1449 -- because that would allow a call like (f 3#) as well as (f True),
1450 --and the calling conventions differ. This defaulting is done in TcMType.zonkTcTyVarBndr.
1452 | isSubOpenTypeKind k = liftedTypeKind
1453 | isSubArgTypeKind k = liftedTypeKind
1456 isCoercionKind :: Kind -> Bool
1457 -- All coercions are of form (ty1 :=: ty2)
1458 -- This function is here rather than in Coercion,
1459 -- because it's used by substTy
1460 isCoercionKind k | Just k' <- kindView k = isCoercionKind k'
1461 isCoercionKind (PredTy (EqPred {})) = True
1462 isCoercionKind other = False