2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
6 Type subsumption and unification
10 -- The above warning supression flag is a temporary kludge.
11 -- While working on this module you are encouraged to remove it and fix
12 -- any warnings in the module. See
13 -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
17 -- Full-blown subsumption
19 checkSigTyVars, checkSigTyVarsWrt, bleatEscapedTvs, sigCtxt,
21 -- Various unifications
22 unifyType, unifyTypeList, unifyTheta,
23 unifyKind, unifyKinds, unifyFunKind,
25 preSubType, boxyMatchTypes,
27 --------------------------------
29 tcInfer, subFunTys, unBox, refineBox, refineBoxToTau, withBox,
30 boxyUnify, boxyUnifyList, zapToMonotype,
31 boxySplitListTy, boxySplitPArrTy, boxySplitTyConApp, boxySplitAppTy,
35 #include "HsVersions.h"
45 import TcRnMonad -- TcType, amongst others
68 %************************************************************************
70 \subsection{'hole' type variables}
72 %************************************************************************
75 tcInfer :: (BoxyType -> TcM a) -> TcM (a, TcType)
76 tcInfer tc_infer = withBox openTypeKind tc_infer
80 %************************************************************************
84 %************************************************************************
87 subFunTys :: SDoc -- Somthing like "The function f has 3 arguments"
88 -- or "The abstraction (\x.e) takes 1 argument"
89 -> Arity -- Expected # of args
90 -> BoxyRhoType -- res_ty
91 -> ([BoxySigmaType] -> BoxyRhoType -> TcM a)
93 -- Attempt to decompse res_ty to have enough top-level arrows to
94 -- match the number of patterns in the match group
96 -- If (subFunTys n_args res_ty thing_inside) = (co_fn, res)
97 -- and the inner call to thing_inside passes args: [a1,...,an], b
98 -- then co_fn :: (a1 -> ... -> an -> b) ~ res_ty
100 -- Note that it takes a BoxyRho type, and guarantees to return a BoxyRhoType
103 {- Error messages from subFunTys
105 The abstraction `\Just 1 -> ...' has two arguments
106 but its type `Maybe a -> a' has only one
108 The equation(s) for `f' have two arguments
109 but its type `Maybe a -> a' has only one
111 The section `(f 3)' requires 'f' to take two arguments
112 but its type `Int -> Int' has only one
114 The function 'f' is applied to two arguments
115 but its type `Int -> Int' has only one
119 subFunTys error_herald n_pats res_ty thing_inside
120 = loop n_pats [] res_ty
122 -- In 'loop', the parameter 'arg_tys' accumulates
123 -- the arg types so far, in *reverse order*
124 -- INVARIANT: res_ty :: *
125 loop n args_so_far res_ty
126 | Just res_ty' <- tcView res_ty = loop n args_so_far res_ty'
128 loop n args_so_far res_ty
129 | isSigmaTy res_ty -- Do this before checking n==0, because we
130 -- guarantee to return a BoxyRhoType, not a
132 = do { (gen_fn, (co_fn, res)) <- tcGen res_ty emptyVarSet $ \ _ res_ty' ->
133 loop n args_so_far res_ty'
134 ; return (gen_fn <.> co_fn, res) }
136 loop 0 args_so_far res_ty
137 = do { res <- thing_inside (reverse args_so_far) res_ty
138 ; return (idHsWrapper, res) }
140 loop n args_so_far (FunTy arg_ty res_ty)
141 = do { (co_fn, res) <- loop (n-1) (arg_ty:args_so_far) res_ty
142 ; co_fn' <- wrapFunResCoercion [arg_ty] co_fn
143 ; return (co_fn', res) }
145 -- Try to normalise synonym families and defer if that's not possible
146 loop n args_so_far ty@(TyConApp tc tys)
148 = do { (coi1, ty') <- tcNormaliseFamInst ty
150 IdCo -> defer n args_so_far ty
151 -- no progress, but maybe solvable => defer
152 ACo _ -> -- progress: so lets try again
153 do { (co_fn, res) <- loop n args_so_far ty'
154 ; return $ (co_fn <.> coiToHsWrapper (mkSymCoI coi1), res)
158 -- res_ty might have a type variable at the head, such as (a b c),
159 -- in which case we must fill in with (->). Simplest thing to do
160 -- is to use boxyUnify, but we catch failure and generate our own
161 -- error message on failure
162 loop n args_so_far res_ty@(AppTy _ _)
163 = do { [arg_ty',res_ty'] <- newBoxyTyVarTys [argTypeKind, openTypeKind]
164 ; (_, mb_coi) <- tryTcErrs $
165 boxyUnify res_ty (FunTy arg_ty' res_ty')
166 ; if isNothing mb_coi then bale_out args_so_far
167 else do { let coi = expectJust "subFunTys" mb_coi
168 ; (co_fn, res) <- loop n args_so_far (FunTy arg_ty'
170 ; return (co_fn <.> coiToHsWrapper coi, res)
174 loop n args_so_far ty@(TyVarTy tv)
175 | isTyConableTyVar tv
176 = do { cts <- readMetaTyVar tv
178 Indirect ty -> loop n args_so_far ty
180 do { (res_ty:arg_tys) <- withMetaTvs tv kinds mk_res_ty
181 ; res <- thing_inside (reverse args_so_far ++ arg_tys)
183 ; return (idHsWrapper, res) } }
184 | otherwise -- defer as tyvar may be refined by equalities
185 = defer n args_so_far ty
187 mk_res_ty (res_ty' : arg_tys') = mkFunTys arg_tys' res_ty'
188 mk_res_ty [] = panic "TcUnify.mk_res_ty1"
189 kinds = openTypeKind : take n (repeat argTypeKind)
190 -- Note argTypeKind: the args can have an unboxed type,
191 -- but not an unboxed tuple.
193 loop n args_so_far res_ty = bale_out args_so_far
195 -- build a template type a1 -> ... -> an -> b and defer an equality
196 -- between that template and the expected result type res_ty; then,
197 -- use the template to type the thing_inside
198 defer n args_so_far ty
199 = do { arg_tys <- newFlexiTyVarTys n argTypeKind
200 ; res_ty' <- newFlexiTyVarTy openTypeKind
201 ; let fun_ty = mkFunTys arg_tys res_ty'
202 err = error_herald <> comma $$
203 text "which does not match its type"
204 ; coi <- addErrCtxt err $
205 defer_unification False False fun_ty ty
206 ; res <- thing_inside (reverse args_so_far ++ arg_tys) res_ty'
207 ; return (coiToHsWrapper coi, res)
211 = do { env0 <- tcInitTidyEnv
212 ; res_ty' <- zonkTcType res_ty
213 ; let (env1, res_ty'') = tidyOpenType env0 res_ty'
214 ; failWithTcM (env1, mk_msg res_ty'' (length args_so_far)) }
216 mk_msg res_ty n_actual
217 = error_herald <> comma $$
218 sep [ptext SLIT("but its type") <+> quotes (pprType res_ty),
219 if n_actual == 0 then ptext SLIT("has none")
220 else ptext SLIT("has only") <+> speakN n_actual]
224 ----------------------
225 boxySplitTyConApp :: TyCon -- T :: k1 -> ... -> kn -> *
226 -> BoxyRhoType -- Expected type (T a b c)
227 -> TcM ([BoxySigmaType], -- Element types, a b c
228 CoercionI) -- T a b c ~ orig_ty
229 -- It's used for wired-in tycons, so we call checkWiredInTyCon
230 -- Precondition: never called with FunTyCon
231 -- Precondition: input type :: *
233 boxySplitTyConApp tc orig_ty
234 = do { checkWiredInTyCon tc
235 ; loop (tyConArity tc) [] orig_ty }
237 loop n_req args_so_far ty
238 | Just ty' <- tcView ty = loop n_req args_so_far ty'
240 loop n_req args_so_far ty@(TyConApp tycon args)
242 = ASSERT( n_req == length args) -- ty::*
243 return (args ++ args_so_far, IdCo)
245 | isOpenSynTyCon tycon -- try to normalise type family application
246 = do { (coi1, ty') <- tcNormaliseFamInst ty
247 ; traceTc $ text "boxySplitTyConApp:" <+>
248 ppr ty <+> text "==>" <+> ppr ty'
250 IdCo -> defer -- no progress, but maybe solvable => defer
251 ACo _ -> -- progress: so lets try again
252 do { (args, coi2) <- loop n_req args_so_far ty'
253 ; return $ (args, coi2 `mkTransCoI` mkSymCoI coi1)
257 loop n_req args_so_far (AppTy fun arg)
259 = do { (args, coi) <- loop (n_req - 1) (arg:args_so_far) fun
260 ; return (args, mkAppTyCoI fun coi arg IdCo)
263 loop n_req args_so_far (TyVarTy tv)
264 | isTyConableTyVar tv
265 , res_kind `isSubKind` tyVarKind tv
266 = do { cts <- readMetaTyVar tv
268 Indirect ty -> loop n_req args_so_far ty
269 Flexi -> do { arg_tys <- withMetaTvs tv arg_kinds mk_res_ty
270 ; return (arg_tys ++ args_so_far, IdCo) }
272 | otherwise -- defer as tyvar may be refined by equalities
275 (arg_kinds, res_kind) = splitKindFunTysN n_req (tyConKind tc)
277 loop _ _ _ = boxySplitFailure (mkTyConApp tc (mkTyVarTys (tyConTyVars tc)))
280 -- defer splitting by generating an equality constraint
281 defer = boxySplitDefer arg_kinds mk_res_ty orig_ty
283 (arg_kinds, _) = splitKindFunTys (tyConKind tc)
285 -- apply splitted tycon to arguments
286 mk_res_ty = mkTyConApp tc
288 ----------------------
289 boxySplitListTy :: BoxyRhoType -> TcM (BoxySigmaType, CoercionI)
290 -- Special case for lists
291 boxySplitListTy exp_ty
292 = do { ([elt_ty], coi) <- boxySplitTyConApp listTyCon exp_ty
293 ; return (elt_ty, coi) }
295 ----------------------
296 boxySplitPArrTy :: BoxyRhoType -> TcM (BoxySigmaType, CoercionI)
297 -- Special case for parrs
298 boxySplitPArrTy exp_ty
299 = do { ([elt_ty], coi) <- boxySplitTyConApp parrTyCon exp_ty
300 ; return (elt_ty, coi) }
302 ----------------------
303 boxySplitAppTy :: BoxyRhoType -- Type to split: m a
304 -> TcM ((BoxySigmaType, BoxySigmaType), -- Returns m, a
306 -- If the incoming type is a mutable type variable of kind k, then
307 -- boxySplitAppTy returns a new type variable (m: * -> k); note the *.
308 -- If the incoming type is boxy, then so are the result types; and vice versa
310 boxySplitAppTy orig_ty
314 | Just ty' <- tcView ty = loop ty'
317 | Just (fun_ty, arg_ty) <- tcSplitAppTy_maybe ty
318 = return ((fun_ty, arg_ty), IdCo)
320 loop ty@(TyConApp tycon _args)
321 | isOpenSynTyCon tycon -- try to normalise type family application
322 = do { (coi1, ty') <- tcNormaliseFamInst ty
324 IdCo -> defer -- no progress, but maybe solvable => defer
325 ACo co -> -- progress: so lets try again
326 do { (args, coi2) <- loop ty'
327 ; return $ (args, coi2 `mkTransCoI` mkSymCoI coi1)
332 | isTyConableTyVar tv
333 = do { cts <- readMetaTyVar tv
335 Indirect ty -> loop ty
336 Flexi -> do { [fun_ty, arg_ty] <- withMetaTvs tv kinds mk_res_ty
337 ; return ((fun_ty, arg_ty), IdCo) } }
338 | otherwise -- defer as tyvar may be refined by equalities
341 tv_kind = tyVarKind tv
342 kinds = [mkArrowKind liftedTypeKind (defaultKind tv_kind),
344 liftedTypeKind] -- arg type :: *
345 -- The defaultKind is a bit smelly. If you remove it,
346 -- try compiling f x = do { x }
347 -- and you'll get a kind mis-match. It smells, but
348 -- not enough to lose sleep over.
350 loop _ = boxySplitFailure (mkAppTy alphaTy betaTy) orig_ty
352 -- defer splitting by generating an equality constraint
353 defer = do { ([ty1, ty2], coi) <- boxySplitDefer arg_kinds mk_res_ty orig_ty
354 ; return ((ty1, ty2), coi)
357 orig_kind = typeKind orig_ty
358 arg_kinds = [mkArrowKind liftedTypeKind (defaultKind orig_kind),
360 liftedTypeKind] -- arg type :: *
362 -- build type application
363 mk_res_ty [fun_ty', arg_ty'] = mkAppTy fun_ty' arg_ty'
364 mk_res_ty _other = panic "TcUnify.mk_res_ty2"
367 boxySplitFailure actual_ty expected_ty
368 = unifyMisMatch False False actual_ty expected_ty
369 -- "outer" is False, so we don't pop the context
370 -- which is what we want since we have not pushed one!
373 boxySplitDefer :: [Kind] -- kinds of required arguments
374 -> ([TcType] -> TcTauType) -- construct lhs from argument tyvars
375 -> BoxyRhoType -- type to split
376 -> TcM ([TcType], CoercionI)
377 boxySplitDefer kinds mkTy orig_ty
378 = do { tau_tys <- mapM newFlexiTyVarTy kinds
379 ; coi <- defer_unification False False (mkTy tau_tys) orig_ty
380 ; return (tau_tys, coi)
385 --------------------------------
386 -- withBoxes: the key utility function
387 --------------------------------
390 withMetaTvs :: TcTyVar -- An unfilled-in, non-skolem, meta type variable
391 -> [Kind] -- Make fresh boxes (with the same BoxTv/TauTv setting as tv)
392 -> ([BoxySigmaType] -> BoxySigmaType)
393 -- Constructs the type to assign
394 -- to the original var
395 -> TcM [BoxySigmaType] -- Return the fresh boxes
397 -- It's entirely possible for the [kind] to be empty.
398 -- For example, when pattern-matching on True,
399 -- we call boxySplitTyConApp passing a boolTyCon
401 -- Invariant: tv is still Flexi
403 withMetaTvs tv kinds mk_res_ty
405 = do { box_tvs <- mapM (newMetaTyVar BoxTv) kinds
406 ; let box_tys = mkTyVarTys box_tvs
407 ; writeMetaTyVar tv (mk_res_ty box_tys)
410 | otherwise -- Non-boxy meta type variable
411 = do { tau_tys <- mapM newFlexiTyVarTy kinds
412 ; writeMetaTyVar tv (mk_res_ty tau_tys) -- Write it *first*
413 -- Sure to be a tau-type
416 withBox :: Kind -> (BoxySigmaType -> TcM a) -> TcM (a, TcType)
417 -- Allocate a *boxy* tyvar
418 withBox kind thing_inside
419 = do { box_tv <- newBoxyTyVar kind
420 ; res <- thing_inside (mkTyVarTy box_tv)
421 ; ty <- {- pprTrace "with_box" (ppr (mkTyVarTy box_tv)) $ -} readFilledBox box_tv
426 %************************************************************************
428 Approximate boxy matching
430 %************************************************************************
433 preSubType :: [TcTyVar] -- Quantified type variables
434 -> TcTyVarSet -- Subset of quantified type variables
435 -- see Note [Pre-sub boxy]
436 -> TcType -- The rho-type part; quantified tyvars scopes over this
437 -> BoxySigmaType -- Matching type from the context
438 -> TcM [TcType] -- Types to instantiate the tyvars
439 -- Perform pre-subsumption, and return suitable types
440 -- to instantiate the quantified type varibles:
441 -- info from the pre-subsumption, if there is any
442 -- a boxy type variable otherwise
444 -- Note [Pre-sub boxy]
445 -- The 'btvs' are a subset of 'qtvs'. They are the ones we can
446 -- instantiate to a boxy type variable, because they'll definitely be
447 -- filled in later. This isn't always the case; sometimes we have type
448 -- variables mentioned in the context of the type, but not the body;
449 -- f :: forall a b. C a b => a -> a
450 -- Then we may land up with an unconstrained 'b', so we want to
451 -- instantiate it to a monotype (non-boxy) type variable
453 -- The 'qtvs' that are *neither* fixed by the pre-subsumption, *nor* are in 'btvs',
454 -- are instantiated to TauTv meta variables.
456 preSubType qtvs btvs qty expected_ty
457 = do { tys <- mapM inst_tv qtvs
458 ; traceTc (text "preSubType" <+> (ppr qtvs $$ ppr btvs $$ ppr qty $$ ppr expected_ty $$ ppr pre_subst $$ ppr tys))
461 pre_subst = boxySubMatchType (mkVarSet qtvs) qty expected_ty
463 | Just boxy_ty <- lookupTyVar pre_subst tv = return boxy_ty
464 | tv `elemVarSet` btvs = do { tv' <- tcInstBoxyTyVar tv
465 ; return (mkTyVarTy tv') }
466 | otherwise = do { tv' <- tcInstTyVar tv
467 ; return (mkTyVarTy tv') }
470 :: TcTyVarSet -> TcType -- The "template"; the tyvars are skolems
471 -> BoxyRhoType -- Type to match (note a *Rho* type)
472 -> TvSubst -- Substitution of the [TcTyVar] to BoxySigmaTypes
474 -- boxySubMatchType implements the Pre-subsumption judgement, in Fig 5 of the paper
475 -- "Boxy types: inference for higher rank types and impredicativity"
477 boxySubMatchType tmpl_tvs tmpl_ty boxy_ty
478 = go tmpl_tvs tmpl_ty emptyVarSet boxy_ty
480 go t_tvs t_ty b_tvs b_ty
481 | Just t_ty' <- tcView t_ty = go t_tvs t_ty' b_tvs b_ty
482 | Just b_ty' <- tcView b_ty = go t_tvs t_ty b_tvs b_ty'
484 go t_tvs (TyVarTy _) b_tvs b_ty = emptyTvSubst -- Rule S-ANY; no bindings
485 -- Rule S-ANY covers (a) type variables and (b) boxy types
486 -- in the template. Both look like a TyVarTy.
487 -- See Note [Sub-match] below
489 go t_tvs t_ty b_tvs b_ty
490 | isSigmaTy t_ty, (tvs, _, t_tau) <- tcSplitSigmaTy t_ty
491 = go (t_tvs `delVarSetList` tvs) t_tau b_tvs b_ty -- Rule S-SPEC
492 -- Under a forall on the left, if there is shadowing,
493 -- do not bind! Hence the delVarSetList.
494 | isSigmaTy b_ty, (tvs, _, b_tau) <- tcSplitSigmaTy b_ty
495 = go t_tvs t_ty (extendVarSetList b_tvs tvs) b_tau -- Rule S-SKOL
496 -- Add to the variables we must not bind to
497 -- NB: it's *important* to discard the theta part. Otherwise
498 -- consider (forall a. Eq a => a -> b) ~<~ (Int -> Int -> Bool)
499 -- and end up with a completely bogus binding (b |-> Bool), by lining
500 -- up the (Eq a) with the Int, whereas it should be (b |-> (Int->Bool)).
501 -- This pre-subsumption stuff can return too few bindings, but it
502 -- must *never* return bogus info.
504 go t_tvs (FunTy arg1 res1) b_tvs (FunTy arg2 res2) -- Rule S-FUN
505 = boxy_match t_tvs arg1 b_tvs arg2 (go t_tvs res1 b_tvs res2)
506 -- Match the args, and sub-match the results
508 go t_tvs t_ty b_tvs b_ty = boxy_match t_tvs t_ty b_tvs b_ty emptyTvSubst
509 -- Otherwise defer to boxy matching
510 -- This covers TyConApp, AppTy, PredTy
517 |- head xs : <rhobox>
518 We will do a boxySubMatchType between a ~ <rhobox>
519 But we *don't* want to match [a |-> <rhobox>] because
520 (a) The box should be filled in with a rho-type, but
521 but the returned substitution maps TyVars to boxy
523 (b) In any case, the right final answer might be *either*
524 instantiate 'a' with a rho-type or a sigma type
525 head xs : Int vs head xs : forall b. b->b
526 So the matcher MUST NOT make a choice here. In general, we only
527 bind a template type variable in boxyMatchType, not in boxySubMatchType.
532 :: TcTyVarSet -> [TcType] -- The "template"; the tyvars are skolems
533 -> [BoxySigmaType] -- Type to match
534 -> TvSubst -- Substitution of the [TcTyVar] to BoxySigmaTypes
536 -- boxyMatchTypes implements the Pre-matching judgement, in Fig 5 of the paper
537 -- "Boxy types: inference for higher rank types and impredicativity"
539 -- Find a *boxy* substitution that makes the template look as much
540 -- like the BoxySigmaType as possible.
541 -- It's always ok to return an empty substitution;
542 -- anything more is jam on the pudding
544 -- NB1: This is a pure, non-monadic function.
545 -- It does no unification, and cannot fail
547 -- Precondition: the arg lengths are equal
548 -- Precondition: none of the template type variables appear anywhere in the [BoxySigmaType]
552 boxyMatchTypes tmpl_tvs tmpl_tys boxy_tys
553 = ASSERT( length tmpl_tys == length boxy_tys )
554 boxy_match_s tmpl_tvs tmpl_tys emptyVarSet boxy_tys emptyTvSubst
555 -- ToDo: add error context?
557 boxy_match_s tmpl_tvs [] boxy_tvs [] subst
559 boxy_match_s tmpl_tvs (t_ty:t_tys) boxy_tvs (b_ty:b_tys) subst
560 = boxy_match tmpl_tvs t_ty boxy_tvs b_ty $
561 boxy_match_s tmpl_tvs t_tys boxy_tvs b_tys subst
562 boxy_match_s tmpl_tvs _ boxy_tvs _ subst
563 = panic "boxy_match_s" -- Lengths do not match
567 boxy_match :: TcTyVarSet -> TcType -- Template
568 -> TcTyVarSet -- boxy_tvs: do not bind template tyvars to any of these
569 -> BoxySigmaType -- Match against this type
573 -- The boxy_tvs argument prevents this match:
574 -- [a] forall b. a ~ forall b. b
575 -- We don't want to bind the template variable 'a'
576 -- to the quantified type variable 'b'!
578 boxy_match tmpl_tvs orig_tmpl_ty boxy_tvs orig_boxy_ty subst
579 = go orig_tmpl_ty orig_boxy_ty
582 | Just t_ty' <- tcView t_ty = go t_ty' b_ty
583 | Just b_ty' <- tcView b_ty = go t_ty b_ty'
585 go ty1 ty2 -- C.f. the isSigmaTy case for boxySubMatchType
587 , (tvs1, _, tau1) <- tcSplitSigmaTy ty1
588 , (tvs2, _, tau2) <- tcSplitSigmaTy ty2
589 , equalLength tvs1 tvs2
590 = boxy_match (tmpl_tvs `delVarSetList` tvs1) tau1
591 (boxy_tvs `extendVarSetList` tvs2) tau2 subst
593 go (TyConApp tc1 tys1) (TyConApp tc2 tys2)
595 , not $ isOpenSynTyCon tc1
598 go (FunTy arg1 res1) (FunTy arg2 res2)
599 = go_s [arg1,res1] [arg2,res2]
602 | Just (s1,t1) <- tcSplitAppTy_maybe t_ty,
603 Just (s2,t2) <- tcSplitAppTy_maybe b_ty,
604 typeKind t2 `isSubKind` typeKind t1 -- Maintain invariant
605 = go_s [s1,t1] [s2,t2]
608 | tv `elemVarSet` tmpl_tvs -- Template type variable in the template
609 , boxy_tvs `disjointVarSet` tyVarsOfType orig_boxy_ty
610 , typeKind b_ty `isSubKind` tyVarKind tv -- See Note [Matching kinds]
611 = extendTvSubst subst tv boxy_ty'
613 = subst -- Ignore others
615 boxy_ty' = case lookupTyVar subst tv of
616 Nothing -> orig_boxy_ty
617 Just ty -> ty `boxyLub` orig_boxy_ty
619 go _ _ = emptyTvSubst -- It's important to *fail* by returning the empty substitution
620 -- Example: Tree a ~ Maybe Int
621 -- We do not want to bind (a |-> Int) in pre-matching, because that can give very
622 -- misleading error messages. An even more confusing case is
623 -- a -> b ~ Maybe Int
624 -- Then we do not want to bind (b |-> Int)! It's always safe to discard bindings
625 -- from this pre-matching phase.
628 go_s tys1 tys2 = boxy_match_s tmpl_tvs tys1 boxy_tvs tys2 subst
631 boxyLub :: BoxySigmaType -> BoxySigmaType -> BoxySigmaType
632 -- Combine boxy information from the two types
633 -- If there is a conflict, return the first
634 boxyLub orig_ty1 orig_ty2
635 = go orig_ty1 orig_ty2
637 go (AppTy f1 a1) (AppTy f2 a2) = AppTy (boxyLub f1 f2) (boxyLub a1 a2)
638 go (FunTy f1 a1) (FunTy f2 a2) = FunTy (boxyLub f1 f2) (boxyLub a1 a2)
639 go (TyConApp tc1 ts1) (TyConApp tc2 ts2)
640 | tc1 == tc2, length ts1 == length ts2
641 = TyConApp tc1 (zipWith boxyLub ts1 ts2)
643 go (TyVarTy tv1) ty2 -- This is the whole point;
644 | isTcTyVar tv1, isBoxyTyVar tv1 -- choose ty2 if ty2 is a box
647 -- Look inside type synonyms, but only if the naive version fails
648 go ty1 ty2 | Just ty1' <- tcView ty1 = go ty1' ty2
649 | Just ty2' <- tcView ty1 = go ty1 ty2'
651 -- For now, we don't look inside ForAlls, PredTys
652 go ty1 ty2 = orig_ty1 -- Default
655 Note [Matching kinds]
656 ~~~~~~~~~~~~~~~~~~~~~
657 The target type might legitimately not be a sub-kind of template.
658 For example, suppose the target is simply a box with an OpenTypeKind,
659 and the template is a type variable with LiftedTypeKind.
660 Then it's ok (because the target type will later be refined).
661 We simply don't bind the template type variable.
663 It might also be that the kind mis-match is an error. For example,
664 suppose we match the template (a -> Int) against (Int# -> Int),
665 where the template type variable 'a' has LiftedTypeKind. This
666 matching function does not fail; it simply doesn't bind the template.
667 Later stuff will fail.
669 %************************************************************************
673 %************************************************************************
675 All the tcSub calls have the form
677 tcSub actual_ty expected_ty
679 actual_ty <= expected_ty
681 That is, that a value of type actual_ty is acceptable in
682 a place expecting a value of type expected_ty.
684 It returns a coercion function
685 co_fn :: actual_ty ~ expected_ty
686 which takes an HsExpr of type actual_ty into one of type
691 tcSubExp :: InstOrigin -> BoxySigmaType -> BoxySigmaType -> TcM HsWrapper
692 -- (tcSub act exp) checks that
694 tcSubExp orig actual_ty expected_ty
695 = -- addErrCtxtM (unifyCtxt actual_ty expected_ty) $
696 -- Adding the error context here leads to some very confusing error
697 -- messages, such as "can't match forall a. a->a with forall a. a->a"
698 -- Example is tcfail165:
699 -- do var <- newEmptyMVar :: IO (MVar (forall a. Show a => a -> String))
700 -- putMVar var (show :: forall a. Show a => a -> String)
701 -- Here the info does not flow from the 'var' arg of putMVar to its 'show' arg
702 -- but after zonking it looks as if it does!
704 -- So instead I'm adding the error context when moving from tc_sub to u_tys
706 traceTc (text "tcSubExp" <+> ppr actual_ty <+> ppr expected_ty) >>
707 tc_sub orig actual_ty actual_ty False expected_ty expected_ty
711 -> BoxySigmaType -- actual_ty, before expanding synonyms
712 -> BoxySigmaType -- ..and after
713 -> InBox -- True <=> expected_ty is inside a box
714 -> BoxySigmaType -- expected_ty, before
715 -> BoxySigmaType -- ..and after
717 -- The acual_ty is never inside a box
718 -- IMPORTANT pre-condition: if the args contain foralls, the bound type
719 -- variables are visible non-monadically
720 -- (i.e. tha args are sufficiently zonked)
721 -- This invariant is needed so that we can "see" the foralls, ad
722 -- e.g. in the SPEC rule where we just use splitSigmaTy
724 tc_sub orig act_sty act_ty exp_ib exp_sty exp_ty
725 = traceTc (text "tc_sub" <+> ppr act_ty $$ ppr exp_ty) >>
726 tc_sub1 orig act_sty act_ty exp_ib exp_sty exp_ty
727 -- This indirection is just here to make
728 -- it easy to insert a debug trace!
730 tc_sub1 orig act_sty act_ty exp_ib exp_sty exp_ty
731 | Just exp_ty' <- tcView exp_ty = tc_sub orig act_sty act_ty exp_ib exp_sty exp_ty'
732 tc_sub1 orig act_sty act_ty exp_ib exp_sty exp_ty
733 | Just act_ty' <- tcView act_ty = tc_sub orig act_sty act_ty' exp_ib exp_sty exp_ty
735 -----------------------------------
736 -- Rule SBOXY, plus other cases when act_ty is a type variable
737 -- Just defer to boxy matching
738 -- This rule takes precedence over SKOL!
739 tc_sub1 orig act_sty (TyVarTy tv) exp_ib exp_sty exp_ty
740 = do { traceTc (text "tc_sub1 - case 1")
741 ; coi <- addSubCtxt orig act_sty exp_sty $
742 uVar True False tv exp_ib exp_sty exp_ty
743 ; traceTc (case coi of
744 IdCo -> text "tc_sub1 (Rule SBOXY) IdCo"
745 ACo co -> text "tc_sub1 (Rule SBOXY) ACo" <+> ppr co)
746 ; return $ coiToHsWrapper coi
749 -----------------------------------
750 -- Skolemisation case (rule SKOL)
751 -- actual_ty: d:Eq b => b->b
752 -- expected_ty: forall a. Ord a => a->a
753 -- co_fn e /\a. \d2:Ord a. let d = eqFromOrd d2 in e
755 -- It is essential to do this *before* the specialisation case
756 -- Example: f :: (Eq a => a->a) -> ...
757 -- g :: Ord b => b->b
760 tc_sub1 orig act_sty act_ty exp_ib exp_sty exp_ty
761 | isSigmaTy exp_ty = do
762 { traceTc (text "tc_sub1 - case 2") ;
763 if exp_ib then -- SKOL does not apply if exp_ty is inside a box
764 defer_to_boxy_matching orig act_sty act_ty exp_ib exp_sty exp_ty
766 { (gen_fn, co_fn) <- tcGen exp_ty act_tvs $ \ _ body_exp_ty ->
767 tc_sub orig act_sty act_ty False body_exp_ty body_exp_ty
768 ; return (gen_fn <.> co_fn) }
771 act_tvs = tyVarsOfType act_ty
772 -- It's really important to check for escape wrt
773 -- the free vars of both expected_ty *and* actual_ty
775 -----------------------------------
776 -- Specialisation case (rule ASPEC):
777 -- actual_ty: forall a. Ord a => a->a
778 -- expected_ty: Int -> Int
779 -- co_fn e = e Int dOrdInt
781 tc_sub1 orig act_sty actual_ty exp_ib exp_sty expected_ty
782 -- Implements the new SPEC rule in the Appendix of the paper
783 -- "Boxy types: inference for higher rank types and impredicativity"
784 -- (This appendix isn't in the published version.)
785 -- The idea is to *first* do pre-subsumption, and then full subsumption
786 -- Example: forall a. a->a <= Int -> (forall b. Int)
787 -- Pre-subsumpion finds a|->Int, and that works fine, whereas
788 -- just running full subsumption would fail.
789 | isSigmaTy actual_ty
790 = do { traceTc (text "tc_sub1 - case 3")
791 ; -- Perform pre-subsumption, and instantiate
792 -- the type with info from the pre-subsumption;
793 -- boxy tyvars if pre-subsumption gives no info
794 let (tyvars, theta, tau) = tcSplitSigmaTy actual_ty
795 tau_tvs = exactTyVarsOfType tau
796 ; inst_tys <- if exp_ib then -- Inside a box, do not do clever stuff
797 do { tyvars' <- mapM tcInstBoxyTyVar tyvars
798 ; return (mkTyVarTys tyvars') }
799 else -- Outside, do clever stuff
800 preSubType tyvars tau_tvs tau expected_ty
801 ; let subst' = zipOpenTvSubst tyvars inst_tys
802 tau' = substTy subst' tau
804 -- Perform a full subsumption check
805 ; traceTc (text "tc_sub_spec" <+> vcat [ppr actual_ty,
806 ppr tyvars <+> ppr theta <+> ppr tau,
808 ; co_fn2 <- tc_sub orig tau' tau' exp_ib exp_sty expected_ty
810 -- Deal with the dictionaries
811 ; co_fn1 <- instCall orig inst_tys (substTheta subst' theta)
812 ; return (co_fn2 <.> co_fn1) }
814 -----------------------------------
815 -- Function case (rule F1)
816 tc_sub1 orig act_sty (FunTy act_arg act_res) exp_ib exp_sty (FunTy exp_arg exp_res)
817 = do { traceTc (text "tc_sub1 - case 4")
818 ; tc_sub_funs orig act_arg act_res exp_ib exp_arg exp_res
821 -- Function case (rule F2)
822 tc_sub1 orig act_sty act_ty@(FunTy act_arg act_res) _ exp_sty (TyVarTy exp_tv)
824 = do { traceTc (text "tc_sub1 - case 5")
825 ; cts <- readMetaTyVar exp_tv
827 Indirect ty -> tc_sub orig act_sty act_ty True exp_sty ty
828 Flexi -> do { [arg_ty,res_ty] <- withMetaTvs exp_tv fun_kinds mk_res_ty
829 ; tc_sub_funs orig act_arg act_res True arg_ty res_ty } }
831 mk_res_ty [arg_ty', res_ty'] = mkFunTy arg_ty' res_ty'
832 mk_res_ty other = panic "TcUnify.mk_res_ty3"
833 fun_kinds = [argTypeKind, openTypeKind]
835 -- Everything else: defer to boxy matching
836 tc_sub1 orig act_sty actual_ty exp_ib exp_sty expected_ty@(TyVarTy exp_tv)
837 = do { traceTc (text "tc_sub1 - case 6a" <+> ppr [isBoxyTyVar exp_tv, isMetaTyVar exp_tv, isSkolemTyVar exp_tv, isExistentialTyVar exp_tv,isSigTyVar exp_tv] )
838 ; defer_to_boxy_matching orig act_sty actual_ty exp_ib exp_sty expected_ty
841 tc_sub1 orig act_sty actual_ty exp_ib exp_sty expected_ty
842 = do { traceTc (text "tc_sub1 - case 6")
843 ; defer_to_boxy_matching orig act_sty actual_ty exp_ib exp_sty expected_ty
846 -----------------------------------
847 defer_to_boxy_matching orig act_sty actual_ty exp_ib exp_sty expected_ty
848 = do { coi <- addSubCtxt orig act_sty exp_sty $
849 u_tys True False act_sty actual_ty exp_ib exp_sty expected_ty
850 ; return $ coiToHsWrapper coi }
852 -----------------------------------
853 tc_sub_funs orig act_arg act_res exp_ib exp_arg exp_res
854 = do { arg_coi <- addSubCtxt orig act_arg exp_arg $
855 uTysOuter False act_arg exp_ib exp_arg
856 ; co_fn_res <- tc_sub orig act_res act_res exp_ib exp_res exp_res
857 ; wrapper1 <- wrapFunResCoercion [exp_arg] co_fn_res
858 ; let wrapper2 = case arg_coi of
860 ACo co -> WpCo $ FunTy co act_res
861 ; return (wrapper1 <.> wrapper2) }
863 -----------------------------------
865 :: [TcType] -- Type of args
866 -> HsWrapper -- HsExpr a -> HsExpr b
867 -> TcM HsWrapper -- HsExpr (arg_tys -> a) -> HsExpr (arg_tys -> b)
868 wrapFunResCoercion arg_tys co_fn_res
869 | isIdHsWrapper co_fn_res
874 = do { arg_ids <- newSysLocalIds FSLIT("sub") arg_tys
875 ; return (mkWpLams arg_ids <.> co_fn_res <.> mkWpApps arg_ids) }
880 %************************************************************************
882 \subsection{Generalisation}
884 %************************************************************************
887 tcGen :: BoxySigmaType -- expected_ty
888 -> TcTyVarSet -- Extra tyvars that the universally
889 -- quantified tyvars of expected_ty
890 -- must not be unified
891 -> ([TcTyVar] -> BoxyRhoType -> TcM result)
892 -> TcM (HsWrapper, result)
893 -- The expression has type: spec_ty -> expected_ty
895 tcGen expected_ty extra_tvs thing_inside -- We expect expected_ty to be a forall-type
896 -- If not, the call is a no-op
897 = do { traceTc (text "tcGen")
898 -- We want the GenSkol info in the skolemised type variables to
899 -- mention the *instantiated* tyvar names, so that we get a
900 -- good error message "Rigid variable 'a' is bound by (forall a. a->a)"
901 -- Hence the tiresome but innocuous fixM
902 ; ((tvs', theta', rho'), skol_info) <- fixM (\ ~(_, skol_info) ->
903 do { (forall_tvs, theta, rho_ty) <- tcInstSkolType skol_info expected_ty
904 -- Get loation from monad, not from expected_ty
905 ; let skol_info = GenSkol forall_tvs (mkPhiTy theta rho_ty)
906 ; return ((forall_tvs, theta, rho_ty), skol_info) })
909 traceTc (text "tcGen" <+> vcat [
910 text "extra_tvs" <+> ppr extra_tvs,
911 text "expected_ty" <+> ppr expected_ty,
912 text "inst ty" <+> ppr tvs' <+> ppr theta'
914 text "free_tvs" <+> ppr free_tvs])
916 -- Type-check the arg and unify with poly type
917 ; (result, lie) <- getLIE (thing_inside tvs' rho')
919 -- Check that the "forall_tvs" havn't been constrained
920 -- The interesting bit here is that we must include the free variables
921 -- of the expected_ty. Here's an example:
922 -- runST (newVar True)
923 -- Here, if we don't make a check, we'll get a type (ST s (MutVar s Bool))
924 -- for (newVar True), with s fresh. Then we unify with the runST's arg type
925 -- forall s'. ST s' a. That unifies s' with s, and a with MutVar s Bool.
926 -- So now s' isn't unconstrained because it's linked to a.
927 -- Conclusion: include the free vars of the expected_ty in the
928 -- list of "free vars" for the signature check.
930 ; loc <- getInstLoc (SigOrigin skol_info)
931 ; dicts <- newDictBndrs loc theta' -- Includes equalities
932 ; inst_binds <- tcSimplifyCheck loc tvs' dicts lie
934 ; checkSigTyVarsWrt free_tvs tvs'
935 ; traceTc (text "tcGen:done")
938 -- The WpLet binds any Insts which came out of the simplification.
939 dict_vars = map instToVar dicts
940 co_fn = mkWpTyLams tvs' <.> mkWpLams dict_vars <.> WpLet inst_binds
941 ; return (co_fn, result) }
943 free_tvs = tyVarsOfType expected_ty `unionVarSet` extra_tvs
948 %************************************************************************
952 %************************************************************************
954 The exported functions are all defined as versions of some
955 non-exported generic functions.
958 boxyUnify :: BoxyType -> BoxyType -> TcM CoercionI
959 -- Acutal and expected, respectively
961 = addErrCtxtM (unifyCtxt ty1 ty2) $
962 uTysOuter False ty1 False ty2
965 boxyUnifyList :: [BoxyType] -> [BoxyType] -> TcM [CoercionI]
966 -- Arguments should have equal length
967 -- Acutal and expected types
968 boxyUnifyList tys1 tys2 = uList boxyUnify tys1 tys2
971 unifyType :: TcTauType -> TcTauType -> TcM CoercionI
972 -- No boxes expected inside these types
973 -- Acutal and expected types
974 unifyType ty1 ty2 -- ty1 expected, ty2 inferred
975 = ASSERT2( not (isBoxyTy ty1), ppr ty1 )
976 ASSERT2( not (isBoxyTy ty2), ppr ty2 )
977 addErrCtxtM (unifyCtxt ty1 ty2) $
978 uTysOuter True ty1 True ty2
981 unifyPred :: PredType -> PredType -> TcM CoercionI
982 -- Acutal and expected types
983 unifyPred p1 p2 = addErrCtxtM (unifyCtxt (mkPredTy p1) (mkPredTy p2)) $
984 uPred True True p1 True p2
986 unifyTheta :: TcThetaType -> TcThetaType -> TcM [CoercionI]
987 -- Acutal and expected types
988 unifyTheta theta1 theta2
989 = do { checkTc (equalLength theta1 theta2)
990 (vcat [ptext SLIT("Contexts differ in length"),
991 nest 2 $ parens $ ptext SLIT("Use -fglasgow-exts to allow this")])
992 ; uList unifyPred theta1 theta2
996 uList :: (a -> a -> TcM b)
997 -> [a] -> [a] -> TcM [b]
998 -- Unify corresponding elements of two lists of types, which
999 -- should be of equal length. We charge down the list explicitly so that
1000 -- we can complain if their lengths differ.
1001 uList unify [] [] = return []
1002 uList unify (ty1:tys1) (ty2:tys2) = do { x <- unify ty1 ty2;
1003 ; xs <- uList unify tys1 tys2
1006 uList unify ty1s ty2s = panic "Unify.uList: mismatched type lists!"
1009 @unifyTypeList@ takes a single list of @TauType@s and unifies them
1010 all together. It is used, for example, when typechecking explicit
1011 lists, when all the elts should be of the same type.
1014 unifyTypeList :: [TcTauType] -> TcM ()
1015 unifyTypeList [] = return ()
1016 unifyTypeList [ty] = return ()
1017 unifyTypeList (ty1:tys@(ty2:_)) = do { unifyType ty1 ty2
1018 ; unifyTypeList tys }
1021 %************************************************************************
1023 \subsection[Unify-uTys]{@uTys@: getting down to business}
1025 %************************************************************************
1027 @uTys@ is the heart of the unifier. Each arg occurs twice, because
1028 we want to report errors in terms of synomyms if possible. The first of
1029 the pair is used in error messages only; it is always the same as the
1030 second, except that if the first is a synonym then the second may be a
1031 de-synonym'd version. This way we get better error messages.
1033 We call the first one \tr{ps_ty1}, \tr{ps_ty2} for ``possible synomym''.
1036 type SwapFlag = Bool
1037 -- False <=> the two args are (actual, expected) respectively
1038 -- True <=> the two args are (expected, actual) respectively
1040 type InBox = Bool -- True <=> we are inside a box
1041 -- False <=> we are outside a box
1042 -- The importance of this is that if we get "filled-box meets
1043 -- filled-box", we'll look into the boxes and unify... but
1044 -- we must not allow polytypes. But if we are in a box on
1045 -- just one side, then we can allow polytypes
1047 type Outer = Bool -- True <=> this is the outer level of a unification
1048 -- so that the types being unified are the
1049 -- very ones we began with, not some sub
1050 -- component or synonym expansion
1051 -- The idea is that if Outer is true then unifyMisMatch should
1052 -- pop the context to remove the "Expected/Acutal" context
1055 :: InBox -> TcType -- ty1 is the *actual* type
1056 -> InBox -> TcType -- ty2 is the *expected* type
1058 uTysOuter nb1 ty1 nb2 ty2
1059 = do { traceTc (text "uTysOuter" <+> ppr ty1 <+> ppr ty2)
1060 ; u_tys True nb1 ty1 ty1 nb2 ty2 ty2 }
1061 uTys nb1 ty1 nb2 ty2
1062 = do { traceTc (text "uTys" <+> ppr ty1 <+> ppr ty2)
1063 ; u_tys False nb1 ty1 ty1 nb2 ty2 ty2 }
1067 uTys_s :: InBox -> [TcType] -- tys1 are the *actual* types
1068 -> InBox -> [TcType] -- tys2 are the *expected* types
1070 uTys_s nb1 [] nb2 [] = return []
1071 uTys_s nb1 (ty1:tys1) nb2 (ty2:tys2) = do { coi <- uTys nb1 ty1 nb2 ty2
1072 ; cois <- uTys_s nb1 tys1 nb2 tys2
1075 uTys_s nb1 ty1s nb2 ty2s = panic "Unify.uTys_s: mismatched type lists!"
1079 -> InBox -> TcType -> TcType -- ty1 is the *actual* type
1080 -> InBox -> TcType -> TcType -- ty2 is the *expected* type
1083 u_tys outer nb1 orig_ty1 ty1 nb2 orig_ty2 ty2
1084 = do { traceTc (text "u_tys " <+> ppr ty1 <+> text " " <+> ppr ty2)
1085 ; coi <- go outer ty1 ty2
1086 ; traceTc (case coi of
1087 ACo co -> text "u_tys yields coercion: " <+> ppr co
1088 IdCo -> text "u_tys yields no coercion")
1093 go :: Outer -> TcType -> TcType -> TcM CoercionI
1095 do { traceTc (text "go " <+> ppr orig_ty1 <+> text "/" <+> ppr ty1
1096 <+> ppr orig_ty2 <+> text "/" <+> ppr ty2)
1100 go1 :: Outer -> TcType -> TcType -> TcM CoercionI
1101 -- Always expand synonyms: see Note [Unification and synonyms]
1102 -- (this also throws away FTVs)
1104 | Just ty1' <- tcView ty1 = go False ty1' ty2
1105 | Just ty2' <- tcView ty2 = go False ty1 ty2'
1107 -- Variables; go for uVar
1108 go1 outer (TyVarTy tyvar1) ty2 = uVar outer False tyvar1 nb2 orig_ty2 ty2
1109 go1 outer ty1 (TyVarTy tyvar2) = uVar outer True tyvar2 nb1 orig_ty1 ty1
1110 -- "True" means args swapped
1112 -- The case for sigma-types must *follow* the variable cases
1113 -- because a boxy variable can be filed with a polytype;
1114 -- but must precede FunTy, because ((?x::Int) => ty) look
1115 -- like a FunTy; there isn't necy a forall at the top
1117 | isSigmaTy ty1 || isSigmaTy ty2
1118 = do { traceTc (text "We have sigma types: equalLength" <+> ppr tvs1 <+> ppr tvs2)
1119 ; unless (equalLength tvs1 tvs2)
1120 (unifyMisMatch outer False orig_ty1 orig_ty2)
1121 ; traceTc (text "We're past the first length test")
1122 ; tvs <- tcInstSkolTyVars UnkSkol tvs1 -- Not a helpful SkolemInfo
1123 -- Get location from monad, not from tvs1
1124 ; let tys = mkTyVarTys tvs
1125 in_scope = mkInScopeSet (mkVarSet tvs)
1126 phi1 = substTy (mkTvSubst in_scope (zipTyEnv tvs1 tys)) body1
1127 phi2 = substTy (mkTvSubst in_scope (zipTyEnv tvs2 tys)) body2
1128 (theta1,tau1) = tcSplitPhiTy phi1
1129 (theta2,tau2) = tcSplitPhiTy phi2
1131 ; addErrCtxtM (unifyForAllCtxt tvs phi1 phi2) $ do
1132 { unless (equalLength theta1 theta2)
1133 (unifyMisMatch outer False orig_ty1 orig_ty2)
1135 ; cois <- uPreds False nb1 theta1 nb2 theta2 -- TOMDO: do something with these pred_cois
1136 ; traceTc (text "TOMDO!")
1137 ; coi <- uTys nb1 tau1 nb2 tau2
1139 -- Check for escape; e.g. (forall a. a->b) ~ (forall a. a->a)
1140 ; free_tvs <- zonkTcTyVarsAndFV (varSetElems (tyVarsOfType ty1 `unionVarSet` tyVarsOfType ty2))
1141 ; when (any (`elemVarSet` free_tvs) tvs)
1142 (bleatEscapedTvs free_tvs tvs tvs)
1144 -- If both sides are inside a box, we are in a "box-meets-box"
1145 -- situation, and we should not have a polytype at all.
1146 -- If we get here we have two boxes, already filled with
1147 -- the same polytype... but it should be a monotype.
1148 -- This check comes last, because the error message is
1149 -- extremely unhelpful.
1150 ; when (nb1 && nb2) (notMonoType ty1)
1154 (tvs1, body1) = tcSplitForAllTys ty1
1155 (tvs2, body2) = tcSplitForAllTys ty2
1158 go1 outer (PredTy p1) (PredTy p2)
1159 = uPred False nb1 p1 nb2 p2
1161 -- Type constructors must match
1162 go1 _ (TyConApp con1 tys1) (TyConApp con2 tys2)
1163 | con1 == con2 && not (isOpenSynTyCon con1)
1164 = do { cois <- uTys_s nb1 tys1 nb2 tys2
1165 ; return $ mkTyConAppCoI con1 tys1 cois
1167 -- See Note [TyCon app]
1168 | con1 == con2 && identicalOpenSynTyConApp
1169 = do { cois <- uTys_s nb1 tys1' nb2 tys2'
1170 ; return $ mkTyConAppCoI con1 tys1 (replicate n IdCo ++ cois)
1174 (idxTys1, tys1') = splitAt n tys1
1175 (idxTys2, tys2') = splitAt n tys2
1176 identicalOpenSynTyConApp = idxTys1 `tcEqTypes` idxTys2
1177 -- See Note [OpenSynTyCon app]
1179 -- Functions; just check the two parts
1180 go1 _ (FunTy fun1 arg1) (FunTy fun2 arg2)
1181 = do { coi_l <- uTys nb1 fun1 nb2 fun2
1182 ; coi_r <- uTys nb1 arg1 nb2 arg2
1183 ; return $ mkFunTyCoI fun1 coi_l arg1 coi_r
1186 -- Applications need a bit of care!
1187 -- They can match FunTy and TyConApp, so use splitAppTy_maybe
1188 -- NB: we've already dealt with type variables and Notes,
1189 -- so if one type is an App the other one jolly well better be too
1190 go1 outer (AppTy s1 t1) ty2
1191 | Just (s2,t2) <- tcSplitAppTy_maybe ty2
1192 = do { coi_s <- uTys nb1 s1 nb2 s2; coi_t <- uTys nb1 t1 nb2 t2
1193 ; return $ mkAppTyCoI s1 coi_s t1 coi_t }
1195 -- Now the same, but the other way round
1196 -- Don't swap the types, because the error messages get worse
1197 go1 outer ty1 (AppTy s2 t2)
1198 | Just (s1,t1) <- tcSplitAppTy_maybe ty1
1199 = do { coi_s <- uTys nb1 s1 nb2 s2; coi_t <- uTys nb1 t1 nb2 t2
1200 ; return $ mkAppTyCoI s1 coi_s t1 coi_t }
1202 -- One or both outermost constructors are type family applications.
1203 -- If we can normalise them away, proceed as usual; otherwise, we
1204 -- need to defer unification by generating a wanted equality constraint.
1206 | ty1_is_fun || ty2_is_fun
1207 = do { (coi1, ty1') <- if ty1_is_fun then tcNormaliseFamInst ty1
1208 else return (IdCo, ty1)
1209 ; (coi2, ty2') <- if ty2_is_fun then tcNormaliseFamInst ty2
1210 else return (IdCo, ty2)
1211 ; coi <- if isOpenSynTyConApp ty1' || isOpenSynTyConApp ty2'
1212 then do { -- One type family app can't be reduced yet
1214 ; ty1'' <- zonkTcType ty1'
1215 ; ty2'' <- zonkTcType ty2'
1216 ; if tcEqType ty1'' ty2''
1218 else -- see [Deferred Unification]
1219 defer_unification outer False orig_ty1 orig_ty2
1221 else -- unification can proceed
1223 ; return $ coi1 `mkTransCoI` coi `mkTransCoI` (mkSymCoI coi2)
1226 ty1_is_fun = isOpenSynTyConApp ty1
1227 ty2_is_fun = isOpenSynTyConApp ty2
1229 -- Anything else fails
1230 go1 outer _ _ = unifyMisMatch outer False orig_ty1 orig_ty2
1234 uPred outer nb1 (IParam n1 t1) nb2 (IParam n2 t2)
1236 do { coi <- uTys nb1 t1 nb2 t2
1237 ; return $ mkIParamPredCoI n1 coi
1239 uPred outer nb1 (ClassP c1 tys1) nb2 (ClassP c2 tys2)
1241 do { cois <- uTys_s nb1 tys1 nb2 tys2 -- Guaranteed equal lengths because the kinds check
1242 ; return $ mkClassPPredCoI c1 tys1 cois
1244 uPred outer _ p1 _ p2 = unifyMisMatch outer False (mkPredTy p1) (mkPredTy p2)
1246 uPreds outer nb1 [] nb2 [] = return []
1247 uPreds outer nb1 (p1:ps1) nb2 (p2:ps2) =
1248 do { coi <- uPred outer nb1 p1 nb2 p2
1249 ; cois <- uPreds outer nb1 ps1 nb2 ps2
1252 uPreds outer nb1 ps1 nb2 ps2 = panic "uPreds"
1257 When we find two TyConApps, the argument lists are guaranteed equal
1258 length. Reason: intially the kinds of the two types to be unified is
1259 the same. The only way it can become not the same is when unifying two
1260 AppTys (f1 a1):=:(f2 a2). In that case there can't be a TyConApp in
1261 the f1,f2 (because it'd absorb the app). If we unify f1:=:f2 first,
1262 which we do, that ensures that f1,f2 have the same kind; and that
1263 means a1,a2 have the same kind. And now the argument repeats.
1265 Note [OpenSynTyCon app]
1266 ~~~~~~~~~~~~~~~~~~~~~~~
1269 type family T a :: * -> *
1271 the two types (T () a) and (T () Int) must unify, even if there are
1272 no type instances for T at all. Should we just turn them into an
1273 equality (T () a ~ T () Int)? I don't think so. We currently try to
1274 eagerly unify everything we can before generating equalities; otherwise,
1275 we could turn the unification of [Int] with [a] into an equality, too.
1277 Note [Unification and synonyms]
1278 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1279 If you are tempted to make a short cut on synonyms, as in this
1283 -- NO uTys (SynTy con1 args1 ty1) (SynTy con2 args2 ty2)
1284 -- NO = if (con1 == con2) then
1285 -- NO -- Good news! Same synonym constructors, so we can shortcut
1286 -- NO -- by unifying their arguments and ignoring their expansions.
1287 -- NO unifyTypepeLists args1 args2
1289 -- NO -- Never mind. Just expand them and try again
1293 then THINK AGAIN. Here is the whole story, as detected and reported
1294 by Chris Okasaki \tr{<Chris_Okasaki@loch.mess.cs.cmu.edu>}:
1296 Here's a test program that should detect the problem:
1300 x = (1 :: Bogus Char) :: Bogus Bool
1303 The problem with [the attempted shortcut code] is that
1307 is not a sufficient condition to be able to use the shortcut!
1308 You also need to know that the type synonym actually USES all
1309 its arguments. For example, consider the following type synonym
1310 which does not use all its arguments.
1315 If you ever tried unifying, say, \tr{Bogus Char} with \tr{Bogus Bool},
1316 the unifier would blithely try to unify \tr{Char} with \tr{Bool} and
1317 would fail, even though the expanded forms (both \tr{Int}) should
1320 Similarly, unifying \tr{Bogus Char} with \tr{Bogus t} would
1321 unnecessarily bind \tr{t} to \tr{Char}.
1323 ... You could explicitly test for the problem synonyms and mark them
1324 somehow as needing expansion, perhaps also issuing a warning to the
1329 %************************************************************************
1331 \subsection[Unify-uVar]{@uVar@: unifying with a type variable}
1333 %************************************************************************
1335 @uVar@ is called when at least one of the types being unified is a
1336 variable. It does {\em not} assume that the variable is a fixed point
1337 of the substitution; rather, notice that @uVar@ (defined below) nips
1338 back into @uTys@ if it turns out that the variable is already bound.
1342 -> SwapFlag -- False => tyvar is the "actual" (ty is "expected")
1343 -- True => ty is the "actual" (tyvar is "expected")
1345 -> InBox -- True <=> definitely no boxes in t2
1346 -> TcTauType -> TcTauType -- printing and real versions
1349 uVar outer swapped tv1 nb2 ps_ty2 ty2
1350 = do { let expansion | showSDoc (ppr ty2) == showSDoc (ppr ps_ty2) = empty
1351 | otherwise = brackets (equals <+> ppr ty2)
1352 ; traceTc (text "uVar" <+> ppr swapped <+>
1353 sep [ppr tv1 <+> dcolon <+> ppr (tyVarKind tv1 ),
1354 nest 2 (ptext SLIT(" <-> ")),
1355 ppr ps_ty2 <+> dcolon <+> ppr (typeKind ty2) <+> expansion])
1356 ; details <- lookupTcTyVar tv1
1359 | swapped -> u_tys outer nb2 ps_ty2 ty2 True ty1 ty1 -- Swap back
1360 | otherwise -> u_tys outer True ty1 ty1 nb2 ps_ty2 ty2 -- Same order
1361 -- The 'True' here says that ty1 is now inside a box
1362 DoneTv details1 -> uUnfilledVar outer swapped tv1 details1 ps_ty2 ty2
1366 uUnfilledVar :: Outer
1368 -> TcTyVar -> TcTyVarDetails -- Tyvar 1
1369 -> TcTauType -> TcTauType -- Type 2
1371 -- Invariant: tyvar 1 is not unified with anything
1373 uUnfilledVar outer swapped tv1 details1 ps_ty2 ty2
1374 | Just ty2' <- tcView ty2
1375 = -- Expand synonyms; ignore FTVs
1376 uUnfilledVar False swapped tv1 details1 ps_ty2 ty2'
1378 uUnfilledVar outer swapped tv1 details1 ps_ty2 (TyVarTy tv2)
1379 | tv1 == tv2 -- Same type variable => no-op (but watch out for the boxy case)
1381 MetaTv BoxTv ref1 -- A boxy type variable meets itself;
1382 -- this is box-meets-box, so fill in with a tau-type
1383 -> do { tau_tv <- tcInstTyVar tv1
1384 ; updateMeta tv1 ref1 (mkTyVarTy tau_tv)
1387 other -> return IdCo -- No-op
1389 | otherwise -- Distinct type variables
1390 = do { lookup2 <- lookupTcTyVar tv2
1392 IndirectTv ty2' -> uUnfilledVar outer swapped tv1 details1 ty2' ty2'
1393 DoneTv details2 -> uUnfilledVars outer swapped tv1 details1 tv2 details2
1396 uUnfilledVar outer swapped tv1 details1 ps_ty2 non_var_ty2
1397 = -- ty2 is not a type variable
1399 MetaTv (SigTv _) _ -> rigid_variable
1401 uMetaVar outer swapped tv1 info ref1 ps_ty2 non_var_ty2
1402 SkolemTv _ -> rigid_variable
1405 | isOpenSynTyConApp non_var_ty2
1406 = -- 'non_var_ty2's outermost constructor is a type family,
1407 -- which we may may be able to normalise
1408 do { (coi2, ty2') <- tcNormaliseFamInst non_var_ty2
1410 IdCo -> -- no progress, but maybe after other instantiations
1411 defer_unification outer swapped (TyVarTy tv1) ps_ty2
1412 ACo co -> -- progress: so lets try again
1414 ppr co <+> text "::"<+> ppr non_var_ty2 <+> text "~" <+>
1416 ; coi <- uUnfilledVar outer swapped tv1 details1 ps_ty2 ty2'
1417 ; let coi2' = (if swapped then id else mkSymCoI) coi2
1418 ; return $ coi2' `mkTransCoI` coi
1421 | SkolemTv RuntimeUnkSkol <- details1
1422 -- runtime unknown will never match
1423 = unifyMisMatch outer swapped (TyVarTy tv1) ps_ty2
1424 | otherwise -- defer as a given equality may still resolve this
1425 = defer_unification outer swapped (TyVarTy tv1) ps_ty2
1428 Note [Deferred Unification]
1429 ~~~~~~~~~~~~~~~~~~~~
1430 We may encounter a unification ty1 = ty2 that cannot be performed syntactically,
1431 and yet its consistency is undetermined. Previously, there was no way to still
1432 make it consistent. So a mismatch error was issued.
1434 Now these unfications are deferred until constraint simplification, where type
1435 family instances and given equations may (or may not) establish the consistency.
1436 Deferred unifications are of the form
1439 where F is a type function and x is a type variable.
1441 id :: x ~ y => x -> y
1444 involves the unfication x = y. It is deferred until we bring into account the
1445 context x ~ y to establish that it holds.
1447 If available, we defer original types (rather than those where closed type
1448 synonyms have already been expanded via tcCoreView). This is, as usual, to
1449 improve error messages.
1451 We need to both 'unBox' and zonk deferred types. We need to unBox as
1452 functions, such as TcExpr.tcMonoExpr promise to fill boxes in the expected
1453 type. We need to zonk as the types go into the kind of the coercion variable
1454 `cotv' and those are not zonked in Inst.zonkInst. (Maybe it would be better
1455 to zonk in zonInst instead. Would that be sufficient?)
1458 defer_unification :: Bool -- pop innermost context?
1463 defer_unification outer True ty1 ty2
1464 = defer_unification outer False ty2 ty1
1465 defer_unification outer False ty1 ty2
1466 = do { ty1' <- unBox ty1 >>= zonkTcType -- unbox *and* zonk..
1467 ; ty2' <- unBox ty2 >>= zonkTcType -- ..see preceding note
1468 ; traceTc $ text "deferring:" <+> ppr ty1 <+> text "~" <+> ppr ty2
1469 ; cotv <- newMetaCoVar ty1' ty2'
1470 -- put ty1 ~ ty2 in LIE
1471 -- Left means "wanted"
1472 ; inst <- (if outer then popErrCtxt else id) $
1473 mkEqInst (EqPred ty1' ty2') (Left cotv)
1475 ; return $ ACo $ TyVarTy cotv }
1478 uMetaVar :: Bool -- pop innermost context?
1480 -> TcTyVar -> BoxInfo -> IORef MetaDetails
1483 -- tv1 is an un-filled-in meta type variable (maybe boxy, maybe tau)
1484 -- ty2 is not a type variable
1486 uMetaVar outer swapped tv1 BoxTv ref1 ps_ty2 non_var_ty2
1487 = -- tv1 is a BoxTv. So we must unbox ty2, to ensure
1488 -- that any boxes in ty2 are filled with monotypes
1490 -- It should not be the case that tv1 occurs in ty2
1491 -- (i.e. no occurs check should be needed), but if perchance
1492 -- it does, the unbox operation will fill it, and the debug code
1494 do { final_ty <- unBox ps_ty2
1495 ; when debugIsOn $ do
1496 { meta_details <- readMutVar ref1
1497 ; case meta_details of
1498 Indirect ty -> WARN( True, ppr tv1 <+> ppr ty )
1499 return () -- This really should *not* happen
1502 ; checkUpdateMeta swapped tv1 ref1 final_ty
1506 uMetaVar outer swapped tv1 info1 ref1 ps_ty2 non_var_ty2
1507 = do { -- Occurs check + monotype check
1508 ; mb_final_ty <- checkTauTvUpdate tv1 ps_ty2
1509 ; case mb_final_ty of
1510 Nothing -> -- tv1 occured in type family parameter
1511 defer_unification outer swapped (mkTyVarTy tv1) ps_ty2
1513 do { checkUpdateMeta swapped tv1 ref1 final_ty
1519 uUnfilledVars :: Outer
1521 -> TcTyVar -> TcTyVarDetails -- Tyvar 1
1522 -> TcTyVar -> TcTyVarDetails -- Tyvar 2
1524 -- Invarant: The type variables are distinct,
1525 -- Neither is filled in yet
1526 -- They might be boxy or not
1528 uUnfilledVars outer swapped tv1 (SkolemTv _) tv2 (SkolemTv _)
1529 = -- see [Deferred Unification]
1530 defer_unification outer swapped (mkTyVarTy tv1) (mkTyVarTy tv2)
1532 uUnfilledVars outer swapped tv1 (MetaTv info1 ref1) tv2 (SkolemTv _)
1533 = checkUpdateMeta swapped tv1 ref1 (mkTyVarTy tv2) >> return IdCo
1534 uUnfilledVars outer swapped tv1 (SkolemTv _) tv2 (MetaTv info2 ref2)
1535 = checkUpdateMeta (not swapped) tv2 ref2 (mkTyVarTy tv1) >> return IdCo
1537 -- ToDo: this function seems too long for what it acutally does!
1538 uUnfilledVars outer swapped tv1 (MetaTv info1 ref1) tv2 (MetaTv info2 ref2)
1539 = case (info1, info2) of
1540 (BoxTv, BoxTv) -> box_meets_box >> return IdCo
1542 -- If a box meets a TauTv, but the fomer has the smaller kind
1543 -- then we must create a fresh TauTv with the smaller kind
1544 (_, BoxTv) | k1_sub_k2 -> update_tv2 >> return IdCo
1545 | otherwise -> box_meets_box >> return IdCo
1546 (BoxTv, _ ) | k2_sub_k1 -> update_tv1 >> return IdCo
1547 | otherwise -> box_meets_box >> return IdCo
1549 -- Avoid SigTvs if poss
1550 (SigTv _, _ ) | k1_sub_k2 -> update_tv2 >> return IdCo
1551 (_, SigTv _) | k2_sub_k1 -> update_tv1 >> return IdCo
1553 (_, _) | k1_sub_k2 -> if k2_sub_k1 && nicer_to_update_tv1
1554 then update_tv1 >> return IdCo -- Same kinds
1555 else update_tv2 >> return IdCo
1556 | k2_sub_k1 -> update_tv1 >> return IdCo
1557 | otherwise -> kind_err >> return IdCo
1559 -- Update the variable with least kind info
1560 -- See notes on type inference in Kind.lhs
1561 -- The "nicer to" part only applies if the two kinds are the same,
1562 -- so we can choose which to do.
1564 -- Kinds should be guaranteed ok at this point
1565 update_tv1 = updateMeta tv1 ref1 (mkTyVarTy tv2)
1566 update_tv2 = updateMeta tv2 ref2 (mkTyVarTy tv1)
1568 box_meets_box | k1_sub_k2 = if k2_sub_k1 && nicer_to_update_tv1
1571 | k2_sub_k1 = fill_from tv2
1572 | otherwise = kind_err
1574 -- Update *both* tyvars with a TauTv whose name and kind
1575 -- are gotten from tv (avoid losing nice names is poss)
1576 fill_from tv = do { tv' <- tcInstTyVar tv
1577 ; let tau_ty = mkTyVarTy tv'
1578 ; updateMeta tv1 ref1 tau_ty
1579 ; updateMeta tv2 ref2 tau_ty }
1581 kind_err = addErrCtxtM (unifyKindCtxt swapped tv1 (mkTyVarTy tv2)) $
1582 unifyKindMisMatch k1 k2
1586 k1_sub_k2 = k1 `isSubKind` k2
1587 k2_sub_k1 = k2 `isSubKind` k1
1589 nicer_to_update_tv1 = isSystemName (Var.varName tv1)
1590 -- Try to update sys-y type variables in preference to ones
1591 -- gotten (say) by instantiating a polymorphic function with
1592 -- a user-written type sig
1596 refineBox :: TcType -> TcM TcType
1597 -- Unbox the outer box of a boxy type (if any)
1598 refineBox ty@(TyVarTy box_tv)
1599 | isMetaTyVar box_tv
1600 = do { cts <- readMetaTyVar box_tv
1603 Indirect ty -> return ty }
1604 refineBox other_ty = return other_ty
1606 refineBoxToTau :: TcType -> TcM TcType
1607 -- Unbox the outer box of a boxy type, filling with a monotype if it is empty
1608 -- Like refineBox except for the "fill with monotype" part.
1609 refineBoxToTau ty@(TyVarTy box_tv)
1610 | isMetaTyVar box_tv
1611 , MetaTv BoxTv ref <- tcTyVarDetails box_tv
1612 = do { cts <- readMutVar ref
1614 Flexi -> fillBoxWithTau box_tv ref
1615 Indirect ty -> return ty }
1616 refineBoxToTau other_ty = return other_ty
1618 zapToMonotype :: BoxySigmaType -> TcM TcTauType
1619 -- Subtle... we must zap the boxy res_ty
1620 -- to kind * before using it to instantiate a LitInst
1621 -- Calling unBox instead doesn't do the job, because the box
1622 -- often has an openTypeKind, and we don't want to instantiate
1624 zapToMonotype res_ty
1625 = do { res_tau <- newFlexiTyVarTy liftedTypeKind
1626 ; boxyUnify res_tau res_ty
1629 unBox :: BoxyType -> TcM TcType
1630 -- unBox implements the judgement
1632 -- with input s', and result s
1634 -- It removes all boxes from the input type, returning a non-boxy type.
1635 -- A filled box in the type can only contain a monotype; unBox fails if not
1636 -- The type can have empty boxes, which unBox fills with a monotype
1638 -- Compare this wth checkTauTvUpdate
1640 -- For once, it's safe to treat synonyms as opaque!
1642 unBox (TyConApp tc tys) = do { tys' <- mapM unBox tys; return (TyConApp tc tys') }
1643 unBox (AppTy f a) = do { f' <- unBox f; a' <- unBox a; return (mkAppTy f' a') }
1644 unBox (FunTy f a) = do { f' <- unBox f; a' <- unBox a; return (FunTy f' a') }
1645 unBox (PredTy p) = do { p' <- unBoxPred p; return (PredTy p') }
1646 unBox (ForAllTy tv ty) = ASSERT( isImmutableTyVar tv )
1647 do { ty' <- unBox ty; return (ForAllTy tv ty') }
1649 | isTcTyVar tv -- It's a boxy type variable
1650 , MetaTv BoxTv ref <- tcTyVarDetails tv -- NB: non-TcTyVars are possible
1651 = do { cts <- readMutVar ref -- under nested quantifiers
1653 Flexi -> fillBoxWithTau tv ref
1654 Indirect ty -> do { non_boxy_ty <- unBox ty
1655 ; if isTauTy non_boxy_ty
1656 then return non_boxy_ty
1657 else notMonoType non_boxy_ty }
1659 | otherwise -- Skolems, and meta-tau-variables
1660 = return (TyVarTy tv)
1662 unBoxPred (ClassP cls tys) = do { tys' <- mapM unBox tys; return (ClassP cls tys') }
1663 unBoxPred (IParam ip ty) = do { ty' <- unBox ty; return (IParam ip ty') }
1664 unBoxPred (EqPred ty1 ty2) = do { ty1' <- unBox ty1; ty2' <- unBox ty2; return (EqPred ty1' ty2') }
1669 %************************************************************************
1671 \subsection[Unify-context]{Errors and contexts}
1673 %************************************************************************
1679 unifyCtxt act_ty exp_ty tidy_env
1680 = do { act_ty' <- zonkTcType act_ty
1681 ; exp_ty' <- zonkTcType exp_ty
1682 ; let (env1, exp_ty'') = tidyOpenType tidy_env exp_ty'
1683 (env2, act_ty'') = tidyOpenType env1 act_ty'
1684 ; return (env2, mkExpectedActualMsg act_ty'' exp_ty'') }
1687 mkExpectedActualMsg act_ty exp_ty
1688 = nest 2 (vcat [ text "Expected type" <> colon <+> ppr exp_ty,
1689 text "Inferred type" <> colon <+> ppr act_ty ])
1692 -- If an error happens we try to figure out whether the function
1693 -- function has been given too many or too few arguments, and say so.
1694 addSubCtxt orig actual_res_ty expected_res_ty thing_inside
1695 = addErrCtxtM mk_err thing_inside
1698 = do { exp_ty' <- zonkTcType expected_res_ty
1699 ; act_ty' <- zonkTcType actual_res_ty
1700 ; let (env1, exp_ty'') = tidyOpenType tidy_env exp_ty'
1701 (env2, act_ty'') = tidyOpenType env1 act_ty'
1702 (exp_args, _) = tcSplitFunTys exp_ty''
1703 (act_args, _) = tcSplitFunTys act_ty''
1705 len_act_args = length act_args
1706 len_exp_args = length exp_args
1708 message = case orig of
1710 | len_exp_args < len_act_args -> wrongArgsCtxt "too few" fun
1711 | len_exp_args > len_act_args -> wrongArgsCtxt "too many" fun
1712 other -> mkExpectedActualMsg act_ty'' exp_ty''
1713 ; return (env2, message) }
1715 wrongArgsCtxt too_many_or_few fun
1716 = ptext SLIT("Probable cause:") <+> quotes (ppr fun)
1717 <+> ptext SLIT("is applied to") <+> text too_many_or_few
1718 <+> ptext SLIT("arguments")
1721 unifyForAllCtxt tvs phi1 phi2 env
1722 = return (env2, msg)
1724 (env', tvs') = tidyOpenTyVars env tvs -- NB: not tidyTyVarBndrs
1725 (env1, phi1') = tidyOpenType env' phi1
1726 (env2, phi2') = tidyOpenType env1 phi2
1727 msg = vcat [ptext SLIT("When matching") <+> quotes (ppr (mkForAllTys tvs' phi1')),
1728 ptext SLIT(" and") <+> quotes (ppr (mkForAllTys tvs' phi2'))]
1730 -----------------------
1731 unifyMisMatch outer swapped ty1 ty2
1732 | swapped = unifyMisMatch outer False ty2 ty1
1733 | outer = popErrCtxt $ unifyMisMatch False swapped ty1 ty2 -- This is the whole point of the 'outer' stuff
1734 | otherwise = failWithMisMatch ty1 ty2
1738 %************************************************************************
1742 %************************************************************************
1744 Unifying kinds is much, much simpler than unifying types.
1747 unifyKind :: TcKind -- Expected
1750 unifyKind (TyConApp kc1 []) (TyConApp kc2 [])
1751 | isSubKindCon kc2 kc1 = return ()
1753 unifyKind (FunTy a1 r1) (FunTy a2 r2)
1754 = do { unifyKind a2 a1; unifyKind r1 r2 }
1755 -- Notice the flip in the argument,
1756 -- so that the sub-kinding works right
1757 unifyKind (TyVarTy kv1) k2 = uKVar False kv1 k2
1758 unifyKind k1 (TyVarTy kv2) = uKVar True kv2 k1
1759 unifyKind k1 k2 = unifyKindMisMatch k1 k2
1761 unifyKinds :: [TcKind] -> [TcKind] -> TcM ()
1762 unifyKinds [] [] = return ()
1763 unifyKinds (k1:ks1) (k2:ks2) = do unifyKind k1 k2
1765 unifyKinds _ _ = panic "unifyKinds: length mis-match"
1768 uKVar :: Bool -> KindVar -> TcKind -> TcM ()
1769 uKVar swapped kv1 k2
1770 = do { mb_k1 <- readKindVar kv1
1772 Flexi -> uUnboundKVar swapped kv1 k2
1773 Indirect k1 | swapped -> unifyKind k2 k1
1774 | otherwise -> unifyKind k1 k2 }
1777 uUnboundKVar :: Bool -> KindVar -> TcKind -> TcM ()
1778 uUnboundKVar swapped kv1 k2@(TyVarTy kv2)
1779 | kv1 == kv2 = return ()
1780 | otherwise -- Distinct kind variables
1781 = do { mb_k2 <- readKindVar kv2
1783 Indirect k2 -> uUnboundKVar swapped kv1 k2
1784 Flexi -> writeKindVar kv1 k2 }
1786 uUnboundKVar swapped kv1 non_var_k2
1787 = do { k2' <- zonkTcKind non_var_k2
1788 ; kindOccurCheck kv1 k2'
1789 ; k2'' <- kindSimpleKind swapped k2'
1790 -- KindVars must be bound only to simple kinds
1791 -- Polarities: (kindSimpleKind True ?) succeeds
1792 -- returning *, corresponding to unifying
1795 ; writeKindVar kv1 k2'' }
1798 kindOccurCheck kv1 k2 -- k2 is zonked
1799 = checkTc (not_in k2) (kindOccurCheckErr kv1 k2)
1801 not_in (TyVarTy kv2) = kv1 /= kv2
1802 not_in (FunTy a2 r2) = not_in a2 && not_in r2
1805 kindSimpleKind :: Bool -> Kind -> TcM SimpleKind
1806 -- (kindSimpleKind True k) returns a simple kind sk such that sk <: k
1807 -- If the flag is False, it requires k <: sk
1808 -- E.g. kindSimpleKind False ?? = *
1809 -- What about (kv -> *) :=: ?? -> *
1810 kindSimpleKind orig_swapped orig_kind
1811 = go orig_swapped orig_kind
1813 go sw (FunTy k1 k2) = do { k1' <- go (not sw) k1
1815 ; return (mkArrowKind k1' k2') }
1817 | isOpenTypeKind k = return liftedTypeKind
1818 | isArgTypeKind k = return liftedTypeKind
1820 | isLiftedTypeKind k = return liftedTypeKind
1821 | isUnliftedTypeKind k = return unliftedTypeKind
1822 go sw k@(TyVarTy _) = return k -- KindVars are always simple
1823 go swapped kind = failWithTc (ptext SLIT("Unexpected kind unification failure:")
1824 <+> ppr orig_swapped <+> ppr orig_kind)
1825 -- I think this can't actually happen
1827 -- T v = MkT v v must be a type
1828 -- T v w = MkT (v -> w) v must not be an umboxed tuple
1831 kindOccurCheckErr tyvar ty
1832 = hang (ptext SLIT("Occurs check: cannot construct the infinite kind:"))
1833 2 (sep [ppr tyvar, char '=', ppr ty])
1837 unifyFunKind :: TcKind -> TcM (Maybe (TcKind, TcKind))
1838 -- Like unifyFunTy, but does not fail; instead just returns Nothing
1840 unifyFunKind (TyVarTy kvar) = do
1841 maybe_kind <- readKindVar kvar
1843 Indirect fun_kind -> unifyFunKind fun_kind
1845 do { arg_kind <- newKindVar
1846 ; res_kind <- newKindVar
1847 ; writeKindVar kvar (mkArrowKind arg_kind res_kind)
1848 ; return (Just (arg_kind,res_kind)) }
1850 unifyFunKind (FunTy arg_kind res_kind) = return (Just (arg_kind,res_kind))
1851 unifyFunKind other = return Nothing
1854 %************************************************************************
1858 %************************************************************************
1860 ---------------------------
1861 -- We would like to get a decent error message from
1862 -- (a) Under-applied type constructors
1863 -- f :: (Maybe, Maybe)
1864 -- (b) Over-applied type constructors
1865 -- f :: Int x -> Int x
1869 checkExpectedKind :: Outputable a => a -> TcKind -> TcKind -> TcM ()
1870 -- A fancy wrapper for 'unifyKind', which tries
1871 -- to give decent error messages.
1872 -- (checkExpectedKind ty act_kind exp_kind)
1873 -- checks that the actual kind act_kind is compatible
1874 -- with the expected kind exp_kind
1875 -- The first argument, ty, is used only in the error message generation
1876 checkExpectedKind ty act_kind exp_kind
1877 | act_kind `isSubKind` exp_kind -- Short cut for a very common case
1880 (_errs, mb_r) <- tryTc (unifyKind exp_kind act_kind)
1882 Just r -> return () ; -- Unification succeeded
1885 -- So there's definitely an error
1886 -- Now to find out what sort
1887 exp_kind <- zonkTcKind exp_kind
1888 act_kind <- zonkTcKind act_kind
1890 env0 <- tcInitTidyEnv
1891 let (exp_as, _) = splitKindFunTys exp_kind
1892 (act_as, _) = splitKindFunTys act_kind
1893 n_exp_as = length exp_as
1894 n_act_as = length act_as
1896 (env1, tidy_exp_kind) = tidyKind env0 exp_kind
1897 (env2, tidy_act_kind) = tidyKind env1 act_kind
1899 err | n_exp_as < n_act_as -- E.g. [Maybe]
1900 = quotes (ppr ty) <+> ptext SLIT("is not applied to enough type arguments")
1902 -- Now n_exp_as >= n_act_as. In the next two cases,
1903 -- n_exp_as == 0, and hence so is n_act_as
1904 | isLiftedTypeKind exp_kind && isUnliftedTypeKind act_kind
1905 = ptext SLIT("Expecting a lifted type, but") <+> quotes (ppr ty)
1906 <+> ptext SLIT("is unlifted")
1908 | isUnliftedTypeKind exp_kind && isLiftedTypeKind act_kind
1909 = ptext SLIT("Expecting an unlifted type, but") <+> quotes (ppr ty)
1910 <+> ptext SLIT("is lifted")
1912 | otherwise -- E.g. Monad [Int]
1913 = ptext SLIT("Kind mis-match")
1915 more_info = sep [ ptext SLIT("Expected kind") <+>
1916 quotes (pprKind tidy_exp_kind) <> comma,
1917 ptext SLIT("but") <+> quotes (ppr ty) <+>
1918 ptext SLIT("has kind") <+> quotes (pprKind tidy_act_kind)]
1920 failWithTcM (env2, err $$ more_info)
1923 %************************************************************************
1925 \subsection{Checking signature type variables}
1927 %************************************************************************
1929 @checkSigTyVars@ checks that a set of universally quantified type varaibles
1930 are not mentioned in the environment. In particular:
1932 (a) Not mentioned in the type of a variable in the envt
1933 eg the signature for f in this:
1939 Here, f is forced to be monorphic by the free occurence of x.
1941 (d) Not (unified with another type variable that is) in scope.
1942 eg f x :: (r->r) = (\y->y) :: forall a. a->r
1943 when checking the expression type signature, we find that
1944 even though there is nothing in scope whose type mentions r,
1945 nevertheless the type signature for the expression isn't right.
1947 Another example is in a class or instance declaration:
1949 op :: forall b. a -> b
1951 Here, b gets unified with a
1953 Before doing this, the substitution is applied to the signature type variable.
1956 checkSigTyVars :: [TcTyVar] -> TcM ()
1957 checkSigTyVars sig_tvs = check_sig_tyvars emptyVarSet sig_tvs
1959 checkSigTyVarsWrt :: TcTyVarSet -> [TcTyVar] -> TcM ()
1960 -- The extra_tvs can include boxy type variables;
1961 -- e.g. TcMatches.tcCheckExistentialPat
1962 checkSigTyVarsWrt extra_tvs sig_tvs
1963 = do { extra_tvs' <- zonkTcTyVarsAndFV (varSetElems extra_tvs)
1964 ; check_sig_tyvars extra_tvs' sig_tvs }
1967 :: TcTyVarSet -- Global type variables. The universally quantified
1968 -- tyvars should not mention any of these
1969 -- Guaranteed already zonked.
1970 -> [TcTyVar] -- Universally-quantified type variables in the signature
1971 -- Guaranteed to be skolems
1973 check_sig_tyvars extra_tvs []
1975 check_sig_tyvars extra_tvs sig_tvs
1976 = ASSERT( all isSkolemTyVar sig_tvs )
1977 do { gbl_tvs <- tcGetGlobalTyVars
1978 ; traceTc (text "check_sig_tyvars" <+> (vcat [text "sig_tys" <+> ppr sig_tvs,
1979 text "gbl_tvs" <+> ppr gbl_tvs,
1980 text "extra_tvs" <+> ppr extra_tvs]))
1982 ; let env_tvs = gbl_tvs `unionVarSet` extra_tvs
1983 ; when (any (`elemVarSet` env_tvs) sig_tvs)
1984 (bleatEscapedTvs env_tvs sig_tvs sig_tvs)
1987 bleatEscapedTvs :: TcTyVarSet -- The global tvs
1988 -> [TcTyVar] -- The possibly-escaping type variables
1989 -> [TcTyVar] -- The zonked versions thereof
1991 -- Complain about escaping type variables
1992 -- We pass a list of type variables, at least one of which
1993 -- escapes. The first list contains the original signature type variable,
1994 -- while the second contains the type variable it is unified to (usually itself)
1995 bleatEscapedTvs globals sig_tvs zonked_tvs
1996 = do { env0 <- tcInitTidyEnv
1997 ; let (env1, tidy_tvs) = tidyOpenTyVars env0 sig_tvs
1998 (env2, tidy_zonked_tvs) = tidyOpenTyVars env1 zonked_tvs
2000 ; (env3, msgs) <- foldlM check (env2, []) (tidy_tvs `zip` tidy_zonked_tvs)
2001 ; failWithTcM (env3, main_msg $$ nest 2 (vcat msgs)) }
2003 main_msg = ptext SLIT("Inferred type is less polymorphic than expected")
2005 check (tidy_env, msgs) (sig_tv, zonked_tv)
2006 | not (zonked_tv `elemVarSet` globals) = return (tidy_env, msgs)
2008 = do { (tidy_env1, globs) <- findGlobals (unitVarSet zonked_tv) tidy_env
2009 ; return (tidy_env1, escape_msg sig_tv zonked_tv globs : msgs) }
2011 -----------------------
2012 escape_msg sig_tv zonked_tv globs
2014 = vcat [sep [msg, ptext SLIT("is mentioned in the environment:")],
2015 nest 2 (vcat globs)]
2017 = msg <+> ptext SLIT("escapes")
2018 -- Sigh. It's really hard to give a good error message
2019 -- all the time. One bad case is an existential pattern match.
2020 -- We rely on the "When..." context to help.
2022 msg = ptext SLIT("Quantified type variable") <+> quotes (ppr sig_tv) <+> is_bound_to
2024 | sig_tv == zonked_tv = empty
2025 | otherwise = ptext SLIT("is unified with") <+> quotes (ppr zonked_tv) <+> ptext SLIT("which")
2028 These two context are used with checkSigTyVars
2031 sigCtxt :: Id -> [TcTyVar] -> TcThetaType -> TcTauType
2032 -> TidyEnv -> TcM (TidyEnv, Message)
2033 sigCtxt id sig_tvs sig_theta sig_tau tidy_env = do
2034 actual_tau <- zonkTcType sig_tau
2036 (env1, tidy_sig_tvs) = tidyOpenTyVars tidy_env sig_tvs
2037 (env2, tidy_sig_rho) = tidyOpenType env1 (mkPhiTy sig_theta sig_tau)
2038 (env3, tidy_actual_tau) = tidyOpenType env2 actual_tau
2039 sub_msg = vcat [ptext SLIT("Signature type: ") <+> pprType (mkForAllTys tidy_sig_tvs tidy_sig_rho),
2040 ptext SLIT("Type to generalise:") <+> pprType tidy_actual_tau
2042 msg = vcat [ptext SLIT("When trying to generalise the type inferred for") <+> quotes (ppr id),