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 BoxySigmaType
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 -- res_ty might have a type variable at the head, such as (a b c),
146 -- in which case we must fill in with (->). Simplest thing to do
147 -- is to use boxyUnify, but we catch failure and generate our own
148 -- error message on failure
149 loop n args_so_far res_ty@(AppTy _ _)
150 = do { [arg_ty',res_ty'] <- newBoxyTyVarTys [argTypeKind, openTypeKind]
151 ; (_, mb_coi) <- tryTcErrs $ boxyUnify res_ty (FunTy arg_ty' res_ty')
152 ; if isNothing mb_coi then bale_out args_so_far
153 else do { case expectJust "subFunTys" mb_coi of
155 ACo co -> traceTc (text "you're dropping a coercion: " <+> ppr co)
156 ; loop n args_so_far (FunTy arg_ty' res_ty')
160 loop n args_so_far (TyVarTy tv)
161 | isTyConableTyVar tv
162 = do { cts <- readMetaTyVar tv
164 Indirect ty -> loop n args_so_far ty
165 Flexi -> do { (res_ty:arg_tys) <- withMetaTvs tv kinds mk_res_ty
166 ; res <- thing_inside (reverse args_so_far ++ arg_tys) res_ty
167 ; return (idHsWrapper, res) } }
169 mk_res_ty (res_ty' : arg_tys') = mkFunTys arg_tys' res_ty'
170 mk_res_ty [] = panic "TcUnify.mk_res_ty1"
171 kinds = openTypeKind : take n (repeat argTypeKind)
172 -- Note argTypeKind: the args can have an unboxed type,
173 -- but not an unboxed tuple.
175 loop n args_so_far res_ty = bale_out args_so_far
178 = do { env0 <- tcInitTidyEnv
179 ; res_ty' <- zonkTcType res_ty
180 ; let (env1, res_ty'') = tidyOpenType env0 res_ty'
181 ; failWithTcM (env1, mk_msg res_ty'' (length args_so_far)) }
183 mk_msg res_ty n_actual
184 = error_herald <> comma $$
185 sep [ptext SLIT("but its type") <+> quotes (pprType res_ty),
186 if n_actual == 0 then ptext SLIT("has none")
187 else ptext SLIT("has only") <+> speakN n_actual]
191 ----------------------
192 boxySplitTyConApp :: TyCon -- T :: k1 -> ... -> kn -> *
193 -> BoxyRhoType -- Expected type (T a b c)
194 -> TcM ([BoxySigmaType], -- Element types, a b c
196 -- It's used for wired-in tycons, so we call checkWiredInTyCon
197 -- Precondition: never called with FunTyCon
198 -- Precondition: input type :: *
200 boxySplitTyConApp tc orig_ty
201 = do { checkWiredInTyCon tc
202 ; loop (tyConArity tc) [] orig_ty }
204 loop n_req args_so_far ty
205 | Just ty' <- tcView ty = loop n_req args_so_far ty'
207 loop n_req args_so_far ty@(TyConApp tycon args)
209 = ASSERT( n_req == length args) -- ty::*
210 return (args ++ args_so_far, IdCo)
212 | isOpenSynTyCon tycon -- try to normalise type family application
213 = do { (coi1, ty') <- tcNormaliseFamInst ty
214 ; traceTc $ text "boxySplitTyConApp:" <+>
215 ppr ty <+> text "==>" <+> ppr ty'
217 IdCo -> defer -- no progress, but maybe solvable => defer
218 ACo _ -> -- progress: so lets try again
219 do { (args, coi2) <- loop n_req args_so_far ty'
220 ; return $ (args, coi2 `mkTransCoI` mkSymCoI coi1)
224 loop n_req args_so_far (AppTy fun arg)
226 = do { (args, coi) <- loop (n_req - 1) (arg:args_so_far) fun
227 ; return (args, mkAppTyCoI fun coi arg IdCo)
230 loop n_req args_so_far (TyVarTy tv)
231 | isTyConableTyVar tv
232 , res_kind `isSubKind` tyVarKind tv
233 = do { cts <- readMetaTyVar tv
235 Indirect ty -> loop n_req args_so_far ty
236 Flexi -> do { arg_tys <- withMetaTvs tv arg_kinds mk_res_ty
237 ; return (arg_tys ++ args_so_far, IdCo) }
239 | otherwise -- defer as tyvar may be refined by equalities
242 (arg_kinds, res_kind) = splitKindFunTysN n_req (tyConKind tc)
244 loop _ _ _ = boxySplitFailure (mkTyConApp tc (mkTyVarTys (tyConTyVars tc)))
247 -- defer splitting by generating an equality constraint
248 defer = boxySplitDefer arg_kinds mk_res_ty orig_ty
250 (arg_kinds, _) = splitKindFunTys (tyConKind tc)
252 -- apply splitted tycon to arguments
253 mk_res_ty = mkTyConApp tc
255 ----------------------
256 boxySplitListTy :: BoxyRhoType -> TcM (BoxySigmaType, CoercionI)
257 -- Special case for lists
258 boxySplitListTy exp_ty
259 = do { ([elt_ty], coi) <- boxySplitTyConApp listTyCon exp_ty
260 ; return (elt_ty, coi) }
262 ----------------------
263 boxySplitPArrTy :: BoxyRhoType -> TcM (BoxySigmaType, CoercionI)
264 -- Special case for parrs
265 boxySplitPArrTy exp_ty
266 = do { ([elt_ty], coi) <- boxySplitTyConApp parrTyCon exp_ty
267 ; return (elt_ty, coi) }
269 ----------------------
270 boxySplitAppTy :: BoxyRhoType -- Type to split: m a
271 -> TcM ((BoxySigmaType, BoxySigmaType), -- Returns m, a
273 -- If the incoming type is a mutable type variable of kind k, then
274 -- boxySplitAppTy returns a new type variable (m: * -> k); note the *.
275 -- If the incoming type is boxy, then so are the result types; and vice versa
277 boxySplitAppTy orig_ty
281 | Just ty' <- tcView ty = loop ty'
284 | Just (fun_ty, arg_ty) <- tcSplitAppTy_maybe ty
285 = return ((fun_ty, arg_ty), IdCo)
287 loop ty@(TyConApp tycon args)
288 | isOpenSynTyCon tycon -- try to normalise type family application
289 = do { (coi1, ty') <- tcNormaliseFamInst ty
291 IdCo -> defer -- no progress, but maybe solvable => defer
292 ACo co -> -- progress: so lets try again
293 do { (args, coi2) <- loop ty'
294 ; return $ (args, coi2 `mkTransCoI` mkSymCoI coi1)
299 | isTyConableTyVar tv
300 = do { cts <- readMetaTyVar tv
302 Indirect ty -> loop ty
303 Flexi -> do { [fun_ty, arg_ty] <- withMetaTvs tv kinds mk_res_ty
304 ; return ((fun_ty, arg_ty), IdCo) } }
305 | otherwise -- defer as tyvar may be refined by equalities
308 tv_kind = tyVarKind tv
309 kinds = [mkArrowKind liftedTypeKind (defaultKind tv_kind),
311 liftedTypeKind] -- arg type :: *
312 -- The defaultKind is a bit smelly. If you remove it,
313 -- try compiling f x = do { x }
314 -- and you'll get a kind mis-match. It smells, but
315 -- not enough to lose sleep over.
317 loop _ = boxySplitFailure (mkAppTy alphaTy betaTy) orig_ty
319 -- defer splitting by generating an equality constraint
320 defer = do { ([ty1, ty2], coi) <- boxySplitDefer arg_kinds mk_res_ty orig_ty
321 ; return ((ty1, ty2), coi)
324 orig_kind = typeKind orig_ty
325 arg_kinds = [mkArrowKind liftedTypeKind (defaultKind orig_kind),
327 liftedTypeKind] -- arg type :: *
329 -- build type application
330 mk_res_ty [fun_ty', arg_ty'] = mkAppTy fun_ty' arg_ty'
331 mk_res_ty _other = panic "TcUnify.mk_res_ty2"
334 boxySplitFailure actual_ty expected_ty
335 = unifyMisMatch False False actual_ty expected_ty
336 -- "outer" is False, so we don't pop the context
337 -- which is what we want since we have not pushed one!
340 boxySplitDefer :: [Kind] -- kinds of required arguments
341 -> ([TcType] -> TcTauType) -- construct lhs from argument tyvars
342 -> BoxyRhoType -- type to split
343 -> TcM ([TcType], CoercionI)
344 boxySplitDefer kinds mkTy orig_ty
345 = do { tau_tys <- mapM newFlexiTyVarTy kinds
346 ; coi <- defer_unification False False (mkTy tau_tys) orig_ty
347 ; return (tau_tys, coi)
352 --------------------------------
353 -- withBoxes: the key utility function
354 --------------------------------
357 withMetaTvs :: TcTyVar -- An unfilled-in, non-skolem, meta type variable
358 -> [Kind] -- Make fresh boxes (with the same BoxTv/TauTv setting as tv)
359 -> ([BoxySigmaType] -> BoxySigmaType)
360 -- Constructs the type to assign
361 -- to the original var
362 -> TcM [BoxySigmaType] -- Return the fresh boxes
364 -- It's entirely possible for the [kind] to be empty.
365 -- For example, when pattern-matching on True,
366 -- we call boxySplitTyConApp passing a boolTyCon
368 -- Invariant: tv is still Flexi
370 withMetaTvs tv kinds mk_res_ty
372 = do { box_tvs <- mapM (newMetaTyVar BoxTv) kinds
373 ; let box_tys = mkTyVarTys box_tvs
374 ; writeMetaTyVar tv (mk_res_ty box_tys)
377 | otherwise -- Non-boxy meta type variable
378 = do { tau_tys <- mapM newFlexiTyVarTy kinds
379 ; writeMetaTyVar tv (mk_res_ty tau_tys) -- Write it *first*
380 -- Sure to be a tau-type
383 withBox :: Kind -> (BoxySigmaType -> TcM a) -> TcM (a, TcType)
384 -- Allocate a *boxy* tyvar
385 withBox kind thing_inside
386 = do { box_tv <- newMetaTyVar BoxTv kind
387 ; res <- thing_inside (mkTyVarTy box_tv)
388 ; ty <- {- pprTrace "with_box" (ppr (mkTyVarTy box_tv)) $ -} readFilledBox box_tv
393 %************************************************************************
395 Approximate boxy matching
397 %************************************************************************
400 preSubType :: [TcTyVar] -- Quantified type variables
401 -> TcTyVarSet -- Subset of quantified type variables
402 -- see Note [Pre-sub boxy]
403 -> TcType -- The rho-type part; quantified tyvars scopes over this
404 -> BoxySigmaType -- Matching type from the context
405 -> TcM [TcType] -- Types to instantiate the tyvars
406 -- Perform pre-subsumption, and return suitable types
407 -- to instantiate the quantified type varibles:
408 -- info from the pre-subsumption, if there is any
409 -- a boxy type variable otherwise
411 -- Note [Pre-sub boxy]
412 -- The 'btvs' are a subset of 'qtvs'. They are the ones we can
413 -- instantiate to a boxy type variable, because they'll definitely be
414 -- filled in later. This isn't always the case; sometimes we have type
415 -- variables mentioned in the context of the type, but not the body;
416 -- f :: forall a b. C a b => a -> a
417 -- Then we may land up with an unconstrained 'b', so we want to
418 -- instantiate it to a monotype (non-boxy) type variable
420 -- The 'qtvs' that are *neither* fixed by the pre-subsumption, *nor* are in 'btvs',
421 -- are instantiated to TauTv meta variables.
423 preSubType qtvs btvs qty expected_ty
424 = do { tys <- mapM inst_tv qtvs
425 ; traceTc (text "preSubType" <+> (ppr qtvs $$ ppr btvs $$ ppr qty $$ ppr expected_ty $$ ppr pre_subst $$ ppr tys))
428 pre_subst = boxySubMatchType (mkVarSet qtvs) qty expected_ty
430 | Just boxy_ty <- lookupTyVar pre_subst tv = return boxy_ty
431 | tv `elemVarSet` btvs = do { tv' <- tcInstBoxyTyVar tv
432 ; return (mkTyVarTy tv') }
433 | otherwise = do { tv' <- tcInstTyVar tv
434 ; return (mkTyVarTy tv') }
437 :: TcTyVarSet -> TcType -- The "template"; the tyvars are skolems
438 -> BoxyRhoType -- Type to match (note a *Rho* type)
439 -> TvSubst -- Substitution of the [TcTyVar] to BoxySigmaTypes
441 -- boxySubMatchType implements the Pre-subsumption judgement, in Fig 5 of the paper
442 -- "Boxy types: inference for higher rank types and impredicativity"
444 boxySubMatchType tmpl_tvs tmpl_ty boxy_ty
445 = go tmpl_tvs tmpl_ty emptyVarSet boxy_ty
447 go t_tvs t_ty b_tvs b_ty
448 | Just t_ty' <- tcView t_ty = go t_tvs t_ty' b_tvs b_ty
449 | Just b_ty' <- tcView b_ty = go t_tvs t_ty b_tvs b_ty'
451 go t_tvs (TyVarTy _) b_tvs b_ty = emptyTvSubst -- Rule S-ANY; no bindings
452 -- Rule S-ANY covers (a) type variables and (b) boxy types
453 -- in the template. Both look like a TyVarTy.
454 -- See Note [Sub-match] below
456 go t_tvs t_ty b_tvs b_ty
457 | isSigmaTy t_ty, (tvs, _, t_tau) <- tcSplitSigmaTy t_ty
458 = go (t_tvs `delVarSetList` tvs) t_tau b_tvs b_ty -- Rule S-SPEC
459 -- Under a forall on the left, if there is shadowing,
460 -- do not bind! Hence the delVarSetList.
461 | isSigmaTy b_ty, (tvs, _, b_tau) <- tcSplitSigmaTy b_ty
462 = go t_tvs t_ty (extendVarSetList b_tvs tvs) b_tau -- Rule S-SKOL
463 -- Add to the variables we must not bind to
464 -- NB: it's *important* to discard the theta part. Otherwise
465 -- consider (forall a. Eq a => a -> b) ~<~ (Int -> Int -> Bool)
466 -- and end up with a completely bogus binding (b |-> Bool), by lining
467 -- up the (Eq a) with the Int, whereas it should be (b |-> (Int->Bool)).
468 -- This pre-subsumption stuff can return too few bindings, but it
469 -- must *never* return bogus info.
471 go t_tvs (FunTy arg1 res1) b_tvs (FunTy arg2 res2) -- Rule S-FUN
472 = boxy_match t_tvs arg1 b_tvs arg2 (go t_tvs res1 b_tvs res2)
473 -- Match the args, and sub-match the results
475 go t_tvs t_ty b_tvs b_ty = boxy_match t_tvs t_ty b_tvs b_ty emptyTvSubst
476 -- Otherwise defer to boxy matching
477 -- This covers TyConApp, AppTy, PredTy
484 |- head xs : <rhobox>
485 We will do a boxySubMatchType between a ~ <rhobox>
486 But we *don't* want to match [a |-> <rhobox>] because
487 (a) The box should be filled in with a rho-type, but
488 but the returned substitution maps TyVars to boxy
490 (b) In any case, the right final answer might be *either*
491 instantiate 'a' with a rho-type or a sigma type
492 head xs : Int vs head xs : forall b. b->b
493 So the matcher MUST NOT make a choice here. In general, we only
494 bind a template type variable in boxyMatchType, not in boxySubMatchType.
499 :: TcTyVarSet -> [TcType] -- The "template"; the tyvars are skolems
500 -> [BoxySigmaType] -- Type to match
501 -> TvSubst -- Substitution of the [TcTyVar] to BoxySigmaTypes
503 -- boxyMatchTypes implements the Pre-matching judgement, in Fig 5 of the paper
504 -- "Boxy types: inference for higher rank types and impredicativity"
506 -- Find a *boxy* substitution that makes the template look as much
507 -- like the BoxySigmaType as possible.
508 -- It's always ok to return an empty substitution;
509 -- anything more is jam on the pudding
511 -- NB1: This is a pure, non-monadic function.
512 -- It does no unification, and cannot fail
514 -- Precondition: the arg lengths are equal
515 -- Precondition: none of the template type variables appear anywhere in the [BoxySigmaType]
519 boxyMatchTypes tmpl_tvs tmpl_tys boxy_tys
520 = ASSERT( length tmpl_tys == length boxy_tys )
521 boxy_match_s tmpl_tvs tmpl_tys emptyVarSet boxy_tys emptyTvSubst
522 -- ToDo: add error context?
524 boxy_match_s tmpl_tvs [] boxy_tvs [] subst
526 boxy_match_s tmpl_tvs (t_ty:t_tys) boxy_tvs (b_ty:b_tys) subst
527 = boxy_match tmpl_tvs t_ty boxy_tvs b_ty $
528 boxy_match_s tmpl_tvs t_tys boxy_tvs b_tys subst
529 boxy_match_s tmpl_tvs _ boxy_tvs _ subst
530 = panic "boxy_match_s" -- Lengths do not match
534 boxy_match :: TcTyVarSet -> TcType -- Template
535 -> TcTyVarSet -- boxy_tvs: do not bind template tyvars to any of these
536 -> BoxySigmaType -- Match against this type
540 -- The boxy_tvs argument prevents this match:
541 -- [a] forall b. a ~ forall b. b
542 -- We don't want to bind the template variable 'a'
543 -- to the quantified type variable 'b'!
545 boxy_match tmpl_tvs orig_tmpl_ty boxy_tvs orig_boxy_ty subst
546 = go orig_tmpl_ty orig_boxy_ty
549 | Just t_ty' <- tcView t_ty = go t_ty' b_ty
550 | Just b_ty' <- tcView b_ty = go t_ty b_ty'
552 go ty1 ty2 -- C.f. the isSigmaTy case for boxySubMatchType
554 , (tvs1, _, tau1) <- tcSplitSigmaTy ty1
555 , (tvs2, _, tau2) <- tcSplitSigmaTy ty2
556 , equalLength tvs1 tvs2
557 = boxy_match (tmpl_tvs `delVarSetList` tvs1) tau1
558 (boxy_tvs `extendVarSetList` tvs2) tau2 subst
560 go (TyConApp tc1 tys1) (TyConApp tc2 tys2)
562 , not $ isOpenSynTyCon tc1
565 go (FunTy arg1 res1) (FunTy arg2 res2)
566 = go_s [arg1,res1] [arg2,res2]
569 | Just (s1,t1) <- tcSplitAppTy_maybe t_ty,
570 Just (s2,t2) <- tcSplitAppTy_maybe b_ty,
571 typeKind t2 `isSubKind` typeKind t1 -- Maintain invariant
572 = go_s [s1,t1] [s2,t2]
575 | tv `elemVarSet` tmpl_tvs -- Template type variable in the template
576 , boxy_tvs `disjointVarSet` tyVarsOfType orig_boxy_ty
577 , typeKind b_ty `isSubKind` tyVarKind tv -- See Note [Matching kinds]
578 = extendTvSubst subst tv boxy_ty'
580 = subst -- Ignore others
582 boxy_ty' = case lookupTyVar subst tv of
583 Nothing -> orig_boxy_ty
584 Just ty -> ty `boxyLub` orig_boxy_ty
586 go _ _ = emptyTvSubst -- It's important to *fail* by returning the empty substitution
587 -- Example: Tree a ~ Maybe Int
588 -- We do not want to bind (a |-> Int) in pre-matching, because that can give very
589 -- misleading error messages. An even more confusing case is
590 -- a -> b ~ Maybe Int
591 -- Then we do not want to bind (b |-> Int)! It's always safe to discard bindings
592 -- from this pre-matching phase.
595 go_s tys1 tys2 = boxy_match_s tmpl_tvs tys1 boxy_tvs tys2 subst
598 boxyLub :: BoxySigmaType -> BoxySigmaType -> BoxySigmaType
599 -- Combine boxy information from the two types
600 -- If there is a conflict, return the first
601 boxyLub orig_ty1 orig_ty2
602 = go orig_ty1 orig_ty2
604 go (AppTy f1 a1) (AppTy f2 a2) = AppTy (boxyLub f1 f2) (boxyLub a1 a2)
605 go (FunTy f1 a1) (FunTy f2 a2) = FunTy (boxyLub f1 f2) (boxyLub a1 a2)
606 go (TyConApp tc1 ts1) (TyConApp tc2 ts2)
607 | tc1 == tc2, length ts1 == length ts2
608 = TyConApp tc1 (zipWith boxyLub ts1 ts2)
610 go (TyVarTy tv1) ty2 -- This is the whole point;
611 | isTcTyVar tv1, isBoxyTyVar tv1 -- choose ty2 if ty2 is a box
614 -- Look inside type synonyms, but only if the naive version fails
615 go ty1 ty2 | Just ty1' <- tcView ty1 = go ty1' ty2
616 | Just ty2' <- tcView ty1 = go ty1 ty2'
618 -- For now, we don't look inside ForAlls, PredTys
619 go ty1 ty2 = orig_ty1 -- Default
622 Note [Matching kinds]
623 ~~~~~~~~~~~~~~~~~~~~~
624 The target type might legitimately not be a sub-kind of template.
625 For example, suppose the target is simply a box with an OpenTypeKind,
626 and the template is a type variable with LiftedTypeKind.
627 Then it's ok (because the target type will later be refined).
628 We simply don't bind the template type variable.
630 It might also be that the kind mis-match is an error. For example,
631 suppose we match the template (a -> Int) against (Int# -> Int),
632 where the template type variable 'a' has LiftedTypeKind. This
633 matching function does not fail; it simply doesn't bind the template.
634 Later stuff will fail.
636 %************************************************************************
640 %************************************************************************
642 All the tcSub calls have the form
644 tcSub expected_ty offered_ty
646 offered_ty <= expected_ty
648 That is, that a value of type offered_ty is acceptable in
649 a place expecting a value of type expected_ty.
651 It returns a coercion function
652 co_fn :: offered_ty ~ expected_ty
653 which takes an HsExpr of type offered_ty into one of type
658 tcSubExp :: BoxySigmaType -> BoxySigmaType -> TcM HsWrapper -- Locally used only
659 -- (tcSub act exp) checks that
661 tcSubExp actual_ty expected_ty
662 = -- addErrCtxtM (unifyCtxt actual_ty expected_ty) $
663 -- Adding the error context here leads to some very confusing error
664 -- messages, such as "can't match forall a. a->a with forall a. a->a"
665 -- Example is tcfail165:
666 -- do var <- newEmptyMVar :: IO (MVar (forall a. Show a => a -> String))
667 -- putMVar var (show :: forall a. Show a => a -> String)
668 -- Here the info does not flow from the 'var' arg of putMVar to its 'show' arg
669 -- but after zonking it looks as if it does!
671 -- So instead I'm adding the error context when moving from tc_sub to u_tys
673 traceTc (text "tcSubExp" <+> ppr actual_ty <+> ppr expected_ty) >>
674 tc_sub SubOther actual_ty actual_ty False expected_ty expected_ty
676 tcFunResTy :: Name -> BoxySigmaType -> BoxySigmaType -> TcM HsWrapper -- Locally used only
677 tcFunResTy fun actual_ty expected_ty
678 = traceTc (text "tcFunResTy" <+> ppr actual_ty <+> ppr expected_ty) >>
679 tc_sub (SubFun fun) actual_ty actual_ty False expected_ty expected_ty
682 data SubCtxt = SubDone -- Error-context already pushed
683 | SubFun Name -- Context is tcFunResTy
684 | SubOther -- Context is something else
686 tc_sub :: SubCtxt -- How to add an error-context
687 -> BoxySigmaType -- actual_ty, before expanding synonyms
688 -> BoxySigmaType -- ..and after
689 -> InBox -- True <=> expected_ty is inside a box
690 -> BoxySigmaType -- expected_ty, before
691 -> BoxySigmaType -- ..and after
693 -- The acual_ty is never inside a box
694 -- IMPORTANT pre-condition: if the args contain foralls, the bound type
695 -- variables are visible non-monadically
696 -- (i.e. tha args are sufficiently zonked)
697 -- This invariant is needed so that we can "see" the foralls, ad
698 -- e.g. in the SPEC rule where we just use splitSigmaTy
700 tc_sub sub_ctxt act_sty act_ty exp_ib exp_sty exp_ty
701 = traceTc (text "tc_sub" <+> ppr act_ty $$ ppr exp_ty) >>
702 tc_sub1 sub_ctxt act_sty act_ty exp_ib exp_sty exp_ty
703 -- This indirection is just here to make
704 -- it easy to insert a debug trace!
706 tc_sub1 sub_ctxt act_sty act_ty exp_ib exp_sty exp_ty
707 | Just exp_ty' <- tcView exp_ty = tc_sub sub_ctxt act_sty act_ty exp_ib exp_sty exp_ty'
708 tc_sub1 sub_ctxt act_sty act_ty exp_ib exp_sty exp_ty
709 | Just act_ty' <- tcView act_ty = tc_sub sub_ctxt act_sty act_ty' exp_ib exp_sty exp_ty
711 -----------------------------------
712 -- Rule SBOXY, plus other cases when act_ty is a type variable
713 -- Just defer to boxy matching
714 -- This rule takes precedence over SKOL!
715 tc_sub1 sub_ctxt act_sty (TyVarTy tv) exp_ib exp_sty exp_ty
716 = do { traceTc (text "tc_sub1 - case 1")
717 ; coi <- addSubCtxt sub_ctxt act_sty exp_sty $
718 uVar True False tv exp_ib exp_sty exp_ty
719 ; traceTc (case coi of
720 IdCo -> text "tc_sub1 (Rule SBOXY) IdCo"
721 ACo co -> text "tc_sub1 (Rule SBOXY) ACo" <+> ppr co)
722 ; return $ case coi of
727 -----------------------------------
728 -- Skolemisation case (rule SKOL)
729 -- actual_ty: d:Eq b => b->b
730 -- expected_ty: forall a. Ord a => a->a
731 -- co_fn e /\a. \d2:Ord a. let d = eqFromOrd d2 in e
733 -- It is essential to do this *before* the specialisation case
734 -- Example: f :: (Eq a => a->a) -> ...
735 -- g :: Ord b => b->b
738 tc_sub1 sub_ctxt act_sty act_ty exp_ib exp_sty exp_ty
740 = do { traceTc (text "tc_sub1 - case 2") ;
741 if exp_ib then -- SKOL does not apply if exp_ty is inside a box
742 defer_to_boxy_matching sub_ctxt act_sty act_ty exp_ib exp_sty exp_ty
744 { (gen_fn, co_fn) <- tcGen exp_ty act_tvs $ \ _ body_exp_ty ->
745 tc_sub sub_ctxt act_sty act_ty False body_exp_ty body_exp_ty
746 ; return (gen_fn <.> co_fn) }
749 act_tvs = tyVarsOfType act_ty
750 -- It's really important to check for escape wrt
751 -- the free vars of both expected_ty *and* actual_ty
753 -----------------------------------
754 -- Specialisation case (rule ASPEC):
755 -- actual_ty: forall a. Ord a => a->a
756 -- expected_ty: Int -> Int
757 -- co_fn e = e Int dOrdInt
759 tc_sub1 sub_ctxt act_sty actual_ty exp_ib exp_sty expected_ty
760 -- Implements the new SPEC rule in the Appendix of the paper
761 -- "Boxy types: inference for higher rank types and impredicativity"
762 -- (This appendix isn't in the published version.)
763 -- The idea is to *first* do pre-subsumption, and then full subsumption
764 -- Example: forall a. a->a <= Int -> (forall b. Int)
765 -- Pre-subsumpion finds a|->Int, and that works fine, whereas
766 -- just running full subsumption would fail.
767 | isSigmaTy actual_ty
768 = do { traceTc (text "tc_sub1 - case 3")
769 ; -- Perform pre-subsumption, and instantiate
770 -- the type with info from the pre-subsumption;
771 -- boxy tyvars if pre-subsumption gives no info
772 let (tyvars, theta, tau) = tcSplitSigmaTy actual_ty
773 tau_tvs = exactTyVarsOfType tau
774 ; inst_tys <- if exp_ib then -- Inside a box, do not do clever stuff
775 do { tyvars' <- mapM tcInstBoxyTyVar tyvars
776 ; return (mkTyVarTys tyvars') }
777 else -- Outside, do clever stuff
778 preSubType tyvars tau_tvs tau expected_ty
779 ; let subst' = zipOpenTvSubst tyvars inst_tys
780 tau' = substTy subst' tau
782 -- Perform a full subsumption check
783 ; traceTc (text "tc_sub_spec" <+> vcat [ppr actual_ty,
784 ppr tyvars <+> ppr theta <+> ppr tau,
786 ; co_fn2 <- tc_sub sub_ctxt tau' tau' exp_ib exp_sty expected_ty
788 -- Deal with the dictionaries
789 -- The origin gives a helpful origin when we have
790 -- a function with type f :: Int -> forall a. Num a => ...
791 -- This way the (Num a) dictionary gets an OccurrenceOf f origin
792 ; let orig = case sub_ctxt of
793 SubFun n -> OccurrenceOf n
794 other -> InstSigOrigin -- Unhelpful
795 ; co_fn1 <- instCall orig inst_tys (substTheta subst' theta)
796 ; return (co_fn2 <.> co_fn1) }
798 -----------------------------------
799 -- Function case (rule F1)
800 tc_sub1 sub_ctxt act_sty (FunTy act_arg act_res) exp_ib exp_sty (FunTy exp_arg exp_res)
801 = do { traceTc (text "tc_sub1 - case 4")
802 ; addSubCtxt sub_ctxt act_sty exp_sty $
803 tc_sub_funs act_arg act_res exp_ib exp_arg exp_res
806 -- Function case (rule F2)
807 tc_sub1 sub_ctxt act_sty act_ty@(FunTy act_arg act_res) _ exp_sty (TyVarTy exp_tv)
809 = addSubCtxt sub_ctxt act_sty exp_sty $
810 do { traceTc (text "tc_sub1 - case 5")
811 ; cts <- readMetaTyVar exp_tv
813 Indirect ty -> tc_sub SubDone act_sty act_ty True exp_sty ty
814 Flexi -> do { [arg_ty,res_ty] <- withMetaTvs exp_tv fun_kinds mk_res_ty
815 ; tc_sub_funs act_arg act_res True arg_ty res_ty } }
817 mk_res_ty [arg_ty', res_ty'] = mkFunTy arg_ty' res_ty'
818 mk_res_ty other = panic "TcUnify.mk_res_ty3"
819 fun_kinds = [argTypeKind, openTypeKind]
821 -- Everything else: defer to boxy matching
822 tc_sub1 sub_ctxt act_sty actual_ty exp_ib exp_sty expected_ty@(TyVarTy exp_tv)
823 = do { traceTc (text "tc_sub1 - case 6a" <+> ppr [isBoxyTyVar exp_tv, isMetaTyVar exp_tv, isSkolemTyVar exp_tv, isExistentialTyVar exp_tv,isSigTyVar exp_tv] )
824 ; defer_to_boxy_matching sub_ctxt act_sty actual_ty exp_ib exp_sty expected_ty
827 tc_sub1 sub_ctxt act_sty actual_ty exp_ib exp_sty expected_ty
828 = do { traceTc (text "tc_sub1 - case 6")
829 ; defer_to_boxy_matching sub_ctxt act_sty actual_ty exp_ib exp_sty expected_ty
832 -----------------------------------
833 defer_to_boxy_matching sub_ctxt act_sty actual_ty exp_ib exp_sty expected_ty
834 = do { coi <- addSubCtxt sub_ctxt act_sty exp_sty $
835 u_tys outer False act_sty actual_ty exp_ib exp_sty expected_ty
836 ; return $ case coi of
841 outer = case sub_ctxt of -- Ugh
845 -----------------------------------
846 tc_sub_funs act_arg act_res exp_ib exp_arg exp_res
847 = do { arg_coi <- uTys False act_arg exp_ib exp_arg
848 ; co_fn_res <- tc_sub SubDone act_res act_res exp_ib exp_res exp_res
849 ; wrapper1 <- wrapFunResCoercion [exp_arg] co_fn_res
850 ; let wrapper2 = case arg_coi of
852 ACo co -> WpCo $ FunTy co act_res
853 ; return (wrapper1 <.> wrapper2)
856 -----------------------------------
858 :: [TcType] -- Type of args
859 -> HsWrapper -- HsExpr a -> HsExpr b
860 -> TcM HsWrapper -- HsExpr (arg_tys -> a) -> HsExpr (arg_tys -> b)
861 wrapFunResCoercion arg_tys co_fn_res
862 | isIdHsWrapper co_fn_res
867 = do { arg_ids <- newSysLocalIds FSLIT("sub") arg_tys
868 ; return (mkWpLams arg_ids <.> co_fn_res <.> mkWpApps arg_ids) }
873 %************************************************************************
875 \subsection{Generalisation}
877 %************************************************************************
880 tcGen :: BoxySigmaType -- expected_ty
881 -> TcTyVarSet -- Extra tyvars that the universally
882 -- quantified tyvars of expected_ty
883 -- must not be unified
884 -> ([TcTyVar] -> BoxyRhoType -> TcM result)
885 -> TcM (HsWrapper, result)
886 -- The expression has type: spec_ty -> expected_ty
888 tcGen expected_ty extra_tvs thing_inside -- We expect expected_ty to be a forall-type
889 -- If not, the call is a no-op
890 = do { traceTc (text "tcGen")
891 -- We want the GenSkol info in the skolemised type variables to
892 -- mention the *instantiated* tyvar names, so that we get a
893 -- good error message "Rigid variable 'a' is bound by (forall a. a->a)"
894 -- Hence the tiresome but innocuous fixM
895 ; ((tvs', theta', rho'), skol_info) <- fixM (\ ~(_, skol_info) ->
896 do { (forall_tvs, theta, rho_ty) <- tcInstSkolType skol_info expected_ty
897 -- Get loation from monad, not from expected_ty
898 ; let skol_info = GenSkol forall_tvs (mkPhiTy theta rho_ty)
899 ; return ((forall_tvs, theta, rho_ty), skol_info) })
902 ; traceTc (text "tcGen" <+> vcat [text "extra_tvs" <+> ppr extra_tvs,
903 text "expected_ty" <+> ppr expected_ty,
904 text "inst ty" <+> ppr tvs' <+> ppr theta' <+> ppr rho',
905 text "free_tvs" <+> ppr free_tvs])
908 -- Type-check the arg and unify with poly type
909 ; (result, lie) <- getLIE (thing_inside tvs' rho')
911 -- Check that the "forall_tvs" havn't been constrained
912 -- The interesting bit here is that we must include the free variables
913 -- of the expected_ty. Here's an example:
914 -- runST (newVar True)
915 -- Here, if we don't make a check, we'll get a type (ST s (MutVar s Bool))
916 -- for (newVar True), with s fresh. Then we unify with the runST's arg type
917 -- forall s'. ST s' a. That unifies s' with s, and a with MutVar s Bool.
918 -- So now s' isn't unconstrained because it's linked to a.
919 -- Conclusion: include the free vars of the expected_ty in the
920 -- list of "free vars" for the signature check.
922 ; loc <- getInstLoc (SigOrigin skol_info)
923 ; dicts <- newDictBndrs loc theta'
924 ; inst_binds <- tcSimplifyCheck loc tvs' dicts lie
926 ; checkSigTyVarsWrt free_tvs tvs'
927 ; traceTc (text "tcGen:done")
930 -- The WpLet binds any Insts which came out of the simplification.
931 dict_vars = map instToVar dicts
932 co_fn = mkWpTyLams tvs' <.> mkWpLams dict_vars <.> WpLet inst_binds
933 ; returnM (co_fn, result) }
935 free_tvs = tyVarsOfType expected_ty `unionVarSet` extra_tvs
940 %************************************************************************
944 %************************************************************************
946 The exported functions are all defined as versions of some
947 non-exported generic functions.
950 boxyUnify :: BoxyType -> BoxyType -> TcM CoercionI
951 -- Acutal and expected, respectively
953 = addErrCtxtM (unifyCtxt ty1 ty2) $
954 uTysOuter False ty1 False ty2
957 boxyUnifyList :: [BoxyType] -> [BoxyType] -> TcM [CoercionI]
958 -- Arguments should have equal length
959 -- Acutal and expected types
960 boxyUnifyList tys1 tys2 = uList boxyUnify tys1 tys2
963 unifyType :: TcTauType -> TcTauType -> TcM CoercionI
964 -- No boxes expected inside these types
965 -- Acutal and expected types
966 unifyType ty1 ty2 -- ty1 expected, ty2 inferred
967 = ASSERT2( not (isBoxyTy ty1), ppr ty1 )
968 ASSERT2( not (isBoxyTy ty2), ppr ty2 )
969 addErrCtxtM (unifyCtxt ty1 ty2) $
970 uTysOuter True ty1 True ty2
973 unifyPred :: PredType -> PredType -> TcM CoercionI
974 -- Acutal and expected types
975 unifyPred p1 p2 = addErrCtxtM (unifyCtxt (mkPredTy p1) (mkPredTy p2)) $
976 uPred True True p1 True p2
978 unifyTheta :: TcThetaType -> TcThetaType -> TcM [CoercionI]
979 -- Acutal and expected types
980 unifyTheta theta1 theta2
981 = do { checkTc (equalLength theta1 theta2)
982 (vcat [ptext SLIT("Contexts differ in length"),
983 nest 2 $ parens $ ptext SLIT("Use -fglasgow-exts to allow this")])
984 ; uList unifyPred theta1 theta2
988 uList :: (a -> a -> TcM b)
989 -> [a] -> [a] -> TcM [b]
990 -- Unify corresponding elements of two lists of types, which
991 -- should be of equal length. We charge down the list explicitly so that
992 -- we can complain if their lengths differ.
993 uList unify [] [] = return []
994 uList unify (ty1:tys1) (ty2:tys2) = do { x <- unify ty1 ty2;
995 ; xs <- uList unify tys1 tys2
998 uList unify ty1s ty2s = panic "Unify.uList: mismatched type lists!"
1001 @unifyTypeList@ takes a single list of @TauType@s and unifies them
1002 all together. It is used, for example, when typechecking explicit
1003 lists, when all the elts should be of the same type.
1006 unifyTypeList :: [TcTauType] -> TcM ()
1007 unifyTypeList [] = returnM ()
1008 unifyTypeList [ty] = returnM ()
1009 unifyTypeList (ty1:tys@(ty2:_)) = do { unifyType ty1 ty2
1010 ; unifyTypeList tys }
1013 %************************************************************************
1015 \subsection[Unify-uTys]{@uTys@: getting down to business}
1017 %************************************************************************
1019 @uTys@ is the heart of the unifier. Each arg occurs twice, because
1020 we want to report errors in terms of synomyms if possible. The first of
1021 the pair is used in error messages only; it is always the same as the
1022 second, except that if the first is a synonym then the second may be a
1023 de-synonym'd version. This way we get better error messages.
1025 We call the first one \tr{ps_ty1}, \tr{ps_ty2} for ``possible synomym''.
1028 type SwapFlag = Bool
1029 -- False <=> the two args are (actual, expected) respectively
1030 -- True <=> the two args are (expected, actual) respectively
1032 type InBox = Bool -- True <=> we are inside a box
1033 -- False <=> we are outside a box
1034 -- The importance of this is that if we get "filled-box meets
1035 -- filled-box", we'll look into the boxes and unify... but
1036 -- we must not allow polytypes. But if we are in a box on
1037 -- just one side, then we can allow polytypes
1039 type Outer = Bool -- True <=> this is the outer level of a unification
1040 -- so that the types being unified are the
1041 -- very ones we began with, not some sub
1042 -- component or synonym expansion
1043 -- The idea is that if Outer is true then unifyMisMatch should
1044 -- pop the context to remove the "Expected/Acutal" context
1047 :: InBox -> TcType -- ty1 is the *actual* type
1048 -> InBox -> TcType -- ty2 is the *expected* type
1050 uTysOuter nb1 ty1 nb2 ty2
1051 = do { traceTc (text "uTysOuter" <+> ppr ty1 <+> ppr ty2)
1052 ; u_tys True nb1 ty1 ty1 nb2 ty2 ty2 }
1053 uTys nb1 ty1 nb2 ty2
1054 = do { traceTc (text "uTys" <+> ppr ty1 <+> ppr ty2)
1055 ; u_tys False nb1 ty1 ty1 nb2 ty2 ty2 }
1059 uTys_s :: InBox -> [TcType] -- tys1 are the *actual* types
1060 -> InBox -> [TcType] -- tys2 are the *expected* types
1062 uTys_s nb1 [] nb2 [] = returnM []
1063 uTys_s nb1 (ty1:tys1) nb2 (ty2:tys2) = do { coi <- uTys nb1 ty1 nb2 ty2
1064 ; cois <- uTys_s nb1 tys1 nb2 tys2
1067 uTys_s nb1 ty1s nb2 ty2s = panic "Unify.uTys_s: mismatched type lists!"
1071 -> InBox -> TcType -> TcType -- ty1 is the *actual* type
1072 -> InBox -> TcType -> TcType -- ty2 is the *expected* type
1075 u_tys outer nb1 orig_ty1 ty1 nb2 orig_ty2 ty2
1076 = do { traceTc (text "u_tys " <+> ppr ty1 <+> text " " <+> ppr ty2)
1077 ; coi <- go outer ty1 ty2
1078 ; traceTc (case coi of
1079 ACo co -> text "u_tys yields coercion: " <+> ppr co
1080 IdCo -> text "u_tys yields no coercion")
1085 go :: Outer -> TcType -> TcType -> TcM CoercionI
1087 do { traceTc (text "go " <+> ppr orig_ty1 <+> text "/" <+> ppr ty1
1088 <+> ppr orig_ty2 <+> text "/" <+> ppr ty2)
1092 go1 :: Outer -> TcType -> TcType -> TcM CoercionI
1093 -- Always expand synonyms: see Note [Unification and synonyms]
1094 -- (this also throws away FTVs)
1096 | Just ty1' <- tcView ty1 = go False ty1' ty2
1097 | Just ty2' <- tcView ty2 = go False ty1 ty2'
1099 -- Variables; go for uVar
1100 go1 outer (TyVarTy tyvar1) ty2 = uVar outer False tyvar1 nb2 orig_ty2 ty2
1101 go1 outer ty1 (TyVarTy tyvar2) = uVar outer True tyvar2 nb1 orig_ty1 ty1
1102 -- "True" means args swapped
1104 -- The case for sigma-types must *follow* the variable cases
1105 -- because a boxy variable can be filed with a polytype;
1106 -- but must precede FunTy, because ((?x::Int) => ty) look
1107 -- like a FunTy; there isn't necy a forall at the top
1109 | isSigmaTy ty1 || isSigmaTy ty2
1110 = do { traceTc (text "We have sigma types: equalLength" <+> ppr tvs1 <+> ppr tvs2)
1111 ; checkM (equalLength tvs1 tvs2)
1112 (unifyMisMatch outer False orig_ty1 orig_ty2)
1113 ; traceTc (text "We're past the first length test")
1114 ; tvs <- tcInstSkolTyVars UnkSkol tvs1 -- Not a helpful SkolemInfo
1115 -- Get location from monad, not from tvs1
1116 ; let tys = mkTyVarTys tvs
1117 in_scope = mkInScopeSet (mkVarSet tvs)
1118 phi1 = substTy (mkTvSubst in_scope (zipTyEnv tvs1 tys)) body1
1119 phi2 = substTy (mkTvSubst in_scope (zipTyEnv tvs2 tys)) body2
1120 (theta1,tau1) = tcSplitPhiTy phi1
1121 (theta2,tau2) = tcSplitPhiTy phi2
1123 ; addErrCtxtM (unifyForAllCtxt tvs phi1 phi2) $ do
1124 { checkM (equalLength theta1 theta2)
1125 (unifyMisMatch outer False orig_ty1 orig_ty2)
1127 ; cois <- uPreds False nb1 theta1 nb2 theta2 -- TOMDO: do something with these pred_cois
1128 ; traceTc (text "TOMDO!")
1129 ; coi <- uTys nb1 tau1 nb2 tau2
1131 -- Check for escape; e.g. (forall a. a->b) ~ (forall a. a->a)
1132 ; free_tvs <- zonkTcTyVarsAndFV (varSetElems (tyVarsOfType ty1 `unionVarSet` tyVarsOfType ty2))
1133 ; ifM (any (`elemVarSet` free_tvs) tvs)
1134 (bleatEscapedTvs free_tvs tvs tvs)
1136 -- If both sides are inside a box, we are in a "box-meets-box"
1137 -- situation, and we should not have a polytype at all.
1138 -- If we get here we have two boxes, already filled with
1139 -- the same polytype... but it should be a monotype.
1140 -- This check comes last, because the error message is
1141 -- extremely unhelpful.
1142 ; ifM (nb1 && nb2) (notMonoType ty1)
1146 (tvs1, body1) = tcSplitForAllTys ty1
1147 (tvs2, body2) = tcSplitForAllTys ty2
1150 go1 outer (PredTy p1) (PredTy p2)
1151 = uPred False nb1 p1 nb2 p2
1153 -- Type constructors must match
1154 go1 _ (TyConApp con1 tys1) (TyConApp con2 tys2)
1155 | con1 == con2 && not (isOpenSynTyCon con1)
1156 = do { cois <- uTys_s nb1 tys1 nb2 tys2
1157 ; return $ mkTyConAppCoI con1 tys1 cois
1159 -- See Note [TyCon app]
1160 | con1 == con2 && identicalOpenSynTyConApp
1161 = do { cois <- uTys_s nb1 tys1' nb2 tys2'
1162 ; return $ mkTyConAppCoI con1 tys1 (replicate n IdCo ++ cois)
1166 (idxTys1, tys1') = splitAt n tys1
1167 (idxTys2, tys2') = splitAt n tys2
1168 identicalOpenSynTyConApp = idxTys1 `tcEqTypes` idxTys2
1169 -- See Note [OpenSynTyCon app]
1171 -- Functions; just check the two parts
1172 go1 _ (FunTy fun1 arg1) (FunTy fun2 arg2)
1173 = do { coi_l <- uTys nb1 fun1 nb2 fun2
1174 ; coi_r <- uTys nb1 arg1 nb2 arg2
1175 ; return $ mkFunTyCoI fun1 coi_l arg1 coi_r
1178 -- Applications need a bit of care!
1179 -- They can match FunTy and TyConApp, so use splitAppTy_maybe
1180 -- NB: we've already dealt with type variables and Notes,
1181 -- so if one type is an App the other one jolly well better be too
1182 go1 outer (AppTy s1 t1) ty2
1183 | Just (s2,t2) <- tcSplitAppTy_maybe ty2
1184 = do { coi_s <- uTys nb1 s1 nb2 s2; coi_t <- uTys nb1 t1 nb2 t2
1185 ; return $ mkAppTyCoI s1 coi_s t1 coi_t }
1187 -- Now the same, but the other way round
1188 -- Don't swap the types, because the error messages get worse
1189 go1 outer ty1 (AppTy s2 t2)
1190 | Just (s1,t1) <- tcSplitAppTy_maybe ty1
1191 = do { coi_s <- uTys nb1 s1 nb2 s2; coi_t <- uTys nb1 t1 nb2 t2
1192 ; return $ mkAppTyCoI s1 coi_s t1 coi_t }
1194 -- One or both outermost constructors are type family applications.
1195 -- If we can normalise them away, proceed as usual; otherwise, we
1196 -- need to defer unification by generating a wanted equality constraint.
1198 | ty1_is_fun || ty2_is_fun
1199 = do { (coi1, ty1') <- if ty1_is_fun then tcNormaliseFamInst ty1
1200 else return (IdCo, ty1)
1201 ; (coi2, ty2') <- if ty2_is_fun then tcNormaliseFamInst ty2
1202 else return (IdCo, ty2)
1203 ; coi <- if isOpenSynTyConApp ty1' || isOpenSynTyConApp ty2'
1204 then do { -- One type family app can't be reduced yet
1206 ; ty1'' <- zonkTcType ty1'
1207 ; ty2'' <- zonkTcType ty2'
1208 ; if tcEqType ty1'' ty2''
1210 else -- see [Deferred Unification]
1211 defer_unification outer False orig_ty1 orig_ty2
1213 else -- unification can proceed
1215 ; return $ coi1 `mkTransCoI` coi `mkTransCoI` (mkSymCoI coi2)
1218 ty1_is_fun = isOpenSynTyConApp ty1
1219 ty2_is_fun = isOpenSynTyConApp ty2
1221 -- Anything else fails
1222 go1 outer _ _ = unifyMisMatch outer False orig_ty1 orig_ty2
1226 uPred outer nb1 (IParam n1 t1) nb2 (IParam n2 t2)
1228 do { coi <- uTys nb1 t1 nb2 t2
1229 ; return $ mkIParamPredCoI n1 coi
1231 uPred outer nb1 (ClassP c1 tys1) nb2 (ClassP c2 tys2)
1233 do { cois <- uTys_s nb1 tys1 nb2 tys2 -- Guaranteed equal lengths because the kinds check
1234 ; return $ mkClassPPredCoI c1 tys1 cois
1236 uPred outer _ p1 _ p2 = unifyMisMatch outer False (mkPredTy p1) (mkPredTy p2)
1238 uPreds outer nb1 [] nb2 [] = return []
1239 uPreds outer nb1 (p1:ps1) nb2 (p2:ps2) =
1240 do { coi <- uPred outer nb1 p1 nb2 p2
1241 ; cois <- uPreds outer nb1 ps1 nb2 ps2
1244 uPreds outer nb1 ps1 nb2 ps2 = panic "uPreds"
1249 When we find two TyConApps, the argument lists are guaranteed equal
1250 length. Reason: intially the kinds of the two types to be unified is
1251 the same. The only way it can become not the same is when unifying two
1252 AppTys (f1 a1):=:(f2 a2). In that case there can't be a TyConApp in
1253 the f1,f2 (because it'd absorb the app). If we unify f1:=:f2 first,
1254 which we do, that ensures that f1,f2 have the same kind; and that
1255 means a1,a2 have the same kind. And now the argument repeats.
1257 Note [OpenSynTyCon app]
1258 ~~~~~~~~~~~~~~~~~~~~~~~
1261 type family T a :: * -> *
1263 the two types (T () a) and (T () Int) must unify, even if there are
1264 no type instances for T at all. Should we just turn them into an
1265 equality (T () a ~ T () Int)? I don't think so. We currently try to
1266 eagerly unify everything we can before generating equalities; otherwise,
1267 we could turn the unification of [Int] with [a] into an equality, too.
1269 Note [Unification and synonyms]
1270 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1271 If you are tempted to make a short cut on synonyms, as in this
1275 -- NO uTys (SynTy con1 args1 ty1) (SynTy con2 args2 ty2)
1276 -- NO = if (con1 == con2) then
1277 -- NO -- Good news! Same synonym constructors, so we can shortcut
1278 -- NO -- by unifying their arguments and ignoring their expansions.
1279 -- NO unifyTypepeLists args1 args2
1281 -- NO -- Never mind. Just expand them and try again
1285 then THINK AGAIN. Here is the whole story, as detected and reported
1286 by Chris Okasaki \tr{<Chris_Okasaki@loch.mess.cs.cmu.edu>}:
1288 Here's a test program that should detect the problem:
1292 x = (1 :: Bogus Char) :: Bogus Bool
1295 The problem with [the attempted shortcut code] is that
1299 is not a sufficient condition to be able to use the shortcut!
1300 You also need to know that the type synonym actually USES all
1301 its arguments. For example, consider the following type synonym
1302 which does not use all its arguments.
1307 If you ever tried unifying, say, \tr{Bogus Char} with \tr{Bogus Bool},
1308 the unifier would blithely try to unify \tr{Char} with \tr{Bool} and
1309 would fail, even though the expanded forms (both \tr{Int}) should
1312 Similarly, unifying \tr{Bogus Char} with \tr{Bogus t} would
1313 unnecessarily bind \tr{t} to \tr{Char}.
1315 ... You could explicitly test for the problem synonyms and mark them
1316 somehow as needing expansion, perhaps also issuing a warning to the
1321 %************************************************************************
1323 \subsection[Unify-uVar]{@uVar@: unifying with a type variable}
1325 %************************************************************************
1327 @uVar@ is called when at least one of the types being unified is a
1328 variable. It does {\em not} assume that the variable is a fixed point
1329 of the substitution; rather, notice that @uVar@ (defined below) nips
1330 back into @uTys@ if it turns out that the variable is already bound.
1334 -> SwapFlag -- False => tyvar is the "actual" (ty is "expected")
1335 -- True => ty is the "actual" (tyvar is "expected")
1337 -> InBox -- True <=> definitely no boxes in t2
1338 -> TcTauType -> TcTauType -- printing and real versions
1341 uVar outer swapped tv1 nb2 ps_ty2 ty2
1342 = do { let expansion | showSDoc (ppr ty2) == showSDoc (ppr ps_ty2) = empty
1343 | otherwise = brackets (equals <+> ppr ty2)
1344 ; traceTc (text "uVar" <+> ppr swapped <+>
1345 sep [ppr tv1 <+> dcolon <+> ppr (tyVarKind tv1 ),
1346 nest 2 (ptext SLIT(" <-> ")),
1347 ppr ps_ty2 <+> dcolon <+> ppr (typeKind ty2) <+> expansion])
1348 ; details <- lookupTcTyVar tv1
1351 | swapped -> u_tys outer nb2 ps_ty2 ty2 True ty1 ty1 -- Swap back
1352 | otherwise -> u_tys outer True ty1 ty1 nb2 ps_ty2 ty2 -- Same order
1353 -- The 'True' here says that ty1 is now inside a box
1354 DoneTv details1 -> uUnfilledVar outer swapped tv1 details1 ps_ty2 ty2
1358 uUnfilledVar :: Outer
1360 -> TcTyVar -> TcTyVarDetails -- Tyvar 1
1361 -> TcTauType -> TcTauType -- Type 2
1363 -- Invariant: tyvar 1 is not unified with anything
1365 uUnfilledVar outer swapped tv1 details1 ps_ty2 ty2
1366 | Just ty2' <- tcView ty2
1367 = -- Expand synonyms; ignore FTVs
1368 uUnfilledVar False swapped tv1 details1 ps_ty2 ty2'
1370 uUnfilledVar outer swapped tv1 details1 ps_ty2 (TyVarTy tv2)
1371 | tv1 == tv2 -- Same type variable => no-op (but watch out for the boxy case)
1373 MetaTv BoxTv ref1 -- A boxy type variable meets itself;
1374 -- this is box-meets-box, so fill in with a tau-type
1375 -> do { tau_tv <- tcInstTyVar tv1
1376 ; updateMeta tv1 ref1 (mkTyVarTy tau_tv)
1379 other -> returnM IdCo -- No-op
1381 | otherwise -- Distinct type variables
1382 = do { lookup2 <- lookupTcTyVar tv2
1384 IndirectTv ty2' -> uUnfilledVar outer swapped tv1 details1 ty2' ty2'
1385 DoneTv details2 -> uUnfilledVars outer swapped tv1 details1 tv2 details2
1388 uUnfilledVar outer swapped tv1 details1 ps_ty2 non_var_ty2
1389 = -- ty2 is not a type variable
1391 MetaTv (SigTv _) _ -> rigid_variable
1393 uMetaVar outer swapped tv1 info ref1 ps_ty2 non_var_ty2
1394 SkolemTv _ -> rigid_variable
1397 | isOpenSynTyConApp non_var_ty2
1398 = -- 'non_var_ty2's outermost constructor is a type family,
1399 -- which we may may be able to normalise
1400 do { (coi2, ty2') <- tcNormaliseFamInst non_var_ty2
1402 IdCo -> -- no progress, but maybe after other instantiations
1403 defer_unification outer swapped (TyVarTy tv1) ps_ty2
1404 ACo co -> -- progress: so lets try again
1406 ppr co <+> text "::"<+> ppr non_var_ty2 <+> text "~" <+>
1408 ; coi <- uUnfilledVar outer swapped tv1 details1 ps_ty2 ty2'
1409 ; let coi2' = (if swapped then id else mkSymCoI) coi2
1410 ; return $ coi2' `mkTransCoI` coi
1413 | SkolemTv RuntimeUnkSkol <- details1
1414 -- runtime unknown will never match
1415 = unifyMisMatch outer swapped (TyVarTy tv1) ps_ty2
1416 | otherwise -- defer as a given equality may still resolve this
1417 = defer_unification outer swapped (TyVarTy tv1) ps_ty2
1420 Note [Deferred Unification]
1421 ~~~~~~~~~~~~~~~~~~~~
1422 We may encounter a unification ty1 = ty2 that cannot be performed syntactically,
1423 and yet its consistency is undetermined. Previously, there was no way to still
1424 make it consistent. So a mismatch error was issued.
1426 Now these unfications are deferred until constraint simplification, where type
1427 family instances and given equations may (or may not) establish the consistency.
1428 Deferred unifications are of the form
1431 where F is a type function and x is a type variable.
1433 id :: x ~ y => x -> y
1436 involves the unfication x = y. It is deferred until we bring into account the
1437 context x ~ y to establish that it holds.
1439 If available, we defer original types (rather than those where closed type
1440 synonyms have already been expanded via tcCoreView). This is, as usual, to
1441 improve error messages.
1443 We need to both 'unBox' and zonk deferred types. We need to unBox as
1444 functions, such as TcExpr.tcMonoExpr promise to fill boxes in the expected
1445 type. We need to zonk as the types go into the kind of the coercion variable
1446 `cotv' and those are not zonked in Inst.zonkInst. (Maybe it would be better
1447 to zonk in zonInst instead. Would that be sufficient?)
1450 defer_unification :: Bool -- pop innermost context?
1455 defer_unification outer True ty1 ty2
1456 = defer_unification outer False ty2 ty1
1457 defer_unification outer False ty1 ty2
1458 = do { ty1' <- unBox ty1 >>= zonkTcType -- unbox *and* zonk..
1459 ; ty2' <- unBox ty2 >>= zonkTcType -- ..see preceding note
1460 ; traceTc $ text "deferring:" <+> ppr ty1 <+> text "~" <+> ppr ty2
1461 ; cotv <- newMetaCoVar ty1' ty2'
1462 -- put ty1 ~ ty2 in LIE
1463 -- Left means "wanted"
1464 ; inst <- (if outer then popErrCtxt else id) $
1465 mkEqInst (EqPred ty1' ty2') (Left cotv)
1467 ; return $ ACo $ TyVarTy cotv }
1470 uMetaVar :: Bool -- pop innermost context?
1472 -> TcTyVar -> BoxInfo -> IORef MetaDetails
1475 -- tv1 is an un-filled-in meta type variable (maybe boxy, maybe tau)
1476 -- ty2 is not a type variable
1478 uMetaVar outer swapped tv1 BoxTv ref1 ps_ty2 non_var_ty2
1479 = -- tv1 is a BoxTv. So we must unbox ty2, to ensure
1480 -- that any boxes in ty2 are filled with monotypes
1482 -- It should not be the case that tv1 occurs in ty2
1483 -- (i.e. no occurs check should be needed), but if perchance
1484 -- it does, the unbox operation will fill it, and the DEBUG
1486 do { final_ty <- unBox ps_ty2
1488 ; meta_details <- readMutVar ref1
1489 ; case meta_details of
1490 Indirect ty -> WARN( True, ppr tv1 <+> ppr ty )
1491 return () -- This really should *not* happen
1494 ; checkUpdateMeta swapped tv1 ref1 final_ty
1498 uMetaVar outer swapped tv1 info1 ref1 ps_ty2 non_var_ty2
1499 = do { -- Occurs check + monotype check
1500 ; mb_final_ty <- checkTauTvUpdate tv1 ps_ty2
1501 ; case mb_final_ty of
1502 Nothing -> -- tv1 occured in type family parameter
1503 defer_unification outer swapped (mkTyVarTy tv1) ps_ty2
1505 do { checkUpdateMeta swapped tv1 ref1 final_ty
1511 uUnfilledVars :: Outer
1513 -> TcTyVar -> TcTyVarDetails -- Tyvar 1
1514 -> TcTyVar -> TcTyVarDetails -- Tyvar 2
1516 -- Invarant: The type variables are distinct,
1517 -- Neither is filled in yet
1518 -- They might be boxy or not
1520 uUnfilledVars outer swapped tv1 (SkolemTv _) tv2 (SkolemTv _)
1521 = -- see [Deferred Unification]
1522 defer_unification outer swapped (mkTyVarTy tv1) (mkTyVarTy tv2)
1524 uUnfilledVars outer swapped tv1 (MetaTv info1 ref1) tv2 (SkolemTv _)
1525 = checkUpdateMeta swapped tv1 ref1 (mkTyVarTy tv2) >> return IdCo
1526 uUnfilledVars outer swapped tv1 (SkolemTv _) tv2 (MetaTv info2 ref2)
1527 = checkUpdateMeta (not swapped) tv2 ref2 (mkTyVarTy tv1) >> return IdCo
1529 -- ToDo: this function seems too long for what it acutally does!
1530 uUnfilledVars outer swapped tv1 (MetaTv info1 ref1) tv2 (MetaTv info2 ref2)
1531 = case (info1, info2) of
1532 (BoxTv, BoxTv) -> box_meets_box >> return IdCo
1534 -- If a box meets a TauTv, but the fomer has the smaller kind
1535 -- then we must create a fresh TauTv with the smaller kind
1536 (_, BoxTv) | k1_sub_k2 -> update_tv2 >> return IdCo
1537 | otherwise -> box_meets_box >> return IdCo
1538 (BoxTv, _ ) | k2_sub_k1 -> update_tv1 >> return IdCo
1539 | otherwise -> box_meets_box >> return IdCo
1541 -- Avoid SigTvs if poss
1542 (SigTv _, _ ) | k1_sub_k2 -> update_tv2 >> return IdCo
1543 (_, SigTv _) | k2_sub_k1 -> update_tv1 >> return IdCo
1545 (_, _) | k1_sub_k2 -> if k2_sub_k1 && nicer_to_update_tv1
1546 then update_tv1 >> return IdCo -- Same kinds
1547 else update_tv2 >> return IdCo
1548 | k2_sub_k1 -> update_tv1 >> return IdCo
1549 | otherwise -> kind_err >> return IdCo
1551 -- Update the variable with least kind info
1552 -- See notes on type inference in Kind.lhs
1553 -- The "nicer to" part only applies if the two kinds are the same,
1554 -- so we can choose which to do.
1556 -- Kinds should be guaranteed ok at this point
1557 update_tv1 = updateMeta tv1 ref1 (mkTyVarTy tv2)
1558 update_tv2 = updateMeta tv2 ref2 (mkTyVarTy tv1)
1560 box_meets_box | k1_sub_k2 = if k2_sub_k1 && nicer_to_update_tv1
1563 | k2_sub_k1 = fill_from tv2
1564 | otherwise = kind_err
1566 -- Update *both* tyvars with a TauTv whose name and kind
1567 -- are gotten from tv (avoid losing nice names is poss)
1568 fill_from tv = do { tv' <- tcInstTyVar tv
1569 ; let tau_ty = mkTyVarTy tv'
1570 ; updateMeta tv1 ref1 tau_ty
1571 ; updateMeta tv2 ref2 tau_ty }
1573 kind_err = addErrCtxtM (unifyKindCtxt swapped tv1 (mkTyVarTy tv2)) $
1574 unifyKindMisMatch k1 k2
1578 k1_sub_k2 = k1 `isSubKind` k2
1579 k2_sub_k1 = k2 `isSubKind` k1
1581 nicer_to_update_tv1 = isSystemName (Var.varName tv1)
1582 -- Try to update sys-y type variables in preference to ones
1583 -- gotten (say) by instantiating a polymorphic function with
1584 -- a user-written type sig
1588 refineBox :: TcType -> TcM TcType
1589 -- Unbox the outer box of a boxy type (if any)
1590 refineBox ty@(TyVarTy box_tv)
1591 | isMetaTyVar box_tv
1592 = do { cts <- readMetaTyVar box_tv
1595 Indirect ty -> return ty }
1596 refineBox other_ty = return other_ty
1598 refineBoxToTau :: TcType -> TcM TcType
1599 -- Unbox the outer box of a boxy type, filling with a monotype if it is empty
1600 -- Like refineBox except for the "fill with monotype" part.
1601 refineBoxToTau ty@(TyVarTy box_tv)
1602 | isMetaTyVar box_tv
1603 , MetaTv BoxTv ref <- tcTyVarDetails box_tv
1604 = do { cts <- readMutVar ref
1606 Flexi -> fillBoxWithTau box_tv ref
1607 Indirect ty -> return ty }
1608 refineBoxToTau other_ty = return other_ty
1610 zapToMonotype :: BoxySigmaType -> TcM TcTauType
1611 -- Subtle... we must zap the boxy res_ty
1612 -- to kind * before using it to instantiate a LitInst
1613 -- Calling unBox instead doesn't do the job, because the box
1614 -- often has an openTypeKind, and we don't want to instantiate
1616 zapToMonotype res_ty
1617 = do { res_tau <- newFlexiTyVarTy liftedTypeKind
1618 ; boxyUnify res_tau res_ty
1621 unBox :: BoxyType -> TcM TcType
1622 -- unBox implements the judgement
1624 -- with input s', and result s
1626 -- It removes all boxes from the input type, returning a non-boxy type.
1627 -- A filled box in the type can only contain a monotype; unBox fails if not
1628 -- The type can have empty boxes, which unBox fills with a monotype
1630 -- Compare this wth checkTauTvUpdate
1632 -- For once, it's safe to treat synonyms as opaque!
1634 unBox (NoteTy n ty) = do { ty' <- unBox ty; return (NoteTy n ty') }
1635 unBox (TyConApp tc tys) = do { tys' <- mapM unBox tys; return (TyConApp tc tys') }
1636 unBox (AppTy f a) = do { f' <- unBox f; a' <- unBox a; return (mkAppTy f' a') }
1637 unBox (FunTy f a) = do { f' <- unBox f; a' <- unBox a; return (FunTy f' a') }
1638 unBox (PredTy p) = do { p' <- unBoxPred p; return (PredTy p') }
1639 unBox (ForAllTy tv ty) = ASSERT( isImmutableTyVar tv )
1640 do { ty' <- unBox ty; return (ForAllTy tv ty') }
1642 | isTcTyVar tv -- It's a boxy type variable
1643 , MetaTv BoxTv ref <- tcTyVarDetails tv -- NB: non-TcTyVars are possible
1644 = do { cts <- readMutVar ref -- under nested quantifiers
1646 Flexi -> fillBoxWithTau tv ref
1647 Indirect ty -> do { non_boxy_ty <- unBox ty
1648 ; if isTauTy non_boxy_ty
1649 then return non_boxy_ty
1650 else notMonoType non_boxy_ty }
1652 | otherwise -- Skolems, and meta-tau-variables
1653 = return (TyVarTy tv)
1655 unBoxPred (ClassP cls tys) = do { tys' <- mapM unBox tys; return (ClassP cls tys') }
1656 unBoxPred (IParam ip ty) = do { ty' <- unBox ty; return (IParam ip ty') }
1657 unBoxPred (EqPred ty1 ty2) = do { ty1' <- unBox ty1; ty2' <- unBox ty2; return (EqPred ty1' ty2') }
1662 %************************************************************************
1664 \subsection[Unify-context]{Errors and contexts}
1666 %************************************************************************
1672 unifyCtxt act_ty exp_ty tidy_env
1673 = do { act_ty' <- zonkTcType act_ty
1674 ; exp_ty' <- zonkTcType exp_ty
1675 ; let (env1, exp_ty'') = tidyOpenType tidy_env exp_ty'
1676 (env2, act_ty'') = tidyOpenType env1 act_ty'
1677 ; return (env2, mkExpectedActualMsg act_ty'' exp_ty'') }
1680 mkExpectedActualMsg act_ty exp_ty
1681 = nest 2 (vcat [ text "Expected type" <> colon <+> ppr exp_ty,
1682 text "Inferred type" <> colon <+> ppr act_ty ])
1685 -- If an error happens we try to figure out whether the function
1686 -- function has been given too many or too few arguments, and say so.
1687 addSubCtxt SubDone actual_res_ty expected_res_ty thing_inside
1689 addSubCtxt sub_ctxt actual_res_ty expected_res_ty thing_inside
1690 = addErrCtxtM mk_err thing_inside
1693 = do { exp_ty' <- zonkTcType expected_res_ty
1694 ; act_ty' <- zonkTcType actual_res_ty
1695 ; let (env1, exp_ty'') = tidyOpenType tidy_env exp_ty'
1696 (env2, act_ty'') = tidyOpenType env1 act_ty'
1697 (exp_args, _) = tcSplitFunTys exp_ty''
1698 (act_args, _) = tcSplitFunTys act_ty''
1700 len_act_args = length act_args
1701 len_exp_args = length exp_args
1703 message = case sub_ctxt of
1704 SubFun fun | len_exp_args < len_act_args -> wrongArgsCtxt "too few" fun
1705 | len_exp_args > len_act_args -> wrongArgsCtxt "too many" fun
1706 other -> mkExpectedActualMsg act_ty'' exp_ty''
1707 ; return (env2, message) }
1709 wrongArgsCtxt too_many_or_few fun
1710 = ptext SLIT("Probable cause:") <+> quotes (ppr fun)
1711 <+> ptext SLIT("is applied to") <+> text too_many_or_few
1712 <+> ptext SLIT("arguments")
1715 unifyForAllCtxt tvs phi1 phi2 env
1716 = returnM (env2, msg)
1718 (env', tvs') = tidyOpenTyVars env tvs -- NB: not tidyTyVarBndrs
1719 (env1, phi1') = tidyOpenType env' phi1
1720 (env2, phi2') = tidyOpenType env1 phi2
1721 msg = vcat [ptext SLIT("When matching") <+> quotes (ppr (mkForAllTys tvs' phi1')),
1722 ptext SLIT(" and") <+> quotes (ppr (mkForAllTys tvs' phi2'))]
1724 -----------------------
1725 unifyMisMatch outer swapped ty1 ty2
1726 = do { (env, msg) <- if swapped then misMatchMsg ty2 ty1
1727 else misMatchMsg ty1 ty2
1729 -- This is the whole point of the 'outer' stuff
1730 ; if outer then popErrCtxt (failWithTcM (env, msg))
1731 else failWithTcM (env, msg)
1736 %************************************************************************
1740 %************************************************************************
1742 Unifying kinds is much, much simpler than unifying types.
1745 unifyKind :: TcKind -- Expected
1748 unifyKind (TyConApp kc1 []) (TyConApp kc2 [])
1749 | isSubKindCon kc2 kc1 = returnM ()
1751 unifyKind (FunTy a1 r1) (FunTy a2 r2)
1752 = do { unifyKind a2 a1; unifyKind r1 r2 }
1753 -- Notice the flip in the argument,
1754 -- so that the sub-kinding works right
1755 unifyKind (TyVarTy kv1) k2 = uKVar False kv1 k2
1756 unifyKind k1 (TyVarTy kv2) = uKVar True kv2 k1
1757 unifyKind k1 k2 = unifyKindMisMatch k1 k2
1759 unifyKinds :: [TcKind] -> [TcKind] -> TcM ()
1760 unifyKinds [] [] = returnM ()
1761 unifyKinds (k1:ks1) (k2:ks2) = unifyKind k1 k2 `thenM_`
1763 unifyKinds _ _ = panic "unifyKinds: length mis-match"
1766 uKVar :: Bool -> KindVar -> TcKind -> TcM ()
1767 uKVar swapped kv1 k2
1768 = do { mb_k1 <- readKindVar kv1
1770 Flexi -> uUnboundKVar swapped kv1 k2
1771 Indirect k1 | swapped -> unifyKind k2 k1
1772 | otherwise -> unifyKind k1 k2 }
1775 uUnboundKVar :: Bool -> KindVar -> TcKind -> TcM ()
1776 uUnboundKVar swapped kv1 k2@(TyVarTy kv2)
1777 | kv1 == kv2 = returnM ()
1778 | otherwise -- Distinct kind variables
1779 = do { mb_k2 <- readKindVar kv2
1781 Indirect k2 -> uUnboundKVar swapped kv1 k2
1782 Flexi -> writeKindVar kv1 k2 }
1784 uUnboundKVar swapped kv1 non_var_k2
1785 = do { k2' <- zonkTcKind non_var_k2
1786 ; kindOccurCheck kv1 k2'
1787 ; k2'' <- kindSimpleKind swapped k2'
1788 -- KindVars must be bound only to simple kinds
1789 -- Polarities: (kindSimpleKind True ?) succeeds
1790 -- returning *, corresponding to unifying
1793 ; writeKindVar kv1 k2'' }
1796 kindOccurCheck kv1 k2 -- k2 is zonked
1797 = checkTc (not_in k2) (kindOccurCheckErr kv1 k2)
1799 not_in (TyVarTy kv2) = kv1 /= kv2
1800 not_in (FunTy a2 r2) = not_in a2 && not_in r2
1803 kindSimpleKind :: Bool -> Kind -> TcM SimpleKind
1804 -- (kindSimpleKind True k) returns a simple kind sk such that sk <: k
1805 -- If the flag is False, it requires k <: sk
1806 -- E.g. kindSimpleKind False ?? = *
1807 -- What about (kv -> *) :=: ?? -> *
1808 kindSimpleKind orig_swapped orig_kind
1809 = go orig_swapped orig_kind
1811 go sw (FunTy k1 k2) = do { k1' <- go (not sw) k1
1813 ; return (mkArrowKind k1' k2') }
1815 | isOpenTypeKind k = return liftedTypeKind
1816 | isArgTypeKind k = return liftedTypeKind
1818 | isLiftedTypeKind k = return liftedTypeKind
1819 | isUnliftedTypeKind k = return unliftedTypeKind
1820 go sw k@(TyVarTy _) = return k -- KindVars are always simple
1821 go swapped kind = failWithTc (ptext SLIT("Unexpected kind unification failure:")
1822 <+> ppr orig_swapped <+> ppr orig_kind)
1823 -- I think this can't actually happen
1825 -- T v = MkT v v must be a type
1826 -- T v w = MkT (v -> w) v must not be an umboxed tuple
1829 kindOccurCheckErr tyvar ty
1830 = hang (ptext SLIT("Occurs check: cannot construct the infinite kind:"))
1831 2 (sep [ppr tyvar, char '=', ppr ty])
1835 unifyFunKind :: TcKind -> TcM (Maybe (TcKind, TcKind))
1836 -- Like unifyFunTy, but does not fail; instead just returns Nothing
1838 unifyFunKind (TyVarTy kvar)
1839 = readKindVar kvar `thenM` \ maybe_kind ->
1841 Indirect fun_kind -> unifyFunKind fun_kind
1843 do { arg_kind <- newKindVar
1844 ; res_kind <- newKindVar
1845 ; writeKindVar kvar (mkArrowKind arg_kind res_kind)
1846 ; returnM (Just (arg_kind,res_kind)) }
1848 unifyFunKind (FunTy arg_kind res_kind) = returnM (Just (arg_kind,res_kind))
1849 unifyFunKind other = returnM Nothing
1852 %************************************************************************
1856 %************************************************************************
1858 ---------------------------
1859 -- We would like to get a decent error message from
1860 -- (a) Under-applied type constructors
1861 -- f :: (Maybe, Maybe)
1862 -- (b) Over-applied type constructors
1863 -- f :: Int x -> Int x
1867 checkExpectedKind :: Outputable a => a -> TcKind -> TcKind -> TcM ()
1868 -- A fancy wrapper for 'unifyKind', which tries
1869 -- to give decent error messages.
1870 -- (checkExpectedKind ty act_kind exp_kind)
1871 -- checks that the actual kind act_kind is compatible
1872 -- with the expected kind exp_kind
1873 -- The first argument, ty, is used only in the error message generation
1874 checkExpectedKind ty act_kind exp_kind
1875 | act_kind `isSubKind` exp_kind -- Short cut for a very common case
1878 = tryTc (unifyKind exp_kind act_kind) `thenM` \ (_errs, mb_r) ->
1880 Just r -> returnM () ; -- Unification succeeded
1883 -- So there's definitely an error
1884 -- Now to find out what sort
1885 zonkTcKind exp_kind `thenM` \ exp_kind ->
1886 zonkTcKind act_kind `thenM` \ act_kind ->
1888 tcInitTidyEnv `thenM` \ env0 ->
1889 let (exp_as, _) = splitKindFunTys exp_kind
1890 (act_as, _) = splitKindFunTys act_kind
1891 n_exp_as = length exp_as
1892 n_act_as = length act_as
1894 (env1, tidy_exp_kind) = tidyKind env0 exp_kind
1895 (env2, tidy_act_kind) = tidyKind env1 act_kind
1897 err | n_exp_as < n_act_as -- E.g. [Maybe]
1898 = quotes (ppr ty) <+> ptext SLIT("is not applied to enough type arguments")
1900 -- Now n_exp_as >= n_act_as. In the next two cases,
1901 -- n_exp_as == 0, and hence so is n_act_as
1902 | isLiftedTypeKind exp_kind && isUnliftedTypeKind act_kind
1903 = ptext SLIT("Expecting a lifted type, but") <+> quotes (ppr ty)
1904 <+> ptext SLIT("is unlifted")
1906 | isUnliftedTypeKind exp_kind && isLiftedTypeKind act_kind
1907 = ptext SLIT("Expecting an unlifted type, but") <+> quotes (ppr ty)
1908 <+> ptext SLIT("is lifted")
1910 | otherwise -- E.g. Monad [Int]
1911 = ptext SLIT("Kind mis-match")
1913 more_info = sep [ ptext SLIT("Expected kind") <+>
1914 quotes (pprKind tidy_exp_kind) <> comma,
1915 ptext SLIT("but") <+> quotes (ppr ty) <+>
1916 ptext SLIT("has kind") <+> quotes (pprKind tidy_act_kind)]
1918 failWithTcM (env2, err $$ more_info)
1922 %************************************************************************
1924 \subsection{Checking signature type variables}
1926 %************************************************************************
1928 @checkSigTyVars@ checks that a set of universally quantified type varaibles
1929 are not mentioned in the environment. In particular:
1931 (a) Not mentioned in the type of a variable in the envt
1932 eg the signature for f in this:
1938 Here, f is forced to be monorphic by the free occurence of x.
1940 (d) Not (unified with another type variable that is) in scope.
1941 eg f x :: (r->r) = (\y->y) :: forall a. a->r
1942 when checking the expression type signature, we find that
1943 even though there is nothing in scope whose type mentions r,
1944 nevertheless the type signature for the expression isn't right.
1946 Another example is in a class or instance declaration:
1948 op :: forall b. a -> b
1950 Here, b gets unified with a
1952 Before doing this, the substitution is applied to the signature type variable.
1955 checkSigTyVars :: [TcTyVar] -> TcM ()
1956 checkSigTyVars sig_tvs = check_sig_tyvars emptyVarSet sig_tvs
1958 checkSigTyVarsWrt :: TcTyVarSet -> [TcTyVar] -> TcM ()
1959 -- The extra_tvs can include boxy type variables;
1960 -- e.g. TcMatches.tcCheckExistentialPat
1961 checkSigTyVarsWrt extra_tvs sig_tvs
1962 = do { extra_tvs' <- zonkTcTyVarsAndFV (varSetElems extra_tvs)
1963 ; check_sig_tyvars extra_tvs' sig_tvs }
1966 :: TcTyVarSet -- Global type variables. The universally quantified
1967 -- tyvars should not mention any of these
1968 -- Guaranteed already zonked.
1969 -> [TcTyVar] -- Universally-quantified type variables in the signature
1970 -- Guaranteed to be skolems
1972 check_sig_tyvars extra_tvs []
1974 check_sig_tyvars extra_tvs sig_tvs
1975 = ASSERT( all isSkolemTyVar sig_tvs )
1976 do { gbl_tvs <- tcGetGlobalTyVars
1977 ; traceTc (text "check_sig_tyvars" <+> (vcat [text "sig_tys" <+> ppr sig_tvs,
1978 text "gbl_tvs" <+> ppr gbl_tvs,
1979 text "extra_tvs" <+> ppr extra_tvs]))
1981 ; let env_tvs = gbl_tvs `unionVarSet` extra_tvs
1982 ; ifM (any (`elemVarSet` env_tvs) sig_tvs)
1983 (bleatEscapedTvs env_tvs sig_tvs sig_tvs)
1986 bleatEscapedTvs :: TcTyVarSet -- The global tvs
1987 -> [TcTyVar] -- The possibly-escaping type variables
1988 -> [TcTyVar] -- The zonked versions thereof
1990 -- Complain about escaping type variables
1991 -- We pass a list of type variables, at least one of which
1992 -- escapes. The first list contains the original signature type variable,
1993 -- while the second contains the type variable it is unified to (usually itself)
1994 bleatEscapedTvs globals sig_tvs zonked_tvs
1995 = do { env0 <- tcInitTidyEnv
1996 ; let (env1, tidy_tvs) = tidyOpenTyVars env0 sig_tvs
1997 (env2, tidy_zonked_tvs) = tidyOpenTyVars env1 zonked_tvs
1999 ; (env3, msgs) <- foldlM check (env2, []) (tidy_tvs `zip` tidy_zonked_tvs)
2000 ; failWithTcM (env3, main_msg $$ nest 2 (vcat msgs)) }
2002 main_msg = ptext SLIT("Inferred type is less polymorphic than expected")
2004 check (tidy_env, msgs) (sig_tv, zonked_tv)
2005 | not (zonked_tv `elemVarSet` globals) = return (tidy_env, msgs)
2007 = do { (tidy_env1, globs) <- findGlobals (unitVarSet zonked_tv) tidy_env
2008 ; returnM (tidy_env1, escape_msg sig_tv zonked_tv globs : msgs) }
2010 -----------------------
2011 escape_msg sig_tv zonked_tv globs
2013 = vcat [sep [msg, ptext SLIT("is mentioned in the environment:")],
2014 nest 2 (vcat globs)]
2016 = msg <+> ptext SLIT("escapes")
2017 -- Sigh. It's really hard to give a good error message
2018 -- all the time. One bad case is an existential pattern match.
2019 -- We rely on the "When..." context to help.
2021 msg = ptext SLIT("Quantified type variable") <+> quotes (ppr sig_tv) <+> is_bound_to
2023 | sig_tv == zonked_tv = empty
2024 | otherwise = ptext SLIT("is unified with") <+> quotes (ppr zonked_tv) <+> ptext SLIT("which")
2027 These two context are used with checkSigTyVars
2030 sigCtxt :: Id -> [TcTyVar] -> TcThetaType -> TcTauType
2031 -> TidyEnv -> TcM (TidyEnv, Message)
2032 sigCtxt id sig_tvs sig_theta sig_tau tidy_env
2033 = zonkTcType sig_tau `thenM` \ actual_tau ->
2035 (env1, tidy_sig_tvs) = tidyOpenTyVars tidy_env sig_tvs
2036 (env2, tidy_sig_rho) = tidyOpenType env1 (mkPhiTy sig_theta sig_tau)
2037 (env3, tidy_actual_tau) = tidyOpenType env2 actual_tau
2038 sub_msg = vcat [ptext SLIT("Signature type: ") <+> pprType (mkForAllTys tidy_sig_tvs tidy_sig_rho),
2039 ptext SLIT("Type to generalise:") <+> pprType tidy_actual_tau
2041 msg = vcat [ptext SLIT("When trying to generalise the type inferred for") <+> quotes (ppr id),