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
18 tcSubExp, tcFunResTy, tcGen,
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
65 %************************************************************************
67 \subsection{'hole' type variables}
69 %************************************************************************
72 tcInfer :: (BoxyType -> TcM a) -> TcM (a, TcType)
74 = do { box <- newBoxyTyVar openTypeKind
75 ; res <- tc_infer (mkTyVarTy box)
76 ; res_ty <- {- pprTrace "tcInfer" (ppr (mkTyVarTy box)) $ -} readFilledBox box -- Guaranteed filled-in by now
77 ; return (res, res_ty) }
81 %************************************************************************
85 %************************************************************************
88 subFunTys :: SDoc -- Somthing like "The function f has 3 arguments"
89 -- or "The abstraction (\x.e) takes 1 argument"
90 -> Arity -- Expected # of args
91 -> BoxyRhoType -- res_ty
92 -> ([BoxySigmaType] -> BoxyRhoType -> TcM a)
94 -- Attempt to decompse res_ty to have enough top-level arrows to
95 -- match the number of patterns in the match group
97 -- If (subFunTys n_args res_ty thing_inside) = (co_fn, res)
98 -- and the inner call to thing_inside passes args: [a1,...,an], b
99 -- then co_fn :: (a1 -> ... -> an -> b) ~ res_ty
101 -- Note that it takes a BoxyRho type, and guarantees to return a BoxyRhoType
104 {- Error messages from subFunTys
106 The abstraction `\Just 1 -> ...' has two arguments
107 but its type `Maybe a -> a' has only one
109 The equation(s) for `f' have two arguments
110 but its type `Maybe a -> a' has only one
112 The section `(f 3)' requires 'f' to take two arguments
113 but its type `Int -> Int' has only one
115 The function 'f' is applied to two arguments
116 but its type `Int -> Int' has only one
120 subFunTys error_herald n_pats res_ty thing_inside
121 = loop n_pats [] res_ty
123 -- In 'loop', the parameter 'arg_tys' accumulates
124 -- the arg types so far, in *reverse order*
125 -- INVARIANT: res_ty :: *
126 loop n args_so_far res_ty
127 | Just res_ty' <- tcView res_ty = loop n args_so_far res_ty'
129 loop n args_so_far res_ty
130 | isSigmaTy res_ty -- Do this before checking n==0, because we
131 -- guarantee to return a BoxyRhoType, not a
133 = do { (gen_fn, (co_fn, res)) <- tcGen res_ty emptyVarSet $ \ _ res_ty' ->
134 loop n args_so_far res_ty'
135 ; return (gen_fn <.> co_fn, res) }
137 loop 0 args_so_far res_ty
138 = do { res <- thing_inside (reverse args_so_far) res_ty
139 ; return (idHsWrapper, res) }
141 loop n args_so_far (FunTy arg_ty res_ty)
142 = do { (co_fn, res) <- loop (n-1) (arg_ty:args_so_far) res_ty
143 ; co_fn' <- wrapFunResCoercion [arg_ty] co_fn
144 ; return (co_fn', res) }
146 -- Try to normalise synonym families and defer if that's not possible
147 loop n args_so_far ty@(TyConApp tc tys)
149 = do { (coi1, ty') <- tcNormaliseFamInst ty
151 IdCo -> defer -- 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 (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
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
199 = do { arg_tys <- newFlexiTyVarTys n_pats argTypeKind
200 ; res_ty' <- newFlexiTyVarTy openTypeKind
201 ; let fun_ty = mkFunTys arg_tys res_ty'
202 ; coi <- defer_unification False False fun_ty res_ty
203 ; res <- thing_inside arg_tys res_ty'
204 ; return (coiToHsWrapper coi, res)
208 = do { env0 <- tcInitTidyEnv
209 ; res_ty' <- zonkTcType res_ty
210 ; let (env1, res_ty'') = tidyOpenType env0 res_ty'
211 ; failWithTcM (env1, mk_msg res_ty'' (length args_so_far)) }
213 mk_msg res_ty n_actual
214 = error_herald <> comma $$
215 sep [ptext SLIT("but its type") <+> quotes (pprType res_ty),
216 if n_actual == 0 then ptext SLIT("has none")
217 else ptext SLIT("has only") <+> speakN n_actual]
221 ----------------------
222 boxySplitTyConApp :: TyCon -- T :: k1 -> ... -> kn -> *
223 -> BoxyRhoType -- Expected type (T a b c)
224 -> TcM ([BoxySigmaType], -- Element types, a b c
226 -- It's used for wired-in tycons, so we call checkWiredInTyCon
227 -- Precondition: never called with FunTyCon
228 -- Precondition: input type :: *
230 boxySplitTyConApp tc orig_ty
231 = do { checkWiredInTyCon tc
232 ; loop (tyConArity tc) [] orig_ty }
234 loop n_req args_so_far ty
235 | Just ty' <- tcView ty = loop n_req args_so_far ty'
237 loop n_req args_so_far ty@(TyConApp tycon args)
239 = ASSERT( n_req == length args) -- ty::*
240 return (args ++ args_so_far, IdCo)
242 | isOpenSynTyCon tycon -- try to normalise type family application
243 = do { (coi1, ty') <- tcNormaliseFamInst ty
244 ; traceTc $ text "boxySplitTyConApp:" <+>
245 ppr ty <+> text "==>" <+> ppr ty'
247 IdCo -> defer -- no progress, but maybe solvable => defer
248 ACo _ -> -- progress: so lets try again
249 do { (args, coi2) <- loop n_req args_so_far ty'
250 ; return $ (args, coi2 `mkTransCoI` mkSymCoI coi1)
254 loop n_req args_so_far (AppTy fun arg)
256 = do { (args, coi) <- loop (n_req - 1) (arg:args_so_far) fun
257 ; return (args, mkAppTyCoI fun coi arg IdCo)
260 loop n_req args_so_far (TyVarTy tv)
261 | isTyConableTyVar tv
262 , res_kind `isSubKind` tyVarKind tv
263 = do { cts <- readMetaTyVar tv
265 Indirect ty -> loop n_req args_so_far ty
266 Flexi -> do { arg_tys <- withMetaTvs tv arg_kinds mk_res_ty
267 ; return (arg_tys ++ args_so_far, IdCo) }
269 | otherwise -- defer as tyvar may be refined by equalities
272 (arg_kinds, res_kind) = splitKindFunTysN n_req (tyConKind tc)
274 loop _ _ _ = boxySplitFailure (mkTyConApp tc (mkTyVarTys (tyConTyVars tc)))
277 -- defer splitting by generating an equality constraint
278 defer = boxySplitDefer arg_kinds mk_res_ty orig_ty
280 (arg_kinds, _) = splitKindFunTys (tyConKind tc)
282 -- apply splitted tycon to arguments
283 mk_res_ty = mkTyConApp tc
285 ----------------------
286 boxySplitListTy :: BoxyRhoType -> TcM (BoxySigmaType, CoercionI)
287 -- Special case for lists
288 boxySplitListTy exp_ty
289 = do { ([elt_ty], coi) <- boxySplitTyConApp listTyCon exp_ty
290 ; return (elt_ty, coi) }
292 ----------------------
293 boxySplitPArrTy :: BoxyRhoType -> TcM (BoxySigmaType, CoercionI)
294 -- Special case for parrs
295 boxySplitPArrTy exp_ty
296 = do { ([elt_ty], coi) <- boxySplitTyConApp parrTyCon exp_ty
297 ; return (elt_ty, coi) }
299 ----------------------
300 boxySplitAppTy :: BoxyRhoType -- Type to split: m a
301 -> TcM ((BoxySigmaType, BoxySigmaType), -- Returns m, a
303 -- If the incoming type is a mutable type variable of kind k, then
304 -- boxySplitAppTy returns a new type variable (m: * -> k); note the *.
305 -- If the incoming type is boxy, then so are the result types; and vice versa
307 boxySplitAppTy orig_ty
311 | Just ty' <- tcView ty = loop ty'
314 | Just (fun_ty, arg_ty) <- tcSplitAppTy_maybe ty
315 = return ((fun_ty, arg_ty), IdCo)
317 loop ty@(TyConApp tycon args)
318 | isOpenSynTyCon tycon -- try to normalise type family application
319 = do { (coi1, ty') <- tcNormaliseFamInst ty
321 IdCo -> defer -- no progress, but maybe solvable => defer
322 ACo co -> -- progress: so lets try again
323 do { (args, coi2) <- loop ty'
324 ; return $ (args, coi2 `mkTransCoI` mkSymCoI coi1)
329 | isTyConableTyVar tv
330 = do { cts <- readMetaTyVar tv
332 Indirect ty -> loop ty
333 Flexi -> do { [fun_ty, arg_ty] <- withMetaTvs tv kinds mk_res_ty
334 ; return ((fun_ty, arg_ty), IdCo) } }
335 | otherwise -- defer as tyvar may be refined by equalities
338 tv_kind = tyVarKind tv
339 kinds = [mkArrowKind liftedTypeKind (defaultKind tv_kind),
341 liftedTypeKind] -- arg type :: *
342 -- The defaultKind is a bit smelly. If you remove it,
343 -- try compiling f x = do { x }
344 -- and you'll get a kind mis-match. It smells, but
345 -- not enough to lose sleep over.
347 loop _ = boxySplitFailure (mkAppTy alphaTy betaTy) orig_ty
349 -- defer splitting by generating an equality constraint
350 defer = do { ([ty1, ty2], coi) <- boxySplitDefer arg_kinds mk_res_ty orig_ty
351 ; return ((ty1, ty2), coi)
354 orig_kind = typeKind orig_ty
355 arg_kinds = [mkArrowKind liftedTypeKind (defaultKind orig_kind),
357 liftedTypeKind] -- arg type :: *
359 -- build type application
360 mk_res_ty [fun_ty', arg_ty'] = mkAppTy fun_ty' arg_ty'
361 mk_res_ty _other = panic "TcUnify.mk_res_ty2"
364 boxySplitFailure actual_ty expected_ty
365 = unifyMisMatch False False actual_ty expected_ty
366 -- "outer" is False, so we don't pop the context
367 -- which is what we want since we have not pushed one!
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 mkTy orig_ty
375 = do { tau_tys <- mapM newFlexiTyVarTy kinds
376 ; coi <- defer_unification False False (mkTy tau_tys) orig_ty
377 ; return (tau_tys, coi)
382 --------------------------------
383 -- withBoxes: the key utility function
384 --------------------------------
387 withMetaTvs :: TcTyVar -- An unfilled-in, non-skolem, meta type variable
388 -> [Kind] -- Make fresh boxes (with the same BoxTv/TauTv setting as tv)
389 -> ([BoxySigmaType] -> BoxySigmaType)
390 -- Constructs the type to assign
391 -- to the original var
392 -> TcM [BoxySigmaType] -- Return the fresh boxes
394 -- It's entirely possible for the [kind] to be empty.
395 -- For example, when pattern-matching on True,
396 -- we call boxySplitTyConApp passing a boolTyCon
398 -- Invariant: tv is still Flexi
400 withMetaTvs tv kinds mk_res_ty
402 = do { box_tvs <- mapM (newMetaTyVar BoxTv) kinds
403 ; let box_tys = mkTyVarTys box_tvs
404 ; writeMetaTyVar tv (mk_res_ty box_tys)
407 | otherwise -- Non-boxy meta type variable
408 = do { tau_tys <- mapM newFlexiTyVarTy kinds
409 ; writeMetaTyVar tv (mk_res_ty tau_tys) -- Write it *first*
410 -- Sure to be a tau-type
413 withBox :: Kind -> (BoxySigmaType -> TcM a) -> TcM (a, TcType)
414 -- Allocate a *boxy* tyvar
415 withBox kind thing_inside
416 = do { box_tv <- newMetaTyVar BoxTv kind
417 ; res <- thing_inside (mkTyVarTy box_tv)
418 ; ty <- {- pprTrace "with_box" (ppr (mkTyVarTy box_tv)) $ -} readFilledBox box_tv
423 %************************************************************************
425 Approximate boxy matching
427 %************************************************************************
430 preSubType :: [TcTyVar] -- Quantified type variables
431 -> TcTyVarSet -- Subset of quantified type variables
432 -- see Note [Pre-sub boxy]
433 -> TcType -- The rho-type part; quantified tyvars scopes over this
434 -> BoxySigmaType -- Matching type from the context
435 -> TcM [TcType] -- Types to instantiate the tyvars
436 -- Perform pre-subsumption, and return suitable types
437 -- to instantiate the quantified type varibles:
438 -- info from the pre-subsumption, if there is any
439 -- a boxy type variable otherwise
441 -- Note [Pre-sub boxy]
442 -- The 'btvs' are a subset of 'qtvs'. They are the ones we can
443 -- instantiate to a boxy type variable, because they'll definitely be
444 -- filled in later. This isn't always the case; sometimes we have type
445 -- variables mentioned in the context of the type, but not the body;
446 -- f :: forall a b. C a b => a -> a
447 -- Then we may land up with an unconstrained 'b', so we want to
448 -- instantiate it to a monotype (non-boxy) type variable
450 -- The 'qtvs' that are *neither* fixed by the pre-subsumption, *nor* are in 'btvs',
451 -- are instantiated to TauTv meta variables.
453 preSubType qtvs btvs qty expected_ty
454 = do { tys <- mapM inst_tv qtvs
455 ; traceTc (text "preSubType" <+> (ppr qtvs $$ ppr btvs $$ ppr qty $$ ppr expected_ty $$ ppr pre_subst $$ ppr tys))
458 pre_subst = boxySubMatchType (mkVarSet qtvs) qty expected_ty
460 | Just boxy_ty <- lookupTyVar pre_subst tv = return boxy_ty
461 | tv `elemVarSet` btvs = do { tv' <- tcInstBoxyTyVar tv
462 ; return (mkTyVarTy tv') }
463 | otherwise = do { tv' <- tcInstTyVar tv
464 ; return (mkTyVarTy tv') }
467 :: TcTyVarSet -> TcType -- The "template"; the tyvars are skolems
468 -> BoxyRhoType -- Type to match (note a *Rho* type)
469 -> TvSubst -- Substitution of the [TcTyVar] to BoxySigmaTypes
471 -- boxySubMatchType implements the Pre-subsumption judgement, in Fig 5 of the paper
472 -- "Boxy types: inference for higher rank types and impredicativity"
474 boxySubMatchType tmpl_tvs tmpl_ty boxy_ty
475 = go tmpl_tvs tmpl_ty emptyVarSet boxy_ty
477 go t_tvs t_ty b_tvs b_ty
478 | Just t_ty' <- tcView t_ty = go t_tvs t_ty' b_tvs b_ty
479 | Just b_ty' <- tcView b_ty = go t_tvs t_ty b_tvs b_ty'
481 go t_tvs (TyVarTy _) b_tvs b_ty = emptyTvSubst -- Rule S-ANY; no bindings
482 -- Rule S-ANY covers (a) type variables and (b) boxy types
483 -- in the template. Both look like a TyVarTy.
484 -- See Note [Sub-match] below
486 go t_tvs t_ty b_tvs b_ty
487 | isSigmaTy t_ty, (tvs, _, t_tau) <- tcSplitSigmaTy t_ty
488 = go (t_tvs `delVarSetList` tvs) t_tau b_tvs b_ty -- Rule S-SPEC
489 -- Under a forall on the left, if there is shadowing,
490 -- do not bind! Hence the delVarSetList.
491 | isSigmaTy b_ty, (tvs, _, b_tau) <- tcSplitSigmaTy b_ty
492 = go t_tvs t_ty (extendVarSetList b_tvs tvs) b_tau -- Rule S-SKOL
493 -- Add to the variables we must not bind to
494 -- NB: it's *important* to discard the theta part. Otherwise
495 -- consider (forall a. Eq a => a -> b) ~<~ (Int -> Int -> Bool)
496 -- and end up with a completely bogus binding (b |-> Bool), by lining
497 -- up the (Eq a) with the Int, whereas it should be (b |-> (Int->Bool)).
498 -- This pre-subsumption stuff can return too few bindings, but it
499 -- must *never* return bogus info.
501 go t_tvs (FunTy arg1 res1) b_tvs (FunTy arg2 res2) -- Rule S-FUN
502 = boxy_match t_tvs arg1 b_tvs arg2 (go t_tvs res1 b_tvs res2)
503 -- Match the args, and sub-match the results
505 go t_tvs t_ty b_tvs b_ty = boxy_match t_tvs t_ty b_tvs b_ty emptyTvSubst
506 -- Otherwise defer to boxy matching
507 -- This covers TyConApp, AppTy, PredTy
514 |- head xs : <rhobox>
515 We will do a boxySubMatchType between a ~ <rhobox>
516 But we *don't* want to match [a |-> <rhobox>] because
517 (a) The box should be filled in with a rho-type, but
518 but the returned substitution maps TyVars to boxy
520 (b) In any case, the right final answer might be *either*
521 instantiate 'a' with a rho-type or a sigma type
522 head xs : Int vs head xs : forall b. b->b
523 So the matcher MUST NOT make a choice here. In general, we only
524 bind a template type variable in boxyMatchType, not in boxySubMatchType.
529 :: TcTyVarSet -> [TcType] -- The "template"; the tyvars are skolems
530 -> [BoxySigmaType] -- Type to match
531 -> TvSubst -- Substitution of the [TcTyVar] to BoxySigmaTypes
533 -- boxyMatchTypes implements the Pre-matching judgement, in Fig 5 of the paper
534 -- "Boxy types: inference for higher rank types and impredicativity"
536 -- Find a *boxy* substitution that makes the template look as much
537 -- like the BoxySigmaType as possible.
538 -- It's always ok to return an empty substitution;
539 -- anything more is jam on the pudding
541 -- NB1: This is a pure, non-monadic function.
542 -- It does no unification, and cannot fail
544 -- Precondition: the arg lengths are equal
545 -- Precondition: none of the template type variables appear anywhere in the [BoxySigmaType]
549 boxyMatchTypes tmpl_tvs tmpl_tys boxy_tys
550 = ASSERT( length tmpl_tys == length boxy_tys )
551 boxy_match_s tmpl_tvs tmpl_tys emptyVarSet boxy_tys emptyTvSubst
552 -- ToDo: add error context?
554 boxy_match_s tmpl_tvs [] boxy_tvs [] subst
556 boxy_match_s tmpl_tvs (t_ty:t_tys) boxy_tvs (b_ty:b_tys) subst
557 = boxy_match tmpl_tvs t_ty boxy_tvs b_ty $
558 boxy_match_s tmpl_tvs t_tys boxy_tvs b_tys subst
559 boxy_match_s tmpl_tvs _ boxy_tvs _ subst
560 = panic "boxy_match_s" -- Lengths do not match
564 boxy_match :: TcTyVarSet -> TcType -- Template
565 -> TcTyVarSet -- boxy_tvs: do not bind template tyvars to any of these
566 -> BoxySigmaType -- Match against this type
570 -- The boxy_tvs argument prevents this match:
571 -- [a] forall b. a ~ forall b. b
572 -- We don't want to bind the template variable 'a'
573 -- to the quantified type variable 'b'!
575 boxy_match tmpl_tvs orig_tmpl_ty boxy_tvs orig_boxy_ty subst
576 = go orig_tmpl_ty orig_boxy_ty
579 | Just t_ty' <- tcView t_ty = go t_ty' b_ty
580 | Just b_ty' <- tcView b_ty = go t_ty b_ty'
582 go ty1 ty2 -- C.f. the isSigmaTy case for boxySubMatchType
584 , (tvs1, _, tau1) <- tcSplitSigmaTy ty1
585 , (tvs2, _, tau2) <- tcSplitSigmaTy ty2
586 , equalLength tvs1 tvs2
587 = boxy_match (tmpl_tvs `delVarSetList` tvs1) tau1
588 (boxy_tvs `extendVarSetList` tvs2) tau2 subst
590 go (TyConApp tc1 tys1) (TyConApp tc2 tys2)
592 , not $ isOpenSynTyCon tc1
595 go (FunTy arg1 res1) (FunTy arg2 res2)
596 = go_s [arg1,res1] [arg2,res2]
599 | Just (s1,t1) <- tcSplitAppTy_maybe t_ty,
600 Just (s2,t2) <- tcSplitAppTy_maybe b_ty,
601 typeKind t2 `isSubKind` typeKind t1 -- Maintain invariant
602 = go_s [s1,t1] [s2,t2]
605 | tv `elemVarSet` tmpl_tvs -- Template type variable in the template
606 , boxy_tvs `disjointVarSet` tyVarsOfType orig_boxy_ty
607 , typeKind b_ty `isSubKind` tyVarKind tv -- See Note [Matching kinds]
608 = extendTvSubst subst tv boxy_ty'
610 = subst -- Ignore others
612 boxy_ty' = case lookupTyVar subst tv of
613 Nothing -> orig_boxy_ty
614 Just ty -> ty `boxyLub` orig_boxy_ty
616 go _ _ = emptyTvSubst -- It's important to *fail* by returning the empty substitution
617 -- Example: Tree a ~ Maybe Int
618 -- We do not want to bind (a |-> Int) in pre-matching, because that can give very
619 -- misleading error messages. An even more confusing case is
620 -- a -> b ~ Maybe Int
621 -- Then we do not want to bind (b |-> Int)! It's always safe to discard bindings
622 -- from this pre-matching phase.
625 go_s tys1 tys2 = boxy_match_s tmpl_tvs tys1 boxy_tvs tys2 subst
628 boxyLub :: BoxySigmaType -> BoxySigmaType -> BoxySigmaType
629 -- Combine boxy information from the two types
630 -- If there is a conflict, return the first
631 boxyLub orig_ty1 orig_ty2
632 = go orig_ty1 orig_ty2
634 go (AppTy f1 a1) (AppTy f2 a2) = AppTy (boxyLub f1 f2) (boxyLub a1 a2)
635 go (FunTy f1 a1) (FunTy f2 a2) = FunTy (boxyLub f1 f2) (boxyLub a1 a2)
636 go (TyConApp tc1 ts1) (TyConApp tc2 ts2)
637 | tc1 == tc2, length ts1 == length ts2
638 = TyConApp tc1 (zipWith boxyLub ts1 ts2)
640 go (TyVarTy tv1) ty2 -- This is the whole point;
641 | isTcTyVar tv1, isBoxyTyVar tv1 -- choose ty2 if ty2 is a box
644 -- Look inside type synonyms, but only if the naive version fails
645 go ty1 ty2 | Just ty1' <- tcView ty1 = go ty1' ty2
646 | Just ty2' <- tcView ty1 = go ty1 ty2'
648 -- For now, we don't look inside ForAlls, PredTys
649 go ty1 ty2 = orig_ty1 -- Default
652 Note [Matching kinds]
653 ~~~~~~~~~~~~~~~~~~~~~
654 The target type might legitimately not be a sub-kind of template.
655 For example, suppose the target is simply a box with an OpenTypeKind,
656 and the template is a type variable with LiftedTypeKind.
657 Then it's ok (because the target type will later be refined).
658 We simply don't bind the template type variable.
660 It might also be that the kind mis-match is an error. For example,
661 suppose we match the template (a -> Int) against (Int# -> Int),
662 where the template type variable 'a' has LiftedTypeKind. This
663 matching function does not fail; it simply doesn't bind the template.
664 Later stuff will fail.
666 %************************************************************************
670 %************************************************************************
672 All the tcSub calls have the form
674 tcSub expected_ty offered_ty
676 offered_ty <= expected_ty
678 That is, that a value of type offered_ty is acceptable in
679 a place expecting a value of type expected_ty.
681 It returns a coercion function
682 co_fn :: offered_ty ~ expected_ty
683 which takes an HsExpr of type offered_ty into one of type
688 tcSubExp :: BoxySigmaType -> BoxySigmaType -> TcM HsWrapper -- Locally used only
689 -- (tcSub act exp) checks that
691 tcSubExp actual_ty expected_ty
692 = -- addErrCtxtM (unifyCtxt actual_ty expected_ty) $
693 -- Adding the error context here leads to some very confusing error
694 -- messages, such as "can't match forall a. a->a with forall a. a->a"
695 -- Example is tcfail165:
696 -- do var <- newEmptyMVar :: IO (MVar (forall a. Show a => a -> String))
697 -- putMVar var (show :: forall a. Show a => a -> String)
698 -- Here the info does not flow from the 'var' arg of putMVar to its 'show' arg
699 -- but after zonking it looks as if it does!
701 -- So instead I'm adding the error context when moving from tc_sub to u_tys
703 traceTc (text "tcSubExp" <+> ppr actual_ty <+> ppr expected_ty) >>
704 tc_sub SubOther actual_ty actual_ty False expected_ty expected_ty
706 tcFunResTy :: Name -> BoxySigmaType -> BoxySigmaType -> TcM HsWrapper -- Locally used only
707 tcFunResTy fun actual_ty expected_ty
708 = traceTc (text "tcFunResTy" <+> ppr actual_ty <+> ppr expected_ty) >>
709 tc_sub (SubFun fun) actual_ty actual_ty False expected_ty expected_ty
712 data SubCtxt = SubDone -- Error-context already pushed
713 | SubFun Name -- Context is tcFunResTy
714 | SubOther -- Context is something else
716 tc_sub :: SubCtxt -- How to add an error-context
717 -> BoxySigmaType -- actual_ty, before expanding synonyms
718 -> BoxySigmaType -- ..and after
719 -> InBox -- True <=> expected_ty is inside a box
720 -> BoxySigmaType -- expected_ty, before
721 -> BoxySigmaType -- ..and after
723 -- The acual_ty is never inside a box
724 -- IMPORTANT pre-condition: if the args contain foralls, the bound type
725 -- variables are visible non-monadically
726 -- (i.e. tha args are sufficiently zonked)
727 -- This invariant is needed so that we can "see" the foralls, ad
728 -- e.g. in the SPEC rule where we just use splitSigmaTy
730 tc_sub sub_ctxt act_sty act_ty exp_ib exp_sty exp_ty
731 = traceTc (text "tc_sub" <+> ppr act_ty $$ ppr exp_ty) >>
732 tc_sub1 sub_ctxt act_sty act_ty exp_ib exp_sty exp_ty
733 -- This indirection is just here to make
734 -- it easy to insert a debug trace!
736 tc_sub1 sub_ctxt act_sty act_ty exp_ib exp_sty exp_ty
737 | Just exp_ty' <- tcView exp_ty = tc_sub sub_ctxt act_sty act_ty exp_ib exp_sty exp_ty'
738 tc_sub1 sub_ctxt act_sty act_ty exp_ib exp_sty exp_ty
739 | Just act_ty' <- tcView act_ty = tc_sub sub_ctxt act_sty act_ty' exp_ib exp_sty exp_ty
741 -----------------------------------
742 -- Rule SBOXY, plus other cases when act_ty is a type variable
743 -- Just defer to boxy matching
744 -- This rule takes precedence over SKOL!
745 tc_sub1 sub_ctxt act_sty (TyVarTy tv) exp_ib exp_sty exp_ty
746 = do { traceTc (text "tc_sub1 - case 1")
747 ; coi <- addSubCtxt sub_ctxt act_sty exp_sty $
748 uVar True False tv exp_ib exp_sty exp_ty
749 ; traceTc (case coi of
750 IdCo -> text "tc_sub1 (Rule SBOXY) IdCo"
751 ACo co -> text "tc_sub1 (Rule SBOXY) ACo" <+> ppr co)
752 ; return $ coiToHsWrapper coi
755 -----------------------------------
756 -- Skolemisation case (rule SKOL)
757 -- actual_ty: d:Eq b => b->b
758 -- expected_ty: forall a. Ord a => a->a
759 -- co_fn e /\a. \d2:Ord a. let d = eqFromOrd d2 in e
761 -- It is essential to do this *before* the specialisation case
762 -- Example: f :: (Eq a => a->a) -> ...
763 -- g :: Ord b => b->b
766 tc_sub1 sub_ctxt act_sty act_ty exp_ib exp_sty exp_ty
768 = do { traceTc (text "tc_sub1 - case 2") ;
769 if exp_ib then -- SKOL does not apply if exp_ty is inside a box
770 defer_to_boxy_matching sub_ctxt act_sty act_ty exp_ib exp_sty exp_ty
772 { (gen_fn, co_fn) <- tcGen exp_ty act_tvs $ \ _ body_exp_ty ->
773 tc_sub sub_ctxt act_sty act_ty False body_exp_ty body_exp_ty
774 ; return (gen_fn <.> co_fn) }
777 act_tvs = tyVarsOfType act_ty
778 -- It's really important to check for escape wrt
779 -- the free vars of both expected_ty *and* actual_ty
781 -----------------------------------
782 -- Specialisation case (rule ASPEC):
783 -- actual_ty: forall a. Ord a => a->a
784 -- expected_ty: Int -> Int
785 -- co_fn e = e Int dOrdInt
787 tc_sub1 sub_ctxt act_sty actual_ty exp_ib exp_sty expected_ty
788 -- Implements the new SPEC rule in the Appendix of the paper
789 -- "Boxy types: inference for higher rank types and impredicativity"
790 -- (This appendix isn't in the published version.)
791 -- The idea is to *first* do pre-subsumption, and then full subsumption
792 -- Example: forall a. a->a <= Int -> (forall b. Int)
793 -- Pre-subsumpion finds a|->Int, and that works fine, whereas
794 -- just running full subsumption would fail.
795 | isSigmaTy actual_ty
796 = do { traceTc (text "tc_sub1 - case 3")
797 ; -- Perform pre-subsumption, and instantiate
798 -- the type with info from the pre-subsumption;
799 -- boxy tyvars if pre-subsumption gives no info
800 let (tyvars, theta, tau) = tcSplitSigmaTy actual_ty
801 tau_tvs = exactTyVarsOfType tau
802 ; inst_tys <- if exp_ib then -- Inside a box, do not do clever stuff
803 do { tyvars' <- mapM tcInstBoxyTyVar tyvars
804 ; return (mkTyVarTys tyvars') }
805 else -- Outside, do clever stuff
806 preSubType tyvars tau_tvs tau expected_ty
807 ; let subst' = zipOpenTvSubst tyvars inst_tys
808 tau' = substTy subst' tau
810 -- Perform a full subsumption check
811 ; traceTc (text "tc_sub_spec" <+> vcat [ppr actual_ty,
812 ppr tyvars <+> ppr theta <+> ppr tau,
814 ; co_fn2 <- tc_sub sub_ctxt tau' tau' exp_ib exp_sty expected_ty
816 -- Deal with the dictionaries
817 -- The origin gives a helpful origin when we have
818 -- a function with type f :: Int -> forall a. Num a => ...
819 -- This way the (Num a) dictionary gets an OccurrenceOf f origin
820 ; let orig = case sub_ctxt of
821 SubFun n -> OccurrenceOf n
822 other -> InstSigOrigin -- Unhelpful
823 ; co_fn1 <- instCall orig inst_tys (substTheta subst' theta)
824 ; return (co_fn2 <.> co_fn1) }
826 -----------------------------------
827 -- Function case (rule F1)
828 tc_sub1 sub_ctxt act_sty (FunTy act_arg act_res) exp_ib exp_sty (FunTy exp_arg exp_res)
829 = do { traceTc (text "tc_sub1 - case 4")
830 ; addSubCtxt sub_ctxt act_sty exp_sty $
831 tc_sub_funs act_arg act_res exp_ib exp_arg exp_res
834 -- Function case (rule F2)
835 tc_sub1 sub_ctxt act_sty act_ty@(FunTy act_arg act_res) _ exp_sty (TyVarTy exp_tv)
837 = addSubCtxt sub_ctxt act_sty exp_sty $
838 do { traceTc (text "tc_sub1 - case 5")
839 ; cts <- readMetaTyVar exp_tv
841 Indirect ty -> tc_sub SubDone act_sty act_ty True exp_sty ty
842 Flexi -> do { [arg_ty,res_ty] <- withMetaTvs exp_tv fun_kinds mk_res_ty
843 ; tc_sub_funs act_arg act_res True arg_ty res_ty } }
845 mk_res_ty [arg_ty', res_ty'] = mkFunTy arg_ty' res_ty'
846 mk_res_ty other = panic "TcUnify.mk_res_ty3"
847 fun_kinds = [argTypeKind, openTypeKind]
849 -- Everything else: defer to boxy matching
850 tc_sub1 sub_ctxt act_sty actual_ty exp_ib exp_sty expected_ty@(TyVarTy exp_tv)
851 = do { traceTc (text "tc_sub1 - case 6a" <+> ppr [isBoxyTyVar exp_tv, isMetaTyVar exp_tv, isSkolemTyVar exp_tv, isExistentialTyVar exp_tv,isSigTyVar exp_tv] )
852 ; defer_to_boxy_matching sub_ctxt act_sty actual_ty exp_ib exp_sty expected_ty
855 tc_sub1 sub_ctxt act_sty actual_ty exp_ib exp_sty expected_ty
856 = do { traceTc (text "tc_sub1 - case 6")
857 ; defer_to_boxy_matching sub_ctxt act_sty actual_ty exp_ib exp_sty expected_ty
860 -----------------------------------
861 defer_to_boxy_matching sub_ctxt act_sty actual_ty exp_ib exp_sty expected_ty
862 = do { coi <- addSubCtxt sub_ctxt act_sty exp_sty $
863 u_tys outer False act_sty actual_ty exp_ib exp_sty expected_ty
864 ; return $ coiToHsWrapper coi
867 outer = case sub_ctxt of -- Ugh
871 -----------------------------------
872 tc_sub_funs act_arg act_res exp_ib exp_arg exp_res
873 = do { arg_coi <- uTys False act_arg exp_ib exp_arg
874 ; co_fn_res <- tc_sub SubDone act_res act_res exp_ib exp_res exp_res
875 ; wrapper1 <- wrapFunResCoercion [exp_arg] co_fn_res
876 ; let wrapper2 = case arg_coi of
878 ACo co -> WpCo $ FunTy co act_res
879 ; return (wrapper1 <.> wrapper2)
882 -----------------------------------
884 :: [TcType] -- Type of args
885 -> HsWrapper -- HsExpr a -> HsExpr b
886 -> TcM HsWrapper -- HsExpr (arg_tys -> a) -> HsExpr (arg_tys -> b)
887 wrapFunResCoercion arg_tys co_fn_res
888 | isIdHsWrapper co_fn_res
893 = do { arg_ids <- newSysLocalIds FSLIT("sub") arg_tys
894 ; return (mkWpLams arg_ids <.> co_fn_res <.> mkWpApps arg_ids) }
899 %************************************************************************
901 \subsection{Generalisation}
903 %************************************************************************
906 tcGen :: BoxySigmaType -- expected_ty
907 -> TcTyVarSet -- Extra tyvars that the universally
908 -- quantified tyvars of expected_ty
909 -- must not be unified
910 -> ([TcTyVar] -> BoxyRhoType -> TcM result)
911 -> TcM (HsWrapper, result)
912 -- The expression has type: spec_ty -> expected_ty
914 tcGen expected_ty extra_tvs thing_inside -- We expect expected_ty to be a forall-type
915 -- If not, the call is a no-op
916 = do { traceTc (text "tcGen")
917 -- We want the GenSkol info in the skolemised type variables to
918 -- mention the *instantiated* tyvar names, so that we get a
919 -- good error message "Rigid variable 'a' is bound by (forall a. a->a)"
920 -- Hence the tiresome but innocuous fixM
921 ; ((tvs', theta', rho'), skol_info) <- fixM (\ ~(_, skol_info) ->
922 do { (forall_tvs, theta, rho_ty) <- tcInstSkolType skol_info expected_ty
923 -- Get loation from monad, not from expected_ty
924 ; let skol_info = GenSkol forall_tvs (mkPhiTy theta rho_ty)
925 ; return ((forall_tvs, theta, rho_ty), skol_info) })
928 ; traceTc (text "tcGen" <+> vcat [text "extra_tvs" <+> ppr extra_tvs,
929 text "expected_ty" <+> ppr expected_ty,
930 text "inst ty" <+> ppr tvs' <+> ppr theta' <+> ppr rho',
931 text "free_tvs" <+> ppr free_tvs])
934 -- Type-check the arg and unify with poly type
935 ; (result, lie) <- getLIE (thing_inside tvs' rho')
937 -- Check that the "forall_tvs" havn't been constrained
938 -- The interesting bit here is that we must include the free variables
939 -- of the expected_ty. Here's an example:
940 -- runST (newVar True)
941 -- Here, if we don't make a check, we'll get a type (ST s (MutVar s Bool))
942 -- for (newVar True), with s fresh. Then we unify with the runST's arg type
943 -- forall s'. ST s' a. That unifies s' with s, and a with MutVar s Bool.
944 -- So now s' isn't unconstrained because it's linked to a.
945 -- Conclusion: include the free vars of the expected_ty in the
946 -- list of "free vars" for the signature check.
948 ; loc <- getInstLoc (SigOrigin skol_info)
949 ; dicts <- newDictBndrs loc theta'
950 ; inst_binds <- tcSimplifyCheck loc tvs' dicts lie
952 ; checkSigTyVarsWrt free_tvs tvs'
953 ; traceTc (text "tcGen:done")
956 -- The WpLet binds any Insts which came out of the simplification.
957 dict_vars = map instToVar dicts
958 co_fn = mkWpTyLams tvs' <.> mkWpLams dict_vars <.> WpLet inst_binds
959 ; returnM (co_fn, result) }
961 free_tvs = tyVarsOfType expected_ty `unionVarSet` extra_tvs
966 %************************************************************************
970 %************************************************************************
972 The exported functions are all defined as versions of some
973 non-exported generic functions.
976 boxyUnify :: BoxyType -> BoxyType -> TcM CoercionI
977 -- Acutal and expected, respectively
979 = addErrCtxtM (unifyCtxt ty1 ty2) $
980 uTysOuter False ty1 False ty2
983 boxyUnifyList :: [BoxyType] -> [BoxyType] -> TcM [CoercionI]
984 -- Arguments should have equal length
985 -- Acutal and expected types
986 boxyUnifyList tys1 tys2 = uList boxyUnify tys1 tys2
989 unifyType :: TcTauType -> TcTauType -> TcM CoercionI
990 -- No boxes expected inside these types
991 -- Acutal and expected types
992 unifyType ty1 ty2 -- ty1 expected, ty2 inferred
993 = ASSERT2( not (isBoxyTy ty1), ppr ty1 )
994 ASSERT2( not (isBoxyTy ty2), ppr ty2 )
995 addErrCtxtM (unifyCtxt ty1 ty2) $
996 uTysOuter True ty1 True ty2
999 unifyPred :: PredType -> PredType -> TcM CoercionI
1000 -- Acutal and expected types
1001 unifyPred p1 p2 = addErrCtxtM (unifyCtxt (mkPredTy p1) (mkPredTy p2)) $
1002 uPred True True p1 True p2
1004 unifyTheta :: TcThetaType -> TcThetaType -> TcM [CoercionI]
1005 -- Acutal and expected types
1006 unifyTheta theta1 theta2
1007 = do { checkTc (equalLength theta1 theta2)
1008 (vcat [ptext SLIT("Contexts differ in length"),
1009 nest 2 $ parens $ ptext SLIT("Use -fglasgow-exts to allow this")])
1010 ; uList unifyPred theta1 theta2
1014 uList :: (a -> a -> TcM b)
1015 -> [a] -> [a] -> TcM [b]
1016 -- Unify corresponding elements of two lists of types, which
1017 -- should be of equal length. We charge down the list explicitly so that
1018 -- we can complain if their lengths differ.
1019 uList unify [] [] = return []
1020 uList unify (ty1:tys1) (ty2:tys2) = do { x <- unify ty1 ty2;
1021 ; xs <- uList unify tys1 tys2
1024 uList unify ty1s ty2s = panic "Unify.uList: mismatched type lists!"
1027 @unifyTypeList@ takes a single list of @TauType@s and unifies them
1028 all together. It is used, for example, when typechecking explicit
1029 lists, when all the elts should be of the same type.
1032 unifyTypeList :: [TcTauType] -> TcM ()
1033 unifyTypeList [] = returnM ()
1034 unifyTypeList [ty] = returnM ()
1035 unifyTypeList (ty1:tys@(ty2:_)) = do { unifyType ty1 ty2
1036 ; unifyTypeList tys }
1039 %************************************************************************
1041 \subsection[Unify-uTys]{@uTys@: getting down to business}
1043 %************************************************************************
1045 @uTys@ is the heart of the unifier. Each arg occurs twice, because
1046 we want to report errors in terms of synomyms if possible. The first of
1047 the pair is used in error messages only; it is always the same as the
1048 second, except that if the first is a synonym then the second may be a
1049 de-synonym'd version. This way we get better error messages.
1051 We call the first one \tr{ps_ty1}, \tr{ps_ty2} for ``possible synomym''.
1054 type SwapFlag = Bool
1055 -- False <=> the two args are (actual, expected) respectively
1056 -- True <=> the two args are (expected, actual) respectively
1058 type InBox = Bool -- True <=> we are inside a box
1059 -- False <=> we are outside a box
1060 -- The importance of this is that if we get "filled-box meets
1061 -- filled-box", we'll look into the boxes and unify... but
1062 -- we must not allow polytypes. But if we are in a box on
1063 -- just one side, then we can allow polytypes
1065 type Outer = Bool -- True <=> this is the outer level of a unification
1066 -- so that the types being unified are the
1067 -- very ones we began with, not some sub
1068 -- component or synonym expansion
1069 -- The idea is that if Outer is true then unifyMisMatch should
1070 -- pop the context to remove the "Expected/Acutal" context
1073 :: InBox -> TcType -- ty1 is the *actual* type
1074 -> InBox -> TcType -- ty2 is the *expected* type
1076 uTysOuter nb1 ty1 nb2 ty2
1077 = do { traceTc (text "uTysOuter" <+> ppr ty1 <+> ppr ty2)
1078 ; u_tys True nb1 ty1 ty1 nb2 ty2 ty2 }
1079 uTys nb1 ty1 nb2 ty2
1080 = do { traceTc (text "uTys" <+> ppr ty1 <+> ppr ty2)
1081 ; u_tys False nb1 ty1 ty1 nb2 ty2 ty2 }
1085 uTys_s :: InBox -> [TcType] -- tys1 are the *actual* types
1086 -> InBox -> [TcType] -- tys2 are the *expected* types
1088 uTys_s nb1 [] nb2 [] = returnM []
1089 uTys_s nb1 (ty1:tys1) nb2 (ty2:tys2) = do { coi <- uTys nb1 ty1 nb2 ty2
1090 ; cois <- uTys_s nb1 tys1 nb2 tys2
1093 uTys_s nb1 ty1s nb2 ty2s = panic "Unify.uTys_s: mismatched type lists!"
1097 -> InBox -> TcType -> TcType -- ty1 is the *actual* type
1098 -> InBox -> TcType -> TcType -- ty2 is the *expected* type
1101 u_tys outer nb1 orig_ty1 ty1 nb2 orig_ty2 ty2
1102 = do { traceTc (text "u_tys " <+> ppr ty1 <+> text " " <+> ppr ty2)
1103 ; coi <- go outer ty1 ty2
1104 ; traceTc (case coi of
1105 ACo co -> text "u_tys yields coercion: " <+> ppr co
1106 IdCo -> text "u_tys yields no coercion")
1111 go :: Outer -> TcType -> TcType -> TcM CoercionI
1113 do { traceTc (text "go " <+> ppr orig_ty1 <+> text "/" <+> ppr ty1
1114 <+> ppr orig_ty2 <+> text "/" <+> ppr ty2)
1118 go1 :: Outer -> TcType -> TcType -> TcM CoercionI
1119 -- Always expand synonyms: see Note [Unification and synonyms]
1120 -- (this also throws away FTVs)
1122 | Just ty1' <- tcView ty1 = go False ty1' ty2
1123 | Just ty2' <- tcView ty2 = go False ty1 ty2'
1125 -- Variables; go for uVar
1126 go1 outer (TyVarTy tyvar1) ty2 = uVar outer False tyvar1 nb2 orig_ty2 ty2
1127 go1 outer ty1 (TyVarTy tyvar2) = uVar outer True tyvar2 nb1 orig_ty1 ty1
1128 -- "True" means args swapped
1130 -- The case for sigma-types must *follow* the variable cases
1131 -- because a boxy variable can be filed with a polytype;
1132 -- but must precede FunTy, because ((?x::Int) => ty) look
1133 -- like a FunTy; there isn't necy a forall at the top
1135 | isSigmaTy ty1 || isSigmaTy ty2
1136 = do { traceTc (text "We have sigma types: equalLength" <+> ppr tvs1 <+> ppr tvs2)
1137 ; checkM (equalLength tvs1 tvs2)
1138 (unifyMisMatch outer False orig_ty1 orig_ty2)
1139 ; traceTc (text "We're past the first length test")
1140 ; tvs <- tcInstSkolTyVars UnkSkol tvs1 -- Not a helpful SkolemInfo
1141 -- Get location from monad, not from tvs1
1142 ; let tys = mkTyVarTys tvs
1143 in_scope = mkInScopeSet (mkVarSet tvs)
1144 phi1 = substTy (mkTvSubst in_scope (zipTyEnv tvs1 tys)) body1
1145 phi2 = substTy (mkTvSubst in_scope (zipTyEnv tvs2 tys)) body2
1146 (theta1,tau1) = tcSplitPhiTy phi1
1147 (theta2,tau2) = tcSplitPhiTy phi2
1149 ; addErrCtxtM (unifyForAllCtxt tvs phi1 phi2) $ do
1150 { checkM (equalLength theta1 theta2)
1151 (unifyMisMatch outer False orig_ty1 orig_ty2)
1153 ; cois <- uPreds False 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 ; ifM (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 ; ifM (nb1 && nb2) (notMonoType ty1)
1172 (tvs1, body1) = tcSplitForAllTys ty1
1173 (tvs2, body2) = tcSplitForAllTys ty2
1176 go1 outer (PredTy p1) (PredTy p2)
1177 = uPred False nb1 p1 nb2 p2
1179 -- Type constructors must match
1180 go1 _ (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 go1 _ (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 go1 outer (AppTy s1 t1) ty2
1209 | Just (s2,t2) <- tcSplitAppTy_maybe ty2
1210 = do { coi_s <- uTys nb1 s1 nb2 s2; coi_t <- uTys nb1 t1 nb2 t2
1211 ; return $ mkAppTyCoI s1 coi_s t1 coi_t }
1213 -- Now the same, but the other way round
1214 -- Don't swap the types, because the error messages get worse
1215 go1 outer ty1 (AppTy s2 t2)
1216 | Just (s1,t1) <- tcSplitAppTy_maybe ty1
1217 = do { coi_s <- uTys nb1 s1 nb2 s2; coi_t <- uTys nb1 t1 nb2 t2
1218 ; return $ mkAppTyCoI s1 coi_s t1 coi_t }
1220 -- One or both outermost constructors are type family applications.
1221 -- If we can normalise them away, proceed as usual; otherwise, we
1222 -- need to defer unification by generating a wanted equality constraint.
1224 | ty1_is_fun || ty2_is_fun
1225 = do { (coi1, ty1') <- if ty1_is_fun then tcNormaliseFamInst ty1
1226 else return (IdCo, ty1)
1227 ; (coi2, ty2') <- if ty2_is_fun then tcNormaliseFamInst ty2
1228 else return (IdCo, ty2)
1229 ; coi <- if isOpenSynTyConApp ty1' || isOpenSynTyConApp ty2'
1230 then do { -- One type family app can't be reduced yet
1232 ; ty1'' <- zonkTcType ty1'
1233 ; ty2'' <- zonkTcType ty2'
1234 ; if tcEqType ty1'' ty2''
1236 else -- see [Deferred Unification]
1237 defer_unification outer False orig_ty1 orig_ty2
1239 else -- unification can proceed
1241 ; return $ coi1 `mkTransCoI` coi `mkTransCoI` (mkSymCoI coi2)
1244 ty1_is_fun = isOpenSynTyConApp ty1
1245 ty2_is_fun = isOpenSynTyConApp ty2
1247 -- Anything else fails
1248 go1 outer _ _ = unifyMisMatch outer False orig_ty1 orig_ty2
1252 uPred outer nb1 (IParam n1 t1) nb2 (IParam n2 t2)
1254 do { coi <- uTys nb1 t1 nb2 t2
1255 ; return $ mkIParamPredCoI n1 coi
1257 uPred outer nb1 (ClassP c1 tys1) nb2 (ClassP c2 tys2)
1259 do { cois <- uTys_s nb1 tys1 nb2 tys2 -- Guaranteed equal lengths because the kinds check
1260 ; return $ mkClassPPredCoI c1 tys1 cois
1262 uPred outer _ p1 _ p2 = unifyMisMatch outer False (mkPredTy p1) (mkPredTy p2)
1264 uPreds outer nb1 [] nb2 [] = return []
1265 uPreds outer nb1 (p1:ps1) nb2 (p2:ps2) =
1266 do { coi <- uPred outer nb1 p1 nb2 p2
1267 ; cois <- uPreds outer nb1 ps1 nb2 ps2
1270 uPreds outer nb1 ps1 nb2 ps2 = panic "uPreds"
1275 When we find two TyConApps, the argument lists are guaranteed equal
1276 length. Reason: intially the kinds of the two types to be unified is
1277 the same. The only way it can become not the same is when unifying two
1278 AppTys (f1 a1):=:(f2 a2). In that case there can't be a TyConApp in
1279 the f1,f2 (because it'd absorb the app). If we unify f1:=:f2 first,
1280 which we do, that ensures that f1,f2 have the same kind; and that
1281 means a1,a2 have the same kind. And now the argument repeats.
1283 Note [OpenSynTyCon app]
1284 ~~~~~~~~~~~~~~~~~~~~~~~
1287 type family T a :: * -> *
1289 the two types (T () a) and (T () Int) must unify, even if there are
1290 no type instances for T at all. Should we just turn them into an
1291 equality (T () a ~ T () Int)? I don't think so. We currently try to
1292 eagerly unify everything we can before generating equalities; otherwise,
1293 we could turn the unification of [Int] with [a] into an equality, too.
1295 Note [Unification and synonyms]
1296 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1297 If you are tempted to make a short cut on synonyms, as in this
1301 -- NO uTys (SynTy con1 args1 ty1) (SynTy con2 args2 ty2)
1302 -- NO = if (con1 == con2) then
1303 -- NO -- Good news! Same synonym constructors, so we can shortcut
1304 -- NO -- by unifying their arguments and ignoring their expansions.
1305 -- NO unifyTypepeLists args1 args2
1307 -- NO -- Never mind. Just expand them and try again
1311 then THINK AGAIN. Here is the whole story, as detected and reported
1312 by Chris Okasaki \tr{<Chris_Okasaki@loch.mess.cs.cmu.edu>}:
1314 Here's a test program that should detect the problem:
1318 x = (1 :: Bogus Char) :: Bogus Bool
1321 The problem with [the attempted shortcut code] is that
1325 is not a sufficient condition to be able to use the shortcut!
1326 You also need to know that the type synonym actually USES all
1327 its arguments. For example, consider the following type synonym
1328 which does not use all its arguments.
1333 If you ever tried unifying, say, \tr{Bogus Char} with \tr{Bogus Bool},
1334 the unifier would blithely try to unify \tr{Char} with \tr{Bool} and
1335 would fail, even though the expanded forms (both \tr{Int}) should
1338 Similarly, unifying \tr{Bogus Char} with \tr{Bogus t} would
1339 unnecessarily bind \tr{t} to \tr{Char}.
1341 ... You could explicitly test for the problem synonyms and mark them
1342 somehow as needing expansion, perhaps also issuing a warning to the
1347 %************************************************************************
1349 \subsection[Unify-uVar]{@uVar@: unifying with a type variable}
1351 %************************************************************************
1353 @uVar@ is called when at least one of the types being unified is a
1354 variable. It does {\em not} assume that the variable is a fixed point
1355 of the substitution; rather, notice that @uVar@ (defined below) nips
1356 back into @uTys@ if it turns out that the variable is already bound.
1360 -> SwapFlag -- False => tyvar is the "actual" (ty is "expected")
1361 -- True => ty is the "actual" (tyvar is "expected")
1363 -> InBox -- True <=> definitely no boxes in t2
1364 -> TcTauType -> TcTauType -- printing and real versions
1367 uVar outer swapped tv1 nb2 ps_ty2 ty2
1368 = do { let expansion | showSDoc (ppr ty2) == showSDoc (ppr ps_ty2) = empty
1369 | otherwise = brackets (equals <+> ppr ty2)
1370 ; traceTc (text "uVar" <+> ppr swapped <+>
1371 sep [ppr tv1 <+> dcolon <+> ppr (tyVarKind tv1 ),
1372 nest 2 (ptext SLIT(" <-> ")),
1373 ppr ps_ty2 <+> dcolon <+> ppr (typeKind ty2) <+> expansion])
1374 ; details <- lookupTcTyVar tv1
1377 | swapped -> u_tys outer nb2 ps_ty2 ty2 True ty1 ty1 -- Swap back
1378 | otherwise -> u_tys outer True ty1 ty1 nb2 ps_ty2 ty2 -- Same order
1379 -- The 'True' here says that ty1 is now inside a box
1380 DoneTv details1 -> uUnfilledVar outer swapped tv1 details1 ps_ty2 ty2
1384 uUnfilledVar :: Outer
1386 -> TcTyVar -> TcTyVarDetails -- Tyvar 1
1387 -> TcTauType -> TcTauType -- Type 2
1389 -- Invariant: tyvar 1 is not unified with anything
1391 uUnfilledVar outer swapped tv1 details1 ps_ty2 ty2
1392 | Just ty2' <- tcView ty2
1393 = -- Expand synonyms; ignore FTVs
1394 uUnfilledVar False swapped tv1 details1 ps_ty2 ty2'
1396 uUnfilledVar outer swapped tv1 details1 ps_ty2 (TyVarTy tv2)
1397 | tv1 == tv2 -- Same type variable => no-op (but watch out for the boxy case)
1399 MetaTv BoxTv ref1 -- A boxy type variable meets itself;
1400 -- this is box-meets-box, so fill in with a tau-type
1401 -> do { tau_tv <- tcInstTyVar tv1
1402 ; updateMeta tv1 ref1 (mkTyVarTy tau_tv)
1405 other -> returnM IdCo -- No-op
1407 | otherwise -- Distinct type variables
1408 = do { lookup2 <- lookupTcTyVar tv2
1410 IndirectTv ty2' -> uUnfilledVar outer swapped tv1 details1 ty2' ty2'
1411 DoneTv details2 -> uUnfilledVars outer swapped tv1 details1 tv2 details2
1414 uUnfilledVar outer swapped tv1 details1 ps_ty2 non_var_ty2
1415 = -- ty2 is not a type variable
1417 MetaTv (SigTv _) _ -> rigid_variable
1419 uMetaVar outer swapped tv1 info ref1 ps_ty2 non_var_ty2
1420 SkolemTv _ -> rigid_variable
1423 | isOpenSynTyConApp non_var_ty2
1424 = -- 'non_var_ty2's outermost constructor is a type family,
1425 -- which we may may be able to normalise
1426 do { (coi2, ty2') <- tcNormaliseFamInst non_var_ty2
1428 IdCo -> -- no progress, but maybe after other instantiations
1429 defer_unification outer swapped (TyVarTy tv1) ps_ty2
1430 ACo co -> -- progress: so lets try again
1432 ppr co <+> text "::"<+> ppr non_var_ty2 <+> text "~" <+>
1434 ; coi <- uUnfilledVar outer swapped tv1 details1 ps_ty2 ty2'
1435 ; let coi2' = (if swapped then id else mkSymCoI) coi2
1436 ; return $ coi2' `mkTransCoI` coi
1439 | SkolemTv RuntimeUnkSkol <- details1
1440 -- runtime unknown will never match
1441 = unifyMisMatch outer swapped (TyVarTy tv1) ps_ty2
1442 | otherwise -- defer as a given equality may still resolve this
1443 = defer_unification outer swapped (TyVarTy tv1) ps_ty2
1446 Note [Deferred Unification]
1447 ~~~~~~~~~~~~~~~~~~~~
1448 We may encounter a unification ty1 = ty2 that cannot be performed syntactically,
1449 and yet its consistency is undetermined. Previously, there was no way to still
1450 make it consistent. So a mismatch error was issued.
1452 Now these unfications are deferred until constraint simplification, where type
1453 family instances and given equations may (or may not) establish the consistency.
1454 Deferred unifications are of the form
1457 where F is a type function and x is a type variable.
1459 id :: x ~ y => x -> y
1462 involves the unfication x = y. It is deferred until we bring into account the
1463 context x ~ y to establish that it holds.
1465 If available, we defer original types (rather than those where closed type
1466 synonyms have already been expanded via tcCoreView). This is, as usual, to
1467 improve error messages.
1469 We need to both 'unBox' and zonk deferred types. We need to unBox as
1470 functions, such as TcExpr.tcMonoExpr promise to fill boxes in the expected
1471 type. We need to zonk as the types go into the kind of the coercion variable
1472 `cotv' and those are not zonked in Inst.zonkInst. (Maybe it would be better
1473 to zonk in zonInst instead. Would that be sufficient?)
1476 defer_unification :: Bool -- pop innermost context?
1481 defer_unification outer True ty1 ty2
1482 = defer_unification outer False ty2 ty1
1483 defer_unification outer False ty1 ty2
1484 = do { ty1' <- unBox ty1 >>= zonkTcType -- unbox *and* zonk..
1485 ; ty2' <- unBox ty2 >>= zonkTcType -- ..see preceding note
1486 ; traceTc $ text "deferring:" <+> ppr ty1 <+> text "~" <+> ppr ty2
1487 ; cotv <- newMetaCoVar ty1' ty2'
1488 -- put ty1 ~ ty2 in LIE
1489 -- Left means "wanted"
1490 ; inst <- (if outer then popErrCtxt else id) $
1491 mkEqInst (EqPred ty1' ty2') (Left cotv)
1493 ; return $ ACo $ TyVarTy cotv }
1496 uMetaVar :: Bool -- pop innermost context?
1498 -> TcTyVar -> BoxInfo -> IORef MetaDetails
1501 -- tv1 is an un-filled-in meta type variable (maybe boxy, maybe tau)
1502 -- ty2 is not a type variable
1504 uMetaVar outer swapped tv1 BoxTv ref1 ps_ty2 non_var_ty2
1505 = -- tv1 is a BoxTv. So we must unbox ty2, to ensure
1506 -- that any boxes in ty2 are filled with monotypes
1508 -- It should not be the case that tv1 occurs in ty2
1509 -- (i.e. no occurs check should be needed), but if perchance
1510 -- it does, the unbox operation will fill it, and the DEBUG
1512 do { final_ty <- unBox ps_ty2
1514 ; meta_details <- readMutVar ref1
1515 ; case meta_details of
1516 Indirect ty -> WARN( True, ppr tv1 <+> ppr ty )
1517 return () -- This really should *not* happen
1520 ; checkUpdateMeta swapped tv1 ref1 final_ty
1524 uMetaVar outer swapped tv1 info1 ref1 ps_ty2 non_var_ty2
1525 = do { -- Occurs check + monotype check
1526 ; mb_final_ty <- checkTauTvUpdate tv1 ps_ty2
1527 ; case mb_final_ty of
1528 Nothing -> -- tv1 occured in type family parameter
1529 defer_unification outer swapped (mkTyVarTy tv1) ps_ty2
1531 do { checkUpdateMeta swapped tv1 ref1 final_ty
1537 uUnfilledVars :: Outer
1539 -> TcTyVar -> TcTyVarDetails -- Tyvar 1
1540 -> TcTyVar -> TcTyVarDetails -- Tyvar 2
1542 -- Invarant: The type variables are distinct,
1543 -- Neither is filled in yet
1544 -- They might be boxy or not
1546 uUnfilledVars outer swapped tv1 (SkolemTv _) tv2 (SkolemTv _)
1547 = -- see [Deferred Unification]
1548 defer_unification outer swapped (mkTyVarTy tv1) (mkTyVarTy tv2)
1550 uUnfilledVars outer swapped tv1 (MetaTv info1 ref1) tv2 (SkolemTv _)
1551 = checkUpdateMeta swapped tv1 ref1 (mkTyVarTy tv2) >> return IdCo
1552 uUnfilledVars outer swapped tv1 (SkolemTv _) tv2 (MetaTv info2 ref2)
1553 = checkUpdateMeta (not swapped) tv2 ref2 (mkTyVarTy tv1) >> return IdCo
1555 -- ToDo: this function seems too long for what it acutally does!
1556 uUnfilledVars outer swapped tv1 (MetaTv info1 ref1) tv2 (MetaTv info2 ref2)
1557 = case (info1, info2) of
1558 (BoxTv, BoxTv) -> box_meets_box >> return IdCo
1560 -- If a box meets a TauTv, but the fomer has the smaller kind
1561 -- then we must create a fresh TauTv with the smaller kind
1562 (_, BoxTv) | k1_sub_k2 -> update_tv2 >> return IdCo
1563 | otherwise -> box_meets_box >> return IdCo
1564 (BoxTv, _ ) | k2_sub_k1 -> update_tv1 >> return IdCo
1565 | otherwise -> box_meets_box >> return IdCo
1567 -- Avoid SigTvs if poss
1568 (SigTv _, _ ) | k1_sub_k2 -> update_tv2 >> return IdCo
1569 (_, SigTv _) | k2_sub_k1 -> update_tv1 >> return IdCo
1571 (_, _) | k1_sub_k2 -> if k2_sub_k1 && nicer_to_update_tv1
1572 then update_tv1 >> return IdCo -- Same kinds
1573 else update_tv2 >> return IdCo
1574 | k2_sub_k1 -> update_tv1 >> return IdCo
1575 | otherwise -> kind_err >> return IdCo
1577 -- Update the variable with least kind info
1578 -- See notes on type inference in Kind.lhs
1579 -- The "nicer to" part only applies if the two kinds are the same,
1580 -- so we can choose which to do.
1582 -- Kinds should be guaranteed ok at this point
1583 update_tv1 = updateMeta tv1 ref1 (mkTyVarTy tv2)
1584 update_tv2 = updateMeta tv2 ref2 (mkTyVarTy tv1)
1586 box_meets_box | k1_sub_k2 = if k2_sub_k1 && nicer_to_update_tv1
1589 | k2_sub_k1 = fill_from tv2
1590 | otherwise = kind_err
1592 -- Update *both* tyvars with a TauTv whose name and kind
1593 -- are gotten from tv (avoid losing nice names is poss)
1594 fill_from tv = do { tv' <- tcInstTyVar tv
1595 ; let tau_ty = mkTyVarTy tv'
1596 ; updateMeta tv1 ref1 tau_ty
1597 ; updateMeta tv2 ref2 tau_ty }
1599 kind_err = addErrCtxtM (unifyKindCtxt swapped tv1 (mkTyVarTy tv2)) $
1600 unifyKindMisMatch k1 k2
1604 k1_sub_k2 = k1 `isSubKind` k2
1605 k2_sub_k1 = k2 `isSubKind` k1
1607 nicer_to_update_tv1 = isSystemName (Var.varName tv1)
1608 -- Try to update sys-y type variables in preference to ones
1609 -- gotten (say) by instantiating a polymorphic function with
1610 -- a user-written type sig
1614 refineBox :: TcType -> TcM TcType
1615 -- Unbox the outer box of a boxy type (if any)
1616 refineBox ty@(TyVarTy box_tv)
1617 | isMetaTyVar box_tv
1618 = do { cts <- readMetaTyVar box_tv
1621 Indirect ty -> return ty }
1622 refineBox other_ty = return other_ty
1624 refineBoxToTau :: TcType -> TcM TcType
1625 -- Unbox the outer box of a boxy type, filling with a monotype if it is empty
1626 -- Like refineBox except for the "fill with monotype" part.
1627 refineBoxToTau ty@(TyVarTy box_tv)
1628 | isMetaTyVar box_tv
1629 , MetaTv BoxTv ref <- tcTyVarDetails box_tv
1630 = do { cts <- readMutVar ref
1632 Flexi -> fillBoxWithTau box_tv ref
1633 Indirect ty -> return ty }
1634 refineBoxToTau other_ty = return other_ty
1636 zapToMonotype :: BoxySigmaType -> TcM TcTauType
1637 -- Subtle... we must zap the boxy res_ty
1638 -- to kind * before using it to instantiate a LitInst
1639 -- Calling unBox instead doesn't do the job, because the box
1640 -- often has an openTypeKind, and we don't want to instantiate
1642 zapToMonotype res_ty
1643 = do { res_tau <- newFlexiTyVarTy liftedTypeKind
1644 ; boxyUnify res_tau res_ty
1647 unBox :: BoxyType -> TcM TcType
1648 -- unBox implements the judgement
1650 -- with input s', and result s
1652 -- It removes all boxes from the input type, returning a non-boxy type.
1653 -- A filled box in the type can only contain a monotype; unBox fails if not
1654 -- The type can have empty boxes, which unBox fills with a monotype
1656 -- Compare this wth checkTauTvUpdate
1658 -- For once, it's safe to treat synonyms as opaque!
1660 unBox (NoteTy n ty) = do { ty' <- unBox ty; return (NoteTy n ty') }
1661 unBox (TyConApp tc tys) = do { tys' <- mapM unBox tys; return (TyConApp tc tys') }
1662 unBox (AppTy f a) = do { f' <- unBox f; a' <- unBox a; return (mkAppTy f' a') }
1663 unBox (FunTy f a) = do { f' <- unBox f; a' <- unBox a; return (FunTy f' a') }
1664 unBox (PredTy p) = do { p' <- unBoxPred p; return (PredTy p') }
1665 unBox (ForAllTy tv ty) = ASSERT( isImmutableTyVar tv )
1666 do { ty' <- unBox ty; return (ForAllTy tv ty') }
1668 | isTcTyVar tv -- It's a boxy type variable
1669 , MetaTv BoxTv ref <- tcTyVarDetails tv -- NB: non-TcTyVars are possible
1670 = do { cts <- readMutVar ref -- under nested quantifiers
1672 Flexi -> fillBoxWithTau tv ref
1673 Indirect ty -> do { non_boxy_ty <- unBox ty
1674 ; if isTauTy non_boxy_ty
1675 then return non_boxy_ty
1676 else notMonoType non_boxy_ty }
1678 | otherwise -- Skolems, and meta-tau-variables
1679 = return (TyVarTy tv)
1681 unBoxPred (ClassP cls tys) = do { tys' <- mapM unBox tys; return (ClassP cls tys') }
1682 unBoxPred (IParam ip ty) = do { ty' <- unBox ty; return (IParam ip ty') }
1683 unBoxPred (EqPred ty1 ty2) = do { ty1' <- unBox ty1; ty2' <- unBox ty2; return (EqPred ty1' ty2') }
1688 %************************************************************************
1690 \subsection[Unify-context]{Errors and contexts}
1692 %************************************************************************
1698 unifyCtxt act_ty exp_ty tidy_env
1699 = do { act_ty' <- zonkTcType act_ty
1700 ; exp_ty' <- zonkTcType exp_ty
1701 ; let (env1, exp_ty'') = tidyOpenType tidy_env exp_ty'
1702 (env2, act_ty'') = tidyOpenType env1 act_ty'
1703 ; return (env2, mkExpectedActualMsg act_ty'' exp_ty'') }
1706 mkExpectedActualMsg act_ty exp_ty
1707 = nest 2 (vcat [ text "Expected type" <> colon <+> ppr exp_ty,
1708 text "Inferred type" <> colon <+> ppr act_ty ])
1711 -- If an error happens we try to figure out whether the function
1712 -- function has been given too many or too few arguments, and say so.
1713 addSubCtxt SubDone actual_res_ty expected_res_ty thing_inside
1715 addSubCtxt sub_ctxt actual_res_ty expected_res_ty thing_inside
1716 = addErrCtxtM mk_err thing_inside
1719 = do { exp_ty' <- zonkTcType expected_res_ty
1720 ; act_ty' <- zonkTcType actual_res_ty
1721 ; let (env1, exp_ty'') = tidyOpenType tidy_env exp_ty'
1722 (env2, act_ty'') = tidyOpenType env1 act_ty'
1723 (exp_args, _) = tcSplitFunTys exp_ty''
1724 (act_args, _) = tcSplitFunTys act_ty''
1726 len_act_args = length act_args
1727 len_exp_args = length exp_args
1729 message = case sub_ctxt of
1730 SubFun fun | len_exp_args < len_act_args -> wrongArgsCtxt "too few" fun
1731 | len_exp_args > len_act_args -> wrongArgsCtxt "too many" fun
1732 other -> mkExpectedActualMsg act_ty'' exp_ty''
1733 ; return (env2, message) }
1735 wrongArgsCtxt too_many_or_few fun
1736 = ptext SLIT("Probable cause:") <+> quotes (ppr fun)
1737 <+> ptext SLIT("is applied to") <+> text too_many_or_few
1738 <+> ptext SLIT("arguments")
1741 unifyForAllCtxt tvs phi1 phi2 env
1742 = returnM (env2, msg)
1744 (env', tvs') = tidyOpenTyVars env tvs -- NB: not tidyTyVarBndrs
1745 (env1, phi1') = tidyOpenType env' phi1
1746 (env2, phi2') = tidyOpenType env1 phi2
1747 msg = vcat [ptext SLIT("When matching") <+> quotes (ppr (mkForAllTys tvs' phi1')),
1748 ptext SLIT(" and") <+> quotes (ppr (mkForAllTys tvs' phi2'))]
1750 -----------------------
1751 unifyMisMatch outer swapped ty1 ty2
1752 = do { (env, msg) <- if swapped then misMatchMsg ty2 ty1
1753 else misMatchMsg ty1 ty2
1755 -- This is the whole point of the 'outer' stuff
1756 ; if outer then popErrCtxt (failWithTcM (env, msg))
1757 else failWithTcM (env, msg)
1762 %************************************************************************
1766 %************************************************************************
1768 Unifying kinds is much, much simpler than unifying types.
1771 unifyKind :: TcKind -- Expected
1774 unifyKind (TyConApp kc1 []) (TyConApp kc2 [])
1775 | isSubKindCon kc2 kc1 = returnM ()
1777 unifyKind (FunTy a1 r1) (FunTy a2 r2)
1778 = do { unifyKind a2 a1; unifyKind r1 r2 }
1779 -- Notice the flip in the argument,
1780 -- so that the sub-kinding works right
1781 unifyKind (TyVarTy kv1) k2 = uKVar False kv1 k2
1782 unifyKind k1 (TyVarTy kv2) = uKVar True kv2 k1
1783 unifyKind k1 k2 = unifyKindMisMatch k1 k2
1785 unifyKinds :: [TcKind] -> [TcKind] -> TcM ()
1786 unifyKinds [] [] = returnM ()
1787 unifyKinds (k1:ks1) (k2:ks2) = unifyKind k1 k2 `thenM_`
1789 unifyKinds _ _ = panic "unifyKinds: length mis-match"
1792 uKVar :: Bool -> KindVar -> TcKind -> TcM ()
1793 uKVar swapped kv1 k2
1794 = do { mb_k1 <- readKindVar kv1
1796 Flexi -> uUnboundKVar swapped kv1 k2
1797 Indirect k1 | swapped -> unifyKind k2 k1
1798 | otherwise -> unifyKind k1 k2 }
1801 uUnboundKVar :: Bool -> KindVar -> TcKind -> TcM ()
1802 uUnboundKVar swapped kv1 k2@(TyVarTy kv2)
1803 | kv1 == kv2 = returnM ()
1804 | otherwise -- Distinct kind variables
1805 = do { mb_k2 <- readKindVar kv2
1807 Indirect k2 -> uUnboundKVar swapped kv1 k2
1808 Flexi -> writeKindVar kv1 k2 }
1810 uUnboundKVar swapped kv1 non_var_k2
1811 = do { k2' <- zonkTcKind non_var_k2
1812 ; kindOccurCheck kv1 k2'
1813 ; k2'' <- kindSimpleKind swapped k2'
1814 -- KindVars must be bound only to simple kinds
1815 -- Polarities: (kindSimpleKind True ?) succeeds
1816 -- returning *, corresponding to unifying
1819 ; writeKindVar kv1 k2'' }
1822 kindOccurCheck kv1 k2 -- k2 is zonked
1823 = checkTc (not_in k2) (kindOccurCheckErr kv1 k2)
1825 not_in (TyVarTy kv2) = kv1 /= kv2
1826 not_in (FunTy a2 r2) = not_in a2 && not_in r2
1829 kindSimpleKind :: Bool -> Kind -> TcM SimpleKind
1830 -- (kindSimpleKind True k) returns a simple kind sk such that sk <: k
1831 -- If the flag is False, it requires k <: sk
1832 -- E.g. kindSimpleKind False ?? = *
1833 -- What about (kv -> *) :=: ?? -> *
1834 kindSimpleKind orig_swapped orig_kind
1835 = go orig_swapped orig_kind
1837 go sw (FunTy k1 k2) = do { k1' <- go (not sw) k1
1839 ; return (mkArrowKind k1' k2') }
1841 | isOpenTypeKind k = return liftedTypeKind
1842 | isArgTypeKind k = return liftedTypeKind
1844 | isLiftedTypeKind k = return liftedTypeKind
1845 | isUnliftedTypeKind k = return unliftedTypeKind
1846 go sw k@(TyVarTy _) = return k -- KindVars are always simple
1847 go swapped kind = failWithTc (ptext SLIT("Unexpected kind unification failure:")
1848 <+> ppr orig_swapped <+> ppr orig_kind)
1849 -- I think this can't actually happen
1851 -- T v = MkT v v must be a type
1852 -- T v w = MkT (v -> w) v must not be an umboxed tuple
1855 kindOccurCheckErr tyvar ty
1856 = hang (ptext SLIT("Occurs check: cannot construct the infinite kind:"))
1857 2 (sep [ppr tyvar, char '=', ppr ty])
1861 unifyFunKind :: TcKind -> TcM (Maybe (TcKind, TcKind))
1862 -- Like unifyFunTy, but does not fail; instead just returns Nothing
1864 unifyFunKind (TyVarTy kvar)
1865 = readKindVar kvar `thenM` \ maybe_kind ->
1867 Indirect fun_kind -> unifyFunKind fun_kind
1869 do { arg_kind <- newKindVar
1870 ; res_kind <- newKindVar
1871 ; writeKindVar kvar (mkArrowKind arg_kind res_kind)
1872 ; returnM (Just (arg_kind,res_kind)) }
1874 unifyFunKind (FunTy arg_kind res_kind) = returnM (Just (arg_kind,res_kind))
1875 unifyFunKind other = returnM Nothing
1878 %************************************************************************
1882 %************************************************************************
1884 ---------------------------
1885 -- We would like to get a decent error message from
1886 -- (a) Under-applied type constructors
1887 -- f :: (Maybe, Maybe)
1888 -- (b) Over-applied type constructors
1889 -- f :: Int x -> Int x
1893 checkExpectedKind :: Outputable a => a -> TcKind -> TcKind -> TcM ()
1894 -- A fancy wrapper for 'unifyKind', which tries
1895 -- to give decent error messages.
1896 -- (checkExpectedKind ty act_kind exp_kind)
1897 -- checks that the actual kind act_kind is compatible
1898 -- with the expected kind exp_kind
1899 -- The first argument, ty, is used only in the error message generation
1900 checkExpectedKind ty act_kind exp_kind
1901 | act_kind `isSubKind` exp_kind -- Short cut for a very common case
1904 = tryTc (unifyKind exp_kind act_kind) `thenM` \ (_errs, mb_r) ->
1906 Just r -> returnM () ; -- Unification succeeded
1909 -- So there's definitely an error
1910 -- Now to find out what sort
1911 zonkTcKind exp_kind `thenM` \ exp_kind ->
1912 zonkTcKind act_kind `thenM` \ act_kind ->
1914 tcInitTidyEnv `thenM` \ env0 ->
1915 let (exp_as, _) = splitKindFunTys exp_kind
1916 (act_as, _) = splitKindFunTys act_kind
1917 n_exp_as = length exp_as
1918 n_act_as = length act_as
1920 (env1, tidy_exp_kind) = tidyKind env0 exp_kind
1921 (env2, tidy_act_kind) = tidyKind env1 act_kind
1923 err | n_exp_as < n_act_as -- E.g. [Maybe]
1924 = quotes (ppr ty) <+> ptext SLIT("is not applied to enough type arguments")
1926 -- Now n_exp_as >= n_act_as. In the next two cases,
1927 -- n_exp_as == 0, and hence so is n_act_as
1928 | isLiftedTypeKind exp_kind && isUnliftedTypeKind act_kind
1929 = ptext SLIT("Expecting a lifted type, but") <+> quotes (ppr ty)
1930 <+> ptext SLIT("is unlifted")
1932 | isUnliftedTypeKind exp_kind && isLiftedTypeKind act_kind
1933 = ptext SLIT("Expecting an unlifted type, but") <+> quotes (ppr ty)
1934 <+> ptext SLIT("is lifted")
1936 | otherwise -- E.g. Monad [Int]
1937 = ptext SLIT("Kind mis-match")
1939 more_info = sep [ ptext SLIT("Expected kind") <+>
1940 quotes (pprKind tidy_exp_kind) <> comma,
1941 ptext SLIT("but") <+> quotes (ppr ty) <+>
1942 ptext SLIT("has kind") <+> quotes (pprKind tidy_act_kind)]
1944 failWithTcM (env2, err $$ more_info)
1948 %************************************************************************
1950 \subsection{Checking signature type variables}
1952 %************************************************************************
1954 @checkSigTyVars@ checks that a set of universally quantified type varaibles
1955 are not mentioned in the environment. In particular:
1957 (a) Not mentioned in the type of a variable in the envt
1958 eg the signature for f in this:
1964 Here, f is forced to be monorphic by the free occurence of x.
1966 (d) Not (unified with another type variable that is) in scope.
1967 eg f x :: (r->r) = (\y->y) :: forall a. a->r
1968 when checking the expression type signature, we find that
1969 even though there is nothing in scope whose type mentions r,
1970 nevertheless the type signature for the expression isn't right.
1972 Another example is in a class or instance declaration:
1974 op :: forall b. a -> b
1976 Here, b gets unified with a
1978 Before doing this, the substitution is applied to the signature type variable.
1981 checkSigTyVars :: [TcTyVar] -> TcM ()
1982 checkSigTyVars sig_tvs = check_sig_tyvars emptyVarSet sig_tvs
1984 checkSigTyVarsWrt :: TcTyVarSet -> [TcTyVar] -> TcM ()
1985 -- The extra_tvs can include boxy type variables;
1986 -- e.g. TcMatches.tcCheckExistentialPat
1987 checkSigTyVarsWrt extra_tvs sig_tvs
1988 = do { extra_tvs' <- zonkTcTyVarsAndFV (varSetElems extra_tvs)
1989 ; check_sig_tyvars extra_tvs' sig_tvs }
1992 :: TcTyVarSet -- Global type variables. The universally quantified
1993 -- tyvars should not mention any of these
1994 -- Guaranteed already zonked.
1995 -> [TcTyVar] -- Universally-quantified type variables in the signature
1996 -- Guaranteed to be skolems
1998 check_sig_tyvars extra_tvs []
2000 check_sig_tyvars extra_tvs sig_tvs
2001 = ASSERT( all isSkolemTyVar sig_tvs )
2002 do { gbl_tvs <- tcGetGlobalTyVars
2003 ; traceTc (text "check_sig_tyvars" <+> (vcat [text "sig_tys" <+> ppr sig_tvs,
2004 text "gbl_tvs" <+> ppr gbl_tvs,
2005 text "extra_tvs" <+> ppr extra_tvs]))
2007 ; let env_tvs = gbl_tvs `unionVarSet` extra_tvs
2008 ; ifM (any (`elemVarSet` env_tvs) sig_tvs)
2009 (bleatEscapedTvs env_tvs sig_tvs sig_tvs)
2012 bleatEscapedTvs :: TcTyVarSet -- The global tvs
2013 -> [TcTyVar] -- The possibly-escaping type variables
2014 -> [TcTyVar] -- The zonked versions thereof
2016 -- Complain about escaping type variables
2017 -- We pass a list of type variables, at least one of which
2018 -- escapes. The first list contains the original signature type variable,
2019 -- while the second contains the type variable it is unified to (usually itself)
2020 bleatEscapedTvs globals sig_tvs zonked_tvs
2021 = do { env0 <- tcInitTidyEnv
2022 ; let (env1, tidy_tvs) = tidyOpenTyVars env0 sig_tvs
2023 (env2, tidy_zonked_tvs) = tidyOpenTyVars env1 zonked_tvs
2025 ; (env3, msgs) <- foldlM check (env2, []) (tidy_tvs `zip` tidy_zonked_tvs)
2026 ; failWithTcM (env3, main_msg $$ nest 2 (vcat msgs)) }
2028 main_msg = ptext SLIT("Inferred type is less polymorphic than expected")
2030 check (tidy_env, msgs) (sig_tv, zonked_tv)
2031 | not (zonked_tv `elemVarSet` globals) = return (tidy_env, msgs)
2033 = do { (tidy_env1, globs) <- findGlobals (unitVarSet zonked_tv) tidy_env
2034 ; returnM (tidy_env1, escape_msg sig_tv zonked_tv globs : msgs) }
2036 -----------------------
2037 escape_msg sig_tv zonked_tv globs
2039 = vcat [sep [msg, ptext SLIT("is mentioned in the environment:")],
2040 nest 2 (vcat globs)]
2042 = msg <+> ptext SLIT("escapes")
2043 -- Sigh. It's really hard to give a good error message
2044 -- all the time. One bad case is an existential pattern match.
2045 -- We rely on the "When..." context to help.
2047 msg = ptext SLIT("Quantified type variable") <+> quotes (ppr sig_tv) <+> is_bound_to
2049 | sig_tv == zonked_tv = empty
2050 | otherwise = ptext SLIT("is unified with") <+> quotes (ppr zonked_tv) <+> ptext SLIT("which")
2053 These two context are used with checkSigTyVars
2056 sigCtxt :: Id -> [TcTyVar] -> TcThetaType -> TcTauType
2057 -> TidyEnv -> TcM (TidyEnv, Message)
2058 sigCtxt id sig_tvs sig_theta sig_tau tidy_env
2059 = zonkTcType sig_tau `thenM` \ actual_tau ->
2061 (env1, tidy_sig_tvs) = tidyOpenTyVars tidy_env sig_tvs
2062 (env2, tidy_sig_rho) = tidyOpenType env1 (mkPhiTy sig_theta sig_tau)
2063 (env3, tidy_actual_tau) = tidyOpenType env2 actual_tau
2064 sub_msg = vcat [ptext SLIT("Signature type: ") <+> pprType (mkForAllTys tidy_sig_tvs tidy_sig_rho),
2065 ptext SLIT("Type to generalise:") <+> pprType tidy_actual_tau
2067 msg = vcat [ptext SLIT("When trying to generalise the type inferred for") <+> quotes (ppr id),