2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
10 tcSimplifyInfer, tcSimplifyInferCheck,
11 tcSimplifyCheck, tcSimplifyRestricted,
12 tcSimplifyRuleLhs, tcSimplifyIPs,
13 tcSimplifySuperClasses,
14 tcSimplifyTop, tcSimplifyInteractive,
15 tcSimplifyBracket, tcSimplifyCheckPat,
17 tcSimplifyDeriv, tcSimplifyDefault,
18 bindInstsOfLocalFuns, bindIrreds,
21 #include "HsVersions.h"
23 import {-# SOURCE #-} TcUnify( unifyType )
60 %************************************************************************
64 %************************************************************************
66 --------------------------------------
67 Notes on functional dependencies (a bug)
68 --------------------------------------
75 instance D a b => C a b -- Undecidable
76 -- (Not sure if it's crucial to this eg)
77 f :: C a b => a -> Bool
80 g :: C a b => a -> Bool
83 Here f typechecks, but g does not!! Reason: before doing improvement,
84 we reduce the (C a b1) constraint from the call of f to (D a b1).
86 Here is a more complicated example:
88 | > class Foo a b | a->b
90 | > class Bar a b | a->b
94 | > instance Bar Obj Obj
96 | > instance (Bar a b) => Foo a b
98 | > foo:: (Foo a b) => a -> String
101 | > runFoo:: (forall a b. (Foo a b) => a -> w) -> w
107 | Could not deduce (Bar a b) from the context (Foo a b)
108 | arising from use of `foo' at <interactive>:1
110 | Add (Bar a b) to the expected type of an expression
111 | In the first argument of `runFoo', namely `foo'
112 | In the definition of `it': it = runFoo foo
114 | Why all of the sudden does GHC need the constraint Bar a b? The
115 | function foo didn't ask for that...
117 The trouble is that to type (runFoo foo), GHC has to solve the problem:
119 Given constraint Foo a b
120 Solve constraint Foo a b'
122 Notice that b and b' aren't the same. To solve this, just do
123 improvement and then they are the same. But GHC currently does
128 That is usually fine, but it isn't here, because it sees that Foo a b is
129 not the same as Foo a b', and so instead applies the instance decl for
130 instance Bar a b => Foo a b. And that's where the Bar constraint comes
133 The Right Thing is to improve whenever the constraint set changes at
134 all. Not hard in principle, but it'll take a bit of fiddling to do.
138 --------------------------------------
139 Notes on quantification
140 --------------------------------------
142 Suppose we are about to do a generalisation step.
146 T the type of the RHS
147 C the constraints from that RHS
149 The game is to figure out
151 Q the set of type variables over which to quantify
152 Ct the constraints we will *not* quantify over
153 Cq the constraints we will quantify over
155 So we're going to infer the type
159 and float the constraints Ct further outwards.
161 Here are the things that *must* be true:
163 (A) Q intersect fv(G) = EMPTY limits how big Q can be
164 (B) Q superset fv(Cq union T) \ oclose(fv(G),C) limits how small Q can be
166 (A) says we can't quantify over a variable that's free in the
167 environment. (B) says we must quantify over all the truly free
168 variables in T, else we won't get a sufficiently general type. We do
169 not *need* to quantify over any variable that is fixed by the free
170 vars of the environment G.
172 BETWEEN THESE TWO BOUNDS, ANY Q WILL DO!
174 Example: class H x y | x->y where ...
176 fv(G) = {a} C = {H a b, H c d}
179 (A) Q intersect {a} is empty
180 (B) Q superset {a,b,c,d} \ oclose({a}, C) = {a,b,c,d} \ {a,b} = {c,d}
182 So Q can be {c,d}, {b,c,d}
184 Other things being equal, however, we'd like to quantify over as few
185 variables as possible: smaller types, fewer type applications, more
186 constraints can get into Ct instead of Cq.
189 -----------------------------------------
192 fv(T) the free type vars of T
194 oclose(vs,C) The result of extending the set of tyvars vs
195 using the functional dependencies from C
197 grow(vs,C) The result of extend the set of tyvars vs
198 using all conceivable links from C.
200 E.g. vs = {a}, C = {H [a] b, K (b,Int) c, Eq e}
201 Then grow(vs,C) = {a,b,c}
203 Note that grow(vs,C) `superset` grow(vs,simplify(C))
204 That is, simplfication can only shrink the result of grow.
207 oclose is conservative one way: v `elem` oclose(vs,C) => v is definitely fixed by vs
208 grow is conservative the other way: if v might be fixed by vs => v `elem` grow(vs,C)
211 -----------------------------------------
215 Here's a good way to choose Q:
217 Q = grow( fv(T), C ) \ oclose( fv(G), C )
219 That is, quantify over all variable that that MIGHT be fixed by the
220 call site (which influences T), but which aren't DEFINITELY fixed by
221 G. This choice definitely quantifies over enough type variables,
222 albeit perhaps too many.
224 Why grow( fv(T), C ) rather than fv(T)? Consider
226 class H x y | x->y where ...
231 If we used fv(T) = {c} we'd get the type
233 forall c. H c d => c -> b
235 And then if the fn was called at several different c's, each of
236 which fixed d differently, we'd get a unification error, because
237 d isn't quantified. Solution: quantify d. So we must quantify
238 everything that might be influenced by c.
240 Why not oclose( fv(T), C )? Because we might not be able to see
241 all the functional dependencies yet:
243 class H x y | x->y where ...
244 instance H x y => Eq (T x y) where ...
249 Now oclose(fv(T),C) = {c}, because the functional dependency isn't
250 apparent yet, and that's wrong. We must really quantify over d too.
253 There really isn't any point in quantifying over any more than
254 grow( fv(T), C ), because the call sites can't possibly influence
255 any other type variables.
259 -------------------------------------
261 -------------------------------------
263 It's very hard to be certain when a type is ambiguous. Consider
267 instance H x y => K (x,y)
269 Is this type ambiguous?
270 forall a b. (K (a,b), Eq b) => a -> a
272 Looks like it! But if we simplify (K (a,b)) we get (H a b) and
273 now we see that a fixes b. So we can't tell about ambiguity for sure
274 without doing a full simplification. And even that isn't possible if
275 the context has some free vars that may get unified. Urgle!
277 Here's another example: is this ambiguous?
278 forall a b. Eq (T b) => a -> a
279 Not if there's an insance decl (with no context)
280 instance Eq (T b) where ...
282 You may say of this example that we should use the instance decl right
283 away, but you can't always do that:
285 class J a b where ...
286 instance J Int b where ...
288 f :: forall a b. J a b => a -> a
290 (Notice: no functional dependency in J's class decl.)
291 Here f's type is perfectly fine, provided f is only called at Int.
292 It's premature to complain when meeting f's signature, or even
293 when inferring a type for f.
297 However, we don't *need* to report ambiguity right away. It'll always
298 show up at the call site.... and eventually at main, which needs special
299 treatment. Nevertheless, reporting ambiguity promptly is an excellent thing.
301 So here's the plan. We WARN about probable ambiguity if
303 fv(Cq) is not a subset of oclose(fv(T) union fv(G), C)
305 (all tested before quantification).
306 That is, all the type variables in Cq must be fixed by the the variables
307 in the environment, or by the variables in the type.
309 Notice that we union before calling oclose. Here's an example:
311 class J a b c | a b -> c
315 forall b c. (J a b c) => b -> b
317 Only if we union {a} from G with {b} from T before using oclose,
318 do we see that c is fixed.
320 It's a bit vague exactly which C we should use for this oclose call. If we
321 don't fix enough variables we might complain when we shouldn't (see
322 the above nasty example). Nothing will be perfect. That's why we can
323 only issue a warning.
326 Can we ever be *certain* about ambiguity? Yes: if there's a constraint
328 c in C such that fv(c) intersect (fv(G) union fv(T)) = EMPTY
330 then c is a "bubble"; there's no way it can ever improve, and it's
331 certainly ambiguous. UNLESS it is a constant (sigh). And what about
336 instance H x y => K (x,y)
338 Is this type ambiguous?
339 forall a b. (K (a,b), Eq b) => a -> a
341 Urk. The (Eq b) looks "definitely ambiguous" but it isn't. What we are after
342 is a "bubble" that's a set of constraints
344 Cq = Ca union Cq' st fv(Ca) intersect (fv(Cq') union fv(T) union fv(G)) = EMPTY
346 Hence another idea. To decide Q start with fv(T) and grow it
347 by transitive closure in Cq (no functional dependencies involved).
348 Now partition Cq using Q, leaving the definitely-ambiguous and probably-ok.
349 The definitely-ambiguous can then float out, and get smashed at top level
350 (which squashes out the constants, like Eq (T a) above)
353 --------------------------------------
354 Notes on principal types
355 --------------------------------------
360 f x = let g y = op (y::Int) in True
362 Here the principal type of f is (forall a. a->a)
363 but we'll produce the non-principal type
364 f :: forall a. C Int => a -> a
367 --------------------------------------
368 The need for forall's in constraints
369 --------------------------------------
371 [Exchange on Haskell Cafe 5/6 Dec 2000]
373 class C t where op :: t -> Bool
374 instance C [t] where op x = True
376 p y = (let f :: c -> Bool; f x = op (y >> return x) in f, y ++ [])
377 q y = (y ++ [], let f :: c -> Bool; f x = op (y >> return x) in f)
379 The definitions of p and q differ only in the order of the components in
380 the pair on their right-hand sides. And yet:
382 ghc and "Typing Haskell in Haskell" reject p, but accept q;
383 Hugs rejects q, but accepts p;
384 hbc rejects both p and q;
385 nhc98 ... (Malcolm, can you fill in the blank for us!).
387 The type signature for f forces context reduction to take place, and
388 the results of this depend on whether or not the type of y is known,
389 which in turn depends on which component of the pair the type checker
392 Solution: if y::m a, float out the constraints
393 Monad m, forall c. C (m c)
394 When m is later unified with [], we can solve both constraints.
397 --------------------------------------
398 Notes on implicit parameters
399 --------------------------------------
401 Note [Inheriting implicit parameters]
402 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
407 where f is *not* a top-level binding.
408 From the RHS of f we'll get the constraint (?y::Int).
409 There are two types we might infer for f:
413 (so we get ?y from the context of f's definition), or
415 f :: (?y::Int) => Int -> Int
417 At first you might think the first was better, becuase then
418 ?y behaves like a free variable of the definition, rather than
419 having to be passed at each call site. But of course, the WHOLE
420 IDEA is that ?y should be passed at each call site (that's what
421 dynamic binding means) so we'd better infer the second.
423 BOTTOM LINE: when *inferring types* you *must* quantify
424 over implicit parameters. See the predicate isFreeWhenInferring.
427 Note [Implicit parameters and ambiguity]
428 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
429 What type should we infer for this?
430 f x = (show ?y, x::Int)
431 Since we must quantify over the ?y, the most plausible type is
432 f :: (Show a, ?y::a) => Int -> (String, Int)
433 But notice that the type of the RHS is (String,Int), with no type
434 varibables mentioned at all! The type of f looks ambiguous. But
435 it isn't, because at a call site we might have
436 let ?y = 5::Int in f 7
437 and all is well. In effect, implicit parameters are, well, parameters,
438 so we can take their type variables into account as part of the
439 "tau-tvs" stuff. This is done in the function 'FunDeps.grow'.
442 Question 2: type signatures
443 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
444 BUT WATCH OUT: When you supply a type signature, we can't force you
445 to quantify over implicit parameters. For example:
449 This is perfectly reasonable. We do not want to insist on
451 (?x + 1) :: (?x::Int => Int)
453 That would be silly. Here, the definition site *is* the occurrence site,
454 so the above strictures don't apply. Hence the difference between
455 tcSimplifyCheck (which *does* allow implicit paramters to be inherited)
456 and tcSimplifyCheckBind (which does not).
458 What about when you supply a type signature for a binding?
459 Is it legal to give the following explicit, user type
460 signature to f, thus:
465 At first sight this seems reasonable, but it has the nasty property
466 that adding a type signature changes the dynamic semantics.
469 (let f x = (x::Int) + ?y
470 in (f 3, f 3 with ?y=5)) with ?y = 6
476 in (f 3, f 3 with ?y=5)) with ?y = 6
480 Indeed, simply inlining f (at the Haskell source level) would change the
483 Nevertheless, as Launchbury says (email Oct 01) we can't really give the
484 semantics for a Haskell program without knowing its typing, so if you
485 change the typing you may change the semantics.
487 To make things consistent in all cases where we are *checking* against
488 a supplied signature (as opposed to inferring a type), we adopt the
491 a signature does not need to quantify over implicit params.
493 [This represents a (rather marginal) change of policy since GHC 5.02,
494 which *required* an explicit signature to quantify over all implicit
495 params for the reasons mentioned above.]
497 But that raises a new question. Consider
499 Given (signature) ?x::Int
500 Wanted (inferred) ?x::Int, ?y::Bool
502 Clearly we want to discharge the ?x and float the ?y out. But
503 what is the criterion that distinguishes them? Clearly it isn't
504 what free type variables they have. The Right Thing seems to be
505 to float a constraint that
506 neither mentions any of the quantified type variables
507 nor any of the quantified implicit parameters
509 See the predicate isFreeWhenChecking.
512 Question 3: monomorphism
513 ~~~~~~~~~~~~~~~~~~~~~~~~
514 There's a nasty corner case when the monomorphism restriction bites:
518 The argument above suggests that we *must* generalise
519 over the ?y parameter, to get
520 z :: (?y::Int) => Int,
521 but the monomorphism restriction says that we *must not*, giving
523 Why does the momomorphism restriction say this? Because if you have
525 let z = x + ?y in z+z
527 you might not expect the addition to be done twice --- but it will if
528 we follow the argument of Question 2 and generalise over ?y.
531 Question 4: top level
532 ~~~~~~~~~~~~~~~~~~~~~
533 At the top level, monomorhism makes no sense at all.
536 main = let ?x = 5 in print foo
540 woggle :: (?x :: Int) => Int -> Int
543 We definitely don't want (foo :: Int) with a top-level implicit parameter
544 (?x::Int) becuase there is no way to bind it.
549 (A) Always generalise over implicit parameters
550 Bindings that fall under the monomorphism restriction can't
554 * Inlining remains valid
555 * No unexpected loss of sharing
556 * But simple bindings like
558 will be rejected, unless you add an explicit type signature
559 (to avoid the monomorphism restriction)
560 z :: (?y::Int) => Int
562 This seems unacceptable
564 (B) Monomorphism restriction "wins"
565 Bindings that fall under the monomorphism restriction can't
567 Always generalise over implicit parameters *except* for bindings
568 that fall under the monomorphism restriction
571 * Inlining isn't valid in general
572 * No unexpected loss of sharing
573 * Simple bindings like
575 accepted (get value of ?y from binding site)
577 (C) Always generalise over implicit parameters
578 Bindings that fall under the monomorphism restriction can't
579 be generalised, EXCEPT for implicit parameters
581 * Inlining remains valid
582 * Unexpected loss of sharing (from the extra generalisation)
583 * Simple bindings like
585 accepted (get value of ?y from occurrence sites)
590 None of these choices seems very satisfactory. But at least we should
591 decide which we want to do.
593 It's really not clear what is the Right Thing To Do. If you see
597 would you expect the value of ?y to be got from the *occurrence sites*
598 of 'z', or from the valuue of ?y at the *definition* of 'z'? In the
599 case of function definitions, the answer is clearly the former, but
600 less so in the case of non-fucntion definitions. On the other hand,
601 if we say that we get the value of ?y from the definition site of 'z',
602 then inlining 'z' might change the semantics of the program.
604 Choice (C) really says "the monomorphism restriction doesn't apply
605 to implicit parameters". Which is fine, but remember that every
606 innocent binding 'x = ...' that mentions an implicit parameter in
607 the RHS becomes a *function* of that parameter, called at each
608 use of 'x'. Now, the chances are that there are no intervening 'with'
609 clauses that bind ?y, so a decent compiler should common up all
610 those function calls. So I think I strongly favour (C). Indeed,
611 one could make a similar argument for abolishing the monomorphism
612 restriction altogether.
614 BOTTOM LINE: we choose (B) at present. See tcSimplifyRestricted
618 %************************************************************************
620 \subsection{tcSimplifyInfer}
622 %************************************************************************
624 tcSimplify is called when we *inferring* a type. Here's the overall game plan:
626 1. Compute Q = grow( fvs(T), C )
628 2. Partition C based on Q into Ct and Cq. Notice that ambiguous
629 predicates will end up in Ct; we deal with them at the top level
631 3. Try improvement, using functional dependencies
633 4. If Step 3 did any unification, repeat from step 1
634 (Unification can change the result of 'grow'.)
636 Note: we don't reduce dictionaries in step 2. For example, if we have
637 Eq (a,b), we don't simplify to (Eq a, Eq b). So Q won't be different
638 after step 2. However note that we may therefore quantify over more
639 type variables than we absolutely have to.
641 For the guts, we need a loop, that alternates context reduction and
642 improvement with unification. E.g. Suppose we have
644 class C x y | x->y where ...
646 and tcSimplify is called with:
648 Then improvement unifies a with b, giving
651 If we need to unify anything, we rattle round the whole thing all over
658 -> TcTyVarSet -- fv(T); type vars
660 -> TcM ([TcTyVar], -- Tyvars to quantify (zonked and quantified)
661 [Inst], -- Dict Ids that must be bound here (zonked)
662 TcDictBinds) -- Bindings
663 -- Any free (escaping) Insts are tossed into the environment
668 tcSimplifyInfer doc tau_tvs wanted
669 = do { tau_tvs' <- zonkTcTyVarsAndFV (varSetElems tau_tvs)
670 ; wanted' <- mappM zonkInst wanted -- Zonk before deciding quantified tyvars
671 ; gbl_tvs <- tcGetGlobalTyVars
672 ; let preds = fdPredsOfInsts wanted'
673 qtvs = grow preds tau_tvs' `minusVarSet` oclose preds gbl_tvs
674 (free, bound) = partition (isFreeWhenInferring qtvs) wanted'
675 ; traceTc (text "infer" <+> (ppr preds $$ ppr (grow preds tau_tvs') $$ ppr gbl_tvs $$ ppr (oclose preds gbl_tvs) $$ ppr free $$ ppr bound))
678 -- To make types simple, reduce as much as possible
679 ; let try_me inst = ReduceMe AddSCs
680 ; (irreds, binds) <- checkLoop (mkRedEnv doc try_me []) bound
682 ; qtvs' <- zonkQuantifiedTyVars (varSetElems qtvs)
684 -- We can't abstract over implications
685 ; let (dicts, implics) = partition isDict irreds
686 ; loc <- getInstLoc (ImplicOrigin doc)
687 ; implic_bind <- bindIrreds loc qtvs' dicts implics
689 ; return (qtvs', dicts, binds `unionBags` implic_bind) }
690 -- NB: when we are done, we might have some bindings, but
691 -- the final qtvs might be empty. See Note [NO TYVARS] below.
695 -----------------------------------------------------------
696 -- tcSimplifyInferCheck is used when we know the constraints we are to simplify
697 -- against, but we don't know the type variables over which we are going to quantify.
698 -- This happens when we have a type signature for a mutually recursive group
701 -> TcTyVarSet -- fv(T)
704 -> TcM ([TyVar], -- Fully zonked, and quantified
705 TcDictBinds) -- Bindings
707 tcSimplifyInferCheck loc tau_tvs givens wanteds
708 = do { (irreds, binds) <- innerCheckLoop loc givens wanteds
710 -- Figure out which type variables to quantify over
711 -- You might think it should just be the signature tyvars,
712 -- but in bizarre cases you can get extra ones
713 -- f :: forall a. Num a => a -> a
714 -- f x = fst (g (x, head [])) + 1
716 -- Here we infer g :: forall a b. a -> b -> (b,a)
717 -- We don't want g to be monomorphic in b just because
718 -- f isn't quantified over b.
719 ; let all_tvs = varSetElems (tau_tvs `unionVarSet` tyVarsOfInsts givens)
720 ; all_tvs <- zonkTcTyVarsAndFV all_tvs
721 ; gbl_tvs <- tcGetGlobalTyVars
722 ; let qtvs = varSetElems (all_tvs `minusVarSet` gbl_tvs)
723 -- We could close gbl_tvs, but its not necessary for
724 -- soundness, and it'll only affect which tyvars, not which
725 -- dictionaries, we quantify over
727 ; qtvs' <- zonkQuantifiedTyVars qtvs
729 -- Now we are back to normal (c.f. tcSimplCheck)
730 ; implic_bind <- bindIrreds loc qtvs' givens irreds
732 ; return (qtvs', binds `unionBags` implic_bind) }
735 Note [Squashing methods]
736 ~~~~~~~~~~~~~~~~~~~~~~~~~
737 Be careful if you want to float methods more:
738 truncate :: forall a. RealFrac a => forall b. Integral b => a -> b
739 From an application (truncate f i) we get
742 If we have also have a second occurrence of truncate, we get
745 When simplifying with i,f free, we might still notice that
746 t1=t3; but alas, the binding for t2 (which mentions t1)
747 may continue to float out!
752 class Y a b | a -> b where
755 instance Y [[a]] a where
758 k :: X a -> X a -> X a
760 g :: Num a => [X a] -> [X a]
763 h ys = ys ++ map (k (y [[0]])) xs
765 The excitement comes when simplifying the bindings for h. Initially
766 try to simplify {y @ [[t1]] t2, 0 @ t1}, with initial qtvs = {t2}.
767 From this we get t1:=:t2, but also various bindings. We can't forget
768 the bindings (because of [LOOP]), but in fact t1 is what g is
771 The net effect of [NO TYVARS]
774 isFreeWhenInferring :: TyVarSet -> Inst -> Bool
775 isFreeWhenInferring qtvs inst
776 = isFreeWrtTyVars qtvs inst -- Constrains no quantified vars
777 && isInheritableInst inst -- and no implicit parameter involved
778 -- see Note [Inheriting implicit parameters]
780 {- No longer used (with implication constraints)
781 isFreeWhenChecking :: TyVarSet -- Quantified tyvars
782 -> NameSet -- Quantified implicit parameters
784 isFreeWhenChecking qtvs ips inst
785 = isFreeWrtTyVars qtvs inst
786 && isFreeWrtIPs ips inst
789 isFreeWrtTyVars qtvs inst = tyVarsOfInst inst `disjointVarSet` qtvs
790 isFreeWrtIPs ips inst = not (any (`elemNameSet` ips) (ipNamesOfInst inst))
794 %************************************************************************
796 \subsection{tcSimplifyCheck}
798 %************************************************************************
800 @tcSimplifyCheck@ is used when we know exactly the set of variables
801 we are going to quantify over. For example, a class or instance declaration.
804 -----------------------------------------------------------
805 -- tcSimplifyCheck is used when checking expression type signatures,
806 -- class decls, instance decls etc.
807 tcSimplifyCheck :: InstLoc
808 -> [TcTyVar] -- Quantify over these
811 -> TcM TcDictBinds -- Bindings
812 tcSimplifyCheck loc qtvs givens wanteds
813 = ASSERT( all isTcTyVar qtvs && all isSkolemTyVar qtvs )
814 do { (irreds, binds) <- innerCheckLoop loc givens wanteds
815 ; implic_bind <- bindIrreds loc qtvs givens irreds
816 ; return (binds `unionBags` implic_bind) }
818 -----------------------------------------------------------
819 -- tcSimplifyCheckPat is used for existential pattern match
820 tcSimplifyCheckPat :: InstLoc
821 -> [CoVar] -> Refinement
822 -> [TcTyVar] -- Quantify over these
825 -> TcM TcDictBinds -- Bindings
826 tcSimplifyCheckPat loc co_vars reft qtvs givens wanteds
827 = ASSERT( all isTcTyVar qtvs && all isSkolemTyVar qtvs )
828 do { (irreds, binds) <- innerCheckLoop loc givens wanteds
829 ; implic_bind <- bindIrredsR loc qtvs co_vars reft
831 ; return (binds `unionBags` implic_bind) }
833 -----------------------------------------------------------
834 bindIrreds :: InstLoc -> [TcTyVar]
837 bindIrreds loc qtvs givens irreds
838 = bindIrredsR loc qtvs [] emptyRefinement givens irreds
840 bindIrredsR :: InstLoc -> [TcTyVar] -> [CoVar]
841 -> Refinement -> [Inst] -> [Inst]
843 -- Make a binding that binds 'irreds', by generating an implication
844 -- constraint for them, *and* throwing the constraint into the LIE
845 bindIrredsR loc qtvs co_vars reft givens irreds
849 = do { let givens' = filter isDict givens
850 -- The givens can include methods
851 -- See Note [Pruning the givens in an implication constraint]
853 -- If there are no 'givens', then it's safe to
854 -- partition the 'wanteds' by their qtvs, thereby trimming irreds
855 -- See Note [Freeness and implications]
856 ; irreds' <- if null givens'
858 { let qtv_set = mkVarSet qtvs
859 (frees, real_irreds) = partition (isFreeWrtTyVars qtv_set) irreds
861 ; return real_irreds }
864 ; let all_tvs = qtvs ++ co_vars -- Abstract over all these
865 ; (implics, bind) <- makeImplicationBind loc all_tvs reft givens' irreds'
866 -- This call does the real work
871 makeImplicationBind :: InstLoc -> [TcTyVar] -> Refinement
873 -> TcM ([Inst], TcDictBinds)
874 -- Make a binding that binds 'irreds', by generating an implication
875 -- constraint for them, *and* throwing the constraint into the LIE
876 -- The binding looks like
877 -- (ir1, .., irn) = f qtvs givens
878 -- where f is (evidence for) the new implication constraint
880 -- This binding must line up the 'rhs' in reduceImplication
881 makeImplicationBind loc all_tvs reft
882 givens -- Guaranteed all Dicts
884 | null irreds -- If there are no irreds, we are done
885 = return ([], emptyBag)
886 | otherwise -- Otherwise we must generate a binding
887 = do { uniq <- newUnique
888 ; span <- getSrcSpanM
889 ; let name = mkInternalName uniq (mkVarOcc "ic") (srcSpanStart span)
890 implic_inst = ImplicInst { tci_name = name, tci_reft = reft,
891 tci_tyvars = all_tvs,
893 tci_wanted = irreds, tci_loc = loc }
895 ; let n_irreds = length irreds
896 irred_ids = map instToId irreds
897 tup_ty = mkTupleTy Boxed n_irreds (map idType irred_ids)
898 pat = TuplePat (map nlVarPat irred_ids) Boxed tup_ty
899 rhs = L span (mkHsWrap co (HsVar (instToId implic_inst)))
900 co = mkWpApps (map instToId givens) <.> mkWpTyApps (mkTyVarTys all_tvs)
901 bind | n_irreds==1 = VarBind (head irred_ids) rhs
902 | otherwise = PatBind { pat_lhs = L span pat,
903 pat_rhs = unguardedGRHSs rhs,
905 bind_fvs = placeHolderNames }
906 ; -- pprTrace "Make implic inst" (ppr implic_inst) $
907 return ([implic_inst], unitBag (L span bind)) }
909 -----------------------------------------------------------
912 -> TcM ([Inst], TcDictBinds)
914 topCheckLoop doc wanteds
915 = checkLoop (mkRedEnv doc try_me []) wanteds
917 try_me inst = ReduceMe AddSCs
919 -----------------------------------------------------------
920 innerCheckLoop :: InstLoc
923 -> TcM ([Inst], TcDictBinds)
925 innerCheckLoop inst_loc givens wanteds
926 = checkLoop env wanteds
928 env = mkRedEnv (pprInstLoc inst_loc) try_me givens
930 try_me inst | isMethodOrLit inst = ReduceMe AddSCs
932 -- When checking against a given signature
933 -- we MUST be very gentle: Note [Check gently]
938 We have to very careful about not simplifying too vigorously
943 f :: Show b => T b -> b
946 Inside the pattern match, which binds (a:*, x:a), we know that
948 Hence we have a dictionary for Show [a] available; and indeed we
949 need it. We are going to build an implication contraint
950 forall a. (b~[a]) => Show [a]
951 Later, we will solve this constraint using the knowledge (Show b)
953 But we MUST NOT reduce (Show [a]) to (Show a), else the whole
954 thing becomes insoluble. So we simplify gently (get rid of literals
955 and methods only, plus common up equal things), deferring the real
956 work until top level, when we solve the implication constraint
961 -----------------------------------------------------------
964 -> TcM ([Inst], TcDictBinds)
965 -- Precondition: givens are completely rigid
967 checkLoop env wanteds
968 = do { -- Givens are skolems, so no need to zonk them
969 wanteds' <- mappM zonkInst wanteds
971 ; (improved, binds, irreds) <- reduceContext env wanteds'
973 ; if not improved then
974 return (irreds, binds)
977 -- If improvement did some unification, we go round again.
978 -- We start again with irreds, not wanteds
979 -- Using an instance decl might have introduced a fresh type variable
980 -- which might have been unified, so we'd get an infinite loop
981 -- if we started again with wanteds! See Note [LOOP]
982 { (irreds1, binds1) <- checkLoop env irreds
983 ; return (irreds1, binds `unionBags` binds1) } }
988 class If b t e r | b t e -> r
991 class Lte a b c | a b -> c where lte :: a -> b -> c
993 instance (Lte a b l,If l b a c) => Max a b c
995 Wanted: Max Z (S x) y
997 Then we'll reduce using the Max instance to:
998 (Lte Z (S x) l, If l (S x) Z y)
999 and improve by binding l->T, after which we can do some reduction
1000 on both the Lte and If constraints. What we *can't* do is start again
1001 with (Max Z (S x) y)!
1005 %************************************************************************
1007 tcSimplifySuperClasses
1009 %************************************************************************
1011 Note [SUPERCLASS-LOOP 1]
1012 ~~~~~~~~~~~~~~~~~~~~~~~~
1013 We have to be very, very careful when generating superclasses, lest we
1014 accidentally build a loop. Here's an example:
1018 class S a => C a where { opc :: a -> a }
1019 class S b => D b where { opd :: b -> b }
1021 instance C Int where
1024 instance D Int where
1027 From (instance C Int) we get the constraint set {ds1:S Int, dd:D Int}
1028 Simplifying, we may well get:
1029 $dfCInt = :C ds1 (opd dd)
1032 Notice that we spot that we can extract ds1 from dd.
1034 Alas! Alack! We can do the same for (instance D Int):
1036 $dfDInt = :D ds2 (opc dc)
1040 And now we've defined the superclass in terms of itself.
1042 Solution: never generate a superclass selectors at all when
1043 satisfying the superclass context of an instance declaration.
1045 Two more nasty cases are in
1050 tcSimplifySuperClasses
1055 tcSimplifySuperClasses loc givens sc_wanteds
1056 = do { (irreds, binds1) <- checkLoop env sc_wanteds
1057 ; let (tidy_env, tidy_irreds) = tidyInsts irreds
1058 ; reportNoInstances tidy_env (Just (loc, givens)) tidy_irreds
1061 env = mkRedEnv (pprInstLoc loc) try_me givens
1062 try_me inst = ReduceMe NoSCs
1063 -- Like topCheckLoop, but with NoSCs
1067 %************************************************************************
1069 \subsection{tcSimplifyRestricted}
1071 %************************************************************************
1073 tcSimplifyRestricted infers which type variables to quantify for a
1074 group of restricted bindings. This isn't trivial.
1077 We want to quantify over a to get id :: forall a. a->a
1080 We do not want to quantify over a, because there's an Eq a
1081 constraint, so we get eq :: a->a->Bool (notice no forall)
1084 RHS has type 'tau', whose free tyvars are tau_tvs
1085 RHS has constraints 'wanteds'
1088 Quantify over (tau_tvs \ ftvs(wanteds))
1089 This is bad. The constraints may contain (Monad (ST s))
1090 where we have instance Monad (ST s) where...
1091 so there's no need to be monomorphic in s!
1093 Also the constraint might be a method constraint,
1094 whose type mentions a perfectly innocent tyvar:
1095 op :: Num a => a -> b -> a
1096 Here, b is unconstrained. A good example would be
1098 We want to infer the polymorphic type
1099 foo :: forall b. b -> b
1102 Plan B (cunning, used for a long time up to and including GHC 6.2)
1103 Step 1: Simplify the constraints as much as possible (to deal
1104 with Plan A's problem). Then set
1105 qtvs = tau_tvs \ ftvs( simplify( wanteds ) )
1107 Step 2: Now simplify again, treating the constraint as 'free' if
1108 it does not mention qtvs, and trying to reduce it otherwise.
1109 The reasons for this is to maximise sharing.
1111 This fails for a very subtle reason. Suppose that in the Step 2
1112 a constraint (Foo (Succ Zero) (Succ Zero) b) gets thrown upstairs as 'free'.
1113 In the Step 1 this constraint might have been simplified, perhaps to
1114 (Foo Zero Zero b), AND THEN THAT MIGHT BE IMPROVED, to bind 'b' to 'T'.
1115 This won't happen in Step 2... but that in turn might prevent some other
1116 constraint (Baz [a] b) being simplified (e.g. via instance Baz [a] T where {..})
1117 and that in turn breaks the invariant that no constraints are quantified over.
1119 Test typecheck/should_compile/tc177 (which failed in GHC 6.2) demonstrates
1124 Step 1: Simplify the constraints as much as possible (to deal
1125 with Plan A's problem). Then set
1126 qtvs = tau_tvs \ ftvs( simplify( wanteds ) )
1127 Return the bindings from Step 1.
1130 A note about Plan C (arising from "bug" reported by George Russel March 2004)
1133 instance (HasBinary ty IO) => HasCodedValue ty
1135 foo :: HasCodedValue a => String -> IO a
1137 doDecodeIO :: HasCodedValue a => () -> () -> IO a
1138 doDecodeIO codedValue view
1139 = let { act = foo "foo" } in act
1141 You might think this should work becuase the call to foo gives rise to a constraint
1142 (HasCodedValue t), which can be satisfied by the type sig for doDecodeIO. But the
1143 restricted binding act = ... calls tcSimplifyRestricted, and PlanC simplifies the
1144 constraint using the (rather bogus) instance declaration, and now we are stuffed.
1146 I claim this is not really a bug -- but it bit Sergey as well as George. So here's
1150 Plan D (a variant of plan B)
1151 Step 1: Simplify the constraints as much as possible (to deal
1152 with Plan A's problem), BUT DO NO IMPROVEMENT. Then set
1153 qtvs = tau_tvs \ ftvs( simplify( wanteds ) )
1155 Step 2: Now simplify again, treating the constraint as 'free' if
1156 it does not mention qtvs, and trying to reduce it otherwise.
1158 The point here is that it's generally OK to have too few qtvs; that is,
1159 to make the thing more monomorphic than it could be. We don't want to
1160 do that in the common cases, but in wierd cases it's ok: the programmer
1161 can always add a signature.
1163 Too few qtvs => too many wanteds, which is what happens if you do less
1168 tcSimplifyRestricted -- Used for restricted binding groups
1169 -- i.e. ones subject to the monomorphism restriction
1172 -> [Name] -- Things bound in this group
1173 -> TcTyVarSet -- Free in the type of the RHSs
1174 -> [Inst] -- Free in the RHSs
1175 -> TcM ([TyVar], -- Tyvars to quantify (zonked and quantified)
1176 TcDictBinds) -- Bindings
1177 -- tcSimpifyRestricted returns no constraints to
1178 -- quantify over; by definition there are none.
1179 -- They are all thrown back in the LIE
1181 tcSimplifyRestricted doc top_lvl bndrs tau_tvs wanteds
1182 -- Zonk everything in sight
1183 = do { wanteds' <- mappM zonkInst wanteds
1185 -- 'ReduceMe': Reduce as far as we can. Don't stop at
1186 -- dicts; the idea is to get rid of as many type
1187 -- variables as possible, and we don't want to stop
1188 -- at (say) Monad (ST s), because that reduces
1189 -- immediately, with no constraint on s.
1191 -- BUT do no improvement! See Plan D above
1192 -- HOWEVER, some unification may take place, if we instantiate
1193 -- a method Inst with an equality constraint
1194 ; let env = mkNoImproveRedEnv doc (\i -> ReduceMe AddSCs)
1195 ; (_imp, _binds, constrained_dicts) <- reduceContext env wanteds'
1197 -- Next, figure out the tyvars we will quantify over
1198 ; tau_tvs' <- zonkTcTyVarsAndFV (varSetElems tau_tvs)
1199 ; gbl_tvs' <- tcGetGlobalTyVars
1200 ; constrained_dicts' <- mappM zonkInst constrained_dicts
1202 ; let constrained_tvs' = tyVarsOfInsts constrained_dicts'
1203 qtvs = (tau_tvs' `minusVarSet` oclose (fdPredsOfInsts constrained_dicts) gbl_tvs')
1204 `minusVarSet` constrained_tvs'
1205 ; traceTc (text "tcSimplifyRestricted" <+> vcat [
1206 pprInsts wanteds, pprInsts constrained_dicts',
1208 ppr constrained_tvs', ppr tau_tvs', ppr qtvs ])
1210 -- The first step may have squashed more methods than
1211 -- necessary, so try again, this time more gently, knowing the exact
1212 -- set of type variables to quantify over.
1214 -- We quantify only over constraints that are captured by qtvs;
1215 -- these will just be a subset of non-dicts. This in contrast
1216 -- to normal inference (using isFreeWhenInferring) in which we quantify over
1217 -- all *non-inheritable* constraints too. This implements choice
1218 -- (B) under "implicit parameter and monomorphism" above.
1220 -- Remember that we may need to do *some* simplification, to
1221 -- (for example) squash {Monad (ST s)} into {}. It's not enough
1222 -- just to float all constraints
1224 -- At top level, we *do* squash methods becuase we want to
1225 -- expose implicit parameters to the test that follows
1226 ; let is_nested_group = isNotTopLevel top_lvl
1227 try_me inst | isFreeWrtTyVars qtvs inst,
1228 (is_nested_group || isDict inst) = Stop
1229 | otherwise = ReduceMe AddSCs
1230 env = mkNoImproveRedEnv doc try_me
1231 ; (_imp, binds, irreds) <- reduceContext env wanteds'
1233 -- See "Notes on implicit parameters, Question 4: top level"
1234 ; ASSERT( all (isFreeWrtTyVars qtvs) irreds ) -- None should be captured
1235 if is_nested_group then
1237 else do { let (bad_ips, non_ips) = partition isIPDict irreds
1238 ; addTopIPErrs bndrs bad_ips
1239 ; extendLIEs non_ips }
1241 ; qtvs' <- zonkQuantifiedTyVars (varSetElems qtvs)
1242 ; return (qtvs', binds) }
1246 %************************************************************************
1250 %************************************************************************
1252 On the LHS of transformation rules we only simplify methods and constants,
1253 getting dictionaries. We want to keep all of them unsimplified, to serve
1254 as the available stuff for the RHS of the rule.
1256 Example. Consider the following left-hand side of a rule
1258 f (x == y) (y > z) = ...
1260 If we typecheck this expression we get constraints
1262 d1 :: Ord a, d2 :: Eq a
1264 We do NOT want to "simplify" to the LHS
1266 forall x::a, y::a, z::a, d1::Ord a.
1267 f ((==) (eqFromOrd d1) x y) ((>) d1 y z) = ...
1271 forall x::a, y::a, z::a, d1::Ord a, d2::Eq a.
1272 f ((==) d2 x y) ((>) d1 y z) = ...
1274 Here is another example:
1276 fromIntegral :: (Integral a, Num b) => a -> b
1277 {-# RULES "foo" fromIntegral = id :: Int -> Int #-}
1279 In the rule, a=b=Int, and Num Int is a superclass of Integral Int. But
1280 we *dont* want to get
1282 forall dIntegralInt.
1283 fromIntegral Int Int dIntegralInt (scsel dIntegralInt) = id Int
1285 because the scsel will mess up RULE matching. Instead we want
1287 forall dIntegralInt, dNumInt.
1288 fromIntegral Int Int dIntegralInt dNumInt = id Int
1292 g (x == y) (y == z) = ..
1294 where the two dictionaries are *identical*, we do NOT WANT
1296 forall x::a, y::a, z::a, d1::Eq a
1297 f ((==) d1 x y) ((>) d1 y z) = ...
1299 because that will only match if the dict args are (visibly) equal.
1300 Instead we want to quantify over the dictionaries separately.
1302 In short, tcSimplifyRuleLhs must *only* squash LitInst and MethInts, leaving
1303 all dicts unchanged, with absolutely no sharing. It's simpler to do this
1304 from scratch, rather than further parameterise simpleReduceLoop etc
1307 tcSimplifyRuleLhs :: [Inst] -> TcM ([Inst], TcDictBinds)
1308 tcSimplifyRuleLhs wanteds
1309 = go [] emptyBag wanteds
1312 = return (dicts, binds)
1313 go dicts binds (w:ws)
1315 = go (w:dicts) binds ws
1317 = do { w' <- zonkInst w -- So that (3::Int) does not generate a call
1318 -- to fromInteger; this looks fragile to me
1319 ; lookup_result <- lookupSimpleInst w'
1320 ; case lookup_result of
1321 GenInst ws' rhs -> go dicts (addBind binds w rhs) (ws' ++ ws)
1322 NoInstance -> pprPanic "tcSimplifyRuleLhs" (ppr w)
1326 tcSimplifyBracket is used when simplifying the constraints arising from
1327 a Template Haskell bracket [| ... |]. We want to check that there aren't
1328 any constraints that can't be satisfied (e.g. Show Foo, where Foo has no
1329 Show instance), but we aren't otherwise interested in the results.
1330 Nor do we care about ambiguous dictionaries etc. We will type check
1331 this bracket again at its usage site.
1334 tcSimplifyBracket :: [Inst] -> TcM ()
1335 tcSimplifyBracket wanteds
1336 = do { topCheckLoop doc wanteds
1339 doc = text "tcSimplifyBracket"
1343 %************************************************************************
1345 \subsection{Filtering at a dynamic binding}
1347 %************************************************************************
1352 we must discharge all the ?x constraints from B. We also do an improvement
1353 step; if we have ?x::t1 and ?x::t2 we must unify t1, t2.
1355 Actually, the constraints from B might improve the types in ?x. For example
1357 f :: (?x::Int) => Char -> Char
1360 then the constraint (?x::Int) arising from the call to f will
1361 force the binding for ?x to be of type Int.
1364 tcSimplifyIPs :: [Inst] -- The implicit parameters bound here
1367 -- We need a loop so that we do improvement, and then
1368 -- (next time round) generate a binding to connect the two
1370 -- Here the two ?x's have different types, and improvement
1371 -- makes them the same.
1373 tcSimplifyIPs given_ips wanteds
1374 = do { wanteds' <- mappM zonkInst wanteds
1375 ; given_ips' <- mappM zonkInst given_ips
1376 -- Unusually for checking, we *must* zonk the given_ips
1378 ; let env = mkRedEnv doc try_me given_ips'
1379 ; (improved, binds, irreds) <- reduceContext env wanteds'
1381 ; if not improved then
1382 ASSERT( all is_free irreds )
1383 do { extendLIEs irreds
1386 tcSimplifyIPs given_ips wanteds }
1388 doc = text "tcSimplifyIPs" <+> ppr given_ips
1389 ip_set = mkNameSet (ipNamesOfInsts given_ips)
1390 is_free inst = isFreeWrtIPs ip_set inst
1392 -- Simplify any methods that mention the implicit parameter
1393 try_me inst | is_free inst = Stop
1394 | otherwise = ReduceMe NoSCs
1398 %************************************************************************
1400 \subsection[binds-for-local-funs]{@bindInstsOfLocalFuns@}
1402 %************************************************************************
1404 When doing a binding group, we may have @Insts@ of local functions.
1405 For example, we might have...
1407 let f x = x + 1 -- orig local function (overloaded)
1408 f.1 = f Int -- two instances of f
1413 The point is: we must drop the bindings for @f.1@ and @f.2@ here,
1414 where @f@ is in scope; those @Insts@ must certainly not be passed
1415 upwards towards the top-level. If the @Insts@ were binding-ified up
1416 there, they would have unresolvable references to @f@.
1418 We pass in an @init_lie@ of @Insts@ and a list of locally-bound @Ids@.
1419 For each method @Inst@ in the @init_lie@ that mentions one of the
1420 @Ids@, we create a binding. We return the remaining @Insts@ (in an
1421 @LIE@), as well as the @HsBinds@ generated.
1424 bindInstsOfLocalFuns :: [Inst] -> [TcId] -> TcM TcDictBinds
1425 -- Simlifies only MethodInsts, and generate only bindings of form
1427 -- We're careful not to even generate bindings of the form
1429 -- You'd think that'd be fine, but it interacts with what is
1430 -- arguably a bug in Match.tidyEqnInfo (see notes there)
1432 bindInstsOfLocalFuns wanteds local_ids
1433 | null overloaded_ids
1435 = extendLIEs wanteds `thenM_`
1436 returnM emptyLHsBinds
1439 = do { (irreds, binds) <- checkLoop env for_me
1440 ; extendLIEs not_for_me
1444 env = mkRedEnv doc try_me []
1445 doc = text "bindInsts" <+> ppr local_ids
1446 overloaded_ids = filter is_overloaded local_ids
1447 is_overloaded id = isOverloadedTy (idType id)
1448 (for_me, not_for_me) = partition (isMethodFor overloaded_set) wanteds
1450 overloaded_set = mkVarSet overloaded_ids -- There can occasionally be a lot of them
1451 -- so it's worth building a set, so that
1452 -- lookup (in isMethodFor) is faster
1453 try_me inst | isMethod inst = ReduceMe NoSCs
1458 %************************************************************************
1460 \subsection{Data types for the reduction mechanism}
1462 %************************************************************************
1464 The main control over context reduction is here
1468 = RedEnv { red_doc :: SDoc -- The context
1469 , red_try_me :: Inst -> WhatToDo
1470 , red_improve :: Bool -- True <=> do improvement
1471 , red_givens :: [Inst] -- All guaranteed rigid
1473 -- but see Note [Rigidity]
1474 , red_stack :: (Int, [Inst]) -- Recursion stack (for err msg)
1475 -- See Note [RedStack]
1479 -- The red_givens are rigid so far as cmpInst is concerned.
1480 -- There is one case where they are not totally rigid, namely in tcSimplifyIPs
1481 -- let ?x = e in ...
1482 -- Here, the given is (?x::a), where 'a' is not necy a rigid type
1483 -- But that doesn't affect the comparison, which is based only on mame.
1486 -- The red_stack pair (n,insts) pair is just used for error reporting.
1487 -- 'n' is always the depth of the stack.
1488 -- The 'insts' is the stack of Insts being reduced: to produce X
1489 -- I had to produce Y, to produce Y I had to produce Z, and so on.
1492 mkRedEnv :: SDoc -> (Inst -> WhatToDo) -> [Inst] -> RedEnv
1493 mkRedEnv doc try_me givens
1494 = RedEnv { red_doc = doc, red_try_me = try_me,
1495 red_givens = givens, red_stack = (0,[]),
1496 red_improve = True }
1498 mkNoImproveRedEnv :: SDoc -> (Inst -> WhatToDo) -> RedEnv
1499 -- Do not do improvement; no givens
1500 mkNoImproveRedEnv doc try_me
1501 = RedEnv { red_doc = doc, red_try_me = try_me,
1502 red_givens = [], red_stack = (0,[]),
1503 red_improve = True }
1506 = ReduceMe WantSCs -- Try to reduce this
1507 -- If there's no instance, add the inst to the
1508 -- irreductible ones, but don't produce an error
1509 -- message of any kind.
1510 -- It might be quite legitimate such as (Eq a)!
1512 | Stop -- Return as irreducible unless it can
1513 -- be reduced to a constant in one step
1514 -- Do not add superclasses; see
1516 data WantSCs = NoSCs | AddSCs -- Tells whether we should add the superclasses
1517 -- of a predicate when adding it to the avails
1518 -- The reason for this flag is entirely the super-class loop problem
1519 -- Note [SUPER-CLASS LOOP 1]
1522 %************************************************************************
1524 \subsection[reduce]{@reduce@}
1526 %************************************************************************
1530 reduceContext :: RedEnv
1532 -> TcM (ImprovementDone,
1533 TcDictBinds, -- Dictionary bindings
1534 [Inst]) -- Irreducible
1536 reduceContext env wanteds
1537 = do { traceTc (text "reduceContext" <+> (vcat [
1538 text "----------------------",
1540 text "given" <+> ppr (red_givens env),
1541 text "wanted" <+> ppr wanteds,
1542 text "----------------------"
1545 -- Build the Avail mapping from "givens"
1546 ; init_state <- foldlM addGiven emptyAvails (red_givens env)
1549 ; avails <- reduceList env wanteds init_state
1551 ; let improved = availsImproved avails
1552 ; (binds, irreds) <- extractResults avails wanteds
1554 ; traceTc (text "reduceContext end" <+> (vcat [
1555 text "----------------------",
1557 text "given" <+> ppr (red_givens env),
1558 text "wanted" <+> ppr wanteds,
1560 text "avails" <+> pprAvails avails,
1561 text "improved =" <+> ppr improved,
1562 text "----------------------"
1565 ; return (improved, binds, irreds) }
1567 tcImproveOne :: Avails -> Inst -> TcM ImprovementDone
1568 tcImproveOne avails inst
1569 | not (isDict inst) = return False
1571 = do { inst_envs <- tcGetInstEnvs
1572 ; let eqns = improveOne (classInstances inst_envs)
1573 (dictPred inst, pprInstArising inst)
1574 [ (dictPred p, pprInstArising p)
1575 | p <- availsInsts avails, isDict p ]
1576 -- Avails has all the superclasses etc (good)
1577 -- It also has all the intermediates of the deduction (good)
1578 -- It does not have duplicates (good)
1579 -- NB that (?x::t1) and (?x::t2) will be held separately in avails
1580 -- so that improve will see them separate
1581 ; traceTc (text "improveOne" <+> ppr inst)
1584 unifyEqns :: [(Equation,(PredType,SDoc),(PredType,SDoc))]
1585 -> TcM ImprovementDone
1586 unifyEqns [] = return False
1588 = do { traceTc (ptext SLIT("Improve:") <+> vcat (map pprEquationDoc eqns))
1592 unify ((qtvs, pairs), what1, what2)
1593 = addErrCtxtM (mkEqnMsg what1 what2) $
1594 tcInstTyVars (varSetElems qtvs) `thenM` \ (_, _, tenv) ->
1595 mapM_ (unif_pr tenv) pairs
1596 unif_pr tenv (ty1,ty2) = unifyType (substTy tenv ty1) (substTy tenv ty2)
1598 pprEquationDoc (eqn, (p1,w1), (p2,w2)) = vcat [pprEquation eqn, nest 2 (ppr p1), nest 2 (ppr p2)]
1600 mkEqnMsg (pred1,from1) (pred2,from2) tidy_env
1601 = do { pred1' <- zonkTcPredType pred1; pred2' <- zonkTcPredType pred2
1602 ; let { pred1'' = tidyPred tidy_env pred1'; pred2'' = tidyPred tidy_env pred2' }
1603 ; let msg = vcat [ptext SLIT("When using functional dependencies to combine"),
1604 nest 2 (sep [ppr pred1'' <> comma, nest 2 from1]),
1605 nest 2 (sep [ppr pred2'' <> comma, nest 2 from2])]
1606 ; return (tidy_env, msg) }
1609 The main context-reduction function is @reduce@. Here's its game plan.
1612 reduceList :: RedEnv -> [Inst] -> Avails -> TcM Avails
1613 reduceList env@(RedEnv {red_stack = (n,stk)}) wanteds state
1614 = do { dopts <- getDOpts
1617 dumpTcRn (hang (ptext SLIT("Interesting! Context reduction stack depth") <+> int n)
1618 2 (ifPprDebug (nest 2 (pprStack stk))))
1621 ; if n >= ctxtStkDepth dopts then
1622 failWithTc (reduceDepthErr n stk)
1626 go [] state = return state
1627 go (w:ws) state = do { state' <- reduce (env {red_stack = (n+1, w:stk)}) w state
1630 -- Base case: we're done!
1631 reduce env wanted avails
1632 -- It's the same as an existing inst, or a superclass thereof
1633 | Just avail <- findAvail avails wanted
1637 = case red_try_me env wanted of {
1638 ; Stop -> try_simple (addIrred NoSCs) -- See Note [No superclasses for Stop]
1640 ; ReduceMe want_scs -> -- It should be reduced
1641 reduceInst env avails wanted `thenM` \ (avails, lookup_result) ->
1642 case lookup_result of
1643 NoInstance -> -- No such instance!
1644 -- Add it and its superclasses
1645 addIrred want_scs avails wanted
1647 GenInst [] rhs -> addWanted want_scs avails wanted rhs []
1649 GenInst wanteds' rhs -> do { avails1 <- addIrred NoSCs avails wanted
1650 ; avails2 <- reduceList env wanteds' avails1
1651 ; addWanted want_scs avails2 wanted rhs wanteds' }
1652 -- Temporarily do addIrred *before* the reduceList,
1653 -- which has the effect of adding the thing we are trying
1654 -- to prove to the database before trying to prove the things it
1655 -- needs. See note [RECURSIVE DICTIONARIES]
1656 -- NB: we must not do an addWanted before, because that adds the
1657 -- superclasses too, and thaat can lead to a spurious loop; see
1658 -- the examples in [SUPERCLASS-LOOP]
1659 -- So we do an addIrred before, and then overwrite it afterwards with addWanted
1663 -- First, see if the inst can be reduced to a constant in one step
1664 -- Works well for literals (1::Int) and constant dictionaries (d::Num Int)
1665 -- Don't bother for implication constraints, which take real work
1666 try_simple do_this_otherwise
1667 = do { res <- lookupSimpleInst wanted
1669 GenInst [] rhs -> addWanted AddSCs avails wanted rhs []
1670 other -> do_this_otherwise avails wanted }
1674 Note [SUPERCLASS-LOOP 2]
1675 ~~~~~~~~~~~~~~~~~~~~~~~~
1676 But the above isn't enough. Suppose we are *given* d1:Ord a,
1677 and want to deduce (d2:C [a]) where
1679 class Ord a => C a where
1680 instance Ord [a] => C [a] where ...
1682 Then we'll use the instance decl to deduce C [a] from Ord [a], and then add the
1683 superclasses of C [a] to avails. But we must not overwrite the binding
1684 for Ord [a] (which is obtained from Ord a) with a superclass selection or we'll just
1687 Here's another variant, immortalised in tcrun020
1688 class Monad m => C1 m
1689 class C1 m => C2 m x
1690 instance C2 Maybe Bool
1691 For the instance decl we need to build (C1 Maybe), and it's no good if
1692 we run around and add (C2 Maybe Bool) and its superclasses to the avails
1693 before we search for C1 Maybe.
1695 Here's another example
1696 class Eq b => Foo a b
1697 instance Eq a => Foo [a] a
1701 we'll first deduce that it holds (via the instance decl). We must not
1702 then overwrite the Eq t constraint with a superclass selection!
1704 At first I had a gross hack, whereby I simply did not add superclass constraints
1705 in addWanted, though I did for addGiven and addIrred. This was sub-optimal,
1706 becuase it lost legitimate superclass sharing, and it still didn't do the job:
1707 I found a very obscure program (now tcrun021) in which improvement meant the
1708 simplifier got two bites a the cherry... so something seemed to be an Stop
1709 first time, but reducible next time.
1711 Now we implement the Right Solution, which is to check for loops directly
1712 when adding superclasses. It's a bit like the occurs check in unification.
1715 Note [RECURSIVE DICTIONARIES]
1716 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1718 data D r = ZeroD | SuccD (r (D r));
1720 instance (Eq (r (D r))) => Eq (D r) where
1721 ZeroD == ZeroD = True
1722 (SuccD a) == (SuccD b) = a == b
1725 equalDC :: D [] -> D [] -> Bool;
1728 We need to prove (Eq (D [])). Here's how we go:
1732 by instance decl, holds if
1736 by instance decl of Eq, holds if
1738 where d2 = dfEqList d3
1741 But now we can "tie the knot" to give
1747 and it'll even run! The trick is to put the thing we are trying to prove
1748 (in this case Eq (D []) into the database before trying to prove its
1749 contributing clauses.
1752 %************************************************************************
1754 Reducing a single constraint
1756 %************************************************************************
1759 ---------------------------------------------
1760 reduceInst :: RedEnv -> Avails -> Inst -> TcM (Avails, LookupInstResult)
1761 reduceInst env avails (ImplicInst { tci_tyvars = tvs, tci_reft = reft, tci_loc = loc,
1762 tci_given = extra_givens, tci_wanted = wanteds })
1763 = reduceImplication env avails reft tvs extra_givens wanteds loc
1765 reduceInst env avails other_inst
1766 = do { result <- lookupSimpleInst other_inst
1767 ; return (avails, result) }
1771 ---------------------------------------------
1772 reduceImplication :: RedEnv
1774 -> Refinement -- May refine the givens; often empty
1775 -> [TcTyVar] -- Quantified type variables; all skolems
1776 -> [Inst] -- Extra givens; all rigid
1779 -> TcM (Avails, LookupInstResult)
1782 Suppose we are simplifying the constraint
1783 forall bs. extras => wanted
1784 in the context of an overall simplification problem with givens 'givens',
1785 and refinment 'reft'.
1788 * The refinement is often empty
1790 * The 'extra givens' need not mention any of the quantified type variables
1791 e.g. forall {}. Eq a => Eq [a]
1792 forall {}. C Int => D (Tree Int)
1794 This happens when you have something like
1796 T1 :: Eq a => a -> T a
1799 f x = ...(case x of { T1 v -> v==v })...
1802 -- ToDo: should we instantiate tvs? I think it's not necessary
1804 -- ToDo: what about improvement? There may be some improvement
1805 -- exposed as a result of the simplifications done by reduceList
1806 -- which are discarded if we back off.
1807 -- This is almost certainly Wrong, but we'll fix it when dealing
1808 -- better with equality constraints
1809 reduceImplication env orig_avails reft tvs extra_givens wanteds inst_loc
1810 = do { -- Add refined givens, and the extra givens
1811 (refined_red_givens, avails)
1812 <- if isEmptyRefinement reft then return (red_givens env, orig_avails)
1813 else foldlM (addRefinedGiven reft) ([], orig_avails) (red_givens env)
1814 ; avails <- foldlM addGiven avails extra_givens
1816 -- Solve the sub-problem
1817 ; let try_me inst = ReduceMe AddSCs -- Note [Freeness and implications]
1818 env' = env { red_givens = refined_red_givens ++ extra_givens
1819 , red_try_me = try_me }
1821 ; traceTc (text "reduceImplication" <+> vcat
1823 ppr (red_givens env), ppr extra_givens,
1824 ppr reft, ppr wanteds, ppr avails ])
1825 ; avails <- reduceList env' wanteds avails
1827 -- Extract the binding
1828 ; (binds, irreds) <- extractResults avails wanteds
1830 -- We always discard the extra avails we've generated;
1831 -- but we remember if we have done any (global) improvement
1832 ; let ret_avails = updateImprovement orig_avails avails
1834 ; if isEmptyLHsBinds binds then -- No progress
1835 return (ret_avails, NoInstance)
1837 { (implic_insts, bind) <- makeImplicationBind inst_loc tvs reft extra_givens irreds
1838 -- This binding is useless if the recursive simplification
1839 -- made no progress; but currently we don't try to optimise that
1840 -- case. After all, we only try hard to reduce at top level, or
1841 -- when inferring types.
1843 ; let dict_ids = map instToId extra_givens
1844 co = mkWpTyLams tvs <.> mkWpLams dict_ids <.> WpLet (binds `unionBags` bind)
1845 rhs = mkHsWrap co payload
1846 loc = instLocSpan inst_loc
1847 payload | isSingleton wanteds = HsVar (instToId (head wanteds))
1848 | otherwise = ExplicitTuple (map (L loc . HsVar . instToId) wanteds) Boxed
1850 -- If there are any irreds, we back off and return NoInstance
1851 ; return (ret_avails, GenInst implic_insts (L loc rhs))
1855 Note [Freeness and implications]
1856 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1857 It's hard to say when an implication constraint can be floated out. Consider
1858 forall {} Eq a => Foo [a]
1859 The (Foo [a]) doesn't mention any of the quantified variables, but it
1860 still might be partially satisfied by the (Eq a).
1862 There is a useful special case when it *is* easy to partition the
1863 constraints, namely when there are no 'givens'. Consider
1864 forall {a}. () => Bar b
1865 There are no 'givens', and so there is no reason to capture (Bar b).
1866 We can let it float out. But if there is even one constraint we
1867 must be much more careful:
1868 forall {a}. C a b => Bar (m b)
1869 because (C a b) might have a superclass (D b), from which we might
1870 deduce (Bar [b]) when m later gets instantiated to []. Ha!
1872 Here is an even more exotic example
1874 Now consider the constraint
1875 forall b. D Int b => C Int
1876 We can satisfy the (C Int) from the superclass of D, so we don't want
1877 to float the (C Int) out, even though it mentions no type variable in
1880 Note [Pruning the givens in an implication constraint]
1881 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1882 Suppose we are about to form the implication constraint
1883 forall tvs. Eq a => Ord b
1884 The (Eq a) cannot contribute to the (Ord b), because it has no access to
1885 the type variable 'b'. So we could filter out the (Eq a) from the givens.
1887 Doing so would be a bit tidier, but all the implication constraints get
1888 simplified away by the optimiser, so it's no great win. So I don't take
1889 advantage of that at the moment.
1891 If you do, BE CAREFUL of wobbly type variables.
1894 %************************************************************************
1896 Avails and AvailHow: the pool of evidence
1898 %************************************************************************
1902 data Avails = Avails !ImprovementDone !AvailEnv
1904 type ImprovementDone = Bool -- True <=> some unification has happened
1905 -- so some Irreds might now be reducible
1906 -- keys that are now
1908 type AvailEnv = FiniteMap Inst AvailHow
1910 = IsIrred -- Used for irreducible dictionaries,
1911 -- which are going to be lambda bound
1913 | Given TcId -- Used for dictionaries for which we have a binding
1914 -- e.g. those "given" in a signature
1916 | Rhs -- Used when there is a RHS
1917 (LHsExpr TcId) -- The RHS
1918 [Inst] -- Insts free in the RHS; we need these too
1920 instance Outputable Avails where
1923 pprAvails (Avails imp avails)
1924 = vcat [ ptext SLIT("Avails") <> (if imp then ptext SLIT("[improved]") else empty)
1925 , nest 2 (vcat [sep [ppr inst, nest 2 (equals <+> ppr avail)]
1926 | (inst,avail) <- fmToList avails ])]
1928 instance Outputable AvailHow where
1931 -------------------------
1932 pprAvail :: AvailHow -> SDoc
1933 pprAvail IsIrred = text "Irred"
1934 pprAvail (Given x) = text "Given" <+> ppr x
1935 pprAvail (Rhs rhs bs) = text "Rhs" <+> ppr rhs <+> braces (ppr bs)
1937 -------------------------
1938 extendAvailEnv :: AvailEnv -> Inst -> AvailHow -> AvailEnv
1939 extendAvailEnv env inst avail = addToFM env inst avail
1941 findAvailEnv :: AvailEnv -> Inst -> Maybe AvailHow
1942 findAvailEnv env wanted = lookupFM env wanted
1943 -- NB 1: the Ord instance of Inst compares by the class/type info
1944 -- *not* by unique. So
1945 -- d1::C Int == d2::C Int
1947 emptyAvails :: Avails
1948 emptyAvails = Avails False emptyFM
1950 findAvail :: Avails -> Inst -> Maybe AvailHow
1951 findAvail (Avails _ avails) wanted = findAvailEnv avails wanted
1953 elemAvails :: Inst -> Avails -> Bool
1954 elemAvails wanted (Avails _ avails) = wanted `elemFM` avails
1956 extendAvails :: Avails -> Inst -> AvailHow -> TcM Avails
1958 extendAvails avails@(Avails imp env) inst avail
1959 = do { imp1 <- tcImproveOne avails inst -- Do any improvement
1960 ; return (Avails (imp || imp1) (extendAvailEnv env inst avail)) }
1962 availsInsts :: Avails -> [Inst]
1963 availsInsts (Avails _ avails) = keysFM avails
1965 availsImproved (Avails imp _) = imp
1967 updateImprovement :: Avails -> Avails -> Avails
1968 -- (updateImprovement a1 a2) sets a1's improvement flag from a2
1969 updateImprovement (Avails _ avails1) (Avails imp2 _) = Avails imp2 avails1
1972 Extracting the bindings from a bunch of Avails.
1973 The bindings do *not* come back sorted in dependency order.
1974 We assume that they'll be wrapped in a big Rec, so that the
1975 dependency analyser can sort them out later
1978 extractResults :: Avails
1980 -> TcM ( TcDictBinds, -- Bindings
1981 [Inst]) -- Irreducible ones
1983 extractResults (Avails _ avails) wanteds
1984 = go avails emptyBag [] wanteds
1986 go :: AvailEnv -> TcDictBinds -> [Inst] -> [Inst]
1987 -> TcM (TcDictBinds, [Inst])
1988 go avails binds irreds []
1989 = returnM (binds, irreds)
1991 go avails binds irreds (w:ws)
1992 = case findAvailEnv avails w of
1993 Nothing -> pprTrace "Urk: extractResults" (ppr w) $
1994 go avails binds irreds ws
1996 Just IsIrred -> go (add_given avails w) binds (w:irreds) ws
2000 -> go avails binds irreds ws
2001 -- The sought Id can be one of the givens, via a superclass chain
2002 -- and then we definitely don't want to generate an x=x binding!
2005 -> go avails (addBind binds w (nlHsVar id)) irreds ws
2007 Just (Rhs rhs ws') -> go (add_given avails w) new_binds irreds (ws' ++ ws)
2009 new_binds = addBind binds w rhs
2011 add_given avails w = extendAvailEnv avails w (Given (instToId w))
2013 addBind binds inst rhs = binds `unionBags` unitBag (L (instSpan inst)
2014 (VarBind (instToId inst) rhs))
2018 Note [No superclasses for Stop]
2019 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2020 When we decide not to reduce an Inst -- the 'WhatToDo' --- we still
2021 add it to avails, so that any other equal Insts will be commoned up
2022 right here. However, we do *not* add superclasses. If we have
2025 but a is not bound here, then we *don't* want to derive dn from df
2026 here lest we lose sharing.
2029 addWanted :: WantSCs -> Avails -> Inst -> LHsExpr TcId -> [Inst] -> TcM Avails
2030 addWanted want_scs avails wanted rhs_expr wanteds
2031 = addAvailAndSCs want_scs avails wanted avail
2033 avail = Rhs rhs_expr wanteds
2035 addGiven :: Avails -> Inst -> TcM Avails
2036 addGiven avails given = addAvailAndSCs AddSCs avails given (Given (instToId given))
2037 -- Always add superclasses for 'givens'
2039 -- No ASSERT( not (given `elemAvails` avails) ) because in an instance
2040 -- decl for Ord t we can add both Ord t and Eq t as 'givens',
2041 -- so the assert isn't true
2043 addRefinedGiven :: Refinement -> ([Inst], Avails) -> Inst -> TcM ([Inst], Avails)
2044 addRefinedGiven reft (refined_givens, avails) given
2045 | isDict given -- We sometimes have 'given' methods, but they
2046 -- are always optional, so we can drop them
2047 , let pred = dictPred given
2048 , isRefineablePred pred -- See Note [ImplicInst rigidity]
2049 , Just (co, pred) <- refinePred reft pred
2050 = do { new_given <- newDictBndr (instLoc given) pred
2051 ; let rhs = L (instSpan given) $
2052 HsWrap (WpCo co) (HsVar (instToId given))
2053 ; avails <- addAvailAndSCs AddSCs avails new_given (Rhs rhs [given])
2054 ; return (new_given:refined_givens, avails) }
2055 -- ToDo: the superclasses of the original given all exist in Avails
2056 -- so we could really just cast them, but it's more awkward to do,
2057 -- and hopefully the optimiser will spot the duplicated work
2059 = return (refined_givens, avails)
2062 Note [ImplicInst rigidity]
2063 ~~~~~~~~~~~~~~~~~~~~~~~~~~
2065 C :: forall ab. (Eq a, Ord b) => b -> T a
2067 ...(case x of C v -> <body>)...
2069 From the case (where x::T ty) we'll get an implication constraint
2070 forall b. (Eq ty, Ord b) => <body-constraints>
2071 Now suppose <body-constraints> itself has an implication constraint
2073 forall c. <reft> => <payload>
2074 Then, we can certainly apply the refinement <reft> to the Ord b, becuase it is
2075 existential, but we probably should not apply it to the (Eq ty) because it may
2076 be wobbly. Hence the isRigidInst
2078 @Insts@ are ordered by their class/type info, rather than by their
2079 unique. This allows the context-reduction mechanism to use standard finite
2080 maps to do their stuff. It's horrible that this code is here, rather
2081 than with the Avails handling stuff in TcSimplify
2084 addIrred :: WantSCs -> Avails -> Inst -> TcM Avails
2085 addIrred want_scs avails irred = ASSERT2( not (irred `elemAvails` avails), ppr irred $$ ppr avails )
2086 addAvailAndSCs want_scs avails irred IsIrred
2088 addAvailAndSCs :: WantSCs -> Avails -> Inst -> AvailHow -> TcM Avails
2089 addAvailAndSCs want_scs avails inst avail
2090 | not (isClassDict inst) = extendAvails avails inst avail
2091 | NoSCs <- want_scs = extendAvails avails inst avail
2092 | otherwise = do { traceTc (text "addAvailAndSCs" <+> vcat [ppr inst, ppr deps])
2093 ; avails' <- extendAvails avails inst avail
2094 ; addSCs is_loop avails' inst }
2096 is_loop pred = any (`tcEqType` mkPredTy pred) dep_tys
2097 -- Note: this compares by *type*, not by Unique
2098 deps = findAllDeps (unitVarSet (instToId inst)) avail
2099 dep_tys = map idType (varSetElems deps)
2101 findAllDeps :: IdSet -> AvailHow -> IdSet
2102 -- Find all the Insts that this one depends on
2103 -- See Note [SUPERCLASS-LOOP 2]
2104 -- Watch out, though. Since the avails may contain loops
2105 -- (see Note [RECURSIVE DICTIONARIES]), so we need to track the ones we've seen so far
2106 findAllDeps so_far (Rhs _ kids) = foldl find_all so_far kids
2107 findAllDeps so_far other = so_far
2109 find_all :: IdSet -> Inst -> IdSet
2111 | kid_id `elemVarSet` so_far = so_far
2112 | Just avail <- findAvail avails kid = findAllDeps so_far' avail
2113 | otherwise = so_far'
2115 so_far' = extendVarSet so_far kid_id -- Add the new kid to so_far
2116 kid_id = instToId kid
2118 addSCs :: (TcPredType -> Bool) -> Avails -> Inst -> TcM Avails
2119 -- Add all the superclasses of the Inst to Avails
2120 -- The first param says "dont do this because the original thing
2121 -- depends on this one, so you'd build a loop"
2122 -- Invariant: the Inst is already in Avails.
2124 addSCs is_loop avails dict
2125 = ASSERT( isDict dict )
2126 do { sc_dicts <- newDictBndrs (instLoc dict) sc_theta'
2127 ; foldlM add_sc avails (zipEqual "add_scs" sc_dicts sc_sels) }
2129 (clas, tys) = getDictClassTys dict
2130 (tyvars, sc_theta, sc_sels, _) = classBigSig clas
2131 sc_theta' = substTheta (zipTopTvSubst tyvars tys) sc_theta
2133 add_sc avails (sc_dict, sc_sel)
2134 | is_loop (dictPred sc_dict) = return avails -- See Note [SUPERCLASS-LOOP 2]
2135 | is_given sc_dict = return avails
2136 | otherwise = do { avails' <- extendAvails avails sc_dict (Rhs sc_sel_rhs [dict])
2137 ; addSCs is_loop avails' sc_dict }
2139 sc_sel_rhs = L (instSpan dict) (HsWrap co_fn (HsVar sc_sel))
2140 co_fn = WpApp (instToId dict) <.> mkWpTyApps tys
2142 is_given :: Inst -> Bool
2143 is_given sc_dict = case findAvail avails sc_dict of
2144 Just (Given _) -> True -- Given is cheaper than superclass selection
2148 %************************************************************************
2150 \section{tcSimplifyTop: defaulting}
2152 %************************************************************************
2155 @tcSimplifyTop@ is called once per module to simplify all the constant
2156 and ambiguous Insts.
2158 We need to be careful of one case. Suppose we have
2160 instance Num a => Num (Foo a b) where ...
2162 and @tcSimplifyTop@ is given a constraint (Num (Foo x y)). Then it'll simplify
2163 to (Num x), and default x to Int. But what about y??
2165 It's OK: the final zonking stage should zap y to (), which is fine.
2169 tcSimplifyTop, tcSimplifyInteractive :: [Inst] -> TcM TcDictBinds
2170 tcSimplifyTop wanteds
2171 = tc_simplify_top doc False wanteds
2173 doc = text "tcSimplifyTop"
2175 tcSimplifyInteractive wanteds
2176 = tc_simplify_top doc True wanteds
2178 doc = text "tcSimplifyInteractive"
2180 -- The TcLclEnv should be valid here, solely to improve
2181 -- error message generation for the monomorphism restriction
2182 tc_simplify_top doc interactive wanteds
2183 = do { wanteds <- mapM zonkInst wanteds
2184 ; mapM_ zonkTopTyVar (varSetElems (tyVarsOfInsts wanteds))
2186 ; (irreds1, binds1) <- topCheckLoop doc wanteds
2188 ; if null irreds1 then
2191 -- OK, so there are some errors
2192 { -- Use the defaulting rules to do extra unification
2193 -- NB: irreds are already zonked
2194 ; extended_default <- if interactive then return True
2195 else doptM Opt_ExtendedDefaultRules
2196 ; disambiguate extended_default irreds1 -- Does unification
2197 ; (irreds2, binds2) <- topCheckLoop doc irreds1
2199 -- Deal with implicit parameter
2200 ; let (bad_ips, non_ips) = partition isIPDict irreds2
2201 (ambigs, others) = partition isTyVarDict non_ips
2203 ; topIPErrs bad_ips -- Can arise from f :: Int -> Int
2205 ; addNoInstanceErrs others
2206 ; addTopAmbigErrs ambigs
2208 ; return (binds1 `unionBags` binds2) }}
2211 If a dictionary constrains a type variable which is
2212 * not mentioned in the environment
2213 * and not mentioned in the type of the expression
2214 then it is ambiguous. No further information will arise to instantiate
2215 the type variable; nor will it be generalised and turned into an extra
2216 parameter to a function.
2218 It is an error for this to occur, except that Haskell provided for
2219 certain rules to be applied in the special case of numeric types.
2221 * at least one of its classes is a numeric class, and
2222 * all of its classes are numeric or standard
2223 then the type variable can be defaulted to the first type in the
2224 default-type list which is an instance of all the offending classes.
2226 So here is the function which does the work. It takes the ambiguous
2227 dictionaries and either resolves them (producing bindings) or
2228 complains. It works by splitting the dictionary list by type
2229 variable, and using @disambigOne@ to do the real business.
2231 @disambigOne@ assumes that its arguments dictionaries constrain all
2232 the same type variable.
2234 ADR Comment 20/6/94: I've changed the @CReturnable@ case to default to
2235 @()@ instead of @Int@. I reckon this is the Right Thing to do since
2236 the most common use of defaulting is code like:
2238 _ccall_ foo `seqPrimIO` bar
2240 Since we're not using the result of @foo@, the result if (presumably)
2244 disambiguate :: Bool -> [Inst] -> TcM ()
2245 -- Just does unification to fix the default types
2246 -- The Insts are assumed to be pre-zonked
2247 disambiguate extended_defaulting insts
2248 | null defaultable_groups
2249 = do { traceTc (text "disambigutate" <+> vcat [ppr unaries, ppr bad_tvs, ppr defaultable_groups])
2252 = do { -- Figure out what default types to use
2253 mb_defaults <- getDefaultTys
2254 ; default_tys <- case mb_defaults of
2255 Just tys -> return tys
2256 Nothing -> -- No use-supplied default;
2257 -- use [Integer, Double]
2258 do { integer_ty <- tcMetaTy integerTyConName
2259 ; checkWiredInTyCon doubleTyCon
2260 ; return [integer_ty, doubleTy] }
2261 ; traceTc (text "disambigutate" <+> vcat [ppr unaries, ppr bad_tvs, ppr defaultable_groups])
2262 ; mapM_ (disambigGroup default_tys) defaultable_groups }
2264 unaries :: [(Inst,Class, TcTyVar)] -- (C tv) constraints
2265 bad_tvs :: TcTyVarSet -- Tyvars mentioned by *other* constraints
2266 (unaries, bad_tvs) = getDefaultableDicts insts
2268 -- Group by type variable
2269 defaultable_groups :: [[(Inst,Class,TcTyVar)]]
2270 defaultable_groups = filter defaultable_group (equivClasses cmp_tv unaries)
2271 cmp_tv (_,_,tv1) (_,_,tv2) = tv1 `compare` tv2
2273 defaultable_group :: [(Inst,Class,TcTyVar)] -> Bool
2274 defaultable_group ds@((_,_,tv):_)
2275 = not (isImmutableTyVar tv) -- Note [Avoiding spurious errors]
2276 && not (tv `elemVarSet` bad_tvs)
2277 && defaultable_classes [c | (_,c,_) <- ds]
2278 defaultable_group [] = panic "defaultable_group"
2280 defaultable_classes clss
2281 | extended_defaulting = any isInteractiveClass clss
2282 | otherwise = all isStandardClass clss && any isNumericClass clss
2284 -- In interactive mode, or with -fextended-default-rules,
2285 -- we default Show a to Show () to avoid graututious errors on "show []"
2286 isInteractiveClass cls
2287 = isNumericClass cls
2288 || (classKey cls `elem` [showClassKey, eqClassKey, ordClassKey])
2291 disambigGroup :: [Type] -- The default types
2292 -> [(Inst,Class,TcTyVar)] -- All standard classes of form (C a)
2293 -> TcM () -- Just does unification, to fix the default types
2295 disambigGroup default_tys dicts
2296 = try_default default_tys
2298 (_,_,tyvar) = head dicts -- Should be non-empty
2299 classes = [c | (_,c,_) <- dicts]
2301 try_default [] = return ()
2302 try_default (default_ty : default_tys)
2303 = tryTcLIE_ (try_default default_tys) $
2304 do { tcSimplifyDefault [mkClassPred clas [default_ty] | clas <- classes]
2305 -- This may fail; then the tryTcLIE_ kicks in
2306 -- Failure here is caused by there being no type in the
2307 -- default list which can satisfy all the ambiguous classes.
2308 -- For example, if Real a is reqd, but the only type in the
2309 -- default list is Int.
2311 -- After this we can't fail
2312 ; warnDefault dicts default_ty
2313 ; unifyType default_ty (mkTyVarTy tyvar) }
2316 Note [Avoiding spurious errors]
2317 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2318 When doing the unification for defaulting, we check for skolem
2319 type variables, and simply don't default them. For example:
2320 f = (*) -- Monomorphic
2321 g :: Num a => a -> a
2323 Here, we get a complaint when checking the type signature for g,
2324 that g isn't polymorphic enough; but then we get another one when
2325 dealing with the (Num a) context arising from f's definition;
2326 we try to unify a with Int (to default it), but find that it's
2327 already been unified with the rigid variable from g's type sig
2330 %************************************************************************
2332 \subsection[simple]{@Simple@ versions}
2334 %************************************************************************
2336 Much simpler versions when there are no bindings to make!
2338 @tcSimplifyThetas@ simplifies class-type constraints formed by
2339 @deriving@ declarations and when specialising instances. We are
2340 only interested in the simplified bunch of class/type constraints.
2342 It simplifies to constraints of the form (C a b c) where
2343 a,b,c are type variables. This is required for the context of
2344 instance declarations.
2347 tcSimplifyDeriv :: InstOrigin
2350 -> ThetaType -- Wanted
2351 -> TcM ThetaType -- Needed
2353 tcSimplifyDeriv orig tc tyvars theta
2354 = tcInstTyVars tyvars `thenM` \ (tvs, _, tenv) ->
2355 -- The main loop may do unification, and that may crash if
2356 -- it doesn't see a TcTyVar, so we have to instantiate. Sigh
2357 -- ToDo: what if two of them do get unified?
2358 newDictBndrsO orig (substTheta tenv theta) `thenM` \ wanteds ->
2359 topCheckLoop doc wanteds `thenM` \ (irreds, _) ->
2361 doptM Opt_GlasgowExts `thenM` \ gla_exts ->
2362 doptM Opt_AllowUndecidableInstances `thenM` \ undecidable_ok ->
2364 inst_ty = mkTyConApp tc (mkTyVarTys tvs)
2365 (ok_insts, bad_insts) = partition is_ok_inst irreds
2367 = isDict inst -- Exclude implication consraints
2368 && (isTyVarClassPred pred || (gla_exts && ok_gla_pred pred))
2370 pred = dictPred inst
2372 ok_gla_pred pred = null (checkInstTermination [inst_ty] [pred])
2373 -- See Note [Deriving context]
2375 tv_set = mkVarSet tvs
2376 simpl_theta = map dictPred ok_insts
2377 weird_preds = [pred | pred <- simpl_theta
2378 , not (tyVarsOfPred pred `subVarSet` tv_set)]
2380 -- Check for a bizarre corner case, when the derived instance decl should
2381 -- have form instance C a b => D (T a) where ...
2382 -- Note that 'b' isn't a parameter of T. This gives rise to all sorts
2383 -- of problems; in particular, it's hard to compare solutions for
2384 -- equality when finding the fixpoint. So I just rule it out for now.
2386 rev_env = zipTopTvSubst tvs (mkTyVarTys tyvars)
2387 -- This reverse-mapping is a Royal Pain,
2388 -- but the result should mention TyVars not TcTyVars
2390 -- In effect, the bad and wierd insts cover all of the cases that
2391 -- would make checkValidInstance fail; if it were called right after tcSimplifyDeriv
2392 -- * wierd_preds ensures unambiguous instances (checkAmbiguity in checkValidInstance)
2393 -- * ok_gla_pred ensures termination (checkInstTermination in checkValidInstance)
2394 addNoInstanceErrs bad_insts `thenM_`
2395 mapM_ (addErrTc . badDerivedPred) weird_preds `thenM_`
2396 returnM (substTheta rev_env simpl_theta)
2398 doc = ptext SLIT("deriving classes for a data type")
2401 Note [Deriving context]
2402 ~~~~~~~~~~~~~~~~~~~~~~~
2403 With -fglasgow-exts, we allow things like (C Int a) in the simplified
2404 context for a derived instance declaration, because at a use of this
2405 instance, we might know that a=Bool, and have an instance for (C Int
2408 We nevertheless insist that each predicate meets the termination
2409 conditions. If not, the deriving mechanism generates larger and larger
2410 constraints. Example:
2412 data Seq a = Cons a (Seq (Succ a)) | Nil deriving Show
2414 Note the lack of a Show instance for Succ. First we'll generate
2415 instance (Show (Succ a), Show a) => Show (Seq a)
2417 instance (Show (Succ (Succ a)), Show (Succ a), Show a) => Show (Seq a)
2418 and so on. Instead we want to complain of no instance for (Show (Succ a)).
2422 @tcSimplifyDefault@ just checks class-type constraints, essentially;
2423 used with \tr{default} declarations. We are only interested in
2424 whether it worked or not.
2427 tcSimplifyDefault :: ThetaType -- Wanted; has no type variables in it
2430 tcSimplifyDefault theta
2431 = newDictBndrsO DefaultOrigin theta `thenM` \ wanteds ->
2432 topCheckLoop doc wanteds `thenM` \ (irreds, _) ->
2433 addNoInstanceErrs irreds `thenM_`
2439 doc = ptext SLIT("default declaration")
2443 %************************************************************************
2445 \section{Errors and contexts}
2447 %************************************************************************
2449 ToDo: for these error messages, should we note the location as coming
2450 from the insts, or just whatever seems to be around in the monad just
2454 groupErrs :: ([Inst] -> TcM ()) -- Deal with one group
2455 -> [Inst] -- The offending Insts
2457 -- Group together insts with the same origin
2458 -- We want to report them together in error messages
2460 groupErrs report_err []
2462 groupErrs report_err (inst:insts)
2463 = do_one (inst:friends) `thenM_`
2464 groupErrs report_err others
2467 -- (It may seem a bit crude to compare the error messages,
2468 -- but it makes sure that we combine just what the user sees,
2469 -- and it avoids need equality on InstLocs.)
2470 (friends, others) = partition is_friend insts
2471 loc_msg = showSDoc (pprInstLoc (instLoc inst))
2472 is_friend friend = showSDoc (pprInstLoc (instLoc friend)) == loc_msg
2473 do_one insts = addInstCtxt (instLoc (head insts)) (report_err insts)
2474 -- Add location and context information derived from the Insts
2476 -- Add the "arising from..." part to a message about bunch of dicts
2477 addInstLoc :: [Inst] -> Message -> Message
2478 addInstLoc insts msg = msg $$ nest 2 (pprInstArising (head insts))
2480 addTopIPErrs :: [Name] -> [Inst] -> TcM ()
2481 addTopIPErrs bndrs []
2483 addTopIPErrs bndrs ips
2484 = addErrTcM (tidy_env, mk_msg tidy_ips)
2486 (tidy_env, tidy_ips) = tidyInsts ips
2487 mk_msg ips = vcat [sep [ptext SLIT("Implicit parameters escape from"),
2488 nest 2 (ptext SLIT("the monomorphic top-level binding")
2489 <> plural bndrs <+> ptext SLIT("of")
2490 <+> pprBinders bndrs <> colon)],
2491 nest 2 (vcat (map ppr_ip ips)),
2493 ppr_ip ip = pprPred (dictPred ip) <+> pprInstArising ip
2495 topIPErrs :: [Inst] -> TcM ()
2497 = groupErrs report tidy_dicts
2499 (tidy_env, tidy_dicts) = tidyInsts dicts
2500 report dicts = addErrTcM (tidy_env, mk_msg dicts)
2501 mk_msg dicts = addInstLoc dicts (ptext SLIT("Unbound implicit parameter") <>
2502 plural tidy_dicts <+> pprDictsTheta tidy_dicts)
2504 addNoInstanceErrs :: [Inst] -- Wanted (can include implications)
2506 addNoInstanceErrs insts
2507 = do { let (tidy_env, tidy_insts) = tidyInsts insts
2508 ; reportNoInstances tidy_env Nothing tidy_insts }
2512 -> Maybe (InstLoc, [Inst]) -- Context
2513 -- Nothing => top level
2514 -- Just (d,g) => d describes the construct
2516 -> [Inst] -- What is wanted (can include implications)
2519 reportNoInstances tidy_env mb_what insts
2520 = groupErrs (report_no_instances tidy_env mb_what) insts
2522 report_no_instances tidy_env mb_what insts
2523 = do { inst_envs <- tcGetInstEnvs
2524 ; let (implics, insts1) = partition isImplicInst insts
2525 (insts2, overlaps) = partitionWith (check_overlap inst_envs) insts1
2526 ; traceTc (text "reportNoInstnces" <+> vcat
2527 [ppr implics, ppr insts1, ppr insts2])
2528 ; mapM_ complain_implic implics
2529 ; mapM_ (\doc -> addErrTcM (tidy_env, doc)) overlaps
2530 ; groupErrs complain_no_inst insts2 }
2532 complain_no_inst insts = addErrTcM (tidy_env, mk_no_inst_err insts)
2534 complain_implic inst -- Recurse!
2535 = reportNoInstances tidy_env
2536 (Just (tci_loc inst, tci_given inst))
2539 check_overlap :: (InstEnv,InstEnv) -> Inst -> Either Inst SDoc
2540 -- Right msg => overlap message
2541 -- Left inst => no instance
2542 check_overlap inst_envs wanted
2543 | not (isClassDict wanted) = Left wanted
2545 = case lookupInstEnv inst_envs clas tys of
2546 -- The case of exactly one match and no unifiers means
2547 -- a successful lookup. That can't happen here, becuase
2548 -- dicts only end up here if they didn't match in Inst.lookupInst
2550 ([m],[]) -> pprPanic "reportNoInstance" (ppr wanted)
2552 ([], _) -> Left wanted -- No match
2553 res -> Right (mk_overlap_msg wanted res)
2555 (clas,tys) = getDictClassTys wanted
2557 mk_overlap_msg dict (matches, unifiers)
2558 = vcat [ addInstLoc [dict] ((ptext SLIT("Overlapping instances for")
2559 <+> pprPred (dictPred dict))),
2560 sep [ptext SLIT("Matching instances") <> colon,
2561 nest 2 (vcat [pprInstances ispecs, pprInstances unifiers])],
2562 ASSERT( not (null matches) )
2563 if not (isSingleton matches)
2564 then -- Two or more matches
2566 else -- One match, plus some unifiers
2567 ASSERT( not (null unifiers) )
2568 parens (vcat [ptext SLIT("The choice depends on the instantiation of") <+>
2569 quotes (pprWithCommas ppr (varSetElems (tyVarsOfInst dict))),
2570 ptext SLIT("Use -fallow-incoherent-instances to use the first choice above")])]
2572 ispecs = [ispec | (_, ispec) <- matches]
2574 mk_no_inst_err insts
2575 | null insts = empty
2577 | Just (loc, givens) <- mb_what, -- Nested (type signatures, instance decls)
2578 not (isEmptyVarSet (tyVarsOfInsts insts))
2579 = vcat [ addInstLoc insts $
2580 sep [ ptext SLIT("Could not deduce") <+> pprDictsTheta insts
2581 , nest 2 $ ptext SLIT("from the context") <+> pprDictsTheta givens]
2582 , show_fixes (fix1 loc : fixes2) ]
2584 | otherwise -- Top level
2585 = vcat [ addInstLoc insts $
2586 ptext SLIT("No instance") <> plural insts
2587 <+> ptext SLIT("for") <+> pprDictsTheta insts
2588 , show_fixes fixes2 ]
2591 fix1 loc = sep [ ptext SLIT("add") <+> pprDictsTheta insts
2592 <+> ptext SLIT("to the context of"),
2593 nest 2 (ppr (instLocOrigin loc)) ]
2594 -- I'm not sure it helps to add the location
2595 -- nest 2 (ptext SLIT("at") <+> ppr (instLocSpan loc)) ]
2597 fixes2 | null instance_dicts = []
2598 | otherwise = [sep [ptext SLIT("add an instance declaration for"),
2599 pprDictsTheta instance_dicts]]
2600 instance_dicts = [d | d <- insts, isClassDict d, not (isTyVarDict d)]
2601 -- Insts for which it is worth suggesting an adding an instance declaration
2602 -- Exclude implicit parameters, and tyvar dicts
2604 show_fixes :: [SDoc] -> SDoc
2605 show_fixes [] = empty
2606 show_fixes (f:fs) = sep [ptext SLIT("Possible fix:"),
2607 nest 2 (vcat (f : map (ptext SLIT("or") <+>) fs))]
2609 addTopAmbigErrs dicts
2610 -- Divide into groups that share a common set of ambiguous tyvars
2611 = ifErrsM (return ()) $ -- Only report ambiguity if no other errors happened
2612 -- See Note [Avoiding spurious errors]
2613 mapM_ report (equivClasses cmp [(d, tvs_of d) | d <- tidy_dicts])
2615 (tidy_env, tidy_dicts) = tidyInsts dicts
2617 tvs_of :: Inst -> [TcTyVar]
2618 tvs_of d = varSetElems (tyVarsOfInst d)
2619 cmp (_,tvs1) (_,tvs2) = tvs1 `compare` tvs2
2621 report :: [(Inst,[TcTyVar])] -> TcM ()
2622 report pairs@((inst,tvs) : _) -- The pairs share a common set of ambiguous tyvars
2623 = mkMonomorphismMsg tidy_env tvs `thenM` \ (tidy_env, mono_msg) ->
2624 setSrcSpan (instSpan inst) $
2625 -- the location of the first one will do for the err message
2626 addErrTcM (tidy_env, msg $$ mono_msg)
2628 dicts = map fst pairs
2629 msg = sep [text "Ambiguous type variable" <> plural tvs <+>
2630 pprQuotedList tvs <+> in_msg,
2631 nest 2 (pprDictsInFull dicts)]
2632 in_msg = text "in the constraint" <> plural dicts <> colon
2633 report [] = panic "addTopAmbigErrs"
2636 mkMonomorphismMsg :: TidyEnv -> [TcTyVar] -> TcM (TidyEnv, Message)
2637 -- There's an error with these Insts; if they have free type variables
2638 -- it's probably caused by the monomorphism restriction.
2639 -- Try to identify the offending variable
2640 -- ASSUMPTION: the Insts are fully zonked
2641 mkMonomorphismMsg tidy_env inst_tvs
2642 = findGlobals (mkVarSet inst_tvs) tidy_env `thenM` \ (tidy_env, docs) ->
2643 returnM (tidy_env, mk_msg docs)
2645 mk_msg [] = ptext SLIT("Probable fix: add a type signature that fixes these type variable(s)")
2646 -- This happens in things like
2647 -- f x = show (read "foo")
2648 -- where monomorphism doesn't play any role
2649 mk_msg docs = vcat [ptext SLIT("Possible cause: the monomorphism restriction applied to the following:"),
2653 monomorphism_fix :: SDoc
2654 monomorphism_fix = ptext SLIT("Probable fix:") <+>
2655 (ptext SLIT("give these definition(s) an explicit type signature")
2656 $$ ptext SLIT("or use -fno-monomorphism-restriction"))
2658 warnDefault ups default_ty
2659 = doptM Opt_WarnTypeDefaults `thenM` \ warn_flag ->
2660 addInstCtxt (instLoc (head (dicts))) (warnTc warn_flag warn_msg)
2662 dicts = [d | (d,_,_) <- ups]
2665 (_, tidy_dicts) = tidyInsts dicts
2666 warn_msg = vcat [ptext SLIT("Defaulting the following constraint(s) to type") <+>
2667 quotes (ppr default_ty),
2668 pprDictsInFull tidy_dicts]
2670 -- Used for the ...Thetas variants; all top level
2672 = vcat [ptext SLIT("Can't derive instances where the instance context mentions"),
2673 ptext SLIT("type variables that are not data type parameters"),
2674 nest 2 (ptext SLIT("Offending constraint:") <+> ppr pred)]
2676 reduceDepthErr n stack
2677 = vcat [ptext SLIT("Context reduction stack overflow; size =") <+> int n,
2678 ptext SLIT("Use -fcontext-stack=N to increase stack size to N"),
2679 nest 4 (pprStack stack)]
2681 pprStack stack = vcat (map pprInstInFull stack)