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 = mkVarBind dict_irred_id rhs
1024 PatBind { pat_lhs = lpat
1025 , pat_rhs = unguardedGRHSs rhs
1026 , pat_rhs_ty = hsLPatType lpat
1027 , bind_fvs = placeHolderNames
1030 ; traceTc $ text "makeImplicationBind" <+> ppr implic_inst
1031 ; return ([implic_inst], unitBag bind)
1034 -----------------------------------------------------------
1035 tryHardCheckLoop :: SDoc
1037 -> TcM ([Inst], TcDictBinds)
1039 tryHardCheckLoop doc wanteds
1040 = do { (irreds,binds) <- checkLoop (mkInferRedEnv doc try_me) wanteds
1041 ; return (irreds,binds)
1045 -- Here's the try-hard bit
1047 -----------------------------------------------------------
1048 gentleCheckLoop :: InstLoc
1051 -> TcM ([Inst], TcDictBinds)
1053 gentleCheckLoop inst_loc givens wanteds
1054 = do { (irreds,binds) <- checkLoop env wanteds
1055 ; return (irreds,binds)
1058 env = mkRedEnv (pprInstLoc inst_loc) try_me givens
1060 try_me inst | isMethodOrLit inst = ReduceMe
1062 -- When checking against a given signature
1063 -- we MUST be very gentle: Note [Check gently]
1065 gentleInferLoop :: SDoc -> [Inst]
1066 -> TcM ([Inst], TcDictBinds)
1067 gentleInferLoop doc wanteds
1068 = do { (irreds, binds) <- checkLoop env wanteds
1069 ; return (irreds, binds) }
1071 env = mkInferRedEnv doc try_me
1072 try_me inst | isMethodOrLit inst = ReduceMe
1077 ~~~~~~~~~~~~~~~~~~~~
1078 We have to very careful about not simplifying too vigorously
1083 f :: Show b => T b -> b
1084 f (MkT x) = show [x]
1086 Inside the pattern match, which binds (a:*, x:a), we know that
1088 Hence we have a dictionary for Show [a] available; and indeed we
1089 need it. We are going to build an implication contraint
1090 forall a. (b~[a]) => Show [a]
1091 Later, we will solve this constraint using the knowledge (Show b)
1093 But we MUST NOT reduce (Show [a]) to (Show a), else the whole
1094 thing becomes insoluble. So we simplify gently (get rid of literals
1095 and methods only, plus common up equal things), deferring the real
1096 work until top level, when we solve the implication constraint
1097 with tryHardCheckLooop.
1101 -----------------------------------------------------------
1104 -> TcM ([Inst], TcDictBinds)
1105 -- Precondition: givens are completely rigid
1106 -- Postcondition: returned Insts are zonked
1108 checkLoop env wanteds
1110 where go env wanteds
1111 = do { -- We do need to zonk the givens; cf Note [Zonking RedEnv]
1112 ; env' <- zonkRedEnv env
1113 ; wanteds' <- zonkInsts wanteds
1115 ; (improved, tybinds, binds, irreds)
1116 <- reduceContext env' wanteds'
1117 ; execTcTyVarBinds tybinds
1119 ; if null irreds || not improved then
1120 return (irreds, binds)
1123 -- If improvement did some unification, we go round again.
1124 -- We start again with irreds, not wanteds
1125 -- Using an instance decl might have introduced a fresh type
1126 -- variable which might have been unified, so we'd get an
1127 -- infinite loop if we started again with wanteds!
1129 { (irreds1, binds1) <- go env' irreds
1130 ; return (irreds1, binds `unionBags` binds1) } }
1133 Note [Zonking RedEnv]
1134 ~~~~~~~~~~~~~~~~~~~~~
1135 It might appear as if the givens in RedEnv are always rigid, but that is not
1136 necessarily the case for programs involving higher-rank types that have class
1137 contexts constraining the higher-rank variables. An example from tc237 in the
1140 class Modular s a | s -> a
1142 wim :: forall a w. Integral a
1143 => a -> (forall s. Modular s a => M s w) -> w
1144 wim i k = error "urk"
1146 test5 :: (Modular s a, Integral a) => M s a
1149 test4 = wim 4 test4'
1151 Notice how the variable 'a' of (Modular s a) in the rank-2 type of wim is
1152 quantified further outside. When type checking test4, we have to check
1153 whether the signature of test5 is an instance of
1155 (forall s. Modular s a => M s w)
1157 Consequently, we will get (Modular s t_a), where t_a is a TauTv into the
1160 Given the FD of Modular in this example, class improvement will instantiate
1161 t_a to 'a', where 'a' is the skolem from test5's signatures (due to the
1162 Modular s a predicate in that signature). If we don't zonk (Modular s t_a) in
1163 the givens, we will get into a loop as improveOne uses the unification engine
1164 Unify.tcUnifyTys, which doesn't know about mutable type variables.
1169 class If b t e r | b t e -> r
1172 class Lte a b c | a b -> c where lte :: a -> b -> c
1174 instance (Lte a b l,If l b a c) => Max a b c
1176 Wanted: Max Z (S x) y
1178 Then we'll reduce using the Max instance to:
1179 (Lte Z (S x) l, If l (S x) Z y)
1180 and improve by binding l->T, after which we can do some reduction
1181 on both the Lte and If constraints. What we *can't* do is start again
1182 with (Max Z (S x) y)!
1186 %************************************************************************
1188 tcSimplifySuperClasses
1190 %************************************************************************
1192 Note [SUPERCLASS-LOOP 1]
1193 ~~~~~~~~~~~~~~~~~~~~~~~~
1194 We have to be very, very careful when generating superclasses, lest we
1195 accidentally build a loop. Here's an example:
1199 class S a => C a where { opc :: a -> a }
1200 class S b => D b where { opd :: b -> b }
1202 instance C Int where
1205 instance D Int where
1208 From (instance C Int) we get the constraint set {ds1:S Int, dd:D Int}
1209 Simplifying, we may well get:
1210 $dfCInt = :C ds1 (opd dd)
1213 Notice that we spot that we can extract ds1 from dd.
1215 Alas! Alack! We can do the same for (instance D Int):
1217 $dfDInt = :D ds2 (opc dc)
1221 And now we've defined the superclass in terms of itself.
1222 Two more nasty cases are in
1227 - Satisfy the superclass context *all by itself*
1228 (tcSimplifySuperClasses)
1229 - And do so completely; i.e. no left-over constraints
1230 to mix with the constraints arising from method declarations
1233 Note [Recursive instances and superclases]
1234 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1235 Consider this code, which arises in the context of "Scrap Your
1236 Boilerplate with Class".
1240 instance Sat (ctx Char) => Data ctx Char
1241 instance (Sat (ctx [a]), Data ctx a) => Data ctx [a]
1243 class Data Maybe a => Foo a
1245 instance Foo t => Sat (Maybe t)
1247 instance Data Maybe a => Foo a
1248 instance Foo a => Foo [a]
1251 In the instance for Foo [a], when generating evidence for the superclasses
1252 (ie in tcSimplifySuperClasses) we need a superclass (Data Maybe [a]).
1253 Using the instance for Data, we therefore need
1254 (Sat (Maybe [a], Data Maybe a)
1255 But we are given (Foo a), and hence its superclass (Data Maybe a).
1256 So that leaves (Sat (Maybe [a])). Using the instance for Sat means
1257 we need (Foo [a]). And that is the very dictionary we are bulding
1258 an instance for! So we must put that in the "givens". So in this
1260 Given: Foo a, Foo [a]
1261 Watend: Data Maybe [a]
1263 BUT we must *not not not* put the *superclasses* of (Foo [a]) in
1264 the givens, which is what 'addGiven' would normally do. Why? Because
1265 (Data Maybe [a]) is the superclass, so we'd "satisfy" the wanted
1266 by selecting a superclass from Foo [a], which simply makes a loop.
1268 On the other hand we *must* put the superclasses of (Foo a) in
1269 the givens, as you can see from the derivation described above.
1271 Conclusion: in the very special case of tcSimplifySuperClasses
1272 we have one 'given' (namely the "this" dictionary) whose superclasses
1273 must not be added to 'givens' by addGiven.
1275 There is a complication though. Suppose there are equalities
1276 instance (Eq a, a~b) => Num (a,b)
1277 Then we normalise the 'givens' wrt the equalities, so the original
1278 given "this" dictionary is cast to one of a different type. So it's a
1279 bit trickier than before to identify the "special" dictionary whose
1280 superclasses must not be added. See test
1281 indexed-types/should_run/EqInInstance
1283 We need a persistent property of the dictionary to record this
1284 special-ness. Current I'm using the InstLocOrigin (a bit of a hack,
1285 but cool), which is maintained by dictionary normalisation.
1286 Specifically, the InstLocOrigin is
1288 then the no-superclass thing kicks in. WATCH OUT if you fiddle
1292 tcSimplifySuperClasses
1294 -> Inst -- The dict whose superclasses
1295 -- are being figured out
1299 tcSimplifySuperClasses loc this givens sc_wanteds
1300 = do { traceTc (text "tcSimplifySuperClasses")
1302 -- Note [Recursive instances and superclases]
1303 ; no_sc_loc <- getInstLoc NoScOrigin
1304 ; let no_sc_this = setInstLoc this no_sc_loc
1306 ; let env = RedEnv { red_doc = pprInstLoc loc,
1307 red_try_me = try_me,
1308 red_givens = no_sc_this : givens,
1310 red_improve = False } -- No unification vars
1313 ; (irreds,binds1) <- checkLoop env sc_wanteds
1314 ; let (tidy_env, tidy_irreds) = tidyInsts irreds
1315 ; reportNoInstances tidy_env (Just (loc, givens)) [] tidy_irreds
1318 try_me _ = ReduceMe -- Try hard, so we completely solve the superclass
1319 -- constraints right here. See Note [SUPERCLASS-LOOP 1]
1323 %************************************************************************
1325 \subsection{tcSimplifyRestricted}
1327 %************************************************************************
1329 tcSimplifyRestricted infers which type variables to quantify for a
1330 group of restricted bindings. This isn't trivial.
1333 We want to quantify over a to get id :: forall a. a->a
1336 We do not want to quantify over a, because there's an Eq a
1337 constraint, so we get eq :: a->a->Bool (notice no forall)
1340 RHS has type 'tau', whose free tyvars are tau_tvs
1341 RHS has constraints 'wanteds'
1344 Quantify over (tau_tvs \ ftvs(wanteds))
1345 This is bad. The constraints may contain (Monad (ST s))
1346 where we have instance Monad (ST s) where...
1347 so there's no need to be monomorphic in s!
1349 Also the constraint might be a method constraint,
1350 whose type mentions a perfectly innocent tyvar:
1351 op :: Num a => a -> b -> a
1352 Here, b is unconstrained. A good example would be
1354 We want to infer the polymorphic type
1355 foo :: forall b. b -> b
1358 Plan B (cunning, used for a long time up to and including GHC 6.2)
1359 Step 1: Simplify the constraints as much as possible (to deal
1360 with Plan A's problem). Then set
1361 qtvs = tau_tvs \ ftvs( simplify( wanteds ) )
1363 Step 2: Now simplify again, treating the constraint as 'free' if
1364 it does not mention qtvs, and trying to reduce it otherwise.
1365 The reasons for this is to maximise sharing.
1367 This fails for a very subtle reason. Suppose that in the Step 2
1368 a constraint (Foo (Succ Zero) (Succ Zero) b) gets thrown upstairs as 'free'.
1369 In the Step 1 this constraint might have been simplified, perhaps to
1370 (Foo Zero Zero b), AND THEN THAT MIGHT BE IMPROVED, to bind 'b' to 'T'.
1371 This won't happen in Step 2... but that in turn might prevent some other
1372 constraint (Baz [a] b) being simplified (e.g. via instance Baz [a] T where {..})
1373 and that in turn breaks the invariant that no constraints are quantified over.
1375 Test typecheck/should_compile/tc177 (which failed in GHC 6.2) demonstrates
1380 Step 1: Simplify the constraints as much as possible (to deal
1381 with Plan A's problem). Then set
1382 qtvs = tau_tvs \ ftvs( simplify( wanteds ) )
1383 Return the bindings from Step 1.
1386 A note about Plan C (arising from "bug" reported by George Russel March 2004)
1389 instance (HasBinary ty IO) => HasCodedValue ty
1391 foo :: HasCodedValue a => String -> IO a
1393 doDecodeIO :: HasCodedValue a => () -> () -> IO a
1394 doDecodeIO codedValue view
1395 = let { act = foo "foo" } in act
1397 You might think this should work becuase the call to foo gives rise to a constraint
1398 (HasCodedValue t), which can be satisfied by the type sig for doDecodeIO. But the
1399 restricted binding act = ... calls tcSimplifyRestricted, and PlanC simplifies the
1400 constraint using the (rather bogus) instance declaration, and now we are stuffed.
1402 I claim this is not really a bug -- but it bit Sergey as well as George. So here's
1406 Plan D (a variant of plan B)
1407 Step 1: Simplify the constraints as much as possible (to deal
1408 with Plan A's problem), BUT DO NO IMPROVEMENT. Then set
1409 qtvs = tau_tvs \ ftvs( simplify( wanteds ) )
1411 Step 2: Now simplify again, treating the constraint as 'free' if
1412 it does not mention qtvs, and trying to reduce it otherwise.
1414 The point here is that it's generally OK to have too few qtvs; that is,
1415 to make the thing more monomorphic than it could be. We don't want to
1416 do that in the common cases, but in wierd cases it's ok: the programmer
1417 can always add a signature.
1419 Too few qtvs => too many wanteds, which is what happens if you do less
1424 tcSimplifyRestricted -- Used for restricted binding groups
1425 -- i.e. ones subject to the monomorphism restriction
1428 -> [Name] -- Things bound in this group
1429 -> TcTyVarSet -- Free in the type of the RHSs
1430 -> [Inst] -- Free in the RHSs
1431 -> TcM ([TyVar], -- Tyvars to quantify (zonked and quantified)
1432 TcDictBinds) -- Bindings
1433 -- tcSimpifyRestricted returns no constraints to
1434 -- quantify over; by definition there are none.
1435 -- They are all thrown back in the LIE
1437 tcSimplifyRestricted doc top_lvl bndrs tau_tvs wanteds
1438 -- Zonk everything in sight
1439 = do { traceTc (text "tcSimplifyRestricted")
1440 ; wanteds_z <- zonkInsts wanteds
1442 -- 'ReduceMe': Reduce as far as we can. Don't stop at
1443 -- dicts; the idea is to get rid of as many type
1444 -- variables as possible, and we don't want to stop
1445 -- at (say) Monad (ST s), because that reduces
1446 -- immediately, with no constraint on s.
1448 -- BUT do no improvement! See Plan D above
1449 -- HOWEVER, some unification may take place, if we instantiate
1450 -- a method Inst with an equality constraint
1451 ; let env = mkNoImproveRedEnv doc (\_ -> ReduceMe)
1452 ; (_imp, _tybinds, _binds, constrained_dicts)
1453 <- reduceContext env wanteds_z
1455 -- Next, figure out the tyvars we will quantify over
1456 ; tau_tvs' <- zonkTcTyVarsAndFV (varSetElems tau_tvs)
1457 ; gbl_tvs' <- tcGetGlobalTyVars
1458 ; constrained_dicts' <- zonkInsts constrained_dicts
1460 ; let qtvs1 = tau_tvs' `minusVarSet` oclose (fdPredsOfInsts constrained_dicts) gbl_tvs'
1461 -- As in tcSimplifyInfer
1463 -- Do not quantify over constrained type variables:
1464 -- this is the monomorphism restriction
1465 constrained_tvs' = tyVarsOfInsts constrained_dicts'
1466 qtvs = qtvs1 `minusVarSet` constrained_tvs'
1467 pp_bndrs = pprWithCommas (quotes . ppr) bndrs
1470 ; warn_mono <- doptM Opt_WarnMonomorphism
1471 ; warnTc (warn_mono && (constrained_tvs' `intersectsVarSet` qtvs1))
1472 (vcat[ ptext (sLit "the Monomorphism Restriction applies to the binding")
1473 <> plural bndrs <+> ptext (sLit "for") <+> pp_bndrs,
1474 ptext (sLit "Consider giving a type signature for") <+> pp_bndrs])
1476 ; traceTc (text "tcSimplifyRestricted" <+> vcat [
1477 pprInsts wanteds, pprInsts constrained_dicts',
1479 ppr constrained_tvs', ppr tau_tvs', ppr qtvs ])
1481 -- The first step may have squashed more methods than
1482 -- necessary, so try again, this time more gently, knowing the exact
1483 -- set of type variables to quantify over.
1485 -- We quantify only over constraints that are captured by qtvs;
1486 -- these will just be a subset of non-dicts. This in contrast
1487 -- to normal inference (using isFreeWhenInferring) in which we quantify over
1488 -- all *non-inheritable* constraints too. This implements choice
1489 -- (B) under "implicit parameter and monomorphism" above.
1491 -- Remember that we may need to do *some* simplification, to
1492 -- (for example) squash {Monad (ST s)} into {}. It's not enough
1493 -- just to float all constraints
1495 -- At top level, we *do* squash methods because we want to
1496 -- expose implicit parameters to the test that follows
1497 ; let is_nested_group = isNotTopLevel top_lvl
1498 try_me inst | isFreeWrtTyVars qtvs inst,
1499 (is_nested_group || isDict inst) = Stop
1500 | otherwise = ReduceMe
1501 env = mkNoImproveRedEnv doc try_me
1502 ; (_imp, tybinds, binds, irreds) <- reduceContext env wanteds_z
1503 ; execTcTyVarBinds tybinds
1505 -- See "Notes on implicit parameters, Question 4: top level"
1506 ; ASSERT( all (isFreeWrtTyVars qtvs) irreds ) -- None should be captured
1507 if is_nested_group then
1509 else do { let (bad_ips, non_ips) = partition isIPDict irreds
1510 ; addTopIPErrs bndrs bad_ips
1511 ; extendLIEs non_ips }
1513 ; qtvs' <- zonkQuantifiedTyVars (varSetElems qtvs)
1514 ; return (qtvs', binds) }
1518 %************************************************************************
1522 %************************************************************************
1524 On the LHS of transformation rules we only simplify methods and constants,
1525 getting dictionaries. We want to keep all of them unsimplified, to serve
1526 as the available stuff for the RHS of the rule.
1528 Example. Consider the following left-hand side of a rule
1530 f (x == y) (y > z) = ...
1532 If we typecheck this expression we get constraints
1534 d1 :: Ord a, d2 :: Eq a
1536 We do NOT want to "simplify" to the LHS
1538 forall x::a, y::a, z::a, d1::Ord a.
1539 f ((==) (eqFromOrd d1) x y) ((>) d1 y z) = ...
1543 forall x::a, y::a, z::a, d1::Ord a, d2::Eq a.
1544 f ((==) d2 x y) ((>) d1 y z) = ...
1546 Here is another example:
1548 fromIntegral :: (Integral a, Num b) => a -> b
1549 {-# RULES "foo" fromIntegral = id :: Int -> Int #-}
1551 In the rule, a=b=Int, and Num Int is a superclass of Integral Int. But
1552 we *dont* want to get
1554 forall dIntegralInt.
1555 fromIntegral Int Int dIntegralInt (scsel dIntegralInt) = id Int
1557 because the scsel will mess up RULE matching. Instead we want
1559 forall dIntegralInt, dNumInt.
1560 fromIntegral Int Int dIntegralInt dNumInt = id Int
1564 g (x == y) (y == z) = ..
1566 where the two dictionaries are *identical*, we do NOT WANT
1568 forall x::a, y::a, z::a, d1::Eq a
1569 f ((==) d1 x y) ((>) d1 y z) = ...
1571 because that will only match if the dict args are (visibly) equal.
1572 Instead we want to quantify over the dictionaries separately.
1574 In short, tcSimplifyRuleLhs must *only* squash LitInst and MethInts, leaving
1575 all dicts unchanged, with absolutely no sharing. It's simpler to do this
1576 from scratch, rather than further parameterise simpleReduceLoop etc.
1577 Simpler, maybe, but alas not simple (see Trac #2494)
1579 * Type errors may give rise to an (unsatisfiable) equality constraint
1581 * Applications of a higher-rank function on the LHS may give
1582 rise to an implication constraint, esp if there are unsatisfiable
1583 equality constraints inside.
1586 tcSimplifyRuleLhs :: [Inst] -> TcM ([Inst], TcDictBinds)
1587 tcSimplifyRuleLhs wanteds
1588 = do { wanteds' <- zonkInsts wanteds
1590 -- Simplify equalities
1591 -- It's important to do this: Trac #3346 for example
1592 ; (_, wanteds'', tybinds, binds1) <- tcReduceEqs [] wanteds'
1593 ; execTcTyVarBinds tybinds
1595 -- Simplify other constraints
1596 ; (irreds, binds2) <- go [] emptyBag wanteds''
1598 -- Report anything that is left
1599 ; let (dicts, bad_irreds) = partition isDict irreds
1600 ; traceTc (text "tcSimplifyrulelhs" <+> pprInsts bad_irreds)
1601 ; addNoInstanceErrs (nub bad_irreds)
1602 -- The nub removes duplicates, which has
1603 -- not happened otherwise (see notes above)
1605 ; return (dicts, binds1 `unionBags` binds2) }
1607 go :: [Inst] -> TcDictBinds -> [Inst] -> TcM ([Inst], TcDictBinds)
1609 = return (irreds, binds)
1610 go irreds binds (w:ws)
1612 = go (w:irreds) binds ws
1613 | isImplicInst w -- Have a go at reducing the implication
1614 = do { (binds1, irreds1) <- reduceImplication red_env w
1615 ; let (bad_irreds, ok_irreds) = partition isImplicInst irreds1
1616 ; go (bad_irreds ++ irreds)
1617 (binds `unionBags` binds1)
1620 = do { w' <- zonkInst w -- So that (3::Int) does not generate a call
1621 -- to fromInteger; this looks fragile to me
1622 ; lookup_result <- lookupSimpleInst w'
1623 ; case lookup_result of
1624 NoInstance -> go (w:irreds) binds ws
1625 GenInst ws' rhs -> go irreds binds' (ws' ++ ws)
1627 binds' = addInstToDictBind binds w rhs
1630 -- Sigh: we need to reduce inside implications
1631 red_env = mkInferRedEnv doc try_me
1632 doc = ptext (sLit "Implication constraint in RULE lhs")
1633 try_me inst | isMethodOrLit inst = ReduceMe
1634 | otherwise = Stop -- Be gentle
1637 tcSimplifyBracket is used when simplifying the constraints arising from
1638 a Template Haskell bracket [| ... |]. We want to check that there aren't
1639 any constraints that can't be satisfied (e.g. Show Foo, where Foo has no
1640 Show instance), but we aren't otherwise interested in the results.
1641 Nor do we care about ambiguous dictionaries etc. We will type check
1642 this bracket again at its usage site.
1645 tcSimplifyBracket :: [Inst] -> TcM ()
1646 tcSimplifyBracket wanteds
1647 = do { _ <- tryHardCheckLoop doc wanteds
1650 doc = text "tcSimplifyBracket"
1654 %************************************************************************
1656 \subsection{Filtering at a dynamic binding}
1658 %************************************************************************
1663 we must discharge all the ?x constraints from B. We also do an improvement
1664 step; if we have ?x::t1 and ?x::t2 we must unify t1, t2.
1666 Actually, the constraints from B might improve the types in ?x. For example
1668 f :: (?x::Int) => Char -> Char
1671 then the constraint (?x::Int) arising from the call to f will
1672 force the binding for ?x to be of type Int.
1675 tcSimplifyIPs :: [Inst] -- The implicit parameters bound here
1678 -- We need a loop so that we do improvement, and then
1679 -- (next time round) generate a binding to connect the two
1681 -- Here the two ?x's have different types, and improvement
1682 -- makes them the same.
1684 tcSimplifyIPs given_ips wanteds
1685 = do { wanteds' <- zonkInsts wanteds
1686 ; given_ips' <- zonkInsts given_ips
1687 -- Unusually for checking, we *must* zonk the given_ips
1689 ; let env = mkRedEnv doc try_me given_ips'
1690 ; (improved, tybinds, binds, irreds) <- reduceContext env wanteds'
1691 ; execTcTyVarBinds tybinds
1693 ; if null irreds || not improved then
1694 ASSERT( all is_free irreds )
1695 do { extendLIEs irreds
1698 -- If improvement did some unification, we go round again.
1699 -- We start again with irreds, not wanteds
1700 -- Using an instance decl might have introduced a fresh type
1701 -- variable which might have been unified, so we'd get an
1702 -- infinite loop if we started again with wanteds!
1704 { binds1 <- tcSimplifyIPs given_ips' irreds
1705 ; return $ binds `unionBags` binds1
1708 doc = text "tcSimplifyIPs" <+> ppr given_ips
1709 ip_set = mkNameSet (ipNamesOfInsts given_ips)
1710 is_free inst = isFreeWrtIPs ip_set inst
1712 -- Simplify any methods that mention the implicit parameter
1713 try_me inst | is_free inst = Stop
1714 | otherwise = ReduceMe
1718 %************************************************************************
1720 \subsection[binds-for-local-funs]{@bindInstsOfLocalFuns@}
1722 %************************************************************************
1724 When doing a binding group, we may have @Insts@ of local functions.
1725 For example, we might have...
1727 let f x = x + 1 -- orig local function (overloaded)
1728 f.1 = f Int -- two instances of f
1733 The point is: we must drop the bindings for @f.1@ and @f.2@ here,
1734 where @f@ is in scope; those @Insts@ must certainly not be passed
1735 upwards towards the top-level. If the @Insts@ were binding-ified up
1736 there, they would have unresolvable references to @f@.
1738 We pass in an @init_lie@ of @Insts@ and a list of locally-bound @Ids@.
1739 For each method @Inst@ in the @init_lie@ that mentions one of the
1740 @Ids@, we create a binding. We return the remaining @Insts@ (in an
1741 @LIE@), as well as the @HsBinds@ generated.
1744 bindInstsOfLocalFuns :: [Inst] -> [TcId] -> TcM TcDictBinds
1745 -- Simlifies only MethodInsts, and generate only bindings of form
1747 -- We're careful not to even generate bindings of the form
1749 -- You'd think that'd be fine, but it interacts with what is
1750 -- arguably a bug in Match.tidyEqnInfo (see notes there)
1752 bindInstsOfLocalFuns wanteds local_ids
1753 | null overloaded_ids = do
1756 return emptyLHsBinds
1759 = do { (irreds, binds) <- gentleInferLoop doc for_me
1760 ; extendLIEs not_for_me
1764 doc = text "bindInsts" <+> ppr local_ids
1765 overloaded_ids = filter is_overloaded local_ids
1766 is_overloaded id = isOverloadedTy (idType id)
1767 (for_me, not_for_me) = partition (isMethodFor overloaded_set) wanteds
1769 overloaded_set = mkVarSet overloaded_ids -- There can occasionally be a lot of them
1770 -- so it's worth building a set, so that
1771 -- lookup (in isMethodFor) is faster
1775 %************************************************************************
1777 \subsection{Data types for the reduction mechanism}
1779 %************************************************************************
1781 The main control over context reduction is here
1785 = RedEnv { red_doc :: SDoc -- The context
1786 , red_try_me :: Inst -> WhatToDo
1787 , red_improve :: Bool -- True <=> do improvement
1788 , red_givens :: [Inst] -- All guaranteed rigid
1789 -- Always dicts & equalities
1790 -- but see Note [Rigidity]
1792 , red_stack :: (Int, [Inst]) -- Recursion stack (for err msg)
1793 -- See Note [RedStack]
1797 -- The red_givens are rigid so far as cmpInst is concerned.
1798 -- There is one case where they are not totally rigid, namely in tcSimplifyIPs
1799 -- let ?x = e in ...
1800 -- Here, the given is (?x::a), where 'a' is not necy a rigid type
1801 -- But that doesn't affect the comparison, which is based only on mame.
1804 -- The red_stack pair (n,insts) pair is just used for error reporting.
1805 -- 'n' is always the depth of the stack.
1806 -- The 'insts' is the stack of Insts being reduced: to produce X
1807 -- I had to produce Y, to produce Y I had to produce Z, and so on.
1810 mkRedEnv :: SDoc -> (Inst -> WhatToDo) -> [Inst] -> RedEnv
1811 mkRedEnv doc try_me givens
1812 = RedEnv { red_doc = doc, red_try_me = try_me,
1813 red_givens = givens,
1815 red_improve = True }
1817 mkInferRedEnv :: SDoc -> (Inst -> WhatToDo) -> RedEnv
1819 mkInferRedEnv doc try_me
1820 = RedEnv { red_doc = doc, red_try_me = try_me,
1823 red_improve = True }
1825 mkNoImproveRedEnv :: SDoc -> (Inst -> WhatToDo) -> RedEnv
1826 -- Do not do improvement; no givens
1827 mkNoImproveRedEnv doc try_me
1828 = RedEnv { red_doc = doc, red_try_me = try_me,
1831 red_improve = True }
1834 = ReduceMe -- Try to reduce this
1835 -- If there's no instance, add the inst to the
1836 -- irreductible ones, but don't produce an error
1837 -- message of any kind.
1838 -- It might be quite legitimate such as (Eq a)!
1840 | Stop -- Return as irreducible unless it can
1841 -- be reduced to a constant in one step
1842 -- Do not add superclasses; see
1844 data WantSCs = NoSCs | AddSCs -- Tells whether we should add the superclasses
1845 -- of a predicate when adding it to the avails
1846 -- The reason for this flag is entirely the super-class loop problem
1847 -- Note [SUPER-CLASS LOOP 1]
1849 zonkRedEnv :: RedEnv -> TcM RedEnv
1851 = do { givens' <- mapM zonkInst (red_givens env)
1852 ; return $ env {red_givens = givens'}
1857 %************************************************************************
1859 \subsection[reduce]{@reduce@}
1861 %************************************************************************
1863 Note [Ancestor Equalities]
1864 ~~~~~~~~~~~~~~~~~~~~~~~~~~
1865 During context reduction, we add to the wanted equalities also those
1866 equalities that (transitively) occur in superclass contexts of wanted
1867 class constraints. Consider the following code
1869 class a ~ Int => C a
1872 If (C a) is wanted, we want to add (a ~ Int), which will be discharged by
1873 substituting Int for a. Hence, we ultimately want (C Int), which we
1874 discharge with the explicit instance.
1877 reduceContext :: RedEnv
1879 -> TcM (ImprovementDone,
1880 TcTyVarBinds, -- Type variable bindings
1881 TcDictBinds, -- Dictionary bindings
1882 [Inst]) -- Irreducible
1884 reduceContext env wanteds0
1885 = do { traceTc (text "reduceContext" <+> (vcat [
1886 text "----------------------",
1888 text "given" <+> ppr (red_givens env),
1889 text "wanted" <+> ppr wanteds0,
1890 text "----------------------"
1893 -- We want to add as wanted equalities those that (transitively)
1894 -- occur in superclass contexts of wanted class constraints.
1895 -- See Note [Ancestor Equalities]
1896 ; ancestor_eqs <- ancestorEqualities wanteds0
1897 ; traceTc $ text "reduceContext: ancestor eqs" <+> ppr ancestor_eqs
1899 -- Normalise and solve all equality constraints as far as possible
1900 -- and normalise all dictionary constraints wrt to the reduced
1901 -- equalities. The returned wanted constraints include the
1902 -- irreducible wanted equalities.
1903 ; let wanteds = wanteds0 ++ ancestor_eqs
1904 givens = red_givens env
1908 normalise_binds) <- tcReduceEqs givens wanteds
1909 ; traceTc $ text "reduceContext: tcReduceEqs result" <+> vcat
1910 [ppr givens', ppr wanteds', ppr tybinds,
1911 ppr normalise_binds]
1913 -- Build the Avail mapping from "given_dicts"
1914 ; (init_state, _) <- getLIE $ do
1915 { init_state <- foldlM addGiven emptyAvails givens'
1919 -- Solve the *wanted* *dictionary* constraints (not implications)
1920 -- This may expose some further equational constraints in the course
1921 -- of improvement due to functional dependencies if any of the
1922 -- involved unifications gets deferred.
1923 ; let (wanted_implics, wanted_dicts) = partition isImplicInst wanteds'
1924 ; (avails, extra_eqs) <- getLIE (reduceList env wanted_dicts init_state)
1925 -- The getLIE is reqd because reduceList does improvement
1926 -- (via extendAvails) which may in turn do unification
1929 dict_irreds) <- extractResults avails wanted_dicts
1930 ; traceTc $ text "reduceContext: extractResults" <+> vcat
1931 [ppr avails, ppr wanted_dicts, ppr dict_binds]
1933 -- Solve the wanted *implications*. In doing so, we can provide
1934 -- as "given" all the dicts that were originally given,
1935 -- *or* for which we now have bindings,
1936 -- *or* which are now irreds
1937 -- NB: Equality irreds need to be converted, as the recursive
1938 -- invocation of the solver will still treat them as wanteds
1940 ; let implic_env = env { red_givens
1941 = givens ++ bound_dicts ++
1942 map wantedToLocalEqInst dict_irreds }
1943 ; (implic_binds_s, implic_irreds_s)
1944 <- mapAndUnzipM (reduceImplication implic_env) wanted_implics
1945 ; let implic_binds = unionManyBags implic_binds_s
1946 implic_irreds = concat implic_irreds_s
1948 -- Collect all irreducible instances, and determine whether we should
1949 -- go round again. We do so in either of two cases:
1950 -- (1) If dictionary reduction or equality solving led to
1951 -- improvement (i.e., bindings for type variables).
1952 -- (2) If we reduced dictionaries (i.e., got dictionary bindings),
1953 -- they may have exposed further opportunities to normalise
1954 -- family applications. See Note [Dictionary Improvement]
1956 -- NB: We do *not* go around for new extra_eqs. Morally, we should,
1957 -- but we can't without risking non-termination (see #2688). By
1958 -- not going around, we miss some legal programs mixing FDs and
1959 -- TFs, but we never claimed to support such programs in the
1960 -- current implementation anyway.
1962 ; let all_irreds = dict_irreds ++ implic_irreds ++ extra_eqs
1963 avails_improved = availsImproved avails
1964 eq_improved = anyBag (not . isCoVarBind) tybinds
1965 improvedFlexible = avails_improved || eq_improved
1966 reduced_dicts = not (isEmptyBag dict_binds)
1967 improved = improvedFlexible || reduced_dicts
1969 improvedHint = (if avails_improved then " [AVAILS]" else "") ++
1970 (if eq_improved then " [EQ]" else "")
1972 ; traceTc (text "reduceContext end" <+> (vcat [
1973 text "----------------------",
1975 text "given" <+> ppr givens,
1976 text "wanted" <+> ppr wanteds0,
1978 text "tybinds" <+> ppr tybinds,
1979 text "avails" <+> pprAvails avails,
1980 text "improved =" <+> ppr improved <+> text improvedHint,
1981 text "(all) irreds = " <+> ppr all_irreds,
1982 text "dict-binds = " <+> ppr dict_binds,
1983 text "implic-binds = " <+> ppr implic_binds,
1984 text "----------------------"
1989 normalise_binds `unionBags` dict_binds
1990 `unionBags` implic_binds,
1994 isCoVarBind (TcTyVarBind tv _) = isCoVar tv
1996 tcImproveOne :: Avails -> Inst -> TcM ImprovementDone
1997 tcImproveOne avails inst
1998 | not (isDict inst) = return False
2000 = do { inst_envs <- tcGetInstEnvs
2001 ; let eqns = improveOne (classInstances inst_envs)
2002 (dictPred inst, pprInstArising inst)
2003 [ (dictPred p, pprInstArising p)
2004 | p <- availsInsts avails, isDict p ]
2005 -- Avails has all the superclasses etc (good)
2006 -- It also has all the intermediates of the deduction (good)
2007 -- It does not have duplicates (good)
2008 -- NB that (?x::t1) and (?x::t2) will be held separately in
2009 -- avails so that improve will see them separate
2010 ; traceTc (text "improveOne" <+> ppr inst)
2013 unifyEqns :: [(Equation, (PredType, SDoc), (PredType, SDoc))]
2014 -> TcM ImprovementDone
2015 unifyEqns [] = return False
2017 = do { traceTc (ptext (sLit "Improve:") <+> vcat (map pprEquationDoc eqns))
2018 ; improved <- mapM unify eqns
2019 ; return $ or improved
2022 unify ((qtvs, pairs), what1, what2)
2023 = addErrCtxtM (mkEqnMsg what1 what2) $
2024 do { let freeTyVars = unionVarSets (map tvs_pr pairs)
2026 ; (_, _, tenv) <- tcInstTyVars (varSetElems qtvs)
2027 ; mapM_ (unif_pr tenv) pairs
2028 ; anyM isFilledMetaTyVar $ varSetElems freeTyVars
2031 unif_pr tenv (ty1, ty2) = unifyType (substTy tenv ty1) (substTy tenv ty2)
2033 tvs_pr (ty1, ty2) = tyVarsOfType ty1 `unionVarSet` tyVarsOfType ty2
2035 pprEquationDoc :: (Equation, (PredType, SDoc), (PredType, SDoc)) -> SDoc
2036 pprEquationDoc (eqn, (p1, _), (p2, _))
2037 = vcat [pprEquation eqn, nest 2 (ppr p1), nest 2 (ppr p2)]
2039 mkEqnMsg :: (TcPredType, SDoc) -> (TcPredType, SDoc) -> TidyEnv
2040 -> TcM (TidyEnv, SDoc)
2041 mkEqnMsg (pred1,from1) (pred2,from2) tidy_env
2042 = do { pred1' <- zonkTcPredType pred1
2043 ; pred2' <- zonkTcPredType pred2
2044 ; let { pred1'' = tidyPred tidy_env pred1'
2045 ; pred2'' = tidyPred tidy_env pred2' }
2046 ; let msg = vcat [ptext (sLit "When using functional dependencies to combine"),
2047 nest 2 (sep [ppr pred1'' <> comma, nest 2 from1]),
2048 nest 2 (sep [ppr pred2'' <> comma, nest 2 from2])]
2049 ; return (tidy_env, msg) }
2052 Note [Dictionary Improvement]
2053 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2054 In reduceContext, we first reduce equalities and then class constraints.
2055 However, the letter may expose further opportunities for the former. Hence,
2056 we need to go around again if dictionary reduction produced any dictionary
2057 bindings. The following example demonstrated the point:
2059 data EX _x _y (p :: * -> *)
2064 class Base (Def p) => Prop p where
2068 instance Prop () where
2071 instance (Base (Def (p ANY))) => Base (EX _x _y p)
2072 instance (Prop (p ANY)) => Prop (EX _x _y p) where
2073 type Def (EX _x _y p) = EX _x _y p
2076 instance Prop (FOO x) where
2077 type Def (FOO x) = ()
2080 instance Prop BAR where
2081 type Def BAR = EX () () FOO
2083 During checking the last instance declaration, we need to check the superclass
2084 cosntraint Base (Def BAR), which family normalisation reduced to
2085 Base (EX () () FOO). Chasing the instance for Base (EX _x _y p), gives us
2086 Base (Def (FOO ANY)), which again requires family normalisation of Def to
2087 Base () before we can finish.
2090 The main context-reduction function is @reduce@. Here's its game plan.
2093 reduceList :: RedEnv -> [Inst] -> Avails -> TcM Avails
2094 reduceList env@(RedEnv {red_stack = (n,stk)}) wanteds state
2095 = do { traceTc (text "reduceList " <+> (ppr wanteds $$ ppr state))
2097 ; when (debugIsOn && (n > 8)) $ do
2098 debugDumpTcRn (hang (ptext (sLit "Interesting! Context reduction stack depth") <+> int n)
2099 2 (ifPprDebug (nest 2 (pprStack stk))))
2100 ; if n >= ctxtStkDepth dopts then
2101 failWithTc (reduceDepthErr n stk)
2105 go [] state = return state
2106 go (w:ws) state = do { state' <- reduce (env {red_stack = (n+1, w:stk)}) w state
2109 -- Base case: we're done!
2110 reduce :: RedEnv -> Inst -> Avails -> TcM Avails
2111 reduce env wanted avails
2113 -- We don't reduce equalities here (and they must not end up as irreds
2118 -- It's the same as an existing inst, or a superclass thereof
2119 | Just _ <- findAvail avails wanted
2120 = do { traceTc (text "reduce: found " <+> ppr wanted)
2125 = do { traceTc (text "reduce" <+> ppr wanted $$ ppr avails)
2126 ; case red_try_me env wanted of {
2127 Stop -> try_simple (addIrred NoSCs);
2128 -- See Note [No superclasses for Stop]
2130 ReduceMe -> do -- It should be reduced
2131 { (avails, lookup_result) <- reduceInst env avails wanted
2132 ; case lookup_result of
2133 NoInstance -> addIrred AddSCs avails wanted
2134 -- Add it and its superclasses
2136 GenInst [] rhs -> addWanted AddSCs avails wanted rhs []
2138 GenInst wanteds' rhs
2139 -> do { avails1 <- addIrred NoSCs avails wanted
2140 ; avails2 <- reduceList env wanteds' avails1
2141 ; addWanted AddSCs avails2 wanted rhs wanteds' } }
2142 -- Temporarily do addIrred *before* the reduceList,
2143 -- which has the effect of adding the thing we are trying
2144 -- to prove to the database before trying to prove the things it
2145 -- needs. See note [RECURSIVE DICTIONARIES]
2146 -- NB: we must not do an addWanted before, because that adds the
2147 -- superclasses too, and that can lead to a spurious loop; see
2148 -- the examples in [SUPERCLASS-LOOP]
2149 -- So we do an addIrred before, and then overwrite it afterwards with addWanted
2152 -- First, see if the inst can be reduced to a constant in one step
2153 -- Works well for literals (1::Int) and constant dictionaries (d::Num Int)
2154 -- Don't bother for implication constraints, which take real work
2155 try_simple do_this_otherwise
2156 = do { res <- lookupSimpleInst wanted
2158 GenInst [] rhs -> addWanted AddSCs avails wanted rhs []
2159 _ -> do_this_otherwise avails wanted }
2163 Note [RECURSIVE DICTIONARIES]
2164 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2166 data D r = ZeroD | SuccD (r (D r));
2168 instance (Eq (r (D r))) => Eq (D r) where
2169 ZeroD == ZeroD = True
2170 (SuccD a) == (SuccD b) = a == b
2173 equalDC :: D [] -> D [] -> Bool;
2176 We need to prove (Eq (D [])). Here's how we go:
2180 by instance decl, holds if
2184 by instance decl of Eq, holds if
2186 where d2 = dfEqList d3
2189 But now we can "tie the knot" to give
2195 and it'll even run! The trick is to put the thing we are trying to prove
2196 (in this case Eq (D []) into the database before trying to prove its
2197 contributing clauses.
2199 Note [SUPERCLASS-LOOP 2]
2200 ~~~~~~~~~~~~~~~~~~~~~~~~
2201 We need to be careful when adding "the constaint we are trying to prove".
2202 Suppose we are *given* d1:Ord a, and want to deduce (d2:C [a]) where
2204 class Ord a => C a where
2205 instance Ord [a] => C [a] where ...
2207 Then we'll use the instance decl to deduce C [a] from Ord [a], and then add the
2208 superclasses of C [a] to avails. But we must not overwrite the binding
2209 for Ord [a] (which is obtained from Ord a) with a superclass selection or we'll just
2212 Here's another variant, immortalised in tcrun020
2213 class Monad m => C1 m
2214 class C1 m => C2 m x
2215 instance C2 Maybe Bool
2216 For the instance decl we need to build (C1 Maybe), and it's no good if
2217 we run around and add (C2 Maybe Bool) and its superclasses to the avails
2218 before we search for C1 Maybe.
2220 Here's another example
2221 class Eq b => Foo a b
2222 instance Eq a => Foo [a] a
2226 we'll first deduce that it holds (via the instance decl). We must not
2227 then overwrite the Eq t constraint with a superclass selection!
2229 At first I had a gross hack, whereby I simply did not add superclass constraints
2230 in addWanted, though I did for addGiven and addIrred. This was sub-optimal,
2231 becuase it lost legitimate superclass sharing, and it still didn't do the job:
2232 I found a very obscure program (now tcrun021) in which improvement meant the
2233 simplifier got two bites a the cherry... so something seemed to be an Stop
2234 first time, but reducible next time.
2236 Now we implement the Right Solution, which is to check for loops directly
2237 when adding superclasses. It's a bit like the occurs check in unification.
2241 %************************************************************************
2243 Reducing a single constraint
2245 %************************************************************************
2248 ---------------------------------------------
2249 reduceInst :: RedEnv -> Avails -> Inst -> TcM (Avails, LookupInstResult)
2250 reduceInst _ avails other_inst
2251 = do { result <- lookupSimpleInst other_inst
2252 ; return (avails, result) }
2255 Note [Equational Constraints in Implication Constraints]
2256 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2258 An implication constraint is of the form
2260 where Given and Wanted may contain both equational and dictionary
2261 constraints. The delay and reduction of these two kinds of constraints
2264 -) In the generated code, wanted Dictionary constraints are wrapped up in an
2265 implication constraint that is created at the code site where the wanted
2266 dictionaries can be reduced via a let-binding. This let-bound implication
2267 constraint is deconstructed at the use-site of the wanted dictionaries.
2269 -) While the reduction of equational constraints is also delayed, the delay
2270 is not manifest in the generated code. The required evidence is generated
2271 in the code directly at the use-site. There is no let-binding and deconstruction
2272 necessary. The main disadvantage is that we cannot exploit sharing as the
2273 same evidence may be generated at multiple use-sites. However, this disadvantage
2274 is limited because it only concerns coercions which are erased.
2276 The different treatment is motivated by the different in representation. Dictionary
2277 constraints require manifest runtime dictionaries, while equations require coercions
2281 ---------------------------------------------
2282 reduceImplication :: RedEnv
2284 -> TcM (TcDictBinds, [Inst])
2287 Suppose we are simplifying the constraint
2288 forall bs. extras => wanted
2289 in the context of an overall simplification problem with givens 'givens'.
2292 * The 'givens' need not mention any of the quantified type variables
2293 e.g. forall {}. Eq a => Eq [a]
2294 forall {}. C Int => D (Tree Int)
2296 This happens when you have something like
2298 T1 :: Eq a => a -> T a
2301 f x = ...(case x of { T1 v -> v==v })...
2304 -- ToDo: should we instantiate tvs? I think it's not necessary
2306 -- Note on coercion variables:
2308 -- The extra given coercion variables are bound at two different
2311 -- -) in the creation context of the implication constraint
2312 -- the solved equational constraints use these binders
2314 -- -) at the solving site of the implication constraint
2315 -- the solved dictionaries use these binders;
2316 -- these binders are generated by reduceImplication
2318 -- Note [Binders for equalities]
2319 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2320 -- To reuse the binders of local/given equalities in the binders of
2321 -- implication constraints, it is crucial that these given equalities
2322 -- always have the form
2324 -- where cotv is a simple coercion type variable (and not a more
2325 -- complex coercion term). We require that the extra_givens always
2326 -- have this form and exploit the special form when generating binders.
2327 reduceImplication env
2328 orig_implic@(ImplicInst { tci_name = name, tci_loc = inst_loc,
2330 tci_given = extra_givens, tci_wanted = wanteds
2332 = do { -- Solve the sub-problem
2333 ; let try_me _ = ReduceMe -- Note [Freeness and implications]
2334 env' = env { red_givens = extra_givens ++ red_givens env
2335 , red_doc = sep [ptext (sLit "reduceImplication for")
2337 nest 2 (parens $ ptext (sLit "within")
2339 , red_try_me = try_me }
2341 ; traceTc (text "reduceImplication" <+> vcat
2342 [ ppr (red_givens env), ppr extra_givens,
2344 ; (irreds, binds) <- checkLoop env' wanteds
2346 ; traceTc (text "reduceImplication result" <+> vcat
2347 [ppr irreds, ppr binds])
2349 ; -- extract superclass binds
2350 -- (sc_binds,_) <- extractResults avails []
2351 -- ; traceTc (text "reduceImplication sc_binds" <+> vcat
2352 -- [ppr sc_binds, ppr avails])
2355 -- SLPJ Sept 07: what if improvement happened inside the checkLoop?
2356 -- Then we must iterate the outer loop too!
2358 ; didntSolveWantedEqs <- allM wantedEqInstIsUnsolved wanteds
2359 -- we solve wanted eqs by side effect!
2361 -- Progress is no longer measered by the number of bindings
2362 -- If there are any irreds, but no bindings and no solved
2363 -- equalities, we back off and do nothing
2364 ; let backOff = isEmptyLHsBinds binds && -- no new bindings
2365 (not $ null irreds) && -- but still some irreds
2366 didntSolveWantedEqs -- no instantiated cotv
2368 ; if backOff then -- No progress
2369 return (emptyBag, [orig_implic])
2371 { (simpler_implic_insts, bind)
2372 <- makeImplicationBind inst_loc tvs extra_givens irreds
2373 -- This binding is useless if the recursive simplification
2374 -- made no progress; but currently we don't try to optimise that
2375 -- case. After all, we only try hard to reduce at top level, or
2376 -- when inferring types.
2378 ; let -- extract Id binders for dicts and CoTyVar binders for eqs;
2379 -- see Note [Binders for equalities]
2380 (extra_eq_givens, extra_dict_givens) = partition isEqInst
2382 eq_cotvs = map instToVar extra_eq_givens
2383 dict_ids = map instToId extra_dict_givens
2386 <.> mkWpTyLams eq_cotvs
2387 <.> mkWpLams dict_ids
2388 <.> WpLet (binds `unionBags` bind)
2389 rhs = mkLHsWrap co payload
2390 loc = instLocSpan inst_loc
2391 -- wanted equalities are solved by updating their
2392 -- cotv; we don't generate bindings for them
2393 dict_bndrs = map (L loc . HsVar . instToId)
2394 . filter (not . isEqInst)
2396 payload = mkBigLHsTup dict_bndrs
2398 ; traceTc (vcat [text "reduceImplication" <+> ppr name,
2399 ppr simpler_implic_insts,
2400 text "->" <+> ppr rhs])
2401 ; return (unitBag (L loc (VarBind { var_id= instToId orig_implic
2403 , var_inline = notNull dict_ids }
2404 -- See Note [Always inline implication constraints]
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)