2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section{Type subsumption and unification}
8 -- Full-blown subsumption
9 tcSubExp, tcFunResTy, tcGen,
10 checkSigTyVars, checkSigTyVarsWrt, bleatEscapedTvs, sigCtxt,
12 -- Various unifications
13 unifyType, unifyTypeList, unifyTheta,
14 unifyKind, unifyKinds, unifyFunKind,
16 preSubType, boxyMatchTypes,
18 --------------------------------
20 tcInfer, subFunTys, unBox, stripBoxyType, withBox,
21 boxyUnify, boxyUnifyList, zapToMonotype,
22 boxySplitListTy, boxySplitTyConApp, boxySplitAppTy,
26 #include "HsVersions.h"
28 import HsSyn ( ExprCoFn(..), idCoercion, isIdCoercion, (<.>) )
29 import TypeRep ( Type(..), PredType(..) )
31 import TcMType ( lookupTcTyVar, LookupTyVarResult(..),
32 tcInstSkolType, tcInstBoxyTyVar, newKindVar, newMetaTyVar,
33 newBoxyTyVar, newBoxyTyVarTys, readFilledBox,
34 readMetaTyVar, writeMetaTyVar, newFlexiTyVarTy,
35 tcInstSkolTyVars, tcInstTyVar,
36 zonkTcKind, zonkType, zonkTcType, zonkTcTyVarsAndFV,
37 readKindVar, writeKindVar )
38 import TcSimplify ( tcSimplifyCheck )
39 import TcEnv ( tcGetGlobalTyVars, findGlobals )
40 import TcIface ( checkWiredInTyCon )
41 import TcRnMonad -- TcType, amongst others
42 import TcType ( TcKind, TcType, TcTyVar, BoxyTyVar, TcTauType,
43 BoxySigmaType, BoxyRhoType, BoxyType,
44 TcTyVarSet, TcThetaType, TcTyVarDetails(..), BoxInfo(..),
45 SkolemInfo( GenSkol, UnkSkol ), MetaDetails(..), isImmutableTyVar,
46 pprSkolTvBinding, isTauTy, isTauTyCon, isSigmaTy,
47 mkFunTy, mkFunTys, mkTyConApp, isMetaTyVar,
48 tcSplitForAllTys, tcSplitAppTy_maybe, tcSplitFunTys, mkTyVarTys,
49 tcSplitSigmaTy, tyVarsOfType, mkPhiTy, mkTyVarTy, mkPredTy,
50 typeKind, mkForAllTys, mkAppTy, isBoxyTyVar,
52 tidyOpenType, tidyOpenTyVar, tidyOpenTyVars,
53 pprType, tidyKind, tidySkolemTyVar, isSkolemTyVar, tcView,
54 TvSubst, mkTvSubst, zipTyEnv, zipOpenTvSubst, emptyTvSubst,
56 lookupTyVar, extendTvSubst )
57 import Kind ( Kind(..), SimpleKind, KindVar, isArgTypeKind,
58 openTypeKind, liftedTypeKind, unliftedTypeKind,
59 mkArrowKind, defaultKind,
60 isOpenTypeKind, argTypeKind, isLiftedTypeKind, isUnliftedTypeKind,
61 isSubKind, pprKind, splitKindFunTys )
62 import TysPrim ( alphaTy, betaTy )
63 import Inst ( newDicts, instToId )
64 import TyCon ( TyCon, tyConArity, tyConTyVars, isSynTyCon )
65 import TysWiredIn ( listTyCon )
66 import Id ( Id, mkSysLocal )
67 import Var ( Var, varName, tyVarKind, isTcTyVar, tcTyVarDetails )
70 import Name ( Name, isSystemName )
71 import ErrUtils ( Message )
72 import Maybes ( expectJust, isNothing )
73 import BasicTypes ( Arity )
74 import UniqSupply ( uniqsFromSupply )
75 import Util ( notNull, equalLength )
80 import TcType ( isBoxyTy, isFlexi )
84 %************************************************************************
86 \subsection{'hole' type variables}
88 %************************************************************************
91 tcInfer :: (BoxyType -> TcM a) -> TcM (a, TcType)
93 = do { box <- newBoxyTyVar openTypeKind
94 ; res <- tc_infer (mkTyVarTy box)
95 ; res_ty <- readFilledBox box -- Guaranteed filled-in by now
96 ; return (res, res_ty) }
100 %************************************************************************
104 %************************************************************************
107 subFunTys :: SDoc -- Somthing like "The function f has 3 arguments"
108 -- or "The abstraction (\x.e) takes 1 argument"
109 -> Arity -- Expected # of args
110 -> BoxyRhoType -- res_ty
111 -> ([BoxySigmaType] -> BoxyRhoType -> TcM a)
113 -- Attempt to decompse res_ty to have enough top-level arrows to
114 -- match the number of patterns in the match group
116 -- If (subFunTys n_args res_ty thing_inside) = (co_fn, res)
117 -- and the inner call to thing_inside passes args: [a1,...,an], b
118 -- then co_fn :: (a1 -> ... -> an -> b) -> res_ty
120 -- Note that it takes a BoxyRho type, and guarantees to return a BoxyRhoType
123 {- Error messages from subFunTys
125 The abstraction `\Just 1 -> ...' has two arguments
126 but its type `Maybe a -> a' has only one
128 The equation(s) for `f' have two arguments
129 but its type `Maybe a -> a' has only one
131 The section `(f 3)' requires 'f' to take two arguments
132 but its type `Int -> Int' has only one
134 The function 'f' is applied to two arguments
135 but its type `Int -> Int' has only one
139 subFunTys error_herald n_pats res_ty thing_inside
140 = loop n_pats [] res_ty
142 -- In 'loop', the parameter 'arg_tys' accumulates
143 -- the arg types so far, in *reverse order*
144 loop n args_so_far res_ty
145 | Just res_ty' <- tcView res_ty = loop n args_so_far res_ty'
147 loop n args_so_far res_ty
148 | isSigmaTy res_ty -- Do this before checking n==0, because we
149 -- guarantee to return a BoxyRhoType, not a BoxySigmaType
150 = do { (gen_fn, (co_fn, res)) <- tcGen res_ty emptyVarSet $ \ res_ty' ->
151 loop n args_so_far res_ty'
152 ; return (gen_fn <.> co_fn, res) }
154 loop 0 args_so_far res_ty
155 = do { res <- thing_inside (reverse args_so_far) res_ty
156 ; return (idCoercion, res) }
158 loop n args_so_far (FunTy arg_ty res_ty)
159 = do { (co_fn, res) <- loop (n-1) (arg_ty:args_so_far) res_ty
160 ; co_fn' <- wrapFunResCoercion [arg_ty] co_fn
161 ; return (co_fn', res) }
163 -- res_ty might have a type variable at the head, such as (a b c),
164 -- in which case we must fill in with (->). Simplest thing to do
165 -- is to use boxyUnify, but we catch failure and generate our own
166 -- error message on failure
167 loop n args_so_far res_ty@(AppTy _ _)
168 = do { [arg_ty',res_ty'] <- newBoxyTyVarTys [argTypeKind, openTypeKind]
169 ; (_, mb_unit) <- tryTcErrs $ boxyUnify res_ty (FunTy arg_ty' res_ty')
170 ; if isNothing mb_unit then bale_out args_so_far
171 else loop n args_so_far (FunTy arg_ty' res_ty') }
173 loop n args_so_far (TyVarTy tv)
174 | not (isImmutableTyVar tv)
175 = do { cts <- readMetaTyVar tv
177 Indirect ty -> loop n args_so_far ty
178 Flexi -> do { (res_ty:arg_tys) <- withMetaTvs tv kinds mk_res_ty
179 ; res <- thing_inside (reverse args_so_far ++ arg_tys) res_ty
180 ; return (idCoercion, res) } }
182 mk_res_ty (res_ty' : arg_tys') = mkFunTys arg_tys' res_ty'
183 kinds = openTypeKind : take n (repeat argTypeKind)
184 -- Note argTypeKind: the args can have an unboxed type,
185 -- but not an unboxed tuple.
187 loop n args_so_far res_ty = bale_out args_so_far
190 = do { env0 <- tcInitTidyEnv
191 ; res_ty' <- zonkTcType res_ty
192 ; let (env1, res_ty'') = tidyOpenType env0 res_ty'
193 ; failWithTcM (env1, mk_msg res_ty'' (length args_so_far)) }
195 mk_msg res_ty n_actual
196 = error_herald <> comma $$
197 sep [ptext SLIT("but its type") <+> quotes (pprType res_ty),
198 if n_actual == 0 then ptext SLIT("has none")
199 else ptext SLIT("has only") <+> speakN n_actual]
203 ----------------------
204 boxySplitTyConApp :: TyCon -- T :: k1 -> ... -> kn -> *
205 -> BoxyRhoType -- Expected type (T a b c)
206 -> TcM [BoxySigmaType] -- Element types, a b c
207 -- It's used for wired-in tycons, so we call checkWiredInTyCOn
208 -- Precondition: never called with FunTyCon
209 -- Precondition: input type :: *
211 boxySplitTyConApp tc orig_ty
212 = do { checkWiredInTyCon tc
213 ; loop (tyConArity tc) [] orig_ty }
215 loop n_req args_so_far ty
216 | Just ty' <- tcView ty = loop n_req args_so_far ty'
218 loop n_req args_so_far (TyConApp tycon args)
220 = ASSERT( n_req == length args) -- ty::*
221 return (args ++ args_so_far)
223 loop n_req args_so_far (AppTy fun arg)
224 = loop (n_req - 1) (arg:args_so_far) fun
226 loop n_req args_so_far (TyVarTy tv)
227 | not (isImmutableTyVar tv)
228 = do { cts <- readMetaTyVar tv
230 Indirect ty -> loop n_req args_so_far ty
231 Flexi -> do { arg_tys <- withMetaTvs tv arg_kinds mk_res_ty
232 ; return (arg_tys ++ args_so_far) }
235 mk_res_ty arg_tys' = mkTyConApp tc arg_tys'
236 arg_kinds = map tyVarKind (take n_req (tyConTyVars tc))
238 loop _ _ _ = boxySplitFailure (mkTyConApp tc (mkTyVarTys (tyConTyVars tc))) orig_ty
240 ----------------------
241 boxySplitListTy :: BoxyRhoType -> TcM BoxySigmaType -- Special case for lists
242 boxySplitListTy exp_ty = do { [elt_ty] <- boxySplitTyConApp listTyCon exp_ty
246 ----------------------
247 boxySplitAppTy :: BoxyRhoType -- Type to split: m a
248 -> TcM (BoxySigmaType, BoxySigmaType) -- Returns m, a
249 -- Assumes (m: * -> k), where k is the kind of the incoming type
250 -- If the incoming type is boxy, then so are the result types; and vice versa
252 boxySplitAppTy orig_ty
256 | Just ty' <- tcView ty = loop ty'
259 | Just (fun_ty, arg_ty) <- tcSplitAppTy_maybe ty
260 = return (fun_ty, arg_ty)
263 | not (isImmutableTyVar tv)
264 = do { cts <- readMetaTyVar tv
266 Indirect ty -> loop ty
267 Flexi -> do { [fun_ty,arg_ty] <- withMetaTvs tv kinds mk_res_ty
268 ; return (fun_ty, arg_ty) } }
270 mk_res_ty [fun_ty', arg_ty'] = mkAppTy fun_ty' arg_ty'
271 tv_kind = tyVarKind tv
272 kinds = [mkArrowKind liftedTypeKind (defaultKind tv_kind),
274 liftedTypeKind] -- arg type :: *
275 -- The defaultKind is a bit smelly. If you remove it,
276 -- try compiling f x = do { x }
277 -- and you'll get a kind mis-match. It smells, but
278 -- not enough to lose sleep over.
280 loop _ = boxySplitFailure (mkAppTy alphaTy betaTy) orig_ty
283 boxySplitFailure actual_ty expected_ty
284 = unifyMisMatch False False actual_ty expected_ty
285 -- "outer" is False, so we don't pop the context
286 -- which is what we want since we have not pushed one!
290 --------------------------------
291 -- withBoxes: the key utility function
292 --------------------------------
295 withMetaTvs :: TcTyVar -- An unfilled-in, non-skolem, meta type variable
296 -> [Kind] -- Make fresh boxes (with the same BoxTv/TauTv setting as tv)
297 -> ([BoxySigmaType] -> BoxySigmaType)
298 -- Constructs the type to assign
299 -- to the original var
300 -> TcM [BoxySigmaType] -- Return the fresh boxes
302 -- It's entirely possible for the [kind] to be empty.
303 -- For example, when pattern-matching on True,
304 -- we call boxySplitTyConApp passing a boolTyCon
306 -- Invariant: tv is still Flexi
308 withMetaTvs tv kinds mk_res_ty
310 = do { box_tvs <- mapM (newMetaTyVar BoxTv) kinds
311 ; let box_tys = mkTyVarTys box_tvs
312 ; writeMetaTyVar tv (mk_res_ty box_tys)
315 | otherwise -- Non-boxy meta type variable
316 = do { tau_tys <- mapM newFlexiTyVarTy kinds
317 ; writeMetaTyVar tv (mk_res_ty tau_tys) -- Write it *first*
318 -- Sure to be a tau-type
321 withBox :: Kind -> (BoxySigmaType -> TcM a) -> TcM (a, TcType)
322 -- Allocate a *boxy* tyvar
323 withBox kind thing_inside
324 = do { box_tv <- newMetaTyVar BoxTv kind
325 ; res <- thing_inside (mkTyVarTy box_tv)
326 ; ty <- readFilledBox box_tv
331 %************************************************************************
333 Approximate boxy matching
335 %************************************************************************
338 preSubType :: [TcTyVar] -- Quantified type variables
339 -> TcTyVarSet -- Subset of quantified type variables
340 -- that can be instantiated with boxy types
341 -> TcType -- The rho-type part; quantified tyvars scopes over this
342 -> BoxySigmaType -- Matching type from the context
343 -> TcM [TcType] -- Types to instantiate the tyvars
344 -- Perform pre-subsumption, and return suitable types
345 -- to instantiate the quantified type varibles:
346 -- info from the pre-subsumption, if there is any
347 -- a boxy type variable otherwise
349 -- The 'btvs' are a subset of 'qtvs'. They are the ones we can
350 -- instantiate to a boxy type variable, because they'll definitely be
351 -- filled in later. This isn't always the case; sometimes we have type
352 -- variables mentioned in the context of the type, but not the body;
353 -- f :: forall a b. C a b => a -> a
354 -- Then we may land up with an unconstrained 'b', so we want to
355 -- instantiate it to a monotype (non-boxy) type variable
357 preSubType qtvs btvs qty expected_ty
358 = do { tys <- mapM inst_tv qtvs
359 ; traceTc (text "preSubType" <+> (ppr qtvs $$ ppr btvs $$ ppr qty $$ ppr expected_ty $$ ppr pre_subst $$ ppr tys))
362 pre_subst = boxySubMatchType (mkVarSet qtvs) qty expected_ty
364 | Just boxy_ty <- lookupTyVar pre_subst tv = return boxy_ty
365 | tv `elemVarSet` btvs = do { tv' <- tcInstBoxyTyVar tv
366 ; return (mkTyVarTy tv') }
367 | otherwise = do { tv' <- tcInstTyVar tv
368 ; return (mkTyVarTy tv') }
371 :: TcTyVarSet -> TcType -- The "template"; the tyvars are skolems
372 -> BoxyRhoType -- Type to match (note a *Rho* type)
373 -> TvSubst -- Substitution of the [TcTyVar] to BoxySigmaTypes
375 -- boxySubMatchType implements the Pre-subsumption judgement, in Fig 5 of the paper
376 -- "Boxy types: inference for higher rank types and impredicativity"
378 boxySubMatchType tmpl_tvs tmpl_ty boxy_ty
379 = go tmpl_tvs tmpl_ty emptyVarSet boxy_ty
381 go t_tvs t_ty b_tvs b_ty
382 | Just t_ty' <- tcView t_ty = go t_tvs t_ty' b_tvs b_ty
383 | Just b_ty' <- tcView b_ty = go t_tvs t_ty b_tvs b_ty'
385 go t_tvs (TyVarTy _) b_tvs b_ty = emptyTvSubst -- Rule S-ANY; no bindings
386 -- Rule S-ANY covers (a) type variables and (b) boxy types
387 -- in the template. Both look like a TyVarTy.
388 -- See Note [Sub-match] below
390 go t_tvs t_ty b_tvs b_ty
391 | isSigmaTy t_ty, (tvs, _, t_tau) <- tcSplitSigmaTy t_ty
392 = go (t_tvs `delVarSetList` tvs) t_tau b_tvs b_ty -- Rule S-SPEC
393 -- Under a forall on the left, if there is shadowing,
394 -- do not bind! Hence the delVarSetList.
395 | isSigmaTy b_ty, (tvs, _, b_tau) <- tcSplitSigmaTy b_ty
396 = go t_tvs t_ty (extendVarSetList b_tvs tvs) b_tau -- Rule S-SKOL
397 -- Add to the variables we must not bind to
398 -- NB: it's *important* to discard the theta part. Otherwise
399 -- consider (forall a. Eq a => a -> b) ~<~ (Int -> Int -> Bool)
400 -- and end up with a completely bogus binding (b |-> Bool), by lining
401 -- up the (Eq a) with the Int, whereas it should be (b |-> (Int->Bool)).
402 -- This pre-subsumption stuff can return too few bindings, but it
403 -- must *never* return bogus info.
405 go t_tvs (FunTy arg1 res1) b_tvs (FunTy arg2 res2) -- Rule S-FUN
406 = boxy_match t_tvs arg1 b_tvs arg2 (go t_tvs res1 b_tvs res2)
407 -- Match the args, and sub-match the results
409 go t_tvs t_ty b_tvs b_ty = boxy_match t_tvs t_ty b_tvs b_ty emptyTvSubst
410 -- Otherwise defer to boxy matching
411 -- This covers TyConApp, AppTy, PredTy
418 |- head xs : <rhobox>
419 We will do a boxySubMatchType between a ~ <rhobox>
420 But we *don't* want to match [a |-> <rhobox>] because
421 (a) The box should be filled in with a rho-type, but
422 but the returned substitution maps TyVars to boxy
424 (b) In any case, the right final answer might be *either*
425 instantiate 'a' with a rho-type or a sigma type
426 head xs : Int vs head xs : forall b. b->b
427 So the matcher MUST NOT make a choice here. In general, we only
428 bind a template type variable in boxyMatchType, not in boxySubMatchType.
433 :: TcTyVarSet -> [TcType] -- The "template"; the tyvars are skolems
434 -> [BoxySigmaType] -- Type to match
435 -> TvSubst -- Substitution of the [TcTyVar] to BoxySigmaTypes
437 -- boxyMatchTypes implements the Pre-matching judgement, in Fig 5 of the paper
438 -- "Boxy types: inference for higher rank types and impredicativity"
440 -- Find a *boxy* substitution that makes the template look as much
441 -- like the BoxySigmaType as possible.
442 -- It's always ok to return an empty substitution;
443 -- anything more is jam on the pudding
445 -- NB1: This is a pure, non-monadic function.
446 -- It does no unification, and cannot fail
448 -- Precondition: the arg lengths are equal
449 -- Precondition: none of the template type variables appear anywhere in the [BoxySigmaType]
453 boxyMatchTypes tmpl_tvs tmpl_tys boxy_tys
454 = ASSERT( length tmpl_tys == length boxy_tys )
455 boxy_match_s tmpl_tvs tmpl_tys emptyVarSet boxy_tys emptyTvSubst
456 -- ToDo: add error context?
458 boxy_match_s tmpl_tvs [] boxy_tvs [] subst
460 boxy_match_s tmpl_tvs (t_ty:t_tys) boxy_tvs (b_ty:b_tys) subst
461 = boxy_match tmpl_tvs t_ty boxy_tvs b_ty $
462 boxy_match_s tmpl_tvs t_tys boxy_tvs b_tys subst
466 boxy_match :: TcTyVarSet -> TcType -- Template
467 -> TcTyVarSet -- boxy_tvs: do not bind template tyvars to any of these
468 -> BoxySigmaType -- Match against this type
472 -- The boxy_tvs argument prevents this match:
473 -- [a] forall b. a ~ forall b. b
474 -- We don't want to bind the template variable 'a'
475 -- to the quantified type variable 'b'!
477 boxy_match tmpl_tvs orig_tmpl_ty boxy_tvs orig_boxy_ty subst
478 = go orig_tmpl_ty orig_boxy_ty
481 | Just t_ty' <- tcView t_ty = go t_ty' b_ty
482 | Just b_ty' <- tcView b_ty = go t_ty b_ty'
484 go ty1 ty2 -- C.f. the isSigmaTy case for boxySubMatchType
486 , (tvs1, _, tau1) <- tcSplitSigmaTy ty1
487 , (tvs2, _, tau2) <- tcSplitSigmaTy ty2
488 , equalLength tvs1 tvs2
489 = boxy_match (tmpl_tvs `delVarSetList` tvs1) tau1
490 (boxy_tvs `extendVarSetList` tvs2) tau2 subst
492 go (TyConApp tc1 tys1) (TyConApp tc2 tys2)
493 | tc1 == tc2 = go_s tys1 tys2
495 go (FunTy arg1 res1) (FunTy arg2 res2)
496 = go_s [arg1,res1] [arg2,res2]
499 | Just (s1,t1) <- tcSplitAppTy_maybe t_ty,
500 Just (s2,t2) <- tcSplitAppTy_maybe b_ty,
501 typeKind t2 `isSubKind` typeKind t1 -- Maintain invariant
502 = go_s [s1,t1] [s2,t2]
505 | tv `elemVarSet` tmpl_tvs -- Template type variable in the template
506 , not (intersectsVarSet boxy_tvs (tyVarsOfType orig_boxy_ty))
507 , typeKind b_ty `isSubKind` tyVarKind tv -- See Note [Matching kinds]
508 = extendTvSubst subst tv boxy_ty'
510 = subst -- Ignore others
512 boxy_ty' = case lookupTyVar subst tv of
513 Nothing -> orig_boxy_ty
514 Just ty -> ty `boxyLub` orig_boxy_ty
516 go _ _ = emptyTvSubst -- It's important to *fail* by returning the empty substitution
517 -- Example: Tree a ~ Maybe Int
518 -- We do not want to bind (a |-> Int) in pre-matching, because that can give very
519 -- misleading error messages. An even more confusing case is
520 -- a -> b ~ Maybe Int
521 -- Then we do not want to bind (b |-> Int)! It's always safe to discard bindings
522 -- from this pre-matching phase.
525 go_s tys1 tys2 = boxy_match_s tmpl_tvs tys1 boxy_tvs tys2 subst
528 boxyLub :: BoxySigmaType -> BoxySigmaType -> BoxySigmaType
529 -- Combine boxy information from the two types
530 -- If there is a conflict, return the first
531 boxyLub orig_ty1 orig_ty2
532 = go orig_ty1 orig_ty2
534 go (AppTy f1 a1) (AppTy f2 a2) = AppTy (boxyLub f1 f2) (boxyLub a1 a2)
535 go (FunTy f1 a1) (FunTy f2 a2) = FunTy (boxyLub f1 f2) (boxyLub a1 a2)
536 go (TyConApp tc1 ts1) (TyConApp tc2 ts2)
537 | tc1 == tc2, length ts1 == length ts2
538 = TyConApp tc1 (zipWith boxyLub ts1 ts2)
540 go (TyVarTy tv1) ty2 -- This is the whole point;
541 | isTcTyVar tv1, isBoxyTyVar tv1 -- choose ty2 if ty2 is a box
544 -- Look inside type synonyms, but only if the naive version fails
545 go ty1 ty2 | Just ty1' <- tcView ty1 = go ty1' ty2
546 | Just ty2' <- tcView ty1 = go ty1 ty2'
548 -- For now, we don't look inside ForAlls, PredTys
549 go ty1 ty2 = orig_ty1 -- Default
552 Note [Matching kinds]
553 ~~~~~~~~~~~~~~~~~~~~~
554 The target type might legitimately not be a sub-kind of template.
555 For example, suppose the target is simply a box with an OpenTypeKind,
556 and the template is a type variable with LiftedTypeKind.
557 Then it's ok (because the target type will later be refined).
558 We simply don't bind the template type variable.
560 It might also be that the kind mis-match is an error. For example,
561 suppose we match the template (a -> Int) against (Int# -> Int),
562 where the template type variable 'a' has LiftedTypeKind. This
563 matching function does not fail; it simply doesn't bind the template.
564 Later stuff will fail.
566 %************************************************************************
570 %************************************************************************
572 All the tcSub calls have the form
574 tcSub expected_ty offered_ty
576 offered_ty <= expected_ty
578 That is, that a value of type offered_ty is acceptable in
579 a place expecting a value of type expected_ty.
581 It returns a coercion function
582 co_fn :: offered_ty -> expected_ty
583 which takes an HsExpr of type offered_ty into one of type
588 tcSubExp :: BoxySigmaType -> BoxySigmaType -> TcM ExprCoFn -- Locally used only
589 -- (tcSub act exp) checks that
591 tcSubExp actual_ty expected_ty
592 = addErrCtxtM (unifyCtxt actual_ty expected_ty)
593 (tc_sub True actual_ty actual_ty expected_ty expected_ty)
595 tcFunResTy :: Name -> BoxySigmaType -> BoxySigmaType -> TcM ExprCoFn -- Locally used only
596 tcFunResTy fun actual_ty expected_ty
597 = addErrCtxtM (checkFunResCtxt fun actual_ty expected_ty) $
598 (tc_sub True actual_ty actual_ty expected_ty expected_ty)
601 tc_sub :: Outer -- See comments with uTys
602 -> BoxySigmaType -- actual_ty, before expanding synonyms
603 -> BoxySigmaType -- ..and after
604 -> BoxySigmaType -- expected_ty, before
605 -> BoxySigmaType -- ..and after
608 tc_sub outer act_sty act_ty exp_sty exp_ty
609 | Just exp_ty' <- tcView exp_ty = tc_sub False act_sty act_ty exp_sty exp_ty'
610 tc_sub outer act_sty act_ty exp_sty exp_ty
611 | Just act_ty' <- tcView act_ty = tc_sub False act_sty act_ty' exp_sty exp_ty
613 -----------------------------------
614 -- Rule SBOXY, plus other cases when act_ty is a type variable
615 -- Just defer to boxy matching
616 -- This rule takes precedence over SKOL!
617 tc_sub outer act_sty (TyVarTy tv) exp_sty exp_ty
618 = do { uVar outer False tv False exp_sty exp_ty
619 ; return idCoercion }
621 -----------------------------------
622 -- Skolemisation case (rule SKOL)
623 -- actual_ty: d:Eq b => b->b
624 -- expected_ty: forall a. Ord a => a->a
625 -- co_fn e /\a. \d2:Ord a. let d = eqFromOrd d2 in e
627 -- It is essential to do this *before* the specialisation case
628 -- Example: f :: (Eq a => a->a) -> ...
629 -- g :: Ord b => b->b
632 tc_sub outer act_sty act_ty exp_sty exp_ty
634 = do { (gen_fn, co_fn) <- tcGen exp_ty act_tvs $ \ body_exp_ty ->
635 tc_sub False act_sty act_ty body_exp_ty body_exp_ty
636 ; return (gen_fn <.> co_fn) }
638 act_tvs = tyVarsOfType act_ty
639 -- It's really important to check for escape wrt
640 -- the free vars of both expected_ty *and* actual_ty
642 -----------------------------------
643 -- Specialisation case (rule ASPEC):
644 -- actual_ty: forall a. Ord a => a->a
645 -- expected_ty: Int -> Int
646 -- co_fn e = e Int dOrdInt
648 tc_sub outer act_sty actual_ty exp_sty expected_ty
649 -- Implements the new SPEC rule in the Appendix of the paper
650 -- "Boxy types: inference for higher rank types and impredicativity"
651 -- (This appendix isn't in the published version.)
652 -- The idea is to *first* do pre-subsumption, and then full subsumption
653 -- Example: forall a. a->a <= Int -> (forall b. Int)
654 -- Pre-subsumpion finds a|->Int, and that works fine, whereas
655 -- just running full subsumption would fail.
656 | isSigmaTy actual_ty
657 = do { -- Perform pre-subsumption, and instantiate
658 -- the type with info from the pre-subsumption;
659 -- boxy tyvars if pre-subsumption gives no info
660 let (tyvars, theta, tau) = tcSplitSigmaTy actual_ty
661 tau_tvs = exactTyVarsOfType tau
662 ; inst_tys <- preSubType tyvars tau_tvs tau expected_ty
663 ; let subst' = zipOpenTvSubst tyvars inst_tys
664 tau' = substTy subst' tau
666 -- Perform a full subsumption check
667 ; co_fn <- tc_sub False tau' tau' exp_sty expected_ty
669 -- Deal with the dictionaries
670 ; dicts <- newDicts InstSigOrigin (substTheta subst' theta)
672 ; let inst_fn = CoApps (CoTyApps CoHole inst_tys)
674 ; return (co_fn <.> inst_fn) }
676 -----------------------------------
677 -- Function case (rule F1)
678 tc_sub _ _ (FunTy act_arg act_res) _ (FunTy exp_arg exp_res)
679 = tc_sub_funs act_arg act_res exp_arg exp_res
681 -- Function case (rule F2)
682 tc_sub outer act_sty act_ty@(FunTy act_arg act_res) exp_sty (TyVarTy exp_tv)
684 = do { cts <- readMetaTyVar exp_tv
686 Indirect ty -> do { u_tys outer False act_sty act_ty True exp_sty ty
687 ; return idCoercion }
688 Flexi -> do { [arg_ty,res_ty] <- withMetaTvs exp_tv fun_kinds mk_res_ty
689 ; tc_sub_funs act_arg act_res arg_ty res_ty } }
691 mk_res_ty [arg_ty', res_ty'] = mkFunTy arg_ty' res_ty'
692 fun_kinds = [argTypeKind, openTypeKind]
694 -- Everything else: defer to boxy matching
695 tc_sub outer act_sty actual_ty exp_sty expected_ty
696 = do { u_tys outer False act_sty actual_ty False exp_sty expected_ty
697 ; return idCoercion }
700 -----------------------------------
701 tc_sub_funs act_arg act_res exp_arg exp_res
702 = do { uTys False act_arg False exp_arg
703 ; co_fn_res <- tc_sub False act_res act_res exp_res exp_res
704 ; wrapFunResCoercion [exp_arg] co_fn_res }
706 -----------------------------------
708 :: [TcType] -- Type of args
709 -> ExprCoFn -- HsExpr a -> HsExpr b
710 -> TcM ExprCoFn -- HsExpr (arg_tys -> a) -> HsExpr (arg_tys -> b)
711 wrapFunResCoercion arg_tys co_fn_res
712 | isIdCoercion co_fn_res = return idCoercion
713 | null arg_tys = return co_fn_res
715 = do { us <- newUniqueSupply
716 ; let arg_ids = zipWith (mkSysLocal FSLIT("sub")) (uniqsFromSupply us) arg_tys
717 ; return (CoLams arg_ids (co_fn_res <.> (CoApps CoHole arg_ids))) }
722 %************************************************************************
724 \subsection{Generalisation}
726 %************************************************************************
729 tcGen :: BoxySigmaType -- expected_ty
730 -> TcTyVarSet -- Extra tyvars that the universally
731 -- quantified tyvars of expected_ty
732 -- must not be unified
733 -> (BoxyRhoType -> TcM result) -- spec_ty
734 -> TcM (ExprCoFn, result)
735 -- The expression has type: spec_ty -> expected_ty
737 tcGen expected_ty extra_tvs thing_inside -- We expect expected_ty to be a forall-type
738 -- If not, the call is a no-op
739 = do { -- We want the GenSkol info in the skolemised type variables to
740 -- mention the *instantiated* tyvar names, so that we get a
741 -- good error message "Rigid variable 'a' is bound by (forall a. a->a)"
742 -- Hence the tiresome but innocuous fixM
743 ((forall_tvs, theta, rho_ty), skol_info) <- fixM (\ ~(_, skol_info) ->
744 do { (forall_tvs, theta, rho_ty) <- tcInstSkolType skol_info expected_ty
745 ; span <- getSrcSpanM
746 ; let skol_info = GenSkol forall_tvs (mkPhiTy theta rho_ty) span
747 ; return ((forall_tvs, theta, rho_ty), skol_info) })
750 ; traceTc (text "tcGen" <+> vcat [text "extra_tvs" <+> ppr extra_tvs,
751 text "expected_ty" <+> ppr expected_ty,
752 text "inst ty" <+> ppr forall_tvs <+> ppr theta <+> ppr rho_ty,
753 text "free_tvs" <+> ppr free_tvs,
754 text "forall_tvs" <+> ppr forall_tvs])
757 -- Type-check the arg and unify with poly type
758 ; (result, lie) <- getLIE (thing_inside rho_ty)
760 -- Check that the "forall_tvs" havn't been constrained
761 -- The interesting bit here is that we must include the free variables
762 -- of the expected_ty. Here's an example:
763 -- runST (newVar True)
764 -- Here, if we don't make a check, we'll get a type (ST s (MutVar s Bool))
765 -- for (newVar True), with s fresh. Then we unify with the runST's arg type
766 -- forall s'. ST s' a. That unifies s' with s, and a with MutVar s Bool.
767 -- So now s' isn't unconstrained because it's linked to a.
768 -- Conclusion: include the free vars of the expected_ty in the
769 -- list of "free vars" for the signature check.
771 ; dicts <- newDicts (SigOrigin skol_info) theta
772 ; inst_binds <- tcSimplifyCheck sig_msg forall_tvs dicts lie
774 ; checkSigTyVarsWrt free_tvs forall_tvs
775 ; traceTc (text "tcGen:done")
778 -- This HsLet binds any Insts which came out of the simplification.
779 -- It's a bit out of place here, but using AbsBind involves inventing
780 -- a couple of new names which seems worse.
781 dict_ids = map instToId dicts
782 co_fn = CoTyLams forall_tvs $ CoLams dict_ids $ CoLet inst_binds CoHole
783 ; returnM (co_fn, result) }
785 free_tvs = tyVarsOfType expected_ty `unionVarSet` extra_tvs
786 sig_msg = ptext SLIT("expected type of an expression")
791 %************************************************************************
795 %************************************************************************
797 The exported functions are all defined as versions of some
798 non-exported generic functions.
801 boxyUnify :: BoxyType -> BoxyType -> TcM ()
802 -- Acutal and expected, respectively
804 = addErrCtxtM (unifyCtxt ty1 ty2) $
805 uTysOuter False ty1 False ty2
808 boxyUnifyList :: [BoxyType] -> [BoxyType] -> TcM ()
809 -- Arguments should have equal length
810 -- Acutal and expected types
811 boxyUnifyList tys1 tys2 = uList boxyUnify tys1 tys2
814 unifyType :: TcTauType -> TcTauType -> TcM ()
815 -- No boxes expected inside these types
816 -- Acutal and expected types
817 unifyType ty1 ty2 -- ty1 expected, ty2 inferred
818 = ASSERT2( not (isBoxyTy ty1), ppr ty1 )
819 ASSERT2( not (isBoxyTy ty2), ppr ty2 )
820 addErrCtxtM (unifyCtxt ty1 ty2) $
821 uTysOuter True ty1 True ty2
824 unifyPred :: PredType -> PredType -> TcM ()
825 -- Acutal and expected types
826 unifyPred p1 p2 = addErrCtxtM (unifyCtxt (mkPredTy p1) (mkPredTy p2)) $
827 uPred True True p1 True p2
829 unifyTheta :: TcThetaType -> TcThetaType -> TcM ()
830 -- Acutal and expected types
831 unifyTheta theta1 theta2
832 = do { checkTc (equalLength theta1 theta2)
833 (ptext SLIT("Contexts differ in length"))
834 ; uList unifyPred theta1 theta2 }
837 uList :: (a -> a -> TcM ())
838 -> [a] -> [a] -> TcM ()
839 -- Unify corresponding elements of two lists of types, which
840 -- should be f equal length. We charge down the list explicitly so that
841 -- we can complain if their lengths differ.
842 uList unify [] [] = return ()
843 uList unify (ty1:tys1) (ty2:tys2) = do { unify ty1 ty2; uList unify tys1 tys2 }
844 uList unify ty1s ty2s = panic "Unify.uList: mismatched type lists!"
847 @unifyTypeList@ takes a single list of @TauType@s and unifies them
848 all together. It is used, for example, when typechecking explicit
849 lists, when all the elts should be of the same type.
852 unifyTypeList :: [TcTauType] -> TcM ()
853 unifyTypeList [] = returnM ()
854 unifyTypeList [ty] = returnM ()
855 unifyTypeList (ty1:tys@(ty2:_)) = do { unifyType ty1 ty2
856 ; unifyTypeList tys }
859 %************************************************************************
861 \subsection[Unify-uTys]{@uTys@: getting down to business}
863 %************************************************************************
865 @uTys@ is the heart of the unifier. Each arg happens twice, because
866 we want to report errors in terms of synomyms if poss. The first of
867 the pair is used in error messages only; it is always the same as the
868 second, except that if the first is a synonym then the second may be a
869 de-synonym'd version. This way we get better error messages.
871 We call the first one \tr{ps_ty1}, \tr{ps_ty2} for ``possible synomym''.
874 type NoBoxes = Bool -- True <=> definitely no boxes in this type
875 -- False <=> there might be boxes (always safe)
877 type Outer = Bool -- True <=> this is the outer level of a unification
878 -- so that the types being unified are the
879 -- very ones we began with, not some sub
880 -- component or synonym expansion
881 -- The idea is that if Outer is true then unifyMisMatch should
882 -- pop the context to remove the "Expected/Acutal" context
885 :: NoBoxes -> TcType -- ty1 is the *expected* type
886 -> NoBoxes -> TcType -- ty2 is the *actual* type
888 uTysOuter nb1 ty1 nb2 ty2 = u_tys True nb1 ty1 ty1 nb2 ty2 ty2
889 uTys nb1 ty1 nb2 ty2 = u_tys False nb1 ty1 ty1 nb2 ty2 ty2
893 uTys_s :: NoBoxes -> [TcType] -- ty1 is the *actual* types
894 -> NoBoxes -> [TcType] -- ty2 is the *expected* types
896 uTys_s nb1 [] nb2 [] = returnM ()
897 uTys_s nb1 (ty1:tys1) nb2 (ty2:tys2) = do { uTys nb1 ty1 nb2 ty2
898 ; uTys_s nb1 tys1 nb2 tys2 }
899 uTys_s nb1 ty1s nb2 ty2s = panic "Unify.uTys_s: mismatched type lists!"
903 -> NoBoxes -> TcType -> TcType -- ty1 is the *actual* type
904 -> NoBoxes -> TcType -> TcType -- ty2 is the *expected* type
907 u_tys outer nb1 orig_ty1 ty1 nb2 orig_ty2 ty2
911 -- Always expand synonyms (see notes at end)
912 -- (this also throws away FTVs)
914 | Just ty1' <- tcView ty1 = go False ty1' ty2
915 | Just ty2' <- tcView ty2 = go False ty1 ty2'
917 -- Variables; go for uVar
918 go outer (TyVarTy tyvar1) ty2 = uVar outer False tyvar1 nb2 orig_ty2 ty2
919 go outer ty1 (TyVarTy tyvar2) = uVar outer True tyvar2 nb1 orig_ty1 ty1
920 -- "True" means args swapped
922 go outer (PredTy p1) (PredTy p2) = uPred outer nb1 p1 nb2 p2
924 -- Type constructors must match
925 go _ (TyConApp con1 tys1) (TyConApp con2 tys2)
926 | con1 == con2 = uTys_s nb1 tys1 nb2 tys2
927 -- See Note [TyCon app]
929 -- Functions; just check the two parts
930 go _ (FunTy fun1 arg1) (FunTy fun2 arg2)
931 = do { uTys nb1 fun1 nb2 fun2
932 ; uTys nb1 arg1 nb2 arg2 }
934 -- Applications need a bit of care!
935 -- They can match FunTy and TyConApp, so use splitAppTy_maybe
936 -- NB: we've already dealt with type variables and Notes,
937 -- so if one type is an App the other one jolly well better be too
938 go outer (AppTy s1 t1) ty2
939 | Just (s2,t2) <- tcSplitAppTy_maybe ty2
940 = do { uTys nb1 s1 nb2 s2; uTys nb1 t1 nb2 t2 }
942 -- Now the same, but the other way round
943 -- Don't swap the types, because the error messages get worse
944 go outer ty1 (AppTy s2 t2)
945 | Just (s1,t1) <- tcSplitAppTy_maybe ty1
946 = do { uTys nb1 s1 nb2 s2; uTys nb1 t1 nb2 t2 }
948 go _ ty1@(ForAllTy _ _) ty2@(ForAllTy _ _)
949 | length tvs1 == length tvs2
950 = do { tvs <- tcInstSkolTyVars UnkSkol tvs1 -- Not a helpful SkolemInfo
951 ; let tys = mkTyVarTys tvs
952 in_scope = mkInScopeSet (mkVarSet tvs)
953 subst1 = mkTvSubst in_scope (zipTyEnv tvs1 tys)
954 subst2 = mkTvSubst in_scope (zipTyEnv tvs2 tys)
955 ; uTys nb1 (substTy subst1 body1) nb2 (substTy subst2 body2)
957 -- If both sides are inside a box, we should not have
958 -- a polytype at all. This check comes last, because
959 -- the error message is extremely unhelpful.
960 ; ifM (nb1 && nb2) (notMonoType ty1)
963 (tvs1, body1) = tcSplitForAllTys ty1
964 (tvs2, body2) = tcSplitForAllTys ty2
966 -- Anything else fails
967 go outer _ _ = unifyMisMatch outer False orig_ty1 orig_ty2
970 uPred outer nb1 (IParam n1 t1) nb2 (IParam n2 t2)
971 | n1 == n2 = uTys nb1 t1 nb2 t2
972 uPred outer nb1 (ClassP c1 tys1) nb2 (ClassP c2 tys2)
973 | c1 == c2 = uTys_s nb1 tys1 nb2 tys2 -- Guaranteed equal lengths because the kinds check
974 uPred outer _ p1 _ p2 = unifyMisMatch outer False (mkPredTy p1) (mkPredTy p2)
979 When we find two TyConApps, the argument lists are guaranteed equal
980 length. Reason: intially the kinds of the two types to be unified is
981 the same. The only way it can become not the same is when unifying two
982 AppTys (f1 a1):=:(f2 a2). In that case there can't be a TyConApp in
983 the f1,f2 (because it'd absorb the app). If we unify f1:=:f2 first,
984 which we do, that ensures that f1,f2 have the same kind; and that
985 means a1,a2 have the same kind. And now the argument repeats.
990 If you are tempted to make a short cut on synonyms, as in this
994 -- NO uTys (SynTy con1 args1 ty1) (SynTy con2 args2 ty2)
995 -- NO = if (con1 == con2) then
996 -- NO -- Good news! Same synonym constructors, so we can shortcut
997 -- NO -- by unifying their arguments and ignoring their expansions.
998 -- NO unifyTypepeLists args1 args2
1000 -- NO -- Never mind. Just expand them and try again
1004 then THINK AGAIN. Here is the whole story, as detected and reported
1005 by Chris Okasaki \tr{<Chris_Okasaki@loch.mess.cs.cmu.edu>}:
1007 Here's a test program that should detect the problem:
1011 x = (1 :: Bogus Char) :: Bogus Bool
1014 The problem with [the attempted shortcut code] is that
1018 is not a sufficient condition to be able to use the shortcut!
1019 You also need to know that the type synonym actually USES all
1020 its arguments. For example, consider the following type synonym
1021 which does not use all its arguments.
1026 If you ever tried unifying, say, \tr{Bogus Char} with \tr{Bogus Bool},
1027 the unifier would blithely try to unify \tr{Char} with \tr{Bool} and
1028 would fail, even though the expanded forms (both \tr{Int}) should
1031 Similarly, unifying \tr{Bogus Char} with \tr{Bogus t} would
1032 unnecessarily bind \tr{t} to \tr{Char}.
1034 ... You could explicitly test for the problem synonyms and mark them
1035 somehow as needing expansion, perhaps also issuing a warning to the
1040 %************************************************************************
1042 \subsection[Unify-uVar]{@uVar@: unifying with a type variable}
1044 %************************************************************************
1046 @uVar@ is called when at least one of the types being unified is a
1047 variable. It does {\em not} assume that the variable is a fixed point
1048 of the substitution; rather, notice that @uVar@ (defined below) nips
1049 back into @uTys@ if it turns out that the variable is already bound.
1053 -> Bool -- False => tyvar is the "expected"
1054 -- True => ty is the "expected" thing
1056 -> NoBoxes -- True <=> definitely no boxes in t2
1057 -> TcTauType -> TcTauType -- printing and real versions
1060 uVar outer swapped tv1 nb2 ps_ty2 ty2
1061 = do { let expansion | showSDoc (ppr ty2) == showSDoc (ppr ps_ty2) = empty
1062 | otherwise = brackets (equals <+> ppr ty2)
1063 ; traceTc (text "uVar" <+> ppr swapped <+>
1064 sep [ppr tv1 <+> dcolon <+> ppr (tyVarKind tv1 ),
1065 nest 2 (ptext SLIT(" :=: ")),
1066 ppr ps_ty2 <+> dcolon <+> ppr (typeKind ty2) <+> expansion])
1067 ; details <- lookupTcTyVar tv1
1070 | swapped -> u_tys outer nb2 ps_ty2 ty2 True ty1 ty1 -- Swap back
1071 | otherwise -> u_tys outer True ty1 ty1 nb2 ps_ty2 ty2 -- Same order
1072 -- The 'True' here says that ty1
1073 -- is definitely box-free
1074 DoneTv details1 -> uUnfilledVar outer swapped tv1 details1 nb2 ps_ty2 ty2
1078 uUnfilledVar :: Outer
1079 -> Bool -- Args are swapped
1080 -> TcTyVar -> TcTyVarDetails -- Tyvar 1
1081 -> NoBoxes -> TcTauType -> TcTauType -- Type 2
1083 -- Invariant: tyvar 1 is not unified with anything
1085 uUnfilledVar outer swapped tv1 details1 nb2 ps_ty2 ty2
1086 | Just ty2' <- tcView ty2
1087 = -- Expand synonyms; ignore FTVs
1088 uUnfilledVar False swapped tv1 details1 nb2 ps_ty2 ty2'
1090 uUnfilledVar outer swapped tv1 details1 nb2 ps_ty2 (TyVarTy tv2)
1091 | tv1 == tv2 -- Same type variable => no-op (but watch out for the boxy case)
1093 MetaTv BoxTv ref1 -- A boxy type variable meets itself;
1094 -- this is box-meets-box, so fill in with a tau-type
1095 -> do { tau_tv <- tcInstTyVar tv1
1096 ; updateMeta tv1 ref1 (mkTyVarTy tau_tv) }
1097 other -> returnM () -- No-op
1099 -- Distinct type variables
1101 = do { lookup2 <- lookupTcTyVar tv2
1103 IndirectTv ty2' -> uUnfilledVar outer swapped tv1 details1 True ty2' ty2'
1104 DoneTv details2 -> uUnfilledVars outer swapped tv1 details1 tv2 details2
1107 uUnfilledVar outer swapped tv1 details1 nb2 ps_ty2 non_var_ty2 -- ty2 is not a type variable
1109 MetaTv (SigTv _) ref1 -> mis_match -- Can't update a skolem with a non-type-variable
1110 MetaTv info ref1 -> uMetaVar swapped tv1 info ref1 nb2 ps_ty2 non_var_ty2
1111 skolem_details -> mis_match
1113 mis_match = unifyMisMatch outer swapped (TyVarTy tv1) ps_ty2
1117 -> TcTyVar -> BoxInfo -> IORef MetaDetails
1118 -> NoBoxes -> TcType -> TcType
1120 -- tv1 is an un-filled-in meta type variable (maybe boxy, maybe tau)
1121 -- ty2 is not a type variable
1123 uMetaVar swapped tv1 BoxTv ref1 nb2 ps_ty2 non_var_ty2
1124 = -- tv1 is a BoxTv. So we must unbox ty2, to ensure
1125 -- that any boxes in ty2 are filled with monotypes
1127 -- It should not be the case that tv1 occurs in ty2
1128 -- (i.e. no occurs check should be needed), but if perchance
1129 -- it does, the unbox operation will fill it, and the DEBUG
1131 do { final_ty <- unBox ps_ty2
1133 ; meta_details <- readMutVar ref1
1134 ; case meta_details of
1135 Indirect ty -> WARN( True, ppr tv1 <+> ppr ty )
1136 return () -- This really should *not* happen
1139 ; checkUpdateMeta swapped tv1 ref1 final_ty }
1141 uMetaVar swapped tv1 info1 ref1 nb2 ps_ty2 non_var_ty2
1142 = do { final_ty <- checkTauTvUpdate tv1 ps_ty2 -- Occurs check + monotype check
1143 ; checkUpdateMeta swapped tv1 ref1 final_ty }
1146 uUnfilledVars :: Outer
1147 -> Bool -- Args are swapped
1148 -> TcTyVar -> TcTyVarDetails -- Tyvar 1
1149 -> TcTyVar -> TcTyVarDetails -- Tyvar 2
1151 -- Invarant: The type variables are distinct,
1152 -- Neither is filled in yet
1153 -- They might be boxy or not
1155 uUnfilledVars outer swapped tv1 (SkolemTv _) tv2 (SkolemTv _)
1156 = unifyMisMatch outer swapped (mkTyVarTy tv1) (mkTyVarTy tv2)
1158 uUnfilledVars outer swapped tv1 (MetaTv info1 ref1) tv2 (SkolemTv _)
1159 = checkUpdateMeta swapped tv1 ref1 (mkTyVarTy tv2)
1160 uUnfilledVars outer swapped tv1 (SkolemTv _) tv2 (MetaTv info2 ref2)
1161 = checkUpdateMeta (not swapped) tv2 ref2 (mkTyVarTy tv1)
1163 -- ToDo: this function seems too long for what it acutally does!
1164 uUnfilledVars outer swapped tv1 (MetaTv info1 ref1) tv2 (MetaTv info2 ref2)
1165 = case (info1, info2) of
1166 (BoxTv, BoxTv) -> box_meets_box
1168 -- If a box meets a TauTv, but the fomer has the smaller kind
1169 -- then we must create a fresh TauTv with the smaller kind
1170 (_, BoxTv) | k1_sub_k2 -> update_tv2
1171 | otherwise -> box_meets_box
1172 (BoxTv, _ ) | k2_sub_k1 -> update_tv1
1173 | otherwise -> box_meets_box
1175 -- Avoid SigTvs if poss
1176 (SigTv _, _ ) | k1_sub_k2 -> update_tv2
1177 (_, SigTv _) | k2_sub_k1 -> update_tv1
1179 (_, _) | k1_sub_k2 -> if k2_sub_k1 && nicer_to_update_tv1
1180 then update_tv1 -- Same kinds
1182 | k2_sub_k1 -> update_tv1
1183 | otherwise -> kind_err
1185 -- Update the variable with least kind info
1186 -- See notes on type inference in Kind.lhs
1187 -- The "nicer to" part only applies if the two kinds are the same,
1188 -- so we can choose which to do.
1190 -- Kinds should be guaranteed ok at this point
1191 update_tv1 = updateMeta tv1 ref1 (mkTyVarTy tv2)
1192 update_tv2 = updateMeta tv2 ref2 (mkTyVarTy tv1)
1194 box_meets_box | k1_sub_k2 = if k2_sub_k1 && nicer_to_update_tv1
1197 | k2_sub_k1 = fill_from tv2
1198 | otherwise = kind_err
1200 -- Update *both* tyvars with a TauTv whose name and kind
1201 -- are gotten from tv (avoid losing nice names is poss)
1202 fill_from tv = do { tv' <- tcInstTyVar tv
1203 ; let tau_ty = mkTyVarTy tv'
1204 ; updateMeta tv1 ref1 tau_ty
1205 ; updateMeta tv2 ref2 tau_ty }
1207 kind_err = addErrCtxtM (unifyKindCtxt swapped tv1 (mkTyVarTy tv2)) $
1208 unifyKindMisMatch k1 k2
1212 k1_sub_k2 = k1 `isSubKind` k2
1213 k2_sub_k1 = k2 `isSubKind` k1
1215 nicer_to_update_tv1 = isSystemName (varName tv1)
1216 -- Try to update sys-y type variables in preference to ones
1217 -- gotten (say) by instantiating a polymorphic function with
1218 -- a user-written type sig
1221 checkUpdateMeta :: Bool -> TcTyVar -> IORef MetaDetails -> TcType -> TcM ()
1222 -- Update tv1, which is flexi; occurs check is alrady done
1223 -- The 'check' version does a kind check too
1224 -- We do a sub-kind check here: we might unify (a b) with (c d)
1225 -- where b::*->* and d::*; this should fail
1227 checkUpdateMeta swapped tv1 ref1 ty2
1228 = do { checkKinds swapped tv1 ty2
1229 ; updateMeta tv1 ref1 ty2 }
1231 updateMeta :: TcTyVar -> IORef MetaDetails -> TcType -> TcM ()
1232 updateMeta tv1 ref1 ty2
1233 = ASSERT( isMetaTyVar tv1 )
1234 ASSERT( isBoxyTyVar tv1 || isTauTy ty2 )
1235 do { ASSERTM2( do { details <- readMetaTyVar tv1; return (isFlexi details) }, ppr tv1 )
1236 ; traceTc (text "updateMeta" <+> ppr tv1 <+> text ":=" <+> ppr ty2)
1237 ; writeMutVar ref1 (Indirect ty2) }
1240 checkKinds swapped tv1 ty2
1241 -- We're about to unify a type variable tv1 with a non-tyvar-type ty2.
1242 -- ty2 has been zonked at this stage, which ensures that
1243 -- its kind has as much boxity information visible as possible.
1244 | tk2 `isSubKind` tk1 = returnM ()
1247 -- Either the kinds aren't compatible
1248 -- (can happen if we unify (a b) with (c d))
1249 -- or we are unifying a lifted type variable with an
1250 -- unlifted type: e.g. (id 3#) is illegal
1251 = addErrCtxtM (unifyKindCtxt swapped tv1 ty2) $
1252 unifyKindMisMatch k1 k2
1254 (k1,k2) | swapped = (tk2,tk1)
1255 | otherwise = (tk1,tk2)
1260 checkTauTvUpdate :: TcTyVar -> TcType -> TcM TcType
1261 -- (checkTauTvUpdate tv ty)
1262 -- We are about to update the TauTv tv with ty.
1263 -- Check (a) that tv doesn't occur in ty (occurs check)
1264 -- (b) that ty is a monotype
1265 -- Furthermore, in the interest of (b), if you find an
1266 -- empty box (BoxTv that is Flexi), fill it in with a TauTv
1268 -- Returns the (non-boxy) type to update the type variable with, or fails
1270 checkTauTvUpdate orig_tv orig_ty
1273 go (TyConApp tc tys)
1274 | isSynTyCon tc = go_syn tc tys
1275 | otherwise = do { tys' <- mappM go tys; return (TyConApp tc tys') }
1276 go (NoteTy _ ty2) = go ty2 -- Discard free-tyvar annotations
1277 go (PredTy p) = do { p' <- go_pred p; return (PredTy p') }
1278 go (FunTy arg res) = do { arg' <- go arg; res' <- go res; return (FunTy arg' res') }
1279 go (AppTy fun arg) = do { fun' <- go fun; arg' <- go arg; return (mkAppTy fun' arg') }
1280 -- NB the mkAppTy; we might have instantiated a
1281 -- type variable to a type constructor, so we need
1282 -- to pull the TyConApp to the top.
1283 go (ForAllTy tv ty) = notMonoType orig_ty -- (b)
1286 | orig_tv == tv = occurCheck tv orig_ty -- (a)
1287 | isTcTyVar tv = go_tyvar tv (tcTyVarDetails tv)
1288 | otherwise = return (TyVarTy tv)
1289 -- Ordinary (non Tc) tyvars
1290 -- occur inside quantified types
1292 go_pred (ClassP c tys) = do { tys' <- mapM go tys; return (ClassP c tys') }
1293 go_pred (IParam n ty) = do { ty' <- go ty; return (IParam n ty') }
1295 go_tyvar tv (SkolemTv _) = return (TyVarTy tv)
1296 go_tyvar tv (MetaTv box ref)
1297 = do { cts <- readMutVar ref
1299 Indirect ty -> go ty
1300 Flexi -> case box of
1301 BoxTv -> fillBoxWithTau tv ref
1302 other -> return (TyVarTy tv)
1305 -- go_syn is called for synonyms only
1306 -- See Note [Type synonyms and the occur check]
1308 | not (isTauTyCon tc)
1309 = notMonoType orig_ty -- (b) again
1311 = do { (msgs, mb_tys') <- tryTc (mapM go tys)
1313 Just tys' -> return (TyConApp tc tys')
1314 -- Retain the synonym (the common case)
1315 Nothing -> go (expectJust "checkTauTvUpdate"
1316 (tcView (TyConApp tc tys)))
1317 -- Try again, expanding the synonym
1320 fillBoxWithTau :: BoxyTyVar -> IORef MetaDetails -> TcM TcType
1321 -- (fillBoxWithTau tv ref) fills ref with a freshly allocated
1322 -- tau-type meta-variable, whose print-name is the same as tv
1323 -- Choosing the same name is good: when we instantiate a function
1324 -- we allocate boxy tyvars with the same print-name as the quantified
1325 -- tyvar; and then we often fill the box with a tau-tyvar, and again
1326 -- we want to choose the same name.
1327 fillBoxWithTau tv ref
1328 = do { tv' <- tcInstTyVar tv -- Do not gratuitously forget
1329 ; let tau = mkTyVarTy tv' -- name of the type variable
1330 ; writeMutVar ref (Indirect tau)
1334 Note [Type synonyms and the occur check]
1335 ~~~~~~~~~~~~~~~~~~~~
1336 Basically we want to update tv1 := ps_ty2
1337 because ps_ty2 has type-synonym info, which improves later error messages
1342 f :: (A a -> a -> ()) -> ()
1346 x = f (\ x p -> p x)
1348 In the application (p x), we try to match "t" with "A t". If we go
1349 ahead and bind t to A t (= ps_ty2), we'll lead the type checker into
1350 an infinite loop later.
1351 But we should not reject the program, because A t = ().
1352 Rather, we should bind t to () (= non_var_ty2).
1355 stripBoxyType :: BoxyType -> TcM TcType
1356 -- Strip all boxes from the input type, returning a non-boxy type.
1357 -- It's fine for there to be a polytype inside a box (c.f. unBox)
1358 -- All of the boxes should have been filled in by now;
1359 -- hence we return a TcType
1360 stripBoxyType ty = zonkType strip_tv ty
1362 strip_tv tv = ASSERT( not (isBoxyTyVar tv) ) return (TyVarTy tv)
1363 -- strip_tv will be called for *Flexi* meta-tyvars
1364 -- There should not be any Boxy ones; hence the ASSERT
1366 zapToMonotype :: BoxySigmaType -> TcM TcTauType
1367 -- Subtle... we must zap the boxy res_ty
1368 -- to kind * before using it to instantiate a LitInst
1369 -- Calling unBox instead doesn't do the job, because the box
1370 -- often has an openTypeKind, and we don't want to instantiate
1372 zapToMonotype res_ty
1373 = do { res_tau <- newFlexiTyVarTy liftedTypeKind
1374 ; boxyUnify res_tau res_ty
1377 unBox :: BoxyType -> TcM TcType
1378 -- unBox implements the judgement
1380 -- with input s', and result s
1382 -- It removes all boxes from the input type, returning a non-boxy type.
1383 -- A filled box in the type can only contain a monotype; unBox fails if not
1384 -- The type can have empty boxes, which unBox fills with a monotype
1386 -- Compare this wth checkTauTvUpdate
1388 -- For once, it's safe to treat synonyms as opaque!
1390 unBox (NoteTy n ty) = do { ty' <- unBox ty; return (NoteTy n ty') }
1391 unBox (TyConApp tc tys) = do { tys' <- mapM unBox tys; return (TyConApp tc tys') }
1392 unBox (AppTy f a) = do { f' <- unBox f; a' <- unBox a; return (mkAppTy f' a') }
1393 unBox (FunTy f a) = do { f' <- unBox f; a' <- unBox a; return (FunTy f' a') }
1394 unBox (PredTy p) = do { p' <- unBoxPred p; return (PredTy p') }
1395 unBox (ForAllTy tv ty) = ASSERT( isImmutableTyVar tv )
1396 do { ty' <- unBox ty; return (ForAllTy tv ty') }
1398 | isTcTyVar tv -- It's a boxy type variable
1399 , MetaTv BoxTv ref <- tcTyVarDetails tv -- NB: non-TcTyVars are possible
1400 = do { cts <- readMutVar ref -- under nested quantifiers
1402 Flexi -> fillBoxWithTau tv ref
1403 Indirect ty -> do { non_boxy_ty <- unBox ty
1404 ; if isTauTy non_boxy_ty
1405 then return non_boxy_ty
1406 else notMonoType non_boxy_ty }
1408 | otherwise -- Skolems, and meta-tau-variables
1409 = return (TyVarTy tv)
1411 unBoxPred (ClassP cls tys) = do { tys' <- mapM unBox tys; return (ClassP cls tys') }
1412 unBoxPred (IParam ip ty) = do { ty' <- unBox ty; return (IParam ip ty') }
1417 %************************************************************************
1419 \subsection[Unify-context]{Errors and contexts}
1421 %************************************************************************
1427 unifyCtxt act_ty exp_ty tidy_env
1428 = do { act_ty' <- zonkTcType act_ty
1429 ; exp_ty' <- zonkTcType exp_ty
1430 ; let (env1, exp_ty'') = tidyOpenType tidy_env exp_ty'
1431 (env2, act_ty'') = tidyOpenType env1 act_ty'
1432 ; return (env2, mkExpectedActualMsg act_ty'' exp_ty'') }
1435 mkExpectedActualMsg act_ty exp_ty
1436 = nest 2 (vcat [ text "Expected type" <> colon <+> ppr exp_ty,
1437 text "Inferred type" <> colon <+> ppr act_ty ])
1440 -- If an error happens we try to figure out whether the function
1441 -- function has been given too many or too few arguments, and say so.
1442 checkFunResCtxt fun actual_res_ty expected_res_ty tidy_env
1443 = do { exp_ty' <- zonkTcType expected_res_ty
1444 ; act_ty' <- zonkTcType actual_res_ty
1446 (env1, exp_ty'') = tidyOpenType tidy_env exp_ty'
1447 (env2, act_ty'') = tidyOpenType env1 act_ty'
1448 (exp_args, _) = tcSplitFunTys exp_ty''
1449 (act_args, _) = tcSplitFunTys act_ty''
1451 len_act_args = length act_args
1452 len_exp_args = length exp_args
1454 message | len_exp_args < len_act_args = wrongArgsCtxt "too few" fun
1455 | len_exp_args > len_act_args = wrongArgsCtxt "too many" fun
1456 | otherwise = mkExpectedActualMsg act_ty'' exp_ty''
1457 ; return (env2, message) }
1460 wrongArgsCtxt too_many_or_few fun
1461 = ptext SLIT("Probable cause:") <+> quotes (ppr fun)
1462 <+> ptext SLIT("is applied to") <+> text too_many_or_few
1463 <+> ptext SLIT("arguments")
1466 unifyKindCtxt swapped tv1 ty2 tidy_env -- not swapped => tv1 expected, ty2 inferred
1467 -- tv1 and ty2 are zonked already
1470 msg = (env2, ptext SLIT("When matching the kinds of") <+>
1471 sep [quotes pp_expected <+> ptext SLIT("and"), quotes pp_actual])
1473 (pp_expected, pp_actual) | swapped = (pp2, pp1)
1474 | otherwise = (pp1, pp2)
1475 (env1, tv1') = tidyOpenTyVar tidy_env tv1
1476 (env2, ty2') = tidyOpenType env1 ty2
1477 pp1 = ppr tv1' <+> dcolon <+> ppr (tyVarKind tv1)
1478 pp2 = ppr ty2' <+> dcolon <+> ppr (typeKind ty2)
1480 unifyMisMatch outer swapped ty1 ty2
1481 = do { (env, msg) <- if swapped then misMatchMsg ty1 ty2
1482 else misMatchMsg ty2 ty1
1484 -- This is the whole point of the 'outer' stuff
1485 ; if outer then popErrCtxt (failWithTcM (env, msg))
1486 else failWithTcM (env, msg)
1490 = do { env0 <- tcInitTidyEnv
1491 ; (env1, pp1, extra1) <- ppr_ty env0 ty1
1492 ; (env2, pp2, extra2) <- ppr_ty env1 ty2
1493 ; return (env2, sep [sep [ptext SLIT("Couldn't match expected type") <+> pp1,
1494 nest 7 (ptext SLIT("against inferred type") <+> pp2)],
1495 nest 2 extra1, nest 2 extra2]) }
1497 ppr_ty :: TidyEnv -> TcType -> TcM (TidyEnv, SDoc, SDoc)
1499 = do { ty' <- zonkTcType ty
1500 ; let (env1,tidy_ty) = tidyOpenType env ty'
1501 simple_result = (env1, quotes (ppr tidy_ty), empty)
1504 | isSkolemTyVar tv -> return (env2, pp_rigid tv',
1505 pprSkolTvBinding tv')
1506 | otherwise -> return simple_result
1508 (env2, tv') = tidySkolemTyVar env1 tv
1509 other -> return simple_result }
1511 pp_rigid tv = quotes (ppr tv) <+> parens (ptext SLIT("a rigid variable"))
1515 = do { ty' <- zonkTcType ty
1516 ; env0 <- tcInitTidyEnv
1517 ; let (env1, tidy_ty) = tidyOpenType env0 ty'
1518 msg = ptext SLIT("Cannot match a monotype with") <+> quotes (ppr tidy_ty)
1519 ; failWithTcM (env1, msg) }
1522 = do { env0 <- tcInitTidyEnv
1523 ; ty' <- zonkTcType ty
1524 ; let (env1, tidy_tyvar) = tidyOpenTyVar env0 tyvar
1525 (env2, tidy_ty) = tidyOpenType env1 ty'
1526 extra = sep [ppr tidy_tyvar, char '=', ppr tidy_ty]
1527 ; failWithTcM (env2, hang msg 2 extra) }
1529 msg = ptext SLIT("Occurs check: cannot construct the infinite type:")
1533 %************************************************************************
1537 %************************************************************************
1539 Unifying kinds is much, much simpler than unifying types.
1542 unifyKind :: TcKind -- Expected
1545 unifyKind LiftedTypeKind LiftedTypeKind = returnM ()
1546 unifyKind UnliftedTypeKind UnliftedTypeKind = returnM ()
1548 unifyKind OpenTypeKind k2 | isOpenTypeKind k2 = returnM ()
1549 unifyKind ArgTypeKind k2 | isArgTypeKind k2 = returnM ()
1550 -- Respect sub-kinding
1552 unifyKind (FunKind a1 r1) (FunKind a2 r2)
1553 = do { unifyKind a2 a1; unifyKind r1 r2 }
1554 -- Notice the flip in the argument,
1555 -- so that the sub-kinding works right
1557 unifyKind (KindVar kv1) k2 = uKVar False kv1 k2
1558 unifyKind k1 (KindVar kv2) = uKVar True kv2 k1
1559 unifyKind k1 k2 = unifyKindMisMatch k1 k2
1561 unifyKinds :: [TcKind] -> [TcKind] -> TcM ()
1562 unifyKinds [] [] = returnM ()
1563 unifyKinds (k1:ks1) (k2:ks2) = unifyKind k1 k2 `thenM_`
1565 unifyKinds _ _ = panic "unifyKinds: length mis-match"
1568 uKVar :: Bool -> KindVar -> TcKind -> TcM ()
1569 uKVar swapped kv1 k2
1570 = do { mb_k1 <- readKindVar kv1
1572 Nothing -> uUnboundKVar swapped kv1 k2
1573 Just k1 | swapped -> unifyKind k2 k1
1574 | otherwise -> unifyKind k1 k2 }
1577 uUnboundKVar :: Bool -> KindVar -> TcKind -> TcM ()
1578 uUnboundKVar swapped kv1 k2@(KindVar kv2)
1579 | kv1 == kv2 = returnM ()
1580 | otherwise -- Distinct kind variables
1581 = do { mb_k2 <- readKindVar kv2
1583 Just k2 -> uUnboundKVar swapped kv1 k2
1584 Nothing -> writeKindVar kv1 k2 }
1586 uUnboundKVar swapped kv1 non_var_k2
1587 = do { k2' <- zonkTcKind non_var_k2
1588 ; kindOccurCheck kv1 k2'
1589 ; k2'' <- kindSimpleKind swapped k2'
1590 -- KindVars must be bound only to simple kinds
1591 -- Polarities: (kindSimpleKind True ?) succeeds
1592 -- returning *, corresponding to unifying
1595 ; writeKindVar kv1 k2'' }
1598 kindOccurCheck kv1 k2 -- k2 is zonked
1599 = checkTc (not_in k2) (kindOccurCheckErr kv1 k2)
1601 not_in (KindVar kv2) = kv1 /= kv2
1602 not_in (FunKind a2 r2) = not_in a2 && not_in r2
1605 kindSimpleKind :: Bool -> Kind -> TcM SimpleKind
1606 -- (kindSimpleKind True k) returns a simple kind sk such that sk <: k
1607 -- If the flag is False, it requires k <: sk
1608 -- E.g. kindSimpleKind False ?? = *
1609 -- What about (kv -> *) :=: ?? -> *
1610 kindSimpleKind orig_swapped orig_kind
1611 = go orig_swapped orig_kind
1613 go sw (FunKind k1 k2) = do { k1' <- go (not sw) k1
1615 ; return (FunKind k1' k2') }
1616 go True OpenTypeKind = return liftedTypeKind
1617 go True ArgTypeKind = return liftedTypeKind
1618 go sw LiftedTypeKind = return liftedTypeKind
1619 go sw UnliftedTypeKind = return unliftedTypeKind
1620 go sw k@(KindVar _) = return k -- KindVars are always simple
1621 go swapped kind = failWithTc (ptext SLIT("Unexpected kind unification failure:")
1622 <+> ppr orig_swapped <+> ppr orig_kind)
1623 -- I think this can't actually happen
1625 -- T v = MkT v v must be a type
1626 -- T v w = MkT (v -> w) v must not be an umboxed tuple
1629 kindOccurCheckErr tyvar ty
1630 = hang (ptext SLIT("Occurs check: cannot construct the infinite kind:"))
1631 2 (sep [ppr tyvar, char '=', ppr ty])
1633 unifyKindMisMatch ty1 ty2
1634 = zonkTcKind ty1 `thenM` \ ty1' ->
1635 zonkTcKind ty2 `thenM` \ ty2' ->
1637 msg = hang (ptext SLIT("Couldn't match kind"))
1638 2 (sep [quotes (ppr ty1'),
1639 ptext SLIT("against"),
1646 unifyFunKind :: TcKind -> TcM (Maybe (TcKind, TcKind))
1647 -- Like unifyFunTy, but does not fail; instead just returns Nothing
1649 unifyFunKind (KindVar kvar)
1650 = readKindVar kvar `thenM` \ maybe_kind ->
1652 Just fun_kind -> unifyFunKind fun_kind
1653 Nothing -> do { arg_kind <- newKindVar
1654 ; res_kind <- newKindVar
1655 ; writeKindVar kvar (mkArrowKind arg_kind res_kind)
1656 ; returnM (Just (arg_kind,res_kind)) }
1658 unifyFunKind (FunKind arg_kind res_kind) = returnM (Just (arg_kind,res_kind))
1659 unifyFunKind other = returnM Nothing
1662 %************************************************************************
1666 %************************************************************************
1668 ---------------------------
1669 -- We would like to get a decent error message from
1670 -- (a) Under-applied type constructors
1671 -- f :: (Maybe, Maybe)
1672 -- (b) Over-applied type constructors
1673 -- f :: Int x -> Int x
1677 checkExpectedKind :: Outputable a => a -> TcKind -> TcKind -> TcM ()
1678 -- A fancy wrapper for 'unifyKind', which tries
1679 -- to give decent error messages.
1680 checkExpectedKind ty act_kind exp_kind
1681 | act_kind `isSubKind` exp_kind -- Short cut for a very common case
1684 = tryTc (unifyKind exp_kind act_kind) `thenM` \ (_errs, mb_r) ->
1686 Just r -> returnM () ; -- Unification succeeded
1689 -- So there's definitely an error
1690 -- Now to find out what sort
1691 zonkTcKind exp_kind `thenM` \ exp_kind ->
1692 zonkTcKind act_kind `thenM` \ act_kind ->
1694 tcInitTidyEnv `thenM` \ env0 ->
1695 let (exp_as, _) = splitKindFunTys exp_kind
1696 (act_as, _) = splitKindFunTys act_kind
1697 n_exp_as = length exp_as
1698 n_act_as = length act_as
1700 (env1, tidy_exp_kind) = tidyKind env0 exp_kind
1701 (env2, tidy_act_kind) = tidyKind env1 act_kind
1703 err | n_exp_as < n_act_as -- E.g. [Maybe]
1704 = quotes (ppr ty) <+> ptext SLIT("is not applied to enough type arguments")
1706 -- Now n_exp_as >= n_act_as. In the next two cases,
1707 -- n_exp_as == 0, and hence so is n_act_as
1708 | isLiftedTypeKind exp_kind && isUnliftedTypeKind act_kind
1709 = ptext SLIT("Expecting a lifted type, but") <+> quotes (ppr ty)
1710 <+> ptext SLIT("is unlifted")
1712 | isUnliftedTypeKind exp_kind && isLiftedTypeKind act_kind
1713 = ptext SLIT("Expecting an unlifted type, but") <+> quotes (ppr ty)
1714 <+> ptext SLIT("is lifted")
1716 | otherwise -- E.g. Monad [Int]
1717 = ptext SLIT("Kind mis-match")
1719 more_info = sep [ ptext SLIT("Expected kind") <+>
1720 quotes (pprKind tidy_exp_kind) <> comma,
1721 ptext SLIT("but") <+> quotes (ppr ty) <+>
1722 ptext SLIT("has kind") <+> quotes (pprKind tidy_act_kind)]
1724 failWithTcM (env2, err $$ more_info)
1728 %************************************************************************
1730 \subsection{Checking signature type variables}
1732 %************************************************************************
1734 @checkSigTyVars@ checks that a set of universally quantified type varaibles
1735 are not mentioned in the environment. In particular:
1737 (a) Not mentioned in the type of a variable in the envt
1738 eg the signature for f in this:
1744 Here, f is forced to be monorphic by the free occurence of x.
1746 (d) Not (unified with another type variable that is) in scope.
1747 eg f x :: (r->r) = (\y->y) :: forall a. a->r
1748 when checking the expression type signature, we find that
1749 even though there is nothing in scope whose type mentions r,
1750 nevertheless the type signature for the expression isn't right.
1752 Another example is in a class or instance declaration:
1754 op :: forall b. a -> b
1756 Here, b gets unified with a
1758 Before doing this, the substitution is applied to the signature type variable.
1761 checkSigTyVars :: [TcTyVar] -> TcM ()
1762 checkSigTyVars sig_tvs = check_sig_tyvars emptyVarSet sig_tvs
1764 checkSigTyVarsWrt :: TcTyVarSet -> [TcTyVar] -> TcM ()
1765 -- The extra_tvs can include boxy type variables;
1766 -- e.g. TcMatches.tcCheckExistentialPat
1767 checkSigTyVarsWrt extra_tvs sig_tvs
1768 = do { extra_tvs' <- zonkTcTyVarsAndFV (varSetElems extra_tvs)
1769 ; check_sig_tyvars extra_tvs' sig_tvs }
1772 :: TcTyVarSet -- Global type variables. The universally quantified
1773 -- tyvars should not mention any of these
1774 -- Guaranteed already zonked.
1775 -> [TcTyVar] -- Universally-quantified type variables in the signature
1776 -- Guaranteed to be skolems
1778 check_sig_tyvars extra_tvs []
1780 check_sig_tyvars extra_tvs sig_tvs
1781 = ASSERT( all isSkolemTyVar sig_tvs )
1782 do { gbl_tvs <- tcGetGlobalTyVars
1783 ; traceTc (text "check_sig_tyvars" <+> (vcat [text "sig_tys" <+> ppr sig_tvs,
1784 text "gbl_tvs" <+> ppr gbl_tvs,
1785 text "extra_tvs" <+> ppr extra_tvs]))
1787 ; let env_tvs = gbl_tvs `unionVarSet` extra_tvs
1788 ; ifM (any (`elemVarSet` env_tvs) sig_tvs)
1789 (bleatEscapedTvs env_tvs sig_tvs sig_tvs)
1792 bleatEscapedTvs :: TcTyVarSet -- The global tvs
1793 -> [TcTyVar] -- The possibly-escaping type variables
1794 -> [TcTyVar] -- The zonked versions thereof
1796 -- Complain about escaping type variables
1797 -- We pass a list of type variables, at least one of which
1798 -- escapes. The first list contains the original signature type variable,
1799 -- while the second contains the type variable it is unified to (usually itself)
1800 bleatEscapedTvs globals sig_tvs zonked_tvs
1801 = do { env0 <- tcInitTidyEnv
1802 ; let (env1, tidy_tvs) = tidyOpenTyVars env0 sig_tvs
1803 (env2, tidy_zonked_tvs) = tidyOpenTyVars env1 zonked_tvs
1805 ; (env3, msgs) <- foldlM check (env2, []) (tidy_tvs `zip` tidy_zonked_tvs)
1806 ; failWithTcM (env3, main_msg $$ nest 2 (vcat msgs)) }
1808 main_msg = ptext SLIT("Inferred type is less polymorphic than expected")
1810 check (tidy_env, msgs) (sig_tv, zonked_tv)
1811 | not (zonked_tv `elemVarSet` globals) = return (tidy_env, msgs)
1813 = do { (tidy_env1, globs) <- findGlobals (unitVarSet zonked_tv) tidy_env
1814 ; returnM (tidy_env1, escape_msg sig_tv zonked_tv globs : msgs) }
1816 -----------------------
1817 escape_msg sig_tv zonked_tv globs
1819 = vcat [sep [msg, ptext SLIT("is mentioned in the environment:")],
1820 nest 2 (vcat globs)]
1822 = msg <+> ptext SLIT("escapes")
1823 -- Sigh. It's really hard to give a good error message
1824 -- all the time. One bad case is an existential pattern match.
1825 -- We rely on the "When..." context to help.
1827 msg = ptext SLIT("Quantified type variable") <+> quotes (ppr sig_tv) <+> is_bound_to
1829 | sig_tv == zonked_tv = empty
1830 | otherwise = ptext SLIT("is unified with") <+> quotes (ppr zonked_tv) <+> ptext SLIT("which")
1833 These two context are used with checkSigTyVars
1836 sigCtxt :: Id -> [TcTyVar] -> TcThetaType -> TcTauType
1837 -> TidyEnv -> TcM (TidyEnv, Message)
1838 sigCtxt id sig_tvs sig_theta sig_tau tidy_env
1839 = zonkTcType sig_tau `thenM` \ actual_tau ->
1841 (env1, tidy_sig_tvs) = tidyOpenTyVars tidy_env sig_tvs
1842 (env2, tidy_sig_rho) = tidyOpenType env1 (mkPhiTy sig_theta sig_tau)
1843 (env3, tidy_actual_tau) = tidyOpenType env2 actual_tau
1844 sub_msg = vcat [ptext SLIT("Signature type: ") <+> pprType (mkForAllTys tidy_sig_tvs tidy_sig_rho),
1845 ptext SLIT("Type to generalise:") <+> pprType tidy_actual_tau
1847 msg = vcat [ptext SLIT("When trying to generalise the type inferred for") <+> quotes (ppr id),