2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
6 Type subsumption and unification
10 -- Full-blown subsumption
11 tcSubExp, tcFunResTy, tcGen,
12 checkSigTyVars, checkSigTyVarsWrt, bleatEscapedTvs, sigCtxt,
14 -- Various unifications
15 unifyType, unifyTypeList, unifyTheta,
16 unifyKind, unifyKinds, unifyFunKind,
18 preSubType, boxyMatchTypes,
20 --------------------------------
22 tcInfer, subFunTys, unBox, refineBox, refineBoxToTau, withBox,
23 boxyUnify, boxyUnifyList, zapToMonotype,
24 boxySplitListTy, boxySplitTyConApp, boxySplitAppTy,
28 #include "HsVersions.h"
37 import TcRnMonad -- TcType, amongst others
55 %************************************************************************
57 \subsection{'hole' type variables}
59 %************************************************************************
62 tcInfer :: (BoxyType -> TcM a) -> TcM (a, TcType)
64 = do { box <- newBoxyTyVar openTypeKind
65 ; res <- tc_infer (mkTyVarTy box)
66 ; res_ty <- readFilledBox box -- Guaranteed filled-in by now
67 ; return (res, res_ty) }
71 %************************************************************************
75 %************************************************************************
78 subFunTys :: SDoc -- Somthing like "The function f has 3 arguments"
79 -- or "The abstraction (\x.e) takes 1 argument"
80 -> Arity -- Expected # of args
81 -> BoxyRhoType -- res_ty
82 -> ([BoxySigmaType] -> BoxyRhoType -> TcM a)
84 -- Attempt to decompse res_ty to have enough top-level arrows to
85 -- match the number of patterns in the match group
87 -- If (subFunTys n_args res_ty thing_inside) = (co_fn, res)
88 -- and the inner call to thing_inside passes args: [a1,...,an], b
89 -- then co_fn :: (a1 -> ... -> an -> b) -> res_ty
91 -- Note that it takes a BoxyRho type, and guarantees to return a BoxyRhoType
94 {- Error messages from subFunTys
96 The abstraction `\Just 1 -> ...' has two arguments
97 but its type `Maybe a -> a' has only one
99 The equation(s) for `f' have two arguments
100 but its type `Maybe a -> a' has only one
102 The section `(f 3)' requires 'f' to take two arguments
103 but its type `Int -> Int' has only one
105 The function 'f' is applied to two arguments
106 but its type `Int -> Int' has only one
110 subFunTys error_herald n_pats res_ty thing_inside
111 = loop n_pats [] res_ty
113 -- In 'loop', the parameter 'arg_tys' accumulates
114 -- the arg types so far, in *reverse order*
115 loop n args_so_far res_ty
116 | Just res_ty' <- tcView res_ty = loop n args_so_far res_ty'
118 loop n args_so_far res_ty
119 | isSigmaTy res_ty -- Do this before checking n==0, because we
120 -- guarantee to return a BoxyRhoType, not a BoxySigmaType
121 = do { (gen_fn, (co_fn, res)) <- tcGen res_ty emptyVarSet $ \ _ res_ty' ->
122 loop n args_so_far res_ty'
123 ; return (gen_fn <.> co_fn, res) }
125 loop 0 args_so_far res_ty
126 = do { res <- thing_inside (reverse args_so_far) res_ty
127 ; return (idHsWrapper, res) }
129 loop n args_so_far (FunTy arg_ty res_ty)
130 = do { (co_fn, res) <- loop (n-1) (arg_ty:args_so_far) res_ty
131 ; co_fn' <- wrapFunResCoercion [arg_ty] co_fn
132 ; return (co_fn', res) }
134 -- res_ty might have a type variable at the head, such as (a b c),
135 -- in which case we must fill in with (->). Simplest thing to do
136 -- is to use boxyUnify, but we catch failure and generate our own
137 -- error message on failure
138 loop n args_so_far res_ty@(AppTy _ _)
139 = do { [arg_ty',res_ty'] <- newBoxyTyVarTys [argTypeKind, openTypeKind]
140 ; (_, mb_unit) <- tryTcErrs $ boxyUnify res_ty (FunTy arg_ty' res_ty')
141 ; if isNothing mb_unit then bale_out args_so_far
142 else loop n args_so_far (FunTy arg_ty' res_ty') }
144 loop n args_so_far (TyVarTy tv)
145 | isTyConableTyVar tv
146 = do { cts <- readMetaTyVar tv
148 Indirect ty -> loop n args_so_far ty
149 Flexi -> do { (res_ty:arg_tys) <- withMetaTvs tv kinds mk_res_ty
150 ; res <- thing_inside (reverse args_so_far ++ arg_tys) res_ty
151 ; return (idHsWrapper, res) } }
153 mk_res_ty (res_ty' : arg_tys') = mkFunTys arg_tys' res_ty'
154 mk_res_ty [] = panic "TcUnify.mk_res_ty1"
155 kinds = openTypeKind : take n (repeat argTypeKind)
156 -- Note argTypeKind: the args can have an unboxed type,
157 -- but not an unboxed tuple.
159 loop n args_so_far res_ty = bale_out args_so_far
162 = do { env0 <- tcInitTidyEnv
163 ; res_ty' <- zonkTcType res_ty
164 ; let (env1, res_ty'') = tidyOpenType env0 res_ty'
165 ; failWithTcM (env1, mk_msg res_ty'' (length args_so_far)) }
167 mk_msg res_ty n_actual
168 = error_herald <> comma $$
169 sep [ptext SLIT("but its type") <+> quotes (pprType res_ty),
170 if n_actual == 0 then ptext SLIT("has none")
171 else ptext SLIT("has only") <+> speakN n_actual]
175 ----------------------
176 boxySplitTyConApp :: TyCon -- T :: k1 -> ... -> kn -> *
177 -> BoxyRhoType -- Expected type (T a b c)
178 -> TcM [BoxySigmaType] -- Element types, a b c
179 -- It's used for wired-in tycons, so we call checkWiredInTyCOn
180 -- Precondition: never called with FunTyCon
181 -- Precondition: input type :: *
183 boxySplitTyConApp tc orig_ty
184 = do { checkWiredInTyCon tc
185 ; loop (tyConArity tc) [] orig_ty }
187 loop n_req args_so_far ty
188 | Just ty' <- tcView ty = loop n_req args_so_far ty'
190 loop n_req args_so_far (TyConApp tycon args)
192 = ASSERT( n_req == length args) -- ty::*
193 return (args ++ args_so_far)
195 loop n_req args_so_far (AppTy fun arg)
196 = loop (n_req - 1) (arg:args_so_far) fun
198 loop n_req args_so_far (TyVarTy tv)
199 | isTyConableTyVar tv
200 = do { cts <- readMetaTyVar tv
202 Indirect ty -> loop n_req args_so_far ty
203 Flexi -> do { arg_tys <- withMetaTvs tv arg_kinds mk_res_ty
204 ; return (arg_tys ++ args_so_far) }
207 mk_res_ty arg_tys' = mkTyConApp tc arg_tys'
208 arg_kinds = map tyVarKind (take n_req (tyConTyVars tc))
210 loop _ _ _ = boxySplitFailure (mkTyConApp tc (mkTyVarTys (tyConTyVars tc))) orig_ty
212 ----------------------
213 boxySplitListTy :: BoxyRhoType -> TcM BoxySigmaType -- Special case for lists
214 boxySplitListTy exp_ty = do { [elt_ty] <- boxySplitTyConApp listTyCon exp_ty
218 ----------------------
219 boxySplitAppTy :: BoxyRhoType -- Type to split: m a
220 -> TcM (BoxySigmaType, BoxySigmaType) -- Returns m, a
221 -- Assumes (m: * -> k), where k is the kind of the incoming type
222 -- If the incoming type is boxy, then so are the result types; and vice versa
224 boxySplitAppTy orig_ty
228 | Just ty' <- tcView ty = loop ty'
231 | Just (fun_ty, arg_ty) <- tcSplitAppTy_maybe ty
232 = return (fun_ty, arg_ty)
235 | isTyConableTyVar tv
236 = do { cts <- readMetaTyVar tv
238 Indirect ty -> loop ty
239 Flexi -> do { [fun_ty,arg_ty] <- withMetaTvs tv kinds mk_res_ty
240 ; return (fun_ty, arg_ty) } }
242 mk_res_ty [fun_ty', arg_ty'] = mkAppTy fun_ty' arg_ty'
243 mk_res_ty other = panic "TcUnify.mk_res_ty2"
244 tv_kind = tyVarKind tv
245 kinds = [mkArrowKind liftedTypeKind (defaultKind tv_kind),
247 liftedTypeKind] -- arg type :: *
248 -- The defaultKind is a bit smelly. If you remove it,
249 -- try compiling f x = do { x }
250 -- and you'll get a kind mis-match. It smells, but
251 -- not enough to lose sleep over.
253 loop _ = boxySplitFailure (mkAppTy alphaTy betaTy) orig_ty
256 boxySplitFailure actual_ty expected_ty
257 = unifyMisMatch False False actual_ty expected_ty
258 -- "outer" is False, so we don't pop the context
259 -- which is what we want since we have not pushed one!
263 --------------------------------
264 -- withBoxes: the key utility function
265 --------------------------------
268 withMetaTvs :: TcTyVar -- An unfilled-in, non-skolem, meta type variable
269 -> [Kind] -- Make fresh boxes (with the same BoxTv/TauTv setting as tv)
270 -> ([BoxySigmaType] -> BoxySigmaType)
271 -- Constructs the type to assign
272 -- to the original var
273 -> TcM [BoxySigmaType] -- Return the fresh boxes
275 -- It's entirely possible for the [kind] to be empty.
276 -- For example, when pattern-matching on True,
277 -- we call boxySplitTyConApp passing a boolTyCon
279 -- Invariant: tv is still Flexi
281 withMetaTvs tv kinds mk_res_ty
283 = do { box_tvs <- mapM (newMetaTyVar BoxTv) kinds
284 ; let box_tys = mkTyVarTys box_tvs
285 ; writeMetaTyVar tv (mk_res_ty box_tys)
288 | otherwise -- Non-boxy meta type variable
289 = do { tau_tys <- mapM newFlexiTyVarTy kinds
290 ; writeMetaTyVar tv (mk_res_ty tau_tys) -- Write it *first*
291 -- Sure to be a tau-type
294 withBox :: Kind -> (BoxySigmaType -> TcM a) -> TcM (a, TcType)
295 -- Allocate a *boxy* tyvar
296 withBox kind thing_inside
297 = do { box_tv <- newMetaTyVar BoxTv kind
298 ; res <- thing_inside (mkTyVarTy box_tv)
299 ; ty <- readFilledBox box_tv
304 %************************************************************************
306 Approximate boxy matching
308 %************************************************************************
311 preSubType :: [TcTyVar] -- Quantified type variables
312 -> TcTyVarSet -- Subset of quantified type variables
313 -- see Note [Pre-sub boxy]
314 -> TcType -- The rho-type part; quantified tyvars scopes over this
315 -> BoxySigmaType -- Matching type from the context
316 -> TcM [TcType] -- Types to instantiate the tyvars
317 -- Perform pre-subsumption, and return suitable types
318 -- to instantiate the quantified type varibles:
319 -- info from the pre-subsumption, if there is any
320 -- a boxy type variable otherwise
322 -- Note [Pre-sub boxy]
323 -- The 'btvs' are a subset of 'qtvs'. They are the ones we can
324 -- instantiate to a boxy type variable, because they'll definitely be
325 -- filled in later. This isn't always the case; sometimes we have type
326 -- variables mentioned in the context of the type, but not the body;
327 -- f :: forall a b. C a b => a -> a
328 -- Then we may land up with an unconstrained 'b', so we want to
329 -- instantiate it to a monotype (non-boxy) type variable
331 -- The 'qtvs' that are *neither* fixed by the pre-subsumption, *nor* are in 'btvs',
332 -- are instantiated to TauTv meta variables.
334 preSubType qtvs btvs qty expected_ty
335 = do { tys <- mapM inst_tv qtvs
336 ; traceTc (text "preSubType" <+> (ppr qtvs $$ ppr btvs $$ ppr qty $$ ppr expected_ty $$ ppr pre_subst $$ ppr tys))
339 pre_subst = boxySubMatchType (mkVarSet qtvs) qty expected_ty
341 | Just boxy_ty <- lookupTyVar pre_subst tv = return boxy_ty
342 | tv `elemVarSet` btvs = do { tv' <- tcInstBoxyTyVar tv
343 ; return (mkTyVarTy tv') }
344 | otherwise = do { tv' <- tcInstTyVar tv
345 ; return (mkTyVarTy tv') }
348 :: TcTyVarSet -> TcType -- The "template"; the tyvars are skolems
349 -> BoxyRhoType -- Type to match (note a *Rho* type)
350 -> TvSubst -- Substitution of the [TcTyVar] to BoxySigmaTypes
352 -- boxySubMatchType implements the Pre-subsumption judgement, in Fig 5 of the paper
353 -- "Boxy types: inference for higher rank types and impredicativity"
355 boxySubMatchType tmpl_tvs tmpl_ty boxy_ty
356 = go tmpl_tvs tmpl_ty emptyVarSet boxy_ty
358 go t_tvs t_ty b_tvs b_ty
359 | Just t_ty' <- tcView t_ty = go t_tvs t_ty' b_tvs b_ty
360 | Just b_ty' <- tcView b_ty = go t_tvs t_ty b_tvs b_ty'
362 go t_tvs (TyVarTy _) b_tvs b_ty = emptyTvSubst -- Rule S-ANY; no bindings
363 -- Rule S-ANY covers (a) type variables and (b) boxy types
364 -- in the template. Both look like a TyVarTy.
365 -- See Note [Sub-match] below
367 go t_tvs t_ty b_tvs b_ty
368 | isSigmaTy t_ty, (tvs, _, t_tau) <- tcSplitSigmaTy t_ty
369 = go (t_tvs `delVarSetList` tvs) t_tau b_tvs b_ty -- Rule S-SPEC
370 -- Under a forall on the left, if there is shadowing,
371 -- do not bind! Hence the delVarSetList.
372 | isSigmaTy b_ty, (tvs, _, b_tau) <- tcSplitSigmaTy b_ty
373 = go t_tvs t_ty (extendVarSetList b_tvs tvs) b_tau -- Rule S-SKOL
374 -- Add to the variables we must not bind to
375 -- NB: it's *important* to discard the theta part. Otherwise
376 -- consider (forall a. Eq a => a -> b) ~<~ (Int -> Int -> Bool)
377 -- and end up with a completely bogus binding (b |-> Bool), by lining
378 -- up the (Eq a) with the Int, whereas it should be (b |-> (Int->Bool)).
379 -- This pre-subsumption stuff can return too few bindings, but it
380 -- must *never* return bogus info.
382 go t_tvs (FunTy arg1 res1) b_tvs (FunTy arg2 res2) -- Rule S-FUN
383 = boxy_match t_tvs arg1 b_tvs arg2 (go t_tvs res1 b_tvs res2)
384 -- Match the args, and sub-match the results
386 go t_tvs t_ty b_tvs b_ty = boxy_match t_tvs t_ty b_tvs b_ty emptyTvSubst
387 -- Otherwise defer to boxy matching
388 -- This covers TyConApp, AppTy, PredTy
395 |- head xs : <rhobox>
396 We will do a boxySubMatchType between a ~ <rhobox>
397 But we *don't* want to match [a |-> <rhobox>] because
398 (a) The box should be filled in with a rho-type, but
399 but the returned substitution maps TyVars to boxy
401 (b) In any case, the right final answer might be *either*
402 instantiate 'a' with a rho-type or a sigma type
403 head xs : Int vs head xs : forall b. b->b
404 So the matcher MUST NOT make a choice here. In general, we only
405 bind a template type variable in boxyMatchType, not in boxySubMatchType.
410 :: TcTyVarSet -> [TcType] -- The "template"; the tyvars are skolems
411 -> [BoxySigmaType] -- Type to match
412 -> TvSubst -- Substitution of the [TcTyVar] to BoxySigmaTypes
414 -- boxyMatchTypes implements the Pre-matching judgement, in Fig 5 of the paper
415 -- "Boxy types: inference for higher rank types and impredicativity"
417 -- Find a *boxy* substitution that makes the template look as much
418 -- like the BoxySigmaType as possible.
419 -- It's always ok to return an empty substitution;
420 -- anything more is jam on the pudding
422 -- NB1: This is a pure, non-monadic function.
423 -- It does no unification, and cannot fail
425 -- Precondition: the arg lengths are equal
426 -- Precondition: none of the template type variables appear anywhere in the [BoxySigmaType]
430 boxyMatchTypes tmpl_tvs tmpl_tys boxy_tys
431 = ASSERT( length tmpl_tys == length boxy_tys )
432 boxy_match_s tmpl_tvs tmpl_tys emptyVarSet boxy_tys emptyTvSubst
433 -- ToDo: add error context?
435 boxy_match_s tmpl_tvs [] boxy_tvs [] subst
437 boxy_match_s tmpl_tvs (t_ty:t_tys) boxy_tvs (b_ty:b_tys) subst
438 = boxy_match tmpl_tvs t_ty boxy_tvs b_ty $
439 boxy_match_s tmpl_tvs t_tys boxy_tvs b_tys subst
440 boxy_match_s tmpl_tvs _ boxy_tvs _ subst
441 = panic "boxy_match_s" -- Lengths do not match
445 boxy_match :: TcTyVarSet -> TcType -- Template
446 -> TcTyVarSet -- boxy_tvs: do not bind template tyvars to any of these
447 -> BoxySigmaType -- Match against this type
451 -- The boxy_tvs argument prevents this match:
452 -- [a] forall b. a ~ forall b. b
453 -- We don't want to bind the template variable 'a'
454 -- to the quantified type variable 'b'!
456 boxy_match tmpl_tvs orig_tmpl_ty boxy_tvs orig_boxy_ty subst
457 = go orig_tmpl_ty orig_boxy_ty
460 | Just t_ty' <- tcView t_ty = go t_ty' b_ty
461 | Just b_ty' <- tcView b_ty = go t_ty b_ty'
463 go ty1 ty2 -- C.f. the isSigmaTy case for boxySubMatchType
465 , (tvs1, _, tau1) <- tcSplitSigmaTy ty1
466 , (tvs2, _, tau2) <- tcSplitSigmaTy ty2
467 , equalLength tvs1 tvs2
468 = boxy_match (tmpl_tvs `delVarSetList` tvs1) tau1
469 (boxy_tvs `extendVarSetList` tvs2) tau2 subst
471 go (TyConApp tc1 tys1) (TyConApp tc2 tys2)
472 | tc1 == tc2 = go_s tys1 tys2
474 go (FunTy arg1 res1) (FunTy arg2 res2)
475 = go_s [arg1,res1] [arg2,res2]
478 | Just (s1,t1) <- tcSplitAppTy_maybe t_ty,
479 Just (s2,t2) <- tcSplitAppTy_maybe b_ty,
480 typeKind t2 `isSubKind` typeKind t1 -- Maintain invariant
481 = go_s [s1,t1] [s2,t2]
484 | tv `elemVarSet` tmpl_tvs -- Template type variable in the template
485 , boxy_tvs `disjointVarSet` tyVarsOfType orig_boxy_ty
486 , typeKind b_ty `isSubKind` tyVarKind tv -- See Note [Matching kinds]
487 = extendTvSubst subst tv boxy_ty'
489 = subst -- Ignore others
491 boxy_ty' = case lookupTyVar subst tv of
492 Nothing -> orig_boxy_ty
493 Just ty -> ty `boxyLub` orig_boxy_ty
495 go _ _ = emptyTvSubst -- It's important to *fail* by returning the empty substitution
496 -- Example: Tree a ~ Maybe Int
497 -- We do not want to bind (a |-> Int) in pre-matching, because that can give very
498 -- misleading error messages. An even more confusing case is
499 -- a -> b ~ Maybe Int
500 -- Then we do not want to bind (b |-> Int)! It's always safe to discard bindings
501 -- from this pre-matching phase.
504 go_s tys1 tys2 = boxy_match_s tmpl_tvs tys1 boxy_tvs tys2 subst
507 boxyLub :: BoxySigmaType -> BoxySigmaType -> BoxySigmaType
508 -- Combine boxy information from the two types
509 -- If there is a conflict, return the first
510 boxyLub orig_ty1 orig_ty2
511 = go orig_ty1 orig_ty2
513 go (AppTy f1 a1) (AppTy f2 a2) = AppTy (boxyLub f1 f2) (boxyLub a1 a2)
514 go (FunTy f1 a1) (FunTy f2 a2) = FunTy (boxyLub f1 f2) (boxyLub a1 a2)
515 go (TyConApp tc1 ts1) (TyConApp tc2 ts2)
516 | tc1 == tc2, length ts1 == length ts2
517 = TyConApp tc1 (zipWith boxyLub ts1 ts2)
519 go (TyVarTy tv1) ty2 -- This is the whole point;
520 | isTcTyVar tv1, isBoxyTyVar tv1 -- choose ty2 if ty2 is a box
523 -- Look inside type synonyms, but only if the naive version fails
524 go ty1 ty2 | Just ty1' <- tcView ty1 = go ty1' ty2
525 | Just ty2' <- tcView ty1 = go ty1 ty2'
527 -- For now, we don't look inside ForAlls, PredTys
528 go ty1 ty2 = orig_ty1 -- Default
531 Note [Matching kinds]
532 ~~~~~~~~~~~~~~~~~~~~~
533 The target type might legitimately not be a sub-kind of template.
534 For example, suppose the target is simply a box with an OpenTypeKind,
535 and the template is a type variable with LiftedTypeKind.
536 Then it's ok (because the target type will later be refined).
537 We simply don't bind the template type variable.
539 It might also be that the kind mis-match is an error. For example,
540 suppose we match the template (a -> Int) against (Int# -> Int),
541 where the template type variable 'a' has LiftedTypeKind. This
542 matching function does not fail; it simply doesn't bind the template.
543 Later stuff will fail.
545 %************************************************************************
549 %************************************************************************
551 All the tcSub calls have the form
553 tcSub expected_ty offered_ty
555 offered_ty <= expected_ty
557 That is, that a value of type offered_ty is acceptable in
558 a place expecting a value of type expected_ty.
560 It returns a coercion function
561 co_fn :: offered_ty -> expected_ty
562 which takes an HsExpr of type offered_ty into one of type
567 tcSubExp :: BoxySigmaType -> BoxySigmaType -> TcM HsWrapper -- Locally used only
568 -- (tcSub act exp) checks that
570 tcSubExp actual_ty expected_ty
571 = -- addErrCtxtM (unifyCtxt actual_ty expected_ty) $
572 -- Adding the error context here leads to some very confusing error
573 -- messages, such as "can't match forall a. a->a with forall a. a->a"
574 -- Example is tcfail165:
575 -- do var <- newEmptyMVar :: IO (MVar (forall a. Show a => a -> String))
576 -- putMVar var (show :: forall a. Show a => a -> String)
577 -- Here the info does not flow from the 'var' arg of putMVar to its 'show' arg
578 -- but after zonking it looks as if it does!
580 -- So instead I'm adding the error context when moving from tc_sub to u_tys
582 traceTc (text "tcSubExp" <+> ppr actual_ty <+> ppr expected_ty) >>
583 tc_sub SubOther actual_ty actual_ty False expected_ty expected_ty
585 tcFunResTy :: Name -> BoxySigmaType -> BoxySigmaType -> TcM HsWrapper -- Locally used only
586 tcFunResTy fun actual_ty expected_ty
587 = traceTc (text "tcFunResTy" <+> ppr actual_ty <+> ppr expected_ty) >>
588 tc_sub (SubFun fun) actual_ty actual_ty False expected_ty expected_ty
591 data SubCtxt = SubDone -- Error-context already pushed
592 | SubFun Name -- Context is tcFunResTy
593 | SubOther -- Context is something else
595 tc_sub :: SubCtxt -- How to add an error-context
596 -> BoxySigmaType -- actual_ty, before expanding synonyms
597 -> BoxySigmaType -- ..and after
598 -> InBox -- True <=> expected_ty is inside a box
599 -> BoxySigmaType -- expected_ty, before
600 -> BoxySigmaType -- ..and after
602 -- The acual_ty is never inside a box
603 -- IMPORTANT pre-condition: if the args contain foralls, the bound type
604 -- variables are visible non-monadically
605 -- (i.e. tha args are sufficiently zonked)
606 -- This invariant is needed so that we can "see" the foralls, ad
607 -- e.g. in the SPEC rule where we just use splitSigmaTy
609 tc_sub sub_ctxt act_sty act_ty exp_ib exp_sty exp_ty
610 = traceTc (text "tc_sub" <+> ppr act_ty $$ ppr exp_ty) >>
611 tc_sub1 sub_ctxt act_sty act_ty exp_ib exp_sty exp_ty
612 -- This indirection is just here to make
613 -- it easy to insert a debug trace!
615 tc_sub1 sub_ctxt act_sty act_ty exp_ib exp_sty exp_ty
616 | Just exp_ty' <- tcView exp_ty = tc_sub sub_ctxt act_sty act_ty exp_ib exp_sty exp_ty'
617 tc_sub1 sub_ctxt act_sty act_ty exp_ib exp_sty exp_ty
618 | Just act_ty' <- tcView act_ty = tc_sub sub_ctxt act_sty act_ty' exp_ib exp_sty exp_ty
620 -----------------------------------
621 -- Rule SBOXY, plus other cases when act_ty is a type variable
622 -- Just defer to boxy matching
623 -- This rule takes precedence over SKOL!
624 tc_sub1 sub_ctxt act_sty (TyVarTy tv) exp_ib exp_sty exp_ty
625 = do { addSubCtxt sub_ctxt act_sty exp_sty $
626 uVar True False tv exp_ib exp_sty exp_ty
627 ; return idHsWrapper }
629 -----------------------------------
630 -- Skolemisation case (rule SKOL)
631 -- actual_ty: d:Eq b => b->b
632 -- expected_ty: forall a. Ord a => a->a
633 -- co_fn e /\a. \d2:Ord a. let d = eqFromOrd d2 in e
635 -- It is essential to do this *before* the specialisation case
636 -- Example: f :: (Eq a => a->a) -> ...
637 -- g :: Ord b => b->b
640 tc_sub1 sub_ctxt act_sty act_ty exp_ib exp_sty exp_ty
642 = if exp_ib then -- SKOL does not apply if exp_ty is inside a box
643 defer_to_boxy_matching sub_ctxt act_sty act_ty exp_ib exp_sty exp_ty
645 { (gen_fn, co_fn) <- tcGen exp_ty act_tvs $ \ _ body_exp_ty ->
646 tc_sub sub_ctxt act_sty act_ty False body_exp_ty body_exp_ty
647 ; return (gen_fn <.> co_fn) }
649 act_tvs = tyVarsOfType act_ty
650 -- It's really important to check for escape wrt
651 -- the free vars of both expected_ty *and* actual_ty
653 -----------------------------------
654 -- Specialisation case (rule ASPEC):
655 -- actual_ty: forall a. Ord a => a->a
656 -- expected_ty: Int -> Int
657 -- co_fn e = e Int dOrdInt
659 tc_sub1 sub_ctxt act_sty actual_ty exp_ib exp_sty expected_ty
660 -- Implements the new SPEC rule in the Appendix of the paper
661 -- "Boxy types: inference for higher rank types and impredicativity"
662 -- (This appendix isn't in the published version.)
663 -- The idea is to *first* do pre-subsumption, and then full subsumption
664 -- Example: forall a. a->a <= Int -> (forall b. Int)
665 -- Pre-subsumpion finds a|->Int, and that works fine, whereas
666 -- just running full subsumption would fail.
667 | isSigmaTy actual_ty
668 = do { -- Perform pre-subsumption, and instantiate
669 -- the type with info from the pre-subsumption;
670 -- boxy tyvars if pre-subsumption gives no info
671 let (tyvars, theta, tau) = tcSplitSigmaTy actual_ty
672 tau_tvs = exactTyVarsOfType tau
673 ; inst_tys <- if exp_ib then -- Inside a box, do not do clever stuff
674 do { tyvars' <- mapM tcInstBoxyTyVar tyvars
675 ; return (mkTyVarTys tyvars') }
676 else -- Outside, do clever stuff
677 preSubType tyvars tau_tvs tau expected_ty
678 ; let subst' = zipOpenTvSubst tyvars inst_tys
679 tau' = substTy subst' tau
681 -- Perform a full subsumption check
682 ; traceTc (text "tc_sub_spec" <+> vcat [ppr actual_ty,
683 ppr tyvars <+> ppr theta <+> ppr tau,
685 ; co_fn2 <- tc_sub sub_ctxt tau' tau' exp_ib exp_sty expected_ty
687 -- Deal with the dictionaries
688 -- The origin gives a helpful origin when we have
689 -- a function with type f :: Int -> forall a. Num a => ...
690 -- This way the (Num a) dictionary gets an OccurrenceOf f origin
691 ; let orig = case sub_ctxt of
692 SubFun n -> OccurrenceOf n
693 other -> InstSigOrigin -- Unhelpful
694 ; co_fn1 <- instCall orig inst_tys (substTheta subst' theta)
695 ; return (co_fn2 <.> co_fn1) }
697 -----------------------------------
698 -- Function case (rule F1)
699 tc_sub1 sub_ctxt act_sty (FunTy act_arg act_res) exp_ib exp_sty (FunTy exp_arg exp_res)
700 = addSubCtxt sub_ctxt act_sty exp_sty $
701 tc_sub_funs act_arg act_res exp_ib exp_arg exp_res
703 -- Function case (rule F2)
704 tc_sub1 sub_ctxt act_sty act_ty@(FunTy act_arg act_res) _ exp_sty (TyVarTy exp_tv)
706 = addSubCtxt sub_ctxt act_sty exp_sty $
707 do { cts <- readMetaTyVar exp_tv
709 Indirect ty -> tc_sub SubDone act_sty act_ty True exp_sty ty
710 Flexi -> do { [arg_ty,res_ty] <- withMetaTvs exp_tv fun_kinds mk_res_ty
711 ; tc_sub_funs act_arg act_res True arg_ty res_ty } }
713 mk_res_ty [arg_ty', res_ty'] = mkFunTy arg_ty' res_ty'
714 mk_res_ty other = panic "TcUnify.mk_res_ty3"
715 fun_kinds = [argTypeKind, openTypeKind]
717 -- Everything else: defer to boxy matching
718 tc_sub1 sub_ctxt act_sty actual_ty exp_ib exp_sty expected_ty
719 = defer_to_boxy_matching sub_ctxt act_sty actual_ty exp_ib exp_sty expected_ty
721 -----------------------------------
722 defer_to_boxy_matching sub_ctxt act_sty actual_ty exp_ib exp_sty expected_ty
723 = do { addSubCtxt sub_ctxt act_sty exp_sty $
724 u_tys outer False act_sty actual_ty exp_ib exp_sty expected_ty
725 ; return idHsWrapper }
727 outer = case sub_ctxt of -- Ugh
731 -----------------------------------
732 tc_sub_funs act_arg act_res exp_ib exp_arg exp_res
733 = do { uTys False act_arg exp_ib exp_arg
734 ; co_fn_res <- tc_sub SubDone act_res act_res exp_ib exp_res exp_res
735 ; wrapFunResCoercion [exp_arg] co_fn_res }
737 -----------------------------------
739 :: [TcType] -- Type of args
740 -> HsWrapper -- HsExpr a -> HsExpr b
741 -> TcM HsWrapper -- HsExpr (arg_tys -> a) -> HsExpr (arg_tys -> b)
742 wrapFunResCoercion arg_tys co_fn_res
743 | isIdHsWrapper co_fn_res = return idHsWrapper
744 | null arg_tys = return co_fn_res
746 = do { arg_ids <- newSysLocalIds FSLIT("sub") arg_tys
747 ; return (mkWpLams arg_ids <.> co_fn_res <.> mkWpApps arg_ids) }
752 %************************************************************************
754 \subsection{Generalisation}
756 %************************************************************************
759 tcGen :: BoxySigmaType -- expected_ty
760 -> TcTyVarSet -- Extra tyvars that the universally
761 -- quantified tyvars of expected_ty
762 -- must not be unified
763 -> ([TcTyVar] -> BoxyRhoType -> TcM result)
764 -> TcM (HsWrapper, result)
765 -- The expression has type: spec_ty -> expected_ty
767 tcGen expected_ty extra_tvs thing_inside -- We expect expected_ty to be a forall-type
768 -- If not, the call is a no-op
769 = do { -- We want the GenSkol info in the skolemised type variables to
770 -- mention the *instantiated* tyvar names, so that we get a
771 -- good error message "Rigid variable 'a' is bound by (forall a. a->a)"
772 -- Hence the tiresome but innocuous fixM
773 ((tvs', theta', rho'), skol_info) <- fixM (\ ~(_, skol_info) ->
774 do { (forall_tvs, theta, rho_ty) <- tcInstSkolType skol_info expected_ty
775 -- Get loation from monad, not from expected_ty
776 ; let skol_info = GenSkol forall_tvs (mkPhiTy theta rho_ty)
777 ; return ((forall_tvs, theta, rho_ty), skol_info) })
780 ; traceTc (text "tcGen" <+> vcat [text "extra_tvs" <+> ppr extra_tvs,
781 text "expected_ty" <+> ppr expected_ty,
782 text "inst ty" <+> ppr tvs' <+> ppr theta' <+> ppr rho',
783 text "free_tvs" <+> ppr free_tvs])
786 -- Type-check the arg and unify with poly type
787 ; (result, lie) <- getLIE (thing_inside tvs' rho')
789 -- Check that the "forall_tvs" havn't been constrained
790 -- The interesting bit here is that we must include the free variables
791 -- of the expected_ty. Here's an example:
792 -- runST (newVar True)
793 -- Here, if we don't make a check, we'll get a type (ST s (MutVar s Bool))
794 -- for (newVar True), with s fresh. Then we unify with the runST's arg type
795 -- forall s'. ST s' a. That unifies s' with s, and a with MutVar s Bool.
796 -- So now s' isn't unconstrained because it's linked to a.
797 -- Conclusion: include the free vars of the expected_ty in the
798 -- list of "free vars" for the signature check.
800 ; loc <- getInstLoc (SigOrigin skol_info)
801 ; dicts <- newDictBndrs loc theta'
802 ; inst_binds <- tcSimplifyCheck loc tvs' dicts lie
804 ; checkSigTyVarsWrt free_tvs tvs'
805 ; traceTc (text "tcGen:done")
808 -- The WpLet binds any Insts which came out of the simplification.
809 dict_ids = map instToId dicts
810 co_fn = mkWpTyLams tvs' <.> mkWpLams dict_ids <.> WpLet inst_binds
811 ; returnM (co_fn, result) }
813 free_tvs = tyVarsOfType expected_ty `unionVarSet` extra_tvs
818 %************************************************************************
822 %************************************************************************
824 The exported functions are all defined as versions of some
825 non-exported generic functions.
828 boxyUnify :: BoxyType -> BoxyType -> TcM ()
829 -- Acutal and expected, respectively
831 = addErrCtxtM (unifyCtxt ty1 ty2) $
832 uTysOuter False ty1 False ty2
835 boxyUnifyList :: [BoxyType] -> [BoxyType] -> TcM ()
836 -- Arguments should have equal length
837 -- Acutal and expected types
838 boxyUnifyList tys1 tys2 = uList boxyUnify tys1 tys2
841 unifyType :: TcTauType -> TcTauType -> TcM ()
842 -- No boxes expected inside these types
843 -- Acutal and expected types
844 unifyType ty1 ty2 -- ty1 expected, ty2 inferred
845 = ASSERT2( not (isBoxyTy ty1), ppr ty1 )
846 ASSERT2( not (isBoxyTy ty2), ppr ty2 )
847 addErrCtxtM (unifyCtxt ty1 ty2) $
848 uTysOuter True ty1 True ty2
851 unifyPred :: PredType -> PredType -> TcM ()
852 -- Acutal and expected types
853 unifyPred p1 p2 = addErrCtxtM (unifyCtxt (mkPredTy p1) (mkPredTy p2)) $
854 uPred True True p1 True p2
856 unifyTheta :: TcThetaType -> TcThetaType -> TcM ()
857 -- Acutal and expected types
858 unifyTheta theta1 theta2
859 = do { checkTc (equalLength theta1 theta2)
860 (vcat [ptext SLIT("Contexts differ in length"),
861 nest 2 $ parens $ ptext SLIT("Use -fglasgow-exts to allow this")])
862 ; uList unifyPred theta1 theta2 }
865 uList :: (a -> a -> TcM ())
866 -> [a] -> [a] -> TcM ()
867 -- Unify corresponding elements of two lists of types, which
868 -- should be f equal length. We charge down the list explicitly so that
869 -- we can complain if their lengths differ.
870 uList unify [] [] = return ()
871 uList unify (ty1:tys1) (ty2:tys2) = do { unify ty1 ty2; uList unify tys1 tys2 }
872 uList unify ty1s ty2s = panic "Unify.uList: mismatched type lists!"
875 @unifyTypeList@ takes a single list of @TauType@s and unifies them
876 all together. It is used, for example, when typechecking explicit
877 lists, when all the elts should be of the same type.
880 unifyTypeList :: [TcTauType] -> TcM ()
881 unifyTypeList [] = returnM ()
882 unifyTypeList [ty] = returnM ()
883 unifyTypeList (ty1:tys@(ty2:_)) = do { unifyType ty1 ty2
884 ; unifyTypeList tys }
887 %************************************************************************
889 \subsection[Unify-uTys]{@uTys@: getting down to business}
891 %************************************************************************
893 @uTys@ is the heart of the unifier. Each arg happens twice, because
894 we want to report errors in terms of synomyms if poss. The first of
895 the pair is used in error messages only; it is always the same as the
896 second, except that if the first is a synonym then the second may be a
897 de-synonym'd version. This way we get better error messages.
899 We call the first one \tr{ps_ty1}, \tr{ps_ty2} for ``possible synomym''.
902 type InBox = Bool -- True <=> we are inside a box
903 -- False <=> we are outside a box
904 -- The importance of this is that if we get "filled-box meets
905 -- filled-box", we'll look into the boxes and unify... but
906 -- we must not allow polytypes. But if we are in a box on
907 -- just one side, then we can allow polytypes
909 type Outer = Bool -- True <=> this is the outer level of a unification
910 -- so that the types being unified are the
911 -- very ones we began with, not some sub
912 -- component or synonym expansion
913 -- The idea is that if Outer is true then unifyMisMatch should
914 -- pop the context to remove the "Expected/Acutal" context
917 :: InBox -> TcType -- ty1 is the *expected* type
918 -> InBox -> TcType -- ty2 is the *actual* type
920 uTysOuter nb1 ty1 nb2 ty2 = do { traceTc (text "uTysOuter" <+> ppr ty1 <+> ppr ty2)
921 ; u_tys True nb1 ty1 ty1 nb2 ty2 ty2 }
922 uTys nb1 ty1 nb2 ty2 = do { traceTc (text "uTys" <+> ppr ty1 <+> ppr ty2)
923 ; u_tys False nb1 ty1 ty1 nb2 ty2 ty2 }
927 uTys_s :: InBox -> [TcType] -- ty1 is the *actual* types
928 -> InBox -> [TcType] -- ty2 is the *expected* types
930 uTys_s nb1 [] nb2 [] = returnM ()
931 uTys_s nb1 (ty1:tys1) nb2 (ty2:tys2) = do { uTys nb1 ty1 nb2 ty2
932 ; uTys_s nb1 tys1 nb2 tys2 }
933 uTys_s nb1 ty1s nb2 ty2s = panic "Unify.uTys_s: mismatched type lists!"
937 -> InBox -> TcType -> TcType -- ty1 is the *actual* type
938 -> InBox -> TcType -> TcType -- ty2 is the *expected* type
941 u_tys outer nb1 orig_ty1 ty1 nb2 orig_ty2 ty2
945 -- Always expand synonyms (see notes at end)
946 -- (this also throws away FTVs)
948 | Just ty1' <- tcView ty1 = go False ty1' ty2
949 | Just ty2' <- tcView ty2 = go False ty1 ty2'
951 -- Variables; go for uVar
952 go outer (TyVarTy tyvar1) ty2 = uVar outer False tyvar1 nb2 orig_ty2 ty2
953 go outer ty1 (TyVarTy tyvar2) = uVar outer True tyvar2 nb1 orig_ty1 ty1
954 -- "True" means args swapped
956 -- The case for sigma-types must *follow* the variable cases
957 -- because a boxy variable can be filed with a polytype;
958 -- but must precede FunTy, because ((?x::Int) => ty) look
959 -- like a FunTy; there isn't necy a forall at the top
961 | isSigmaTy ty1 || isSigmaTy ty2
962 = do { checkM (equalLength tvs1 tvs2)
963 (unifyMisMatch outer False orig_ty1 orig_ty2)
965 ; tvs <- tcInstSkolTyVars UnkSkol tvs1 -- Not a helpful SkolemInfo
966 -- Get location from monad, not from tvs1
967 ; let tys = mkTyVarTys tvs
968 in_scope = mkInScopeSet (mkVarSet tvs)
969 phi1 = substTy (mkTvSubst in_scope (zipTyEnv tvs1 tys)) body1
970 phi2 = substTy (mkTvSubst in_scope (zipTyEnv tvs2 tys)) body2
971 (theta1,tau1) = tcSplitPhiTy phi1
972 (theta2,tau2) = tcSplitPhiTy phi2
974 ; addErrCtxtM (unifyForAllCtxt tvs phi1 phi2) $ do
975 { checkM (equalLength theta1 theta2)
976 (unifyMisMatch outer False orig_ty1 orig_ty2)
978 ; uPreds False nb1 theta1 nb2 theta2
979 ; uTys nb1 tau1 nb2 tau2
981 -- Check for escape; e.g. (forall a. a->b) ~ (forall a. a->a)
982 ; free_tvs <- zonkTcTyVarsAndFV (varSetElems (tyVarsOfType ty1 `unionVarSet` tyVarsOfType ty2))
983 ; ifM (any (`elemVarSet` free_tvs) tvs)
984 (bleatEscapedTvs free_tvs tvs tvs)
986 -- If both sides are inside a box, we are in a "box-meets-box"
987 -- situation, and we should not have a polytype at all.
988 -- If we get here we have two boxes, already filled with
989 -- the same polytype... but it should be a monotype.
990 -- This check comes last, because the error message is
991 -- extremely unhelpful.
992 ; ifM (nb1 && nb2) (notMonoType ty1)
995 (tvs1, body1) = tcSplitForAllTys ty1
996 (tvs2, body2) = tcSplitForAllTys ty2
999 go outer (PredTy p1) (PredTy p2) = uPred False nb1 p1 nb2 p2
1001 -- Type constructors must match
1002 go _ (TyConApp con1 tys1) (TyConApp con2 tys2)
1003 | con1 == con2 = uTys_s nb1 tys1 nb2 tys2
1004 -- See Note [TyCon app]
1006 -- Functions; just check the two parts
1007 go _ (FunTy fun1 arg1) (FunTy fun2 arg2)
1008 = do { uTys nb1 fun1 nb2 fun2
1009 ; uTys nb1 arg1 nb2 arg2 }
1011 -- Applications need a bit of care!
1012 -- They can match FunTy and TyConApp, so use splitAppTy_maybe
1013 -- NB: we've already dealt with type variables and Notes,
1014 -- so if one type is an App the other one jolly well better be too
1015 go outer (AppTy s1 t1) ty2
1016 | Just (s2,t2) <- tcSplitAppTy_maybe ty2
1017 = do { uTys nb1 s1 nb2 s2; uTys nb1 t1 nb2 t2 }
1019 -- Now the same, but the other way round
1020 -- Don't swap the types, because the error messages get worse
1021 go outer ty1 (AppTy s2 t2)
1022 | Just (s1,t1) <- tcSplitAppTy_maybe ty1
1023 = do { uTys nb1 s1 nb2 s2; uTys nb1 t1 nb2 t2 }
1026 -- Anything else fails
1027 go outer _ _ = unifyMisMatch outer False orig_ty1 orig_ty2
1030 uPred outer nb1 (IParam n1 t1) nb2 (IParam n2 t2)
1031 | n1 == n2 = uTys nb1 t1 nb2 t2
1032 uPred outer nb1 (ClassP c1 tys1) nb2 (ClassP c2 tys2)
1033 | c1 == c2 = uTys_s nb1 tys1 nb2 tys2 -- Guaranteed equal lengths because the kinds check
1034 uPred outer _ p1 _ p2 = unifyMisMatch outer False (mkPredTy p1) (mkPredTy p2)
1036 uPreds outer nb1 [] nb2 [] = return ()
1037 uPreds outer nb1 (p1:ps1) nb2 (p2:ps2) = uPred outer nb1 p1 nb2 p2 >> uPreds outer nb1 ps1 nb2 ps2
1038 uPreds outer nb1 ps1 nb2 ps2 = panic "uPreds"
1043 When we find two TyConApps, the argument lists are guaranteed equal
1044 length. Reason: intially the kinds of the two types to be unified is
1045 the same. The only way it can become not the same is when unifying two
1046 AppTys (f1 a1):=:(f2 a2). In that case there can't be a TyConApp in
1047 the f1,f2 (because it'd absorb the app). If we unify f1:=:f2 first,
1048 which we do, that ensures that f1,f2 have the same kind; and that
1049 means a1,a2 have the same kind. And now the argument repeats.
1054 If you are tempted to make a short cut on synonyms, as in this
1058 -- NO uTys (SynTy con1 args1 ty1) (SynTy con2 args2 ty2)
1059 -- NO = if (con1 == con2) then
1060 -- NO -- Good news! Same synonym constructors, so we can shortcut
1061 -- NO -- by unifying their arguments and ignoring their expansions.
1062 -- NO unifyTypepeLists args1 args2
1064 -- NO -- Never mind. Just expand them and try again
1068 then THINK AGAIN. Here is the whole story, as detected and reported
1069 by Chris Okasaki \tr{<Chris_Okasaki@loch.mess.cs.cmu.edu>}:
1071 Here's a test program that should detect the problem:
1075 x = (1 :: Bogus Char) :: Bogus Bool
1078 The problem with [the attempted shortcut code] is that
1082 is not a sufficient condition to be able to use the shortcut!
1083 You also need to know that the type synonym actually USES all
1084 its arguments. For example, consider the following type synonym
1085 which does not use all its arguments.
1090 If you ever tried unifying, say, \tr{Bogus Char} with \tr{Bogus Bool},
1091 the unifier would blithely try to unify \tr{Char} with \tr{Bool} and
1092 would fail, even though the expanded forms (both \tr{Int}) should
1095 Similarly, unifying \tr{Bogus Char} with \tr{Bogus t} would
1096 unnecessarily bind \tr{t} to \tr{Char}.
1098 ... You could explicitly test for the problem synonyms and mark them
1099 somehow as needing expansion, perhaps also issuing a warning to the
1104 %************************************************************************
1106 \subsection[Unify-uVar]{@uVar@: unifying with a type variable}
1108 %************************************************************************
1110 @uVar@ is called when at least one of the types being unified is a
1111 variable. It does {\em not} assume that the variable is a fixed point
1112 of the substitution; rather, notice that @uVar@ (defined below) nips
1113 back into @uTys@ if it turns out that the variable is already bound.
1117 -> Bool -- False => tyvar is the "expected"
1118 -- True => ty is the "expected" thing
1120 -> InBox -- True <=> definitely no boxes in t2
1121 -> TcTauType -> TcTauType -- printing and real versions
1124 uVar outer swapped tv1 nb2 ps_ty2 ty2
1125 = do { let expansion | showSDoc (ppr ty2) == showSDoc (ppr ps_ty2) = empty
1126 | otherwise = brackets (equals <+> ppr ty2)
1127 ; traceTc (text "uVar" <+> ppr swapped <+>
1128 sep [ppr tv1 <+> dcolon <+> ppr (tyVarKind tv1 ),
1129 nest 2 (ptext SLIT(" <-> ")),
1130 ppr ps_ty2 <+> dcolon <+> ppr (typeKind ty2) <+> expansion])
1131 ; details <- lookupTcTyVar tv1
1134 | swapped -> u_tys outer nb2 ps_ty2 ty2 True ty1 ty1 -- Swap back
1135 | otherwise -> u_tys outer True ty1 ty1 nb2 ps_ty2 ty2 -- Same order
1136 -- The 'True' here says that ty1 is now inside a box
1137 DoneTv details1 -> uUnfilledVar outer swapped tv1 details1 ps_ty2 ty2
1141 uUnfilledVar :: Outer
1142 -> Bool -- Args are swapped
1143 -> TcTyVar -> TcTyVarDetails -- Tyvar 1
1144 -> TcTauType -> TcTauType -- Type 2
1146 -- Invariant: tyvar 1 is not unified with anything
1148 uUnfilledVar outer swapped tv1 details1 ps_ty2 ty2
1149 | Just ty2' <- tcView ty2
1150 = -- Expand synonyms; ignore FTVs
1151 uUnfilledVar False swapped tv1 details1 ps_ty2 ty2'
1153 uUnfilledVar outer swapped tv1 details1 ps_ty2 (TyVarTy tv2)
1154 | tv1 == tv2 -- Same type variable => no-op (but watch out for the boxy case)
1156 MetaTv BoxTv ref1 -- A boxy type variable meets itself;
1157 -- this is box-meets-box, so fill in with a tau-type
1158 -> do { tau_tv <- tcInstTyVar tv1
1159 ; updateMeta tv1 ref1 (mkTyVarTy tau_tv) }
1160 other -> returnM () -- No-op
1162 -- Distinct type variables
1164 = do { lookup2 <- lookupTcTyVar tv2
1166 IndirectTv ty2' -> uUnfilledVar outer swapped tv1 details1 ty2' ty2'
1167 DoneTv details2 -> uUnfilledVars outer swapped tv1 details1 tv2 details2
1170 uUnfilledVar outer swapped tv1 details1 ps_ty2 non_var_ty2 -- ty2 is not a type variable
1172 MetaTv (SigTv _) ref1 -> mis_match -- Can't update a skolem with a non-type-variable
1173 MetaTv info ref1 -> uMetaVar swapped tv1 info ref1 ps_ty2 non_var_ty2
1174 skolem_details -> mis_match
1176 mis_match = unifyMisMatch outer swapped (TyVarTy tv1) ps_ty2
1180 -> TcTyVar -> BoxInfo -> IORef MetaDetails
1183 -- tv1 is an un-filled-in meta type variable (maybe boxy, maybe tau)
1184 -- ty2 is not a type variable
1186 uMetaVar swapped tv1 BoxTv ref1 ps_ty2 non_var_ty2
1187 = -- tv1 is a BoxTv. So we must unbox ty2, to ensure
1188 -- that any boxes in ty2 are filled with monotypes
1190 -- It should not be the case that tv1 occurs in ty2
1191 -- (i.e. no occurs check should be needed), but if perchance
1192 -- it does, the unbox operation will fill it, and the DEBUG
1194 do { final_ty <- unBox ps_ty2
1196 ; meta_details <- readMutVar ref1
1197 ; case meta_details of
1198 Indirect ty -> WARN( True, ppr tv1 <+> ppr ty )
1199 return () -- This really should *not* happen
1202 ; checkUpdateMeta swapped tv1 ref1 final_ty }
1204 uMetaVar swapped tv1 info1 ref1 ps_ty2 non_var_ty2
1205 = do { final_ty <- checkTauTvUpdate tv1 ps_ty2 -- Occurs check + monotype check
1206 ; checkUpdateMeta swapped tv1 ref1 final_ty }
1209 uUnfilledVars :: Outer
1210 -> Bool -- Args are swapped
1211 -> TcTyVar -> TcTyVarDetails -- Tyvar 1
1212 -> TcTyVar -> TcTyVarDetails -- Tyvar 2
1214 -- Invarant: The type variables are distinct,
1215 -- Neither is filled in yet
1216 -- They might be boxy or not
1218 uUnfilledVars outer swapped tv1 (SkolemTv _) tv2 (SkolemTv _)
1219 = unifyMisMatch outer swapped (mkTyVarTy tv1) (mkTyVarTy tv2)
1221 uUnfilledVars outer swapped tv1 (MetaTv info1 ref1) tv2 (SkolemTv _)
1222 = checkUpdateMeta swapped tv1 ref1 (mkTyVarTy tv2)
1223 uUnfilledVars outer swapped tv1 (SkolemTv _) tv2 (MetaTv info2 ref2)
1224 = checkUpdateMeta (not swapped) tv2 ref2 (mkTyVarTy tv1)
1226 -- ToDo: this function seems too long for what it acutally does!
1227 uUnfilledVars outer swapped tv1 (MetaTv info1 ref1) tv2 (MetaTv info2 ref2)
1228 = case (info1, info2) of
1229 (BoxTv, BoxTv) -> box_meets_box
1231 -- If a box meets a TauTv, but the fomer has the smaller kind
1232 -- then we must create a fresh TauTv with the smaller kind
1233 (_, BoxTv) | k1_sub_k2 -> update_tv2
1234 | otherwise -> box_meets_box
1235 (BoxTv, _ ) | k2_sub_k1 -> update_tv1
1236 | otherwise -> box_meets_box
1238 -- Avoid SigTvs if poss
1239 (SigTv _, _ ) | k1_sub_k2 -> update_tv2
1240 (_, SigTv _) | k2_sub_k1 -> update_tv1
1242 (_, _) | k1_sub_k2 -> if k2_sub_k1 && nicer_to_update_tv1
1243 then update_tv1 -- Same kinds
1245 | k2_sub_k1 -> update_tv1
1246 | otherwise -> kind_err
1248 -- Update the variable with least kind info
1249 -- See notes on type inference in Kind.lhs
1250 -- The "nicer to" part only applies if the two kinds are the same,
1251 -- so we can choose which to do.
1253 -- Kinds should be guaranteed ok at this point
1254 update_tv1 = updateMeta tv1 ref1 (mkTyVarTy tv2)
1255 update_tv2 = updateMeta tv2 ref2 (mkTyVarTy tv1)
1257 box_meets_box | k1_sub_k2 = if k2_sub_k1 && nicer_to_update_tv1
1260 | k2_sub_k1 = fill_from tv2
1261 | otherwise = kind_err
1263 -- Update *both* tyvars with a TauTv whose name and kind
1264 -- are gotten from tv (avoid losing nice names is poss)
1265 fill_from tv = do { tv' <- tcInstTyVar tv
1266 ; let tau_ty = mkTyVarTy tv'
1267 ; updateMeta tv1 ref1 tau_ty
1268 ; updateMeta tv2 ref2 tau_ty }
1270 kind_err = addErrCtxtM (unifyKindCtxt swapped tv1 (mkTyVarTy tv2)) $
1271 unifyKindMisMatch k1 k2
1275 k1_sub_k2 = k1 `isSubKind` k2
1276 k2_sub_k1 = k2 `isSubKind` k1
1278 nicer_to_update_tv1 = isSystemName (Var.varName tv1)
1279 -- Try to update sys-y type variables in preference to ones
1280 -- gotten (say) by instantiating a polymorphic function with
1281 -- a user-written type sig
1284 checkUpdateMeta :: Bool -> TcTyVar -> IORef MetaDetails -> TcType -> TcM ()
1285 -- Update tv1, which is flexi; occurs check is alrady done
1286 -- The 'check' version does a kind check too
1287 -- We do a sub-kind check here: we might unify (a b) with (c d)
1288 -- where b::*->* and d::*; this should fail
1290 checkUpdateMeta swapped tv1 ref1 ty2
1291 = do { checkKinds swapped tv1 ty2
1292 ; updateMeta tv1 ref1 ty2 }
1294 updateMeta :: TcTyVar -> IORef MetaDetails -> TcType -> TcM ()
1295 updateMeta tv1 ref1 ty2
1296 = ASSERT( isMetaTyVar tv1 )
1297 ASSERT( isBoxyTyVar tv1 || isTauTy ty2 )
1298 do { ASSERTM2( do { details <- readMetaTyVar tv1; return (isFlexi details) }, ppr tv1 )
1299 ; traceTc (text "updateMeta" <+> ppr tv1 <+> text ":=" <+> ppr ty2)
1300 ; writeMutVar ref1 (Indirect ty2) }
1303 checkKinds swapped tv1 ty2
1304 -- We're about to unify a type variable tv1 with a non-tyvar-type ty2.
1305 -- ty2 has been zonked at this stage, which ensures that
1306 -- its kind has as much boxity information visible as possible.
1307 | tk2 `isSubKind` tk1 = returnM ()
1310 -- Either the kinds aren't compatible
1311 -- (can happen if we unify (a b) with (c d))
1312 -- or we are unifying a lifted type variable with an
1313 -- unlifted type: e.g. (id 3#) is illegal
1314 = addErrCtxtM (unifyKindCtxt swapped tv1 ty2) $
1315 unifyKindMisMatch k1 k2
1317 (k1,k2) | swapped = (tk2,tk1)
1318 | otherwise = (tk1,tk2)
1323 checkTauTvUpdate :: TcTyVar -> TcType -> TcM TcType
1324 -- (checkTauTvUpdate tv ty)
1325 -- We are about to update the TauTv tv with ty.
1326 -- Check (a) that tv doesn't occur in ty (occurs check)
1327 -- (b) that ty is a monotype
1328 -- Furthermore, in the interest of (b), if you find an
1329 -- empty box (BoxTv that is Flexi), fill it in with a TauTv
1331 -- Returns the (non-boxy) type to update the type variable with, or fails
1333 checkTauTvUpdate orig_tv orig_ty
1336 go (TyConApp tc tys)
1337 | isSynTyCon tc = go_syn tc tys
1338 | otherwise = do { tys' <- mappM go tys; return (TyConApp tc tys') }
1339 go (NoteTy _ ty2) = go ty2 -- Discard free-tyvar annotations
1340 go (PredTy p) = do { p' <- go_pred p; return (PredTy p') }
1341 go (FunTy arg res) = do { arg' <- go arg; res' <- go res; return (FunTy arg' res') }
1342 go (AppTy fun arg) = do { fun' <- go fun; arg' <- go arg; return (mkAppTy fun' arg') }
1343 -- NB the mkAppTy; we might have instantiated a
1344 -- type variable to a type constructor, so we need
1345 -- to pull the TyConApp to the top.
1346 go (ForAllTy tv ty) = notMonoType orig_ty -- (b)
1349 | orig_tv == tv = occurCheck tv orig_ty -- (a)
1350 | isTcTyVar tv = go_tyvar tv (tcTyVarDetails tv)
1351 | otherwise = return (TyVarTy tv)
1352 -- Ordinary (non Tc) tyvars
1353 -- occur inside quantified types
1355 go_pred (ClassP c tys) = do { tys' <- mapM go tys; return (ClassP c tys') }
1356 go_pred (IParam n ty) = do { ty' <- go ty; return (IParam n ty') }
1357 go_pred (EqPred t1 t2) = do { t1' <- go t1; t2' <- go t2; return (EqPred t1' t2') }
1359 go_tyvar tv (SkolemTv _) = return (TyVarTy tv)
1360 go_tyvar tv (MetaTv box ref)
1361 = do { cts <- readMutVar ref
1363 Indirect ty -> go ty
1364 Flexi -> case box of
1365 BoxTv -> fillBoxWithTau tv ref
1366 other -> return (TyVarTy tv)
1369 -- go_syn is called for synonyms only
1370 -- See Note [Type synonyms and the occur check]
1372 | not (isTauTyCon tc)
1373 = notMonoType orig_ty -- (b) again
1375 = do { (msgs, mb_tys') <- tryTc (mapM go tys)
1377 Just tys' -> return (TyConApp tc tys')
1378 -- Retain the synonym (the common case)
1379 Nothing | isOpenTyCon tc
1380 -> notMonoArgs (TyConApp tc tys)
1381 -- Synonym families must have monotype args
1383 -> go (expectJust "checkTauTvUpdate"
1384 (tcView (TyConApp tc tys)))
1385 -- Try again, expanding the synonym
1388 fillBoxWithTau :: BoxyTyVar -> IORef MetaDetails -> TcM TcType
1389 -- (fillBoxWithTau tv ref) fills ref with a freshly allocated
1390 -- tau-type meta-variable, whose print-name is the same as tv
1391 -- Choosing the same name is good: when we instantiate a function
1392 -- we allocate boxy tyvars with the same print-name as the quantified
1393 -- tyvar; and then we often fill the box with a tau-tyvar, and again
1394 -- we want to choose the same name.
1395 fillBoxWithTau tv ref
1396 = do { tv' <- tcInstTyVar tv -- Do not gratuitously forget
1397 ; let tau = mkTyVarTy tv' -- name of the type variable
1398 ; writeMutVar ref (Indirect tau)
1402 Note [Type synonyms and the occur check]
1403 ~~~~~~~~~~~~~~~~~~~~
1404 Basically we want to update tv1 := ps_ty2
1405 because ps_ty2 has type-synonym info, which improves later error messages
1410 f :: (A a -> a -> ()) -> ()
1414 x = f (\ x p -> p x)
1416 In the application (p x), we try to match "t" with "A t". If we go
1417 ahead and bind t to A t (= ps_ty2), we'll lead the type checker into
1418 an infinite loop later.
1419 But we should not reject the program, because A t = ().
1420 Rather, we should bind t to () (= non_var_ty2).
1423 refineBox :: TcType -> TcM TcType
1424 -- Unbox the outer box of a boxy type (if any)
1425 refineBox ty@(TyVarTy box_tv)
1426 | isMetaTyVar box_tv
1427 = do { cts <- readMetaTyVar box_tv
1430 Indirect ty -> return ty }
1431 refineBox other_ty = return other_ty
1433 refineBoxToTau :: TcType -> TcM TcType
1434 -- Unbox the outer box of a boxy type, filling with a monotype if it is empty
1435 -- Like refineBox except for the "fill with monotype" part.
1436 refineBoxToTau ty@(TyVarTy box_tv)
1437 | isMetaTyVar box_tv
1438 , MetaTv BoxTv ref <- tcTyVarDetails box_tv
1439 = do { cts <- readMutVar ref
1441 Flexi -> fillBoxWithTau box_tv ref
1442 Indirect ty -> return ty }
1443 refineBoxToTau other_ty = return other_ty
1445 zapToMonotype :: BoxySigmaType -> TcM TcTauType
1446 -- Subtle... we must zap the boxy res_ty
1447 -- to kind * before using it to instantiate a LitInst
1448 -- Calling unBox instead doesn't do the job, because the box
1449 -- often has an openTypeKind, and we don't want to instantiate
1451 zapToMonotype res_ty
1452 = do { res_tau <- newFlexiTyVarTy liftedTypeKind
1453 ; boxyUnify res_tau res_ty
1456 unBox :: BoxyType -> TcM TcType
1457 -- unBox implements the judgement
1459 -- with input s', and result s
1461 -- It removes all boxes from the input type, returning a non-boxy type.
1462 -- A filled box in the type can only contain a monotype; unBox fails if not
1463 -- The type can have empty boxes, which unBox fills with a monotype
1465 -- Compare this wth checkTauTvUpdate
1467 -- For once, it's safe to treat synonyms as opaque!
1469 unBox (NoteTy n ty) = do { ty' <- unBox ty; return (NoteTy n ty') }
1470 unBox (TyConApp tc tys) = do { tys' <- mapM unBox tys; return (TyConApp tc tys') }
1471 unBox (AppTy f a) = do { f' <- unBox f; a' <- unBox a; return (mkAppTy f' a') }
1472 unBox (FunTy f a) = do { f' <- unBox f; a' <- unBox a; return (FunTy f' a') }
1473 unBox (PredTy p) = do { p' <- unBoxPred p; return (PredTy p') }
1474 unBox (ForAllTy tv ty) = ASSERT( isImmutableTyVar tv )
1475 do { ty' <- unBox ty; return (ForAllTy tv ty') }
1477 | isTcTyVar tv -- It's a boxy type variable
1478 , MetaTv BoxTv ref <- tcTyVarDetails tv -- NB: non-TcTyVars are possible
1479 = do { cts <- readMutVar ref -- under nested quantifiers
1481 Flexi -> fillBoxWithTau tv ref
1482 Indirect ty -> do { non_boxy_ty <- unBox ty
1483 ; if isTauTy non_boxy_ty
1484 then return non_boxy_ty
1485 else notMonoType non_boxy_ty }
1487 | otherwise -- Skolems, and meta-tau-variables
1488 = return (TyVarTy tv)
1490 unBoxPred (ClassP cls tys) = do { tys' <- mapM unBox tys; return (ClassP cls tys') }
1491 unBoxPred (IParam ip ty) = do { ty' <- unBox ty; return (IParam ip ty') }
1492 unBoxPred (EqPred ty1 ty2) = do { ty1' <- unBox ty1; ty2' <- unBox ty2; return (EqPred ty1' ty2') }
1497 %************************************************************************
1499 \subsection[Unify-context]{Errors and contexts}
1501 %************************************************************************
1507 unifyCtxt act_ty exp_ty tidy_env
1508 = do { act_ty' <- zonkTcType act_ty
1509 ; exp_ty' <- zonkTcType exp_ty
1510 ; let (env1, exp_ty'') = tidyOpenType tidy_env exp_ty'
1511 (env2, act_ty'') = tidyOpenType env1 act_ty'
1512 ; return (env2, mkExpectedActualMsg act_ty'' exp_ty'') }
1515 mkExpectedActualMsg act_ty exp_ty
1516 = nest 2 (vcat [ text "Expected type" <> colon <+> ppr exp_ty,
1517 text "Inferred type" <> colon <+> ppr act_ty ])
1520 -- If an error happens we try to figure out whether the function
1521 -- function has been given too many or too few arguments, and say so.
1522 addSubCtxt SubDone actual_res_ty expected_res_ty thing_inside
1524 addSubCtxt sub_ctxt actual_res_ty expected_res_ty thing_inside
1525 = addErrCtxtM mk_err thing_inside
1528 = do { exp_ty' <- zonkTcType expected_res_ty
1529 ; act_ty' <- zonkTcType actual_res_ty
1530 ; let (env1, exp_ty'') = tidyOpenType tidy_env exp_ty'
1531 (env2, act_ty'') = tidyOpenType env1 act_ty'
1532 (exp_args, _) = tcSplitFunTys exp_ty''
1533 (act_args, _) = tcSplitFunTys act_ty''
1535 len_act_args = length act_args
1536 len_exp_args = length exp_args
1538 message = case sub_ctxt of
1539 SubFun fun | len_exp_args < len_act_args -> wrongArgsCtxt "too few" fun
1540 | len_exp_args > len_act_args -> wrongArgsCtxt "too many" fun
1541 other -> mkExpectedActualMsg act_ty'' exp_ty''
1542 ; return (env2, message) }
1544 wrongArgsCtxt too_many_or_few fun
1545 = ptext SLIT("Probable cause:") <+> quotes (ppr fun)
1546 <+> ptext SLIT("is applied to") <+> text too_many_or_few
1547 <+> ptext SLIT("arguments")
1550 unifyForAllCtxt tvs phi1 phi2 env
1551 = returnM (env2, msg)
1553 (env', tvs') = tidyOpenTyVars env tvs -- NB: not tidyTyVarBndrs
1554 (env1, phi1') = tidyOpenType env' phi1
1555 (env2, phi2') = tidyOpenType env1 phi2
1556 msg = vcat [ptext SLIT("When matching") <+> quotes (ppr (mkForAllTys tvs' phi1')),
1557 ptext SLIT(" and") <+> quotes (ppr (mkForAllTys tvs' phi2'))]
1560 unifyKindCtxt swapped tv1 ty2 tidy_env -- not swapped => tv1 expected, ty2 inferred
1561 -- tv1 and ty2 are zonked already
1564 msg = (env2, ptext SLIT("When matching the kinds of") <+>
1565 sep [quotes pp_expected <+> ptext SLIT("and"), quotes pp_actual])
1567 (pp_expected, pp_actual) | swapped = (pp2, pp1)
1568 | otherwise = (pp1, pp2)
1569 (env1, tv1') = tidyOpenTyVar tidy_env tv1
1570 (env2, ty2') = tidyOpenType env1 ty2
1571 pp1 = ppr tv1' <+> dcolon <+> ppr (tyVarKind tv1)
1572 pp2 = ppr ty2' <+> dcolon <+> ppr (typeKind ty2)
1574 unifyMisMatch outer swapped ty1 ty2
1575 = do { (env, msg) <- if swapped then misMatchMsg ty1 ty2
1576 else misMatchMsg ty2 ty1
1578 -- This is the whole point of the 'outer' stuff
1579 ; if outer then popErrCtxt (failWithTcM (env, msg))
1580 else failWithTcM (env, msg)
1584 = do { env0 <- tcInitTidyEnv
1585 ; (env1, pp1, extra1) <- ppr_ty env0 ty1
1586 ; (env2, pp2, extra2) <- ppr_ty env1 ty2
1587 ; return (env2, sep [sep [ptext SLIT("Couldn't match expected type") <+> pp1,
1588 nest 7 (ptext SLIT("against inferred type") <+> pp2)],
1589 nest 2 extra1, nest 2 extra2]) }
1591 ppr_ty :: TidyEnv -> TcType -> TcM (TidyEnv, SDoc, SDoc)
1593 = do { ty' <- zonkTcType ty
1594 ; let (env1,tidy_ty) = tidyOpenType env ty'
1595 simple_result = (env1, quotes (ppr tidy_ty), empty)
1598 | isSkolemTyVar tv || isSigTyVar tv
1599 -> return (env2, pp_rigid tv', pprSkolTvBinding tv')
1600 | otherwise -> return simple_result
1602 (env2, tv') = tidySkolemTyVar env1 tv
1603 other -> return simple_result }
1605 pp_rigid tv = quotes (ppr tv) <+> parens (ptext SLIT("a rigid variable"))
1609 = do { ty' <- zonkTcType ty
1610 ; env0 <- tcInitTidyEnv
1611 ; let (env1, tidy_ty) = tidyOpenType env0 ty'
1612 msg = ptext SLIT("Cannot match a monotype with") <+> quotes (ppr tidy_ty)
1613 ; failWithTcM (env1, msg) }
1616 = do { ty' <- zonkTcType ty
1617 ; env0 <- tcInitTidyEnv
1618 ; let (env1, tidy_ty) = tidyOpenType env0 ty'
1619 msg = ptext SLIT("Arguments of synonym family must be monotypes") <+> quotes (ppr tidy_ty)
1620 ; failWithTcM (env1, msg) }
1623 = do { env0 <- tcInitTidyEnv
1624 ; ty' <- zonkTcType ty
1625 ; let (env1, tidy_tyvar) = tidyOpenTyVar env0 tyvar
1626 (env2, tidy_ty) = tidyOpenType env1 ty'
1627 extra = sep [ppr tidy_tyvar, char '=', ppr tidy_ty]
1628 ; failWithTcM (env2, hang msg 2 extra) }
1630 msg = ptext SLIT("Occurs check: cannot construct the infinite type:")
1634 %************************************************************************
1638 %************************************************************************
1640 Unifying kinds is much, much simpler than unifying types.
1643 unifyKind :: TcKind -- Expected
1646 unifyKind (TyConApp kc1 []) (TyConApp kc2 [])
1647 | isSubKindCon kc2 kc1 = returnM ()
1649 unifyKind (FunTy a1 r1) (FunTy a2 r2)
1650 = do { unifyKind a2 a1; unifyKind r1 r2 }
1651 -- Notice the flip in the argument,
1652 -- so that the sub-kinding works right
1653 unifyKind (TyVarTy kv1) k2 = uKVar False kv1 k2
1654 unifyKind k1 (TyVarTy kv2) = uKVar True kv2 k1
1655 unifyKind k1 k2 = unifyKindMisMatch k1 k2
1657 unifyKinds :: [TcKind] -> [TcKind] -> TcM ()
1658 unifyKinds [] [] = returnM ()
1659 unifyKinds (k1:ks1) (k2:ks2) = unifyKind k1 k2 `thenM_`
1661 unifyKinds _ _ = panic "unifyKinds: length mis-match"
1664 uKVar :: Bool -> KindVar -> TcKind -> TcM ()
1665 uKVar swapped kv1 k2
1666 = do { mb_k1 <- readKindVar kv1
1668 Flexi -> uUnboundKVar swapped kv1 k2
1669 Indirect k1 | swapped -> unifyKind k2 k1
1670 | otherwise -> unifyKind k1 k2 }
1673 uUnboundKVar :: Bool -> KindVar -> TcKind -> TcM ()
1674 uUnboundKVar swapped kv1 k2@(TyVarTy kv2)
1675 | kv1 == kv2 = returnM ()
1676 | otherwise -- Distinct kind variables
1677 = do { mb_k2 <- readKindVar kv2
1679 Indirect k2 -> uUnboundKVar swapped kv1 k2
1680 Flexi -> writeKindVar kv1 k2 }
1682 uUnboundKVar swapped kv1 non_var_k2
1683 = do { k2' <- zonkTcKind non_var_k2
1684 ; kindOccurCheck kv1 k2'
1685 ; k2'' <- kindSimpleKind swapped k2'
1686 -- KindVars must be bound only to simple kinds
1687 -- Polarities: (kindSimpleKind True ?) succeeds
1688 -- returning *, corresponding to unifying
1691 ; writeKindVar kv1 k2'' }
1694 kindOccurCheck kv1 k2 -- k2 is zonked
1695 = checkTc (not_in k2) (kindOccurCheckErr kv1 k2)
1697 not_in (TyVarTy kv2) = kv1 /= kv2
1698 not_in (FunTy a2 r2) = not_in a2 && not_in r2
1701 kindSimpleKind :: Bool -> Kind -> TcM SimpleKind
1702 -- (kindSimpleKind True k) returns a simple kind sk such that sk <: k
1703 -- If the flag is False, it requires k <: sk
1704 -- E.g. kindSimpleKind False ?? = *
1705 -- What about (kv -> *) :=: ?? -> *
1706 kindSimpleKind orig_swapped orig_kind
1707 = go orig_swapped orig_kind
1709 go sw (FunTy k1 k2) = do { k1' <- go (not sw) k1
1711 ; return (mkArrowKind k1' k2') }
1713 | isOpenTypeKind k = return liftedTypeKind
1714 | isArgTypeKind k = return liftedTypeKind
1716 | isLiftedTypeKind k = return liftedTypeKind
1717 | isUnliftedTypeKind k = return unliftedTypeKind
1718 go sw k@(TyVarTy _) = return k -- KindVars are always simple
1719 go swapped kind = failWithTc (ptext SLIT("Unexpected kind unification failure:")
1720 <+> ppr orig_swapped <+> ppr orig_kind)
1721 -- I think this can't actually happen
1723 -- T v = MkT v v must be a type
1724 -- T v w = MkT (v -> w) v must not be an umboxed tuple
1727 kindOccurCheckErr tyvar ty
1728 = hang (ptext SLIT("Occurs check: cannot construct the infinite kind:"))
1729 2 (sep [ppr tyvar, char '=', ppr ty])
1731 unifyKindMisMatch ty1 ty2
1732 = zonkTcKind ty1 `thenM` \ ty1' ->
1733 zonkTcKind ty2 `thenM` \ ty2' ->
1735 msg = hang (ptext SLIT("Couldn't match kind"))
1736 2 (sep [quotes (ppr ty1'),
1737 ptext SLIT("against"),
1744 unifyFunKind :: TcKind -> TcM (Maybe (TcKind, TcKind))
1745 -- Like unifyFunTy, but does not fail; instead just returns Nothing
1747 unifyFunKind (TyVarTy kvar)
1748 = readKindVar kvar `thenM` \ maybe_kind ->
1750 Indirect fun_kind -> unifyFunKind fun_kind
1752 do { arg_kind <- newKindVar
1753 ; res_kind <- newKindVar
1754 ; writeKindVar kvar (mkArrowKind arg_kind res_kind)
1755 ; returnM (Just (arg_kind,res_kind)) }
1757 unifyFunKind (FunTy arg_kind res_kind) = returnM (Just (arg_kind,res_kind))
1758 unifyFunKind other = returnM Nothing
1761 %************************************************************************
1765 %************************************************************************
1767 ---------------------------
1768 -- We would like to get a decent error message from
1769 -- (a) Under-applied type constructors
1770 -- f :: (Maybe, Maybe)
1771 -- (b) Over-applied type constructors
1772 -- f :: Int x -> Int x
1776 checkExpectedKind :: Outputable a => a -> TcKind -> TcKind -> TcM ()
1777 -- A fancy wrapper for 'unifyKind', which tries
1778 -- to give decent error messages.
1779 checkExpectedKind ty act_kind exp_kind
1780 | act_kind `isSubKind` exp_kind -- Short cut for a very common case
1783 = tryTc (unifyKind exp_kind act_kind) `thenM` \ (_errs, mb_r) ->
1785 Just r -> returnM () ; -- Unification succeeded
1788 -- So there's definitely an error
1789 -- Now to find out what sort
1790 zonkTcKind exp_kind `thenM` \ exp_kind ->
1791 zonkTcKind act_kind `thenM` \ act_kind ->
1793 tcInitTidyEnv `thenM` \ env0 ->
1794 let (exp_as, _) = splitKindFunTys exp_kind
1795 (act_as, _) = splitKindFunTys act_kind
1796 n_exp_as = length exp_as
1797 n_act_as = length act_as
1799 (env1, tidy_exp_kind) = tidyKind env0 exp_kind
1800 (env2, tidy_act_kind) = tidyKind env1 act_kind
1802 err | n_exp_as < n_act_as -- E.g. [Maybe]
1803 = quotes (ppr ty) <+> ptext SLIT("is not applied to enough type arguments")
1805 -- Now n_exp_as >= n_act_as. In the next two cases,
1806 -- n_exp_as == 0, and hence so is n_act_as
1807 | isLiftedTypeKind exp_kind && isUnliftedTypeKind act_kind
1808 = ptext SLIT("Expecting a lifted type, but") <+> quotes (ppr ty)
1809 <+> ptext SLIT("is unlifted")
1811 | isUnliftedTypeKind exp_kind && isLiftedTypeKind act_kind
1812 = ptext SLIT("Expecting an unlifted type, but") <+> quotes (ppr ty)
1813 <+> ptext SLIT("is lifted")
1815 | otherwise -- E.g. Monad [Int]
1816 = ptext SLIT("Kind mis-match")
1818 more_info = sep [ ptext SLIT("Expected kind") <+>
1819 quotes (pprKind tidy_exp_kind) <> comma,
1820 ptext SLIT("but") <+> quotes (ppr ty) <+>
1821 ptext SLIT("has kind") <+> quotes (pprKind tidy_act_kind)]
1823 failWithTcM (env2, err $$ more_info)
1827 %************************************************************************
1829 \subsection{Checking signature type variables}
1831 %************************************************************************
1833 @checkSigTyVars@ checks that a set of universally quantified type varaibles
1834 are not mentioned in the environment. In particular:
1836 (a) Not mentioned in the type of a variable in the envt
1837 eg the signature for f in this:
1843 Here, f is forced to be monorphic by the free occurence of x.
1845 (d) Not (unified with another type variable that is) in scope.
1846 eg f x :: (r->r) = (\y->y) :: forall a. a->r
1847 when checking the expression type signature, we find that
1848 even though there is nothing in scope whose type mentions r,
1849 nevertheless the type signature for the expression isn't right.
1851 Another example is in a class or instance declaration:
1853 op :: forall b. a -> b
1855 Here, b gets unified with a
1857 Before doing this, the substitution is applied to the signature type variable.
1860 checkSigTyVars :: [TcTyVar] -> TcM ()
1861 checkSigTyVars sig_tvs = check_sig_tyvars emptyVarSet sig_tvs
1863 checkSigTyVarsWrt :: TcTyVarSet -> [TcTyVar] -> TcM ()
1864 -- The extra_tvs can include boxy type variables;
1865 -- e.g. TcMatches.tcCheckExistentialPat
1866 checkSigTyVarsWrt extra_tvs sig_tvs
1867 = do { extra_tvs' <- zonkTcTyVarsAndFV (varSetElems extra_tvs)
1868 ; check_sig_tyvars extra_tvs' sig_tvs }
1871 :: TcTyVarSet -- Global type variables. The universally quantified
1872 -- tyvars should not mention any of these
1873 -- Guaranteed already zonked.
1874 -> [TcTyVar] -- Universally-quantified type variables in the signature
1875 -- Guaranteed to be skolems
1877 check_sig_tyvars extra_tvs []
1879 check_sig_tyvars extra_tvs sig_tvs
1880 = ASSERT( all isSkolemTyVar sig_tvs )
1881 do { gbl_tvs <- tcGetGlobalTyVars
1882 ; traceTc (text "check_sig_tyvars" <+> (vcat [text "sig_tys" <+> ppr sig_tvs,
1883 text "gbl_tvs" <+> ppr gbl_tvs,
1884 text "extra_tvs" <+> ppr extra_tvs]))
1886 ; let env_tvs = gbl_tvs `unionVarSet` extra_tvs
1887 ; ifM (any (`elemVarSet` env_tvs) sig_tvs)
1888 (bleatEscapedTvs env_tvs sig_tvs sig_tvs)
1891 bleatEscapedTvs :: TcTyVarSet -- The global tvs
1892 -> [TcTyVar] -- The possibly-escaping type variables
1893 -> [TcTyVar] -- The zonked versions thereof
1895 -- Complain about escaping type variables
1896 -- We pass a list of type variables, at least one of which
1897 -- escapes. The first list contains the original signature type variable,
1898 -- while the second contains the type variable it is unified to (usually itself)
1899 bleatEscapedTvs globals sig_tvs zonked_tvs
1900 = do { env0 <- tcInitTidyEnv
1901 ; let (env1, tidy_tvs) = tidyOpenTyVars env0 sig_tvs
1902 (env2, tidy_zonked_tvs) = tidyOpenTyVars env1 zonked_tvs
1904 ; (env3, msgs) <- foldlM check (env2, []) (tidy_tvs `zip` tidy_zonked_tvs)
1905 ; failWithTcM (env3, main_msg $$ nest 2 (vcat msgs)) }
1907 main_msg = ptext SLIT("Inferred type is less polymorphic than expected")
1909 check (tidy_env, msgs) (sig_tv, zonked_tv)
1910 | not (zonked_tv `elemVarSet` globals) = return (tidy_env, msgs)
1912 = do { (tidy_env1, globs) <- findGlobals (unitVarSet zonked_tv) tidy_env
1913 ; returnM (tidy_env1, escape_msg sig_tv zonked_tv globs : msgs) }
1915 -----------------------
1916 escape_msg sig_tv zonked_tv globs
1918 = vcat [sep [msg, ptext SLIT("is mentioned in the environment:")],
1919 nest 2 (vcat globs)]
1921 = msg <+> ptext SLIT("escapes")
1922 -- Sigh. It's really hard to give a good error message
1923 -- all the time. One bad case is an existential pattern match.
1924 -- We rely on the "When..." context to help.
1926 msg = ptext SLIT("Quantified type variable") <+> quotes (ppr sig_tv) <+> is_bound_to
1928 | sig_tv == zonked_tv = empty
1929 | otherwise = ptext SLIT("is unified with") <+> quotes (ppr zonked_tv) <+> ptext SLIT("which")
1932 These two context are used with checkSigTyVars
1935 sigCtxt :: Id -> [TcTyVar] -> TcThetaType -> TcTauType
1936 -> TidyEnv -> TcM (TidyEnv, Message)
1937 sigCtxt id sig_tvs sig_theta sig_tau tidy_env
1938 = zonkTcType sig_tau `thenM` \ actual_tau ->
1940 (env1, tidy_sig_tvs) = tidyOpenTyVars tidy_env sig_tvs
1941 (env2, tidy_sig_rho) = tidyOpenType env1 (mkPhiTy sig_theta sig_tau)
1942 (env3, tidy_actual_tau) = tidyOpenType env2 actual_tau
1943 sub_msg = vcat [ptext SLIT("Signature type: ") <+> pprType (mkForAllTys tidy_sig_tvs tidy_sig_rho),
1944 ptext SLIT("Type to generalise:") <+> pprType tidy_actual_tau
1946 msg = vcat [ptext SLIT("When trying to generalise the type inferred for") <+> quotes (ppr id),