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,
23 #include "HsVersions.h"
25 import {-# SOURCE #-} TcUnify( unifyType )
29 import TcHsSyn ( hsLPatType )
37 import DsUtils -- Big-tuple functions
65 %************************************************************************
69 %************************************************************************
71 --------------------------------------
72 Notes on functional dependencies (a bug)
73 --------------------------------------
80 instance D a b => C a b -- Undecidable
81 -- (Not sure if it's crucial to this eg)
82 f :: C a b => a -> Bool
85 g :: C a b => a -> Bool
88 Here f typechecks, but g does not!! Reason: before doing improvement,
89 we reduce the (C a b1) constraint from the call of f to (D a b1).
91 Here is a more complicated example:
94 > class Foo a b | a->b
96 > class Bar a b | a->b
100 > instance Bar Obj Obj
102 > instance (Bar a b) => Foo a b
104 > foo:: (Foo a b) => a -> String
107 > runFoo:: (forall a b. (Foo a b) => a -> w) -> w
113 Could not deduce (Bar a b) from the context (Foo a b)
114 arising from use of `foo' at <interactive>:1
116 Add (Bar a b) to the expected type of an expression
117 In the first argument of `runFoo', namely `foo'
118 In the definition of `it': it = runFoo foo
120 Why all of the sudden does GHC need the constraint Bar a b? The
121 function foo didn't ask for that...
124 The trouble is that to type (runFoo foo), GHC has to solve the problem:
126 Given constraint Foo a b
127 Solve constraint Foo a b'
129 Notice that b and b' aren't the same. To solve this, just do
130 improvement and then they are the same. But GHC currently does
135 That is usually fine, but it isn't here, because it sees that Foo a b is
136 not the same as Foo a b', and so instead applies the instance decl for
137 instance Bar a b => Foo a b. And that's where the Bar constraint comes
140 The Right Thing is to improve whenever the constraint set changes at
141 all. Not hard in principle, but it'll take a bit of fiddling to do.
143 Note [Choosing which variables to quantify]
144 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
145 Suppose we are about to do a generalisation step. We have in our hand
148 T the type of the RHS
149 C the constraints from that RHS
151 The game is to figure out
153 Q the set of type variables over which to quantify
154 Ct the constraints we will *not* quantify over
155 Cq the constraints we will quantify over
157 So we're going to infer the type
161 and float the constraints Ct further outwards.
163 Here are the things that *must* be true:
165 (A) Q intersect fv(G) = EMPTY limits how big Q can be
166 (B) Q superset fv(Cq union T) \ oclose(fv(G),C) limits how small Q can be
168 (A) says we can't quantify over a variable that's free in the environment.
169 (B) says we must quantify over all the truly free variables in T, else
170 we won't get a sufficiently general type.
172 We do not *need* to quantify over any variable that is fixed by the
173 free vars of the environment G.
175 BETWEEN THESE TWO BOUNDS, ANY Q WILL DO!
177 Example: class H x y | x->y where ...
179 fv(G) = {a} C = {H a b, H c d}
182 (A) Q intersect {a} is empty
183 (B) Q superset {a,b,c,d} \ oclose({a}, C) = {a,b,c,d} \ {a,b} = {c,d}
185 So Q can be {c,d}, {b,c,d}
187 In particular, it's perfectly OK to quantify over more type variables
188 than strictly necessary; there is no need to quantify over 'b', since
189 it is determined by 'a' which is free in the envt, but it's perfectly
190 OK to do so. However we must not quantify over 'a' itself.
192 Other things being equal, however, we'd like to quantify over as few
193 variables as possible: smaller types, fewer type applications, more
194 constraints can get into Ct instead of Cq. Here's a good way to
197 Q = grow( fv(T), C ) \ oclose( fv(G), C )
199 That is, quantify over all variable that that MIGHT be fixed by the
200 call site (which influences T), but which aren't DEFINITELY fixed by
201 G. This choice definitely quantifies over enough type variables,
202 albeit perhaps too many.
204 Why grow( fv(T), C ) rather than fv(T)? Consider
206 class H x y | x->y where ...
211 If we used fv(T) = {c} we'd get the type
213 forall c. H c d => c -> b
215 And then if the fn was called at several different c's, each of
216 which fixed d differently, we'd get a unification error, because
217 d isn't quantified. Solution: quantify d. So we must quantify
218 everything that might be influenced by c.
220 Why not oclose( fv(T), C )? Because we might not be able to see
221 all the functional dependencies yet:
223 class H x y | x->y where ...
224 instance H x y => Eq (T x y) where ...
229 Now oclose(fv(T),C) = {c}, because the functional dependency isn't
230 apparent yet, and that's wrong. We must really quantify over d too.
232 There really isn't any point in quantifying over any more than
233 grow( fv(T), C ), because the call sites can't possibly influence
234 any other type variables.
238 -------------------------------------
240 -------------------------------------
242 It's very hard to be certain when a type is ambiguous. Consider
246 instance H x y => K (x,y)
248 Is this type ambiguous?
249 forall a b. (K (a,b), Eq b) => a -> a
251 Looks like it! But if we simplify (K (a,b)) we get (H a b) and
252 now we see that a fixes b. So we can't tell about ambiguity for sure
253 without doing a full simplification. And even that isn't possible if
254 the context has some free vars that may get unified. Urgle!
256 Here's another example: is this ambiguous?
257 forall a b. Eq (T b) => a -> a
258 Not if there's an insance decl (with no context)
259 instance Eq (T b) where ...
261 You may say of this example that we should use the instance decl right
262 away, but you can't always do that:
264 class J a b where ...
265 instance J Int b where ...
267 f :: forall a b. J a b => a -> a
269 (Notice: no functional dependency in J's class decl.)
270 Here f's type is perfectly fine, provided f is only called at Int.
271 It's premature to complain when meeting f's signature, or even
272 when inferring a type for f.
276 However, we don't *need* to report ambiguity right away. It'll always
277 show up at the call site.... and eventually at main, which needs special
278 treatment. Nevertheless, reporting ambiguity promptly is an excellent thing.
280 So here's the plan. We WARN about probable ambiguity if
282 fv(Cq) is not a subset of oclose(fv(T) union fv(G), C)
284 (all tested before quantification).
285 That is, all the type variables in Cq must be fixed by the the variables
286 in the environment, or by the variables in the type.
288 Notice that we union before calling oclose. Here's an example:
290 class J a b c | a b -> c
294 forall b c. (J a b c) => b -> b
296 Only if we union {a} from G with {b} from T before using oclose,
297 do we see that c is fixed.
299 It's a bit vague exactly which C we should use for this oclose call. If we
300 don't fix enough variables we might complain when we shouldn't (see
301 the above nasty example). Nothing will be perfect. That's why we can
302 only issue a warning.
305 Can we ever be *certain* about ambiguity? Yes: if there's a constraint
307 c in C such that fv(c) intersect (fv(G) union fv(T)) = EMPTY
309 then c is a "bubble"; there's no way it can ever improve, and it's
310 certainly ambiguous. UNLESS it is a constant (sigh). And what about
315 instance H x y => K (x,y)
317 Is this type ambiguous?
318 forall a b. (K (a,b), Eq b) => a -> a
320 Urk. The (Eq b) looks "definitely ambiguous" but it isn't. What we are after
321 is a "bubble" that's a set of constraints
323 Cq = Ca union Cq' st fv(Ca) intersect (fv(Cq') union fv(T) union fv(G)) = EMPTY
325 Hence another idea. To decide Q start with fv(T) and grow it
326 by transitive closure in Cq (no functional dependencies involved).
327 Now partition Cq using Q, leaving the definitely-ambiguous and probably-ok.
328 The definitely-ambiguous can then float out, and get smashed at top level
329 (which squashes out the constants, like Eq (T a) above)
332 --------------------------------------
333 Notes on principal types
334 --------------------------------------
339 f x = let g y = op (y::Int) in True
341 Here the principal type of f is (forall a. a->a)
342 but we'll produce the non-principal type
343 f :: forall a. C Int => a -> a
346 --------------------------------------
347 The need for forall's in constraints
348 --------------------------------------
350 [Exchange on Haskell Cafe 5/6 Dec 2000]
352 class C t where op :: t -> Bool
353 instance C [t] where op x = True
355 p y = (let f :: c -> Bool; f x = op (y >> return x) in f, y ++ [])
356 q y = (y ++ [], let f :: c -> Bool; f x = op (y >> return x) in f)
358 The definitions of p and q differ only in the order of the components in
359 the pair on their right-hand sides. And yet:
361 ghc and "Typing Haskell in Haskell" reject p, but accept q;
362 Hugs rejects q, but accepts p;
363 hbc rejects both p and q;
364 nhc98 ... (Malcolm, can you fill in the blank for us!).
366 The type signature for f forces context reduction to take place, and
367 the results of this depend on whether or not the type of y is known,
368 which in turn depends on which component of the pair the type checker
371 Solution: if y::m a, float out the constraints
372 Monad m, forall c. C (m c)
373 When m is later unified with [], we can solve both constraints.
376 --------------------------------------
377 Notes on implicit parameters
378 --------------------------------------
380 Note [Inheriting implicit parameters]
381 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
386 where f is *not* a top-level binding.
387 From the RHS of f we'll get the constraint (?y::Int).
388 There are two types we might infer for f:
392 (so we get ?y from the context of f's definition), or
394 f :: (?y::Int) => Int -> Int
396 At first you might think the first was better, becuase then
397 ?y behaves like a free variable of the definition, rather than
398 having to be passed at each call site. But of course, the WHOLE
399 IDEA is that ?y should be passed at each call site (that's what
400 dynamic binding means) so we'd better infer the second.
402 BOTTOM LINE: when *inferring types* you *must* quantify
403 over implicit parameters. See the predicate isFreeWhenInferring.
406 Note [Implicit parameters and ambiguity]
407 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
408 Only a *class* predicate can give rise to ambiguity
409 An *implicit parameter* cannot. For example:
410 foo :: (?x :: [a]) => Int
412 is fine. The call site will suppply a particular 'x'
414 Furthermore, the type variables fixed by an implicit parameter
415 propagate to the others. E.g.
416 foo :: (Show a, ?x::[a]) => Int
418 The type of foo looks ambiguous. But it isn't, because at a call site
420 let ?x = 5::Int in foo
421 and all is well. In effect, implicit parameters are, well, parameters,
422 so we can take their type variables into account as part of the
423 "tau-tvs" stuff. This is done in the function 'FunDeps.grow'.
426 Question 2: type signatures
427 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
428 BUT WATCH OUT: When you supply a type signature, we can't force you
429 to quantify over implicit parameters. For example:
433 This is perfectly reasonable. We do not want to insist on
435 (?x + 1) :: (?x::Int => Int)
437 That would be silly. Here, the definition site *is* the occurrence site,
438 so the above strictures don't apply. Hence the difference between
439 tcSimplifyCheck (which *does* allow implicit paramters to be inherited)
440 and tcSimplifyCheckBind (which does not).
442 What about when you supply a type signature for a binding?
443 Is it legal to give the following explicit, user type
444 signature to f, thus:
449 At first sight this seems reasonable, but it has the nasty property
450 that adding a type signature changes the dynamic semantics.
453 (let f x = (x::Int) + ?y
454 in (f 3, f 3 with ?y=5)) with ?y = 6
460 in (f 3, f 3 with ?y=5)) with ?y = 6
464 Indeed, simply inlining f (at the Haskell source level) would change the
467 Nevertheless, as Launchbury says (email Oct 01) we can't really give the
468 semantics for a Haskell program without knowing its typing, so if you
469 change the typing you may change the semantics.
471 To make things consistent in all cases where we are *checking* against
472 a supplied signature (as opposed to inferring a type), we adopt the
475 a signature does not need to quantify over implicit params.
477 [This represents a (rather marginal) change of policy since GHC 5.02,
478 which *required* an explicit signature to quantify over all implicit
479 params for the reasons mentioned above.]
481 But that raises a new question. Consider
483 Given (signature) ?x::Int
484 Wanted (inferred) ?x::Int, ?y::Bool
486 Clearly we want to discharge the ?x and float the ?y out. But
487 what is the criterion that distinguishes them? Clearly it isn't
488 what free type variables they have. The Right Thing seems to be
489 to float a constraint that
490 neither mentions any of the quantified type variables
491 nor any of the quantified implicit parameters
493 See the predicate isFreeWhenChecking.
496 Question 3: monomorphism
497 ~~~~~~~~~~~~~~~~~~~~~~~~
498 There's a nasty corner case when the monomorphism restriction bites:
502 The argument above suggests that we *must* generalise
503 over the ?y parameter, to get
504 z :: (?y::Int) => Int,
505 but the monomorphism restriction says that we *must not*, giving
507 Why does the momomorphism restriction say this? Because if you have
509 let z = x + ?y in z+z
511 you might not expect the addition to be done twice --- but it will if
512 we follow the argument of Question 2 and generalise over ?y.
515 Question 4: top level
516 ~~~~~~~~~~~~~~~~~~~~~
517 At the top level, monomorhism makes no sense at all.
520 main = let ?x = 5 in print foo
524 woggle :: (?x :: Int) => Int -> Int
527 We definitely don't want (foo :: Int) with a top-level implicit parameter
528 (?x::Int) becuase there is no way to bind it.
533 (A) Always generalise over implicit parameters
534 Bindings that fall under the monomorphism restriction can't
538 * Inlining remains valid
539 * No unexpected loss of sharing
540 * But simple bindings like
542 will be rejected, unless you add an explicit type signature
543 (to avoid the monomorphism restriction)
544 z :: (?y::Int) => Int
546 This seems unacceptable
548 (B) Monomorphism restriction "wins"
549 Bindings that fall under the monomorphism restriction can't
551 Always generalise over implicit parameters *except* for bindings
552 that fall under the monomorphism restriction
555 * Inlining isn't valid in general
556 * No unexpected loss of sharing
557 * Simple bindings like
559 accepted (get value of ?y from binding site)
561 (C) Always generalise over implicit parameters
562 Bindings that fall under the monomorphism restriction can't
563 be generalised, EXCEPT for implicit parameters
565 * Inlining remains valid
566 * Unexpected loss of sharing (from the extra generalisation)
567 * Simple bindings like
569 accepted (get value of ?y from occurrence sites)
574 None of these choices seems very satisfactory. But at least we should
575 decide which we want to do.
577 It's really not clear what is the Right Thing To Do. If you see
581 would you expect the value of ?y to be got from the *occurrence sites*
582 of 'z', or from the valuue of ?y at the *definition* of 'z'? In the
583 case of function definitions, the answer is clearly the former, but
584 less so in the case of non-fucntion definitions. On the other hand,
585 if we say that we get the value of ?y from the definition site of 'z',
586 then inlining 'z' might change the semantics of the program.
588 Choice (C) really says "the monomorphism restriction doesn't apply
589 to implicit parameters". Which is fine, but remember that every
590 innocent binding 'x = ...' that mentions an implicit parameter in
591 the RHS becomes a *function* of that parameter, called at each
592 use of 'x'. Now, the chances are that there are no intervening 'with'
593 clauses that bind ?y, so a decent compiler should common up all
594 those function calls. So I think I strongly favour (C). Indeed,
595 one could make a similar argument for abolishing the monomorphism
596 restriction altogether.
598 BOTTOM LINE: we choose (B) at present. See tcSimplifyRestricted
602 %************************************************************************
604 \subsection{tcSimplifyInfer}
606 %************************************************************************
608 tcSimplify is called when we *inferring* a type. Here's the overall game plan:
610 1. Compute Q = grow( fvs(T), C )
612 2. Partition C based on Q into Ct and Cq. Notice that ambiguous
613 predicates will end up in Ct; we deal with them at the top level
615 3. Try improvement, using functional dependencies
617 4. If Step 3 did any unification, repeat from step 1
618 (Unification can change the result of 'grow'.)
620 Note: we don't reduce dictionaries in step 2. For example, if we have
621 Eq (a,b), we don't simplify to (Eq a, Eq b). So Q won't be different
622 after step 2. However note that we may therefore quantify over more
623 type variables than we absolutely have to.
625 For the guts, we need a loop, that alternates context reduction and
626 improvement with unification. E.g. Suppose we have
628 class C x y | x->y where ...
630 and tcSimplify is called with:
632 Then improvement unifies a with b, giving
635 If we need to unify anything, we rattle round the whole thing all over
642 -> TcTyVarSet -- fv(T); type vars
644 -> TcM ([TcTyVar], -- Tyvars to quantify (zonked and quantified)
645 [Inst], -- Dict Ids that must be bound here (zonked)
646 TcDictBinds) -- Bindings
647 -- Any free (escaping) Insts are tossed into the environment
652 tcSimplifyInfer doc tau_tvs wanted
653 = do { tau_tvs1 <- zonkTcTyVarsAndFV (varSetElems tau_tvs)
654 ; wanted' <- mapM zonkInst wanted -- Zonk before deciding quantified tyvars
655 ; gbl_tvs <- tcGetGlobalTyVars
656 ; let preds1 = fdPredsOfInsts wanted'
657 gbl_tvs1 = oclose preds1 gbl_tvs
658 qtvs = growInstsTyVars wanted' tau_tvs1 `minusVarSet` gbl_tvs1
659 -- See Note [Choosing which variables to quantify]
661 -- To maximise sharing, remove from consideration any
662 -- constraints that don't mention qtvs at all
663 ; let (free, bound) = partition (isFreeWhenInferring qtvs) wanted'
666 -- To make types simple, reduce as much as possible
667 ; traceTc (text "infer" <+> (ppr preds1 $$ ppr (growInstsTyVars wanted' tau_tvs1) $$ ppr gbl_tvs $$
668 ppr gbl_tvs1 $$ ppr free $$ ppr bound))
669 ; (irreds1, binds1) <- tryHardCheckLoop doc bound
671 -- Note [Inference and implication constraints]
672 ; let want_dict d = tyVarsOfInst d `intersectsVarSet` qtvs
673 ; (irreds2, binds2) <- approximateImplications doc want_dict irreds1
675 -- Now work out all over again which type variables to quantify,
676 -- exactly in the same way as before, but starting from irreds2. Why?
677 -- a) By now improvment may have taken place, and we must *not*
678 -- quantify over any variable free in the environment
679 -- tc137 (function h inside g) is an example
681 -- b) Do not quantify over constraints that *now* do not
682 -- mention quantified type variables, because they are
683 -- simply ambiguous (or might be bound further out). Example:
684 -- f :: Eq b => a -> (a, b)
686 -- From the RHS of g we get the MethodInst f77 :: alpha -> (alpha, beta)
687 -- We decide to quantify over 'alpha' alone, but free1 does not include f77
688 -- because f77 mentions 'alpha'. Then reducing leaves only the (ambiguous)
689 -- constraint (Eq beta), which we dump back into the free set
690 -- See test tcfail181
692 -- c) irreds may contain type variables not previously mentioned,
693 -- e.g. instance D a x => Foo [a]
695 -- Then after simplifying we'll get (D a x), and x is fresh
696 -- We must quantify over x else it'll be totally unbound
697 ; tau_tvs2 <- zonkTcTyVarsAndFV (varSetElems tau_tvs1)
698 ; gbl_tvs2 <- zonkTcTyVarsAndFV (varSetElems gbl_tvs1)
699 -- Note that we start from gbl_tvs1
700 -- We use tcGetGlobalTyVars, then oclose wrt preds2, because
701 -- we've already put some of the original preds1 into frees
702 -- E.g. wanteds = C a b (where a->b)
705 -- Then b is fixed by gbl_tvs, so (C a b) will be in free, and
706 -- irreds2 will be empty. But we don't want to generalise over b!
707 ; let preds2 = fdPredsOfInsts irreds2 -- irreds2 is zonked
708 qtvs = growInstsTyVars irreds2 tau_tvs2 `minusVarSet` oclose preds2 gbl_tvs2
709 ---------------------------------------------------
710 -- BUG WARNING: there's a nasty bug lurking here
711 -- fdPredsOfInsts may return preds that mention variables quantified in
712 -- one of the implication constraints in irreds2; and that is clearly wrong:
713 -- we might quantify over too many variables through accidental capture
714 ---------------------------------------------------
715 ; let (free, irreds3) = partition (isFreeWhenInferring qtvs) irreds2
718 -- Turn the quantified meta-type variables into real type variables
719 ; qtvs2 <- zonkQuantifiedTyVars (varSetElems qtvs)
721 -- We can't abstract over any remaining unsolved
722 -- implications so instead just float them outwards. Ugh.
723 ; let (q_dicts0, implics) = partition isAbstractableInst irreds3
724 ; loc <- getInstLoc (ImplicOrigin doc)
725 ; implic_bind <- bindIrreds loc qtvs2 q_dicts0 implics
727 -- Prepare equality instances for quantification
728 ; let (q_eqs0,q_dicts) = partition isEqInst q_dicts0
729 ; q_eqs <- mapM finalizeEqInst q_eqs0
731 ; return (qtvs2, q_eqs ++ q_dicts, binds1 `unionBags` binds2 `unionBags` implic_bind) }
732 -- NB: when we are done, we might have some bindings, but
733 -- the final qtvs might be empty. See Note [NO TYVARS] below.
735 approximateImplications :: SDoc -> (Inst -> Bool) -> [Inst] -> TcM ([Inst], TcDictBinds)
736 -- Note [Inference and implication constraints]
737 -- Given a bunch of Dict and ImplicInsts, try to approximate the implications by
738 -- - fetching any dicts inside them that are free
739 -- - using those dicts as cruder constraints, to solve the implications
740 -- - returning the extra ones too
742 approximateImplications doc want_dict irreds
744 = return (irreds, emptyBag)
746 = do { extra_dicts' <- mapM cloneDict extra_dicts
747 ; tryHardCheckLoop doc (extra_dicts' ++ irreds) }
748 -- By adding extra_dicts', we make them
749 -- available to solve the implication constraints
751 extra_dicts = get_dicts (filter isImplicInst irreds)
753 get_dicts :: [Inst] -> [Inst] -- Returns only Dicts
754 -- Find the wanted constraints in implication constraints that satisfy
755 -- want_dict, and are not bound by forall's in the constraint itself
756 get_dicts ds = concatMap get_dict ds
758 get_dict d@(Dict {}) | want_dict d = [d]
760 get_dict (ImplicInst {tci_tyvars = tvs, tci_wanted = wanteds})
761 = [ d | let tv_set = mkVarSet tvs
762 , d <- get_dicts wanteds
763 , not (tyVarsOfInst d `intersectsVarSet` tv_set)]
764 get_dict i@(EqInst {}) | want_dict i = [i]
766 get_dict other = pprPanic "approximateImplications" (ppr other)
769 Note [Inference and implication constraints]
770 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
771 Suppose we have a wanted implication constraint (perhaps arising from
772 a nested pattern match) like
774 and we are now trying to quantify over 'a' when inferring the type for
775 a function. In principle it's possible that there might be an instance
776 instance (C a, E a) => D [a]
777 so the context (E a) would suffice. The Right Thing is to abstract over
778 the implication constraint, but we don't do that (a) because it'll be
779 surprising to programmers and (b) because we don't have the machinery to deal
780 with 'given' implications.
782 So our best approximation is to make (D [a]) part of the inferred
783 context, so we can use that to discharge the implication. Hence
784 the strange function get_dicts in approximateImplications.
786 The common cases are more clear-cut, when we have things like
788 Here, abstracting over (C b) is not an approximation at all -- but see
789 Note [Freeness and implications].
791 See Trac #1430 and test tc228.
795 -----------------------------------------------------------
796 -- tcSimplifyInferCheck is used when we know the constraints we are to simplify
797 -- against, but we don't know the type variables over which we are going to quantify.
798 -- This happens when we have a type signature for a mutually recursive group
801 -> TcTyVarSet -- fv(T)
804 -> TcM ([TyVar], -- Fully zonked, and quantified
805 TcDictBinds) -- Bindings
807 tcSimplifyInferCheck loc tau_tvs givens wanteds
808 = do { traceTc (text "tcSimplifyInferCheck <-" <+> ppr wanteds)
809 ; (irreds, binds) <- gentleCheckLoop loc givens wanteds
811 -- Figure out which type variables to quantify over
812 -- You might think it should just be the signature tyvars,
813 -- but in bizarre cases you can get extra ones
814 -- f :: forall a. Num a => a -> a
815 -- f x = fst (g (x, head [])) + 1
817 -- Here we infer g :: forall a b. a -> b -> (b,a)
818 -- We don't want g to be monomorphic in b just because
819 -- f isn't quantified over b.
820 ; let all_tvs = varSetElems (tau_tvs `unionVarSet` tyVarsOfInsts givens)
821 ; all_tvs <- zonkTcTyVarsAndFV all_tvs
822 ; gbl_tvs <- tcGetGlobalTyVars
823 ; let qtvs = varSetElems (all_tvs `minusVarSet` gbl_tvs)
824 -- We could close gbl_tvs, but its not necessary for
825 -- soundness, and it'll only affect which tyvars, not which
826 -- dictionaries, we quantify over
828 ; qtvs' <- zonkQuantifiedTyVars qtvs
830 -- Now we are back to normal (c.f. tcSimplCheck)
831 ; implic_bind <- bindIrreds loc qtvs' givens irreds
833 ; traceTc (text "tcSimplifyInferCheck ->" <+> ppr (implic_bind))
834 ; return (qtvs', binds `unionBags` implic_bind) }
837 Note [Squashing methods]
838 ~~~~~~~~~~~~~~~~~~~~~~~~~
839 Be careful if you want to float methods more:
840 truncate :: forall a. RealFrac a => forall b. Integral b => a -> b
841 From an application (truncate f i) we get
844 If we have also have a second occurrence of truncate, we get
847 When simplifying with i,f free, we might still notice that
848 t1=t3; but alas, the binding for t2 (which mentions t1)
849 may continue to float out!
854 class Y a b | a -> b where
857 instance Y [[a]] a where
860 k :: X a -> X a -> X a
862 g :: Num a => [X a] -> [X a]
865 h ys = ys ++ map (k (y [[0]])) xs
867 The excitement comes when simplifying the bindings for h. Initially
868 try to simplify {y @ [[t1]] t2, 0 @ t1}, with initial qtvs = {t2}.
869 From this we get t1~t2, but also various bindings. We can't forget
870 the bindings (because of [LOOP]), but in fact t1 is what g is
873 The net effect of [NO TYVARS]
876 isFreeWhenInferring :: TyVarSet -> Inst -> Bool
877 isFreeWhenInferring qtvs inst
878 = isFreeWrtTyVars qtvs inst -- Constrains no quantified vars
879 && isInheritableInst inst -- and no implicit parameter involved
880 -- see Note [Inheriting implicit parameters]
882 {- No longer used (with implication constraints)
883 isFreeWhenChecking :: TyVarSet -- Quantified tyvars
884 -> NameSet -- Quantified implicit parameters
886 isFreeWhenChecking qtvs ips inst
887 = isFreeWrtTyVars qtvs inst
888 && isFreeWrtIPs ips inst
891 isFreeWrtTyVars :: VarSet -> Inst -> Bool
892 isFreeWrtTyVars qtvs inst = tyVarsOfInst inst `disjointVarSet` qtvs
893 isFreeWrtIPs :: NameSet -> Inst -> Bool
894 isFreeWrtIPs ips inst = not (any (`elemNameSet` ips) (ipNamesOfInst inst))
898 %************************************************************************
900 \subsection{tcSimplifyCheck}
902 %************************************************************************
904 @tcSimplifyCheck@ is used when we know exactly the set of variables
905 we are going to quantify over. For example, a class or instance declaration.
908 -----------------------------------------------------------
909 -- tcSimplifyCheck is used when checking expression type signatures,
910 -- class decls, instance decls etc.
911 tcSimplifyCheck :: InstLoc
912 -> [TcTyVar] -- Quantify over these
915 -> TcM TcDictBinds -- Bindings
916 tcSimplifyCheck loc qtvs givens wanteds
917 = ASSERT( all isTcTyVar qtvs && all isSkolemTyVar qtvs )
918 do { traceTc (text "tcSimplifyCheck")
919 ; (irreds, binds) <- gentleCheckLoop loc givens wanteds
920 ; implic_bind <- bindIrreds loc qtvs givens irreds
921 ; return (binds `unionBags` implic_bind) }
923 -----------------------------------------------------------
924 -- tcSimplifyCheckPat is used for existential pattern match
925 tcSimplifyCheckPat :: InstLoc
926 -> [TcTyVar] -- Quantify over these
929 -> TcM TcDictBinds -- Bindings
930 tcSimplifyCheckPat loc qtvs givens wanteds
931 = ASSERT( all isTcTyVar qtvs && all isSkolemTyVar qtvs )
932 do { traceTc (text "tcSimplifyCheckPat")
933 ; (irreds, binds) <- gentleCheckLoop loc givens wanteds
934 ; implic_bind <- bindIrredsR loc qtvs givens irreds
935 ; return (binds `unionBags` implic_bind) }
937 -----------------------------------------------------------
938 bindIrreds :: InstLoc -> [TcTyVar]
941 bindIrreds loc qtvs givens irreds
942 = bindIrredsR loc qtvs givens irreds
944 bindIrredsR :: InstLoc -> [TcTyVar] -> [Inst] -> [Inst] -> TcM TcDictBinds
945 -- Make a binding that binds 'irreds', by generating an implication
946 -- constraint for them, *and* throwing the constraint into the LIE
947 bindIrredsR loc qtvs givens irreds
951 = do { let givens' = filter isAbstractableInst givens
952 -- The givens can (redundantly) include methods
953 -- We want to retain both EqInsts and Dicts
954 -- There should be no implicadtion constraints
955 -- See Note [Pruning the givens in an implication constraint]
957 -- If there are no 'givens', then it's safe to
958 -- partition the 'wanteds' by their qtvs, thereby trimming irreds
959 -- See Note [Freeness and implications]
960 ; irreds' <- if null givens'
962 { let qtv_set = mkVarSet qtvs
963 (frees, real_irreds) = partition (isFreeWrtTyVars qtv_set) irreds
965 ; return real_irreds }
968 ; (implics, bind) <- makeImplicationBind loc qtvs givens' irreds'
969 -- This call does the real work
970 -- If irreds' is empty, it does something sensible
975 makeImplicationBind :: InstLoc -> [TcTyVar]
977 -> TcM ([Inst], TcDictBinds)
978 -- Make a binding that binds 'irreds', by generating an implication
979 -- constraint for them.
981 -- The binding looks like
982 -- (ir1, .., irn) = f qtvs givens
983 -- where f is (evidence for) the new implication constraint
984 -- f :: forall qtvs. givens => (ir1, .., irn)
985 -- qtvs includes coercion variables
987 -- This binding must line up the 'rhs' in reduceImplication
988 makeImplicationBind loc all_tvs
989 givens -- Guaranteed all Dicts or EqInsts
991 | null irreds -- If there are no irreds, we are done
992 = return ([], emptyBag)
993 | otherwise -- Otherwise we must generate a binding
994 = do { uniq <- newUnique
995 ; span <- getSrcSpanM
996 ; let (eq_givens, dict_givens) = partition isEqInst givens
998 -- extract equality binders
999 eq_cotvs = map eqInstType eq_givens
1001 -- make the implication constraint instance
1002 name = mkInternalName uniq (mkVarOcc "ic") span
1003 implic_inst = ImplicInst { tci_name = name,
1004 tci_tyvars = all_tvs,
1005 tci_given = eq_givens ++ dict_givens,
1006 -- same order as binders
1007 tci_wanted = irreds,
1010 -- create binders for the irreducible dictionaries
1011 dict_irreds = filter (not . isEqInst) irreds
1012 dict_irred_ids = map instToId dict_irreds
1013 lpat = mkBigLHsPatTup (map (L span . VarPat) dict_irred_ids)
1015 -- create the binding
1016 rhs = L span (mkHsWrap co (HsVar (instToId implic_inst)))
1017 co = mkWpApps (map instToId dict_givens)
1018 <.> mkWpTyApps eq_cotvs
1019 <.> mkWpTyApps (mkTyVarTys all_tvs)
1020 bind | [dict_irred_id] <- dict_irred_ids
1021 = VarBind dict_irred_id rhs
1023 = PatBind { pat_lhs = lpat
1024 , pat_rhs = unguardedGRHSs rhs
1025 , pat_rhs_ty = hsLPatType lpat
1026 , bind_fvs = placeHolderNames
1029 ; traceTc $ text "makeImplicationBind" <+> ppr implic_inst
1030 ; return ([implic_inst], unitBag (L span bind))
1033 -----------------------------------------------------------
1034 tryHardCheckLoop :: SDoc
1036 -> TcM ([Inst], TcDictBinds)
1038 tryHardCheckLoop doc wanteds
1039 = do { (irreds,binds) <- checkLoop (mkInferRedEnv doc try_me) wanteds
1040 ; return (irreds,binds)
1044 -- Here's the try-hard bit
1046 -----------------------------------------------------------
1047 gentleCheckLoop :: InstLoc
1050 -> TcM ([Inst], TcDictBinds)
1052 gentleCheckLoop inst_loc givens wanteds
1053 = do { (irreds,binds) <- checkLoop env wanteds
1054 ; return (irreds,binds)
1057 env = mkRedEnv (pprInstLoc inst_loc) try_me givens
1059 try_me inst | isMethodOrLit inst = ReduceMe
1061 -- When checking against a given signature
1062 -- we MUST be very gentle: Note [Check gently]
1064 gentleInferLoop :: SDoc -> [Inst]
1065 -> TcM ([Inst], TcDictBinds)
1066 gentleInferLoop doc wanteds
1067 = do { (irreds, binds) <- checkLoop env wanteds
1068 ; return (irreds, binds) }
1070 env = mkInferRedEnv doc try_me
1071 try_me inst | isMethodOrLit inst = ReduceMe
1076 ~~~~~~~~~~~~~~~~~~~~
1077 We have to very careful about not simplifying too vigorously
1082 f :: Show b => T b -> b
1083 f (MkT x) = show [x]
1085 Inside the pattern match, which binds (a:*, x:a), we know that
1087 Hence we have a dictionary for Show [a] available; and indeed we
1088 need it. We are going to build an implication contraint
1089 forall a. (b~[a]) => Show [a]
1090 Later, we will solve this constraint using the knowledge (Show b)
1092 But we MUST NOT reduce (Show [a]) to (Show a), else the whole
1093 thing becomes insoluble. So we simplify gently (get rid of literals
1094 and methods only, plus common up equal things), deferring the real
1095 work until top level, when we solve the implication constraint
1096 with tryHardCheckLooop.
1100 -----------------------------------------------------------
1103 -> TcM ([Inst], TcDictBinds)
1104 -- Precondition: givens are completely rigid
1105 -- Postcondition: returned Insts are zonked
1107 checkLoop env wanteds
1109 where go env wanteds
1110 = do { -- We do need to zonk the givens; cf Note [Zonking RedEnv]
1111 ; env' <- zonkRedEnv env
1112 ; wanteds' <- zonkInsts wanteds
1114 ; (improved, tybinds, binds, irreds)
1115 <- reduceContext env' wanteds'
1116 ; execTcTyVarBinds tybinds
1118 ; if null irreds || not improved then
1119 return (irreds, binds)
1122 -- If improvement did some unification, we go round again.
1123 -- We start again with irreds, not wanteds
1124 -- Using an instance decl might have introduced a fresh type
1125 -- variable which might have been unified, so we'd get an
1126 -- infinite loop if we started again with wanteds!
1128 { (irreds1, binds1) <- go env' irreds
1129 ; return (irreds1, binds `unionBags` binds1) } }
1132 Note [Zonking RedEnv]
1133 ~~~~~~~~~~~~~~~~~~~~~
1134 It might appear as if the givens in RedEnv are always rigid, but that is not
1135 necessarily the case for programs involving higher-rank types that have class
1136 contexts constraining the higher-rank variables. An example from tc237 in the
1139 class Modular s a | s -> a
1141 wim :: forall a w. Integral a
1142 => a -> (forall s. Modular s a => M s w) -> w
1143 wim i k = error "urk"
1145 test5 :: (Modular s a, Integral a) => M s a
1148 test4 = wim 4 test4'
1150 Notice how the variable 'a' of (Modular s a) in the rank-2 type of wim is
1151 quantified further outside. When type checking test4, we have to check
1152 whether the signature of test5 is an instance of
1154 (forall s. Modular s a => M s w)
1156 Consequently, we will get (Modular s t_a), where t_a is a TauTv into the
1159 Given the FD of Modular in this example, class improvement will instantiate
1160 t_a to 'a', where 'a' is the skolem from test5's signatures (due to the
1161 Modular s a predicate in that signature). If we don't zonk (Modular s t_a) in
1162 the givens, we will get into a loop as improveOne uses the unification engine
1163 Unify.tcUnifyTys, which doesn't know about mutable type variables.
1168 class If b t e r | b t e -> r
1171 class Lte a b c | a b -> c where lte :: a -> b -> c
1173 instance (Lte a b l,If l b a c) => Max a b c
1175 Wanted: Max Z (S x) y
1177 Then we'll reduce using the Max instance to:
1178 (Lte Z (S x) l, If l (S x) Z y)
1179 and improve by binding l->T, after which we can do some reduction
1180 on both the Lte and If constraints. What we *can't* do is start again
1181 with (Max Z (S x) y)!
1185 %************************************************************************
1187 tcSimplifySuperClasses
1189 %************************************************************************
1191 Note [SUPERCLASS-LOOP 1]
1192 ~~~~~~~~~~~~~~~~~~~~~~~~
1193 We have to be very, very careful when generating superclasses, lest we
1194 accidentally build a loop. Here's an example:
1198 class S a => C a where { opc :: a -> a }
1199 class S b => D b where { opd :: b -> b }
1201 instance C Int where
1204 instance D Int where
1207 From (instance C Int) we get the constraint set {ds1:S Int, dd:D Int}
1208 Simplifying, we may well get:
1209 $dfCInt = :C ds1 (opd dd)
1212 Notice that we spot that we can extract ds1 from dd.
1214 Alas! Alack! We can do the same for (instance D Int):
1216 $dfDInt = :D ds2 (opc dc)
1220 And now we've defined the superclass in terms of itself.
1221 Two more nasty cases are in
1226 - Satisfy the superclass context *all by itself*
1227 (tcSimplifySuperClasses)
1228 - And do so completely; i.e. no left-over constraints
1229 to mix with the constraints arising from method declarations
1232 Note [Recursive instances and superclases]
1233 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1234 Consider this code, which arises in the context of "Scrap Your
1235 Boilerplate with Class".
1239 instance Sat (ctx Char) => Data ctx Char
1240 instance (Sat (ctx [a]), Data ctx a) => Data ctx [a]
1242 class Data Maybe a => Foo a
1244 instance Foo t => Sat (Maybe t)
1246 instance Data Maybe a => Foo a
1247 instance Foo a => Foo [a]
1250 In the instance for Foo [a], when generating evidence for the superclasses
1251 (ie in tcSimplifySuperClasses) we need a superclass (Data Maybe [a]).
1252 Using the instance for Data, we therefore need
1253 (Sat (Maybe [a], Data Maybe a)
1254 But we are given (Foo a), and hence its superclass (Data Maybe a).
1255 So that leaves (Sat (Maybe [a])). Using the instance for Sat means
1256 we need (Foo [a]). And that is the very dictionary we are bulding
1257 an instance for! So we must put that in the "givens". So in this
1259 Given: Foo a, Foo [a]
1260 Watend: Data Maybe [a]
1262 BUT we must *not not not* put the *superclasses* of (Foo [a]) in
1263 the givens, which is what 'addGiven' would normally do. Why? Because
1264 (Data Maybe [a]) is the superclass, so we'd "satisfy" the wanted
1265 by selecting a superclass from Foo [a], which simply makes a loop.
1267 On the other hand we *must* put the superclasses of (Foo a) in
1268 the givens, as you can see from the derivation described above.
1270 Conclusion: in the very special case of tcSimplifySuperClasses
1271 we have one 'given' (namely the "this" dictionary) whose superclasses
1272 must not be added to 'givens' by addGiven.
1274 There is a complication though. Suppose there are equalities
1275 instance (Eq a, a~b) => Num (a,b)
1276 Then we normalise the 'givens' wrt the equalities, so the original
1277 given "this" dictionary is cast to one of a different type. So it's a
1278 bit trickier than before to identify the "special" dictionary whose
1279 superclasses must not be added. See test
1280 indexed-types/should_run/EqInInstance
1282 We need a persistent property of the dictionary to record this
1283 special-ness. Current I'm using the InstLocOrigin (a bit of a hack,
1284 but cool), which is maintained by dictionary normalisation.
1285 Specifically, the InstLocOrigin is
1287 then the no-superclass thing kicks in. WATCH OUT if you fiddle
1291 tcSimplifySuperClasses
1293 -> Inst -- The dict whose superclasses
1294 -- are being figured out
1298 tcSimplifySuperClasses loc this givens sc_wanteds
1299 = do { traceTc (text "tcSimplifySuperClasses")
1301 -- Note [Recursive instances and superclases]
1302 ; no_sc_loc <- getInstLoc NoScOrigin
1303 ; let no_sc_this = setInstLoc this no_sc_loc
1305 ; let env = RedEnv { red_doc = pprInstLoc loc,
1306 red_try_me = try_me,
1307 red_givens = no_sc_this : givens,
1309 red_improve = False } -- No unification vars
1312 ; (irreds,binds1) <- checkLoop env sc_wanteds
1313 ; let (tidy_env, tidy_irreds) = tidyInsts irreds
1314 ; reportNoInstances tidy_env (Just (loc, givens)) [] tidy_irreds
1317 try_me _ = ReduceMe -- Try hard, so we completely solve the superclass
1318 -- constraints right here. See Note [SUPERCLASS-LOOP 1]
1322 %************************************************************************
1324 \subsection{tcSimplifyRestricted}
1326 %************************************************************************
1328 tcSimplifyRestricted infers which type variables to quantify for a
1329 group of restricted bindings. This isn't trivial.
1332 We want to quantify over a to get id :: forall a. a->a
1335 We do not want to quantify over a, because there's an Eq a
1336 constraint, so we get eq :: a->a->Bool (notice no forall)
1339 RHS has type 'tau', whose free tyvars are tau_tvs
1340 RHS has constraints 'wanteds'
1343 Quantify over (tau_tvs \ ftvs(wanteds))
1344 This is bad. The constraints may contain (Monad (ST s))
1345 where we have instance Monad (ST s) where...
1346 so there's no need to be monomorphic in s!
1348 Also the constraint might be a method constraint,
1349 whose type mentions a perfectly innocent tyvar:
1350 op :: Num a => a -> b -> a
1351 Here, b is unconstrained. A good example would be
1353 We want to infer the polymorphic type
1354 foo :: forall b. b -> b
1357 Plan B (cunning, used for a long time up to and including GHC 6.2)
1358 Step 1: Simplify the constraints as much as possible (to deal
1359 with Plan A's problem). Then set
1360 qtvs = tau_tvs \ ftvs( simplify( wanteds ) )
1362 Step 2: Now simplify again, treating the constraint as 'free' if
1363 it does not mention qtvs, and trying to reduce it otherwise.
1364 The reasons for this is to maximise sharing.
1366 This fails for a very subtle reason. Suppose that in the Step 2
1367 a constraint (Foo (Succ Zero) (Succ Zero) b) gets thrown upstairs as 'free'.
1368 In the Step 1 this constraint might have been simplified, perhaps to
1369 (Foo Zero Zero b), AND THEN THAT MIGHT BE IMPROVED, to bind 'b' to 'T'.
1370 This won't happen in Step 2... but that in turn might prevent some other
1371 constraint (Baz [a] b) being simplified (e.g. via instance Baz [a] T where {..})
1372 and that in turn breaks the invariant that no constraints are quantified over.
1374 Test typecheck/should_compile/tc177 (which failed in GHC 6.2) demonstrates
1379 Step 1: Simplify the constraints as much as possible (to deal
1380 with Plan A's problem). Then set
1381 qtvs = tau_tvs \ ftvs( simplify( wanteds ) )
1382 Return the bindings from Step 1.
1385 A note about Plan C (arising from "bug" reported by George Russel March 2004)
1388 instance (HasBinary ty IO) => HasCodedValue ty
1390 foo :: HasCodedValue a => String -> IO a
1392 doDecodeIO :: HasCodedValue a => () -> () -> IO a
1393 doDecodeIO codedValue view
1394 = let { act = foo "foo" } in act
1396 You might think this should work becuase the call to foo gives rise to a constraint
1397 (HasCodedValue t), which can be satisfied by the type sig for doDecodeIO. But the
1398 restricted binding act = ... calls tcSimplifyRestricted, and PlanC simplifies the
1399 constraint using the (rather bogus) instance declaration, and now we are stuffed.
1401 I claim this is not really a bug -- but it bit Sergey as well as George. So here's
1405 Plan D (a variant of plan B)
1406 Step 1: Simplify the constraints as much as possible (to deal
1407 with Plan A's problem), BUT DO NO IMPROVEMENT. Then set
1408 qtvs = tau_tvs \ ftvs( simplify( wanteds ) )
1410 Step 2: Now simplify again, treating the constraint as 'free' if
1411 it does not mention qtvs, and trying to reduce it otherwise.
1413 The point here is that it's generally OK to have too few qtvs; that is,
1414 to make the thing more monomorphic than it could be. We don't want to
1415 do that in the common cases, but in wierd cases it's ok: the programmer
1416 can always add a signature.
1418 Too few qtvs => too many wanteds, which is what happens if you do less
1423 tcSimplifyRestricted -- Used for restricted binding groups
1424 -- i.e. ones subject to the monomorphism restriction
1427 -> [Name] -- Things bound in this group
1428 -> TcTyVarSet -- Free in the type of the RHSs
1429 -> [Inst] -- Free in the RHSs
1430 -> TcM ([TyVar], -- Tyvars to quantify (zonked and quantified)
1431 TcDictBinds) -- Bindings
1432 -- tcSimpifyRestricted returns no constraints to
1433 -- quantify over; by definition there are none.
1434 -- They are all thrown back in the LIE
1436 tcSimplifyRestricted doc top_lvl bndrs tau_tvs wanteds
1437 -- Zonk everything in sight
1438 = do { traceTc (text "tcSimplifyRestricted")
1439 ; wanteds_z <- zonkInsts wanteds
1441 -- 'ReduceMe': Reduce as far as we can. Don't stop at
1442 -- dicts; the idea is to get rid of as many type
1443 -- variables as possible, and we don't want to stop
1444 -- at (say) Monad (ST s), because that reduces
1445 -- immediately, with no constraint on s.
1447 -- BUT do no improvement! See Plan D above
1448 -- HOWEVER, some unification may take place, if we instantiate
1449 -- a method Inst with an equality constraint
1450 ; let env = mkNoImproveRedEnv doc (\_ -> ReduceMe)
1451 ; (_imp, _tybinds, _binds, constrained_dicts)
1452 <- reduceContext env wanteds_z
1454 -- Next, figure out the tyvars we will quantify over
1455 ; tau_tvs' <- zonkTcTyVarsAndFV (varSetElems tau_tvs)
1456 ; gbl_tvs' <- tcGetGlobalTyVars
1457 ; constrained_dicts' <- zonkInsts constrained_dicts
1459 ; let qtvs1 = tau_tvs' `minusVarSet` oclose (fdPredsOfInsts constrained_dicts) gbl_tvs'
1460 -- As in tcSimplifyInfer
1462 -- Do not quantify over constrained type variables:
1463 -- this is the monomorphism restriction
1464 constrained_tvs' = tyVarsOfInsts constrained_dicts'
1465 qtvs = qtvs1 `minusVarSet` constrained_tvs'
1466 pp_bndrs = pprWithCommas (quotes . ppr) bndrs
1469 ; warn_mono <- doptM Opt_WarnMonomorphism
1470 ; warnTc (warn_mono && (constrained_tvs' `intersectsVarSet` qtvs1))
1471 (vcat[ ptext (sLit "the Monomorphism Restriction applies to the binding")
1472 <> plural bndrs <+> ptext (sLit "for") <+> pp_bndrs,
1473 ptext (sLit "Consider giving a type signature for") <+> pp_bndrs])
1475 ; traceTc (text "tcSimplifyRestricted" <+> vcat [
1476 pprInsts wanteds, pprInsts constrained_dicts',
1478 ppr constrained_tvs', ppr tau_tvs', ppr qtvs ])
1480 -- The first step may have squashed more methods than
1481 -- necessary, so try again, this time more gently, knowing the exact
1482 -- set of type variables to quantify over.
1484 -- We quantify only over constraints that are captured by qtvs;
1485 -- these will just be a subset of non-dicts. This in contrast
1486 -- to normal inference (using isFreeWhenInferring) in which we quantify over
1487 -- all *non-inheritable* constraints too. This implements choice
1488 -- (B) under "implicit parameter and monomorphism" above.
1490 -- Remember that we may need to do *some* simplification, to
1491 -- (for example) squash {Monad (ST s)} into {}. It's not enough
1492 -- just to float all constraints
1494 -- At top level, we *do* squash methods becuase we want to
1495 -- expose implicit parameters to the test that follows
1496 ; let is_nested_group = isNotTopLevel top_lvl
1497 try_me inst | isFreeWrtTyVars qtvs inst,
1498 (is_nested_group || isDict inst) = Stop
1499 | otherwise = ReduceMe
1500 env = mkNoImproveRedEnv doc try_me
1501 ; (_imp, tybinds, binds, irreds) <- reduceContext env wanteds_z
1502 ; execTcTyVarBinds tybinds
1504 -- See "Notes on implicit parameters, Question 4: top level"
1505 ; ASSERT( all (isFreeWrtTyVars qtvs) irreds ) -- None should be captured
1506 if is_nested_group then
1508 else do { let (bad_ips, non_ips) = partition isIPDict irreds
1509 ; addTopIPErrs bndrs bad_ips
1510 ; extendLIEs non_ips }
1512 ; qtvs' <- zonkQuantifiedTyVars (varSetElems qtvs)
1513 ; return (qtvs', binds) }
1517 %************************************************************************
1521 %************************************************************************
1523 On the LHS of transformation rules we only simplify methods and constants,
1524 getting dictionaries. We want to keep all of them unsimplified, to serve
1525 as the available stuff for the RHS of the rule.
1527 Example. Consider the following left-hand side of a rule
1529 f (x == y) (y > z) = ...
1531 If we typecheck this expression we get constraints
1533 d1 :: Ord a, d2 :: Eq a
1535 We do NOT want to "simplify" to the LHS
1537 forall x::a, y::a, z::a, d1::Ord a.
1538 f ((==) (eqFromOrd d1) x y) ((>) d1 y z) = ...
1542 forall x::a, y::a, z::a, d1::Ord a, d2::Eq a.
1543 f ((==) d2 x y) ((>) d1 y z) = ...
1545 Here is another example:
1547 fromIntegral :: (Integral a, Num b) => a -> b
1548 {-# RULES "foo" fromIntegral = id :: Int -> Int #-}
1550 In the rule, a=b=Int, and Num Int is a superclass of Integral Int. But
1551 we *dont* want to get
1553 forall dIntegralInt.
1554 fromIntegral Int Int dIntegralInt (scsel dIntegralInt) = id Int
1556 because the scsel will mess up RULE matching. Instead we want
1558 forall dIntegralInt, dNumInt.
1559 fromIntegral Int Int dIntegralInt dNumInt = id Int
1563 g (x == y) (y == z) = ..
1565 where the two dictionaries are *identical*, we do NOT WANT
1567 forall x::a, y::a, z::a, d1::Eq a
1568 f ((==) d1 x y) ((>) d1 y z) = ...
1570 because that will only match if the dict args are (visibly) equal.
1571 Instead we want to quantify over the dictionaries separately.
1573 In short, tcSimplifyRuleLhs must *only* squash LitInst and MethInts, leaving
1574 all dicts unchanged, with absolutely no sharing. It's simpler to do this
1575 from scratch, rather than further parameterise simpleReduceLoop etc.
1576 Simpler, maybe, but alas not simple (see Trac #2494)
1578 * Type errors may give rise to an (unsatisfiable) equality constraint
1580 * Applications of a higher-rank function on the LHS may give
1581 rise to an implication constraint, esp if there are unsatisfiable
1582 equality constraints inside.
1585 tcSimplifyRuleLhs :: [Inst] -> TcM ([Inst], TcDictBinds)
1586 tcSimplifyRuleLhs wanteds
1587 = do { wanteds' <- zonkInsts wanteds
1589 -- Simplify equalities
1590 -- It's important to do this: Trac #3346 for example
1591 ; (_, wanteds'', tybinds, binds1) <- tcReduceEqs [] wanteds'
1592 ; execTcTyVarBinds tybinds
1594 -- Simplify other constraints
1595 ; (irreds, binds2) <- go [] emptyBag wanteds''
1597 -- Report anything that is left
1598 ; let (dicts, bad_irreds) = partition isDict irreds
1599 ; traceTc (text "tcSimplifyrulelhs" <+> pprInsts bad_irreds)
1600 ; addNoInstanceErrs (nub bad_irreds)
1601 -- The nub removes duplicates, which has
1602 -- not happened otherwise (see notes above)
1604 ; return (dicts, binds1 `unionBags` binds2) }
1606 go :: [Inst] -> TcDictBinds -> [Inst] -> TcM ([Inst], TcDictBinds)
1608 = return (irreds, binds)
1609 go irreds binds (w:ws)
1611 = go (w:irreds) binds ws
1612 | isImplicInst w -- Have a go at reducing the implication
1613 = do { (binds1, irreds1) <- reduceImplication red_env w
1614 ; let (bad_irreds, ok_irreds) = partition isImplicInst irreds1
1615 ; go (bad_irreds ++ irreds)
1616 (binds `unionBags` binds1)
1619 = do { w' <- zonkInst w -- So that (3::Int) does not generate a call
1620 -- to fromInteger; this looks fragile to me
1621 ; lookup_result <- lookupSimpleInst w'
1622 ; case lookup_result of
1623 NoInstance -> go (w:irreds) binds ws
1624 GenInst ws' rhs -> go irreds binds' (ws' ++ ws)
1626 binds' = addInstToDictBind binds w rhs
1629 -- Sigh: we need to reduce inside implications
1630 red_env = mkInferRedEnv doc try_me
1631 doc = ptext (sLit "Implication constraint in RULE lhs")
1632 try_me inst | isMethodOrLit inst = ReduceMe
1633 | otherwise = Stop -- Be gentle
1636 tcSimplifyBracket is used when simplifying the constraints arising from
1637 a Template Haskell bracket [| ... |]. We want to check that there aren't
1638 any constraints that can't be satisfied (e.g. Show Foo, where Foo has no
1639 Show instance), but we aren't otherwise interested in the results.
1640 Nor do we care about ambiguous dictionaries etc. We will type check
1641 this bracket again at its usage site.
1644 tcSimplifyBracket :: [Inst] -> TcM ()
1645 tcSimplifyBracket wanteds
1646 = do { _ <- tryHardCheckLoop doc wanteds
1649 doc = text "tcSimplifyBracket"
1653 %************************************************************************
1655 \subsection{Filtering at a dynamic binding}
1657 %************************************************************************
1662 we must discharge all the ?x constraints from B. We also do an improvement
1663 step; if we have ?x::t1 and ?x::t2 we must unify t1, t2.
1665 Actually, the constraints from B might improve the types in ?x. For example
1667 f :: (?x::Int) => Char -> Char
1670 then the constraint (?x::Int) arising from the call to f will
1671 force the binding for ?x to be of type Int.
1674 tcSimplifyIPs :: [Inst] -- The implicit parameters bound here
1677 -- We need a loop so that we do improvement, and then
1678 -- (next time round) generate a binding to connect the two
1680 -- Here the two ?x's have different types, and improvement
1681 -- makes them the same.
1683 tcSimplifyIPs given_ips wanteds
1684 = do { wanteds' <- zonkInsts wanteds
1685 ; given_ips' <- zonkInsts given_ips
1686 -- Unusually for checking, we *must* zonk the given_ips
1688 ; let env = mkRedEnv doc try_me given_ips'
1689 ; (improved, tybinds, binds, irreds) <- reduceContext env wanteds'
1690 ; execTcTyVarBinds tybinds
1692 ; if null irreds || not improved then
1693 ASSERT( all is_free irreds )
1694 do { extendLIEs irreds
1697 -- If improvement did some unification, we go round again.
1698 -- We start again with irreds, not wanteds
1699 -- Using an instance decl might have introduced a fresh type
1700 -- variable which might have been unified, so we'd get an
1701 -- infinite loop if we started again with wanteds!
1703 { binds1 <- tcSimplifyIPs given_ips' irreds
1704 ; return $ binds `unionBags` binds1
1707 doc = text "tcSimplifyIPs" <+> ppr given_ips
1708 ip_set = mkNameSet (ipNamesOfInsts given_ips)
1709 is_free inst = isFreeWrtIPs ip_set inst
1711 -- Simplify any methods that mention the implicit parameter
1712 try_me inst | is_free inst = Stop
1713 | otherwise = ReduceMe
1717 %************************************************************************
1719 \subsection[binds-for-local-funs]{@bindInstsOfLocalFuns@}
1721 %************************************************************************
1723 When doing a binding group, we may have @Insts@ of local functions.
1724 For example, we might have...
1726 let f x = x + 1 -- orig local function (overloaded)
1727 f.1 = f Int -- two instances of f
1732 The point is: we must drop the bindings for @f.1@ and @f.2@ here,
1733 where @f@ is in scope; those @Insts@ must certainly not be passed
1734 upwards towards the top-level. If the @Insts@ were binding-ified up
1735 there, they would have unresolvable references to @f@.
1737 We pass in an @init_lie@ of @Insts@ and a list of locally-bound @Ids@.
1738 For each method @Inst@ in the @init_lie@ that mentions one of the
1739 @Ids@, we create a binding. We return the remaining @Insts@ (in an
1740 @LIE@), as well as the @HsBinds@ generated.
1743 bindInstsOfLocalFuns :: [Inst] -> [TcId] -> TcM TcDictBinds
1744 -- Simlifies only MethodInsts, and generate only bindings of form
1746 -- We're careful not to even generate bindings of the form
1748 -- You'd think that'd be fine, but it interacts with what is
1749 -- arguably a bug in Match.tidyEqnInfo (see notes there)
1751 bindInstsOfLocalFuns wanteds local_ids
1752 | null overloaded_ids = do
1755 return emptyLHsBinds
1758 = do { (irreds, binds) <- gentleInferLoop doc for_me
1759 ; extendLIEs not_for_me
1763 doc = text "bindInsts" <+> ppr local_ids
1764 overloaded_ids = filter is_overloaded local_ids
1765 is_overloaded id = isOverloadedTy (idType id)
1766 (for_me, not_for_me) = partition (isMethodFor overloaded_set) wanteds
1768 overloaded_set = mkVarSet overloaded_ids -- There can occasionally be a lot of them
1769 -- so it's worth building a set, so that
1770 -- lookup (in isMethodFor) is faster
1774 %************************************************************************
1776 \subsection{Data types for the reduction mechanism}
1778 %************************************************************************
1780 The main control over context reduction is here
1784 = RedEnv { red_doc :: SDoc -- The context
1785 , red_try_me :: Inst -> WhatToDo
1786 , red_improve :: Bool -- True <=> do improvement
1787 , red_givens :: [Inst] -- All guaranteed rigid
1788 -- Always dicts & equalities
1789 -- but see Note [Rigidity]
1791 , red_stack :: (Int, [Inst]) -- Recursion stack (for err msg)
1792 -- See Note [RedStack]
1796 -- The red_givens are rigid so far as cmpInst is concerned.
1797 -- There is one case where they are not totally rigid, namely in tcSimplifyIPs
1798 -- let ?x = e in ...
1799 -- Here, the given is (?x::a), where 'a' is not necy a rigid type
1800 -- But that doesn't affect the comparison, which is based only on mame.
1803 -- The red_stack pair (n,insts) pair is just used for error reporting.
1804 -- 'n' is always the depth of the stack.
1805 -- The 'insts' is the stack of Insts being reduced: to produce X
1806 -- I had to produce Y, to produce Y I had to produce Z, and so on.
1809 mkRedEnv :: SDoc -> (Inst -> WhatToDo) -> [Inst] -> RedEnv
1810 mkRedEnv doc try_me givens
1811 = RedEnv { red_doc = doc, red_try_me = try_me,
1812 red_givens = givens,
1814 red_improve = True }
1816 mkInferRedEnv :: SDoc -> (Inst -> WhatToDo) -> RedEnv
1818 mkInferRedEnv doc try_me
1819 = RedEnv { red_doc = doc, red_try_me = try_me,
1822 red_improve = True }
1824 mkNoImproveRedEnv :: SDoc -> (Inst -> WhatToDo) -> RedEnv
1825 -- Do not do improvement; no givens
1826 mkNoImproveRedEnv doc try_me
1827 = RedEnv { red_doc = doc, red_try_me = try_me,
1830 red_improve = True }
1833 = ReduceMe -- Try to reduce this
1834 -- If there's no instance, add the inst to the
1835 -- irreductible ones, but don't produce an error
1836 -- message of any kind.
1837 -- It might be quite legitimate such as (Eq a)!
1839 | Stop -- Return as irreducible unless it can
1840 -- be reduced to a constant in one step
1841 -- Do not add superclasses; see
1843 data WantSCs = NoSCs | AddSCs -- Tells whether we should add the superclasses
1844 -- of a predicate when adding it to the avails
1845 -- The reason for this flag is entirely the super-class loop problem
1846 -- Note [SUPER-CLASS LOOP 1]
1848 zonkRedEnv :: RedEnv -> TcM RedEnv
1850 = do { givens' <- mapM zonkInst (red_givens env)
1851 ; return $ env {red_givens = givens'}
1856 %************************************************************************
1858 \subsection[reduce]{@reduce@}
1860 %************************************************************************
1862 Note [Ancestor Equalities]
1863 ~~~~~~~~~~~~~~~~~~~~~~~~~~
1864 During context reduction, we add to the wanted equalities also those
1865 equalities that (transitively) occur in superclass contexts of wanted
1866 class constraints. Consider the following code
1868 class a ~ Int => C a
1871 If (C a) is wanted, we want to add (a ~ Int), which will be discharged by
1872 substituting Int for a. Hence, we ultimately want (C Int), which we
1873 discharge with the explicit instance.
1876 reduceContext :: RedEnv
1878 -> TcM (ImprovementDone,
1879 TcTyVarBinds, -- Type variable bindings
1880 TcDictBinds, -- Dictionary bindings
1881 [Inst]) -- Irreducible
1883 reduceContext env wanteds0
1884 = do { traceTc (text "reduceContext" <+> (vcat [
1885 text "----------------------",
1887 text "given" <+> ppr (red_givens env),
1888 text "wanted" <+> ppr wanteds0,
1889 text "----------------------"
1892 -- We want to add as wanted equalities those that (transitively)
1893 -- occur in superclass contexts of wanted class constraints.
1894 -- See Note [Ancestor Equalities]
1895 ; ancestor_eqs <- ancestorEqualities wanteds0
1896 ; traceTc $ text "reduceContext: ancestor eqs" <+> ppr ancestor_eqs
1898 -- Normalise and solve all equality constraints as far as possible
1899 -- and normalise all dictionary constraints wrt to the reduced
1900 -- equalities. The returned wanted constraints include the
1901 -- irreducible wanted equalities.
1902 ; let wanteds = wanteds0 ++ ancestor_eqs
1903 givens = red_givens env
1907 normalise_binds) <- tcReduceEqs givens wanteds
1908 ; traceTc $ text "reduceContext: tcReduceEqs result" <+> vcat
1909 [ppr givens', ppr wanteds', ppr tybinds,
1910 ppr normalise_binds]
1912 -- Build the Avail mapping from "given_dicts"
1913 ; (init_state, _) <- getLIE $ do
1914 { init_state <- foldlM addGiven emptyAvails givens'
1918 -- Solve the *wanted* *dictionary* constraints (not implications)
1919 -- This may expose some further equational constraints in the course
1920 -- of improvement due to functional dependencies if any of the
1921 -- involved unifications gets deferred.
1922 ; let (wanted_implics, wanted_dicts) = partition isImplicInst wanteds'
1923 ; (avails, extra_eqs) <- getLIE (reduceList env wanted_dicts init_state)
1924 -- The getLIE is reqd because reduceList does improvement
1925 -- (via extendAvails) which may in turn do unification
1928 dict_irreds) <- extractResults avails wanted_dicts
1929 ; traceTc $ text "reduceContext: extractResults" <+> vcat
1930 [ppr avails, ppr wanted_dicts, ppr dict_binds]
1932 -- Solve the wanted *implications*. In doing so, we can provide
1933 -- as "given" all the dicts that were originally given,
1934 -- *or* for which we now have bindings,
1935 -- *or* which are now irreds
1936 -- NB: Equality irreds need to be converted, as the recursive
1937 -- invocation of the solver will still treat them as wanteds
1939 ; let implic_env = env { red_givens
1940 = givens ++ bound_dicts ++
1941 map wantedToLocalEqInst dict_irreds }
1942 ; (implic_binds_s, implic_irreds_s)
1943 <- mapAndUnzipM (reduceImplication implic_env) wanted_implics
1944 ; let implic_binds = unionManyBags implic_binds_s
1945 implic_irreds = concat implic_irreds_s
1947 -- Collect all irreducible instances, and determine whether we should
1948 -- go round again. We do so in either of two cases:
1949 -- (1) If dictionary reduction or equality solving led to
1950 -- improvement (i.e., bindings for type variables).
1951 -- (2) If we reduced dictionaries (i.e., got dictionary bindings),
1952 -- they may have exposed further opportunities to normalise
1953 -- family applications. See Note [Dictionary Improvement]
1955 -- NB: We do *not* go around for new extra_eqs. Morally, we should,
1956 -- but we can't without risking non-termination (see #2688). By
1957 -- not going around, we miss some legal programs mixing FDs and
1958 -- TFs, but we never claimed to support such programs in the
1959 -- current implementation anyway.
1961 ; let all_irreds = dict_irreds ++ implic_irreds ++ extra_eqs
1962 avails_improved = availsImproved avails
1963 eq_improved = anyBag (not . isCoVarBind) tybinds
1964 improvedFlexible = avails_improved || eq_improved
1965 reduced_dicts = not (isEmptyBag dict_binds)
1966 improved = improvedFlexible || reduced_dicts
1968 improvedHint = (if avails_improved then " [AVAILS]" else "") ++
1969 (if eq_improved then " [EQ]" else "")
1971 ; traceTc (text "reduceContext end" <+> (vcat [
1972 text "----------------------",
1974 text "given" <+> ppr givens,
1975 text "wanted" <+> ppr wanteds0,
1977 text "tybinds" <+> ppr tybinds,
1978 text "avails" <+> pprAvails avails,
1979 text "improved =" <+> ppr improved <+> text improvedHint,
1980 text "(all) irreds = " <+> ppr all_irreds,
1981 text "dict-binds = " <+> ppr dict_binds,
1982 text "implic-binds = " <+> ppr implic_binds,
1983 text "----------------------"
1988 normalise_binds `unionBags` dict_binds
1989 `unionBags` implic_binds,
1993 isCoVarBind (TcTyVarBind tv _) = isCoVar tv
1995 tcImproveOne :: Avails -> Inst -> TcM ImprovementDone
1996 tcImproveOne avails inst
1997 | not (isDict inst) = return False
1999 = do { inst_envs <- tcGetInstEnvs
2000 ; let eqns = improveOne (classInstances inst_envs)
2001 (dictPred inst, pprInstArising inst)
2002 [ (dictPred p, pprInstArising p)
2003 | p <- availsInsts avails, isDict p ]
2004 -- Avails has all the superclasses etc (good)
2005 -- It also has all the intermediates of the deduction (good)
2006 -- It does not have duplicates (good)
2007 -- NB that (?x::t1) and (?x::t2) will be held separately in
2008 -- avails so that improve will see them separate
2009 ; traceTc (text "improveOne" <+> ppr inst)
2012 unifyEqns :: [(Equation, (PredType, SDoc), (PredType, SDoc))]
2013 -> TcM ImprovementDone
2014 unifyEqns [] = return False
2016 = do { traceTc (ptext (sLit "Improve:") <+> vcat (map pprEquationDoc eqns))
2017 ; improved <- mapM unify eqns
2018 ; return $ or improved
2021 unify ((qtvs, pairs), what1, what2)
2022 = addErrCtxtM (mkEqnMsg what1 what2) $
2023 do { let freeTyVars = unionVarSets (map tvs_pr pairs)
2025 ; (_, _, tenv) <- tcInstTyVars (varSetElems qtvs)
2026 ; mapM_ (unif_pr tenv) pairs
2027 ; anyM isFilledMetaTyVar $ varSetElems freeTyVars
2030 unif_pr tenv (ty1, ty2) = unifyType (substTy tenv ty1) (substTy tenv ty2)
2032 tvs_pr (ty1, ty2) = tyVarsOfType ty1 `unionVarSet` tyVarsOfType ty2
2034 pprEquationDoc :: (Equation, (PredType, SDoc), (PredType, SDoc)) -> SDoc
2035 pprEquationDoc (eqn, (p1, _), (p2, _))
2036 = vcat [pprEquation eqn, nest 2 (ppr p1), nest 2 (ppr p2)]
2038 mkEqnMsg :: (TcPredType, SDoc) -> (TcPredType, SDoc) -> TidyEnv
2039 -> TcM (TidyEnv, SDoc)
2040 mkEqnMsg (pred1,from1) (pred2,from2) tidy_env
2041 = do { pred1' <- zonkTcPredType pred1
2042 ; pred2' <- zonkTcPredType pred2
2043 ; let { pred1'' = tidyPred tidy_env pred1'
2044 ; pred2'' = tidyPred tidy_env pred2' }
2045 ; let msg = vcat [ptext (sLit "When using functional dependencies to combine"),
2046 nest 2 (sep [ppr pred1'' <> comma, nest 2 from1]),
2047 nest 2 (sep [ppr pred2'' <> comma, nest 2 from2])]
2048 ; return (tidy_env, msg) }
2051 Note [Dictionary Improvement]
2052 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2053 In reduceContext, we first reduce equalities and then class constraints.
2054 However, the letter may expose further opportunities for the former. Hence,
2055 we need to go around again if dictionary reduction produced any dictionary
2056 bindings. The following example demonstrated the point:
2058 data EX _x _y (p :: * -> *)
2063 class Base (Def p) => Prop p where
2067 instance Prop () where
2070 instance (Base (Def (p ANY))) => Base (EX _x _y p)
2071 instance (Prop (p ANY)) => Prop (EX _x _y p) where
2072 type Def (EX _x _y p) = EX _x _y p
2075 instance Prop (FOO x) where
2076 type Def (FOO x) = ()
2079 instance Prop BAR where
2080 type Def BAR = EX () () FOO
2082 During checking the last instance declaration, we need to check the superclass
2083 cosntraint Base (Def BAR), which family normalisation reduced to
2084 Base (EX () () FOO). Chasing the instance for Base (EX _x _y p), gives us
2085 Base (Def (FOO ANY)), which again requires family normalisation of Def to
2086 Base () before we can finish.
2089 The main context-reduction function is @reduce@. Here's its game plan.
2092 reduceList :: RedEnv -> [Inst] -> Avails -> TcM Avails
2093 reduceList env@(RedEnv {red_stack = (n,stk)}) wanteds state
2094 = do { traceTc (text "reduceList " <+> (ppr wanteds $$ ppr state))
2096 ; when (debugIsOn && (n > 8)) $ do
2097 debugDumpTcRn (hang (ptext (sLit "Interesting! Context reduction stack depth") <+> int n)
2098 2 (ifPprDebug (nest 2 (pprStack stk))))
2099 ; if n >= ctxtStkDepth dopts then
2100 failWithTc (reduceDepthErr n stk)
2104 go [] state = return state
2105 go (w:ws) state = do { state' <- reduce (env {red_stack = (n+1, w:stk)}) w state
2108 -- Base case: we're done!
2109 reduce :: RedEnv -> Inst -> Avails -> TcM Avails
2110 reduce env wanted avails
2112 -- We don't reduce equalities here (and they must not end up as irreds
2117 -- It's the same as an existing inst, or a superclass thereof
2118 | Just _ <- findAvail avails wanted
2119 = do { traceTc (text "reduce: found " <+> ppr wanted)
2124 = do { traceTc (text "reduce" <+> ppr wanted $$ ppr avails)
2125 ; case red_try_me env wanted of {
2126 Stop -> try_simple (addIrred NoSCs);
2127 -- See Note [No superclasses for Stop]
2129 ReduceMe -> do -- It should be reduced
2130 { (avails, lookup_result) <- reduceInst env avails wanted
2131 ; case lookup_result of
2132 NoInstance -> addIrred AddSCs avails wanted
2133 -- Add it and its superclasses
2135 GenInst [] rhs -> addWanted AddSCs avails wanted rhs []
2137 GenInst wanteds' rhs
2138 -> do { avails1 <- addIrred NoSCs avails wanted
2139 ; avails2 <- reduceList env wanteds' avails1
2140 ; addWanted AddSCs avails2 wanted rhs wanteds' } }
2141 -- Temporarily do addIrred *before* the reduceList,
2142 -- which has the effect of adding the thing we are trying
2143 -- to prove to the database before trying to prove the things it
2144 -- needs. See note [RECURSIVE DICTIONARIES]
2145 -- NB: we must not do an addWanted before, because that adds the
2146 -- superclasses too, and that can lead to a spurious loop; see
2147 -- the examples in [SUPERCLASS-LOOP]
2148 -- So we do an addIrred before, and then overwrite it afterwards with addWanted
2151 -- First, see if the inst can be reduced to a constant in one step
2152 -- Works well for literals (1::Int) and constant dictionaries (d::Num Int)
2153 -- Don't bother for implication constraints, which take real work
2154 try_simple do_this_otherwise
2155 = do { res <- lookupSimpleInst wanted
2157 GenInst [] rhs -> addWanted AddSCs avails wanted rhs []
2158 _ -> do_this_otherwise avails wanted }
2162 Note [RECURSIVE DICTIONARIES]
2163 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2165 data D r = ZeroD | SuccD (r (D r));
2167 instance (Eq (r (D r))) => Eq (D r) where
2168 ZeroD == ZeroD = True
2169 (SuccD a) == (SuccD b) = a == b
2172 equalDC :: D [] -> D [] -> Bool;
2175 We need to prove (Eq (D [])). Here's how we go:
2179 by instance decl, holds if
2183 by instance decl of Eq, holds if
2185 where d2 = dfEqList d3
2188 But now we can "tie the knot" to give
2194 and it'll even run! The trick is to put the thing we are trying to prove
2195 (in this case Eq (D []) into the database before trying to prove its
2196 contributing clauses.
2198 Note [SUPERCLASS-LOOP 2]
2199 ~~~~~~~~~~~~~~~~~~~~~~~~
2200 We need to be careful when adding "the constaint we are trying to prove".
2201 Suppose we are *given* d1:Ord a, and want to deduce (d2:C [a]) where
2203 class Ord a => C a where
2204 instance Ord [a] => C [a] where ...
2206 Then we'll use the instance decl to deduce C [a] from Ord [a], and then add the
2207 superclasses of C [a] to avails. But we must not overwrite the binding
2208 for Ord [a] (which is obtained from Ord a) with a superclass selection or we'll just
2211 Here's another variant, immortalised in tcrun020
2212 class Monad m => C1 m
2213 class C1 m => C2 m x
2214 instance C2 Maybe Bool
2215 For the instance decl we need to build (C1 Maybe), and it's no good if
2216 we run around and add (C2 Maybe Bool) and its superclasses to the avails
2217 before we search for C1 Maybe.
2219 Here's another example
2220 class Eq b => Foo a b
2221 instance Eq a => Foo [a] a
2225 we'll first deduce that it holds (via the instance decl). We must not
2226 then overwrite the Eq t constraint with a superclass selection!
2228 At first I had a gross hack, whereby I simply did not add superclass constraints
2229 in addWanted, though I did for addGiven and addIrred. This was sub-optimal,
2230 becuase it lost legitimate superclass sharing, and it still didn't do the job:
2231 I found a very obscure program (now tcrun021) in which improvement meant the
2232 simplifier got two bites a the cherry... so something seemed to be an Stop
2233 first time, but reducible next time.
2235 Now we implement the Right Solution, which is to check for loops directly
2236 when adding superclasses. It's a bit like the occurs check in unification.
2240 %************************************************************************
2242 Reducing a single constraint
2244 %************************************************************************
2247 ---------------------------------------------
2248 reduceInst :: RedEnv -> Avails -> Inst -> TcM (Avails, LookupInstResult)
2249 reduceInst _ avails other_inst
2250 = do { result <- lookupSimpleInst other_inst
2251 ; return (avails, result) }
2254 Note [Equational Constraints in Implication Constraints]
2255 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2257 An implication constraint is of the form
2259 where Given and Wanted may contain both equational and dictionary
2260 constraints. The delay and reduction of these two kinds of constraints
2263 -) In the generated code, wanted Dictionary constraints are wrapped up in an
2264 implication constraint that is created at the code site where the wanted
2265 dictionaries can be reduced via a let-binding. This let-bound implication
2266 constraint is deconstructed at the use-site of the wanted dictionaries.
2268 -) While the reduction of equational constraints is also delayed, the delay
2269 is not manifest in the generated code. The required evidence is generated
2270 in the code directly at the use-site. There is no let-binding and deconstruction
2271 necessary. The main disadvantage is that we cannot exploit sharing as the
2272 same evidence may be generated at multiple use-sites. However, this disadvantage
2273 is limited because it only concerns coercions which are erased.
2275 The different treatment is motivated by the different in representation. Dictionary
2276 constraints require manifest runtime dictionaries, while equations require coercions
2280 ---------------------------------------------
2281 reduceImplication :: RedEnv
2283 -> TcM (TcDictBinds, [Inst])
2286 Suppose we are simplifying the constraint
2287 forall bs. extras => wanted
2288 in the context of an overall simplification problem with givens 'givens'.
2291 * The 'givens' need not mention any of the quantified type variables
2292 e.g. forall {}. Eq a => Eq [a]
2293 forall {}. C Int => D (Tree Int)
2295 This happens when you have something like
2297 T1 :: Eq a => a -> T a
2300 f x = ...(case x of { T1 v -> v==v })...
2303 -- ToDo: should we instantiate tvs? I think it's not necessary
2305 -- Note on coercion variables:
2307 -- The extra given coercion variables are bound at two different
2310 -- -) in the creation context of the implication constraint
2311 -- the solved equational constraints use these binders
2313 -- -) at the solving site of the implication constraint
2314 -- the solved dictionaries use these binders;
2315 -- these binders are generated by reduceImplication
2317 -- Note [Binders for equalities]
2318 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2319 -- To reuse the binders of local/given equalities in the binders of
2320 -- implication constraints, it is crucial that these given equalities
2321 -- always have the form
2323 -- where cotv is a simple coercion type variable (and not a more
2324 -- complex coercion term). We require that the extra_givens always
2325 -- have this form and exploit the special form when generating binders.
2326 reduceImplication env
2327 orig_implic@(ImplicInst { tci_name = name, tci_loc = inst_loc,
2329 tci_given = extra_givens, tci_wanted = wanteds
2331 = do { -- Solve the sub-problem
2332 ; let try_me _ = ReduceMe -- Note [Freeness and implications]
2333 env' = env { red_givens = extra_givens ++ red_givens env
2334 , red_doc = sep [ptext (sLit "reduceImplication for")
2336 nest 2 (parens $ ptext (sLit "within")
2338 , red_try_me = try_me }
2340 ; traceTc (text "reduceImplication" <+> vcat
2341 [ ppr (red_givens env), ppr extra_givens,
2343 ; (irreds, binds) <- checkLoop env' wanteds
2345 ; traceTc (text "reduceImplication result" <+> vcat
2346 [ppr irreds, ppr binds])
2348 ; -- extract superclass binds
2349 -- (sc_binds,_) <- extractResults avails []
2350 -- ; traceTc (text "reduceImplication sc_binds" <+> vcat
2351 -- [ppr sc_binds, ppr avails])
2354 -- SLPJ Sept 07: what if improvement happened inside the checkLoop?
2355 -- Then we must iterate the outer loop too!
2357 ; didntSolveWantedEqs <- allM wantedEqInstIsUnsolved wanteds
2358 -- we solve wanted eqs by side effect!
2360 -- Progress is no longer measered by the number of bindings
2361 -- If there are any irreds, but no bindings and no solved
2362 -- equalities, we back off and do nothing
2363 ; let backOff = isEmptyLHsBinds binds && -- no new bindings
2364 (not $ null irreds) && -- but still some irreds
2365 didntSolveWantedEqs -- no instantiated cotv
2367 ; if backOff then -- No progress
2368 return (emptyBag, [orig_implic])
2370 { (simpler_implic_insts, bind)
2371 <- makeImplicationBind inst_loc tvs extra_givens irreds
2372 -- This binding is useless if the recursive simplification
2373 -- made no progress; but currently we don't try to optimise that
2374 -- case. After all, we only try hard to reduce at top level, or
2375 -- when inferring types.
2377 ; let -- extract Id binders for dicts and CoTyVar binders for eqs;
2378 -- see Note [Binders for equalities]
2379 (extra_eq_givens, extra_dict_givens) = partition isEqInst
2381 eq_cotvs = map instToVar extra_eq_givens
2382 dict_ids = map instToId extra_dict_givens
2384 -- Note [Always inline implication constraints]
2385 wrap_inline | null dict_ids = idHsWrapper
2386 | otherwise = WpInline
2389 <.> mkWpTyLams eq_cotvs
2390 <.> mkWpLams dict_ids
2391 <.> WpLet (binds `unionBags` bind)
2392 rhs = mkLHsWrap co payload
2393 loc = instLocSpan inst_loc
2394 -- wanted equalities are solved by updating their
2395 -- cotv; we don't generate bindings for them
2396 dict_bndrs = map (L loc . HsVar . instToId)
2397 . filter (not . isEqInst)
2399 payload = mkBigLHsTup dict_bndrs
2402 ; traceTc (vcat [text "reduceImplication" <+> ppr name,
2403 ppr simpler_implic_insts,
2404 text "->" <+> ppr rhs])
2405 ; return (unitBag (L loc (VarBind (instToId orig_implic) rhs)),
2406 simpler_implic_insts)
2409 reduceImplication _ i = pprPanic "reduceImplication" (ppr i)
2412 Note [Always inline implication constraints]
2413 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2414 Suppose an implication constraint floats out of an INLINE function.
2415 Then although the implication has a single call site, it won't be
2416 inlined. And that is bad because it means that even if there is really
2417 *no* overloading (type signatures specify the exact types) there will
2418 still be dictionary passing in the resulting code. To avert this,
2419 we mark the implication constraints themselves as INLINE, at least when
2420 there is no loss of sharing as a result.
2422 Note [Freeness and implications]
2423 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2424 It's hard to say when an implication constraint can be floated out. Consider
2425 forall {} Eq a => Foo [a]
2426 The (Foo [a]) doesn't mention any of the quantified variables, but it
2427 still might be partially satisfied by the (Eq a).
2429 There is a useful special case when it *is* easy to partition the
2430 constraints, namely when there are no 'givens'. Consider
2431 forall {a}. () => Bar b
2432 There are no 'givens', and so there is no reason to capture (Bar b).
2433 We can let it float out. But if there is even one constraint we
2434 must be much more careful:
2435 forall {a}. C a b => Bar (m b)
2436 because (C a b) might have a superclass (D b), from which we might
2437 deduce (Bar [b]) when m later gets instantiated to []. Ha!
2439 Here is an even more exotic example
2441 Now consider the constraint
2442 forall b. D Int b => C Int
2443 We can satisfy the (C Int) from the superclass of D, so we don't want
2444 to float the (C Int) out, even though it mentions no type variable in
2447 One more example: the constraint
2449 instance (C a, E c) => E (a,c)
2451 constraint: forall b. D Int b => E (Int,c)
2453 You might think that the (D Int b) can't possibly contribute
2454 to solving (E (Int,c)), since the latter mentions 'c'. But
2455 in fact it can, because solving the (E (Int,c)) constraint needs
2458 and the (C Int) can be satisfied from the superclass of (D Int b).
2459 So we must still not float (E (Int,c)) out.
2461 To think about: special cases for unary type classes?
2463 Note [Pruning the givens in an implication constraint]
2464 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2465 Suppose we are about to form the implication constraint
2466 forall tvs. Eq a => Ord b
2467 The (Eq a) cannot contribute to the (Ord b), because it has no access to
2468 the type variable 'b'. So we could filter out the (Eq a) from the givens.
2469 But BE CAREFUL of the examples above in [Freeness and implications].
2471 Doing so would be a bit tidier, but all the implication constraints get
2472 simplified away by the optimiser, so it's no great win. So I don't take
2473 advantage of that at the moment.
2475 If you do, BE CAREFUL of wobbly type variables.
2478 %************************************************************************
2480 Avails and AvailHow: the pool of evidence
2482 %************************************************************************
2486 data Avails = Avails !ImprovementDone !AvailEnv
2488 type ImprovementDone = Bool -- True <=> some unification has happened
2489 -- so some Irreds might now be reducible
2490 -- keys that are now
2492 type AvailEnv = FiniteMap Inst AvailHow
2494 = IsIrred -- Used for irreducible dictionaries,
2495 -- which are going to be lambda bound
2497 | Given Inst -- Used for dictionaries for which we have a binding
2498 -- e.g. those "given" in a signature
2500 | Rhs -- Used when there is a RHS
2501 (LHsExpr TcId) -- The RHS
2502 [Inst] -- Insts free in the RHS; we need these too
2504 instance Outputable Avails where
2507 pprAvails :: Avails -> SDoc
2508 pprAvails (Avails imp avails)
2509 = vcat [ ptext (sLit "Avails") <> (if imp then ptext (sLit "[improved]") else empty)
2511 vcat [ sep [ppr inst, nest 2 (equals <+> ppr avail)]
2512 | (inst,avail) <- fmToList avails ]]
2514 instance Outputable AvailHow where
2517 -------------------------
2518 pprAvail :: AvailHow -> SDoc
2519 pprAvail IsIrred = text "Irred"
2520 pprAvail (Given x) = text "Given" <+> ppr x
2521 pprAvail (Rhs rhs bs) = sep [text "Rhs" <+> ppr bs,
2524 -------------------------
2525 extendAvailEnv :: AvailEnv -> Inst -> AvailHow -> AvailEnv
2526 extendAvailEnv env inst avail = addToFM env inst avail
2528 findAvailEnv :: AvailEnv -> Inst -> Maybe AvailHow
2529 findAvailEnv env wanted = lookupFM env wanted
2530 -- NB 1: the Ord instance of Inst compares by the class/type info
2531 -- *not* by unique. So
2532 -- d1::C Int == d2::C Int
2534 emptyAvails :: Avails
2535 emptyAvails = Avails False emptyFM
2537 findAvail :: Avails -> Inst -> Maybe AvailHow
2538 findAvail (Avails _ avails) wanted = findAvailEnv avails wanted
2540 elemAvails :: Inst -> Avails -> Bool
2541 elemAvails wanted (Avails _ avails) = wanted `elemFM` avails
2543 extendAvails :: Avails -> Inst -> AvailHow -> TcM Avails
2545 extendAvails avails@(Avails imp env) inst avail
2546 = do { imp1 <- tcImproveOne avails inst -- Do any improvement
2547 ; return (Avails (imp || imp1) (extendAvailEnv env inst avail)) }
2549 availsInsts :: Avails -> [Inst]
2550 availsInsts (Avails _ avails) = keysFM avails
2552 availsImproved :: Avails -> ImprovementDone
2553 availsImproved (Avails imp _) = imp
2556 Extracting the bindings from a bunch of Avails.
2557 The bindings do *not* come back sorted in dependency order.
2558 We assume that they'll be wrapped in a big Rec, so that the
2559 dependency analyser can sort them out later
2562 type DoneEnv = FiniteMap Inst [Id]
2563 -- Tracks which things we have evidence for
2565 extractResults :: Avails
2567 -> TcM (TcDictBinds, -- Bindings
2568 [Inst], -- The insts bound by the bindings
2569 [Inst]) -- Irreducible ones
2570 -- Note [Reducing implication constraints]
2572 extractResults (Avails _ avails) wanteds
2573 = go emptyBag [] [] emptyFM wanteds
2575 go :: TcDictBinds -- Bindings for dicts
2576 -> [Inst] -- Bound by the bindings
2578 -> DoneEnv -- Has an entry for each inst in the above three sets
2580 -> TcM (TcDictBinds, [Inst], [Inst])
2581 go binds bound_dicts irreds _ []
2582 = return (binds, bound_dicts, irreds)
2584 go binds bound_dicts irreds done (w:ws)
2586 = go binds bound_dicts (w:irreds) done' ws
2588 | Just done_ids@(done_id : rest_done_ids) <- lookupFM done w
2589 = if w_id `elem` done_ids then
2590 go binds bound_dicts irreds done ws
2592 go (add_bind (nlHsVar done_id)) bound_dicts irreds
2593 (addToFM done w (done_id : w_id : rest_done_ids)) ws
2595 | otherwise -- Not yet done
2596 = case findAvailEnv avails w of
2597 Nothing -> pprTrace "Urk: extractResults" (ppr w) $
2598 go binds bound_dicts irreds done ws
2600 Just IsIrred -> go binds bound_dicts (w:irreds) done' ws
2602 Just (Rhs rhs ws') -> go (add_bind rhs) (w:bound_dicts) irreds done' (ws' ++ ws)
2604 Just (Given g) -> go binds' bound_dicts irreds (addToFM done w [g_id]) ws
2607 binds' | w_id == g_id = binds
2608 | otherwise = add_bind (nlHsVar g_id)
2611 done' = addToFM done w [w_id]
2612 add_bind rhs = addInstToDictBind binds w rhs
2616 Note [No superclasses for Stop]
2617 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2618 When we decide not to reduce an Inst -- the 'WhatToDo' --- we still
2619 add it to avails, so that any other equal Insts will be commoned up
2620 right here. However, we do *not* add superclasses. If we have
2623 but a is not bound here, then we *don't* want to derive dn from df
2624 here lest we lose sharing.
2627 addWanted :: WantSCs -> Avails -> Inst -> LHsExpr TcId -> [Inst] -> TcM Avails
2628 addWanted want_scs avails wanted rhs_expr wanteds
2629 = addAvailAndSCs want_scs avails wanted avail
2631 avail = Rhs rhs_expr wanteds
2633 addGiven :: Avails -> Inst -> TcM Avails
2634 addGiven avails given
2635 = addAvailAndSCs want_scs avails given (Given given)
2637 want_scs = case instLocOrigin (instLoc given) of
2640 -- Conditionally add superclasses for 'given'
2641 -- See Note [Recursive instances and superclases]
2643 -- No ASSERT( not (given `elemAvails` avails) ) because in an
2644 -- instance decl for Ord t we can add both Ord t and Eq t as
2645 -- 'givens', so the assert isn't true
2649 addIrred :: WantSCs -> Avails -> Inst -> TcM Avails
2650 addIrred want_scs avails irred = ASSERT2( not (irred `elemAvails` avails), ppr irred $$ ppr avails )
2651 addAvailAndSCs want_scs avails irred IsIrred
2653 addAvailAndSCs :: WantSCs -> Avails -> Inst -> AvailHow -> TcM Avails
2654 addAvailAndSCs want_scs avails inst avail
2655 | not (isClassDict inst) = extendAvails avails inst avail
2656 | NoSCs <- want_scs = extendAvails avails inst avail
2657 | otherwise = do { traceTc (text "addAvailAndSCs" <+> vcat [ppr inst, ppr deps])
2658 ; avails' <- extendAvails avails inst avail
2659 ; addSCs is_loop avails' inst }
2661 is_loop pred = any (`tcEqType` mkPredTy pred) dep_tys
2662 -- Note: this compares by *type*, not by Unique
2663 deps = findAllDeps (unitVarSet (instToVar inst)) avail
2664 dep_tys = map idType (varSetElems deps)
2666 findAllDeps :: IdSet -> AvailHow -> IdSet
2667 -- Find all the Insts that this one depends on
2668 -- See Note [SUPERCLASS-LOOP 2]
2669 -- Watch out, though. Since the avails may contain loops
2670 -- (see Note [RECURSIVE DICTIONARIES]), so we need to track the ones we've seen so far
2671 findAllDeps so_far (Rhs _ kids) = foldl find_all so_far kids
2672 findAllDeps so_far _ = so_far
2674 find_all :: IdSet -> Inst -> IdSet
2676 | isEqInst kid = so_far
2677 | kid_id `elemVarSet` so_far = so_far
2678 | Just avail <- findAvail avails kid = findAllDeps so_far' avail
2679 | otherwise = so_far'
2681 so_far' = extendVarSet so_far kid_id -- Add the new kid to so_far
2682 kid_id = instToId kid
2684 addSCs :: (TcPredType -> Bool) -> Avails -> Inst -> TcM Avails
2685 -- Add all the superclasses of the Inst to Avails
2686 -- The first param says "don't do this because the original thing
2687 -- depends on this one, so you'd build a loop"
2688 -- Invariant: the Inst is already in Avails.
2690 addSCs is_loop avails dict
2691 = ASSERT( isDict dict )
2692 do { sc_dicts <- newDictBndrs (instLoc dict) sc_theta'
2693 ; foldlM add_sc avails (zipEqual "add_scs" sc_dicts sc_sels) }
2695 (clas, tys) = getDictClassTys dict
2696 (tyvars, sc_theta, sc_sels, _) = classBigSig clas
2697 sc_theta' = filter (not . isEqPred) $
2698 substTheta (zipTopTvSubst tyvars tys) sc_theta
2700 add_sc avails (sc_dict, sc_sel)
2701 | is_loop (dictPred sc_dict) = return avails -- See Note [SUPERCLASS-LOOP 2]
2702 | is_given sc_dict = return avails
2703 | otherwise = do { avails' <- extendAvails avails sc_dict (Rhs sc_sel_rhs [dict])
2704 ; addSCs is_loop avails' sc_dict }
2706 sc_sel_rhs = L (instSpan dict) (HsWrap co_fn (HsVar sc_sel))
2707 co_fn = WpApp (instToVar dict) <.> mkWpTyApps tys
2709 is_given :: Inst -> Bool
2710 is_given sc_dict = case findAvail avails sc_dict of
2711 Just (Given _) -> True -- Given is cheaper than superclass selection
2714 -- From the a set of insts obtain all equalities that (transitively) occur in
2715 -- superclass contexts of class constraints (aka the ancestor equalities).
2717 ancestorEqualities :: [Inst] -> TcM [Inst]
2719 = mapM mkWantedEqInst -- turn only equality predicates..
2720 . filter isEqPred -- ..into wanted equality insts
2722 . addAEsToBag emptyBag -- collect the superclass constraints..
2723 . map dictPred -- ..of all predicates in a bag
2724 . filter isClassDict
2726 addAEsToBag :: Bag PredType -> [PredType] -> Bag PredType
2727 addAEsToBag bag [] = bag
2728 addAEsToBag bag (pred:preds)
2729 | pred `elemBag` bag = addAEsToBag bag preds
2730 | isEqPred pred = addAEsToBag bagWithPred preds
2731 | isClassPred pred = addAEsToBag bagWithPred predsWithSCs
2732 | otherwise = addAEsToBag bag preds
2734 bagWithPred = bag `snocBag` pred
2735 predsWithSCs = preds ++ substTheta (zipTopTvSubst tyvars tys) sc_theta
2737 (tyvars, sc_theta, _, _) = classBigSig clas
2738 (clas, tys) = getClassPredTys pred
2742 %************************************************************************
2744 \section{tcSimplifyTop: defaulting}
2746 %************************************************************************
2749 @tcSimplifyTop@ is called once per module to simplify all the constant
2750 and ambiguous Insts.
2752 We need to be careful of one case. Suppose we have
2754 instance Num a => Num (Foo a b) where ...
2756 and @tcSimplifyTop@ is given a constraint (Num (Foo x y)). Then it'll simplify
2757 to (Num x), and default x to Int. But what about y??
2759 It's OK: the final zonking stage should zap y to (), which is fine.
2763 tcSimplifyTop, tcSimplifyInteractive :: [Inst] -> TcM TcDictBinds
2764 tcSimplifyTop wanteds
2765 = tc_simplify_top doc False wanteds
2767 doc = text "tcSimplifyTop"
2769 tcSimplifyInteractive wanteds
2770 = tc_simplify_top doc True wanteds
2772 doc = text "tcSimplifyInteractive"
2774 -- The TcLclEnv should be valid here, solely to improve
2775 -- error message generation for the monomorphism restriction
2776 tc_simplify_top :: SDoc -> Bool -> [Inst] -> TcM (Bag (LHsBind TcId))
2777 tc_simplify_top doc interactive wanteds
2778 = do { dflags <- getDOpts
2779 ; wanteds <- zonkInsts wanteds
2780 ; mapM_ zonkTopTyVar (varSetElems (tyVarsOfInsts wanteds))
2782 ; traceTc (text "tc_simplify_top 0: " <+> ppr wanteds)
2783 ; (irreds1, binds1) <- tryHardCheckLoop doc1 wanteds
2784 -- ; (irreds1, binds1) <- gentleInferLoop doc1 wanteds
2785 ; traceTc (text "tc_simplify_top 1: " <+> ppr irreds1)
2786 ; (irreds2, binds2) <- approximateImplications doc2 (\_ -> True) irreds1
2787 ; traceTc (text "tc_simplify_top 2: " <+> ppr irreds2)
2789 -- Use the defaulting rules to do extra unification
2790 -- NB: irreds2 are already zonked
2791 ; (irreds3, binds3) <- disambiguate doc3 interactive dflags irreds2
2793 -- Deal with implicit parameters
2794 ; let (bad_ips, non_ips) = partition isIPDict irreds3
2795 (ambigs, others) = partition isTyVarDict non_ips
2797 ; topIPErrs bad_ips -- Can arise from f :: Int -> Int
2799 ; addNoInstanceErrs others
2800 ; addTopAmbigErrs ambigs
2802 ; return (binds1 `unionBags` binds2 `unionBags` binds3) }
2804 doc1 = doc <+> ptext (sLit "(first round)")
2805 doc2 = doc <+> ptext (sLit "(approximate)")
2806 doc3 = doc <+> ptext (sLit "(disambiguate)")
2809 If a dictionary constrains a type variable which is
2810 * not mentioned in the environment
2811 * and not mentioned in the type of the expression
2812 then it is ambiguous. No further information will arise to instantiate
2813 the type variable; nor will it be generalised and turned into an extra
2814 parameter to a function.
2816 It is an error for this to occur, except that Haskell provided for
2817 certain rules to be applied in the special case of numeric types.
2819 * at least one of its classes is a numeric class, and
2820 * all of its classes are numeric or standard
2821 then the type variable can be defaulted to the first type in the
2822 default-type list which is an instance of all the offending classes.
2824 So here is the function which does the work. It takes the ambiguous
2825 dictionaries and either resolves them (producing bindings) or
2826 complains. It works by splitting the dictionary list by type
2827 variable, and using @disambigOne@ to do the real business.
2829 @disambigOne@ assumes that its arguments dictionaries constrain all
2830 the same type variable.
2832 ADR Comment 20/6/94: I've changed the @CReturnable@ case to default to
2833 @()@ instead of @Int@. I reckon this is the Right Thing to do since
2834 the most common use of defaulting is code like:
2836 _ccall_ foo `seqPrimIO` bar
2838 Since we're not using the result of @foo@, the result if (presumably)
2842 disambiguate :: SDoc -> Bool -> DynFlags -> [Inst] -> TcM ([Inst], TcDictBinds)
2843 -- Just does unification to fix the default types
2844 -- The Insts are assumed to be pre-zonked
2845 disambiguate doc interactive dflags insts
2847 = return (insts, emptyBag)
2849 | null defaultable_groups
2850 = do { traceTc (text "disambigutate, no defaultable groups" <+> vcat [ppr unaries, ppr insts, ppr bad_tvs, ppr defaultable_groups])
2851 ; return (insts, emptyBag) }
2854 = do { -- Figure out what default types to use
2855 default_tys <- getDefaultTys extended_defaulting ovl_strings
2857 ; traceTc (text "disambiguate1" <+> vcat [ppr insts, ppr unaries, ppr bad_tvs, ppr defaultable_groups])
2858 ; mapM_ (disambigGroup default_tys) defaultable_groups
2860 -- disambigGroup does unification, hence try again
2861 ; tryHardCheckLoop doc insts }
2864 extended_defaulting = interactive || dopt Opt_ExtendedDefaultRules dflags
2865 -- See also Trac #1974
2866 ovl_strings = dopt Opt_OverloadedStrings dflags
2868 unaries :: [(Inst, Class, TcTyVar)] -- (C tv) constraints
2869 bad_tvs :: TcTyVarSet -- Tyvars mentioned by *other* constraints
2870 (unaries, bad_tvs_s) = partitionWith find_unary insts
2871 bad_tvs = unionVarSets bad_tvs_s
2873 -- Finds unary type-class constraints
2874 find_unary d@(Dict {tci_pred = ClassP cls [ty]})
2875 | Just tv <- tcGetTyVar_maybe ty = Left (d,cls,tv)
2876 find_unary inst = Right (tyVarsOfInst inst)
2878 -- Group by type variable
2879 defaultable_groups :: [[(Inst,Class,TcTyVar)]]
2880 defaultable_groups = filter defaultable_group (equivClasses cmp_tv unaries)
2881 cmp_tv (_,_,tv1) (_,_,tv2) = tv1 `compare` tv2
2883 defaultable_group :: [(Inst,Class,TcTyVar)] -> Bool
2884 defaultable_group ds@((_,_,tv):_)
2885 = isTyConableTyVar tv -- Note [Avoiding spurious errors]
2886 && not (tv `elemVarSet` bad_tvs)
2887 && defaultable_classes [c | (_,c,_) <- ds]
2888 defaultable_group [] = panic "defaultable_group"
2890 defaultable_classes clss
2891 | extended_defaulting = any isInteractiveClass clss
2892 | otherwise = all is_std_class clss && (any is_num_class clss)
2894 -- In interactive mode, or with -XExtendedDefaultRules,
2895 -- we default Show a to Show () to avoid graututious errors on "show []"
2896 isInteractiveClass cls
2897 = is_num_class cls || (classKey cls `elem` [showClassKey, eqClassKey, ordClassKey])
2899 is_num_class cls = isNumericClass cls || (ovl_strings && (cls `hasKey` isStringClassKey))
2900 -- is_num_class adds IsString to the standard numeric classes,
2901 -- when -foverloaded-strings is enabled
2903 is_std_class cls = isStandardClass cls || (ovl_strings && (cls `hasKey` isStringClassKey))
2904 -- Similarly is_std_class
2906 -----------------------
2907 disambigGroup :: [Type] -- The default types
2908 -> [(Inst,Class,TcTyVar)] -- All standard classes of form (C a)
2909 -> TcM () -- Just does unification, to fix the default types
2911 disambigGroup default_tys dicts
2912 = do { mb_chosen_ty <- try_default default_tys
2913 ; case mb_chosen_ty of
2914 Nothing -> return ()
2915 Just chosen_ty -> do { _ <- unifyType chosen_ty (mkTyVarTy tyvar)
2916 ; warnDefault dicts chosen_ty } }
2918 (_,_,tyvar) = ASSERT(not (null dicts)) head dicts -- Should be non-empty
2919 classes = [c | (_,c,_) <- dicts]
2921 try_default [] = return Nothing
2922 try_default (default_ty : default_tys)
2923 = tryTcLIE_ (try_default default_tys) $
2924 do { tcSimplifyDefault [mkClassPred clas [default_ty] | clas <- classes]
2925 -- This may fail; then the tryTcLIE_ kicks in
2926 -- Failure here is caused by there being no type in the
2927 -- default list which can satisfy all the ambiguous classes.
2928 -- For example, if Real a is reqd, but the only type in the
2929 -- default list is Int.
2931 ; return (Just default_ty) -- TOMDO: do something with the coercion
2935 -----------------------
2936 getDefaultTys :: Bool -> Bool -> TcM [Type]
2937 getDefaultTys extended_deflts ovl_strings
2938 = do { mb_defaults <- getDeclaredDefaultTys
2939 ; case mb_defaults of {
2940 Just tys -> return tys ; -- User-supplied defaults
2943 -- No use-supplied default
2944 -- Use [Integer, Double], plus modifications
2945 { integer_ty <- tcMetaTy integerTyConName
2946 ; checkWiredInTyCon doubleTyCon
2947 ; string_ty <- tcMetaTy stringTyConName
2948 ; return (opt_deflt extended_deflts unitTy
2949 -- Note [Default unitTy]
2951 [integer_ty,doubleTy]
2953 opt_deflt ovl_strings string_ty) } } }
2955 opt_deflt True ty = [ty]
2956 opt_deflt False _ = []
2959 Note [Default unitTy]
2960 ~~~~~~~~~~~~~~~~~~~~~
2961 In interative mode (or with -XExtendedDefaultRules) we add () as the first type we
2962 try when defaulting. This has very little real impact, except in the following case.
2964 Text.Printf.printf "hello"
2965 This has type (forall a. IO a); it prints "hello", and returns 'undefined'. We don't
2966 want the GHCi repl loop to try to print that 'undefined'. The neatest thing is to
2967 default the 'a' to (), rather than to Integer (which is what would otherwise happen;
2968 and then GHCi doesn't attempt to print the (). So in interactive mode, we add
2969 () to the list of defaulting types. See Trac #1200.
2971 Note [Avoiding spurious errors]
2972 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2973 When doing the unification for defaulting, we check for skolem
2974 type variables, and simply don't default them. For example:
2975 f = (*) -- Monomorphic
2976 g :: Num a => a -> a
2978 Here, we get a complaint when checking the type signature for g,
2979 that g isn't polymorphic enough; but then we get another one when
2980 dealing with the (Num a) context arising from f's definition;
2981 we try to unify a with Int (to default it), but find that it's
2982 already been unified with the rigid variable from g's type sig
2985 %************************************************************************
2987 \subsection[simple]{@Simple@ versions}
2989 %************************************************************************
2991 Much simpler versions when there are no bindings to make!
2993 @tcSimplifyThetas@ simplifies class-type constraints formed by
2994 @deriving@ declarations and when specialising instances. We are
2995 only interested in the simplified bunch of class/type constraints.
2997 It simplifies to constraints of the form (C a b c) where
2998 a,b,c are type variables. This is required for the context of
2999 instance declarations.
3002 tcSimplifyDeriv :: InstOrigin
3004 -> ThetaType -- Wanted
3005 -> TcM ThetaType -- Needed
3006 -- Given instance (wanted) => C inst_ty
3007 -- Simplify 'wanted' as much as possible
3009 tcSimplifyDeriv orig tyvars theta
3010 = do { (tvs, _, tenv) <- tcInstTyVars tyvars
3011 -- The main loop may do unification, and that may crash if
3012 -- it doesn't see a TcTyVar, so we have to instantiate. Sigh
3013 -- ToDo: what if two of them do get unified?
3014 ; wanteds <- newDictBndrsO orig (substTheta tenv theta)
3015 ; (irreds, _) <- tryHardCheckLoop doc wanteds
3017 ; let (tv_dicts, others) = partition ok irreds
3018 (tidy_env, tidy_insts) = tidyInsts others
3019 ; reportNoInstances tidy_env Nothing [alt_fix] tidy_insts
3020 -- See Note [Exotic derived instance contexts] in TcMType
3022 ; let rev_env = zipTopTvSubst tvs (mkTyVarTys tyvars)
3023 simpl_theta = substTheta rev_env (map dictPred tv_dicts)
3024 -- This reverse-mapping is a pain, but the result
3025 -- should mention the original TyVars not TcTyVars
3027 ; return simpl_theta }
3029 doc = ptext (sLit "deriving classes for a data type")
3031 ok dict | isDict dict = validDerivPred (dictPred dict)
3033 alt_fix = vcat [ptext (sLit "use a standalone 'deriving instance' declaration instead,"),
3034 ptext (sLit "so you can specify the instance context yourself")]
3038 @tcSimplifyDefault@ just checks class-type constraints, essentially;
3039 used with \tr{default} declarations. We are only interested in
3040 whether it worked or not.
3043 tcSimplifyDefault :: ThetaType -- Wanted; has no type variables in it
3046 tcSimplifyDefault theta = do
3047 wanteds <- newDictBndrsO DefaultOrigin theta
3048 (irreds, _) <- tryHardCheckLoop doc wanteds
3049 addNoInstanceErrs irreds
3053 traceTc (ptext (sLit "tcSimplifyDefault failing")) >> failM
3055 doc = ptext (sLit "default declaration")
3060 %************************************************************************
3062 \section{Errors and contexts}
3064 %************************************************************************
3066 ToDo: for these error messages, should we note the location as coming
3067 from the insts, or just whatever seems to be around in the monad just
3071 groupErrs :: ([Inst] -> TcM ()) -- Deal with one group
3072 -> [Inst] -- The offending Insts
3074 -- Group together insts with the same origin
3075 -- We want to report them together in error messages
3079 groupErrs report_err (inst:insts)
3080 = do { do_one (inst:friends)
3081 ; groupErrs report_err others }
3083 -- (It may seem a bit crude to compare the error messages,
3084 -- but it makes sure that we combine just what the user sees,
3085 -- and it avoids need equality on InstLocs.)
3086 (friends, others) = partition is_friend insts
3087 loc_msg = showSDoc (pprInstLoc (instLoc inst))
3088 is_friend friend = showSDoc (pprInstLoc (instLoc friend)) == loc_msg
3089 do_one insts = setInstCtxt (instLoc (head insts)) (report_err insts)
3090 -- Add location and context information derived from the Insts
3092 -- Add the "arising from..." part to a message about bunch of dicts
3093 addInstLoc :: [Inst] -> Message -> Message
3094 addInstLoc insts msg = msg $$ nest 2 (pprInstArising (head insts))
3096 addTopIPErrs :: [Name] -> [Inst] -> TcM ()
3099 addTopIPErrs bndrs ips
3100 = do { dflags <- getDOpts
3101 ; addErrTcM (tidy_env, mk_msg dflags tidy_ips) }
3103 (tidy_env, tidy_ips) = tidyInsts ips
3105 = vcat [sep [ptext (sLit "Implicit parameters escape from"),
3106 nest 2 (ptext (sLit "the monomorphic top-level binding")
3107 <> plural bndrs <+> ptext (sLit "of")
3108 <+> pprBinders bndrs <> colon)],
3109 nest 2 (vcat (map ppr_ip ips)),
3110 monomorphism_fix dflags]
3111 ppr_ip ip = pprPred (dictPred ip) <+> pprInstArising ip
3113 topIPErrs :: [Inst] -> TcM ()
3115 = groupErrs report tidy_dicts
3117 (tidy_env, tidy_dicts) = tidyInsts dicts
3118 report dicts = addErrTcM (tidy_env, mk_msg dicts)
3119 mk_msg dicts = addInstLoc dicts (ptext (sLit "Unbound implicit parameter") <>
3120 plural tidy_dicts <+> pprDictsTheta tidy_dicts)
3122 addNoInstanceErrs :: [Inst] -- Wanted (can include implications)
3124 addNoInstanceErrs insts
3125 = do { let (tidy_env, tidy_insts) = tidyInsts insts
3126 ; reportNoInstances tidy_env Nothing [] tidy_insts }
3130 -> Maybe (InstLoc, [Inst]) -- Context
3131 -- Nothing => top level
3132 -- Just (d,g) => d describes the construct
3134 -> [SDoc] -- Alternative fix for no-such-instance
3135 -> [Inst] -- What is wanted (can include implications)
3138 reportNoInstances tidy_env mb_what alt_fix insts
3139 = groupErrs (report_no_instances tidy_env mb_what alt_fix) insts
3141 report_no_instances :: TidyEnv -> Maybe (InstLoc, [Inst]) -> [SDoc] -> [Inst] -> TcM ()
3142 report_no_instances tidy_env mb_what alt_fixes insts
3143 = do { inst_envs <- tcGetInstEnvs
3144 ; let (implics, insts1) = partition isImplicInst insts
3145 (insts2, overlaps) = partitionWith (check_overlap inst_envs) insts1
3146 (eqInsts, insts3) = partition isEqInst insts2
3147 ; traceTc (text "reportNoInstances" <+> vcat
3148 [ppr insts, ppr implics, ppr insts1, ppr insts2])
3149 ; mapM_ complain_implic implics
3150 ; mapM_ (\doc -> addErrTcM (tidy_env, doc)) overlaps
3151 ; groupErrs complain_no_inst insts3
3152 ; mapM_ (addErrTcM . mk_eq_err) eqInsts
3155 complain_no_inst insts = addErrTcM (tidy_env, mk_no_inst_err insts)
3157 complain_implic inst -- Recurse!
3158 = reportNoInstances tidy_env
3159 (Just (tci_loc inst, tci_given inst))
3160 alt_fixes (tci_wanted inst)
3162 check_overlap :: (InstEnv,InstEnv) -> Inst -> Either Inst SDoc
3163 -- Right msg => overlap message
3164 -- Left inst => no instance
3165 check_overlap inst_envs wanted
3166 | not (isClassDict wanted) = Left wanted
3168 = case lookupInstEnv inst_envs clas tys of
3169 ([], _) -> Left wanted -- No match
3170 -- The case of exactly one match and no unifiers means a
3171 -- successful lookup. That can't happen here, because dicts
3172 -- only end up here if they didn't match in Inst.lookupInst
3174 | debugIsOn -> pprPanic "reportNoInstance" (ppr wanted)
3175 res -> Right (mk_overlap_msg wanted res)
3177 (clas,tys) = getDictClassTys wanted
3179 mk_overlap_msg dict (matches, unifiers)
3180 = ASSERT( not (null matches) )
3181 vcat [ addInstLoc [dict] ((ptext (sLit "Overlapping instances for")
3182 <+> pprPred (dictPred dict))),
3183 sep [ptext (sLit "Matching instances") <> colon,
3184 nest 2 (vcat [pprInstances ispecs, pprInstances unifiers])],
3185 if not (isSingleton matches)
3186 then -- Two or more matches
3188 else -- One match, plus some unifiers
3189 ASSERT( not (null unifiers) )
3190 parens (vcat [ptext (sLit "The choice depends on the instantiation of") <+>
3191 quotes (pprWithCommas ppr (varSetElems (tyVarsOfInst dict))),
3192 ptext (sLit "To pick the first instance above, use -XIncoherentInstances"),
3193 ptext (sLit "when compiling the other instance declarations")])]
3195 ispecs = [ispec | (ispec, _) <- matches]
3197 mk_eq_err :: Inst -> (TidyEnv, SDoc)
3198 mk_eq_err inst = misMatchMsg tidy_env (eqInstTys inst)
3200 mk_no_inst_err insts
3201 | null insts = empty
3203 | Just (loc, givens) <- mb_what, -- Nested (type signatures, instance decls)
3204 not (isEmptyVarSet (tyVarsOfInsts insts))
3205 = vcat [ addInstLoc insts $
3206 sep [ ptext (sLit "Could not deduce") <+> pprDictsTheta insts
3207 , nest 2 $ ptext (sLit "from the context") <+> pprDictsTheta givens]
3208 , show_fixes (fix1 loc : fixes2 ++ alt_fixes) ]
3210 | otherwise -- Top level
3211 = vcat [ addInstLoc insts $
3212 ptext (sLit "No instance") <> plural insts
3213 <+> ptext (sLit "for") <+> pprDictsTheta insts
3214 , show_fixes (fixes2 ++ alt_fixes) ]
3217 fix1 loc = sep [ ptext (sLit "add") <+> pprDictsTheta insts
3218 <+> ptext (sLit "to the context of"),
3219 nest 2 (ppr (instLocOrigin loc)) ]
3220 -- I'm not sure it helps to add the location
3221 -- nest 2 (ptext (sLit "at") <+> ppr (instLocSpan loc)) ]
3223 fixes2 | null instance_dicts = []
3224 | otherwise = [sep [ptext (sLit "add an instance declaration for"),
3225 pprDictsTheta instance_dicts]]
3226 instance_dicts = [d | d <- insts, isClassDict d, not (isTyVarDict d)]
3227 -- Insts for which it is worth suggesting an adding an instance declaration
3228 -- Exclude implicit parameters, and tyvar dicts
3230 show_fixes :: [SDoc] -> SDoc
3231 show_fixes [] = empty
3232 show_fixes (f:fs) = sep [ptext (sLit "Possible fix:"),
3233 nest 2 (vcat (f : map (ptext (sLit "or") <+>) fs))]
3235 addTopAmbigErrs :: [Inst] -> TcRn ()
3236 addTopAmbigErrs dicts
3237 -- Divide into groups that share a common set of ambiguous tyvars
3238 = ifErrsM (return ()) $ -- Only report ambiguity if no other errors happened
3239 -- See Note [Avoiding spurious errors]
3240 mapM_ report (equivClasses cmp [(d, tvs_of d) | d <- tidy_dicts])
3242 (tidy_env, tidy_dicts) = tidyInsts dicts
3244 tvs_of :: Inst -> [TcTyVar]
3245 tvs_of d = varSetElems (tyVarsOfInst d)
3246 cmp (_,tvs1) (_,tvs2) = tvs1 `compare` tvs2
3248 report :: [(Inst,[TcTyVar])] -> TcM ()
3249 report pairs@((inst,tvs) : _) = do -- The pairs share a common set of ambiguous tyvars
3250 (tidy_env, mono_msg) <- mkMonomorphismMsg tidy_env tvs
3251 setSrcSpan (instSpan inst) $
3252 -- the location of the first one will do for the err message
3253 addErrTcM (tidy_env, msg $$ mono_msg)
3255 dicts = map fst pairs
3256 msg = sep [text "Ambiguous type variable" <> plural tvs <+>
3257 pprQuotedList tvs <+> in_msg,
3258 nest 2 (pprDictsInFull dicts)]
3259 in_msg = text "in the constraint" <> plural dicts <> colon
3260 report [] = panic "addTopAmbigErrs"
3263 mkMonomorphismMsg :: TidyEnv -> [TcTyVar] -> TcM (TidyEnv, Message)
3264 -- There's an error with these Insts; if they have free type variables
3265 -- it's probably caused by the monomorphism restriction.
3266 -- Try to identify the offending variable
3267 -- ASSUMPTION: the Insts are fully zonked
3268 mkMonomorphismMsg tidy_env inst_tvs
3269 = do { dflags <- getDOpts
3270 ; (tidy_env, docs) <- findGlobals (mkVarSet inst_tvs) tidy_env
3271 ; return (tidy_env, mk_msg dflags docs) }
3273 mk_msg _ _ | any isRuntimeUnk inst_tvs
3274 = vcat [ptext (sLit "Cannot resolve unknown runtime types:") <+>
3275 (pprWithCommas ppr inst_tvs),
3276 ptext (sLit "Use :print or :force to determine these types")]
3277 mk_msg _ [] = ptext (sLit "Probable fix: add a type signature that fixes these type variable(s)")
3278 -- This happens in things like
3279 -- f x = show (read "foo")
3280 -- where monomorphism doesn't play any role
3282 = vcat [ptext (sLit "Possible cause: the monomorphism restriction applied to the following:"),
3284 monomorphism_fix dflags]
3286 monomorphism_fix :: DynFlags -> SDoc
3287 monomorphism_fix dflags
3288 = ptext (sLit "Probable fix:") <+> vcat
3289 [ptext (sLit "give these definition(s) an explicit type signature"),
3290 if dopt Opt_MonomorphismRestriction dflags
3291 then ptext (sLit "or use -XNoMonomorphismRestriction")
3292 else empty] -- Only suggest adding "-XNoMonomorphismRestriction"
3293 -- if it is not already set!
3295 warnDefault :: [(Inst, Class, Var)] -> Type -> TcM ()
3296 warnDefault ups default_ty = do
3297 warn_flag <- doptM Opt_WarnTypeDefaults
3298 setInstCtxt (instLoc (head (dicts))) (warnTc warn_flag warn_msg)
3300 dicts = [d | (d,_,_) <- ups]
3303 (_, tidy_dicts) = tidyInsts dicts
3304 warn_msg = vcat [ptext (sLit "Defaulting the following constraint(s) to type") <+>
3305 quotes (ppr default_ty),
3306 pprDictsInFull tidy_dicts]
3308 reduceDepthErr :: Int -> [Inst] -> SDoc
3309 reduceDepthErr n stack
3310 = vcat [ptext (sLit "Context reduction stack overflow; size =") <+> int n,
3311 ptext (sLit "Use -fcontext-stack=N to increase stack size to N"),
3312 nest 4 (pprStack stack)]
3314 pprStack :: [Inst] -> SDoc
3315 pprStack stack = vcat (map pprInstInFull stack)