2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section{Type subsumption and unification}
8 -- Full-blown subsumption
10 checkSigTyVars, checkSigTyVarsWrt, bleatEscapedTvs, sigCtxt,
12 -- Various unifications
13 unifyType, unifyTypeList, unifyTheta,
14 unifyKind, unifyKinds, unifyFunKind,
16 boxySubMatchType, boxyMatchTypes,
18 --------------------------------
20 tcInfer, subFunTys, unBox, stripBoxyType, withBox,
21 boxyUnify, boxyUnifyList, zapToMonotype,
22 boxySplitListTy, boxySplitTyConApp, boxySplitAppTy,
26 #include "HsVersions.h"
28 import HsSyn ( ExprCoFn(..), idCoercion, isIdCoercion, (<.>) )
29 import TypeRep ( Type(..), PredType(..) )
31 import TcMType ( lookupTcTyVar, LookupTyVarResult(..),
32 tcInstSkolType, newKindVar, newMetaTyVar,
33 tcInstBoxy, newBoxyTyVar, readFilledBox,
34 readMetaTyVar, writeMetaTyVar, newFlexiTyVarTy,
36 zonkTcKind, zonkType, zonkTcType, zonkTcTyVarsAndFV,
37 readKindVar, writeKindVar )
38 import TcSimplify ( tcSimplifyCheck )
39 import TcEnv ( tcGetGlobalTyVars, findGlobals )
40 import TcIface ( checkWiredInTyCon )
41 import TcRnMonad -- TcType, amongst others
42 import TcType ( TcKind, TcType, TcTyVar, TcTauType,
43 BoxySigmaType, BoxyRhoType, BoxyType,
44 TcTyVarSet, TcThetaType, TcTyVarDetails(..), BoxInfo(..),
45 SkolemInfo( GenSkol, UnkSkol ), MetaDetails(..), isImmutableTyVar,
46 pprSkolTvBinding, isTauTy, isTauTyCon, isSigmaTy,
47 mkFunTy, mkFunTys, mkTyConApp, isMetaTyVar,
48 tcSplitForAllTys, tcSplitAppTy_maybe, mkTyVarTys,
49 tyVarsOfType, mkPhiTy, mkTyVarTy, mkPredTy,
50 typeKind, mkForAllTys, mkAppTy, isBoxyTyVar,
51 tidyOpenType, tidyOpenTypes, tidyOpenTyVar, tidyOpenTyVars,
52 pprType, tidyKind, tidySkolemTyVar, isSkolemTyVar, tcView,
53 TvSubst, mkTvSubst, zipTyEnv, substTy, emptyTvSubst,
54 lookupTyVar, extendTvSubst )
55 import Kind ( Kind(..), SimpleKind, KindVar, isArgTypeKind,
56 openTypeKind, liftedTypeKind, mkArrowKind, defaultKind,
57 isOpenTypeKind, argTypeKind, isLiftedTypeKind, isUnliftedTypeKind,
58 isSubKind, pprKind, splitKindFunTys )
59 import TysPrim ( alphaTy, betaTy )
60 import Inst ( newDicts, instToId )
61 import TyCon ( TyCon, tyConArity, tyConTyVars, isSynTyCon )
62 import TysWiredIn ( listTyCon )
63 import Id ( Id, mkSysLocal )
64 import Var ( Var, varName, tyVarKind, isTcTyVar, tcTyVarDetails )
65 import VarSet ( emptyVarSet, mkVarSet, unitVarSet, unionVarSet, elemVarSet, varSetElems,
66 extendVarSet, intersectsVarSet )
68 import Name ( isSystemName )
69 import ErrUtils ( Message )
70 import Maybes ( fromJust )
71 import BasicTypes ( Arity )
72 import UniqSupply ( uniqsFromSupply )
73 import Util ( notNull, equalLength )
78 import TcType ( isBoxyTy, isFlexi )
82 %************************************************************************
84 \subsection{'hole' type variables}
86 %************************************************************************
89 tcInfer :: (BoxyType -> TcM a) -> TcM (a, TcType)
91 = do { box <- newBoxyTyVar
92 ; res <- tc_infer (mkTyVarTy box)
93 ; res_ty <- readFilledBox box -- Guaranteed filled-in by now
94 ; return (res, res_ty) }
98 %************************************************************************
102 %************************************************************************
105 subFunTys :: SDoc -- Somthing like "The function f has 3 arguments"
106 -- or "The abstraction (\x.e) takes 1 argument"
107 -> Arity -- Expected # of args
108 -> BoxyRhoType -- res_ty
109 -> ([BoxySigmaType] -> BoxyRhoType -> TcM a)
111 -- Attempt to decompse res_ty to have enough top-level arrows to
112 -- match the number of patterns in the match group
114 -- If (subFunTys n_args res_ty thing_inside) = (co_fn, res)
115 -- and the inner call to thing_inside passes args: [a1,...,an], b
116 -- then co_fn :: (a1 -> ... -> an -> b) -> res_ty
118 -- Note that it takes a BoxyRho type, and guarantees to return a BoxyRhoType
121 {- Error messages from subFunTys
123 The abstraction `\Just 1 -> ...' has two arguments
124 but its type `Maybe a -> a' has only one
126 The equation(s) for `f' have two arguments
127 but its type `Maybe a -> a' has only one
129 The section `(f 3)' requires 'f' to take two arguments
130 but its type `Int -> Int' has only one
132 The function 'f' is applied to two arguments
133 but its type `Int -> Int' has only one
137 subFunTys error_herald n_pats res_ty thing_inside
138 = loop n_pats [] res_ty
140 -- In 'loop', the parameter 'arg_tys' accumulates
141 -- the arg types so far, in *reverse order*
142 loop n args_so_far res_ty
143 | Just res_ty' <- tcView res_ty = loop n args_so_far res_ty'
145 loop n args_so_far res_ty
146 | isSigmaTy res_ty -- Do this first, because we guarantee to return
147 -- a BoxyRhoType, not a BoxySigmaType
148 = do { (gen_fn, (co_fn, res)) <- tcGen res_ty emptyVarSet $ \ res_ty' ->
149 loop n args_so_far res_ty'
150 ; return (gen_fn <.> co_fn, res) }
152 loop 0 args_so_far res_ty = do { res <- thing_inside (reverse args_so_far) res_ty
153 ; return (idCoercion, res) }
154 loop n args_so_far (FunTy arg_ty res_ty)
155 = do { (co_fn, res) <- loop (n-1) (arg_ty:args_so_far) res_ty
156 ; co_fn' <- wrapFunResCoercion [arg_ty] co_fn
157 ; return (co_fn', res) }
159 loop n args_so_far (TyVarTy tv)
160 | not (isImmutableTyVar tv)
161 = do { cts <- readMetaTyVar tv
163 Indirect ty -> loop n args_so_far ty
164 Flexi -> do { (res_ty:arg_tys) <- withMetaTvs tv kinds mk_res_ty
165 ; res <- thing_inside (reverse args_so_far ++ arg_tys) res_ty
166 ; return (idCoercion, res) } }
168 mk_res_ty (res_ty' : arg_tys') = mkFunTys arg_tys' res_ty'
169 kinds = openTypeKind : take n (repeat argTypeKind)
170 -- Note argTypeKind: the args can have an unboxed type,
171 -- but not an unboxed tuple.
173 loop n args_so_far res_ty
174 = failWithTc (mk_msg (length args_so_far))
177 = error_herald <> comma $$
178 sep [ptext SLIT("but its type") <+> quotes (pprType res_ty),
179 if n_actual == 0 then ptext SLIT("has none")
180 else ptext SLIT("has only") <+> speakN n_actual]
184 ----------------------
185 boxySplitTyConApp :: TyCon -- T :: k1 -> ... -> kn -> *
186 -> BoxyRhoType -- Expected type (T a b c)
187 -> TcM [BoxySigmaType] -- Element types, a b c
188 -- It's used for wired-in tycons, so we call checkWiredInTyCOn
189 -- Precondition: never called with FunTyCon
190 -- Precondition: input type :: *
192 boxySplitTyConApp tc orig_ty
193 = do { checkWiredInTyCon tc
194 ; loop (tyConArity tc) [] orig_ty }
196 loop n_req args_so_far ty
197 | Just ty' <- tcView ty = loop n_req args_so_far ty'
199 loop n_req args_so_far (TyConApp tycon args)
201 = ASSERT( n_req == length args) -- ty::*
202 return (args ++ args_so_far)
204 loop n_req args_so_far (AppTy fun arg)
205 = loop (n_req - 1) (arg:args_so_far) fun
207 loop n_req args_so_far (TyVarTy tv)
208 | not (isImmutableTyVar tv)
209 = do { cts <- readMetaTyVar tv
211 Indirect ty -> loop n_req args_so_far ty
212 Flexi -> do { arg_tys <- withMetaTvs tv arg_kinds mk_res_ty
213 ; return (arg_tys ++ args_so_far) }
216 mk_res_ty arg_tys' = mkTyConApp tc arg_tys'
217 arg_kinds = map tyVarKind (take n_req (tyConTyVars tc))
219 loop _ _ _ = boxySplitFailure (mkTyConApp tc (mkTyVarTys (tyConTyVars tc))) orig_ty
221 ----------------------
222 boxySplitListTy :: BoxyRhoType -> TcM BoxySigmaType -- Special case for lists
223 boxySplitListTy exp_ty = do { [elt_ty] <- boxySplitTyConApp listTyCon exp_ty
227 ----------------------
228 boxySplitAppTy :: BoxyRhoType -- Type to split: m a
229 -> TcM (BoxySigmaType, BoxySigmaType) -- Returns m, a
230 -- Assumes (m: * -> k), where k is the kind of the incoming type
231 -- If the incoming type is boxy, then so are the result types; and vice versa
233 boxySplitAppTy orig_ty
237 | Just ty' <- tcView ty = loop ty'
240 | Just (fun_ty, arg_ty) <- tcSplitAppTy_maybe ty
241 = return (fun_ty, arg_ty)
244 | not (isImmutableTyVar tv)
245 = do { cts <- readMetaTyVar tv
247 Indirect ty -> loop ty
248 Flexi -> do { [fun_ty,arg_ty] <- withMetaTvs tv kinds mk_res_ty
249 ; return (fun_ty, arg_ty) } }
251 mk_res_ty [fun_ty', arg_ty'] = mkAppTy fun_ty' arg_ty'
252 tv_kind = tyVarKind tv
253 kinds = [mkArrowKind liftedTypeKind (defaultKind tv_kind),
255 liftedTypeKind] -- arg type :: *
256 -- The defaultKind is a bit smelly. If you remove it,
257 -- try compiling f x = do { x }
258 -- and you'll get a kind mis-match. It smells, but
259 -- not enough to lose sleep over.
261 loop _ = boxySplitFailure (mkAppTy alphaTy betaTy) orig_ty
264 boxySplitFailure actual_ty expected_ty
265 = unifyMisMatch False actual_ty expected_ty
269 --------------------------------
270 -- withBoxes: the key utility function
271 --------------------------------
274 withMetaTvs :: TcTyVar -- An unfilled-in, non-skolem, meta type variable
275 -> [Kind] -- Make fresh boxes (with the same BoxTv/TauTv setting as tv)
276 -> ([BoxySigmaType] -> BoxySigmaType)
277 -- Constructs the type to assign
278 -- to the original var
279 -> TcM [BoxySigmaType] -- Return the fresh boxes
281 -- It's entirely possible for the [kind] to be empty.
282 -- For example, when pattern-matching on True,
283 -- we call boxySplitTyConApp passing a boolTyCon
285 -- Invariant: tv is still Flexi
287 withMetaTvs tv kinds mk_res_ty
289 = do { box_tvs <- mapM (newMetaTyVar BoxTv) kinds
290 ; let box_tys = mkTyVarTys box_tvs
291 ; writeMetaTyVar tv (mk_res_ty box_tys)
294 | otherwise -- Non-boxy meta type variable
295 = do { tau_tys <- mapM newFlexiTyVarTy kinds
296 ; writeMetaTyVar tv (mk_res_ty tau_tys) -- Write it *first*
297 -- Sure to be a tau-type
300 withBox :: Kind -> (BoxySigmaType -> TcM a) -> TcM (a, TcType)
301 -- Allocate a *boxy* tyvar
302 withBox kind thing_inside
303 = do { box_tv <- newMetaTyVar BoxTv kind
304 ; res <- thing_inside (mkTyVarTy box_tv)
305 ; ty <- readFilledBox box_tv
310 %************************************************************************
312 Approximate boxy matching
314 %************************************************************************
318 :: TcTyVarSet -> TcType -- The "template"; the tyvars are skolems
319 -> BoxyRhoType -- Type to match (note a *Rho* type)
320 -> TvSubst -- Substitution of the [TcTyVar] to BoxySigmaTypes
323 :: TcTyVarSet -> [TcType] -- The "template"; the tyvars are skolems
324 -> [BoxySigmaType] -- Type to match
325 -> TvSubst -- Substitution of the [TcTyVar] to BoxySigmaTypes
327 -- Find a *boxy* substitution that makes the template look as much
328 -- like the BoxySigmaType as possible.
329 -- It's always ok to return an empty substitution;
330 -- anything more is jam on the pudding
332 -- NB1: This is a pure, non-monadic function.
333 -- It does no unification, and cannot fail
335 -- Note [Matching kinds]
336 -- The target type might legitimately not be a sub-kind of template.
337 -- For example, suppose the target is simply a box with an OpenTypeKind,
338 -- and the template is a type variable with LiftedTypeKind.
339 -- Then it's ok (because the target type will later be refined).
340 -- We simply don't bind the template type variable.
342 -- It might also be that the kind mis-match is an error. For example,
343 -- suppose we match the template (a -> Int) against (Int# -> Int),
344 -- where the template type variable 'a' has LiftedTypeKind. This
345 -- matching function does not fail; it simply doesn't bind the template.
346 -- Later stuff will fail.
348 -- Precondition: the arg lengths are equal
349 -- Precondition: none of the template type variables appear in the [BoxySigmaType]
350 -- Precondition: any nested quantifiers in either type differ from
351 -- the template type variables passed as arguments
357 -- |- head xs : <rhobox>
358 -- We will do a boxySubMatchType between a ~ <rhobox>
359 -- But we *don't* want to match [a |-> <rhobox>] because
360 -- (a) The box should be filled in with a rho-type, but
361 -- but the returned substitution maps TyVars to boxy *sigma*
363 -- (b) In any case, the right final answer might be *either*
364 -- instantiate 'a' with a rho-type or a sigma type
365 -- head xs : Int vs head xs : forall b. b->b
366 -- So the matcher MUST NOT make a choice here. In general, we only
367 -- bind a template type variable in boxyMatchType, not in boxySubMatchType.
369 boxySubMatchType tmpl_tvs tmpl_ty boxy_ty
373 | Just t_ty' <- tcView t_ty = go t_ty' b_ty
374 | Just b_ty' <- tcView b_ty = go t_ty b_ty'
376 go (FunTy arg1 res1) (FunTy arg2 res2)
377 = do_match arg1 arg2 (go res1 res2)
378 -- Match the args, and sub-match the results
380 go (TyVarTy _) b_ty = emptyTvSubst -- Do not bind! See Note [Sub-match]
382 go t_ty b_ty = do_match t_ty b_ty emptyTvSubst -- Otherwise we are safe to bind
384 do_match t_ty b_ty subst = boxy_match tmpl_tvs t_ty emptyVarSet b_ty subst
387 boxyMatchTypes tmpl_tvs tmpl_tys boxy_tys
388 = ASSERT( length tmpl_tys == length boxy_tys )
389 boxy_match_s tmpl_tvs tmpl_tys emptyVarSet boxy_tys emptyTvSubst
390 -- ToDo: add error context?
392 boxy_match_s tmpl_tvs [] boxy_tvs [] subst
394 boxy_match_s tmpl_tvs (t_ty:t_tys) boxy_tvs (b_ty:b_tys) subst
395 = boxy_match_s tmpl_tvs t_tys boxy_tvs b_tys $
396 boxy_match tmpl_tvs t_ty boxy_tvs b_ty subst
399 boxy_match :: TcTyVarSet -> TcType -- Template
400 -> TcTyVarSet -- boxy_tvs: do not bind template tyvars to any of these
401 -> BoxySigmaType -- Match against this type
405 -- The boxy_tvs argument prevents this match:
406 -- [a] forall b. a ~ forall b. b
407 -- We don't want to bind the template variable 'a'
408 -- to the quantified type variable 'b'!
410 boxy_match tmpl_tvs orig_tmpl_ty boxy_tvs orig_boxy_ty subst
411 = go orig_tmpl_ty orig_boxy_ty
414 | Just t_ty' <- tcView t_ty = go t_ty' b_ty
415 | Just b_ty' <- tcView b_ty = go t_ty b_ty'
417 go (ForAllTy _ ty1) (ForAllTy tv2 ty2)
418 = boxy_match tmpl_tvs ty1 (boxy_tvs `extendVarSet` tv2) ty2 subst
420 go (TyConApp tc1 tys1) (TyConApp tc2 tys2)
421 | tc1 == tc2 = go_s tys1 tys2
423 go (FunTy arg1 res1) (FunTy arg2 res2)
424 = go_s [arg1,res1] [arg2,res2]
427 | Just (s1,t1) <- tcSplitAppTy_maybe t_ty,
428 Just (s2,t2) <- tcSplitAppTy_maybe b_ty,
429 typeKind t2 `isSubKind` typeKind t1 -- Maintain invariant
430 = go_s [s1,t1] [s2,t2]
433 | tv `elemVarSet` tmpl_tvs -- Template type variable in the template
434 , not (intersectsVarSet boxy_tvs (tyVarsOfType orig_boxy_ty))
435 , typeKind b_ty `isSubKind` tyVarKind tv
436 = extendTvSubst subst tv boxy_ty'
438 boxy_ty' = case lookupTyVar subst tv of
439 Nothing -> orig_boxy_ty
440 Just ty -> ty `boxyLub` orig_boxy_ty
442 go _ _ = subst -- Always safe
445 go_s tys1 tys2 = boxy_match_s tmpl_tvs tys1 boxy_tvs tys2 subst
448 boxyLub :: BoxySigmaType -> BoxySigmaType -> BoxySigmaType
449 -- Combine boxy information from the two types
450 -- If there is a conflict, return the first
451 boxyLub orig_ty1 orig_ty2
452 = go orig_ty1 orig_ty2
454 go (AppTy f1 a1) (AppTy f2 a2) = AppTy (boxyLub f1 f2) (boxyLub a1 a2)
455 go (FunTy f1 a1) (FunTy f2 a2) = FunTy (boxyLub f1 f2) (boxyLub a1 a2)
456 go (TyConApp tc1 ts1) (TyConApp tc2 ts2)
457 | tc1 == tc2, length ts1 == length ts2
458 = TyConApp tc1 (zipWith boxyLub ts1 ts2)
460 go (TyVarTy tv1) ty2 -- This is the whole point;
461 | isTcTyVar tv1, isMetaTyVar tv1 -- choose ty2 if ty2 is a box
464 -- Look inside type synonyms, but only if the naive version fails
465 go ty1 ty2 | Just ty1' <- tcView ty1 = go ty1' ty2
466 | Just ty2' <- tcView ty1 = go ty1 ty2'
468 -- For now, we don't look inside ForAlls, PredTys
469 go ty1 ty2 = orig_ty1 -- Default
473 %************************************************************************
477 %************************************************************************
479 All the tcSub calls have the form
481 tcSub expected_ty offered_ty
483 offered_ty <= expected_ty
485 That is, that a value of type offered_ty is acceptable in
486 a place expecting a value of type expected_ty.
488 It returns a coercion function
489 co_fn :: offered_ty -> expected_ty
490 which takes an HsExpr of type offered_ty into one of type
495 tcSubExp :: BoxySigmaType -> BoxySigmaType -> TcM ExprCoFn -- Locally used only
496 -- (tcSub act exp) checks that
498 tcSubExp actual_ty expected_ty
499 = traceTc (text "tcSub" <+> details) `thenM_`
500 addErrCtxtM (unifyCtxt "type" actual_ty expected_ty)
501 (tc_sub actual_ty actual_ty expected_ty expected_ty)
503 details = vcat [text "Expected:" <+> ppr expected_ty,
504 text "Actual: " <+> ppr actual_ty]
507 tc_sub :: BoxySigmaType -- actual_ty, before expanding synonyms
508 -> BoxySigmaType -- ..and after
509 -> BoxySigmaType -- expected_ty, before
510 -> BoxySigmaType -- ..and after
513 tc_sub act_sty act_ty exp_sty exp_ty
514 | Just exp_ty' <- tcView exp_ty = tc_sub act_sty act_ty exp_sty exp_ty'
515 tc_sub act_sty act_ty exp_sty exp_ty
516 | Just act_ty' <- tcView act_ty = tc_sub act_sty act_ty' exp_sty exp_ty
518 -----------------------------------
519 -- Rule SBOXY, plus other cases when act_ty is a type variable
520 -- Just defer to boxy matching
521 -- This rule takes precedence over SKOL!
522 tc_sub act_sty (TyVarTy tv) exp_sty exp_ty
523 = do { uVar False tv False exp_sty exp_ty
524 ; return idCoercion }
526 -----------------------------------
527 -- Skolemisation case (rule SKOL)
528 -- actual_ty: d:Eq b => b->b
529 -- expected_ty: forall a. Ord a => a->a
530 -- co_fn e /\a. \d2:Ord a. let d = eqFromOrd d2 in e
532 -- It is essential to do this *before* the specialisation case
533 -- Example: f :: (Eq a => a->a) -> ...
534 -- g :: Ord b => b->b
537 tc_sub act_sty act_ty exp_sty exp_ty
539 = do { (gen_fn, co_fn) <- tcGen exp_ty act_tvs $ \ body_exp_ty ->
540 tc_sub act_sty act_ty body_exp_ty body_exp_ty
541 ; return (gen_fn <.> co_fn) }
543 act_tvs = tyVarsOfType act_ty
544 -- It's really important to check for escape wrt the free vars of
545 -- both expected_ty *and* actual_ty
547 -----------------------------------
548 -- Specialisation case (rule ASPEC):
549 -- actual_ty: forall a. Ord a => a->a
550 -- expected_ty: Int -> Int
551 -- co_fn e = e Int dOrdInt
553 tc_sub act_sty actual_ty exp_sty expected_ty
554 | isSigmaTy actual_ty
555 = do { (tyvars, theta, tau) <- tcInstBoxy actual_ty
556 ; dicts <- newDicts InstSigOrigin theta
558 ; let inst_fn = CoApps (CoTyApps CoHole (mkTyVarTys tyvars))
560 ; co_fn <- tc_sub tau tau exp_sty expected_ty
561 ; return (co_fn <.> inst_fn) }
563 -----------------------------------
564 -- Function case (rule F1)
565 tc_sub _ (FunTy act_arg act_res) _ (FunTy exp_arg exp_res)
566 = tc_sub_funs act_arg act_res exp_arg exp_res
568 -- Function case (rule F2)
569 tc_sub act_sty act_ty@(FunTy act_arg act_res) exp_sty (TyVarTy exp_tv)
571 = do { cts <- readMetaTyVar exp_tv
573 Indirect ty -> do { u_tys False act_sty act_ty True exp_sty ty
574 ; return idCoercion }
575 Flexi -> do { [arg_ty,res_ty] <- withMetaTvs exp_tv fun_kinds mk_res_ty
576 ; tc_sub_funs act_arg act_res arg_ty res_ty } }
578 mk_res_ty [arg_ty', res_ty'] = mkFunTy arg_ty' res_ty'
579 fun_kinds = [argTypeKind, openTypeKind]
581 -- Everything else: defer to boxy matching
582 tc_sub act_sty actual_ty exp_sty expected_ty
583 = do { u_tys False act_sty actual_ty False exp_sty expected_ty
584 ; return idCoercion }
587 -----------------------------------
588 tc_sub_funs act_arg act_res exp_arg exp_res
589 = do { uTys False act_arg False exp_arg
590 ; co_fn_res <- tc_sub act_res act_res exp_res exp_res
591 ; wrapFunResCoercion [exp_arg] co_fn_res }
593 -----------------------------------
595 :: [TcType] -- Type of args
596 -> ExprCoFn -- HsExpr a -> HsExpr b
597 -> TcM ExprCoFn -- HsExpr (arg_tys -> a) -> HsExpr (arg_tys -> b)
598 wrapFunResCoercion arg_tys co_fn_res
599 | isIdCoercion co_fn_res = return idCoercion
600 | null arg_tys = return co_fn_res
602 = do { us <- newUniqueSupply
603 ; let arg_ids = zipWith (mkSysLocal FSLIT("sub")) (uniqsFromSupply us) arg_tys
604 ; return (CoLams arg_ids (co_fn_res <.> (CoApps CoHole arg_ids))) }
609 %************************************************************************
611 \subsection{Generalisation}
613 %************************************************************************
616 tcGen :: BoxySigmaType -- expected_ty
617 -> TcTyVarSet -- Extra tyvars that the universally
618 -- quantified tyvars of expected_ty
619 -- must not be unified
620 -> (BoxyRhoType -> TcM result) -- spec_ty
621 -> TcM (ExprCoFn, result)
622 -- The expression has type: spec_ty -> expected_ty
624 tcGen expected_ty extra_tvs thing_inside -- We expect expected_ty to be a forall-type
625 -- If not, the call is a no-op
626 = do { -- We want the GenSkol info in the skolemised type variables to
627 -- mention the *instantiated* tyvar names, so that we get a
628 -- good error message "Rigid variable 'a' is bound by (forall a. a->a)"
629 -- Hence the tiresome but innocuous fixM
630 ((forall_tvs, theta, rho_ty), skol_info) <- fixM (\ ~(_, skol_info) ->
631 do { (forall_tvs, theta, rho_ty) <- tcInstSkolType skol_info expected_ty
632 ; span <- getSrcSpanM
633 ; let skol_info = GenSkol forall_tvs (mkPhiTy theta rho_ty) span
634 ; return ((forall_tvs, theta, rho_ty), skol_info) })
637 ; traceTc (text "tcGen" <+> vcat [text "extra_tvs" <+> ppr extra_tvs,
638 text "expected_ty" <+> ppr expected_ty,
639 text "inst ty" <+> ppr forall_tvs <+> ppr theta <+> ppr rho_ty,
640 text "free_tvs" <+> ppr free_tvs,
641 text "forall_tvs" <+> ppr forall_tvs])
644 -- Type-check the arg and unify with poly type
645 ; (result, lie) <- getLIE (thing_inside rho_ty)
647 -- Check that the "forall_tvs" havn't been constrained
648 -- The interesting bit here is that we must include the free variables
649 -- of the expected_ty. Here's an example:
650 -- runST (newVar True)
651 -- Here, if we don't make a check, we'll get a type (ST s (MutVar s Bool))
652 -- for (newVar True), with s fresh. Then we unify with the runST's arg type
653 -- forall s'. ST s' a. That unifies s' with s, and a with MutVar s Bool.
654 -- So now s' isn't unconstrained because it's linked to a.
655 -- Conclusion: include the free vars of the expected_ty in the
656 -- list of "free vars" for the signature check.
658 ; dicts <- newDicts (SigOrigin skol_info) theta
659 ; inst_binds <- tcSimplifyCheck sig_msg forall_tvs dicts lie
661 ; checkSigTyVarsWrt free_tvs forall_tvs
662 ; traceTc (text "tcGen:done")
665 -- This HsLet binds any Insts which came out of the simplification.
666 -- It's a bit out of place here, but using AbsBind involves inventing
667 -- a couple of new names which seems worse.
668 dict_ids = map instToId dicts
669 co_fn = CoTyLams forall_tvs $ CoLams dict_ids $ CoLet inst_binds CoHole
670 ; returnM (co_fn, result) }
672 free_tvs = tyVarsOfType expected_ty `unionVarSet` extra_tvs
673 sig_msg = ptext SLIT("expected type of an expression")
678 %************************************************************************
682 %************************************************************************
684 The exported functions are all defined as versions of some
685 non-exported generic functions.
688 boxyUnify :: BoxyType -> BoxyType -> TcM ()
689 -- Acutal and expected, respectively
691 = addErrCtxtM (unifyCtxt "type" ty1 ty2) $
692 uTys False ty1 False ty2
695 boxyUnifyList :: [BoxyType] -> [BoxyType] -> TcM ()
696 -- Arguments should have equal length
697 -- Acutal and expected types
698 boxyUnifyList tys1 tys2 = uList boxyUnify tys1 tys2
701 unifyType :: TcTauType -> TcTauType -> TcM ()
702 -- No boxes expected inside these types
703 -- Acutal and expected types
704 unifyType ty1 ty2 -- ty1 expected, ty2 inferred
705 = ASSERT2( not (isBoxyTy ty1), ppr ty1 )
706 ASSERT2( not (isBoxyTy ty2), ppr ty2 )
707 addErrCtxtM (unifyCtxt "type" ty1 ty2) $
708 uTys True ty1 True ty2
711 unifyPred :: PredType -> PredType -> TcM ()
712 -- Acutal and expected types
713 unifyPred p1 p2 = addErrCtxtM (unifyCtxt "type constraint" (mkPredTy p1) (mkPredTy p2)) $
714 uPred True p1 True p2
716 unifyTheta :: TcThetaType -> TcThetaType -> TcM ()
717 -- Acutal and expected types
718 unifyTheta theta1 theta2
719 = do { checkTc (equalLength theta1 theta2)
720 (ptext SLIT("Contexts differ in length"))
721 ; uList unifyPred theta1 theta2 }
724 uList :: (a -> a -> TcM ())
725 -> [a] -> [a] -> TcM ()
726 -- Unify corresponding elements of two lists of types, which
727 -- should be f equal length. We charge down the list explicitly so that
728 -- we can complain if their lengths differ.
729 uList unify [] [] = return ()
730 uList unify (ty1:tys1) (ty2:tys2) = do { unify ty1 ty2; uList unify tys1 tys2 }
731 uList unify ty1s ty2s = panic "Unify.uList: mismatched type lists!"
734 @unifyTypeList@ takes a single list of @TauType@s and unifies them
735 all together. It is used, for example, when typechecking explicit
736 lists, when all the elts should be of the same type.
739 unifyTypeList :: [TcTauType] -> TcM ()
740 unifyTypeList [] = returnM ()
741 unifyTypeList [ty] = returnM ()
742 unifyTypeList (ty1:tys@(ty2:_)) = do { unifyType ty1 ty2
743 ; unifyTypeList tys }
746 %************************************************************************
748 \subsection[Unify-uTys]{@uTys@: getting down to business}
750 %************************************************************************
752 @uTys@ is the heart of the unifier. Each arg happens twice, because
753 we want to report errors in terms of synomyms if poss. The first of
754 the pair is used in error messages only; it is always the same as the
755 second, except that if the first is a synonym then the second may be a
756 de-synonym'd version. This way we get better error messages.
758 We call the first one \tr{ps_ty1}, \tr{ps_ty2} for ``possible synomym''.
761 type NoBoxes = Bool -- True <=> definitely no boxes in this type
762 -- False <=> there might be boxes (always safe)
764 uTys :: NoBoxes -> TcType -- ty1 is the *expected* type
765 -> NoBoxes -> TcType -- ty2 is the *actual* type
767 uTys nb1 ty1 nb2 ty2 = u_tys nb1 ty1 ty1 nb2 ty2 ty2
771 uTys_s :: NoBoxes -> [TcType] -- ty1 is the *actual* types
772 -> NoBoxes -> [TcType] -- ty2 is the *expected* types
774 uTys_s nb1 [] nb2 [] = returnM ()
775 uTys_s nb1 (ty1:tys1) nb2 (ty2:tys2) = do { uTys nb1 ty1 nb2 ty2
776 ; uTys_s nb1 tys1 nb2 tys2 }
777 uTys_s nb1 ty1s nb2 ty2s = panic "Unify.uTys_s: mismatched type lists!"
780 u_tys :: NoBoxes -> TcType -> TcType -- ty1 is the *actual* type
781 -> NoBoxes -> TcType -> TcType -- ty2 is the *expected* type
784 u_tys nb1 orig_ty1 ty1 nb2 orig_ty2 ty2
788 -- Always expand synonyms (see notes at end)
789 -- (this also throws away FTVs)
791 | Just ty1' <- tcView ty1 = go ty1' ty2
792 | Just ty2' <- tcView ty2 = go ty1 ty2'
794 -- Variables; go for uVar
795 go (TyVarTy tyvar1) ty2 = uVar False tyvar1 nb2 orig_ty2 ty2
796 go ty1 (TyVarTy tyvar2) = uVar True tyvar2 nb1 orig_ty1 ty1
797 -- "True" means args swapped
799 go (PredTy p1) (PredTy p2) = uPred nb1 p1 nb2 p2
801 -- Type constructors must match
802 go (TyConApp con1 tys1) (TyConApp con2 tys2)
803 | con1 == con2 = uTys_s nb1 tys1 nb2 tys2
804 -- See Note [TyCon app]
806 -- Functions; just check the two parts
807 go (FunTy fun1 arg1) (FunTy fun2 arg2)
808 = do { uTys nb1 fun1 nb2 fun2
809 ; uTys nb1 arg1 nb2 arg2 }
811 -- Applications need a bit of care!
812 -- They can match FunTy and TyConApp, so use splitAppTy_maybe
813 -- NB: we've already dealt with type variables and Notes,
814 -- so if one type is an App the other one jolly well better be too
816 = case tcSplitAppTy_maybe ty2 of
817 Just (s2,t2) -> do { uTys nb1 s1 nb2 s2; uTys nb1 t1 nb2 t2 }
818 Nothing -> unifyMisMatch False orig_ty1 orig_ty2
820 -- Now the same, but the other way round
821 -- Don't swap the types, because the error messages get worse
823 = case tcSplitAppTy_maybe ty1 of
824 Just (s1,t1) -> do { uTys nb1 s1 nb2 s2; uTys nb1 t1 nb2 t2 }
825 Nothing -> unifyMisMatch False orig_ty1 orig_ty2
827 go ty1@(ForAllTy _ _) ty2@(ForAllTy _ _)
828 | length tvs1 == length tvs2
829 = do { tvs <- tcInstSkolTyVars UnkSkol tvs1 -- Not a helpful SkolemInfo
830 ; let tys = mkTyVarTys tvs
831 in_scope = mkInScopeSet (mkVarSet tvs)
832 subst1 = mkTvSubst in_scope (zipTyEnv tvs1 tys)
833 subst2 = mkTvSubst in_scope (zipTyEnv tvs2 tys)
834 ; uTys nb1 (substTy subst1 body1) nb2 (substTy subst2 body2)
836 -- If both sides are inside a box, we should not have
837 -- a polytype at all. This check comes last, because
838 -- the error message is extremely unhelpful.
839 ; ifM (nb1 && nb2) (notMonoType ty1)
842 (tvs1, body1) = tcSplitForAllTys ty1
843 (tvs2, body2) = tcSplitForAllTys ty2
845 -- Anything else fails
846 go _ _ = unifyMisMatch False orig_ty1 orig_ty2
849 uPred nb1 (IParam n1 t1) nb2 (IParam n2 t2)
850 | n1 == n2 = uTys nb1 t1 nb2 t2
851 uPred nb1 (ClassP c1 tys1) nb2 (ClassP c2 tys2)
852 | c1 == c2 = uTys_s nb1 tys1 nb2 tys2 -- Guaranteed equal lengths because the kinds check
853 uPred _ p1 _ p2 = unifyMisMatch False (mkPredTy p1) (mkPredTy p2)
858 When we find two TyConApps, the argument lists are guaranteed equal
859 length. Reason: intially the kinds of the two types to be unified is
860 the same. The only way it can become not the same is when unifying two
861 AppTys (f1 a1):=:(f2 a2). In that case there can't be a TyConApp in
862 the f1,f2 (because it'd absorb the app). If we unify f1:=:f2 first,
863 which we do, that ensures that f1,f2 have the same kind; and that
864 means a1,a2 have the same kind. And now the argument repeats.
869 If you are tempted to make a short cut on synonyms, as in this
873 -- NO uTys (SynTy con1 args1 ty1) (SynTy con2 args2 ty2)
874 -- NO = if (con1 == con2) then
875 -- NO -- Good news! Same synonym constructors, so we can shortcut
876 -- NO -- by unifying their arguments and ignoring their expansions.
877 -- NO unifyTypepeLists args1 args2
879 -- NO -- Never mind. Just expand them and try again
883 then THINK AGAIN. Here is the whole story, as detected and reported
884 by Chris Okasaki \tr{<Chris_Okasaki@loch.mess.cs.cmu.edu>}:
886 Here's a test program that should detect the problem:
890 x = (1 :: Bogus Char) :: Bogus Bool
893 The problem with [the attempted shortcut code] is that
897 is not a sufficient condition to be able to use the shortcut!
898 You also need to know that the type synonym actually USES all
899 its arguments. For example, consider the following type synonym
900 which does not use all its arguments.
905 If you ever tried unifying, say, \tr{Bogus Char} with \tr{Bogus Bool},
906 the unifier would blithely try to unify \tr{Char} with \tr{Bool} and
907 would fail, even though the expanded forms (both \tr{Int}) should
910 Similarly, unifying \tr{Bogus Char} with \tr{Bogus t} would
911 unnecessarily bind \tr{t} to \tr{Char}.
913 ... You could explicitly test for the problem synonyms and mark them
914 somehow as needing expansion, perhaps also issuing a warning to the
919 %************************************************************************
921 \subsection[Unify-uVar]{@uVar@: unifying with a type variable}
923 %************************************************************************
925 @uVar@ is called when at least one of the types being unified is a
926 variable. It does {\em not} assume that the variable is a fixed point
927 of the substitution; rather, notice that @uVar@ (defined below) nips
928 back into @uTys@ if it turns out that the variable is already bound.
931 uVar :: Bool -- False => tyvar is the "expected"
932 -- True => ty is the "expected" thing
934 -> NoBoxes -- True <=> definitely no boxes in t2
935 -> TcTauType -> TcTauType -- printing and real versions
938 uVar swapped tv1 nb2 ps_ty2 ty2
939 = do { let expansion | showSDoc (ppr ty2) == showSDoc (ppr ps_ty2) = empty
940 | otherwise = brackets (equals <+> ppr ty2)
941 ; traceTc (text "uVar" <+> ppr swapped <+>
942 sep [ppr tv1 <+> dcolon <+> ppr (tyVarKind tv1 ),
943 nest 2 (ptext SLIT(" :=: ")),
944 ppr ps_ty2 <+> dcolon <+> ppr (typeKind ty2) <+> expansion])
945 ; details <- lookupTcTyVar tv1
948 | swapped -> u_tys nb2 ps_ty2 ty2 True ty1 ty1 -- Swap back
949 | otherwise -> u_tys True ty1 ty1 nb2 ps_ty2 ty2 -- Same order
950 -- The 'True' here says that ty1
951 -- is definitely box-free
952 DoneTv details1 -> uUnfilledVar swapped tv1 details1 nb2 ps_ty2 ty2
956 uUnfilledVar :: Bool -- Args are swapped
957 -> TcTyVar -> TcTyVarDetails -- Tyvar 1
958 -> NoBoxes -> TcTauType -> TcTauType -- Type 2
960 -- Invariant: tyvar 1 is not unified with anything
962 uUnfilledVar swapped tv1 details1 nb2 ps_ty2 ty2
963 | Just ty2' <- tcView ty2
964 = -- Expand synonyms; ignore FTVs
965 uUnfilledVar swapped tv1 details1 nb2 ps_ty2 ty2'
967 uUnfilledVar swapped tv1 details1 nb2 ps_ty2 ty2@(TyVarTy tv2)
968 -- Same type variable => no-op
972 -- Distinct type variables
974 = do { lookup2 <- lookupTcTyVar tv2
976 IndirectTv ty2' -> uUnfilledVar swapped tv1 details1 True ty2' ty2'
977 DoneTv details2 -> uUnfilledVars swapped tv1 details1 tv2 details2
980 uUnfilledVar swapped tv1 details1 nb2 ps_ty2 non_var_ty2 -- ty2 is not a type variable
982 MetaTv (SigTv _) ref1 -> mis_match -- Can't update a skolem with a non-type-variable
983 MetaTv info ref1 -> uMetaVar swapped tv1 info ref1 nb2 ps_ty2 non_var_ty2
984 skolem_details -> mis_match
986 mis_match = unifyMisMatch swapped (TyVarTy tv1) ps_ty2
990 -> TcTyVar -> BoxInfo -> IORef MetaDetails
991 -> NoBoxes -> TcType -> TcType
993 -- tv1 is an un-filled-in meta type variable (maybe boxy, maybe tau)
994 -- ty2 is not a type variable
996 uMetaVar swapped tv1 info1 ref1 nb2 ps_ty2 non_var_ty2
997 = do { final_ty <- case info1 of
998 BoxTv -> unBox ps_ty2 -- No occurs check
999 other -> checkTauTvUpdate tv1 ps_ty2 -- Occurs check + monotype check
1000 ; checkUpdateMeta swapped tv1 ref1 final_ty }
1003 uUnfilledVars :: Bool -- Args are swapped
1004 -> TcTyVar -> TcTyVarDetails -- Tyvar 1
1005 -> TcTyVar -> TcTyVarDetails -- Tyvar 2
1007 -- Invarant: The type variables are distinct,
1008 -- Neither is filled in yet
1009 -- They might be boxy or not
1011 uUnfilledVars swapped tv1 (SkolemTv _) tv2 (SkolemTv _)
1012 = unifyMisMatch swapped (mkTyVarTy tv1) (mkTyVarTy tv2)
1014 uUnfilledVars swapped tv1 (MetaTv info1 ref1) tv2 (SkolemTv _)
1015 = checkUpdateMeta swapped tv1 ref1 (mkTyVarTy tv2)
1016 uUnfilledVars swapped tv1 (SkolemTv _) tv2 (MetaTv info2 ref2)
1017 = checkUpdateMeta (not swapped) tv2 ref2 (mkTyVarTy tv1)
1019 -- ToDo: this function seems too long for what it acutally does!
1020 uUnfilledVars swapped tv1 (MetaTv info1 ref1) tv2 (MetaTv info2 ref2)
1021 = case (info1, info2) of
1022 (BoxTv, BoxTv) -> box_meets_box
1024 -- If a box meets a TauTv, but the fomer has the smaller kind
1025 -- then we must create a fresh TauTv with the smaller kind
1026 (_, BoxTv) | k1_sub_k2 -> update_tv2
1027 | otherwise -> box_meets_box
1028 (BoxTv, _ ) | k2_sub_k1 -> update_tv1
1029 | otherwise -> box_meets_box
1031 -- Avoid SigTvs if poss
1032 (SigTv _, _ ) | k1_sub_k2 -> update_tv2
1033 (_, SigTv _) | k2_sub_k1 -> update_tv1
1035 (_, _) | k1_sub_k2 -> if k2_sub_k1 && nicer_to_update_tv1
1036 then update_tv1 -- Same kinds
1038 | k2_sub_k1 -> update_tv1
1039 | otherwise -> kind_err
1041 -- Update the variable with least kind info
1042 -- See notes on type inference in Kind.lhs
1043 -- The "nicer to" part only applies if the two kinds are the same,
1044 -- so we can choose which to do.
1046 -- Kinds should be guaranteed ok at this point
1047 update_tv1 = updateMeta tv1 ref1 (mkTyVarTy tv2)
1048 update_tv2 = updateMeta tv2 ref2 (mkTyVarTy tv1)
1050 box_meets_box | k1_sub_k2 = fill_with k1
1051 | k2_sub_k1 = fill_with k2
1052 | otherwise = kind_err
1054 fill_with kind = do { tau_ty <- newFlexiTyVarTy kind
1055 ; updateMeta tv1 ref1 tau_ty
1056 ; updateMeta tv2 ref2 tau_ty }
1058 kind_err = addErrCtxtM (unifyKindCtxt swapped tv1 (mkTyVarTy tv2)) $
1059 unifyKindMisMatch k1 k2
1063 k1_sub_k2 = k1 `isSubKind` k2
1064 k2_sub_k1 = k2 `isSubKind` k1
1066 nicer_to_update_tv1 = isSystemName (varName tv1)
1067 -- Try to update sys-y type variables in preference to ones
1068 -- gotten (say) by instantiating a polymorphic function with
1069 -- a user-written type sig
1072 checkUpdateMeta :: Bool -> TcTyVar -> IORef MetaDetails -> TcType -> TcM ()
1073 -- Update tv1, which is flexi; occurs check is alrady done
1074 -- The 'check' version does a kind check too
1075 -- We do a sub-kind check here: we might unify (a b) with (c d)
1076 -- where b::*->* and d::*; this should fail
1078 checkUpdateMeta swapped tv1 ref1 ty2
1079 = do { checkKinds swapped tv1 ty2
1080 ; updateMeta tv1 ref1 ty2 }
1082 updateMeta :: TcTyVar -> IORef MetaDetails -> TcType -> TcM ()
1083 updateMeta tv1 ref1 ty2
1084 = ASSERT( isMetaTyVar tv1 )
1085 ASSERT( isBoxyTyVar tv1 || isTauTy ty2 )
1086 do { ASSERTM2( do { details <- readMetaTyVar tv1; return (isFlexi details) }, ppr tv1 )
1087 ; traceTc (text "updateMeta" <+> ppr tv1 <+> text ":=" <+> ppr ty2)
1088 ; writeMutVar ref1 (Indirect ty2) }
1091 checkKinds swapped tv1 ty2
1092 -- We're about to unify a type variable tv1 with a non-tyvar-type ty2.
1093 -- ty2 has been zonked at this stage, which ensures that
1094 -- its kind has as much boxity information visible as possible.
1095 | tk2 `isSubKind` tk1 = returnM ()
1098 -- Either the kinds aren't compatible
1099 -- (can happen if we unify (a b) with (c d))
1100 -- or we are unifying a lifted type variable with an
1101 -- unlifted type: e.g. (id 3#) is illegal
1102 = addErrCtxtM (unifyKindCtxt swapped tv1 ty2) $
1103 unifyKindMisMatch k1 k2
1105 (k1,k2) | swapped = (tk2,tk1)
1106 | otherwise = (tk1,tk2)
1111 checkTauTvUpdate :: TcTyVar -> TcType -> TcM TcType
1112 -- (checkTauTvUpdate tv ty)
1113 -- We are about to update the TauTv tv with ty.
1114 -- Check (a) that tv doesn't occur in ty (occurs check)
1115 -- (b) that ty is a monotype
1116 -- Furthermore, in the interest of (b), if you find an
1117 -- empty box (BoxTv that is Flexi), fill it in with a TauTv
1119 -- Returns the (non-boxy) type to update the type variable with, or fails
1121 checkTauTvUpdate orig_tv orig_ty
1124 go (TyConApp tc tys)
1125 | isSynTyCon tc = go_syn tc tys
1126 | otherwise = do { tys' <- mappM go tys; return (TyConApp tc tys') }
1127 go (NoteTy _ ty2) = go ty2 -- Discard free-tyvar annotations
1128 go (PredTy p) = do { p' <- go_pred p; return (PredTy p') }
1129 go (FunTy arg res) = do { arg' <- go arg; res' <- go res; return (FunTy arg' res') }
1130 go (AppTy fun arg) = do { fun' <- go fun; arg' <- go arg; return (mkAppTy fun' arg') }
1131 -- NB the mkAppTy; we might have instantiated a
1132 -- type variable to a type constructor, so we need
1133 -- to pull the TyConApp to the top.
1134 go (ForAllTy tv ty) = notMonoType orig_ty -- (b)
1137 | orig_tv == tv = occurCheck tv orig_ty -- (a)
1138 | isTcTyVar tv = go_tyvar tv (tcTyVarDetails tv)
1139 | otherwise = return (TyVarTy tv)
1140 -- Ordinary (non Tc) tyvars
1141 -- occur inside quantified types
1143 go_pred (ClassP c tys) = do { tys' <- mapM go tys; return (ClassP c tys') }
1144 go_pred (IParam n ty) = do { ty' <- go ty; return (IParam n ty') }
1146 go_tyvar tv (SkolemTv _) = return (TyVarTy tv)
1147 go_tyvar tv (MetaTv box ref)
1148 = do { cts <- readMutVar ref
1150 Indirect ty -> go ty
1151 Flexi -> case box of
1152 BoxTv -> do { tau <- newFlexiTyVarTy (tyVarKind tv)
1153 ; writeMutVar ref (Indirect tau)
1155 other -> return (TyVarTy tv)
1158 -- go_syn is called for synonyms only
1159 -- See Note [Type synonyms and the occur check]
1161 | not (isTauTyCon tc)
1162 = notMonoType orig_ty -- (b) again
1164 = do { (msgs, mb_tys') <- tryTc (mapM go tys)
1166 Just tys' -> return (TyConApp tc tys')
1167 -- Retain the synonym (the common case)
1168 Nothing -> go (fromJust (tcView (TyConApp tc tys)))
1169 -- Try again, expanding the synonym
1173 Note [Type synonyms and the occur check]
1174 ~~~~~~~~~~~~~~~~~~~~
1175 Basically we want to update tv1 := ps_ty2
1176 because ps_ty2 has type-synonym info, which improves later error messages
1181 f :: (A a -> a -> ()) -> ()
1185 x = f (\ x p -> p x)
1187 In the application (p x), we try to match "t" with "A t". If we go
1188 ahead and bind t to A t (= ps_ty2), we'll lead the type checker into
1189 an infinite loop later.
1190 But we should not reject the program, because A t = ().
1191 Rather, we should bind t to () (= non_var_ty2).
1194 stripBoxyType :: BoxyType -> TcM TcType
1195 -- Strip all boxes from the input type, returning a non-boxy type.
1196 -- It's fine for there to be a polytype inside a box (c.f. unBox)
1197 -- All of the boxes should have been filled in by now;
1198 -- hence we return a TcType
1199 stripBoxyType ty = zonkType strip_tv ty
1201 strip_tv tv = ASSERT( not (isBoxyTyVar tv) ) return (TyVarTy tv)
1202 -- strip_tv will be called for *Flexi* meta-tyvars
1203 -- There should not be any Boxy ones; hence the ASSERT
1205 zapToMonotype :: BoxySigmaType -> TcM TcTauType
1206 -- Subtle... we must zap the boxy res_ty
1207 -- to kind * before using it to instantiate a LitInst
1208 -- Calling unBox instead doesn't do the job, because the box
1209 -- often has an openTypeKind, and we don't want to instantiate
1211 zapToMonotype res_ty
1212 = do { res_tau <- newFlexiTyVarTy liftedTypeKind
1213 ; boxyUnify res_tau res_ty
1216 unBox :: BoxyType -> TcM TcType
1217 -- unBox implements the judgement
1219 -- with input s', and result s
1221 -- It remove all boxes from the input type, returning a non-boxy type.
1222 -- A filled box in the type can only contain a monotype; unBox fails if not
1223 -- The type can have empty boxes, which unBox fills with a monotype
1225 -- Compare this wth checkTauTvUpdate
1227 -- For once, it's safe to treat synonyms as opaque!
1229 unBox (NoteTy n ty) = do { ty' <- unBox ty; return (NoteTy n ty') }
1230 unBox (TyConApp tc tys) = do { tys' <- mapM unBox tys; return (TyConApp tc tys') }
1231 unBox (AppTy f a) = do { f' <- unBox f; a' <- unBox a; return (mkAppTy f' a') }
1232 unBox (FunTy f a) = do { f' <- unBox f; a' <- unBox a; return (FunTy f' a') }
1233 unBox (PredTy p) = do { p' <- unBoxPred p; return (PredTy p') }
1234 unBox (ForAllTy tv ty) = ASSERT( isImmutableTyVar tv )
1235 do { ty' <- unBox ty; return (ForAllTy tv ty') }
1237 | isTcTyVar tv -- It's a boxy type variable
1238 , MetaTv BoxTv ref <- tcTyVarDetails tv -- NB: non-TcTyVars are possible
1239 = do { cts <- readMutVar ref -- under nested quantifiers
1241 Indirect ty -> do { non_boxy_ty <- unBox ty
1242 ; if isTauTy non_boxy_ty
1243 then return non_boxy_ty
1244 else notMonoType non_boxy_ty }
1245 Flexi -> do { tau <- newFlexiTyVarTy (tyVarKind tv)
1246 ; writeMutVar ref (Indirect tau)
1249 | otherwise -- Skolems, and meta-tau-variables
1250 = return (TyVarTy tv)
1252 unBoxPred (ClassP cls tys) = do { tys' <- mapM unBox tys; return (ClassP cls tys') }
1253 unBoxPred (IParam ip ty) = do { ty' <- unBox ty; return (IParam ip ty') }
1258 %************************************************************************
1262 %************************************************************************
1264 Unifying kinds is much, much simpler than unifying types.
1267 unifyKind :: TcKind -- Expected
1270 unifyKind LiftedTypeKind LiftedTypeKind = returnM ()
1271 unifyKind UnliftedTypeKind UnliftedTypeKind = returnM ()
1273 unifyKind OpenTypeKind k2 | isOpenTypeKind k2 = returnM ()
1274 unifyKind ArgTypeKind k2 | isArgTypeKind k2 = returnM ()
1275 -- Respect sub-kinding
1277 unifyKind (FunKind a1 r1) (FunKind a2 r2)
1278 = do { unifyKind a2 a1; unifyKind r1 r2 }
1279 -- Notice the flip in the argument,
1280 -- so that the sub-kinding works right
1282 unifyKind (KindVar kv1) k2 = uKVar False kv1 k2
1283 unifyKind k1 (KindVar kv2) = uKVar True kv2 k1
1284 unifyKind k1 k2 = unifyKindMisMatch k1 k2
1286 unifyKinds :: [TcKind] -> [TcKind] -> TcM ()
1287 unifyKinds [] [] = returnM ()
1288 unifyKinds (k1:ks1) (k2:ks2) = unifyKind k1 k2 `thenM_`
1290 unifyKinds _ _ = panic "unifyKinds: length mis-match"
1293 uKVar :: Bool -> KindVar -> TcKind -> TcM ()
1294 uKVar swapped kv1 k2
1295 = do { mb_k1 <- readKindVar kv1
1297 Nothing -> uUnboundKVar swapped kv1 k2
1298 Just k1 | swapped -> unifyKind k2 k1
1299 | otherwise -> unifyKind k1 k2 }
1302 uUnboundKVar :: Bool -> KindVar -> TcKind -> TcM ()
1303 uUnboundKVar swapped kv1 k2@(KindVar kv2)
1304 | kv1 == kv2 = returnM ()
1305 | otherwise -- Distinct kind variables
1306 = do { mb_k2 <- readKindVar kv2
1308 Just k2 -> uUnboundKVar swapped kv1 k2
1309 Nothing -> writeKindVar kv1 k2 }
1311 uUnboundKVar swapped kv1 non_var_k2
1312 = do { k2' <- zonkTcKind non_var_k2
1313 ; kindOccurCheck kv1 k2'
1314 ; k2'' <- kindSimpleKind swapped k2'
1315 -- KindVars must be bound only to simple kinds
1316 -- Polarities: (kindSimpleKind True ?) succeeds
1317 -- returning *, corresponding to unifying
1320 ; writeKindVar kv1 k2'' }
1323 kindOccurCheck kv1 k2 -- k2 is zonked
1324 = checkTc (not_in k2) (kindOccurCheckErr kv1 k2)
1326 not_in (KindVar kv2) = kv1 /= kv2
1327 not_in (FunKind a2 r2) = not_in a2 && not_in r2
1330 kindSimpleKind :: Bool -> Kind -> TcM SimpleKind
1331 -- (kindSimpleKind True k) returns a simple kind sk such that sk <: k
1332 -- If the flag is False, it requires k <: sk
1333 -- E.g. kindSimpleKind False ?? = *
1334 -- What about (kv -> *) :=: ?? -> *
1335 kindSimpleKind orig_swapped orig_kind
1336 = go orig_swapped orig_kind
1338 go sw (FunKind k1 k2) = do { k1' <- go (not sw) k1
1340 ; return (FunKind k1' k2') }
1341 go True OpenTypeKind = return liftedTypeKind
1342 go True ArgTypeKind = return liftedTypeKind
1343 go sw LiftedTypeKind = return liftedTypeKind
1344 go sw k@(KindVar _) = return k -- KindVars are always simple
1345 go swapped kind = failWithTc (ptext SLIT("Unexpected kind unification failure:")
1346 <+> ppr orig_swapped <+> ppr orig_kind)
1347 -- I think this can't actually happen
1349 -- T v = MkT v v must be a type
1350 -- T v w = MkT (v -> w) v must not be an umboxed tuple
1353 kindOccurCheckErr tyvar ty
1354 = hang (ptext SLIT("Occurs check: cannot construct the infinite kind:"))
1355 2 (sep [ppr tyvar, char '=', ppr ty])
1357 unifyKindMisMatch ty1 ty2
1358 = zonkTcKind ty1 `thenM` \ ty1' ->
1359 zonkTcKind ty2 `thenM` \ ty2' ->
1361 msg = hang (ptext SLIT("Couldn't match kind"))
1362 2 (sep [quotes (ppr ty1'),
1363 ptext SLIT("against"),
1370 unifyFunKind :: TcKind -> TcM (Maybe (TcKind, TcKind))
1371 -- Like unifyFunTy, but does not fail; instead just returns Nothing
1373 unifyFunKind (KindVar kvar)
1374 = readKindVar kvar `thenM` \ maybe_kind ->
1376 Just fun_kind -> unifyFunKind fun_kind
1377 Nothing -> do { arg_kind <- newKindVar
1378 ; res_kind <- newKindVar
1379 ; writeKindVar kvar (mkArrowKind arg_kind res_kind)
1380 ; returnM (Just (arg_kind,res_kind)) }
1382 unifyFunKind (FunKind arg_kind res_kind) = returnM (Just (arg_kind,res_kind))
1383 unifyFunKind other = returnM Nothing
1386 %************************************************************************
1388 \subsection[Unify-context]{Errors and contexts}
1390 %************************************************************************
1396 unifyCtxt s ty1 ty2 tidy_env -- ty1 inferred, ty2 expected
1397 = zonkTcType ty1 `thenM` \ ty1' ->
1398 zonkTcType ty2 `thenM` \ ty2' ->
1399 returnM (err ty1' ty2')
1401 err ty1 ty2 = (env1,
1404 text "Expected" <+> text s <> colon <+> ppr tidy_ty2,
1405 text "Inferred" <+> text s <> colon <+> ppr tidy_ty1
1408 (env1, [tidy_ty1,tidy_ty2]) = tidyOpenTypes tidy_env [ty1,ty2]
1410 unifyKindCtxt swapped tv1 ty2 tidy_env -- not swapped => tv1 expected, ty2 inferred
1411 -- tv1 and ty2 are zonked already
1414 msg = (env2, ptext SLIT("When matching the kinds of") <+>
1415 sep [quotes pp_expected <+> ptext SLIT("and"), quotes pp_actual])
1417 (pp_expected, pp_actual) | swapped = (pp2, pp1)
1418 | otherwise = (pp1, pp2)
1419 (env1, tv1') = tidyOpenTyVar tidy_env tv1
1420 (env2, ty2') = tidyOpenType env1 ty2
1421 pp1 = ppr tv1' <+> dcolon <+> ppr (tyVarKind tv1)
1422 pp2 = ppr ty2' <+> dcolon <+> ppr (typeKind ty2)
1424 unifyMisMatch swapped ty1 ty2
1425 = do { (env, msg) <- if swapped then misMatchMsg ty2 ty1
1426 else misMatchMsg ty1 ty2
1427 ; failWithTcM (env, msg) }
1430 = do { env0 <- tcInitTidyEnv
1431 ; (env1, pp1, extra1) <- ppr_ty env0 ty1
1432 ; (env2, pp2, extra2) <- ppr_ty env1 ty2
1433 ; return (env2, sep [sep [ptext SLIT("Couldn't match") <+> pp1,
1434 nest 7 (ptext SLIT("against") <+> pp2)],
1435 nest 2 extra1, nest 2 extra2]) }
1437 ppr_ty :: TidyEnv -> TcType -> TcM (TidyEnv, SDoc, SDoc)
1439 = do { ty' <- zonkTcType ty
1440 ; let (env1,tidy_ty) = tidyOpenType env ty'
1441 simple_result = (env1, quotes (ppr tidy_ty), empty)
1444 | isSkolemTyVar tv -> return (env2, pp_rigid tv',
1445 pprSkolTvBinding tv')
1446 | otherwise -> return simple_result
1448 (env2, tv') = tidySkolemTyVar env1 tv
1449 other -> return simple_result }
1451 pp_rigid tv = ptext SLIT("the rigid variable") <+> quotes (ppr tv)
1455 = do { ty' <- zonkTcType ty
1456 ; env0 <- tcInitTidyEnv
1457 ; let (env1, tidy_ty) = tidyOpenType env0 ty'
1458 msg = ptext SLIT("Cannot match a monotype with") <+> ppr tidy_ty
1459 ; failWithTcM (env1, msg) }
1462 = do { env0 <- tcInitTidyEnv
1463 ; ty' <- zonkTcType ty
1464 ; let (env1, tidy_tyvar) = tidyOpenTyVar env0 tyvar
1465 (env2, tidy_ty) = tidyOpenType env1 ty
1466 extra = sep [ppr tidy_tyvar, char '=', ppr tidy_ty]
1467 ; failWithTcM (env2, hang msg 2 extra) }
1469 msg = ptext SLIT("Occurs check: cannot construct the infinite type:")
1473 %************************************************************************
1477 %************************************************************************
1479 ---------------------------
1480 -- We would like to get a decent error message from
1481 -- (a) Under-applied type constructors
1482 -- f :: (Maybe, Maybe)
1483 -- (b) Over-applied type constructors
1484 -- f :: Int x -> Int x
1488 checkExpectedKind :: Outputable a => a -> TcKind -> TcKind -> TcM ()
1489 -- A fancy wrapper for 'unifyKind', which tries
1490 -- to give decent error messages.
1491 checkExpectedKind ty act_kind exp_kind
1492 | act_kind `isSubKind` exp_kind -- Short cut for a very common case
1495 = tryTc (unifyKind exp_kind act_kind) `thenM` \ (_errs, mb_r) ->
1497 Just r -> returnM () ; -- Unification succeeded
1500 -- So there's definitely an error
1501 -- Now to find out what sort
1502 zonkTcKind exp_kind `thenM` \ exp_kind ->
1503 zonkTcKind act_kind `thenM` \ act_kind ->
1505 tcInitTidyEnv `thenM` \ env0 ->
1506 let (exp_as, _) = splitKindFunTys exp_kind
1507 (act_as, _) = splitKindFunTys act_kind
1508 n_exp_as = length exp_as
1509 n_act_as = length act_as
1511 (env1, tidy_exp_kind) = tidyKind env0 exp_kind
1512 (env2, tidy_act_kind) = tidyKind env1 act_kind
1514 err | n_exp_as < n_act_as -- E.g. [Maybe]
1515 = quotes (ppr ty) <+> ptext SLIT("is not applied to enough type arguments")
1517 -- Now n_exp_as >= n_act_as. In the next two cases,
1518 -- n_exp_as == 0, and hence so is n_act_as
1519 | isLiftedTypeKind exp_kind && isUnliftedTypeKind act_kind
1520 = ptext SLIT("Expecting a lifted type, but") <+> quotes (ppr ty)
1521 <+> ptext SLIT("is unlifted")
1523 | isUnliftedTypeKind exp_kind && isLiftedTypeKind act_kind
1524 = ptext SLIT("Expecting an unlifted type, but") <+> quotes (ppr ty)
1525 <+> ptext SLIT("is lifted")
1527 | otherwise -- E.g. Monad [Int]
1528 = ptext SLIT("Kind mis-match")
1530 more_info = sep [ ptext SLIT("Expected kind") <+>
1531 quotes (pprKind tidy_exp_kind) <> comma,
1532 ptext SLIT("but") <+> quotes (ppr ty) <+>
1533 ptext SLIT("has kind") <+> quotes (pprKind tidy_act_kind)]
1535 failWithTcM (env2, err $$ more_info)
1539 %************************************************************************
1541 \subsection{Checking signature type variables}
1543 %************************************************************************
1545 @checkSigTyVars@ checks that a set of universally quantified type varaibles
1546 are not mentioned in the environment. In particular:
1548 (a) Not mentioned in the type of a variable in the envt
1549 eg the signature for f in this:
1555 Here, f is forced to be monorphic by the free occurence of x.
1557 (d) Not (unified with another type variable that is) in scope.
1558 eg f x :: (r->r) = (\y->y) :: forall a. a->r
1559 when checking the expression type signature, we find that
1560 even though there is nothing in scope whose type mentions r,
1561 nevertheless the type signature for the expression isn't right.
1563 Another example is in a class or instance declaration:
1565 op :: forall b. a -> b
1567 Here, b gets unified with a
1569 Before doing this, the substitution is applied to the signature type variable.
1572 checkSigTyVars :: [TcTyVar] -> TcM ()
1573 checkSigTyVars sig_tvs = check_sig_tyvars emptyVarSet sig_tvs
1575 checkSigTyVarsWrt :: TcTyVarSet -> [TcTyVar] -> TcM ()
1576 -- The extra_tvs can include boxy type variables;
1577 -- e.g. TcMatches.tcCheckExistentialPat
1578 checkSigTyVarsWrt extra_tvs sig_tvs
1579 = do { extra_tvs' <- zonkTcTyVarsAndFV (varSetElems extra_tvs)
1580 ; check_sig_tyvars extra_tvs' sig_tvs }
1583 :: TcTyVarSet -- Global type variables. The universally quantified
1584 -- tyvars should not mention any of these
1585 -- Guaranteed already zonked.
1586 -> [TcTyVar] -- Universally-quantified type variables in the signature
1587 -- Guaranteed to be skolems
1589 check_sig_tyvars extra_tvs []
1591 check_sig_tyvars extra_tvs sig_tvs
1592 = ASSERT( all isSkolemTyVar sig_tvs )
1593 do { gbl_tvs <- tcGetGlobalTyVars
1594 ; traceTc (text "check_sig_tyvars" <+> (vcat [text "sig_tys" <+> ppr sig_tvs,
1595 text "gbl_tvs" <+> ppr gbl_tvs,
1596 text "extra_tvs" <+> ppr extra_tvs]))
1598 ; let env_tvs = gbl_tvs `unionVarSet` extra_tvs
1599 ; ifM (any (`elemVarSet` env_tvs) sig_tvs)
1600 (bleatEscapedTvs env_tvs sig_tvs sig_tvs)
1603 bleatEscapedTvs :: TcTyVarSet -- The global tvs
1604 -> [TcTyVar] -- The possibly-escaping type variables
1605 -> [TcTyVar] -- The zonked versions thereof
1607 -- Complain about escaping type variables
1608 -- We pass a list of type variables, at least one of which
1609 -- escapes. The first list contains the original signature type variable,
1610 -- while the second contains the type variable it is unified to (usually itself)
1611 bleatEscapedTvs globals sig_tvs zonked_tvs
1612 = do { env0 <- tcInitTidyEnv
1613 ; let (env1, tidy_tvs) = tidyOpenTyVars env0 sig_tvs
1614 (env2, tidy_zonked_tvs) = tidyOpenTyVars env1 zonked_tvs
1616 ; (env3, msgs) <- foldlM check (env2, []) (tidy_tvs `zip` tidy_zonked_tvs)
1617 ; failWithTcM (env3, main_msg $$ nest 2 (vcat msgs)) }
1619 main_msg = ptext SLIT("Inferred type is less polymorphic than expected")
1621 check (tidy_env, msgs) (sig_tv, zonked_tv)
1622 | not (zonked_tv `elemVarSet` globals) = return (tidy_env, msgs)
1624 = do { (tidy_env1, globs) <- findGlobals (unitVarSet zonked_tv) tidy_env
1625 ; returnM (tidy_env1, escape_msg sig_tv zonked_tv globs : msgs) }
1627 -----------------------
1628 escape_msg sig_tv zonked_tv globs
1630 = vcat [sep [msg, ptext SLIT("is mentioned in the environment:")],
1631 nest 2 (vcat globs)]
1633 = msg <+> ptext SLIT("escapes")
1634 -- Sigh. It's really hard to give a good error message
1635 -- all the time. One bad case is an existential pattern match.
1636 -- We rely on the "When..." context to help.
1638 msg = ptext SLIT("Quantified type variable") <+> quotes (ppr sig_tv) <+> is_bound_to
1640 | sig_tv == zonked_tv = empty
1641 | otherwise = ptext SLIT("is unified with") <+> quotes (ppr zonked_tv) <+> ptext SLIT("which")
1644 These two context are used with checkSigTyVars
1647 sigCtxt :: Id -> [TcTyVar] -> TcThetaType -> TcTauType
1648 -> TidyEnv -> TcM (TidyEnv, Message)
1649 sigCtxt id sig_tvs sig_theta sig_tau tidy_env
1650 = zonkTcType sig_tau `thenM` \ actual_tau ->
1652 (env1, tidy_sig_tvs) = tidyOpenTyVars tidy_env sig_tvs
1653 (env2, tidy_sig_rho) = tidyOpenType env1 (mkPhiTy sig_theta sig_tau)
1654 (env3, tidy_actual_tau) = tidyOpenType env2 actual_tau
1655 sub_msg = vcat [ptext SLIT("Signature type: ") <+> pprType (mkForAllTys tidy_sig_tvs tidy_sig_rho),
1656 ptext SLIT("Type to generalise:") <+> pprType tidy_actual_tau
1658 msg = vcat [ptext SLIT("When trying to generalise the type inferred for") <+> quotes (ppr id),