2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
6 Type subsumption and unification
10 -- The above warning supression flag is a temporary kludge.
11 -- While working on this module you are encouraged to remove it and fix
12 -- any warnings in the module. See
13 -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
17 -- Full-blown subsumption
19 checkSigTyVars, checkSigTyVarsWrt, bleatEscapedTvs, sigCtxt,
21 -- Various unifications
22 unifyType, unifyTypeList, unifyTheta,
23 unifyKind, unifyKinds, unifyFunKind,
25 preSubType, boxyMatchTypes,
27 --------------------------------
29 tcInfer, subFunTys, unBox, refineBox, refineBoxToTau, withBox,
30 boxyUnify, boxyUnifyList, zapToMonotype,
31 boxySplitListTy, boxySplitPArrTy, boxySplitTyConApp, boxySplitAppTy,
35 #include "HsVersions.h"
45 import TcRnMonad -- TcType, amongst others
68 %************************************************************************
70 \subsection{'hole' type variables}
72 %************************************************************************
75 tcInfer :: (BoxyType -> TcM a) -> TcM (a, TcType)
76 tcInfer tc_infer = withBox openTypeKind tc_infer
80 %************************************************************************
84 %************************************************************************
87 subFunTys :: SDoc -- Somthing like "The function f has 3 arguments"
88 -- or "The abstraction (\x.e) takes 1 argument"
89 -> Arity -- Expected # of args
90 -> BoxyRhoType -- res_ty
91 -> ([BoxySigmaType] -> BoxyRhoType -> TcM a)
93 -- Attempt to decompse res_ty to have enough top-level arrows to
94 -- match the number of patterns in the match group
96 -- If (subFunTys n_args res_ty thing_inside) = (co_fn, res)
97 -- and the inner call to thing_inside passes args: [a1,...,an], b
98 -- then co_fn :: (a1 -> ... -> an -> b) ~ res_ty
100 -- Note that it takes a BoxyRho type, and guarantees to return a BoxyRhoType
103 {- Error messages from subFunTys
105 The abstraction `\Just 1 -> ...' has two arguments
106 but its type `Maybe a -> a' has only one
108 The equation(s) for `f' have two arguments
109 but its type `Maybe a -> a' has only one
111 The section `(f 3)' requires 'f' to take two arguments
112 but its type `Int -> Int' has only one
114 The function 'f' is applied to two arguments
115 but its type `Int -> Int' has only one
119 subFunTys error_herald n_pats res_ty thing_inside
120 = loop n_pats [] res_ty
122 -- In 'loop', the parameter 'arg_tys' accumulates
123 -- the arg types so far, in *reverse order*
124 -- INVARIANT: res_ty :: *
125 loop n args_so_far res_ty
126 | Just res_ty' <- tcView res_ty = loop n args_so_far res_ty'
128 loop n args_so_far res_ty
129 | isSigmaTy res_ty -- Do this before checking n==0, because we
130 -- guarantee to return a BoxyRhoType, not a
132 = do { (gen_fn, (co_fn, res)) <- tcGen res_ty emptyVarSet $ \ _ res_ty' ->
133 loop n args_so_far res_ty'
134 ; return (gen_fn <.> co_fn, res) }
136 loop 0 args_so_far res_ty
137 = do { res <- thing_inside (reverse args_so_far) res_ty
138 ; return (idHsWrapper, res) }
140 loop n args_so_far (FunTy arg_ty res_ty)
141 = do { (co_fn, res) <- loop (n-1) (arg_ty:args_so_far) res_ty
142 ; co_fn' <- wrapFunResCoercion [arg_ty] co_fn
143 ; return (co_fn', res) }
145 -- Try to normalise synonym families and defer if that's not possible
146 loop n args_so_far ty@(TyConApp tc tys)
148 = do { (coi1, ty') <- tcNormaliseFamInst ty
150 IdCo -> defer n args_so_far ty
151 -- no progress, but maybe solvable => defer
152 ACo _ -> -- progress: so lets try again
153 do { (co_fn, res) <- loop n args_so_far ty'
154 ; return $ (co_fn <.> coiToHsWrapper (mkSymCoI coi1), res)
158 -- res_ty might have a type variable at the head, such as (a b c),
159 -- in which case we must fill in with (->). Simplest thing to do
160 -- is to use boxyUnify, but we catch failure and generate our own
161 -- error message on failure
162 loop n args_so_far res_ty@(AppTy _ _)
163 = do { [arg_ty',res_ty'] <- newBoxyTyVarTys [argTypeKind, openTypeKind]
164 ; (_, mb_coi) <- tryTcErrs $
165 boxyUnify res_ty (FunTy arg_ty' res_ty')
166 ; if isNothing mb_coi then bale_out args_so_far
167 else do { let coi = expectJust "subFunTys" mb_coi
168 ; (co_fn, res) <- loop n args_so_far (FunTy arg_ty'
170 ; return (co_fn <.> coiToHsWrapper coi, res)
174 loop n args_so_far ty@(TyVarTy tv)
175 | isTyConableTyVar tv
176 = do { cts <- readMetaTyVar tv
178 Indirect ty -> loop n args_so_far ty
180 do { (res_ty:arg_tys) <- withMetaTvs tv kinds mk_res_ty
181 ; res <- thing_inside (reverse args_so_far ++ arg_tys)
183 ; return (idHsWrapper, res) } }
184 | otherwise -- defer as tyvar may be refined by equalities
185 = defer n args_so_far ty
187 mk_res_ty (res_ty' : arg_tys') = mkFunTys arg_tys' res_ty'
188 mk_res_ty [] = panic "TcUnify.mk_res_ty1"
189 kinds = openTypeKind : take n (repeat argTypeKind)
190 -- Note argTypeKind: the args can have an unboxed type,
191 -- but not an unboxed tuple.
193 loop n args_so_far res_ty = bale_out args_so_far
195 -- Build a template type a1 -> ... -> an -> b and defer an equality
196 -- between that template and the expected result type res_ty; then,
197 -- use the template to type the thing_inside
198 defer n args_so_far ty
199 = do { arg_tys <- newFlexiTyVarTys n argTypeKind
200 ; res_ty' <- newFlexiTyVarTy openTypeKind
201 ; let fun_ty = mkFunTys arg_tys res_ty'
202 err = error_herald <> comma $$
203 text "which does not match its type"
204 ; coi <- addErrCtxt err $
205 defer_unification (Unify False fun_ty ty) False fun_ty ty
206 ; res <- thing_inside (reverse args_so_far ++ arg_tys) res_ty'
207 ; return (coiToHsWrapper coi, res)
211 = do { env0 <- tcInitTidyEnv
212 ; res_ty' <- zonkTcType res_ty
213 ; let (env1, res_ty'') = tidyOpenType env0 res_ty'
214 ; failWithTcM (env1, mk_msg res_ty'' (length args_so_far)) }
216 mk_msg res_ty n_actual
217 = error_herald <> comma $$
218 sep [ptext (sLit "but its type") <+> quotes (pprType res_ty),
219 if n_actual == 0 then ptext (sLit "has none")
220 else ptext (sLit "has only") <+> speakN n_actual]
224 ----------------------
225 boxySplitTyConApp :: TyCon -- T :: k1 -> ... -> kn -> *
226 -> BoxyRhoType -- Expected type (T a b c)
227 -> TcM ([BoxySigmaType], -- Element types, a b c
228 CoercionI) -- T a b c ~ orig_ty
229 -- It's used for wired-in tycons, so we call checkWiredInTyCon
230 -- Precondition: never called with FunTyCon
231 -- Precondition: input type :: *
233 boxySplitTyConApp tc orig_ty
234 = do { checkWiredInTyCon tc
235 ; loop (tyConArity tc) [] orig_ty }
237 loop n_req args_so_far ty
238 | Just ty' <- tcView ty = loop n_req args_so_far ty'
240 loop n_req args_so_far ty@(TyConApp tycon args)
242 = ASSERT( n_req == length args) -- ty::*
243 return (args ++ args_so_far, IdCo)
245 | isOpenSynTyCon tycon -- try to normalise type family application
246 = do { (coi1, ty') <- tcNormaliseFamInst ty
247 ; traceTc $ text "boxySplitTyConApp:" <+>
248 ppr ty <+> text "==>" <+> ppr ty'
250 IdCo -> defer -- no progress, but maybe solvable => defer
251 ACo _ -> -- progress: so lets try again
252 do { (args, coi2) <- loop n_req args_so_far ty'
253 ; return $ (args, coi2 `mkTransCoI` mkSymCoI coi1)
257 loop n_req args_so_far (AppTy fun arg)
259 = do { (args, coi) <- loop (n_req - 1) (arg:args_so_far) fun
260 ; return (args, mkAppTyCoI fun coi arg IdCo)
263 loop n_req args_so_far (TyVarTy tv)
264 | isTyConableTyVar tv
265 , res_kind `isSubKind` tyVarKind tv
266 = do { cts <- readMetaTyVar tv
268 Indirect ty -> loop n_req args_so_far ty
269 Flexi -> do { arg_tys <- withMetaTvs tv arg_kinds mk_res_ty
270 ; return (arg_tys ++ args_so_far, IdCo) }
272 | otherwise -- defer as tyvar may be refined by equalities
275 (arg_kinds, res_kind) = splitKindFunTysN n_req (tyConKind tc)
277 loop _ _ _ = boxySplitFailure (mkTyConApp tc (mkTyVarTys (tyConTyVars tc)))
280 -- defer splitting by generating an equality constraint
281 defer = boxySplitDefer arg_kinds mk_res_ty orig_ty
283 (arg_kinds, _) = splitKindFunTys (tyConKind tc)
285 -- apply splitted tycon to arguments
286 mk_res_ty = mkTyConApp tc
288 ----------------------
289 boxySplitListTy :: BoxyRhoType -> TcM (BoxySigmaType, CoercionI)
290 -- Special case for lists
291 boxySplitListTy exp_ty
292 = do { ([elt_ty], coi) <- boxySplitTyConApp listTyCon exp_ty
293 ; return (elt_ty, coi) }
295 ----------------------
296 boxySplitPArrTy :: BoxyRhoType -> TcM (BoxySigmaType, CoercionI)
297 -- Special case for parrs
298 boxySplitPArrTy exp_ty
299 = do { ([elt_ty], coi) <- boxySplitTyConApp parrTyCon exp_ty
300 ; return (elt_ty, coi) }
302 ----------------------
303 boxySplitAppTy :: BoxyRhoType -- Type to split: m a
304 -> TcM ((BoxySigmaType, BoxySigmaType), -- Returns m, a
306 -- If the incoming type is a mutable type variable of kind k, then
307 -- boxySplitAppTy returns a new type variable (m: * -> k); note the *.
308 -- If the incoming type is boxy, then so are the result types; and vice versa
310 boxySplitAppTy orig_ty
314 | Just ty' <- tcView ty = loop ty'
317 | Just (fun_ty, arg_ty) <- tcSplitAppTy_maybe ty
318 = return ((fun_ty, arg_ty), IdCo)
320 loop ty@(TyConApp tycon _args)
321 | isOpenSynTyCon tycon -- try to normalise type family application
322 = do { (coi1, ty') <- tcNormaliseFamInst ty
324 IdCo -> defer -- no progress, but maybe solvable => defer
325 ACo co -> -- progress: so lets try again
326 do { (args, coi2) <- loop ty'
327 ; return $ (args, coi2 `mkTransCoI` mkSymCoI coi1)
332 | isTyConableTyVar tv
333 = do { cts <- readMetaTyVar tv
335 Indirect ty -> loop ty
336 Flexi -> do { [fun_ty, arg_ty] <- withMetaTvs tv kinds mk_res_ty
337 ; return ((fun_ty, arg_ty), IdCo) } }
338 | otherwise -- defer as tyvar may be refined by equalities
341 tv_kind = tyVarKind tv
342 kinds = [mkArrowKind liftedTypeKind (defaultKind tv_kind),
344 liftedTypeKind] -- arg type :: *
345 -- The defaultKind is a bit smelly. If you remove it,
346 -- try compiling f x = do { x }
347 -- and you'll get a kind mis-match. It smells, but
348 -- not enough to lose sleep over.
350 loop _ = boxySplitFailure (mkAppTy alphaTy betaTy) orig_ty
352 -- defer splitting by generating an equality constraint
353 defer = do { ([ty1, ty2], coi) <- boxySplitDefer arg_kinds mk_res_ty orig_ty
354 ; return ((ty1, ty2), coi)
357 orig_kind = typeKind orig_ty
358 arg_kinds = [mkArrowKind liftedTypeKind (defaultKind orig_kind),
360 liftedTypeKind] -- arg type :: *
362 -- build type application
363 mk_res_ty [fun_ty', arg_ty'] = mkAppTy fun_ty' arg_ty'
364 mk_res_ty _other = panic "TcUnify.mk_res_ty2"
367 boxySplitFailure actual_ty expected_ty = failWithMisMatch actual_ty expected_ty
370 boxySplitDefer :: [Kind] -- kinds of required arguments
371 -> ([TcType] -> TcTauType) -- construct lhs from argument tyvars
372 -> BoxyRhoType -- type to split
373 -> TcM ([TcType], CoercionI)
374 boxySplitDefer kinds mk_ty orig_ty
375 = do { tau_tys <- mapM newFlexiTyVarTy kinds
376 ; let ty1 = mk_ty tau_tys
377 ; coi <- defer_unification (Unify False ty1 orig_ty) False ty1 orig_ty
378 ; return (tau_tys, coi)
383 --------------------------------
384 -- withBoxes: the key utility function
385 --------------------------------
388 withMetaTvs :: TcTyVar -- An unfilled-in, non-skolem, meta type variable
389 -> [Kind] -- Make fresh boxes (with the same BoxTv/TauTv setting as tv)
390 -> ([BoxySigmaType] -> BoxySigmaType)
391 -- Constructs the type to assign
392 -- to the original var
393 -> TcM [BoxySigmaType] -- Return the fresh boxes
395 -- It's entirely possible for the [kind] to be empty.
396 -- For example, when pattern-matching on True,
397 -- we call boxySplitTyConApp passing a boolTyCon
399 -- Invariant: tv is still Flexi
401 withMetaTvs tv kinds mk_res_ty
403 = do { box_tvs <- mapM (newMetaTyVar BoxTv) kinds
404 ; let box_tys = mkTyVarTys box_tvs
405 ; writeMetaTyVar tv (mk_res_ty box_tys)
408 | otherwise -- Non-boxy meta type variable
409 = do { tau_tys <- mapM newFlexiTyVarTy kinds
410 ; writeMetaTyVar tv (mk_res_ty tau_tys) -- Write it *first*
411 -- Sure to be a tau-type
414 withBox :: Kind -> (BoxySigmaType -> TcM a) -> TcM (a, TcType)
415 -- Allocate a *boxy* tyvar
416 withBox kind thing_inside
417 = do { box_tv <- newBoxyTyVar kind
418 ; res <- thing_inside (mkTyVarTy box_tv)
419 ; ty <- {- pprTrace "with_box" (ppr (mkTyVarTy box_tv)) $ -} readFilledBox box_tv
424 %************************************************************************
426 Approximate boxy matching
428 %************************************************************************
431 preSubType :: [TcTyVar] -- Quantified type variables
432 -> TcTyVarSet -- Subset of quantified type variables
433 -- see Note [Pre-sub boxy]
434 -> TcType -- The rho-type part; quantified tyvars scopes over this
435 -> BoxySigmaType -- Matching type from the context
436 -> TcM [TcType] -- Types to instantiate the tyvars
437 -- Perform pre-subsumption, and return suitable types
438 -- to instantiate the quantified type varibles:
439 -- info from the pre-subsumption, if there is any
440 -- a boxy type variable otherwise
442 -- Note [Pre-sub boxy]
443 -- The 'btvs' are a subset of 'qtvs'. They are the ones we can
444 -- instantiate to a boxy type variable, because they'll definitely be
445 -- filled in later. This isn't always the case; sometimes we have type
446 -- variables mentioned in the context of the type, but not the body;
447 -- f :: forall a b. C a b => a -> a
448 -- Then we may land up with an unconstrained 'b', so we want to
449 -- instantiate it to a monotype (non-boxy) type variable
451 -- The 'qtvs' that are *neither* fixed by the pre-subsumption, *nor* are in 'btvs',
452 -- are instantiated to TauTv meta variables.
454 preSubType qtvs btvs qty expected_ty
455 = do { tys <- mapM inst_tv qtvs
456 ; traceTc (text "preSubType" <+> (ppr qtvs $$ ppr btvs $$ ppr qty $$ ppr expected_ty $$ ppr pre_subst $$ ppr tys))
459 pre_subst = boxySubMatchType (mkVarSet qtvs) qty expected_ty
461 | Just boxy_ty <- lookupTyVar pre_subst tv = return boxy_ty
462 | tv `elemVarSet` btvs = do { tv' <- tcInstBoxyTyVar tv
463 ; return (mkTyVarTy tv') }
464 | otherwise = do { tv' <- tcInstTyVar tv
465 ; return (mkTyVarTy tv') }
468 :: TcTyVarSet -> TcType -- The "template"; the tyvars are skolems
469 -> BoxyRhoType -- Type to match (note a *Rho* type)
470 -> TvSubst -- Substitution of the [TcTyVar] to BoxySigmaTypes
472 -- boxySubMatchType implements the Pre-subsumption judgement, in Fig 5 of the paper
473 -- "Boxy types: inference for higher rank types and impredicativity"
475 boxySubMatchType tmpl_tvs tmpl_ty boxy_ty
476 = go tmpl_tvs tmpl_ty emptyVarSet boxy_ty
478 go t_tvs t_ty b_tvs b_ty
479 | Just t_ty' <- tcView t_ty = go t_tvs t_ty' b_tvs b_ty
480 | Just b_ty' <- tcView b_ty = go t_tvs t_ty b_tvs b_ty'
482 go t_tvs (TyVarTy _) b_tvs b_ty = emptyTvSubst -- Rule S-ANY; no bindings
483 -- Rule S-ANY covers (a) type variables and (b) boxy types
484 -- in the template. Both look like a TyVarTy.
485 -- See Note [Sub-match] below
487 go t_tvs t_ty b_tvs b_ty
488 | isSigmaTy t_ty, (tvs, _, t_tau) <- tcSplitSigmaTy t_ty
489 = go (t_tvs `delVarSetList` tvs) t_tau b_tvs b_ty -- Rule S-SPEC
490 -- Under a forall on the left, if there is shadowing,
491 -- do not bind! Hence the delVarSetList.
492 | isSigmaTy b_ty, (tvs, _, b_tau) <- tcSplitSigmaTy b_ty
493 = go t_tvs t_ty (extendVarSetList b_tvs tvs) b_tau -- Rule S-SKOL
494 -- Add to the variables we must not bind to
495 -- NB: it's *important* to discard the theta part. Otherwise
496 -- consider (forall a. Eq a => a -> b) ~<~ (Int -> Int -> Bool)
497 -- and end up with a completely bogus binding (b |-> Bool), by lining
498 -- up the (Eq a) with the Int, whereas it should be (b |-> (Int->Bool)).
499 -- This pre-subsumption stuff can return too few bindings, but it
500 -- must *never* return bogus info.
502 go t_tvs (FunTy arg1 res1) b_tvs (FunTy arg2 res2) -- Rule S-FUN
503 = boxy_match t_tvs arg1 b_tvs arg2 (go t_tvs res1 b_tvs res2)
504 -- Match the args, and sub-match the results
506 go t_tvs t_ty b_tvs b_ty = boxy_match t_tvs t_ty b_tvs b_ty emptyTvSubst
507 -- Otherwise defer to boxy matching
508 -- This covers TyConApp, AppTy, PredTy
515 |- head xs : <rhobox>
516 We will do a boxySubMatchType between a ~ <rhobox>
517 But we *don't* want to match [a |-> <rhobox>] because
518 (a) The box should be filled in with a rho-type, but
519 but the returned substitution maps TyVars to boxy
521 (b) In any case, the right final answer might be *either*
522 instantiate 'a' with a rho-type or a sigma type
523 head xs : Int vs head xs : forall b. b->b
524 So the matcher MUST NOT make a choice here. In general, we only
525 bind a template type variable in boxyMatchType, not in boxySubMatchType.
530 :: TcTyVarSet -> [TcType] -- The "template"; the tyvars are skolems
531 -> [BoxySigmaType] -- Type to match
532 -> TvSubst -- Substitution of the [TcTyVar] to BoxySigmaTypes
534 -- boxyMatchTypes implements the Pre-matching judgement, in Fig 5 of the paper
535 -- "Boxy types: inference for higher rank types and impredicativity"
537 -- Find a *boxy* substitution that makes the template look as much
538 -- like the BoxySigmaType as possible.
539 -- It's always ok to return an empty substitution;
540 -- anything more is jam on the pudding
542 -- NB1: This is a pure, non-monadic function.
543 -- It does no unification, and cannot fail
545 -- Precondition: the arg lengths are equal
546 -- Precondition: none of the template type variables appear anywhere in the [BoxySigmaType]
550 boxyMatchTypes tmpl_tvs tmpl_tys boxy_tys
551 = ASSERT( length tmpl_tys == length boxy_tys )
552 boxy_match_s tmpl_tvs tmpl_tys emptyVarSet boxy_tys emptyTvSubst
553 -- ToDo: add error context?
555 boxy_match_s tmpl_tvs [] boxy_tvs [] subst
557 boxy_match_s tmpl_tvs (t_ty:t_tys) boxy_tvs (b_ty:b_tys) subst
558 = boxy_match tmpl_tvs t_ty boxy_tvs b_ty $
559 boxy_match_s tmpl_tvs t_tys boxy_tvs b_tys subst
560 boxy_match_s tmpl_tvs _ boxy_tvs _ subst
561 = panic "boxy_match_s" -- Lengths do not match
565 boxy_match :: TcTyVarSet -> TcType -- Template
566 -> TcTyVarSet -- boxy_tvs: do not bind template tyvars to any of these
567 -> BoxySigmaType -- Match against this type
571 -- The boxy_tvs argument prevents this match:
572 -- [a] forall b. a ~ forall b. b
573 -- We don't want to bind the template variable 'a'
574 -- to the quantified type variable 'b'!
576 boxy_match tmpl_tvs orig_tmpl_ty boxy_tvs orig_boxy_ty subst
577 = go orig_tmpl_ty orig_boxy_ty
580 | Just t_ty' <- tcView t_ty = go t_ty' b_ty
581 | Just b_ty' <- tcView b_ty = go t_ty b_ty'
583 go ty1 ty2 -- C.f. the isSigmaTy case for boxySubMatchType
585 , (tvs1, _, tau1) <- tcSplitSigmaTy ty1
586 , (tvs2, _, tau2) <- tcSplitSigmaTy ty2
587 , equalLength tvs1 tvs2
588 = boxy_match (tmpl_tvs `delVarSetList` tvs1) tau1
589 (boxy_tvs `extendVarSetList` tvs2) tau2 subst
591 go (TyConApp tc1 tys1) (TyConApp tc2 tys2)
593 , not $ isOpenSynTyCon tc1
596 go (FunTy arg1 res1) (FunTy arg2 res2)
597 = go_s [arg1,res1] [arg2,res2]
600 | Just (s1,t1) <- tcSplitAppTy_maybe t_ty,
601 Just (s2,t2) <- tcSplitAppTy_maybe b_ty,
602 typeKind t2 `isSubKind` typeKind t1 -- Maintain invariant
603 = go_s [s1,t1] [s2,t2]
606 | tv `elemVarSet` tmpl_tvs -- Template type variable in the template
607 , boxy_tvs `disjointVarSet` tyVarsOfType orig_boxy_ty
608 , typeKind b_ty `isSubKind` tyVarKind tv -- See Note [Matching kinds]
609 = extendTvSubst subst tv boxy_ty'
611 = subst -- Ignore others
613 boxy_ty' = case lookupTyVar subst tv of
614 Nothing -> orig_boxy_ty
615 Just ty -> ty `boxyLub` orig_boxy_ty
617 go _ (TyVarTy tv) | isMetaTyVar tv
618 = subst -- Don't fail if the template has more info than the target!
619 -- Otherwise, with tmpl_tvs = [a], matching (a -> Int) ~ (Bool -> beta)
620 -- would fail to instantiate 'a', because the meta-type-variable
621 -- beta is as yet un-filled-in
623 go _ _ = emptyTvSubst -- It's important to *fail* by returning the empty substitution
624 -- Example: Tree a ~ Maybe Int
625 -- We do not want to bind (a |-> Int) in pre-matching, because that can give very
626 -- misleading error messages. An even more confusing case is
627 -- a -> b ~ Maybe Int
628 -- Then we do not want to bind (b |-> Int)! It's always safe to discard bindings
629 -- from this pre-matching phase.
632 go_s tys1 tys2 = boxy_match_s tmpl_tvs tys1 boxy_tvs tys2 subst
635 boxyLub :: BoxySigmaType -> BoxySigmaType -> BoxySigmaType
636 -- Combine boxy information from the two types
637 -- If there is a conflict, return the first
638 boxyLub orig_ty1 orig_ty2
639 = go orig_ty1 orig_ty2
641 go (AppTy f1 a1) (AppTy f2 a2) = AppTy (boxyLub f1 f2) (boxyLub a1 a2)
642 go (FunTy f1 a1) (FunTy f2 a2) = FunTy (boxyLub f1 f2) (boxyLub a1 a2)
643 go (TyConApp tc1 ts1) (TyConApp tc2 ts2)
644 | tc1 == tc2, length ts1 == length ts2
645 = TyConApp tc1 (zipWith boxyLub ts1 ts2)
647 go (TyVarTy tv1) ty2 -- This is the whole point;
648 | isTcTyVar tv1, isBoxyTyVar tv1 -- choose ty2 if ty2 is a box
651 go ty1 (TyVarTy tv2) -- Symmetrical case
652 | isTcTyVar tv2, isBoxyTyVar tv2
655 -- Look inside type synonyms, but only if the naive version fails
656 go ty1 ty2 | Just ty1' <- tcView ty1 = go ty1' ty2
657 | Just ty2' <- tcView ty1 = go ty1 ty2'
659 -- For now, we don't look inside ForAlls, PredTys
660 go ty1 ty2 = orig_ty1 -- Default
663 Note [Matching kinds]
664 ~~~~~~~~~~~~~~~~~~~~~
665 The target type might legitimately not be a sub-kind of template.
666 For example, suppose the target is simply a box with an OpenTypeKind,
667 and the template is a type variable with LiftedTypeKind.
668 Then it's ok (because the target type will later be refined).
669 We simply don't bind the template type variable.
671 It might also be that the kind mis-match is an error. For example,
672 suppose we match the template (a -> Int) against (Int# -> Int),
673 where the template type variable 'a' has LiftedTypeKind. This
674 matching function does not fail; it simply doesn't bind the template.
675 Later stuff will fail.
677 %************************************************************************
681 %************************************************************************
683 All the tcSub calls have the form
685 tcSub actual_ty expected_ty
687 actual_ty <= expected_ty
689 That is, that a value of type actual_ty is acceptable in
690 a place expecting a value of type expected_ty.
692 It returns a coercion function
693 co_fn :: actual_ty ~ expected_ty
694 which takes an HsExpr of type actual_ty into one of type
699 tcSubExp :: InstOrigin -> BoxySigmaType -> BoxySigmaType -> TcM HsWrapper
700 -- (tcSub act exp) checks that
702 tcSubExp orig actual_ty expected_ty
703 = -- addErrCtxtM (unifyCtxt actual_ty expected_ty) $
704 -- Adding the error context here leads to some very confusing error
705 -- messages, such as "can't match forall a. a->a with forall a. a->a"
706 -- Example is tcfail165:
707 -- do var <- newEmptyMVar :: IO (MVar (forall a. Show a => a -> String))
708 -- putMVar var (show :: forall a. Show a => a -> String)
709 -- Here the info does not flow from the 'var' arg of putMVar to its 'show' arg
710 -- but after zonking it looks as if it does!
712 -- So instead I'm adding the error context when moving from tc_sub to u_tys
714 traceTc (text "tcSubExp" <+> ppr actual_ty <+> ppr expected_ty) >>
715 tc_sub orig actual_ty actual_ty False expected_ty expected_ty
719 -> BoxySigmaType -- actual_ty, before expanding synonyms
720 -> BoxySigmaType -- ..and after
721 -> InBox -- True <=> expected_ty is inside a box
722 -> BoxySigmaType -- expected_ty, before
723 -> BoxySigmaType -- ..and after
725 -- The acual_ty is never inside a box
726 -- IMPORTANT pre-condition: if the args contain foralls, the bound type
727 -- variables are visible non-monadically
728 -- (i.e. tha args are sufficiently zonked)
729 -- This invariant is needed so that we can "see" the foralls, ad
730 -- e.g. in the SPEC rule where we just use splitSigmaTy
732 tc_sub orig act_sty act_ty exp_ib exp_sty exp_ty
733 = traceTc (text "tc_sub" <+> ppr act_ty $$ ppr exp_ty) >>
734 tc_sub1 orig act_sty act_ty exp_ib exp_sty exp_ty
735 -- This indirection is just here to make
736 -- it easy to insert a debug trace!
738 tc_sub1 orig act_sty act_ty exp_ib exp_sty exp_ty
739 | Just exp_ty' <- tcView exp_ty = tc_sub orig act_sty act_ty exp_ib exp_sty exp_ty'
740 tc_sub1 orig act_sty act_ty exp_ib exp_sty exp_ty
741 | Just act_ty' <- tcView act_ty = tc_sub orig act_sty act_ty' exp_ib exp_sty exp_ty
743 -----------------------------------
744 -- Rule SBOXY, plus other cases when act_ty is a type variable
745 -- Just defer to boxy matching
746 -- This rule takes precedence over SKOL!
747 tc_sub1 orig act_sty (TyVarTy tv) exp_ib exp_sty exp_ty
748 = do { traceTc (text "tc_sub1 - case 1")
749 ; coi <- addSubCtxt orig act_sty exp_sty $
750 uVar (Unify True act_sty exp_sty) False tv exp_ib exp_sty exp_ty
751 ; traceTc (case coi of
752 IdCo -> text "tc_sub1 (Rule SBOXY) IdCo"
753 ACo co -> text "tc_sub1 (Rule SBOXY) ACo" <+> ppr co)
754 ; return $ coiToHsWrapper coi
757 -----------------------------------
758 -- Skolemisation case (rule SKOL)
759 -- actual_ty: d:Eq b => b->b
760 -- expected_ty: forall a. Ord a => a->a
761 -- co_fn e /\a. \d2:Ord a. let d = eqFromOrd d2 in e
763 -- It is essential to do this *before* the specialisation case
764 -- Example: f :: (Eq a => a->a) -> ...
765 -- g :: Ord b => b->b
768 tc_sub1 orig act_sty act_ty exp_ib exp_sty exp_ty
769 | isSigmaTy exp_ty = do
770 { traceTc (text "tc_sub1 - case 2") ;
771 if exp_ib then -- SKOL does not apply if exp_ty is inside a box
772 defer_to_boxy_matching orig act_sty act_ty exp_ib exp_sty exp_ty
774 { (gen_fn, co_fn) <- tcGen exp_ty act_tvs $ \ _ body_exp_ty ->
775 tc_sub orig act_sty act_ty False body_exp_ty body_exp_ty
776 ; return (gen_fn <.> co_fn) }
779 act_tvs = tyVarsOfType act_ty
780 -- It's really important to check for escape wrt
781 -- the free vars of both expected_ty *and* actual_ty
783 -----------------------------------
784 -- Specialisation case (rule ASPEC):
785 -- actual_ty: forall a. Ord a => a->a
786 -- expected_ty: Int -> Int
787 -- co_fn e = e Int dOrdInt
789 tc_sub1 orig act_sty actual_ty exp_ib exp_sty expected_ty
790 -- Implements the new SPEC rule in the Appendix of the paper
791 -- "Boxy types: inference for higher rank types and impredicativity"
792 -- (This appendix isn't in the published version.)
793 -- The idea is to *first* do pre-subsumption, and then full subsumption
794 -- Example: forall a. a->a <= Int -> (forall b. Int)
795 -- Pre-subsumpion finds a|->Int, and that works fine, whereas
796 -- just running full subsumption would fail.
797 | isSigmaTy actual_ty
798 = do { traceTc (text "tc_sub1 - case 3")
799 ; -- Perform pre-subsumption, and instantiate
800 -- the type with info from the pre-subsumption;
801 -- boxy tyvars if pre-subsumption gives no info
802 let (tyvars, theta, tau) = tcSplitSigmaTy actual_ty
803 tau_tvs = exactTyVarsOfType tau
804 ; inst_tys <- if exp_ib then -- Inside a box, do not do clever stuff
805 do { tyvars' <- mapM tcInstBoxyTyVar tyvars
806 ; return (mkTyVarTys tyvars') }
807 else -- Outside, do clever stuff
808 preSubType tyvars tau_tvs tau expected_ty
809 ; let subst' = zipOpenTvSubst tyvars inst_tys
810 tau' = substTy subst' tau
812 -- Perform a full subsumption check
813 ; traceTc (text "tc_sub_spec" <+> vcat [ppr actual_ty,
814 ppr tyvars <+> ppr theta <+> ppr tau,
816 ; co_fn2 <- tc_sub orig tau' tau' exp_ib exp_sty expected_ty
818 -- Deal with the dictionaries
819 ; co_fn1 <- instCall orig inst_tys (substTheta subst' theta)
820 ; return (co_fn2 <.> co_fn1) }
822 -----------------------------------
823 -- Function case (rule F1)
824 tc_sub1 orig act_sty (FunTy act_arg act_res) exp_ib exp_sty (FunTy exp_arg exp_res)
825 = do { traceTc (text "tc_sub1 - case 4")
826 ; tc_sub_funs orig act_arg act_res exp_ib exp_arg exp_res
829 -- Function case (rule F2)
830 tc_sub1 orig act_sty act_ty@(FunTy act_arg act_res) _ exp_sty (TyVarTy exp_tv)
832 = do { traceTc (text "tc_sub1 - case 5")
833 ; cts <- readMetaTyVar exp_tv
835 Indirect ty -> tc_sub orig act_sty act_ty True exp_sty ty
836 Flexi -> do { [arg_ty,res_ty] <- withMetaTvs exp_tv fun_kinds mk_res_ty
837 ; tc_sub_funs orig act_arg act_res True arg_ty res_ty } }
839 mk_res_ty [arg_ty', res_ty'] = mkFunTy arg_ty' res_ty'
840 mk_res_ty other = panic "TcUnify.mk_res_ty3"
841 fun_kinds = [argTypeKind, openTypeKind]
843 -- Everything else: defer to boxy matching
844 tc_sub1 orig act_sty actual_ty exp_ib exp_sty expected_ty@(TyVarTy exp_tv)
845 = do { traceTc (text "tc_sub1 - case 6a" <+> ppr [isBoxyTyVar exp_tv, isMetaTyVar exp_tv, isSkolemTyVar exp_tv, isExistentialTyVar exp_tv,isSigTyVar exp_tv] )
846 ; defer_to_boxy_matching orig act_sty actual_ty exp_ib exp_sty expected_ty
849 tc_sub1 orig act_sty actual_ty exp_ib exp_sty expected_ty
850 = do { traceTc (text "tc_sub1 - case 6")
851 ; defer_to_boxy_matching orig act_sty actual_ty exp_ib exp_sty expected_ty
854 -----------------------------------
855 defer_to_boxy_matching orig act_sty actual_ty exp_ib exp_sty expected_ty
856 = do { coi <- addSubCtxt orig act_sty exp_sty $
857 u_tys (Unify True act_sty exp_sty)
858 False act_sty actual_ty exp_ib exp_sty expected_ty
859 ; return $ coiToHsWrapper coi }
861 -----------------------------------
862 tc_sub_funs orig act_arg act_res exp_ib exp_arg exp_res
863 = do { arg_coi <- addSubCtxt orig act_arg exp_arg $
864 uTysOuter False act_arg exp_ib exp_arg
865 ; co_fn_res <- tc_sub orig act_res act_res exp_ib exp_res exp_res
866 ; wrapper1 <- wrapFunResCoercion [exp_arg] co_fn_res
867 ; let wrapper2 = case arg_coi of
869 ACo co -> WpCast $ FunTy co act_res
870 ; return (wrapper1 <.> wrapper2) }
872 -----------------------------------
874 :: [TcType] -- Type of args
875 -> HsWrapper -- HsExpr a -> HsExpr b
876 -> TcM HsWrapper -- HsExpr (arg_tys -> a) -> HsExpr (arg_tys -> b)
877 wrapFunResCoercion arg_tys co_fn_res
878 | isIdHsWrapper co_fn_res
883 = do { arg_ids <- newSysLocalIds (fsLit "sub") arg_tys
884 ; return (mkWpLams arg_ids <.> co_fn_res <.> mkWpApps arg_ids) }
889 %************************************************************************
891 \subsection{Generalisation}
893 %************************************************************************
896 tcGen :: BoxySigmaType -- expected_ty
897 -> TcTyVarSet -- Extra tyvars that the universally
898 -- quantified tyvars of expected_ty
899 -- must not be unified
900 -> ([TcTyVar] -> BoxyRhoType -> TcM result)
901 -> TcM (HsWrapper, result)
902 -- The expression has type: spec_ty -> expected_ty
904 tcGen expected_ty extra_tvs thing_inside -- We expect expected_ty to be a forall-type
905 -- If not, the call is a no-op
906 = do { traceTc (text "tcGen")
907 -- We want the GenSkol info in the skolemised type variables to
908 -- mention the *instantiated* tyvar names, so that we get a
909 -- good error message "Rigid variable 'a' is bound by (forall a. a->a)"
910 -- Hence the tiresome but innocuous fixM
911 ; ((tvs', theta', rho'), skol_info) <- fixM (\ ~(_, skol_info) ->
912 do { (forall_tvs, theta, rho_ty) <- tcInstSkolType skol_info expected_ty
913 -- Get loation from monad, not from expected_ty
914 ; let skol_info = GenSkol forall_tvs (mkPhiTy theta rho_ty)
915 ; return ((forall_tvs, theta, rho_ty), skol_info) })
918 traceTc (text "tcGen" <+> vcat [
919 text "extra_tvs" <+> ppr extra_tvs,
920 text "expected_ty" <+> ppr expected_ty,
921 text "inst ty" <+> ppr tvs' <+> ppr theta'
923 text "free_tvs" <+> ppr free_tvs])
925 -- Type-check the arg and unify with poly type
926 ; (result, lie) <- getLIE (thing_inside tvs' rho')
928 -- Check that the "forall_tvs" havn't been constrained
929 -- The interesting bit here is that we must include the free variables
930 -- of the expected_ty. Here's an example:
931 -- runST (newVar True)
932 -- Here, if we don't make a check, we'll get a type (ST s (MutVar s Bool))
933 -- for (newVar True), with s fresh. Then we unify with the runST's arg type
934 -- forall s'. ST s' a. That unifies s' with s, and a with MutVar s Bool.
935 -- So now s' isn't unconstrained because it's linked to a.
936 -- Conclusion: include the free vars of the expected_ty in the
937 -- list of "free vars" for the signature check.
939 ; loc <- getInstLoc (SigOrigin skol_info)
940 ; dicts <- newDictBndrs loc theta' -- Includes equalities
941 ; inst_binds <- tcSimplifyCheck loc tvs' dicts lie
943 ; checkSigTyVarsWrt free_tvs tvs'
944 ; traceTc (text "tcGen:done")
947 -- The WpLet binds any Insts which came out of the simplification.
948 dict_vars = map instToVar dicts
949 co_fn = mkWpTyLams tvs' <.> mkWpLams dict_vars <.> WpLet inst_binds
950 ; return (co_fn, result) }
952 free_tvs = tyVarsOfType expected_ty `unionVarSet` extra_tvs
957 %************************************************************************
961 %************************************************************************
963 The exported functions are all defined as versions of some
964 non-exported generic functions.
967 boxyUnify :: BoxyType -> BoxyType -> TcM CoercionI
968 -- Acutal and expected, respectively
969 boxyUnify ty1 ty2 = addErrCtxtM (unifyCtxt ty1 ty2) $
970 uTysOuter False ty1 False ty2
973 boxyUnifyList :: [BoxyType] -> [BoxyType] -> TcM [CoercionI]
974 -- Arguments should have equal length
975 -- Acutal and expected types
976 boxyUnifyList tys1 tys2 = uList boxyUnify tys1 tys2
979 unifyType :: TcTauType -> TcTauType -> TcM CoercionI
980 -- No boxes expected inside these types
981 -- Acutal and expected types
982 unifyType ty1 ty2 -- ty1 expected, ty2 inferred
983 = ASSERT2( not (isBoxyTy ty1), ppr ty1 )
984 ASSERT2( not (isBoxyTy ty2), ppr ty2 )
985 addErrCtxtM (unifyCtxt ty1 ty2) $
986 uTysOuter True ty1 True ty2
989 unifyPred :: PredType -> PredType -> TcM CoercionI
990 -- Acutal and expected types
991 unifyPred p1 p2 = uPred (Unify False (mkPredTy p1) (mkPredTy p2)) True p1 True p2
993 unifyTheta :: TcThetaType -> TcThetaType -> TcM [CoercionI]
994 -- Acutal and expected types
995 unifyTheta theta1 theta2
996 = do { checkTc (equalLength theta1 theta2)
997 (vcat [ptext (sLit "Contexts differ in length"),
998 nest 2 $ parens $ ptext (sLit "Use -fglasgow-exts to allow this")])
999 ; uList unifyPred theta1 theta2
1003 uList :: (a -> a -> TcM b)
1004 -> [a] -> [a] -> TcM [b]
1005 -- Unify corresponding elements of two lists of types, which
1006 -- should be of equal length. We charge down the list explicitly so that
1007 -- we can complain if their lengths differ.
1008 uList unify [] [] = return []
1009 uList unify (ty1:tys1) (ty2:tys2) = do { x <- unify ty1 ty2;
1010 ; xs <- uList unify tys1 tys2
1013 uList unify ty1s ty2s = panic "Unify.uList: mismatched type lists!"
1016 @unifyTypeList@ takes a single list of @TauType@s and unifies them
1017 all together. It is used, for example, when typechecking explicit
1018 lists, when all the elts should be of the same type.
1021 unifyTypeList :: [TcTauType] -> TcM ()
1022 unifyTypeList [] = return ()
1023 unifyTypeList [ty] = return ()
1024 unifyTypeList (ty1:tys@(ty2:_)) = do { unifyType ty1 ty2
1025 ; unifyTypeList tys }
1028 %************************************************************************
1030 \subsection[Unify-uTys]{@uTys@: getting down to business}
1032 %************************************************************************
1034 @uTys@ is the heart of the unifier. Each arg occurs twice, because
1035 we want to report errors in terms of synomyms if possible. The first of
1036 the pair is used in error messages only; it is always the same as the
1037 second, except that if the first is a synonym then the second may be a
1038 de-synonym'd version. This way we get better error messages.
1040 We call the first one \tr{ps_ty1}, \tr{ps_ty2} for ``possible synomym''.
1043 type SwapFlag = Bool
1044 -- False <=> the two args are (actual, expected) respectively
1045 -- True <=> the two args are (expected, actual) respectively
1047 type InBox = Bool -- True <=> we are inside a box
1048 -- False <=> we are outside a box
1049 -- The importance of this is that if we get "filled-box meets
1050 -- filled-box", we'll look into the boxes and unify... but
1051 -- we must not allow polytypes. But if we are in a box on
1052 -- just one side, then we can allow polytypes
1054 data Outer = Unify Bool TcType TcType
1055 -- If there is a unification error, report these types as mis-matching
1056 -- Bool = True <=> the context says "Expected = ty1, Acutal = ty2"
1057 -- for this particular ty1,ty2
1059 instance Outputable Outer where
1060 ppr (Unify c ty1 ty2) = pp_c <+> pprParendType ty1 <+> ptext (sLit "~")
1061 <+> pprParendType ty2
1063 pp_c = if c then ptext (sLit "Top") else ptext (sLit "NonTop")
1066 -------------------------
1067 uTysOuter :: InBox -> TcType -- ty1 is the *actual* type
1068 -> InBox -> TcType -- ty2 is the *expected* type
1070 -- We've just pushed a context describing ty1,ty2
1071 uTysOuter nb1 ty1 nb2 ty2
1072 = do { traceTc (text "uTysOuter" <+> ppr ty1 <+> ppr ty2)
1073 ; u_tys (Unify True ty1 ty2) nb1 ty1 ty1 nb2 ty2 ty2 }
1075 uTys :: InBox -> TcType -> InBox -> TcType -> TcM CoercionI
1076 -- The context does not describe ty1,ty2
1077 uTys nb1 ty1 nb2 ty2
1078 = do { traceTc (text "uTys" <+> ppr ty1 <+> ppr ty2)
1079 ; u_tys (Unify False ty1 ty2) nb1 ty1 ty1 nb2 ty2 ty2 }
1083 uTys_s :: InBox -> [TcType] -- tys1 are the *actual* types
1084 -> InBox -> [TcType] -- tys2 are the *expected* types
1086 uTys_s nb1 [] nb2 [] = return []
1087 uTys_s nb1 (ty1:tys1) nb2 (ty2:tys2) = do { coi <- uTys nb1 ty1 nb2 ty2
1088 ; cois <- uTys_s nb1 tys1 nb2 tys2
1089 ; return (coi:cois) }
1090 uTys_s nb1 ty1s nb2 ty2s = panic "Unify.uTys_s: mismatched type lists!"
1094 -> InBox -> TcType -> TcType -- ty1 is the *actual* type
1095 -> InBox -> TcType -> TcType -- ty2 is the *expected* type
1098 u_tys outer nb1 orig_ty1 ty1 nb2 orig_ty2 ty2
1099 = do { traceTc (text "u_tys " <+> vcat [sep [ braces (ppr orig_ty1 <+> text "/" <+> ppr ty1),
1101 braces (ppr orig_ty2 <+> text "/" <+> ppr ty2)],
1103 ; coi <- go outer orig_ty1 ty1 orig_ty2 ty2
1104 ; traceTc (case coi of
1105 ACo co -> text "u_tys yields coercion:" <+> ppr co
1106 IdCo -> text "u_tys yields no coercion")
1110 bale_out :: Outer -> TcM a
1111 bale_out outer = unifyMisMatch outer
1112 -- We report a mis-match in terms of the original arugments to
1113 -- u_tys, even though 'go' has recursed inwards somewhat
1115 -- Note [Unifying AppTy]
1116 -- A case in point is unifying (m Int) ~ (IO Int)
1117 -- where m is a unification variable that is now bound to (say) (Bool ->)
1118 -- Then we want to report "Can't unify (Bool -> Int) with (IO Int)
1119 -- and not "Can't unify ((->) Bool) with IO"
1121 go :: Outer -> TcType -> TcType -> TcType -> TcType -> TcM CoercionI
1122 -- Always expand synonyms: see Note [Unification and synonyms]
1123 -- (this also throws away FTVs)
1124 go outer sty1 ty1 sty2 ty2
1125 | Just ty1' <- tcView ty1 = go (Unify False ty1' ty2 ) sty1 ty1' sty2 ty2
1126 | Just ty2' <- tcView ty2 = go (Unify False ty1 ty2') sty1 ty1 sty2 ty2'
1128 -- Variables; go for uVar
1129 go outer sty1 (TyVarTy tyvar1) sty2 ty2 = uVar outer False tyvar1 nb2 sty2 ty2
1130 go outer sty1 ty1 sty2 (TyVarTy tyvar2) = uVar outer True tyvar2 nb1 sty1 ty1
1131 -- "True" means args swapped
1133 -- The case for sigma-types must *follow* the variable cases
1134 -- because a boxy variable can be filed with a polytype;
1135 -- but must precede FunTy, because ((?x::Int) => ty) look
1136 -- like a FunTy; there isn't necy a forall at the top
1138 | isSigmaTy ty1 || isSigmaTy ty2
1139 = do { traceTc (text "We have sigma types: equalLength" <+> ppr tvs1 <+> ppr tvs2)
1140 ; unless (equalLength tvs1 tvs2) (bale_out outer)
1141 ; traceTc (text "We're past the first length test")
1142 ; tvs <- tcInstSkolTyVars UnkSkol tvs1 -- Not a helpful SkolemInfo
1143 -- Get location from monad, not from tvs1
1144 ; let tys = mkTyVarTys tvs
1145 in_scope = mkInScopeSet (mkVarSet tvs)
1146 phi1 = substTy (mkTvSubst in_scope (zipTyEnv tvs1 tys)) body1
1147 phi2 = substTy (mkTvSubst in_scope (zipTyEnv tvs2 tys)) body2
1148 (theta1,tau1) = tcSplitPhiTy phi1
1149 (theta2,tau2) = tcSplitPhiTy phi2
1151 ; addErrCtxtM (unifyForAllCtxt tvs phi1 phi2) $ do
1152 { unless (equalLength theta1 theta2) (bale_out outer)
1153 ; cois <- uPreds outer nb1 theta1 nb2 theta2 -- TOMDO: do something with these pred_cois
1154 ; traceTc (text "TOMDO!")
1155 ; coi <- uTys nb1 tau1 nb2 tau2
1157 -- Check for escape; e.g. (forall a. a->b) ~ (forall a. a->a)
1158 ; free_tvs <- zonkTcTyVarsAndFV (varSetElems (tyVarsOfType ty1 `unionVarSet` tyVarsOfType ty2))
1159 ; when (any (`elemVarSet` free_tvs) tvs)
1160 (bleatEscapedTvs free_tvs tvs tvs)
1162 -- If both sides are inside a box, we are in a "box-meets-box"
1163 -- situation, and we should not have a polytype at all.
1164 -- If we get here we have two boxes, already filled with
1165 -- the same polytype... but it should be a monotype.
1166 -- This check comes last, because the error message is
1167 -- extremely unhelpful.
1168 ; when (nb1 && nb2) (notMonoType ty1)
1172 (tvs1, body1) = tcSplitForAllTys ty1
1173 (tvs2, body2) = tcSplitForAllTys ty2
1176 go outer _ (PredTy p1) _ (PredTy p2)
1177 = uPred outer nb1 p1 nb2 p2
1179 -- Type constructors must match
1180 go _ _ (TyConApp con1 tys1) _ (TyConApp con2 tys2)
1181 | con1 == con2 && not (isOpenSynTyCon con1)
1182 = do { cois <- uTys_s nb1 tys1 nb2 tys2
1183 ; return $ mkTyConAppCoI con1 tys1 cois
1185 -- See Note [TyCon app]
1186 | con1 == con2 && identicalOpenSynTyConApp
1187 = do { cois <- uTys_s nb1 tys1' nb2 tys2'
1188 ; return $ mkTyConAppCoI con1 tys1 (replicate n IdCo ++ cois)
1192 (idxTys1, tys1') = splitAt n tys1
1193 (idxTys2, tys2') = splitAt n tys2
1194 identicalOpenSynTyConApp = idxTys1 `tcEqTypes` idxTys2
1195 -- See Note [OpenSynTyCon app]
1197 -- Functions; just check the two parts
1198 go _ _ (FunTy fun1 arg1) _ (FunTy fun2 arg2)
1199 = do { coi_l <- uTys nb1 fun1 nb2 fun2
1200 ; coi_r <- uTys nb1 arg1 nb2 arg2
1201 ; return $ mkFunTyCoI fun1 coi_l arg1 coi_r
1204 -- Applications need a bit of care!
1205 -- They can match FunTy and TyConApp, so use splitAppTy_maybe
1206 -- NB: we've already dealt with type variables and Notes,
1207 -- so if one type is an App the other one jolly well better be too
1208 go outer _ (AppTy s1 t1) _ ty2
1209 | Just (s2,t2) <- tcSplitAppTy_maybe ty2
1210 = do { coi_s <- go outer s1 s1 s2 s2 -- NB recurse into go
1211 ; coi_t <- uTys nb1 t1 nb2 t2 -- See Note [Unifying AppTy]
1212 ; return $ mkAppTyCoI s1 coi_s t1 coi_t }
1214 -- Now the same, but the other way round
1215 -- Don't swap the types, because the error messages get worse
1216 go outer _ ty1 _ (AppTy s2 t2)
1217 | Just (s1,t1) <- tcSplitAppTy_maybe ty1
1218 = do { coi_s <- go outer s1 s1 s2 s2
1219 ; coi_t <- uTys nb1 t1 nb2 t2
1220 ; return $ mkAppTyCoI s1 coi_s t1 coi_t }
1222 -- One or both outermost constructors are type family applications.
1223 -- If we can normalise them away, proceed as usual; otherwise, we
1224 -- need to defer unification by generating a wanted equality constraint.
1225 go outer sty1 ty1 sty2 ty2
1226 | ty1_is_fun || ty2_is_fun
1227 = do { (coi1, ty1') <- if ty1_is_fun then tcNormaliseFamInst ty1
1228 else return (IdCo, ty1)
1229 ; (coi2, ty2') <- if ty2_is_fun then tcNormaliseFamInst ty2
1230 else return (IdCo, ty2)
1231 ; coi <- if isOpenSynTyConApp ty1' || isOpenSynTyConApp ty2'
1232 then do { -- One type family app can't be reduced yet
1234 ; ty1'' <- zonkTcType ty1'
1235 ; ty2'' <- zonkTcType ty2'
1236 ; if tcEqType ty1'' ty2''
1238 else -- see [Deferred Unification]
1239 defer_unification outer False orig_ty1 orig_ty2
1241 else -- unification can proceed
1242 go outer sty1 ty1' sty2 ty2'
1243 ; return $ coi1 `mkTransCoI` coi `mkTransCoI` (mkSymCoI coi2)
1246 ty1_is_fun = isOpenSynTyConApp ty1
1247 ty2_is_fun = isOpenSynTyConApp ty2
1249 -- Anything else fails
1250 go outer _ _ _ _ = bale_out outer
1253 uPred outer nb1 (IParam n1 t1) nb2 (IParam n2 t2)
1255 do { coi <- uTys nb1 t1 nb2 t2
1256 ; return $ mkIParamPredCoI n1 coi
1258 uPred outer nb1 (ClassP c1 tys1) nb2 (ClassP c2 tys2)
1260 do { cois <- uTys_s nb1 tys1 nb2 tys2 -- Guaranteed equal lengths because the kinds check
1261 ; return $ mkClassPPredCoI c1 tys1 cois
1263 uPred outer _ p1 _ p2 = unifyMisMatch outer
1265 uPreds outer nb1 [] nb2 [] = return []
1266 uPreds outer nb1 (p1:ps1) nb2 (p2:ps2) =
1267 do { coi <- uPred outer nb1 p1 nb2 p2
1268 ; cois <- uPreds outer nb1 ps1 nb2 ps2
1271 uPreds outer nb1 ps1 nb2 ps2 = panic "uPreds"
1276 When we find two TyConApps, the argument lists are guaranteed equal
1277 length. Reason: intially the kinds of the two types to be unified is
1278 the same. The only way it can become not the same is when unifying two
1279 AppTys (f1 a1):=:(f2 a2). In that case there can't be a TyConApp in
1280 the f1,f2 (because it'd absorb the app). If we unify f1:=:f2 first,
1281 which we do, that ensures that f1,f2 have the same kind; and that
1282 means a1,a2 have the same kind. And now the argument repeats.
1284 Note [OpenSynTyCon app]
1285 ~~~~~~~~~~~~~~~~~~~~~~~
1288 type family T a :: * -> *
1290 the two types (T () a) and (T () Int) must unify, even if there are
1291 no type instances for T at all. Should we just turn them into an
1292 equality (T () a ~ T () Int)? I don't think so. We currently try to
1293 eagerly unify everything we can before generating equalities; otherwise,
1294 we could turn the unification of [Int] with [a] into an equality, too.
1296 Note [Unification and synonyms]
1297 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1298 If you are tempted to make a short cut on synonyms, as in this
1302 -- NO uTys (SynTy con1 args1 ty1) (SynTy con2 args2 ty2)
1303 -- NO = if (con1 == con2) then
1304 -- NO -- Good news! Same synonym constructors, so we can shortcut
1305 -- NO -- by unifying their arguments and ignoring their expansions.
1306 -- NO unifyTypepeLists args1 args2
1308 -- NO -- Never mind. Just expand them and try again
1312 then THINK AGAIN. Here is the whole story, as detected and reported
1313 by Chris Okasaki \tr{<Chris_Okasaki@loch.mess.cs.cmu.edu>}:
1315 Here's a test program that should detect the problem:
1319 x = (1 :: Bogus Char) :: Bogus Bool
1322 The problem with [the attempted shortcut code] is that
1326 is not a sufficient condition to be able to use the shortcut!
1327 You also need to know that the type synonym actually USES all
1328 its arguments. For example, consider the following type synonym
1329 which does not use all its arguments.
1334 If you ever tried unifying, say, \tr{Bogus Char} with \tr{Bogus Bool},
1335 the unifier would blithely try to unify \tr{Char} with \tr{Bool} and
1336 would fail, even though the expanded forms (both \tr{Int}) should
1339 Similarly, unifying \tr{Bogus Char} with \tr{Bogus t} would
1340 unnecessarily bind \tr{t} to \tr{Char}.
1342 ... You could explicitly test for the problem synonyms and mark them
1343 somehow as needing expansion, perhaps also issuing a warning to the
1348 %************************************************************************
1350 \subsection[Unify-uVar]{@uVar@: unifying with a type variable}
1352 %************************************************************************
1354 @uVar@ is called when at least one of the types being unified is a
1355 variable. It does {\em not} assume that the variable is a fixed point
1356 of the substitution; rather, notice that @uVar@ (defined below) nips
1357 back into @uTys@ if it turns out that the variable is already bound.
1361 -> SwapFlag -- False => tyvar is the "actual" (ty is "expected")
1362 -- True => ty is the "actual" (tyvar is "expected")
1364 -> InBox -- True <=> definitely no boxes in t2
1365 -> TcTauType -> TcTauType -- printing and real versions
1368 uVar outer swapped tv1 nb2 ps_ty2 ty2
1369 = do { let expansion | showSDoc (ppr ty2) == showSDoc (ppr ps_ty2) = empty
1370 | otherwise = brackets (equals <+> ppr ty2)
1371 ; traceTc (text "uVar" <+> ppr outer <+> ppr swapped <+>
1372 sep [ppr tv1 <+> dcolon <+> ppr (tyVarKind tv1 ),
1373 nest 2 (ptext (sLit " <-> ")),
1374 ppr ps_ty2 <+> dcolon <+> ppr (typeKind ty2) <+> expansion])
1375 ; details <- lookupTcTyVar tv1
1378 | swapped -> u_tys outer nb2 ps_ty2 ty2 True ty1 ty1 -- Swap back
1379 | otherwise -> u_tys outer True ty1 ty1 nb2 ps_ty2 ty2 -- Same order
1380 -- The 'True' here says that ty1 is now inside a box
1381 DoneTv details1 -> uUnfilledVar outer swapped tv1 details1 ps_ty2 ty2
1385 uUnfilledVar :: Outer
1387 -> TcTyVar -> TcTyVarDetails -- Tyvar 1
1388 -> TcTauType -> TcTauType -- Type 2
1390 -- Invariant: tyvar 1 is not unified with anything
1392 uUnfilledVar outer swapped tv1 details1 ps_ty2 ty2
1393 | Just ty2' <- tcView ty2
1394 = -- Expand synonyms; ignore FTVs
1395 let outer' | swapped = Unify False ty2' (mkTyVarTy tv1)
1396 | otherwise = Unify False (mkTyVarTy tv1) ty2'
1397 in uUnfilledVar outer' swapped tv1 details1 ps_ty2 ty2'
1399 uUnfilledVar outer swapped tv1 details1 ps_ty2 (TyVarTy tv2)
1400 | tv1 == tv2 -- Same type variable => no-op (but watch out for the boxy case)
1402 MetaTv BoxTv ref1 -- A boxy type variable meets itself;
1403 -- this is box-meets-box, so fill in with a tau-type
1404 -> do { tau_tv <- tcInstTyVar tv1
1405 ; updateMeta tv1 ref1 (mkTyVarTy tau_tv)
1408 other -> return IdCo -- No-op
1410 | otherwise -- Distinct type variables
1411 = do { lookup2 <- lookupTcTyVar tv2
1413 IndirectTv ty2' -> uUnfilledVar outer swapped tv1 details1 ty2' ty2'
1414 DoneTv details2 -> uUnfilledVars outer swapped tv1 details1 tv2 details2
1417 uUnfilledVar outer swapped tv1 details1 ps_ty2 non_var_ty2
1418 = -- ty2 is not a type variable
1420 MetaTv (SigTv _) _ -> rigid_variable
1421 MetaTv info ref1 -> uMetaVar outer swapped tv1 info ref1 ps_ty2 non_var_ty2
1422 SkolemTv _ -> rigid_variable
1425 | isOpenSynTyConApp non_var_ty2
1426 = -- 'non_var_ty2's outermost constructor is a type family,
1427 -- which we may may be able to normalise
1428 do { (coi2, ty2') <- tcNormaliseFamInst non_var_ty2
1430 IdCo -> -- no progress, but maybe after other instantiations
1431 defer_unification outer swapped (TyVarTy tv1) ps_ty2
1432 ACo co -> -- progress: so lets try again
1434 ppr co <+> text "::"<+> ppr non_var_ty2 <+> text "~" <+>
1436 ; coi <- uUnfilledVar outer swapped tv1 details1 ps_ty2 ty2'
1437 ; let coi2' = (if swapped then id else mkSymCoI) coi2
1438 ; return $ coi2' `mkTransCoI` coi
1441 | SkolemTv RuntimeUnkSkol <- details1
1442 -- runtime unknown will never match
1443 = unifyMisMatch outer
1444 | otherwise -- defer as a given equality may still resolve this
1445 = defer_unification outer swapped (TyVarTy tv1) ps_ty2
1448 Note [Deferred Unification]
1449 ~~~~~~~~~~~~~~~~~~~~
1450 We may encounter a unification ty1 = ty2 that cannot be performed syntactically,
1451 and yet its consistency is undetermined. Previously, there was no way to still
1452 make it consistent. So a mismatch error was issued.
1454 Now these unfications are deferred until constraint simplification, where type
1455 family instances and given equations may (or may not) establish the consistency.
1456 Deferred unifications are of the form
1459 where F is a type function and x is a type variable.
1461 id :: x ~ y => x -> y
1464 involves the unfication x = y. It is deferred until we bring into account the
1465 context x ~ y to establish that it holds.
1467 If available, we defer original types (rather than those where closed type
1468 synonyms have already been expanded via tcCoreView). This is, as usual, to
1469 improve error messages.
1471 We need to both 'unBox' and zonk deferred types. We need to unBox as
1472 functions, such as TcExpr.tcMonoExpr promise to fill boxes in the expected
1473 type. We need to zonk as the types go into the kind of the coercion variable
1474 `cotv' and those are not zonked in Inst.zonkInst. (Maybe it would be better
1475 to zonk in zonInst instead. Would that be sufficient?)
1478 defer_unification :: Outer
1483 defer_unification outer True ty1 ty2
1484 = defer_unification outer False ty2 ty1
1485 defer_unification outer False ty1 ty2
1486 = do { ty1' <- unBox ty1 >>= zonkTcType -- unbox *and* zonk..
1487 ; ty2' <- unBox ty2 >>= zonkTcType -- ..see preceding note
1488 ; traceTc $ text "deferring:" <+> ppr ty1 <+> text "~" <+> ppr ty2
1489 ; cotv <- newMetaCoVar ty1' ty2'
1490 -- put ty1 ~ ty2 in LIE
1491 -- Left means "wanted"
1492 ; inst <- popUnifyCtxt outer $
1493 mkEqInst (EqPred ty1' ty2') (Left cotv)
1495 ; return $ ACo $ TyVarTy cotv }
1500 -> TcTyVar -> BoxInfo -> IORef MetaDetails
1503 -- tv1 is an un-filled-in meta type variable (maybe boxy, maybe tau)
1504 -- ty2 is not a type variable
1506 uMetaVar outer swapped tv1 BoxTv ref1 ps_ty2 non_var_ty2
1507 = -- tv1 is a BoxTv. So we must unbox ty2, to ensure
1508 -- that any boxes in ty2 are filled with monotypes
1510 -- It should not be the case that tv1 occurs in ty2
1511 -- (i.e. no occurs check should be needed), but if perchance
1512 -- it does, the unbox operation will fill it, and the debug code
1514 do { final_ty <- unBox ps_ty2
1515 ; when debugIsOn $ do
1516 { meta_details <- readMutVar ref1
1517 ; case meta_details of
1518 Indirect ty -> WARN( True, ppr tv1 <+> ppr ty )
1519 return () -- This really should *not* happen
1522 ; checkUpdateMeta swapped tv1 ref1 final_ty
1526 uMetaVar outer swapped tv1 info1 ref1 ps_ty2 non_var_ty2
1527 = do { -- Occurs check + monotype check
1528 ; mb_final_ty <- checkTauTvUpdate tv1 ps_ty2
1529 ; case mb_final_ty of
1530 Nothing -> -- tv1 occured in type family parameter
1531 defer_unification outer swapped (mkTyVarTy tv1) ps_ty2
1533 do { checkUpdateMeta swapped tv1 ref1 final_ty
1539 uUnfilledVars :: Outer
1541 -> TcTyVar -> TcTyVarDetails -- Tyvar 1
1542 -> TcTyVar -> TcTyVarDetails -- Tyvar 2
1544 -- Invarant: The type variables are distinct,
1545 -- Neither is filled in yet
1546 -- They might be boxy or not
1548 uUnfilledVars outer swapped tv1 (SkolemTv _) tv2 (SkolemTv _)
1549 = -- see [Deferred Unification]
1550 defer_unification outer swapped (mkTyVarTy tv1) (mkTyVarTy tv2)
1552 uUnfilledVars outer swapped tv1 (MetaTv info1 ref1) tv2 (SkolemTv _)
1553 = checkUpdateMeta swapped tv1 ref1 (mkTyVarTy tv2) >> return IdCo
1554 uUnfilledVars outer swapped tv1 (SkolemTv _) tv2 (MetaTv info2 ref2)
1555 = checkUpdateMeta (not swapped) tv2 ref2 (mkTyVarTy tv1) >> return IdCo
1557 -- ToDo: this function seems too long for what it acutally does!
1558 uUnfilledVars outer swapped tv1 (MetaTv info1 ref1) tv2 (MetaTv info2 ref2)
1559 = case (info1, info2) of
1560 (BoxTv, BoxTv) -> box_meets_box >> return IdCo
1562 -- If a box meets a TauTv, but the fomer has the smaller kind
1563 -- then we must create a fresh TauTv with the smaller kind
1564 (_, BoxTv) | k1_sub_k2 -> update_tv2 >> return IdCo
1565 | otherwise -> box_meets_box >> return IdCo
1566 (BoxTv, _ ) | k2_sub_k1 -> update_tv1 >> return IdCo
1567 | otherwise -> box_meets_box >> return IdCo
1569 -- Avoid SigTvs if poss
1570 (SigTv _, _ ) | k1_sub_k2 -> update_tv2 >> return IdCo
1571 (_, SigTv _) | k2_sub_k1 -> update_tv1 >> return IdCo
1573 (_, _) | k1_sub_k2 -> if k2_sub_k1 && nicer_to_update_tv1
1574 then update_tv1 >> return IdCo -- Same kinds
1575 else update_tv2 >> return IdCo
1576 | k2_sub_k1 -> update_tv1 >> return IdCo
1577 | otherwise -> kind_err >> return IdCo
1579 -- Update the variable with least kind info
1580 -- See notes on type inference in Kind.lhs
1581 -- The "nicer to" part only applies if the two kinds are the same,
1582 -- so we can choose which to do.
1584 -- Kinds should be guaranteed ok at this point
1585 update_tv1 = updateMeta tv1 ref1 (mkTyVarTy tv2)
1586 update_tv2 = updateMeta tv2 ref2 (mkTyVarTy tv1)
1588 box_meets_box | k1_sub_k2 = if k2_sub_k1 && nicer_to_update_tv1
1591 | k2_sub_k1 = fill_from tv2
1592 | otherwise = kind_err
1594 -- Update *both* tyvars with a TauTv whose name and kind
1595 -- are gotten from tv (avoid losing nice names is poss)
1596 fill_from tv = do { tv' <- tcInstTyVar tv
1597 ; let tau_ty = mkTyVarTy tv'
1598 ; updateMeta tv1 ref1 tau_ty
1599 ; updateMeta tv2 ref2 tau_ty }
1601 kind_err = addErrCtxtM (unifyKindCtxt swapped tv1 (mkTyVarTy tv2)) $
1602 unifyKindMisMatch k1 k2
1606 k1_sub_k2 = k1 `isSubKind` k2
1607 k2_sub_k1 = k2 `isSubKind` k1
1609 nicer_to_update_tv1 = isSystemName (Var.varName tv1)
1610 -- Try to update sys-y type variables in preference to ones
1611 -- gotten (say) by instantiating a polymorphic function with
1612 -- a user-written type sig
1616 refineBox :: TcType -> TcM TcType
1617 -- Unbox the outer box of a boxy type (if any)
1618 refineBox ty@(TyVarTy box_tv)
1619 | isMetaTyVar box_tv
1620 = do { cts <- readMetaTyVar box_tv
1623 Indirect ty -> return ty }
1624 refineBox other_ty = return other_ty
1626 refineBoxToTau :: TcType -> TcM TcType
1627 -- Unbox the outer box of a boxy type, filling with a monotype if it is empty
1628 -- Like refineBox except for the "fill with monotype" part.
1629 refineBoxToTau ty@(TyVarTy box_tv)
1630 | isMetaTyVar box_tv
1631 , MetaTv BoxTv ref <- tcTyVarDetails box_tv
1632 = do { cts <- readMutVar ref
1634 Flexi -> fillBoxWithTau box_tv ref
1635 Indirect ty -> return ty }
1636 refineBoxToTau other_ty = return other_ty
1638 zapToMonotype :: BoxySigmaType -> TcM TcTauType
1639 -- Subtle... we must zap the boxy res_ty
1640 -- to kind * before using it to instantiate a LitInst
1641 -- Calling unBox instead doesn't do the job, because the box
1642 -- often has an openTypeKind, and we don't want to instantiate
1644 zapToMonotype res_ty
1645 = do { res_tau <- newFlexiTyVarTy liftedTypeKind
1646 ; boxyUnify res_tau res_ty
1649 unBox :: BoxyType -> TcM TcType
1650 -- unBox implements the judgement
1652 -- with input s', and result s
1654 -- It removes all boxes from the input type, returning a non-boxy type.
1655 -- A filled box in the type can only contain a monotype; unBox fails if not
1656 -- The type can have empty boxes, which unBox fills with a monotype
1658 -- Compare this wth checkTauTvUpdate
1660 -- For once, it's safe to treat synonyms as opaque!
1662 unBox (TyConApp tc tys) = do { tys' <- mapM unBox tys; return (TyConApp tc tys') }
1663 unBox (AppTy f a) = do { f' <- unBox f; a' <- unBox a; return (mkAppTy f' a') }
1664 unBox (FunTy f a) = do { f' <- unBox f; a' <- unBox a; return (FunTy f' a') }
1665 unBox (PredTy p) = do { p' <- unBoxPred p; return (PredTy p') }
1666 unBox (ForAllTy tv ty) = ASSERT( isImmutableTyVar tv )
1667 do { ty' <- unBox ty; return (ForAllTy tv ty') }
1669 | isTcTyVar tv -- It's a boxy type variable
1670 , MetaTv BoxTv ref <- tcTyVarDetails tv -- NB: non-TcTyVars are possible
1671 = do { cts <- readMutVar ref -- under nested quantifiers
1673 Flexi -> fillBoxWithTau tv ref
1674 Indirect ty -> do { non_boxy_ty <- unBox ty
1675 ; if isTauTy non_boxy_ty
1676 then return non_boxy_ty
1677 else notMonoType non_boxy_ty }
1679 | otherwise -- Skolems, and meta-tau-variables
1680 = return (TyVarTy tv)
1682 unBoxPred (ClassP cls tys) = do { tys' <- mapM unBox tys; return (ClassP cls tys') }
1683 unBoxPred (IParam ip ty) = do { ty' <- unBox ty; return (IParam ip ty') }
1684 unBoxPred (EqPred ty1 ty2) = do { ty1' <- unBox ty1; ty2' <- unBox ty2; return (EqPred ty1' ty2') }
1689 %************************************************************************
1693 %************************************************************************
1696 unifyMisMatch :: Outer -> TcM a
1697 unifyMisMatch (Unify is_outer ty1 ty2)
1698 | is_outer = popErrCtxt $ failWithMisMatch ty1 ty2 -- This is the whole point of the 'outer' stuff
1699 | otherwise = failWithMisMatch ty1 ty2
1701 popUnifyCtxt :: Outer -> TcM a -> TcM a
1702 popUnifyCtxt (Unify True _ _) thing = popErrCtxt thing
1703 popUnifyCtxt (Unify False _ _) thing = thing
1705 -----------------------
1706 unifyCtxt act_ty exp_ty tidy_env
1707 = do { act_ty' <- zonkTcType act_ty
1708 ; exp_ty' <- zonkTcType exp_ty
1709 ; let (env1, exp_ty'') = tidyOpenType tidy_env exp_ty'
1710 (env2, act_ty'') = tidyOpenType env1 act_ty'
1711 ; return (env2, mkExpectedActualMsg act_ty'' exp_ty'') }
1714 mkExpectedActualMsg act_ty exp_ty
1715 = nest 2 (vcat [ text "Expected type" <> colon <+> ppr exp_ty,
1716 text "Inferred type" <> colon <+> ppr act_ty ])
1719 -- If an error happens we try to figure out whether the function
1720 -- function has been given too many or too few arguments, and say so.
1721 addSubCtxt orig actual_res_ty expected_res_ty thing_inside
1722 = addErrCtxtM mk_err thing_inside
1725 = do { exp_ty' <- zonkTcType expected_res_ty
1726 ; act_ty' <- zonkTcType actual_res_ty
1727 ; let (env1, exp_ty'') = tidyOpenType tidy_env exp_ty'
1728 (env2, act_ty'') = tidyOpenType env1 act_ty'
1729 (exp_args, _) = tcSplitFunTys exp_ty''
1730 (act_args, _) = tcSplitFunTys act_ty''
1732 len_act_args = length act_args
1733 len_exp_args = length exp_args
1735 message = case orig of
1737 | len_exp_args < len_act_args -> wrongArgsCtxt "too few" fun
1738 | len_exp_args > len_act_args -> wrongArgsCtxt "too many" fun
1739 other -> mkExpectedActualMsg act_ty'' exp_ty''
1740 ; return (env2, message) }
1742 wrongArgsCtxt too_many_or_few fun
1743 = ptext (sLit "Probable cause:") <+> quotes (ppr fun)
1744 <+> ptext (sLit "is applied to") <+> text too_many_or_few
1745 <+> ptext (sLit "arguments")
1748 unifyForAllCtxt tvs phi1 phi2 env
1749 = return (env2, msg)
1751 (env', tvs') = tidyOpenTyVars env tvs -- NB: not tidyTyVarBndrs
1752 (env1, phi1') = tidyOpenType env' phi1
1753 (env2, phi2') = tidyOpenType env1 phi2
1754 msg = vcat [ptext (sLit "When matching") <+> quotes (ppr (mkForAllTys tvs' phi1')),
1755 ptext (sLit " and") <+> quotes (ppr (mkForAllTys tvs' phi2'))]
1760 %************************************************************************
1764 %************************************************************************
1766 Unifying kinds is much, much simpler than unifying types.
1769 unifyKind :: TcKind -- Expected
1772 unifyKind (TyConApp kc1 []) (TyConApp kc2 [])
1773 | isSubKindCon kc2 kc1 = return ()
1775 unifyKind (FunTy a1 r1) (FunTy a2 r2)
1776 = do { unifyKind a2 a1; unifyKind r1 r2 }
1777 -- Notice the flip in the argument,
1778 -- so that the sub-kinding works right
1779 unifyKind (TyVarTy kv1) k2 = uKVar False kv1 k2
1780 unifyKind k1 (TyVarTy kv2) = uKVar True kv2 k1
1781 unifyKind k1 k2 = unifyKindMisMatch k1 k2
1783 unifyKinds :: [TcKind] -> [TcKind] -> TcM ()
1784 unifyKinds [] [] = return ()
1785 unifyKinds (k1:ks1) (k2:ks2) = do unifyKind k1 k2
1787 unifyKinds _ _ = panic "unifyKinds: length mis-match"
1790 uKVar :: Bool -> KindVar -> TcKind -> TcM ()
1791 uKVar swapped kv1 k2
1792 = do { mb_k1 <- readKindVar kv1
1794 Flexi -> uUnboundKVar swapped kv1 k2
1795 Indirect k1 | swapped -> unifyKind k2 k1
1796 | otherwise -> unifyKind k1 k2 }
1799 uUnboundKVar :: Bool -> KindVar -> TcKind -> TcM ()
1800 uUnboundKVar swapped kv1 k2@(TyVarTy kv2)
1801 | kv1 == kv2 = return ()
1802 | otherwise -- Distinct kind variables
1803 = do { mb_k2 <- readKindVar kv2
1805 Indirect k2 -> uUnboundKVar swapped kv1 k2
1806 Flexi -> writeKindVar kv1 k2 }
1808 uUnboundKVar swapped kv1 non_var_k2
1809 = do { k2' <- zonkTcKind non_var_k2
1810 ; kindOccurCheck kv1 k2'
1811 ; k2'' <- kindSimpleKind swapped k2'
1812 -- KindVars must be bound only to simple kinds
1813 -- Polarities: (kindSimpleKind True ?) succeeds
1814 -- returning *, corresponding to unifying
1817 ; writeKindVar kv1 k2'' }
1820 kindOccurCheck kv1 k2 -- k2 is zonked
1821 = checkTc (not_in k2) (kindOccurCheckErr kv1 k2)
1823 not_in (TyVarTy kv2) = kv1 /= kv2
1824 not_in (FunTy a2 r2) = not_in a2 && not_in r2
1827 kindSimpleKind :: Bool -> Kind -> TcM SimpleKind
1828 -- (kindSimpleKind True k) returns a simple kind sk such that sk <: k
1829 -- If the flag is False, it requires k <: sk
1830 -- E.g. kindSimpleKind False ?? = *
1831 -- What about (kv -> *) :=: ?? -> *
1832 kindSimpleKind orig_swapped orig_kind
1833 = go orig_swapped orig_kind
1835 go sw (FunTy k1 k2) = do { k1' <- go (not sw) k1
1837 ; return (mkArrowKind k1' k2') }
1839 | isOpenTypeKind k = return liftedTypeKind
1840 | isArgTypeKind k = return liftedTypeKind
1842 | isLiftedTypeKind k = return liftedTypeKind
1843 | isUnliftedTypeKind k = return unliftedTypeKind
1844 go sw k@(TyVarTy _) = return k -- KindVars are always simple
1845 go swapped kind = failWithTc (ptext (sLit "Unexpected kind unification failure:")
1846 <+> ppr orig_swapped <+> ppr orig_kind)
1847 -- I think this can't actually happen
1849 -- T v = MkT v v must be a type
1850 -- T v w = MkT (v -> w) v must not be an umboxed tuple
1853 kindOccurCheckErr tyvar ty
1854 = hang (ptext (sLit "Occurs check: cannot construct the infinite kind:"))
1855 2 (sep [ppr tyvar, char '=', ppr ty])
1859 unifyFunKind :: TcKind -> TcM (Maybe (TcKind, TcKind))
1860 -- Like unifyFunTy, but does not fail; instead just returns Nothing
1862 unifyFunKind (TyVarTy kvar) = do
1863 maybe_kind <- readKindVar kvar
1865 Indirect fun_kind -> unifyFunKind fun_kind
1867 do { arg_kind <- newKindVar
1868 ; res_kind <- newKindVar
1869 ; writeKindVar kvar (mkArrowKind arg_kind res_kind)
1870 ; return (Just (arg_kind,res_kind)) }
1872 unifyFunKind (FunTy arg_kind res_kind) = return (Just (arg_kind,res_kind))
1873 unifyFunKind other = return Nothing
1876 %************************************************************************
1880 %************************************************************************
1882 ---------------------------
1883 -- We would like to get a decent error message from
1884 -- (a) Under-applied type constructors
1885 -- f :: (Maybe, Maybe)
1886 -- (b) Over-applied type constructors
1887 -- f :: Int x -> Int x
1891 checkExpectedKind :: Outputable a => a -> TcKind -> TcKind -> TcM ()
1892 -- A fancy wrapper for 'unifyKind', which tries
1893 -- to give decent error messages.
1894 -- (checkExpectedKind ty act_kind exp_kind)
1895 -- checks that the actual kind act_kind is compatible
1896 -- with the expected kind exp_kind
1897 -- The first argument, ty, is used only in the error message generation
1898 checkExpectedKind ty act_kind exp_kind
1899 | act_kind `isSubKind` exp_kind -- Short cut for a very common case
1902 (_errs, mb_r) <- tryTc (unifyKind exp_kind act_kind)
1904 Just r -> return () ; -- Unification succeeded
1907 -- So there's definitely an error
1908 -- Now to find out what sort
1909 exp_kind <- zonkTcKind exp_kind
1910 act_kind <- zonkTcKind act_kind
1912 env0 <- tcInitTidyEnv
1913 let (exp_as, _) = splitKindFunTys exp_kind
1914 (act_as, _) = splitKindFunTys act_kind
1915 n_exp_as = length exp_as
1916 n_act_as = length act_as
1918 (env1, tidy_exp_kind) = tidyKind env0 exp_kind
1919 (env2, tidy_act_kind) = tidyKind env1 act_kind
1921 err | n_exp_as < n_act_as -- E.g. [Maybe]
1922 = quotes (ppr ty) <+> ptext (sLit "is not applied to enough type arguments")
1924 -- Now n_exp_as >= n_act_as. In the next two cases,
1925 -- n_exp_as == 0, and hence so is n_act_as
1926 | isLiftedTypeKind exp_kind && isUnliftedTypeKind act_kind
1927 = ptext (sLit "Expecting a lifted type, but") <+> quotes (ppr ty)
1928 <+> ptext (sLit "is unlifted")
1930 | isUnliftedTypeKind exp_kind && isLiftedTypeKind act_kind
1931 = ptext (sLit "Expecting an unlifted type, but") <+> quotes (ppr ty)
1932 <+> ptext (sLit "is lifted")
1934 | otherwise -- E.g. Monad [Int]
1935 = ptext (sLit "Kind mis-match")
1937 more_info = sep [ ptext (sLit "Expected kind") <+>
1938 quotes (pprKind tidy_exp_kind) <> comma,
1939 ptext (sLit "but") <+> quotes (ppr ty) <+>
1940 ptext (sLit "has kind") <+> quotes (pprKind tidy_act_kind)]
1942 failWithTcM (env2, err $$ more_info)
1945 %************************************************************************
1947 \subsection{Checking signature type variables}
1949 %************************************************************************
1951 @checkSigTyVars@ checks that a set of universally quantified type varaibles
1952 are not mentioned in the environment. In particular:
1954 (a) Not mentioned in the type of a variable in the envt
1955 eg the signature for f in this:
1961 Here, f is forced to be monorphic by the free occurence of x.
1963 (d) Not (unified with another type variable that is) in scope.
1964 eg f x :: (r->r) = (\y->y) :: forall a. a->r
1965 when checking the expression type signature, we find that
1966 even though there is nothing in scope whose type mentions r,
1967 nevertheless the type signature for the expression isn't right.
1969 Another example is in a class or instance declaration:
1971 op :: forall b. a -> b
1973 Here, b gets unified with a
1975 Before doing this, the substitution is applied to the signature type variable.
1978 checkSigTyVars :: [TcTyVar] -> TcM ()
1979 checkSigTyVars sig_tvs = check_sig_tyvars emptyVarSet sig_tvs
1981 checkSigTyVarsWrt :: TcTyVarSet -> [TcTyVar] -> TcM ()
1982 -- The extra_tvs can include boxy type variables;
1983 -- e.g. TcMatches.tcCheckExistentialPat
1984 checkSigTyVarsWrt extra_tvs sig_tvs
1985 = do { extra_tvs' <- zonkTcTyVarsAndFV (varSetElems extra_tvs)
1986 ; check_sig_tyvars extra_tvs' sig_tvs }
1989 :: TcTyVarSet -- Global type variables. The universally quantified
1990 -- tyvars should not mention any of these
1991 -- Guaranteed already zonked.
1992 -> [TcTyVar] -- Universally-quantified type variables in the signature
1993 -- Guaranteed to be skolems
1995 check_sig_tyvars extra_tvs []
1997 check_sig_tyvars extra_tvs sig_tvs
1998 = ASSERT( all isSkolemTyVar sig_tvs )
1999 do { gbl_tvs <- tcGetGlobalTyVars
2000 ; traceTc (text "check_sig_tyvars" <+> (vcat [text "sig_tys" <+> ppr sig_tvs,
2001 text "gbl_tvs" <+> ppr gbl_tvs,
2002 text "extra_tvs" <+> ppr extra_tvs]))
2004 ; let env_tvs = gbl_tvs `unionVarSet` extra_tvs
2005 ; when (any (`elemVarSet` env_tvs) sig_tvs)
2006 (bleatEscapedTvs env_tvs sig_tvs sig_tvs)
2009 bleatEscapedTvs :: TcTyVarSet -- The global tvs
2010 -> [TcTyVar] -- The possibly-escaping type variables
2011 -> [TcTyVar] -- The zonked versions thereof
2013 -- Complain about escaping type variables
2014 -- We pass a list of type variables, at least one of which
2015 -- escapes. The first list contains the original signature type variable,
2016 -- while the second contains the type variable it is unified to (usually itself)
2017 bleatEscapedTvs globals sig_tvs zonked_tvs
2018 = do { env0 <- tcInitTidyEnv
2019 ; let (env1, tidy_tvs) = tidyOpenTyVars env0 sig_tvs
2020 (env2, tidy_zonked_tvs) = tidyOpenTyVars env1 zonked_tvs
2022 ; (env3, msgs) <- foldlM check (env2, []) (tidy_tvs `zip` tidy_zonked_tvs)
2023 ; failWithTcM (env3, main_msg $$ nest 2 (vcat msgs)) }
2025 main_msg = ptext (sLit "Inferred type is less polymorphic than expected")
2027 check (tidy_env, msgs) (sig_tv, zonked_tv)
2028 | not (zonked_tv `elemVarSet` globals) = return (tidy_env, msgs)
2030 = do { (tidy_env1, globs) <- findGlobals (unitVarSet zonked_tv) tidy_env
2031 ; return (tidy_env1, escape_msg sig_tv zonked_tv globs : msgs) }
2033 -----------------------
2034 escape_msg sig_tv zonked_tv globs
2036 = vcat [sep [msg, ptext (sLit "is mentioned in the environment:")],
2037 nest 2 (vcat globs)]
2039 = msg <+> ptext (sLit "escapes")
2040 -- Sigh. It's really hard to give a good error message
2041 -- all the time. One bad case is an existential pattern match.
2042 -- We rely on the "When..." context to help.
2044 msg = ptext (sLit "Quantified type variable") <+> quotes (ppr sig_tv) <+> is_bound_to
2046 | sig_tv == zonked_tv = empty
2047 | otherwise = ptext (sLit "is unified with") <+> quotes (ppr zonked_tv) <+> ptext (sLit "which")
2050 These two context are used with checkSigTyVars
2053 sigCtxt :: Id -> [TcTyVar] -> TcThetaType -> TcTauType
2054 -> TidyEnv -> TcM (TidyEnv, Message)
2055 sigCtxt id sig_tvs sig_theta sig_tau tidy_env = do
2056 actual_tau <- zonkTcType sig_tau
2058 (env1, tidy_sig_tvs) = tidyOpenTyVars tidy_env sig_tvs
2059 (env2, tidy_sig_rho) = tidyOpenType env1 (mkPhiTy sig_theta sig_tau)
2060 (env3, tidy_actual_tau) = tidyOpenType env2 actual_tau
2061 sub_msg = vcat [ptext (sLit "Signature type: ") <+> pprType (mkForAllTys tidy_sig_tvs tidy_sig_rho),
2062 ptext (sLit "Type to generalise:") <+> pprType tidy_actual_tau
2064 msg = vcat [ptext (sLit "When trying to generalise the type inferred for") <+> quotes (ppr id),