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
67 %************************************************************************
69 \subsection{'hole' type variables}
71 %************************************************************************
74 tcInfer :: (BoxyType -> TcM a) -> TcM (a, TcType)
75 tcInfer tc_infer = withBox openTypeKind tc_infer
79 %************************************************************************
83 %************************************************************************
86 subFunTys :: SDoc -- Somthing like "The function f has 3 arguments"
87 -- or "The abstraction (\x.e) takes 1 argument"
88 -> Arity -- Expected # of args
89 -> BoxyRhoType -- res_ty
90 -> ([BoxySigmaType] -> BoxyRhoType -> TcM a)
92 -- Attempt to decompse res_ty to have enough top-level arrows to
93 -- match the number of patterns in the match group
95 -- If (subFunTys n_args res_ty thing_inside) = (co_fn, res)
96 -- and the inner call to thing_inside passes args: [a1,...,an], b
97 -- then co_fn :: (a1 -> ... -> an -> b) ~ res_ty
99 -- Note that it takes a BoxyRho type, and guarantees to return a BoxyRhoType
102 {- Error messages from subFunTys
104 The abstraction `\Just 1 -> ...' has two arguments
105 but its type `Maybe a -> a' has only one
107 The equation(s) for `f' have two arguments
108 but its type `Maybe a -> a' has only one
110 The section `(f 3)' requires 'f' to take two arguments
111 but its type `Int -> Int' has only one
113 The function 'f' is applied to two arguments
114 but its type `Int -> Int' has only one
118 subFunTys error_herald n_pats res_ty thing_inside
119 = loop n_pats [] res_ty
121 -- In 'loop', the parameter 'arg_tys' accumulates
122 -- the arg types so far, in *reverse order*
123 -- INVARIANT: res_ty :: *
124 loop n args_so_far res_ty
125 | Just res_ty' <- tcView res_ty = loop n args_so_far res_ty'
127 loop n args_so_far res_ty
128 | isSigmaTy res_ty -- Do this before checking n==0, because we
129 -- guarantee to return a BoxyRhoType, not a
131 = do { (gen_fn, (co_fn, res)) <- tcGen res_ty emptyVarSet $ \ _ res_ty' ->
132 loop n args_so_far res_ty'
133 ; return (gen_fn <.> co_fn, res) }
135 loop 0 args_so_far res_ty
136 = do { res <- thing_inside (reverse args_so_far) res_ty
137 ; return (idHsWrapper, res) }
139 loop n args_so_far (FunTy arg_ty res_ty)
140 = do { (co_fn, res) <- loop (n-1) (arg_ty:args_so_far) res_ty
141 ; co_fn' <- wrapFunResCoercion [arg_ty] co_fn
142 ; return (co_fn', res) }
144 -- Try to normalise synonym families and defer if that's not possible
145 loop n args_so_far ty@(TyConApp tc tys)
147 = do { (coi1, ty') <- tcNormaliseFamInst ty
149 IdCo -> defer n args_so_far ty
150 -- no progress, but maybe solvable => defer
151 ACo _ -> -- progress: so lets try again
152 do { (co_fn, res) <- loop n args_so_far ty'
153 ; return $ (co_fn <.> coiToHsWrapper (mkSymCoI coi1), res)
157 -- res_ty might have a type variable at the head, such as (a b c),
158 -- in which case we must fill in with (->). Simplest thing to do
159 -- is to use boxyUnify, but we catch failure and generate our own
160 -- error message on failure
161 loop n args_so_far res_ty@(AppTy _ _)
162 = do { [arg_ty',res_ty'] <- newBoxyTyVarTys [argTypeKind, openTypeKind]
163 ; (_, mb_coi) <- tryTcErrs $
164 boxyUnify res_ty (FunTy arg_ty' res_ty')
165 ; if isNothing mb_coi then bale_out args_so_far
166 else do { let coi = expectJust "subFunTys" mb_coi
167 ; (co_fn, res) <- loop n args_so_far (FunTy arg_ty'
169 ; return (co_fn <.> coiToHsWrapper coi, res)
173 loop n args_so_far ty@(TyVarTy tv)
174 | isTyConableTyVar tv
175 = do { cts <- readMetaTyVar tv
177 Indirect ty -> loop n args_so_far ty
179 do { (res_ty:arg_tys) <- withMetaTvs tv kinds mk_res_ty
180 ; res <- thing_inside (reverse args_so_far ++ arg_tys)
182 ; return (idHsWrapper, res) } }
183 | otherwise -- defer as tyvar may be refined by equalities
184 = defer n args_so_far ty
186 mk_res_ty (res_ty' : arg_tys') = mkFunTys arg_tys' res_ty'
187 mk_res_ty [] = panic "TcUnify.mk_res_ty1"
188 kinds = openTypeKind : take n (repeat argTypeKind)
189 -- Note argTypeKind: the args can have an unboxed type,
190 -- but not an unboxed tuple.
192 loop n args_so_far res_ty = bale_out args_so_far
194 -- build a template type a1 -> ... -> an -> b and defer an equality
195 -- between that template and the expected result type res_ty; then,
196 -- use the template to type the thing_inside
197 defer n args_so_far ty
198 = do { arg_tys <- newFlexiTyVarTys n argTypeKind
199 ; res_ty' <- newFlexiTyVarTy openTypeKind
200 ; let fun_ty = mkFunTys arg_tys res_ty'
201 err = error_herald <> comma $$
202 text "which does not match its type"
203 ; coi <- addErrCtxt err $
204 defer_unification False False fun_ty ty
205 ; res <- thing_inside (reverse args_so_far ++ arg_tys) res_ty'
206 ; return (coiToHsWrapper coi, res)
210 = do { env0 <- tcInitTidyEnv
211 ; res_ty' <- zonkTcType res_ty
212 ; let (env1, res_ty'') = tidyOpenType env0 res_ty'
213 ; failWithTcM (env1, mk_msg res_ty'' (length args_so_far)) }
215 mk_msg res_ty n_actual
216 = error_herald <> comma $$
217 sep [ptext SLIT("but its type") <+> quotes (pprType res_ty),
218 if n_actual == 0 then ptext SLIT("has none")
219 else ptext SLIT("has only") <+> speakN n_actual]
223 ----------------------
224 boxySplitTyConApp :: TyCon -- T :: k1 -> ... -> kn -> *
225 -> BoxyRhoType -- Expected type (T a b c)
226 -> TcM ([BoxySigmaType], -- Element types, a b c
227 CoercionI) -- T a b c ~ orig_ty
228 -- It's used for wired-in tycons, so we call checkWiredInTyCon
229 -- Precondition: never called with FunTyCon
230 -- Precondition: input type :: *
232 boxySplitTyConApp tc orig_ty
233 = do { checkWiredInTyCon tc
234 ; loop (tyConArity tc) [] orig_ty }
236 loop n_req args_so_far ty
237 | Just ty' <- tcView ty = loop n_req args_so_far ty'
239 loop n_req args_so_far ty@(TyConApp tycon args)
241 = ASSERT( n_req == length args) -- ty::*
242 return (args ++ args_so_far, IdCo)
244 | isOpenSynTyCon tycon -- try to normalise type family application
245 = do { (coi1, ty') <- tcNormaliseFamInst ty
246 ; traceTc $ text "boxySplitTyConApp:" <+>
247 ppr ty <+> text "==>" <+> ppr ty'
249 IdCo -> defer -- no progress, but maybe solvable => defer
250 ACo _ -> -- progress: so lets try again
251 do { (args, coi2) <- loop n_req args_so_far ty'
252 ; return $ (args, coi2 `mkTransCoI` mkSymCoI coi1)
256 loop n_req args_so_far (AppTy fun arg)
258 = do { (args, coi) <- loop (n_req - 1) (arg:args_so_far) fun
259 ; return (args, mkAppTyCoI fun coi arg IdCo)
262 loop n_req args_so_far (TyVarTy tv)
263 | isTyConableTyVar tv
264 , res_kind `isSubKind` tyVarKind tv
265 = do { cts <- readMetaTyVar tv
267 Indirect ty -> loop n_req args_so_far ty
268 Flexi -> do { arg_tys <- withMetaTvs tv arg_kinds mk_res_ty
269 ; return (arg_tys ++ args_so_far, IdCo) }
271 | otherwise -- defer as tyvar may be refined by equalities
274 (arg_kinds, res_kind) = splitKindFunTysN n_req (tyConKind tc)
276 loop _ _ _ = boxySplitFailure (mkTyConApp tc (mkTyVarTys (tyConTyVars tc)))
279 -- defer splitting by generating an equality constraint
280 defer = boxySplitDefer arg_kinds mk_res_ty orig_ty
282 (arg_kinds, _) = splitKindFunTys (tyConKind tc)
284 -- apply splitted tycon to arguments
285 mk_res_ty = mkTyConApp tc
287 ----------------------
288 boxySplitListTy :: BoxyRhoType -> TcM (BoxySigmaType, CoercionI)
289 -- Special case for lists
290 boxySplitListTy exp_ty
291 = do { ([elt_ty], coi) <- boxySplitTyConApp listTyCon exp_ty
292 ; return (elt_ty, coi) }
294 ----------------------
295 boxySplitPArrTy :: BoxyRhoType -> TcM (BoxySigmaType, CoercionI)
296 -- Special case for parrs
297 boxySplitPArrTy exp_ty
298 = do { ([elt_ty], coi) <- boxySplitTyConApp parrTyCon exp_ty
299 ; return (elt_ty, coi) }
301 ----------------------
302 boxySplitAppTy :: BoxyRhoType -- Type to split: m a
303 -> TcM ((BoxySigmaType, BoxySigmaType), -- Returns m, a
305 -- If the incoming type is a mutable type variable of kind k, then
306 -- boxySplitAppTy returns a new type variable (m: * -> k); note the *.
307 -- If the incoming type is boxy, then so are the result types; and vice versa
309 boxySplitAppTy orig_ty
313 | Just ty' <- tcView ty = loop ty'
316 | Just (fun_ty, arg_ty) <- tcSplitAppTy_maybe ty
317 = return ((fun_ty, arg_ty), IdCo)
319 loop ty@(TyConApp tycon _args)
320 | isOpenSynTyCon tycon -- try to normalise type family application
321 = do { (coi1, ty') <- tcNormaliseFamInst ty
323 IdCo -> defer -- no progress, but maybe solvable => defer
324 ACo co -> -- progress: so lets try again
325 do { (args, coi2) <- loop ty'
326 ; return $ (args, coi2 `mkTransCoI` mkSymCoI coi1)
331 | isTyConableTyVar tv
332 = do { cts <- readMetaTyVar tv
334 Indirect ty -> loop ty
335 Flexi -> do { [fun_ty, arg_ty] <- withMetaTvs tv kinds mk_res_ty
336 ; return ((fun_ty, arg_ty), IdCo) } }
337 | otherwise -- defer as tyvar may be refined by equalities
340 tv_kind = tyVarKind tv
341 kinds = [mkArrowKind liftedTypeKind (defaultKind tv_kind),
343 liftedTypeKind] -- arg type :: *
344 -- The defaultKind is a bit smelly. If you remove it,
345 -- try compiling f x = do { x }
346 -- and you'll get a kind mis-match. It smells, but
347 -- not enough to lose sleep over.
349 loop _ = boxySplitFailure (mkAppTy alphaTy betaTy) orig_ty
351 -- defer splitting by generating an equality constraint
352 defer = do { ([ty1, ty2], coi) <- boxySplitDefer arg_kinds mk_res_ty orig_ty
353 ; return ((ty1, ty2), coi)
356 orig_kind = typeKind orig_ty
357 arg_kinds = [mkArrowKind liftedTypeKind (defaultKind orig_kind),
359 liftedTypeKind] -- arg type :: *
361 -- build type application
362 mk_res_ty [fun_ty', arg_ty'] = mkAppTy fun_ty' arg_ty'
363 mk_res_ty _other = panic "TcUnify.mk_res_ty2"
366 boxySplitFailure actual_ty expected_ty
367 = unifyMisMatch False False actual_ty expected_ty
368 -- "outer" is False, so we don't pop the context
369 -- which is what we want since we have not pushed one!
372 boxySplitDefer :: [Kind] -- kinds of required arguments
373 -> ([TcType] -> TcTauType) -- construct lhs from argument tyvars
374 -> BoxyRhoType -- type to split
375 -> TcM ([TcType], CoercionI)
376 boxySplitDefer kinds mkTy orig_ty
377 = do { tau_tys <- mapM newFlexiTyVarTy kinds
378 ; coi <- defer_unification False False (mkTy tau_tys) orig_ty
379 ; return (tau_tys, coi)
384 --------------------------------
385 -- withBoxes: the key utility function
386 --------------------------------
389 withMetaTvs :: TcTyVar -- An unfilled-in, non-skolem, meta type variable
390 -> [Kind] -- Make fresh boxes (with the same BoxTv/TauTv setting as tv)
391 -> ([BoxySigmaType] -> BoxySigmaType)
392 -- Constructs the type to assign
393 -- to the original var
394 -> TcM [BoxySigmaType] -- Return the fresh boxes
396 -- It's entirely possible for the [kind] to be empty.
397 -- For example, when pattern-matching on True,
398 -- we call boxySplitTyConApp passing a boolTyCon
400 -- Invariant: tv is still Flexi
402 withMetaTvs tv kinds mk_res_ty
404 = do { box_tvs <- mapM (newMetaTyVar BoxTv) kinds
405 ; let box_tys = mkTyVarTys box_tvs
406 ; writeMetaTyVar tv (mk_res_ty box_tys)
409 | otherwise -- Non-boxy meta type variable
410 = do { tau_tys <- mapM newFlexiTyVarTy kinds
411 ; writeMetaTyVar tv (mk_res_ty tau_tys) -- Write it *first*
412 -- Sure to be a tau-type
415 withBox :: Kind -> (BoxySigmaType -> TcM a) -> TcM (a, TcType)
416 -- Allocate a *boxy* tyvar
417 withBox kind thing_inside
418 = do { box_tv <- newBoxyTyVar kind
419 ; res <- thing_inside (mkTyVarTy box_tv)
420 ; ty <- {- pprTrace "with_box" (ppr (mkTyVarTy box_tv)) $ -} readFilledBox box_tv
425 %************************************************************************
427 Approximate boxy matching
429 %************************************************************************
432 preSubType :: [TcTyVar] -- Quantified type variables
433 -> TcTyVarSet -- Subset of quantified type variables
434 -- see Note [Pre-sub boxy]
435 -> TcType -- The rho-type part; quantified tyvars scopes over this
436 -> BoxySigmaType -- Matching type from the context
437 -> TcM [TcType] -- Types to instantiate the tyvars
438 -- Perform pre-subsumption, and return suitable types
439 -- to instantiate the quantified type varibles:
440 -- info from the pre-subsumption, if there is any
441 -- a boxy type variable otherwise
443 -- Note [Pre-sub boxy]
444 -- The 'btvs' are a subset of 'qtvs'. They are the ones we can
445 -- instantiate to a boxy type variable, because they'll definitely be
446 -- filled in later. This isn't always the case; sometimes we have type
447 -- variables mentioned in the context of the type, but not the body;
448 -- f :: forall a b. C a b => a -> a
449 -- Then we may land up with an unconstrained 'b', so we want to
450 -- instantiate it to a monotype (non-boxy) type variable
452 -- The 'qtvs' that are *neither* fixed by the pre-subsumption, *nor* are in 'btvs',
453 -- are instantiated to TauTv meta variables.
455 preSubType qtvs btvs qty expected_ty
456 = do { tys <- mapM inst_tv qtvs
457 ; traceTc (text "preSubType" <+> (ppr qtvs $$ ppr btvs $$ ppr qty $$ ppr expected_ty $$ ppr pre_subst $$ ppr tys))
460 pre_subst = boxySubMatchType (mkVarSet qtvs) qty expected_ty
462 | Just boxy_ty <- lookupTyVar pre_subst tv = return boxy_ty
463 | tv `elemVarSet` btvs = do { tv' <- tcInstBoxyTyVar tv
464 ; return (mkTyVarTy tv') }
465 | otherwise = do { tv' <- tcInstTyVar tv
466 ; return (mkTyVarTy tv') }
469 :: TcTyVarSet -> TcType -- The "template"; the tyvars are skolems
470 -> BoxyRhoType -- Type to match (note a *Rho* type)
471 -> TvSubst -- Substitution of the [TcTyVar] to BoxySigmaTypes
473 -- boxySubMatchType implements the Pre-subsumption judgement, in Fig 5 of the paper
474 -- "Boxy types: inference for higher rank types and impredicativity"
476 boxySubMatchType tmpl_tvs tmpl_ty boxy_ty
477 = go tmpl_tvs tmpl_ty emptyVarSet boxy_ty
479 go t_tvs t_ty b_tvs b_ty
480 | Just t_ty' <- tcView t_ty = go t_tvs t_ty' b_tvs b_ty
481 | Just b_ty' <- tcView b_ty = go t_tvs t_ty b_tvs b_ty'
483 go t_tvs (TyVarTy _) b_tvs b_ty = emptyTvSubst -- Rule S-ANY; no bindings
484 -- Rule S-ANY covers (a) type variables and (b) boxy types
485 -- in the template. Both look like a TyVarTy.
486 -- See Note [Sub-match] below
488 go t_tvs t_ty b_tvs b_ty
489 | isSigmaTy t_ty, (tvs, _, t_tau) <- tcSplitSigmaTy t_ty
490 = go (t_tvs `delVarSetList` tvs) t_tau b_tvs b_ty -- Rule S-SPEC
491 -- Under a forall on the left, if there is shadowing,
492 -- do not bind! Hence the delVarSetList.
493 | isSigmaTy b_ty, (tvs, _, b_tau) <- tcSplitSigmaTy b_ty
494 = go t_tvs t_ty (extendVarSetList b_tvs tvs) b_tau -- Rule S-SKOL
495 -- Add to the variables we must not bind to
496 -- NB: it's *important* to discard the theta part. Otherwise
497 -- consider (forall a. Eq a => a -> b) ~<~ (Int -> Int -> Bool)
498 -- and end up with a completely bogus binding (b |-> Bool), by lining
499 -- up the (Eq a) with the Int, whereas it should be (b |-> (Int->Bool)).
500 -- This pre-subsumption stuff can return too few bindings, but it
501 -- must *never* return bogus info.
503 go t_tvs (FunTy arg1 res1) b_tvs (FunTy arg2 res2) -- Rule S-FUN
504 = boxy_match t_tvs arg1 b_tvs arg2 (go t_tvs res1 b_tvs res2)
505 -- Match the args, and sub-match the results
507 go t_tvs t_ty b_tvs b_ty = boxy_match t_tvs t_ty b_tvs b_ty emptyTvSubst
508 -- Otherwise defer to boxy matching
509 -- This covers TyConApp, AppTy, PredTy
516 |- head xs : <rhobox>
517 We will do a boxySubMatchType between a ~ <rhobox>
518 But we *don't* want to match [a |-> <rhobox>] because
519 (a) The box should be filled in with a rho-type, but
520 but the returned substitution maps TyVars to boxy
522 (b) In any case, the right final answer might be *either*
523 instantiate 'a' with a rho-type or a sigma type
524 head xs : Int vs head xs : forall b. b->b
525 So the matcher MUST NOT make a choice here. In general, we only
526 bind a template type variable in boxyMatchType, not in boxySubMatchType.
531 :: TcTyVarSet -> [TcType] -- The "template"; the tyvars are skolems
532 -> [BoxySigmaType] -- Type to match
533 -> TvSubst -- Substitution of the [TcTyVar] to BoxySigmaTypes
535 -- boxyMatchTypes implements the Pre-matching judgement, in Fig 5 of the paper
536 -- "Boxy types: inference for higher rank types and impredicativity"
538 -- Find a *boxy* substitution that makes the template look as much
539 -- like the BoxySigmaType as possible.
540 -- It's always ok to return an empty substitution;
541 -- anything more is jam on the pudding
543 -- NB1: This is a pure, non-monadic function.
544 -- It does no unification, and cannot fail
546 -- Precondition: the arg lengths are equal
547 -- Precondition: none of the template type variables appear anywhere in the [BoxySigmaType]
551 boxyMatchTypes tmpl_tvs tmpl_tys boxy_tys
552 = ASSERT( length tmpl_tys == length boxy_tys )
553 boxy_match_s tmpl_tvs tmpl_tys emptyVarSet boxy_tys emptyTvSubst
554 -- ToDo: add error context?
556 boxy_match_s tmpl_tvs [] boxy_tvs [] subst
558 boxy_match_s tmpl_tvs (t_ty:t_tys) boxy_tvs (b_ty:b_tys) subst
559 = boxy_match tmpl_tvs t_ty boxy_tvs b_ty $
560 boxy_match_s tmpl_tvs t_tys boxy_tvs b_tys subst
561 boxy_match_s tmpl_tvs _ boxy_tvs _ subst
562 = panic "boxy_match_s" -- Lengths do not match
566 boxy_match :: TcTyVarSet -> TcType -- Template
567 -> TcTyVarSet -- boxy_tvs: do not bind template tyvars to any of these
568 -> BoxySigmaType -- Match against this type
572 -- The boxy_tvs argument prevents this match:
573 -- [a] forall b. a ~ forall b. b
574 -- We don't want to bind the template variable 'a'
575 -- to the quantified type variable 'b'!
577 boxy_match tmpl_tvs orig_tmpl_ty boxy_tvs orig_boxy_ty subst
578 = go orig_tmpl_ty orig_boxy_ty
581 | Just t_ty' <- tcView t_ty = go t_ty' b_ty
582 | Just b_ty' <- tcView b_ty = go t_ty b_ty'
584 go ty1 ty2 -- C.f. the isSigmaTy case for boxySubMatchType
586 , (tvs1, _, tau1) <- tcSplitSigmaTy ty1
587 , (tvs2, _, tau2) <- tcSplitSigmaTy ty2
588 , equalLength tvs1 tvs2
589 = boxy_match (tmpl_tvs `delVarSetList` tvs1) tau1
590 (boxy_tvs `extendVarSetList` tvs2) tau2 subst
592 go (TyConApp tc1 tys1) (TyConApp tc2 tys2)
594 , not $ isOpenSynTyCon tc1
597 go (FunTy arg1 res1) (FunTy arg2 res2)
598 = go_s [arg1,res1] [arg2,res2]
601 | Just (s1,t1) <- tcSplitAppTy_maybe t_ty,
602 Just (s2,t2) <- tcSplitAppTy_maybe b_ty,
603 typeKind t2 `isSubKind` typeKind t1 -- Maintain invariant
604 = go_s [s1,t1] [s2,t2]
607 | tv `elemVarSet` tmpl_tvs -- Template type variable in the template
608 , boxy_tvs `disjointVarSet` tyVarsOfType orig_boxy_ty
609 , typeKind b_ty `isSubKind` tyVarKind tv -- See Note [Matching kinds]
610 = extendTvSubst subst tv boxy_ty'
612 = subst -- Ignore others
614 boxy_ty' = case lookupTyVar subst tv of
615 Nothing -> orig_boxy_ty
616 Just ty -> ty `boxyLub` orig_boxy_ty
618 go _ _ = emptyTvSubst -- It's important to *fail* by returning the empty substitution
619 -- Example: Tree a ~ Maybe Int
620 -- We do not want to bind (a |-> Int) in pre-matching, because that can give very
621 -- misleading error messages. An even more confusing case is
622 -- a -> b ~ Maybe Int
623 -- Then we do not want to bind (b |-> Int)! It's always safe to discard bindings
624 -- from this pre-matching phase.
627 go_s tys1 tys2 = boxy_match_s tmpl_tvs tys1 boxy_tvs tys2 subst
630 boxyLub :: BoxySigmaType -> BoxySigmaType -> BoxySigmaType
631 -- Combine boxy information from the two types
632 -- If there is a conflict, return the first
633 boxyLub orig_ty1 orig_ty2
634 = go orig_ty1 orig_ty2
636 go (AppTy f1 a1) (AppTy f2 a2) = AppTy (boxyLub f1 f2) (boxyLub a1 a2)
637 go (FunTy f1 a1) (FunTy f2 a2) = FunTy (boxyLub f1 f2) (boxyLub a1 a2)
638 go (TyConApp tc1 ts1) (TyConApp tc2 ts2)
639 | tc1 == tc2, length ts1 == length ts2
640 = TyConApp tc1 (zipWith boxyLub ts1 ts2)
642 go (TyVarTy tv1) ty2 -- This is the whole point;
643 | isTcTyVar tv1, isBoxyTyVar tv1 -- choose ty2 if ty2 is a box
646 -- Look inside type synonyms, but only if the naive version fails
647 go ty1 ty2 | Just ty1' <- tcView ty1 = go ty1' ty2
648 | Just ty2' <- tcView ty1 = go ty1 ty2'
650 -- For now, we don't look inside ForAlls, PredTys
651 go ty1 ty2 = orig_ty1 -- Default
654 Note [Matching kinds]
655 ~~~~~~~~~~~~~~~~~~~~~
656 The target type might legitimately not be a sub-kind of template.
657 For example, suppose the target is simply a box with an OpenTypeKind,
658 and the template is a type variable with LiftedTypeKind.
659 Then it's ok (because the target type will later be refined).
660 We simply don't bind the template type variable.
662 It might also be that the kind mis-match is an error. For example,
663 suppose we match the template (a -> Int) against (Int# -> Int),
664 where the template type variable 'a' has LiftedTypeKind. This
665 matching function does not fail; it simply doesn't bind the template.
666 Later stuff will fail.
668 %************************************************************************
672 %************************************************************************
674 All the tcSub calls have the form
676 tcSub actual_ty expected_ty
678 actual_ty <= expected_ty
680 That is, that a value of type actual_ty is acceptable in
681 a place expecting a value of type expected_ty.
683 It returns a coercion function
684 co_fn :: actual_ty ~ expected_ty
685 which takes an HsExpr of type actual_ty into one of type
690 tcSubExp :: InstOrigin -> BoxySigmaType -> BoxySigmaType -> TcM HsWrapper
691 -- (tcSub act exp) checks that
693 tcSubExp orig actual_ty expected_ty
694 = -- addErrCtxtM (unifyCtxt actual_ty expected_ty) $
695 -- Adding the error context here leads to some very confusing error
696 -- messages, such as "can't match forall a. a->a with forall a. a->a"
697 -- Example is tcfail165:
698 -- do var <- newEmptyMVar :: IO (MVar (forall a. Show a => a -> String))
699 -- putMVar var (show :: forall a. Show a => a -> String)
700 -- Here the info does not flow from the 'var' arg of putMVar to its 'show' arg
701 -- but after zonking it looks as if it does!
703 -- So instead I'm adding the error context when moving from tc_sub to u_tys
705 traceTc (text "tcSubExp" <+> ppr actual_ty <+> ppr expected_ty) >>
706 tc_sub orig actual_ty actual_ty False expected_ty expected_ty
710 -> BoxySigmaType -- actual_ty, before expanding synonyms
711 -> BoxySigmaType -- ..and after
712 -> InBox -- True <=> expected_ty is inside a box
713 -> BoxySigmaType -- expected_ty, before
714 -> BoxySigmaType -- ..and after
716 -- The acual_ty is never inside a box
717 -- IMPORTANT pre-condition: if the args contain foralls, the bound type
718 -- variables are visible non-monadically
719 -- (i.e. tha args are sufficiently zonked)
720 -- This invariant is needed so that we can "see" the foralls, ad
721 -- e.g. in the SPEC rule where we just use splitSigmaTy
723 tc_sub orig act_sty act_ty exp_ib exp_sty exp_ty
724 = traceTc (text "tc_sub" <+> ppr act_ty $$ ppr exp_ty) >>
725 tc_sub1 orig act_sty act_ty exp_ib exp_sty exp_ty
726 -- This indirection is just here to make
727 -- it easy to insert a debug trace!
729 tc_sub1 orig act_sty act_ty exp_ib exp_sty exp_ty
730 | Just exp_ty' <- tcView exp_ty = tc_sub orig act_sty act_ty exp_ib exp_sty exp_ty'
731 tc_sub1 orig act_sty act_ty exp_ib exp_sty exp_ty
732 | Just act_ty' <- tcView act_ty = tc_sub orig act_sty act_ty' exp_ib exp_sty exp_ty
734 -----------------------------------
735 -- Rule SBOXY, plus other cases when act_ty is a type variable
736 -- Just defer to boxy matching
737 -- This rule takes precedence over SKOL!
738 tc_sub1 orig act_sty (TyVarTy tv) exp_ib exp_sty exp_ty
739 = do { traceTc (text "tc_sub1 - case 1")
740 ; coi <- addSubCtxt orig act_sty exp_sty $
741 uVar True False tv exp_ib exp_sty exp_ty
742 ; traceTc (case coi of
743 IdCo -> text "tc_sub1 (Rule SBOXY) IdCo"
744 ACo co -> text "tc_sub1 (Rule SBOXY) ACo" <+> ppr co)
745 ; return $ coiToHsWrapper coi
748 -----------------------------------
749 -- Skolemisation case (rule SKOL)
750 -- actual_ty: d:Eq b => b->b
751 -- expected_ty: forall a. Ord a => a->a
752 -- co_fn e /\a. \d2:Ord a. let d = eqFromOrd d2 in e
754 -- It is essential to do this *before* the specialisation case
755 -- Example: f :: (Eq a => a->a) -> ...
756 -- g :: Ord b => b->b
759 tc_sub1 orig act_sty act_ty exp_ib exp_sty exp_ty
760 | isSigmaTy exp_ty = do
761 { traceTc (text "tc_sub1 - case 2") ;
762 if exp_ib then -- SKOL does not apply if exp_ty is inside a box
763 defer_to_boxy_matching orig act_sty act_ty exp_ib exp_sty exp_ty
765 { (gen_fn, co_fn) <- tcGen exp_ty act_tvs $ \ _ body_exp_ty ->
766 tc_sub orig act_sty act_ty False body_exp_ty body_exp_ty
767 ; return (gen_fn <.> co_fn) }
770 act_tvs = tyVarsOfType act_ty
771 -- It's really important to check for escape wrt
772 -- the free vars of both expected_ty *and* actual_ty
774 -----------------------------------
775 -- Specialisation case (rule ASPEC):
776 -- actual_ty: forall a. Ord a => a->a
777 -- expected_ty: Int -> Int
778 -- co_fn e = e Int dOrdInt
780 tc_sub1 orig act_sty actual_ty exp_ib exp_sty expected_ty
781 -- Implements the new SPEC rule in the Appendix of the paper
782 -- "Boxy types: inference for higher rank types and impredicativity"
783 -- (This appendix isn't in the published version.)
784 -- The idea is to *first* do pre-subsumption, and then full subsumption
785 -- Example: forall a. a->a <= Int -> (forall b. Int)
786 -- Pre-subsumpion finds a|->Int, and that works fine, whereas
787 -- just running full subsumption would fail.
788 | isSigmaTy actual_ty
789 = do { traceTc (text "tc_sub1 - case 3")
790 ; -- Perform pre-subsumption, and instantiate
791 -- the type with info from the pre-subsumption;
792 -- boxy tyvars if pre-subsumption gives no info
793 let (tyvars, theta, tau) = tcSplitSigmaTy actual_ty
794 tau_tvs = exactTyVarsOfType tau
795 ; inst_tys <- if exp_ib then -- Inside a box, do not do clever stuff
796 do { tyvars' <- mapM tcInstBoxyTyVar tyvars
797 ; return (mkTyVarTys tyvars') }
798 else -- Outside, do clever stuff
799 preSubType tyvars tau_tvs tau expected_ty
800 ; let subst' = zipOpenTvSubst tyvars inst_tys
801 tau' = substTy subst' tau
803 -- Perform a full subsumption check
804 ; traceTc (text "tc_sub_spec" <+> vcat [ppr actual_ty,
805 ppr tyvars <+> ppr theta <+> ppr tau,
807 ; co_fn2 <- tc_sub orig tau' tau' exp_ib exp_sty expected_ty
809 -- Deal with the dictionaries
810 ; co_fn1 <- instCall orig inst_tys (substTheta subst' theta)
811 ; return (co_fn2 <.> co_fn1) }
813 -----------------------------------
814 -- Function case (rule F1)
815 tc_sub1 orig act_sty (FunTy act_arg act_res) exp_ib exp_sty (FunTy exp_arg exp_res)
816 = do { traceTc (text "tc_sub1 - case 4")
817 ; tc_sub_funs orig act_arg act_res exp_ib exp_arg exp_res
820 -- Function case (rule F2)
821 tc_sub1 orig act_sty act_ty@(FunTy act_arg act_res) _ exp_sty (TyVarTy exp_tv)
823 = do { traceTc (text "tc_sub1 - case 5")
824 ; cts <- readMetaTyVar exp_tv
826 Indirect ty -> tc_sub orig act_sty act_ty True exp_sty ty
827 Flexi -> do { [arg_ty,res_ty] <- withMetaTvs exp_tv fun_kinds mk_res_ty
828 ; tc_sub_funs orig act_arg act_res True arg_ty res_ty } }
830 mk_res_ty [arg_ty', res_ty'] = mkFunTy arg_ty' res_ty'
831 mk_res_ty other = panic "TcUnify.mk_res_ty3"
832 fun_kinds = [argTypeKind, openTypeKind]
834 -- Everything else: defer to boxy matching
835 tc_sub1 orig act_sty actual_ty exp_ib exp_sty expected_ty@(TyVarTy exp_tv)
836 = do { traceTc (text "tc_sub1 - case 6a" <+> ppr [isBoxyTyVar exp_tv, isMetaTyVar exp_tv, isSkolemTyVar exp_tv, isExistentialTyVar exp_tv,isSigTyVar exp_tv] )
837 ; defer_to_boxy_matching orig act_sty actual_ty exp_ib exp_sty expected_ty
840 tc_sub1 orig act_sty actual_ty exp_ib exp_sty expected_ty
841 = do { traceTc (text "tc_sub1 - case 6")
842 ; defer_to_boxy_matching orig act_sty actual_ty exp_ib exp_sty expected_ty
845 -----------------------------------
846 defer_to_boxy_matching orig act_sty actual_ty exp_ib exp_sty expected_ty
847 = do { coi <- addSubCtxt orig act_sty exp_sty $
848 u_tys True False act_sty actual_ty exp_ib exp_sty expected_ty
849 ; return $ coiToHsWrapper coi }
851 -----------------------------------
852 tc_sub_funs orig act_arg act_res exp_ib exp_arg exp_res
853 = do { arg_coi <- addSubCtxt orig act_arg exp_arg $
854 uTysOuter False act_arg exp_ib exp_arg
855 ; co_fn_res <- tc_sub orig act_res act_res exp_ib exp_res exp_res
856 ; wrapper1 <- wrapFunResCoercion [exp_arg] co_fn_res
857 ; let wrapper2 = case arg_coi of
859 ACo co -> WpCo $ FunTy co act_res
860 ; return (wrapper1 <.> wrapper2) }
862 -----------------------------------
864 :: [TcType] -- Type of args
865 -> HsWrapper -- HsExpr a -> HsExpr b
866 -> TcM HsWrapper -- HsExpr (arg_tys -> a) -> HsExpr (arg_tys -> b)
867 wrapFunResCoercion arg_tys co_fn_res
868 | isIdHsWrapper co_fn_res
873 = do { arg_ids <- newSysLocalIds FSLIT("sub") arg_tys
874 ; return (mkWpLams arg_ids <.> co_fn_res <.> mkWpApps arg_ids) }
879 %************************************************************************
881 \subsection{Generalisation}
883 %************************************************************************
886 tcGen :: BoxySigmaType -- expected_ty
887 -> TcTyVarSet -- Extra tyvars that the universally
888 -- quantified tyvars of expected_ty
889 -- must not be unified
890 -> ([TcTyVar] -> BoxyRhoType -> TcM result)
891 -> TcM (HsWrapper, result)
892 -- The expression has type: spec_ty -> expected_ty
894 tcGen expected_ty extra_tvs thing_inside -- We expect expected_ty to be a forall-type
895 -- If not, the call is a no-op
896 = do { traceTc (text "tcGen")
897 -- We want the GenSkol info in the skolemised type variables to
898 -- mention the *instantiated* tyvar names, so that we get a
899 -- good error message "Rigid variable 'a' is bound by (forall a. a->a)"
900 -- Hence the tiresome but innocuous fixM
901 ; ((tvs', theta', rho'), skol_info) <- fixM (\ ~(_, skol_info) ->
902 do { (forall_tvs, theta, rho_ty) <- tcInstSkolType skol_info expected_ty
903 -- Get loation from monad, not from expected_ty
904 ; let skol_info = GenSkol forall_tvs (mkPhiTy theta rho_ty)
905 ; return ((forall_tvs, theta, rho_ty), skol_info) })
908 traceTc (text "tcGen" <+> vcat [
909 text "extra_tvs" <+> ppr extra_tvs,
910 text "expected_ty" <+> ppr expected_ty,
911 text "inst ty" <+> ppr tvs' <+> ppr theta'
913 text "free_tvs" <+> ppr free_tvs])
915 -- Type-check the arg and unify with poly type
916 ; (result, lie) <- getLIE (thing_inside tvs' rho')
918 -- Check that the "forall_tvs" havn't been constrained
919 -- The interesting bit here is that we must include the free variables
920 -- of the expected_ty. Here's an example:
921 -- runST (newVar True)
922 -- Here, if we don't make a check, we'll get a type (ST s (MutVar s Bool))
923 -- for (newVar True), with s fresh. Then we unify with the runST's arg type
924 -- forall s'. ST s' a. That unifies s' with s, and a with MutVar s Bool.
925 -- So now s' isn't unconstrained because it's linked to a.
926 -- Conclusion: include the free vars of the expected_ty in the
927 -- list of "free vars" for the signature check.
929 ; loc <- getInstLoc (SigOrigin skol_info)
930 ; dicts <- newDictBndrs loc theta' -- Includes equalities
931 ; inst_binds <- tcSimplifyCheck loc tvs' dicts lie
933 ; checkSigTyVarsWrt free_tvs tvs'
934 ; traceTc (text "tcGen:done")
937 -- The WpLet binds any Insts which came out of the simplification.
938 dict_vars = map instToVar dicts
939 co_fn = mkWpTyLams tvs' <.> mkWpLams dict_vars <.> WpLet inst_binds
940 ; return (co_fn, result) }
942 free_tvs = tyVarsOfType expected_ty `unionVarSet` extra_tvs
947 %************************************************************************
951 %************************************************************************
953 The exported functions are all defined as versions of some
954 non-exported generic functions.
957 boxyUnify :: BoxyType -> BoxyType -> TcM CoercionI
958 -- Acutal and expected, respectively
960 = addErrCtxtM (unifyCtxt ty1 ty2) $
961 uTysOuter False ty1 False ty2
964 boxyUnifyList :: [BoxyType] -> [BoxyType] -> TcM [CoercionI]
965 -- Arguments should have equal length
966 -- Acutal and expected types
967 boxyUnifyList tys1 tys2 = uList boxyUnify tys1 tys2
970 unifyType :: TcTauType -> TcTauType -> TcM CoercionI
971 -- No boxes expected inside these types
972 -- Acutal and expected types
973 unifyType ty1 ty2 -- ty1 expected, ty2 inferred
974 = ASSERT2( not (isBoxyTy ty1), ppr ty1 )
975 ASSERT2( not (isBoxyTy ty2), ppr ty2 )
976 addErrCtxtM (unifyCtxt ty1 ty2) $
977 uTysOuter True ty1 True ty2
980 unifyPred :: PredType -> PredType -> TcM CoercionI
981 -- Acutal and expected types
982 unifyPred p1 p2 = addErrCtxtM (unifyCtxt (mkPredTy p1) (mkPredTy p2)) $
983 uPred True True p1 True p2
985 unifyTheta :: TcThetaType -> TcThetaType -> TcM [CoercionI]
986 -- Acutal and expected types
987 unifyTheta theta1 theta2
988 = do { checkTc (equalLength theta1 theta2)
989 (vcat [ptext SLIT("Contexts differ in length"),
990 nest 2 $ parens $ ptext SLIT("Use -fglasgow-exts to allow this")])
991 ; uList unifyPred theta1 theta2
995 uList :: (a -> a -> TcM b)
996 -> [a] -> [a] -> TcM [b]
997 -- Unify corresponding elements of two lists of types, which
998 -- should be of equal length. We charge down the list explicitly so that
999 -- we can complain if their lengths differ.
1000 uList unify [] [] = return []
1001 uList unify (ty1:tys1) (ty2:tys2) = do { x <- unify ty1 ty2;
1002 ; xs <- uList unify tys1 tys2
1005 uList unify ty1s ty2s = panic "Unify.uList: mismatched type lists!"
1008 @unifyTypeList@ takes a single list of @TauType@s and unifies them
1009 all together. It is used, for example, when typechecking explicit
1010 lists, when all the elts should be of the same type.
1013 unifyTypeList :: [TcTauType] -> TcM ()
1014 unifyTypeList [] = return ()
1015 unifyTypeList [ty] = return ()
1016 unifyTypeList (ty1:tys@(ty2:_)) = do { unifyType ty1 ty2
1017 ; unifyTypeList tys }
1020 %************************************************************************
1022 \subsection[Unify-uTys]{@uTys@: getting down to business}
1024 %************************************************************************
1026 @uTys@ is the heart of the unifier. Each arg occurs twice, because
1027 we want to report errors in terms of synomyms if possible. The first of
1028 the pair is used in error messages only; it is always the same as the
1029 second, except that if the first is a synonym then the second may be a
1030 de-synonym'd version. This way we get better error messages.
1032 We call the first one \tr{ps_ty1}, \tr{ps_ty2} for ``possible synomym''.
1035 type SwapFlag = Bool
1036 -- False <=> the two args are (actual, expected) respectively
1037 -- True <=> the two args are (expected, actual) respectively
1039 type InBox = Bool -- True <=> we are inside a box
1040 -- False <=> we are outside a box
1041 -- The importance of this is that if we get "filled-box meets
1042 -- filled-box", we'll look into the boxes and unify... but
1043 -- we must not allow polytypes. But if we are in a box on
1044 -- just one side, then we can allow polytypes
1046 type Outer = Bool -- True <=> this is the outer level of a unification
1047 -- so that the types being unified are the
1048 -- very ones we began with, not some sub
1049 -- component or synonym expansion
1050 -- The idea is that if Outer is true then unifyMisMatch should
1051 -- pop the context to remove the "Expected/Acutal" context
1054 :: InBox -> TcType -- ty1 is the *actual* type
1055 -> InBox -> TcType -- ty2 is the *expected* type
1057 uTysOuter nb1 ty1 nb2 ty2
1058 = do { traceTc (text "uTysOuter" <+> ppr ty1 <+> ppr ty2)
1059 ; u_tys True nb1 ty1 ty1 nb2 ty2 ty2 }
1060 uTys nb1 ty1 nb2 ty2
1061 = do { traceTc (text "uTys" <+> ppr ty1 <+> ppr ty2)
1062 ; u_tys False nb1 ty1 ty1 nb2 ty2 ty2 }
1066 uTys_s :: InBox -> [TcType] -- tys1 are the *actual* types
1067 -> InBox -> [TcType] -- tys2 are the *expected* types
1069 uTys_s nb1 [] nb2 [] = return []
1070 uTys_s nb1 (ty1:tys1) nb2 (ty2:tys2) = do { coi <- uTys nb1 ty1 nb2 ty2
1071 ; cois <- uTys_s nb1 tys1 nb2 tys2
1074 uTys_s nb1 ty1s nb2 ty2s = panic "Unify.uTys_s: mismatched type lists!"
1078 -> InBox -> TcType -> TcType -- ty1 is the *actual* type
1079 -> InBox -> TcType -> TcType -- ty2 is the *expected* type
1082 u_tys outer nb1 orig_ty1 ty1 nb2 orig_ty2 ty2
1083 = do { traceTc (text "u_tys " <+> ppr ty1 <+> text " " <+> ppr ty2)
1084 ; coi <- go outer ty1 ty2
1085 ; traceTc (case coi of
1086 ACo co -> text "u_tys yields coercion: " <+> ppr co
1087 IdCo -> text "u_tys yields no coercion")
1092 go :: Outer -> TcType -> TcType -> TcM CoercionI
1094 do { traceTc (text "go " <+> ppr orig_ty1 <+> text "/" <+> ppr ty1
1095 <+> ppr orig_ty2 <+> text "/" <+> ppr ty2)
1099 go1 :: Outer -> TcType -> TcType -> TcM CoercionI
1100 -- Always expand synonyms: see Note [Unification and synonyms]
1101 -- (this also throws away FTVs)
1103 | Just ty1' <- tcView ty1 = go False ty1' ty2
1104 | Just ty2' <- tcView ty2 = go False ty1 ty2'
1106 -- Variables; go for uVar
1107 go1 outer (TyVarTy tyvar1) ty2 = uVar outer False tyvar1 nb2 orig_ty2 ty2
1108 go1 outer ty1 (TyVarTy tyvar2) = uVar outer True tyvar2 nb1 orig_ty1 ty1
1109 -- "True" means args swapped
1111 -- The case for sigma-types must *follow* the variable cases
1112 -- because a boxy variable can be filed with a polytype;
1113 -- but must precede FunTy, because ((?x::Int) => ty) look
1114 -- like a FunTy; there isn't necy a forall at the top
1116 | isSigmaTy ty1 || isSigmaTy ty2
1117 = do { traceTc (text "We have sigma types: equalLength" <+> ppr tvs1 <+> ppr tvs2)
1118 ; unless (equalLength tvs1 tvs2)
1119 (unifyMisMatch outer False orig_ty1 orig_ty2)
1120 ; traceTc (text "We're past the first length test")
1121 ; tvs <- tcInstSkolTyVars UnkSkol tvs1 -- Not a helpful SkolemInfo
1122 -- Get location from monad, not from tvs1
1123 ; let tys = mkTyVarTys tvs
1124 in_scope = mkInScopeSet (mkVarSet tvs)
1125 phi1 = substTy (mkTvSubst in_scope (zipTyEnv tvs1 tys)) body1
1126 phi2 = substTy (mkTvSubst in_scope (zipTyEnv tvs2 tys)) body2
1127 (theta1,tau1) = tcSplitPhiTy phi1
1128 (theta2,tau2) = tcSplitPhiTy phi2
1130 ; addErrCtxtM (unifyForAllCtxt tvs phi1 phi2) $ do
1131 { unless (equalLength theta1 theta2)
1132 (unifyMisMatch outer False orig_ty1 orig_ty2)
1134 ; cois <- uPreds False nb1 theta1 nb2 theta2 -- TOMDO: do something with these pred_cois
1135 ; traceTc (text "TOMDO!")
1136 ; coi <- uTys nb1 tau1 nb2 tau2
1138 -- Check for escape; e.g. (forall a. a->b) ~ (forall a. a->a)
1139 ; free_tvs <- zonkTcTyVarsAndFV (varSetElems (tyVarsOfType ty1 `unionVarSet` tyVarsOfType ty2))
1140 ; when (any (`elemVarSet` free_tvs) tvs)
1141 (bleatEscapedTvs free_tvs tvs tvs)
1143 -- If both sides are inside a box, we are in a "box-meets-box"
1144 -- situation, and we should not have a polytype at all.
1145 -- If we get here we have two boxes, already filled with
1146 -- the same polytype... but it should be a monotype.
1147 -- This check comes last, because the error message is
1148 -- extremely unhelpful.
1149 ; when (nb1 && nb2) (notMonoType ty1)
1153 (tvs1, body1) = tcSplitForAllTys ty1
1154 (tvs2, body2) = tcSplitForAllTys ty2
1157 go1 outer (PredTy p1) (PredTy p2)
1158 = uPred False nb1 p1 nb2 p2
1160 -- Type constructors must match
1161 go1 _ (TyConApp con1 tys1) (TyConApp con2 tys2)
1162 | con1 == con2 && not (isOpenSynTyCon con1)
1163 = do { cois <- uTys_s nb1 tys1 nb2 tys2
1164 ; return $ mkTyConAppCoI con1 tys1 cois
1166 -- See Note [TyCon app]
1167 | con1 == con2 && identicalOpenSynTyConApp
1168 = do { cois <- uTys_s nb1 tys1' nb2 tys2'
1169 ; return $ mkTyConAppCoI con1 tys1 (replicate n IdCo ++ cois)
1173 (idxTys1, tys1') = splitAt n tys1
1174 (idxTys2, tys2') = splitAt n tys2
1175 identicalOpenSynTyConApp = idxTys1 `tcEqTypes` idxTys2
1176 -- See Note [OpenSynTyCon app]
1178 -- Functions; just check the two parts
1179 go1 _ (FunTy fun1 arg1) (FunTy fun2 arg2)
1180 = do { coi_l <- uTys nb1 fun1 nb2 fun2
1181 ; coi_r <- uTys nb1 arg1 nb2 arg2
1182 ; return $ mkFunTyCoI fun1 coi_l arg1 coi_r
1185 -- Applications need a bit of care!
1186 -- They can match FunTy and TyConApp, so use splitAppTy_maybe
1187 -- NB: we've already dealt with type variables and Notes,
1188 -- so if one type is an App the other one jolly well better be too
1189 go1 outer (AppTy s1 t1) ty2
1190 | Just (s2,t2) <- tcSplitAppTy_maybe ty2
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 -- Now the same, but the other way round
1195 -- Don't swap the types, because the error messages get worse
1196 go1 outer ty1 (AppTy s2 t2)
1197 | Just (s1,t1) <- tcSplitAppTy_maybe ty1
1198 = do { coi_s <- uTys nb1 s1 nb2 s2; coi_t <- uTys nb1 t1 nb2 t2
1199 ; return $ mkAppTyCoI s1 coi_s t1 coi_t }
1201 -- One or both outermost constructors are type family applications.
1202 -- If we can normalise them away, proceed as usual; otherwise, we
1203 -- need to defer unification by generating a wanted equality constraint.
1205 | ty1_is_fun || ty2_is_fun
1206 = do { (coi1, ty1') <- if ty1_is_fun then tcNormaliseFamInst ty1
1207 else return (IdCo, ty1)
1208 ; (coi2, ty2') <- if ty2_is_fun then tcNormaliseFamInst ty2
1209 else return (IdCo, ty2)
1210 ; coi <- if isOpenSynTyConApp ty1' || isOpenSynTyConApp ty2'
1211 then do { -- One type family app can't be reduced yet
1213 ; ty1'' <- zonkTcType ty1'
1214 ; ty2'' <- zonkTcType ty2'
1215 ; if tcEqType ty1'' ty2''
1217 else -- see [Deferred Unification]
1218 defer_unification outer False orig_ty1 orig_ty2
1220 else -- unification can proceed
1222 ; return $ coi1 `mkTransCoI` coi `mkTransCoI` (mkSymCoI coi2)
1225 ty1_is_fun = isOpenSynTyConApp ty1
1226 ty2_is_fun = isOpenSynTyConApp ty2
1228 -- Anything else fails
1229 go1 outer _ _ = unifyMisMatch outer False orig_ty1 orig_ty2
1233 uPred outer nb1 (IParam n1 t1) nb2 (IParam n2 t2)
1235 do { coi <- uTys nb1 t1 nb2 t2
1236 ; return $ mkIParamPredCoI n1 coi
1238 uPred outer nb1 (ClassP c1 tys1) nb2 (ClassP c2 tys2)
1240 do { cois <- uTys_s nb1 tys1 nb2 tys2 -- Guaranteed equal lengths because the kinds check
1241 ; return $ mkClassPPredCoI c1 tys1 cois
1243 uPred outer _ p1 _ p2 = unifyMisMatch outer False (mkPredTy p1) (mkPredTy p2)
1245 uPreds outer nb1 [] nb2 [] = return []
1246 uPreds outer nb1 (p1:ps1) nb2 (p2:ps2) =
1247 do { coi <- uPred outer nb1 p1 nb2 p2
1248 ; cois <- uPreds outer nb1 ps1 nb2 ps2
1251 uPreds outer nb1 ps1 nb2 ps2 = panic "uPreds"
1256 When we find two TyConApps, the argument lists are guaranteed equal
1257 length. Reason: intially the kinds of the two types to be unified is
1258 the same. The only way it can become not the same is when unifying two
1259 AppTys (f1 a1):=:(f2 a2). In that case there can't be a TyConApp in
1260 the f1,f2 (because it'd absorb the app). If we unify f1:=:f2 first,
1261 which we do, that ensures that f1,f2 have the same kind; and that
1262 means a1,a2 have the same kind. And now the argument repeats.
1264 Note [OpenSynTyCon app]
1265 ~~~~~~~~~~~~~~~~~~~~~~~
1268 type family T a :: * -> *
1270 the two types (T () a) and (T () Int) must unify, even if there are
1271 no type instances for T at all. Should we just turn them into an
1272 equality (T () a ~ T () Int)? I don't think so. We currently try to
1273 eagerly unify everything we can before generating equalities; otherwise,
1274 we could turn the unification of [Int] with [a] into an equality, too.
1276 Note [Unification and synonyms]
1277 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1278 If you are tempted to make a short cut on synonyms, as in this
1282 -- NO uTys (SynTy con1 args1 ty1) (SynTy con2 args2 ty2)
1283 -- NO = if (con1 == con2) then
1284 -- NO -- Good news! Same synonym constructors, so we can shortcut
1285 -- NO -- by unifying their arguments and ignoring their expansions.
1286 -- NO unifyTypepeLists args1 args2
1288 -- NO -- Never mind. Just expand them and try again
1292 then THINK AGAIN. Here is the whole story, as detected and reported
1293 by Chris Okasaki \tr{<Chris_Okasaki@loch.mess.cs.cmu.edu>}:
1295 Here's a test program that should detect the problem:
1299 x = (1 :: Bogus Char) :: Bogus Bool
1302 The problem with [the attempted shortcut code] is that
1306 is not a sufficient condition to be able to use the shortcut!
1307 You also need to know that the type synonym actually USES all
1308 its arguments. For example, consider the following type synonym
1309 which does not use all its arguments.
1314 If you ever tried unifying, say, \tr{Bogus Char} with \tr{Bogus Bool},
1315 the unifier would blithely try to unify \tr{Char} with \tr{Bool} and
1316 would fail, even though the expanded forms (both \tr{Int}) should
1319 Similarly, unifying \tr{Bogus Char} with \tr{Bogus t} would
1320 unnecessarily bind \tr{t} to \tr{Char}.
1322 ... You could explicitly test for the problem synonyms and mark them
1323 somehow as needing expansion, perhaps also issuing a warning to the
1328 %************************************************************************
1330 \subsection[Unify-uVar]{@uVar@: unifying with a type variable}
1332 %************************************************************************
1334 @uVar@ is called when at least one of the types being unified is a
1335 variable. It does {\em not} assume that the variable is a fixed point
1336 of the substitution; rather, notice that @uVar@ (defined below) nips
1337 back into @uTys@ if it turns out that the variable is already bound.
1341 -> SwapFlag -- False => tyvar is the "actual" (ty is "expected")
1342 -- True => ty is the "actual" (tyvar is "expected")
1344 -> InBox -- True <=> definitely no boxes in t2
1345 -> TcTauType -> TcTauType -- printing and real versions
1348 uVar outer swapped tv1 nb2 ps_ty2 ty2
1349 = do { let expansion | showSDoc (ppr ty2) == showSDoc (ppr ps_ty2) = empty
1350 | otherwise = brackets (equals <+> ppr ty2)
1351 ; traceTc (text "uVar" <+> ppr swapped <+>
1352 sep [ppr tv1 <+> dcolon <+> ppr (tyVarKind tv1 ),
1353 nest 2 (ptext SLIT(" <-> ")),
1354 ppr ps_ty2 <+> dcolon <+> ppr (typeKind ty2) <+> expansion])
1355 ; details <- lookupTcTyVar tv1
1358 | swapped -> u_tys outer nb2 ps_ty2 ty2 True ty1 ty1 -- Swap back
1359 | otherwise -> u_tys outer True ty1 ty1 nb2 ps_ty2 ty2 -- Same order
1360 -- The 'True' here says that ty1 is now inside a box
1361 DoneTv details1 -> uUnfilledVar outer swapped tv1 details1 ps_ty2 ty2
1365 uUnfilledVar :: Outer
1367 -> TcTyVar -> TcTyVarDetails -- Tyvar 1
1368 -> TcTauType -> TcTauType -- Type 2
1370 -- Invariant: tyvar 1 is not unified with anything
1372 uUnfilledVar outer swapped tv1 details1 ps_ty2 ty2
1373 | Just ty2' <- tcView ty2
1374 = -- Expand synonyms; ignore FTVs
1375 uUnfilledVar False swapped tv1 details1 ps_ty2 ty2'
1377 uUnfilledVar outer swapped tv1 details1 ps_ty2 (TyVarTy tv2)
1378 | tv1 == tv2 -- Same type variable => no-op (but watch out for the boxy case)
1380 MetaTv BoxTv ref1 -- A boxy type variable meets itself;
1381 -- this is box-meets-box, so fill in with a tau-type
1382 -> do { tau_tv <- tcInstTyVar tv1
1383 ; updateMeta tv1 ref1 (mkTyVarTy tau_tv)
1386 other -> return IdCo -- No-op
1388 | otherwise -- Distinct type variables
1389 = do { lookup2 <- lookupTcTyVar tv2
1391 IndirectTv ty2' -> uUnfilledVar outer swapped tv1 details1 ty2' ty2'
1392 DoneTv details2 -> uUnfilledVars outer swapped tv1 details1 tv2 details2
1395 uUnfilledVar outer swapped tv1 details1 ps_ty2 non_var_ty2
1396 = -- ty2 is not a type variable
1398 MetaTv (SigTv _) _ -> rigid_variable
1400 uMetaVar outer swapped tv1 info ref1 ps_ty2 non_var_ty2
1401 SkolemTv _ -> rigid_variable
1404 | isOpenSynTyConApp non_var_ty2
1405 = -- 'non_var_ty2's outermost constructor is a type family,
1406 -- which we may may be able to normalise
1407 do { (coi2, ty2') <- tcNormaliseFamInst non_var_ty2
1409 IdCo -> -- no progress, but maybe after other instantiations
1410 defer_unification outer swapped (TyVarTy tv1) ps_ty2
1411 ACo co -> -- progress: so lets try again
1413 ppr co <+> text "::"<+> ppr non_var_ty2 <+> text "~" <+>
1415 ; coi <- uUnfilledVar outer swapped tv1 details1 ps_ty2 ty2'
1416 ; let coi2' = (if swapped then id else mkSymCoI) coi2
1417 ; return $ coi2' `mkTransCoI` coi
1420 | SkolemTv RuntimeUnkSkol <- details1
1421 -- runtime unknown will never match
1422 = unifyMisMatch outer swapped (TyVarTy tv1) ps_ty2
1423 | otherwise -- defer as a given equality may still resolve this
1424 = defer_unification outer swapped (TyVarTy tv1) ps_ty2
1427 Note [Deferred Unification]
1428 ~~~~~~~~~~~~~~~~~~~~
1429 We may encounter a unification ty1 = ty2 that cannot be performed syntactically,
1430 and yet its consistency is undetermined. Previously, there was no way to still
1431 make it consistent. So a mismatch error was issued.
1433 Now these unfications are deferred until constraint simplification, where type
1434 family instances and given equations may (or may not) establish the consistency.
1435 Deferred unifications are of the form
1438 where F is a type function and x is a type variable.
1440 id :: x ~ y => x -> y
1443 involves the unfication x = y. It is deferred until we bring into account the
1444 context x ~ y to establish that it holds.
1446 If available, we defer original types (rather than those where closed type
1447 synonyms have already been expanded via tcCoreView). This is, as usual, to
1448 improve error messages.
1450 We need to both 'unBox' and zonk deferred types. We need to unBox as
1451 functions, such as TcExpr.tcMonoExpr promise to fill boxes in the expected
1452 type. We need to zonk as the types go into the kind of the coercion variable
1453 `cotv' and those are not zonked in Inst.zonkInst. (Maybe it would be better
1454 to zonk in zonInst instead. Would that be sufficient?)
1457 defer_unification :: Bool -- pop innermost context?
1462 defer_unification outer True ty1 ty2
1463 = defer_unification outer False ty2 ty1
1464 defer_unification outer False ty1 ty2
1465 = do { ty1' <- unBox ty1 >>= zonkTcType -- unbox *and* zonk..
1466 ; ty2' <- unBox ty2 >>= zonkTcType -- ..see preceding note
1467 ; traceTc $ text "deferring:" <+> ppr ty1 <+> text "~" <+> ppr ty2
1468 ; cotv <- newMetaCoVar ty1' ty2'
1469 -- put ty1 ~ ty2 in LIE
1470 -- Left means "wanted"
1471 ; inst <- (if outer then popErrCtxt else id) $
1472 mkEqInst (EqPred ty1' ty2') (Left cotv)
1474 ; return $ ACo $ TyVarTy cotv }
1477 uMetaVar :: Bool -- pop innermost context?
1479 -> TcTyVar -> BoxInfo -> IORef MetaDetails
1482 -- tv1 is an un-filled-in meta type variable (maybe boxy, maybe tau)
1483 -- ty2 is not a type variable
1485 uMetaVar outer swapped tv1 BoxTv ref1 ps_ty2 non_var_ty2
1486 = -- tv1 is a BoxTv. So we must unbox ty2, to ensure
1487 -- that any boxes in ty2 are filled with monotypes
1489 -- It should not be the case that tv1 occurs in ty2
1490 -- (i.e. no occurs check should be needed), but if perchance
1491 -- it does, the unbox operation will fill it, and the debug code
1493 do { final_ty <- unBox ps_ty2
1494 ; when debugIsOn $ do
1495 { meta_details <- readMutVar ref1
1496 ; case meta_details of
1497 Indirect ty -> WARN( True, ppr tv1 <+> ppr ty )
1498 return () -- This really should *not* happen
1501 ; checkUpdateMeta swapped tv1 ref1 final_ty
1505 uMetaVar outer swapped tv1 info1 ref1 ps_ty2 non_var_ty2
1506 = do { -- Occurs check + monotype check
1507 ; mb_final_ty <- checkTauTvUpdate tv1 ps_ty2
1508 ; case mb_final_ty of
1509 Nothing -> -- tv1 occured in type family parameter
1510 defer_unification outer swapped (mkTyVarTy tv1) ps_ty2
1512 do { checkUpdateMeta swapped tv1 ref1 final_ty
1518 uUnfilledVars :: Outer
1520 -> TcTyVar -> TcTyVarDetails -- Tyvar 1
1521 -> TcTyVar -> TcTyVarDetails -- Tyvar 2
1523 -- Invarant: The type variables are distinct,
1524 -- Neither is filled in yet
1525 -- They might be boxy or not
1527 uUnfilledVars outer swapped tv1 (SkolemTv _) tv2 (SkolemTv _)
1528 = -- see [Deferred Unification]
1529 defer_unification outer swapped (mkTyVarTy tv1) (mkTyVarTy tv2)
1531 uUnfilledVars outer swapped tv1 (MetaTv info1 ref1) tv2 (SkolemTv _)
1532 = checkUpdateMeta swapped tv1 ref1 (mkTyVarTy tv2) >> return IdCo
1533 uUnfilledVars outer swapped tv1 (SkolemTv _) tv2 (MetaTv info2 ref2)
1534 = checkUpdateMeta (not swapped) tv2 ref2 (mkTyVarTy tv1) >> return IdCo
1536 -- ToDo: this function seems too long for what it acutally does!
1537 uUnfilledVars outer swapped tv1 (MetaTv info1 ref1) tv2 (MetaTv info2 ref2)
1538 = case (info1, info2) of
1539 (BoxTv, BoxTv) -> box_meets_box >> return IdCo
1541 -- If a box meets a TauTv, but the fomer has the smaller kind
1542 -- then we must create a fresh TauTv with the smaller kind
1543 (_, BoxTv) | k1_sub_k2 -> update_tv2 >> return IdCo
1544 | otherwise -> box_meets_box >> return IdCo
1545 (BoxTv, _ ) | k2_sub_k1 -> update_tv1 >> return IdCo
1546 | otherwise -> box_meets_box >> return IdCo
1548 -- Avoid SigTvs if poss
1549 (SigTv _, _ ) | k1_sub_k2 -> update_tv2 >> return IdCo
1550 (_, SigTv _) | k2_sub_k1 -> update_tv1 >> return IdCo
1552 (_, _) | k1_sub_k2 -> if k2_sub_k1 && nicer_to_update_tv1
1553 then update_tv1 >> return IdCo -- Same kinds
1554 else update_tv2 >> return IdCo
1555 | k2_sub_k1 -> update_tv1 >> return IdCo
1556 | otherwise -> kind_err >> return IdCo
1558 -- Update the variable with least kind info
1559 -- See notes on type inference in Kind.lhs
1560 -- The "nicer to" part only applies if the two kinds are the same,
1561 -- so we can choose which to do.
1563 -- Kinds should be guaranteed ok at this point
1564 update_tv1 = updateMeta tv1 ref1 (mkTyVarTy tv2)
1565 update_tv2 = updateMeta tv2 ref2 (mkTyVarTy tv1)
1567 box_meets_box | k1_sub_k2 = if k2_sub_k1 && nicer_to_update_tv1
1570 | k2_sub_k1 = fill_from tv2
1571 | otherwise = kind_err
1573 -- Update *both* tyvars with a TauTv whose name and kind
1574 -- are gotten from tv (avoid losing nice names is poss)
1575 fill_from tv = do { tv' <- tcInstTyVar tv
1576 ; let tau_ty = mkTyVarTy tv'
1577 ; updateMeta tv1 ref1 tau_ty
1578 ; updateMeta tv2 ref2 tau_ty }
1580 kind_err = addErrCtxtM (unifyKindCtxt swapped tv1 (mkTyVarTy tv2)) $
1581 unifyKindMisMatch k1 k2
1585 k1_sub_k2 = k1 `isSubKind` k2
1586 k2_sub_k1 = k2 `isSubKind` k1
1588 nicer_to_update_tv1 = isSystemName (Var.varName tv1)
1589 -- Try to update sys-y type variables in preference to ones
1590 -- gotten (say) by instantiating a polymorphic function with
1591 -- a user-written type sig
1595 refineBox :: TcType -> TcM TcType
1596 -- Unbox the outer box of a boxy type (if any)
1597 refineBox ty@(TyVarTy box_tv)
1598 | isMetaTyVar box_tv
1599 = do { cts <- readMetaTyVar box_tv
1602 Indirect ty -> return ty }
1603 refineBox other_ty = return other_ty
1605 refineBoxToTau :: TcType -> TcM TcType
1606 -- Unbox the outer box of a boxy type, filling with a monotype if it is empty
1607 -- Like refineBox except for the "fill with monotype" part.
1608 refineBoxToTau ty@(TyVarTy box_tv)
1609 | isMetaTyVar box_tv
1610 , MetaTv BoxTv ref <- tcTyVarDetails box_tv
1611 = do { cts <- readMutVar ref
1613 Flexi -> fillBoxWithTau box_tv ref
1614 Indirect ty -> return ty }
1615 refineBoxToTau other_ty = return other_ty
1617 zapToMonotype :: BoxySigmaType -> TcM TcTauType
1618 -- Subtle... we must zap the boxy res_ty
1619 -- to kind * before using it to instantiate a LitInst
1620 -- Calling unBox instead doesn't do the job, because the box
1621 -- often has an openTypeKind, and we don't want to instantiate
1623 zapToMonotype res_ty
1624 = do { res_tau <- newFlexiTyVarTy liftedTypeKind
1625 ; boxyUnify res_tau res_ty
1628 unBox :: BoxyType -> TcM TcType
1629 -- unBox implements the judgement
1631 -- with input s', and result s
1633 -- It removes all boxes from the input type, returning a non-boxy type.
1634 -- A filled box in the type can only contain a monotype; unBox fails if not
1635 -- The type can have empty boxes, which unBox fills with a monotype
1637 -- Compare this wth checkTauTvUpdate
1639 -- For once, it's safe to treat synonyms as opaque!
1641 unBox (TyConApp tc tys) = do { tys' <- mapM unBox tys; return (TyConApp tc tys') }
1642 unBox (AppTy f a) = do { f' <- unBox f; a' <- unBox a; return (mkAppTy f' a') }
1643 unBox (FunTy f a) = do { f' <- unBox f; a' <- unBox a; return (FunTy f' a') }
1644 unBox (PredTy p) = do { p' <- unBoxPred p; return (PredTy p') }
1645 unBox (ForAllTy tv ty) = ASSERT( isImmutableTyVar tv )
1646 do { ty' <- unBox ty; return (ForAllTy tv ty') }
1648 | isTcTyVar tv -- It's a boxy type variable
1649 , MetaTv BoxTv ref <- tcTyVarDetails tv -- NB: non-TcTyVars are possible
1650 = do { cts <- readMutVar ref -- under nested quantifiers
1652 Flexi -> fillBoxWithTau tv ref
1653 Indirect ty -> do { non_boxy_ty <- unBox ty
1654 ; if isTauTy non_boxy_ty
1655 then return non_boxy_ty
1656 else notMonoType non_boxy_ty }
1658 | otherwise -- Skolems, and meta-tau-variables
1659 = return (TyVarTy tv)
1661 unBoxPred (ClassP cls tys) = do { tys' <- mapM unBox tys; return (ClassP cls tys') }
1662 unBoxPred (IParam ip ty) = do { ty' <- unBox ty; return (IParam ip ty') }
1663 unBoxPred (EqPred ty1 ty2) = do { ty1' <- unBox ty1; ty2' <- unBox ty2; return (EqPred ty1' ty2') }
1668 %************************************************************************
1670 \subsection[Unify-context]{Errors and contexts}
1672 %************************************************************************
1678 unifyCtxt act_ty exp_ty tidy_env
1679 = do { act_ty' <- zonkTcType act_ty
1680 ; exp_ty' <- zonkTcType exp_ty
1681 ; let (env1, exp_ty'') = tidyOpenType tidy_env exp_ty'
1682 (env2, act_ty'') = tidyOpenType env1 act_ty'
1683 ; return (env2, mkExpectedActualMsg act_ty'' exp_ty'') }
1686 mkExpectedActualMsg act_ty exp_ty
1687 = nest 2 (vcat [ text "Expected type" <> colon <+> ppr exp_ty,
1688 text "Inferred type" <> colon <+> ppr act_ty ])
1691 -- If an error happens we try to figure out whether the function
1692 -- function has been given too many or too few arguments, and say so.
1693 addSubCtxt orig actual_res_ty expected_res_ty thing_inside
1694 = addErrCtxtM mk_err thing_inside
1697 = do { exp_ty' <- zonkTcType expected_res_ty
1698 ; act_ty' <- zonkTcType actual_res_ty
1699 ; let (env1, exp_ty'') = tidyOpenType tidy_env exp_ty'
1700 (env2, act_ty'') = tidyOpenType env1 act_ty'
1701 (exp_args, _) = tcSplitFunTys exp_ty''
1702 (act_args, _) = tcSplitFunTys act_ty''
1704 len_act_args = length act_args
1705 len_exp_args = length exp_args
1707 message = case orig of
1709 | len_exp_args < len_act_args -> wrongArgsCtxt "too few" fun
1710 | len_exp_args > len_act_args -> wrongArgsCtxt "too many" fun
1711 other -> mkExpectedActualMsg act_ty'' exp_ty''
1712 ; return (env2, message) }
1714 wrongArgsCtxt too_many_or_few fun
1715 = ptext SLIT("Probable cause:") <+> quotes (ppr fun)
1716 <+> ptext SLIT("is applied to") <+> text too_many_or_few
1717 <+> ptext SLIT("arguments")
1720 unifyForAllCtxt tvs phi1 phi2 env
1721 = return (env2, msg)
1723 (env', tvs') = tidyOpenTyVars env tvs -- NB: not tidyTyVarBndrs
1724 (env1, phi1') = tidyOpenType env' phi1
1725 (env2, phi2') = tidyOpenType env1 phi2
1726 msg = vcat [ptext SLIT("When matching") <+> quotes (ppr (mkForAllTys tvs' phi1')),
1727 ptext SLIT(" and") <+> quotes (ppr (mkForAllTys tvs' phi2'))]
1729 -----------------------
1730 unifyMisMatch outer swapped ty1 ty2
1731 | swapped = unifyMisMatch outer False ty2 ty1
1732 | outer = popErrCtxt $ unifyMisMatch False swapped ty1 ty2 -- This is the whole point of the 'outer' stuff
1733 | otherwise = failWithMisMatch ty1 ty2
1737 %************************************************************************
1741 %************************************************************************
1743 Unifying kinds is much, much simpler than unifying types.
1746 unifyKind :: TcKind -- Expected
1749 unifyKind (TyConApp kc1 []) (TyConApp kc2 [])
1750 | isSubKindCon kc2 kc1 = return ()
1752 unifyKind (FunTy a1 r1) (FunTy a2 r2)
1753 = do { unifyKind a2 a1; unifyKind r1 r2 }
1754 -- Notice the flip in the argument,
1755 -- so that the sub-kinding works right
1756 unifyKind (TyVarTy kv1) k2 = uKVar False kv1 k2
1757 unifyKind k1 (TyVarTy kv2) = uKVar True kv2 k1
1758 unifyKind k1 k2 = unifyKindMisMatch k1 k2
1760 unifyKinds :: [TcKind] -> [TcKind] -> TcM ()
1761 unifyKinds [] [] = return ()
1762 unifyKinds (k1:ks1) (k2:ks2) = do unifyKind k1 k2
1764 unifyKinds _ _ = panic "unifyKinds: length mis-match"
1767 uKVar :: Bool -> KindVar -> TcKind -> TcM ()
1768 uKVar swapped kv1 k2
1769 = do { mb_k1 <- readKindVar kv1
1771 Flexi -> uUnboundKVar swapped kv1 k2
1772 Indirect k1 | swapped -> unifyKind k2 k1
1773 | otherwise -> unifyKind k1 k2 }
1776 uUnboundKVar :: Bool -> KindVar -> TcKind -> TcM ()
1777 uUnboundKVar swapped kv1 k2@(TyVarTy kv2)
1778 | kv1 == kv2 = return ()
1779 | otherwise -- Distinct kind variables
1780 = do { mb_k2 <- readKindVar kv2
1782 Indirect k2 -> uUnboundKVar swapped kv1 k2
1783 Flexi -> writeKindVar kv1 k2 }
1785 uUnboundKVar swapped kv1 non_var_k2
1786 = do { k2' <- zonkTcKind non_var_k2
1787 ; kindOccurCheck kv1 k2'
1788 ; k2'' <- kindSimpleKind swapped k2'
1789 -- KindVars must be bound only to simple kinds
1790 -- Polarities: (kindSimpleKind True ?) succeeds
1791 -- returning *, corresponding to unifying
1794 ; writeKindVar kv1 k2'' }
1797 kindOccurCheck kv1 k2 -- k2 is zonked
1798 = checkTc (not_in k2) (kindOccurCheckErr kv1 k2)
1800 not_in (TyVarTy kv2) = kv1 /= kv2
1801 not_in (FunTy a2 r2) = not_in a2 && not_in r2
1804 kindSimpleKind :: Bool -> Kind -> TcM SimpleKind
1805 -- (kindSimpleKind True k) returns a simple kind sk such that sk <: k
1806 -- If the flag is False, it requires k <: sk
1807 -- E.g. kindSimpleKind False ?? = *
1808 -- What about (kv -> *) :=: ?? -> *
1809 kindSimpleKind orig_swapped orig_kind
1810 = go orig_swapped orig_kind
1812 go sw (FunTy k1 k2) = do { k1' <- go (not sw) k1
1814 ; return (mkArrowKind k1' k2') }
1816 | isOpenTypeKind k = return liftedTypeKind
1817 | isArgTypeKind k = return liftedTypeKind
1819 | isLiftedTypeKind k = return liftedTypeKind
1820 | isUnliftedTypeKind k = return unliftedTypeKind
1821 go sw k@(TyVarTy _) = return k -- KindVars are always simple
1822 go swapped kind = failWithTc (ptext SLIT("Unexpected kind unification failure:")
1823 <+> ppr orig_swapped <+> ppr orig_kind)
1824 -- I think this can't actually happen
1826 -- T v = MkT v v must be a type
1827 -- T v w = MkT (v -> w) v must not be an umboxed tuple
1830 kindOccurCheckErr tyvar ty
1831 = hang (ptext SLIT("Occurs check: cannot construct the infinite kind:"))
1832 2 (sep [ppr tyvar, char '=', ppr ty])
1836 unifyFunKind :: TcKind -> TcM (Maybe (TcKind, TcKind))
1837 -- Like unifyFunTy, but does not fail; instead just returns Nothing
1839 unifyFunKind (TyVarTy kvar) = do
1840 maybe_kind <- readKindVar kvar
1842 Indirect fun_kind -> unifyFunKind fun_kind
1844 do { arg_kind <- newKindVar
1845 ; res_kind <- newKindVar
1846 ; writeKindVar kvar (mkArrowKind arg_kind res_kind)
1847 ; return (Just (arg_kind,res_kind)) }
1849 unifyFunKind (FunTy arg_kind res_kind) = return (Just (arg_kind,res_kind))
1850 unifyFunKind other = return Nothing
1853 %************************************************************************
1857 %************************************************************************
1859 ---------------------------
1860 -- We would like to get a decent error message from
1861 -- (a) Under-applied type constructors
1862 -- f :: (Maybe, Maybe)
1863 -- (b) Over-applied type constructors
1864 -- f :: Int x -> Int x
1868 checkExpectedKind :: Outputable a => a -> TcKind -> TcKind -> TcM ()
1869 -- A fancy wrapper for 'unifyKind', which tries
1870 -- to give decent error messages.
1871 -- (checkExpectedKind ty act_kind exp_kind)
1872 -- checks that the actual kind act_kind is compatible
1873 -- with the expected kind exp_kind
1874 -- The first argument, ty, is used only in the error message generation
1875 checkExpectedKind ty act_kind exp_kind
1876 | act_kind `isSubKind` exp_kind -- Short cut for a very common case
1879 (_errs, mb_r) <- tryTc (unifyKind exp_kind act_kind)
1881 Just r -> return () ; -- Unification succeeded
1884 -- So there's definitely an error
1885 -- Now to find out what sort
1886 exp_kind <- zonkTcKind exp_kind
1887 act_kind <- zonkTcKind act_kind
1889 env0 <- tcInitTidyEnv
1890 let (exp_as, _) = splitKindFunTys exp_kind
1891 (act_as, _) = splitKindFunTys act_kind
1892 n_exp_as = length exp_as
1893 n_act_as = length act_as
1895 (env1, tidy_exp_kind) = tidyKind env0 exp_kind
1896 (env2, tidy_act_kind) = tidyKind env1 act_kind
1898 err | n_exp_as < n_act_as -- E.g. [Maybe]
1899 = quotes (ppr ty) <+> ptext SLIT("is not applied to enough type arguments")
1901 -- Now n_exp_as >= n_act_as. In the next two cases,
1902 -- n_exp_as == 0, and hence so is n_act_as
1903 | isLiftedTypeKind exp_kind && isUnliftedTypeKind act_kind
1904 = ptext SLIT("Expecting a lifted type, but") <+> quotes (ppr ty)
1905 <+> ptext SLIT("is unlifted")
1907 | isUnliftedTypeKind exp_kind && isLiftedTypeKind act_kind
1908 = ptext SLIT("Expecting an unlifted type, but") <+> quotes (ppr ty)
1909 <+> ptext SLIT("is lifted")
1911 | otherwise -- E.g. Monad [Int]
1912 = ptext SLIT("Kind mis-match")
1914 more_info = sep [ ptext SLIT("Expected kind") <+>
1915 quotes (pprKind tidy_exp_kind) <> comma,
1916 ptext SLIT("but") <+> quotes (ppr ty) <+>
1917 ptext SLIT("has kind") <+> quotes (pprKind tidy_act_kind)]
1919 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 ; when (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 ; return (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 = do
2033 actual_tau <- zonkTcType sig_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),