2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
10 tcSimplifyInfer, tcSimplifyInferCheck,
11 tcSimplifyCheck, tcSimplifyRestricted,
12 tcSimplifyRuleLhs, tcSimplifyIPs,
13 tcSimplifySuperClasses,
14 tcSimplifyTop, tcSimplifyInteractive,
15 tcSimplifyBracket, tcSimplifyCheckPat,
17 tcSimplifyDeriv, tcSimplifyDefault,
18 bindInstsOfLocalFuns, bindIrreds,
21 #include "HsVersions.h"
23 import {-# SOURCE #-} TcUnify( unifyType )
59 %************************************************************************
63 %************************************************************************
65 --------------------------------------
66 Notes on functional dependencies (a bug)
67 --------------------------------------
74 instance D a b => C a b -- Undecidable
75 -- (Not sure if it's crucial to this eg)
76 f :: C a b => a -> Bool
79 g :: C a b => a -> Bool
82 Here f typechecks, but g does not!! Reason: before doing improvement,
83 we reduce the (C a b1) constraint from the call of f to (D a b1).
85 Here is a more complicated example:
87 | > class Foo a b | a->b
89 | > class Bar a b | a->b
93 | > instance Bar Obj Obj
95 | > instance (Bar a b) => Foo a b
97 | > foo:: (Foo a b) => a -> String
100 | > runFoo:: (forall a b. (Foo a b) => a -> w) -> w
106 | Could not deduce (Bar a b) from the context (Foo a b)
107 | arising from use of `foo' at <interactive>:1
109 | Add (Bar a b) to the expected type of an expression
110 | In the first argument of `runFoo', namely `foo'
111 | In the definition of `it': it = runFoo foo
113 | Why all of the sudden does GHC need the constraint Bar a b? The
114 | function foo didn't ask for that...
116 The trouble is that to type (runFoo foo), GHC has to solve the problem:
118 Given constraint Foo a b
119 Solve constraint Foo a b'
121 Notice that b and b' aren't the same. To solve this, just do
122 improvement and then they are the same. But GHC currently does
127 That is usually fine, but it isn't here, because it sees that Foo a b is
128 not the same as Foo a b', and so instead applies the instance decl for
129 instance Bar a b => Foo a b. And that's where the Bar constraint comes
132 The Right Thing is to improve whenever the constraint set changes at
133 all. Not hard in principle, but it'll take a bit of fiddling to do.
137 --------------------------------------
138 Notes on quantification
139 --------------------------------------
141 Suppose we are about to do a generalisation step.
145 T the type of the RHS
146 C the constraints from that RHS
148 The game is to figure out
150 Q the set of type variables over which to quantify
151 Ct the constraints we will *not* quantify over
152 Cq the constraints we will quantify over
154 So we're going to infer the type
158 and float the constraints Ct further outwards.
160 Here are the things that *must* be true:
162 (A) Q intersect fv(G) = EMPTY limits how big Q can be
163 (B) Q superset fv(Cq union T) \ oclose(fv(G),C) limits how small Q can be
165 (A) says we can't quantify over a variable that's free in the
166 environment. (B) says we must quantify over all the truly free
167 variables in T, else we won't get a sufficiently general type. We do
168 not *need* to quantify over any variable that is fixed by the free
169 vars of the environment G.
171 BETWEEN THESE TWO BOUNDS, ANY Q WILL DO!
173 Example: class H x y | x->y where ...
175 fv(G) = {a} C = {H a b, H c d}
178 (A) Q intersect {a} is empty
179 (B) Q superset {a,b,c,d} \ oclose({a}, C) = {a,b,c,d} \ {a,b} = {c,d}
181 So Q can be {c,d}, {b,c,d}
183 Other things being equal, however, we'd like to quantify over as few
184 variables as possible: smaller types, fewer type applications, more
185 constraints can get into Ct instead of Cq.
188 -----------------------------------------
191 fv(T) the free type vars of T
193 oclose(vs,C) The result of extending the set of tyvars vs
194 using the functional dependencies from C
196 grow(vs,C) The result of extend the set of tyvars vs
197 using all conceivable links from C.
199 E.g. vs = {a}, C = {H [a] b, K (b,Int) c, Eq e}
200 Then grow(vs,C) = {a,b,c}
202 Note that grow(vs,C) `superset` grow(vs,simplify(C))
203 That is, simplfication can only shrink the result of grow.
206 oclose is conservative one way: v `elem` oclose(vs,C) => v is definitely fixed by vs
207 grow is conservative the other way: if v might be fixed by vs => v `elem` grow(vs,C)
210 -----------------------------------------
212 Note [Choosing which variables to quantify]
213 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
214 Here's a good way to choose Q:
216 Q = grow( fv(T), C ) \ oclose( fv(G), C )
218 That is, quantify over all variable that that MIGHT be fixed by the
219 call site (which influences T), but which aren't DEFINITELY fixed by
220 G. This choice definitely quantifies over enough type variables,
221 albeit perhaps too many.
223 Why grow( fv(T), C ) rather than fv(T)? Consider
225 class H x y | x->y where ...
230 If we used fv(T) = {c} we'd get the type
232 forall c. H c d => c -> b
234 And then if the fn was called at several different c's, each of
235 which fixed d differently, we'd get a unification error, because
236 d isn't quantified. Solution: quantify d. So we must quantify
237 everything that might be influenced by c.
239 Why not oclose( fv(T), C )? Because we might not be able to see
240 all the functional dependencies yet:
242 class H x y | x->y where ...
243 instance H x y => Eq (T x y) where ...
248 Now oclose(fv(T),C) = {c}, because the functional dependency isn't
249 apparent yet, and that's wrong. We must really quantify over d too.
252 There really isn't any point in quantifying over any more than
253 grow( fv(T), C ), because the call sites can't possibly influence
254 any other type variables.
258 -------------------------------------
260 -------------------------------------
262 It's very hard to be certain when a type is ambiguous. Consider
266 instance H x y => K (x,y)
268 Is this type ambiguous?
269 forall a b. (K (a,b), Eq b) => a -> a
271 Looks like it! But if we simplify (K (a,b)) we get (H a b) and
272 now we see that a fixes b. So we can't tell about ambiguity for sure
273 without doing a full simplification. And even that isn't possible if
274 the context has some free vars that may get unified. Urgle!
276 Here's another example: is this ambiguous?
277 forall a b. Eq (T b) => a -> a
278 Not if there's an insance decl (with no context)
279 instance Eq (T b) where ...
281 You may say of this example that we should use the instance decl right
282 away, but you can't always do that:
284 class J a b where ...
285 instance J Int b where ...
287 f :: forall a b. J a b => a -> a
289 (Notice: no functional dependency in J's class decl.)
290 Here f's type is perfectly fine, provided f is only called at Int.
291 It's premature to complain when meeting f's signature, or even
292 when inferring a type for f.
296 However, we don't *need* to report ambiguity right away. It'll always
297 show up at the call site.... and eventually at main, which needs special
298 treatment. Nevertheless, reporting ambiguity promptly is an excellent thing.
300 So here's the plan. We WARN about probable ambiguity if
302 fv(Cq) is not a subset of oclose(fv(T) union fv(G), C)
304 (all tested before quantification).
305 That is, all the type variables in Cq must be fixed by the the variables
306 in the environment, or by the variables in the type.
308 Notice that we union before calling oclose. Here's an example:
310 class J a b c | a b -> c
314 forall b c. (J a b c) => b -> b
316 Only if we union {a} from G with {b} from T before using oclose,
317 do we see that c is fixed.
319 It's a bit vague exactly which C we should use for this oclose call. If we
320 don't fix enough variables we might complain when we shouldn't (see
321 the above nasty example). Nothing will be perfect. That's why we can
322 only issue a warning.
325 Can we ever be *certain* about ambiguity? Yes: if there's a constraint
327 c in C such that fv(c) intersect (fv(G) union fv(T)) = EMPTY
329 then c is a "bubble"; there's no way it can ever improve, and it's
330 certainly ambiguous. UNLESS it is a constant (sigh). And what about
335 instance H x y => K (x,y)
337 Is this type ambiguous?
338 forall a b. (K (a,b), Eq b) => a -> a
340 Urk. The (Eq b) looks "definitely ambiguous" but it isn't. What we are after
341 is a "bubble" that's a set of constraints
343 Cq = Ca union Cq' st fv(Ca) intersect (fv(Cq') union fv(T) union fv(G)) = EMPTY
345 Hence another idea. To decide Q start with fv(T) and grow it
346 by transitive closure in Cq (no functional dependencies involved).
347 Now partition Cq using Q, leaving the definitely-ambiguous and probably-ok.
348 The definitely-ambiguous can then float out, and get smashed at top level
349 (which squashes out the constants, like Eq (T a) above)
352 --------------------------------------
353 Notes on principal types
354 --------------------------------------
359 f x = let g y = op (y::Int) in True
361 Here the principal type of f is (forall a. a->a)
362 but we'll produce the non-principal type
363 f :: forall a. C Int => a -> a
366 --------------------------------------
367 The need for forall's in constraints
368 --------------------------------------
370 [Exchange on Haskell Cafe 5/6 Dec 2000]
372 class C t where op :: t -> Bool
373 instance C [t] where op x = True
375 p y = (let f :: c -> Bool; f x = op (y >> return x) in f, y ++ [])
376 q y = (y ++ [], let f :: c -> Bool; f x = op (y >> return x) in f)
378 The definitions of p and q differ only in the order of the components in
379 the pair on their right-hand sides. And yet:
381 ghc and "Typing Haskell in Haskell" reject p, but accept q;
382 Hugs rejects q, but accepts p;
383 hbc rejects both p and q;
384 nhc98 ... (Malcolm, can you fill in the blank for us!).
386 The type signature for f forces context reduction to take place, and
387 the results of this depend on whether or not the type of y is known,
388 which in turn depends on which component of the pair the type checker
391 Solution: if y::m a, float out the constraints
392 Monad m, forall c. C (m c)
393 When m is later unified with [], we can solve both constraints.
396 --------------------------------------
397 Notes on implicit parameters
398 --------------------------------------
400 Note [Inheriting implicit parameters]
401 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
406 where f is *not* a top-level binding.
407 From the RHS of f we'll get the constraint (?y::Int).
408 There are two types we might infer for f:
412 (so we get ?y from the context of f's definition), or
414 f :: (?y::Int) => Int -> Int
416 At first you might think the first was better, becuase then
417 ?y behaves like a free variable of the definition, rather than
418 having to be passed at each call site. But of course, the WHOLE
419 IDEA is that ?y should be passed at each call site (that's what
420 dynamic binding means) so we'd better infer the second.
422 BOTTOM LINE: when *inferring types* you *must* quantify
423 over implicit parameters. See the predicate isFreeWhenInferring.
426 Note [Implicit parameters and ambiguity]
427 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
428 What type should we infer for this?
429 f x = (show ?y, x::Int)
430 Since we must quantify over the ?y, the most plausible type is
431 f :: (Show a, ?y::a) => Int -> (String, Int)
432 But notice that the type of the RHS is (String,Int), with no type
433 varibables mentioned at all! The type of f looks ambiguous. But
434 it isn't, because at a call site we might have
435 let ?y = 5::Int in f 7
436 and all is well. In effect, implicit parameters are, well, parameters,
437 so we can take their type variables into account as part of the
438 "tau-tvs" stuff. This is done in the function 'FunDeps.grow'.
441 Question 2: type signatures
442 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
443 BUT WATCH OUT: When you supply a type signature, we can't force you
444 to quantify over implicit parameters. For example:
448 This is perfectly reasonable. We do not want to insist on
450 (?x + 1) :: (?x::Int => Int)
452 That would be silly. Here, the definition site *is* the occurrence site,
453 so the above strictures don't apply. Hence the difference between
454 tcSimplifyCheck (which *does* allow implicit paramters to be inherited)
455 and tcSimplifyCheckBind (which does not).
457 What about when you supply a type signature for a binding?
458 Is it legal to give the following explicit, user type
459 signature to f, thus:
464 At first sight this seems reasonable, but it has the nasty property
465 that adding a type signature changes the dynamic semantics.
468 (let f x = (x::Int) + ?y
469 in (f 3, f 3 with ?y=5)) with ?y = 6
475 in (f 3, f 3 with ?y=5)) with ?y = 6
479 Indeed, simply inlining f (at the Haskell source level) would change the
482 Nevertheless, as Launchbury says (email Oct 01) we can't really give the
483 semantics for a Haskell program without knowing its typing, so if you
484 change the typing you may change the semantics.
486 To make things consistent in all cases where we are *checking* against
487 a supplied signature (as opposed to inferring a type), we adopt the
490 a signature does not need to quantify over implicit params.
492 [This represents a (rather marginal) change of policy since GHC 5.02,
493 which *required* an explicit signature to quantify over all implicit
494 params for the reasons mentioned above.]
496 But that raises a new question. Consider
498 Given (signature) ?x::Int
499 Wanted (inferred) ?x::Int, ?y::Bool
501 Clearly we want to discharge the ?x and float the ?y out. But
502 what is the criterion that distinguishes them? Clearly it isn't
503 what free type variables they have. The Right Thing seems to be
504 to float a constraint that
505 neither mentions any of the quantified type variables
506 nor any of the quantified implicit parameters
508 See the predicate isFreeWhenChecking.
511 Question 3: monomorphism
512 ~~~~~~~~~~~~~~~~~~~~~~~~
513 There's a nasty corner case when the monomorphism restriction bites:
517 The argument above suggests that we *must* generalise
518 over the ?y parameter, to get
519 z :: (?y::Int) => Int,
520 but the monomorphism restriction says that we *must not*, giving
522 Why does the momomorphism restriction say this? Because if you have
524 let z = x + ?y in z+z
526 you might not expect the addition to be done twice --- but it will if
527 we follow the argument of Question 2 and generalise over ?y.
530 Question 4: top level
531 ~~~~~~~~~~~~~~~~~~~~~
532 At the top level, monomorhism makes no sense at all.
535 main = let ?x = 5 in print foo
539 woggle :: (?x :: Int) => Int -> Int
542 We definitely don't want (foo :: Int) with a top-level implicit parameter
543 (?x::Int) becuase there is no way to bind it.
548 (A) Always generalise over implicit parameters
549 Bindings that fall under the monomorphism restriction can't
553 * Inlining remains valid
554 * No unexpected loss of sharing
555 * But simple bindings like
557 will be rejected, unless you add an explicit type signature
558 (to avoid the monomorphism restriction)
559 z :: (?y::Int) => Int
561 This seems unacceptable
563 (B) Monomorphism restriction "wins"
564 Bindings that fall under the monomorphism restriction can't
566 Always generalise over implicit parameters *except* for bindings
567 that fall under the monomorphism restriction
570 * Inlining isn't valid in general
571 * No unexpected loss of sharing
572 * Simple bindings like
574 accepted (get value of ?y from binding site)
576 (C) Always generalise over implicit parameters
577 Bindings that fall under the monomorphism restriction can't
578 be generalised, EXCEPT for implicit parameters
580 * Inlining remains valid
581 * Unexpected loss of sharing (from the extra generalisation)
582 * Simple bindings like
584 accepted (get value of ?y from occurrence sites)
589 None of these choices seems very satisfactory. But at least we should
590 decide which we want to do.
592 It's really not clear what is the Right Thing To Do. If you see
596 would you expect the value of ?y to be got from the *occurrence sites*
597 of 'z', or from the valuue of ?y at the *definition* of 'z'? In the
598 case of function definitions, the answer is clearly the former, but
599 less so in the case of non-fucntion definitions. On the other hand,
600 if we say that we get the value of ?y from the definition site of 'z',
601 then inlining 'z' might change the semantics of the program.
603 Choice (C) really says "the monomorphism restriction doesn't apply
604 to implicit parameters". Which is fine, but remember that every
605 innocent binding 'x = ...' that mentions an implicit parameter in
606 the RHS becomes a *function* of that parameter, called at each
607 use of 'x'. Now, the chances are that there are no intervening 'with'
608 clauses that bind ?y, so a decent compiler should common up all
609 those function calls. So I think I strongly favour (C). Indeed,
610 one could make a similar argument for abolishing the monomorphism
611 restriction altogether.
613 BOTTOM LINE: we choose (B) at present. See tcSimplifyRestricted
617 %************************************************************************
619 \subsection{tcSimplifyInfer}
621 %************************************************************************
623 tcSimplify is called when we *inferring* a type. Here's the overall game plan:
625 1. Compute Q = grow( fvs(T), C )
627 2. Partition C based on Q into Ct and Cq. Notice that ambiguous
628 predicates will end up in Ct; we deal with them at the top level
630 3. Try improvement, using functional dependencies
632 4. If Step 3 did any unification, repeat from step 1
633 (Unification can change the result of 'grow'.)
635 Note: we don't reduce dictionaries in step 2. For example, if we have
636 Eq (a,b), we don't simplify to (Eq a, Eq b). So Q won't be different
637 after step 2. However note that we may therefore quantify over more
638 type variables than we absolutely have to.
640 For the guts, we need a loop, that alternates context reduction and
641 improvement with unification. E.g. Suppose we have
643 class C x y | x->y where ...
645 and tcSimplify is called with:
647 Then improvement unifies a with b, giving
650 If we need to unify anything, we rattle round the whole thing all over
657 -> TcTyVarSet -- fv(T); type vars
659 -> TcM ([TcTyVar], -- Tyvars to quantify (zonked and quantified)
660 [Inst], -- Dict Ids that must be bound here (zonked)
661 TcDictBinds) -- Bindings
662 -- Any free (escaping) Insts are tossed into the environment
667 tcSimplifyInfer doc tau_tvs wanted
668 = do { tau_tvs' <- zonkTcTyVarsAndFV (varSetElems tau_tvs)
669 ; wanted' <- mappM zonkInst wanted -- Zonk before deciding quantified tyvars
670 ; gbl_tvs <- tcGetGlobalTyVars
671 ; let preds = fdPredsOfInsts wanted'
672 qtvs = grow preds tau_tvs' `minusVarSet` oclose preds gbl_tvs
673 -- See Note [Choosing which variables to quantify]
675 -- To maximise sharing, remove from consideration any
676 -- constraints that don't mention qtvs at all
677 ; let (free1, bound) = partition (isFreeWhenInferring qtvs) wanted'
680 -- To make types simple, reduce as much as possible
681 ; traceTc (text "infer" <+> (ppr preds $$ ppr (grow preds tau_tvs') $$ ppr gbl_tvs $$
682 ppr (oclose preds gbl_tvs) $$ ppr free1 $$ ppr bound))
683 ; let try_me inst = ReduceMe AddSCs
684 ; (irreds, binds) <- checkLoop (mkRedEnv doc try_me []) bound
685 ; qtvs' <- zonkQuantifiedTyVars (varSetElems qtvs)
687 -- Do not quantify over constraints that *now* do not
688 -- mention quantified type variables, because they are
689 -- simply ambiguous. Example:
690 -- f :: Eq b => a -> (a, b)
692 -- From the RHS of g we get the MethodInst f77 :: alpha -> (alpha, beta)
693 -- We decide to quantify over 'alpha' alone, bur free1 does not include f77
694 -- because f77 mentions 'alpha'. Then reducing leaves only the (ambiguous)
695 -- constraint (Eq beta), which we dump back into the free set
696 -- See test tcfail181
697 ; let (free2, irreds2) = partition (isFreeWhenInferring (mkVarSet qtvs')) irreds
700 -- We can't abstract over implications
701 ; let (dicts, implics) = partition isDict irreds2
702 ; loc <- getInstLoc (ImplicOrigin doc)
703 ; implic_bind <- bindIrreds loc qtvs' dicts implics
705 ; return (qtvs', dicts, binds `unionBags` implic_bind) }
706 -- NB: when we are done, we might have some bindings, but
707 -- the final qtvs might be empty. See Note [NO TYVARS] below.
711 -----------------------------------------------------------
712 -- tcSimplifyInferCheck is used when we know the constraints we are to simplify
713 -- against, but we don't know the type variables over which we are going to quantify.
714 -- This happens when we have a type signature for a mutually recursive group
717 -> TcTyVarSet -- fv(T)
720 -> TcM ([TyVar], -- Fully zonked, and quantified
721 TcDictBinds) -- Bindings
723 tcSimplifyInferCheck loc tau_tvs givens wanteds
724 = do { (irreds, binds) <- innerCheckLoop loc givens wanteds
726 -- Figure out which type variables to quantify over
727 -- You might think it should just be the signature tyvars,
728 -- but in bizarre cases you can get extra ones
729 -- f :: forall a. Num a => a -> a
730 -- f x = fst (g (x, head [])) + 1
732 -- Here we infer g :: forall a b. a -> b -> (b,a)
733 -- We don't want g to be monomorphic in b just because
734 -- f isn't quantified over b.
735 ; let all_tvs = varSetElems (tau_tvs `unionVarSet` tyVarsOfInsts givens)
736 ; all_tvs <- zonkTcTyVarsAndFV all_tvs
737 ; gbl_tvs <- tcGetGlobalTyVars
738 ; let qtvs = varSetElems (all_tvs `minusVarSet` gbl_tvs)
739 -- We could close gbl_tvs, but its not necessary for
740 -- soundness, and it'll only affect which tyvars, not which
741 -- dictionaries, we quantify over
743 ; qtvs' <- zonkQuantifiedTyVars qtvs
745 -- Now we are back to normal (c.f. tcSimplCheck)
746 ; implic_bind <- bindIrreds loc qtvs' givens irreds
748 ; return (qtvs', binds `unionBags` implic_bind) }
751 Note [Squashing methods]
752 ~~~~~~~~~~~~~~~~~~~~~~~~~
753 Be careful if you want to float methods more:
754 truncate :: forall a. RealFrac a => forall b. Integral b => a -> b
755 From an application (truncate f i) we get
758 If we have also have a second occurrence of truncate, we get
761 When simplifying with i,f free, we might still notice that
762 t1=t3; but alas, the binding for t2 (which mentions t1)
763 may continue to float out!
768 class Y a b | a -> b where
771 instance Y [[a]] a where
774 k :: X a -> X a -> X a
776 g :: Num a => [X a] -> [X a]
779 h ys = ys ++ map (k (y [[0]])) xs
781 The excitement comes when simplifying the bindings for h. Initially
782 try to simplify {y @ [[t1]] t2, 0 @ t1}, with initial qtvs = {t2}.
783 From this we get t1:=:t2, but also various bindings. We can't forget
784 the bindings (because of [LOOP]), but in fact t1 is what g is
787 The net effect of [NO TYVARS]
790 isFreeWhenInferring :: TyVarSet -> Inst -> Bool
791 isFreeWhenInferring qtvs inst
792 = isFreeWrtTyVars qtvs inst -- Constrains no quantified vars
793 && isInheritableInst inst -- and no implicit parameter involved
794 -- see Note [Inheriting implicit parameters]
796 {- No longer used (with implication constraints)
797 isFreeWhenChecking :: TyVarSet -- Quantified tyvars
798 -> NameSet -- Quantified implicit parameters
800 isFreeWhenChecking qtvs ips inst
801 = isFreeWrtTyVars qtvs inst
802 && isFreeWrtIPs ips inst
805 isFreeWrtTyVars qtvs inst = tyVarsOfInst inst `disjointVarSet` qtvs
806 isFreeWrtIPs ips inst = not (any (`elemNameSet` ips) (ipNamesOfInst inst))
810 %************************************************************************
812 \subsection{tcSimplifyCheck}
814 %************************************************************************
816 @tcSimplifyCheck@ is used when we know exactly the set of variables
817 we are going to quantify over. For example, a class or instance declaration.
820 -----------------------------------------------------------
821 -- tcSimplifyCheck is used when checking expression type signatures,
822 -- class decls, instance decls etc.
823 tcSimplifyCheck :: InstLoc
824 -> [TcTyVar] -- Quantify over these
827 -> TcM TcDictBinds -- Bindings
828 tcSimplifyCheck loc qtvs givens wanteds
829 = ASSERT( all isTcTyVar qtvs && all isSkolemTyVar qtvs )
830 do { (irreds, binds) <- innerCheckLoop loc givens wanteds
831 ; implic_bind <- bindIrreds loc qtvs givens irreds
832 ; return (binds `unionBags` implic_bind) }
834 -----------------------------------------------------------
835 -- tcSimplifyCheckPat is used for existential pattern match
836 tcSimplifyCheckPat :: InstLoc
837 -> [CoVar] -> Refinement
838 -> [TcTyVar] -- Quantify over these
841 -> TcM TcDictBinds -- Bindings
842 tcSimplifyCheckPat loc co_vars reft qtvs givens wanteds
843 = ASSERT( all isTcTyVar qtvs && all isSkolemTyVar qtvs )
844 do { (irreds, binds) <- innerCheckLoop loc givens wanteds
845 ; implic_bind <- bindIrredsR loc qtvs co_vars reft
847 ; return (binds `unionBags` implic_bind) }
849 -----------------------------------------------------------
850 bindIrreds :: InstLoc -> [TcTyVar]
853 bindIrreds loc qtvs givens irreds
854 = bindIrredsR loc qtvs [] emptyRefinement givens irreds
856 bindIrredsR :: InstLoc -> [TcTyVar] -> [CoVar]
857 -> Refinement -> [Inst] -> [Inst]
859 -- Make a binding that binds 'irreds', by generating an implication
860 -- constraint for them, *and* throwing the constraint into the LIE
861 bindIrredsR loc qtvs co_vars reft givens irreds
865 = do { let givens' = filter isDict givens
866 -- The givens can include methods
867 -- See Note [Pruning the givens in an implication constraint]
869 -- If there are no 'givens' *and* the refinement is empty
870 -- (the refinement is like more givens), then it's safe to
871 -- partition the 'wanteds' by their qtvs, thereby trimming irreds
872 -- See Note [Freeness and implications]
873 ; irreds' <- if null givens' && isEmptyRefinement reft
875 { let qtv_set = mkVarSet qtvs
876 (frees, real_irreds) = partition (isFreeWrtTyVars qtv_set) irreds
878 ; return real_irreds }
881 ; let all_tvs = qtvs ++ co_vars -- Abstract over all these
882 ; (implics, bind) <- makeImplicationBind loc all_tvs reft givens' irreds'
883 -- This call does the real work
884 -- If irreds' is empty, it does something sensible
889 makeImplicationBind :: InstLoc -> [TcTyVar] -> Refinement
891 -> TcM ([Inst], TcDictBinds)
892 -- Make a binding that binds 'irreds', by generating an implication
893 -- constraint for them, *and* throwing the constraint into the LIE
894 -- The binding looks like
895 -- (ir1, .., irn) = f qtvs givens
896 -- where f is (evidence for) the new implication constraint
897 -- f :: forall qtvs. {reft} givens => (ir1, .., irn)
898 -- qtvs includes coercion variables
900 -- This binding must line up the 'rhs' in reduceImplication
901 makeImplicationBind loc all_tvs reft
902 givens -- Guaranteed all Dicts
904 | null irreds -- If there are no irreds, we are done
905 = return ([], emptyBag)
906 | otherwise -- Otherwise we must generate a binding
907 = do { uniq <- newUnique
908 ; span <- getSrcSpanM
909 ; let name = mkInternalName uniq (mkVarOcc "ic") span
910 implic_inst = ImplicInst { tci_name = name, tci_reft = reft,
911 tci_tyvars = all_tvs,
913 tci_wanted = irreds, tci_loc = loc }
915 ; let n_irreds = length irreds
916 irred_ids = map instToId irreds
917 tup_ty = mkTupleTy Boxed n_irreds (map idType irred_ids)
918 pat = TuplePat (map nlVarPat irred_ids) Boxed tup_ty
919 rhs = L span (mkHsWrap co (HsVar (instToId implic_inst)))
920 co = mkWpApps (map instToId givens) <.> mkWpTyApps (mkTyVarTys all_tvs)
921 bind | n_irreds==1 = VarBind (head irred_ids) rhs
922 | otherwise = PatBind { pat_lhs = L span pat,
923 pat_rhs = unguardedGRHSs rhs,
925 bind_fvs = placeHolderNames }
926 ; -- pprTrace "Make implic inst" (ppr implic_inst) $
927 return ([implic_inst], unitBag (L span bind)) }
929 -----------------------------------------------------------
932 -> TcM ([Inst], TcDictBinds)
934 topCheckLoop doc wanteds
935 = checkLoop (mkRedEnv doc try_me []) wanteds
937 try_me inst = ReduceMe AddSCs
939 -----------------------------------------------------------
940 innerCheckLoop :: InstLoc
943 -> TcM ([Inst], TcDictBinds)
945 innerCheckLoop inst_loc givens wanteds
946 = checkLoop env wanteds
948 env = mkRedEnv (pprInstLoc inst_loc) try_me givens
950 try_me inst | isMethodOrLit inst = ReduceMe AddSCs
952 -- When checking against a given signature
953 -- we MUST be very gentle: Note [Check gently]
958 We have to very careful about not simplifying too vigorously
963 f :: Show b => T b -> b
966 Inside the pattern match, which binds (a:*, x:a), we know that
968 Hence we have a dictionary for Show [a] available; and indeed we
969 need it. We are going to build an implication contraint
970 forall a. (b~[a]) => Show [a]
971 Later, we will solve this constraint using the knowledge (Show b)
973 But we MUST NOT reduce (Show [a]) to (Show a), else the whole
974 thing becomes insoluble. So we simplify gently (get rid of literals
975 and methods only, plus common up equal things), deferring the real
976 work until top level, when we solve the implication constraint
981 -----------------------------------------------------------
984 -> TcM ([Inst], TcDictBinds)
985 -- Precondition: givens are completely rigid
987 checkLoop env wanteds
988 = do { -- Givens are skolems, so no need to zonk them
989 wanteds' <- mappM zonkInst wanteds
991 ; (improved, binds, irreds) <- reduceContext env wanteds'
993 ; if not improved then
994 return (irreds, binds)
997 -- If improvement did some unification, we go round again.
998 -- We start again with irreds, not wanteds
999 -- Using an instance decl might have introduced a fresh type variable
1000 -- which might have been unified, so we'd get an infinite loop
1001 -- if we started again with wanteds! See Note [LOOP]
1002 { (irreds1, binds1) <- checkLoop env irreds
1003 ; return (irreds1, binds `unionBags` binds1) } }
1008 class If b t e r | b t e -> r
1011 class Lte a b c | a b -> c where lte :: a -> b -> c
1013 instance (Lte a b l,If l b a c) => Max a b c
1015 Wanted: Max Z (S x) y
1017 Then we'll reduce using the Max instance to:
1018 (Lte Z (S x) l, If l (S x) Z y)
1019 and improve by binding l->T, after which we can do some reduction
1020 on both the Lte and If constraints. What we *can't* do is start again
1021 with (Max Z (S x) y)!
1025 %************************************************************************
1027 tcSimplifySuperClasses
1029 %************************************************************************
1031 Note [SUPERCLASS-LOOP 1]
1032 ~~~~~~~~~~~~~~~~~~~~~~~~
1033 We have to be very, very careful when generating superclasses, lest we
1034 accidentally build a loop. Here's an example:
1038 class S a => C a where { opc :: a -> a }
1039 class S b => D b where { opd :: b -> b }
1041 instance C Int where
1044 instance D Int where
1047 From (instance C Int) we get the constraint set {ds1:S Int, dd:D Int}
1048 Simplifying, we may well get:
1049 $dfCInt = :C ds1 (opd dd)
1052 Notice that we spot that we can extract ds1 from dd.
1054 Alas! Alack! We can do the same for (instance D Int):
1056 $dfDInt = :D ds2 (opc dc)
1060 And now we've defined the superclass in terms of itself.
1062 Solution: never generate a superclass selectors at all when
1063 satisfying the superclass context of an instance declaration.
1065 Two more nasty cases are in
1070 tcSimplifySuperClasses
1075 tcSimplifySuperClasses loc givens sc_wanteds
1076 = do { (irreds, binds1) <- checkLoop env sc_wanteds
1077 ; let (tidy_env, tidy_irreds) = tidyInsts irreds
1078 ; reportNoInstances tidy_env (Just (loc, givens)) tidy_irreds
1081 env = mkRedEnv (pprInstLoc loc) try_me givens
1082 try_me inst = ReduceMe NoSCs
1083 -- Like topCheckLoop, but with NoSCs
1087 %************************************************************************
1089 \subsection{tcSimplifyRestricted}
1091 %************************************************************************
1093 tcSimplifyRestricted infers which type variables to quantify for a
1094 group of restricted bindings. This isn't trivial.
1097 We want to quantify over a to get id :: forall a. a->a
1100 We do not want to quantify over a, because there's an Eq a
1101 constraint, so we get eq :: a->a->Bool (notice no forall)
1104 RHS has type 'tau', whose free tyvars are tau_tvs
1105 RHS has constraints 'wanteds'
1108 Quantify over (tau_tvs \ ftvs(wanteds))
1109 This is bad. The constraints may contain (Monad (ST s))
1110 where we have instance Monad (ST s) where...
1111 so there's no need to be monomorphic in s!
1113 Also the constraint might be a method constraint,
1114 whose type mentions a perfectly innocent tyvar:
1115 op :: Num a => a -> b -> a
1116 Here, b is unconstrained. A good example would be
1118 We want to infer the polymorphic type
1119 foo :: forall b. b -> b
1122 Plan B (cunning, used for a long time up to and including GHC 6.2)
1123 Step 1: Simplify the constraints as much as possible (to deal
1124 with Plan A's problem). Then set
1125 qtvs = tau_tvs \ ftvs( simplify( wanteds ) )
1127 Step 2: Now simplify again, treating the constraint as 'free' if
1128 it does not mention qtvs, and trying to reduce it otherwise.
1129 The reasons for this is to maximise sharing.
1131 This fails for a very subtle reason. Suppose that in the Step 2
1132 a constraint (Foo (Succ Zero) (Succ Zero) b) gets thrown upstairs as 'free'.
1133 In the Step 1 this constraint might have been simplified, perhaps to
1134 (Foo Zero Zero b), AND THEN THAT MIGHT BE IMPROVED, to bind 'b' to 'T'.
1135 This won't happen in Step 2... but that in turn might prevent some other
1136 constraint (Baz [a] b) being simplified (e.g. via instance Baz [a] T where {..})
1137 and that in turn breaks the invariant that no constraints are quantified over.
1139 Test typecheck/should_compile/tc177 (which failed in GHC 6.2) demonstrates
1144 Step 1: Simplify the constraints as much as possible (to deal
1145 with Plan A's problem). Then set
1146 qtvs = tau_tvs \ ftvs( simplify( wanteds ) )
1147 Return the bindings from Step 1.
1150 A note about Plan C (arising from "bug" reported by George Russel March 2004)
1153 instance (HasBinary ty IO) => HasCodedValue ty
1155 foo :: HasCodedValue a => String -> IO a
1157 doDecodeIO :: HasCodedValue a => () -> () -> IO a
1158 doDecodeIO codedValue view
1159 = let { act = foo "foo" } in act
1161 You might think this should work becuase the call to foo gives rise to a constraint
1162 (HasCodedValue t), which can be satisfied by the type sig for doDecodeIO. But the
1163 restricted binding act = ... calls tcSimplifyRestricted, and PlanC simplifies the
1164 constraint using the (rather bogus) instance declaration, and now we are stuffed.
1166 I claim this is not really a bug -- but it bit Sergey as well as George. So here's
1170 Plan D (a variant of plan B)
1171 Step 1: Simplify the constraints as much as possible (to deal
1172 with Plan A's problem), BUT DO NO IMPROVEMENT. Then set
1173 qtvs = tau_tvs \ ftvs( simplify( wanteds ) )
1175 Step 2: Now simplify again, treating the constraint as 'free' if
1176 it does not mention qtvs, and trying to reduce it otherwise.
1178 The point here is that it's generally OK to have too few qtvs; that is,
1179 to make the thing more monomorphic than it could be. We don't want to
1180 do that in the common cases, but in wierd cases it's ok: the programmer
1181 can always add a signature.
1183 Too few qtvs => too many wanteds, which is what happens if you do less
1188 tcSimplifyRestricted -- Used for restricted binding groups
1189 -- i.e. ones subject to the monomorphism restriction
1192 -> [Name] -- Things bound in this group
1193 -> TcTyVarSet -- Free in the type of the RHSs
1194 -> [Inst] -- Free in the RHSs
1195 -> TcM ([TyVar], -- Tyvars to quantify (zonked and quantified)
1196 TcDictBinds) -- Bindings
1197 -- tcSimpifyRestricted returns no constraints to
1198 -- quantify over; by definition there are none.
1199 -- They are all thrown back in the LIE
1201 tcSimplifyRestricted doc top_lvl bndrs tau_tvs wanteds
1202 -- Zonk everything in sight
1203 = do { wanteds' <- mappM zonkInst wanteds
1205 -- 'ReduceMe': Reduce as far as we can. Don't stop at
1206 -- dicts; the idea is to get rid of as many type
1207 -- variables as possible, and we don't want to stop
1208 -- at (say) Monad (ST s), because that reduces
1209 -- immediately, with no constraint on s.
1211 -- BUT do no improvement! See Plan D above
1212 -- HOWEVER, some unification may take place, if we instantiate
1213 -- a method Inst with an equality constraint
1214 ; let env = mkNoImproveRedEnv doc (\i -> ReduceMe AddSCs)
1215 ; (_imp, _binds, constrained_dicts) <- reduceContext env wanteds'
1217 -- Next, figure out the tyvars we will quantify over
1218 ; tau_tvs' <- zonkTcTyVarsAndFV (varSetElems tau_tvs)
1219 ; gbl_tvs' <- tcGetGlobalTyVars
1220 ; constrained_dicts' <- mappM zonkInst constrained_dicts
1222 ; let qtvs1 = tau_tvs' `minusVarSet` oclose (fdPredsOfInsts constrained_dicts) gbl_tvs'
1223 -- As in tcSimplifyInfer
1225 -- Do not quantify over constrained type variables:
1226 -- this is the monomorphism restriction
1227 constrained_tvs' = tyVarsOfInsts constrained_dicts'
1228 qtvs = qtvs1 `minusVarSet` constrained_tvs'
1229 pp_bndrs = pprWithCommas (quotes . ppr) bndrs
1232 ; warn_mono <- doptM Opt_WarnMonomorphism
1233 ; warnTc (warn_mono && (constrained_tvs' `intersectsVarSet` qtvs1))
1234 (vcat[ ptext SLIT("the Monomorphism Restriction applies to the binding")
1235 <> plural bndrs <+> ptext SLIT("for") <+> pp_bndrs,
1236 ptext SLIT("Consider giving a type signature for") <+> pp_bndrs])
1238 ; traceTc (text "tcSimplifyRestricted" <+> vcat [
1239 pprInsts wanteds, pprInsts constrained_dicts',
1241 ppr constrained_tvs', ppr tau_tvs', ppr qtvs ])
1243 -- The first step may have squashed more methods than
1244 -- necessary, so try again, this time more gently, knowing the exact
1245 -- set of type variables to quantify over.
1247 -- We quantify only over constraints that are captured by qtvs;
1248 -- these will just be a subset of non-dicts. This in contrast
1249 -- to normal inference (using isFreeWhenInferring) in which we quantify over
1250 -- all *non-inheritable* constraints too. This implements choice
1251 -- (B) under "implicit parameter and monomorphism" above.
1253 -- Remember that we may need to do *some* simplification, to
1254 -- (for example) squash {Monad (ST s)} into {}. It's not enough
1255 -- just to float all constraints
1257 -- At top level, we *do* squash methods becuase we want to
1258 -- expose implicit parameters to the test that follows
1259 ; let is_nested_group = isNotTopLevel top_lvl
1260 try_me inst | isFreeWrtTyVars qtvs inst,
1261 (is_nested_group || isDict inst) = Stop
1262 | otherwise = ReduceMe AddSCs
1263 env = mkNoImproveRedEnv doc try_me
1264 ; (_imp, binds, irreds) <- reduceContext env wanteds'
1266 -- See "Notes on implicit parameters, Question 4: top level"
1267 ; ASSERT( all (isFreeWrtTyVars qtvs) irreds ) -- None should be captured
1268 if is_nested_group then
1270 else do { let (bad_ips, non_ips) = partition isIPDict irreds
1271 ; addTopIPErrs bndrs bad_ips
1272 ; extendLIEs non_ips }
1274 ; qtvs' <- zonkQuantifiedTyVars (varSetElems qtvs)
1275 ; return (qtvs', binds) }
1279 %************************************************************************
1283 %************************************************************************
1285 On the LHS of transformation rules we only simplify methods and constants,
1286 getting dictionaries. We want to keep all of them unsimplified, to serve
1287 as the available stuff for the RHS of the rule.
1289 Example. Consider the following left-hand side of a rule
1291 f (x == y) (y > z) = ...
1293 If we typecheck this expression we get constraints
1295 d1 :: Ord a, d2 :: Eq a
1297 We do NOT want to "simplify" to the LHS
1299 forall x::a, y::a, z::a, d1::Ord a.
1300 f ((==) (eqFromOrd d1) x y) ((>) d1 y z) = ...
1304 forall x::a, y::a, z::a, d1::Ord a, d2::Eq a.
1305 f ((==) d2 x y) ((>) d1 y z) = ...
1307 Here is another example:
1309 fromIntegral :: (Integral a, Num b) => a -> b
1310 {-# RULES "foo" fromIntegral = id :: Int -> Int #-}
1312 In the rule, a=b=Int, and Num Int is a superclass of Integral Int. But
1313 we *dont* want to get
1315 forall dIntegralInt.
1316 fromIntegral Int Int dIntegralInt (scsel dIntegralInt) = id Int
1318 because the scsel will mess up RULE matching. Instead we want
1320 forall dIntegralInt, dNumInt.
1321 fromIntegral Int Int dIntegralInt dNumInt = id Int
1325 g (x == y) (y == z) = ..
1327 where the two dictionaries are *identical*, we do NOT WANT
1329 forall x::a, y::a, z::a, d1::Eq a
1330 f ((==) d1 x y) ((>) d1 y z) = ...
1332 because that will only match if the dict args are (visibly) equal.
1333 Instead we want to quantify over the dictionaries separately.
1335 In short, tcSimplifyRuleLhs must *only* squash LitInst and MethInts, leaving
1336 all dicts unchanged, with absolutely no sharing. It's simpler to do this
1337 from scratch, rather than further parameterise simpleReduceLoop etc
1340 tcSimplifyRuleLhs :: [Inst] -> TcM ([Inst], TcDictBinds)
1341 tcSimplifyRuleLhs wanteds
1342 = go [] emptyBag wanteds
1345 = return (dicts, binds)
1346 go dicts binds (w:ws)
1348 = go (w:dicts) binds ws
1350 = do { w' <- zonkInst w -- So that (3::Int) does not generate a call
1351 -- to fromInteger; this looks fragile to me
1352 ; lookup_result <- lookupSimpleInst w'
1353 ; case lookup_result of
1354 GenInst ws' rhs -> go dicts (addBind binds w rhs) (ws' ++ ws)
1355 NoInstance -> pprPanic "tcSimplifyRuleLhs" (ppr w)
1359 tcSimplifyBracket is used when simplifying the constraints arising from
1360 a Template Haskell bracket [| ... |]. We want to check that there aren't
1361 any constraints that can't be satisfied (e.g. Show Foo, where Foo has no
1362 Show instance), but we aren't otherwise interested in the results.
1363 Nor do we care about ambiguous dictionaries etc. We will type check
1364 this bracket again at its usage site.
1367 tcSimplifyBracket :: [Inst] -> TcM ()
1368 tcSimplifyBracket wanteds
1369 = do { topCheckLoop doc wanteds
1372 doc = text "tcSimplifyBracket"
1376 %************************************************************************
1378 \subsection{Filtering at a dynamic binding}
1380 %************************************************************************
1385 we must discharge all the ?x constraints from B. We also do an improvement
1386 step; if we have ?x::t1 and ?x::t2 we must unify t1, t2.
1388 Actually, the constraints from B might improve the types in ?x. For example
1390 f :: (?x::Int) => Char -> Char
1393 then the constraint (?x::Int) arising from the call to f will
1394 force the binding for ?x to be of type Int.
1397 tcSimplifyIPs :: [Inst] -- The implicit parameters bound here
1400 -- We need a loop so that we do improvement, and then
1401 -- (next time round) generate a binding to connect the two
1403 -- Here the two ?x's have different types, and improvement
1404 -- makes them the same.
1406 tcSimplifyIPs given_ips wanteds
1407 = do { wanteds' <- mappM zonkInst wanteds
1408 ; given_ips' <- mappM zonkInst given_ips
1409 -- Unusually for checking, we *must* zonk the given_ips
1411 ; let env = mkRedEnv doc try_me given_ips'
1412 ; (improved, binds, irreds) <- reduceContext env wanteds'
1414 ; if not improved then
1415 ASSERT( all is_free irreds )
1416 do { extendLIEs irreds
1419 tcSimplifyIPs given_ips wanteds }
1421 doc = text "tcSimplifyIPs" <+> ppr given_ips
1422 ip_set = mkNameSet (ipNamesOfInsts given_ips)
1423 is_free inst = isFreeWrtIPs ip_set inst
1425 -- Simplify any methods that mention the implicit parameter
1426 try_me inst | is_free inst = Stop
1427 | otherwise = ReduceMe NoSCs
1431 %************************************************************************
1433 \subsection[binds-for-local-funs]{@bindInstsOfLocalFuns@}
1435 %************************************************************************
1437 When doing a binding group, we may have @Insts@ of local functions.
1438 For example, we might have...
1440 let f x = x + 1 -- orig local function (overloaded)
1441 f.1 = f Int -- two instances of f
1446 The point is: we must drop the bindings for @f.1@ and @f.2@ here,
1447 where @f@ is in scope; those @Insts@ must certainly not be passed
1448 upwards towards the top-level. If the @Insts@ were binding-ified up
1449 there, they would have unresolvable references to @f@.
1451 We pass in an @init_lie@ of @Insts@ and a list of locally-bound @Ids@.
1452 For each method @Inst@ in the @init_lie@ that mentions one of the
1453 @Ids@, we create a binding. We return the remaining @Insts@ (in an
1454 @LIE@), as well as the @HsBinds@ generated.
1457 bindInstsOfLocalFuns :: [Inst] -> [TcId] -> TcM TcDictBinds
1458 -- Simlifies only MethodInsts, and generate only bindings of form
1460 -- We're careful not to even generate bindings of the form
1462 -- You'd think that'd be fine, but it interacts with what is
1463 -- arguably a bug in Match.tidyEqnInfo (see notes there)
1465 bindInstsOfLocalFuns wanteds local_ids
1466 | null overloaded_ids
1468 = extendLIEs wanteds `thenM_`
1469 returnM emptyLHsBinds
1472 = do { (irreds, binds) <- checkLoop env for_me
1473 ; extendLIEs not_for_me
1477 env = mkRedEnv doc try_me []
1478 doc = text "bindInsts" <+> ppr local_ids
1479 overloaded_ids = filter is_overloaded local_ids
1480 is_overloaded id = isOverloadedTy (idType id)
1481 (for_me, not_for_me) = partition (isMethodFor overloaded_set) wanteds
1483 overloaded_set = mkVarSet overloaded_ids -- There can occasionally be a lot of them
1484 -- so it's worth building a set, so that
1485 -- lookup (in isMethodFor) is faster
1486 try_me inst | isMethod inst = ReduceMe NoSCs
1491 %************************************************************************
1493 \subsection{Data types for the reduction mechanism}
1495 %************************************************************************
1497 The main control over context reduction is here
1501 = RedEnv { red_doc :: SDoc -- The context
1502 , red_try_me :: Inst -> WhatToDo
1503 , red_improve :: Bool -- True <=> do improvement
1504 , red_givens :: [Inst] -- All guaranteed rigid
1506 -- but see Note [Rigidity]
1507 , red_stack :: (Int, [Inst]) -- Recursion stack (for err msg)
1508 -- See Note [RedStack]
1512 -- The red_givens are rigid so far as cmpInst is concerned.
1513 -- There is one case where they are not totally rigid, namely in tcSimplifyIPs
1514 -- let ?x = e in ...
1515 -- Here, the given is (?x::a), where 'a' is not necy a rigid type
1516 -- But that doesn't affect the comparison, which is based only on mame.
1519 -- The red_stack pair (n,insts) pair is just used for error reporting.
1520 -- 'n' is always the depth of the stack.
1521 -- The 'insts' is the stack of Insts being reduced: to produce X
1522 -- I had to produce Y, to produce Y I had to produce Z, and so on.
1525 mkRedEnv :: SDoc -> (Inst -> WhatToDo) -> [Inst] -> RedEnv
1526 mkRedEnv doc try_me givens
1527 = RedEnv { red_doc = doc, red_try_me = try_me,
1528 red_givens = givens, red_stack = (0,[]),
1529 red_improve = True }
1531 mkNoImproveRedEnv :: SDoc -> (Inst -> WhatToDo) -> RedEnv
1532 -- Do not do improvement; no givens
1533 mkNoImproveRedEnv doc try_me
1534 = RedEnv { red_doc = doc, red_try_me = try_me,
1535 red_givens = [], red_stack = (0,[]),
1536 red_improve = True }
1539 = ReduceMe WantSCs -- Try to reduce this
1540 -- If there's no instance, add the inst to the
1541 -- irreductible ones, but don't produce an error
1542 -- message of any kind.
1543 -- It might be quite legitimate such as (Eq a)!
1545 | Stop -- Return as irreducible unless it can
1546 -- be reduced to a constant in one step
1547 -- Do not add superclasses; see
1549 data WantSCs = NoSCs | AddSCs -- Tells whether we should add the superclasses
1550 -- of a predicate when adding it to the avails
1551 -- The reason for this flag is entirely the super-class loop problem
1552 -- Note [SUPER-CLASS LOOP 1]
1555 %************************************************************************
1557 \subsection[reduce]{@reduce@}
1559 %************************************************************************
1563 reduceContext :: RedEnv
1565 -> TcM (ImprovementDone,
1566 TcDictBinds, -- Dictionary bindings
1567 [Inst]) -- Irreducible
1569 reduceContext env wanteds
1570 = do { traceTc (text "reduceContext" <+> (vcat [
1571 text "----------------------",
1573 text "given" <+> ppr (red_givens env),
1574 text "wanted" <+> ppr wanteds,
1575 text "----------------------"
1578 -- Build the Avail mapping from "givens"
1579 ; init_state <- foldlM addGiven emptyAvails (red_givens env)
1582 ; avails <- reduceList env wanteds init_state
1584 ; let improved = availsImproved avails
1585 ; (binds, irreds) <- extractResults avails wanteds
1587 ; traceTc (text "reduceContext end" <+> (vcat [
1588 text "----------------------",
1590 text "given" <+> ppr (red_givens env),
1591 text "wanted" <+> ppr wanteds,
1593 text "avails" <+> pprAvails avails,
1594 text "improved =" <+> ppr improved,
1595 text "----------------------"
1598 ; return (improved, binds, irreds) }
1600 tcImproveOne :: Avails -> Inst -> TcM ImprovementDone
1601 tcImproveOne avails inst
1602 | not (isDict inst) = return False
1604 = do { inst_envs <- tcGetInstEnvs
1605 ; let eqns = improveOne (classInstances inst_envs)
1606 (dictPred inst, pprInstArising inst)
1607 [ (dictPred p, pprInstArising p)
1608 | p <- availsInsts avails, isDict p ]
1609 -- Avails has all the superclasses etc (good)
1610 -- It also has all the intermediates of the deduction (good)
1611 -- It does not have duplicates (good)
1612 -- NB that (?x::t1) and (?x::t2) will be held separately in avails
1613 -- so that improve will see them separate
1614 ; traceTc (text "improveOne" <+> ppr inst)
1617 unifyEqns :: [(Equation,(PredType,SDoc),(PredType,SDoc))]
1618 -> TcM ImprovementDone
1619 unifyEqns [] = return False
1621 = do { traceTc (ptext SLIT("Improve:") <+> vcat (map pprEquationDoc eqns))
1625 unify ((qtvs, pairs), what1, what2)
1626 = addErrCtxtM (mkEqnMsg what1 what2) $
1627 tcInstTyVars (varSetElems qtvs) `thenM` \ (_, _, tenv) ->
1628 mapM_ (unif_pr tenv) pairs
1629 unif_pr tenv (ty1,ty2) = unifyType (substTy tenv ty1) (substTy tenv ty2)
1631 pprEquationDoc (eqn, (p1,w1), (p2,w2)) = vcat [pprEquation eqn, nest 2 (ppr p1), nest 2 (ppr p2)]
1633 mkEqnMsg (pred1,from1) (pred2,from2) tidy_env
1634 = do { pred1' <- zonkTcPredType pred1; pred2' <- zonkTcPredType pred2
1635 ; let { pred1'' = tidyPred tidy_env pred1'; pred2'' = tidyPred tidy_env pred2' }
1636 ; let msg = vcat [ptext SLIT("When using functional dependencies to combine"),
1637 nest 2 (sep [ppr pred1'' <> comma, nest 2 from1]),
1638 nest 2 (sep [ppr pred2'' <> comma, nest 2 from2])]
1639 ; return (tidy_env, msg) }
1642 The main context-reduction function is @reduce@. Here's its game plan.
1645 reduceList :: RedEnv -> [Inst] -> Avails -> TcM Avails
1646 reduceList env@(RedEnv {red_stack = (n,stk)}) wanteds state
1647 = do { dopts <- getDOpts
1650 dumpTcRn (hang (ptext SLIT("Interesting! Context reduction stack depth") <+> int n)
1651 2 (ifPprDebug (nest 2 (pprStack stk))))
1654 ; if n >= ctxtStkDepth dopts then
1655 failWithTc (reduceDepthErr n stk)
1659 go [] state = return state
1660 go (w:ws) state = do { state' <- reduce (env {red_stack = (n+1, w:stk)}) w state
1663 -- Base case: we're done!
1664 reduce env wanted avails
1665 -- It's the same as an existing inst, or a superclass thereof
1666 | Just avail <- findAvail avails wanted
1670 = case red_try_me env wanted of {
1671 ; Stop -> try_simple (addIrred NoSCs) -- See Note [No superclasses for Stop]
1673 ; ReduceMe want_scs -> -- It should be reduced
1674 reduceInst env avails wanted `thenM` \ (avails, lookup_result) ->
1675 case lookup_result of
1676 NoInstance -> -- No such instance!
1677 -- Add it and its superclasses
1678 addIrred want_scs avails wanted
1680 GenInst [] rhs -> addWanted want_scs avails wanted rhs []
1682 GenInst wanteds' rhs -> do { avails1 <- addIrred NoSCs avails wanted
1683 ; avails2 <- reduceList env wanteds' avails1
1684 ; addWanted want_scs avails2 wanted rhs wanteds' }
1685 -- Temporarily do addIrred *before* the reduceList,
1686 -- which has the effect of adding the thing we are trying
1687 -- to prove to the database before trying to prove the things it
1688 -- needs. See note [RECURSIVE DICTIONARIES]
1689 -- NB: we must not do an addWanted before, because that adds the
1690 -- superclasses too, and thaat can lead to a spurious loop; see
1691 -- the examples in [SUPERCLASS-LOOP]
1692 -- So we do an addIrred before, and then overwrite it afterwards with addWanted
1696 -- First, see if the inst can be reduced to a constant in one step
1697 -- Works well for literals (1::Int) and constant dictionaries (d::Num Int)
1698 -- Don't bother for implication constraints, which take real work
1699 try_simple do_this_otherwise
1700 = do { res <- lookupSimpleInst wanted
1702 GenInst [] rhs -> addWanted AddSCs avails wanted rhs []
1703 other -> do_this_otherwise avails wanted }
1707 Note [SUPERCLASS-LOOP 2]
1708 ~~~~~~~~~~~~~~~~~~~~~~~~
1709 But the above isn't enough. Suppose we are *given* d1:Ord a,
1710 and want to deduce (d2:C [a]) where
1712 class Ord a => C a where
1713 instance Ord [a] => C [a] where ...
1715 Then we'll use the instance decl to deduce C [a] from Ord [a], and then add the
1716 superclasses of C [a] to avails. But we must not overwrite the binding
1717 for Ord [a] (which is obtained from Ord a) with a superclass selection or we'll just
1720 Here's another variant, immortalised in tcrun020
1721 class Monad m => C1 m
1722 class C1 m => C2 m x
1723 instance C2 Maybe Bool
1724 For the instance decl we need to build (C1 Maybe), and it's no good if
1725 we run around and add (C2 Maybe Bool) and its superclasses to the avails
1726 before we search for C1 Maybe.
1728 Here's another example
1729 class Eq b => Foo a b
1730 instance Eq a => Foo [a] a
1734 we'll first deduce that it holds (via the instance decl). We must not
1735 then overwrite the Eq t constraint with a superclass selection!
1737 At first I had a gross hack, whereby I simply did not add superclass constraints
1738 in addWanted, though I did for addGiven and addIrred. This was sub-optimal,
1739 becuase it lost legitimate superclass sharing, and it still didn't do the job:
1740 I found a very obscure program (now tcrun021) in which improvement meant the
1741 simplifier got two bites a the cherry... so something seemed to be an Stop
1742 first time, but reducible next time.
1744 Now we implement the Right Solution, which is to check for loops directly
1745 when adding superclasses. It's a bit like the occurs check in unification.
1748 Note [RECURSIVE DICTIONARIES]
1749 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1751 data D r = ZeroD | SuccD (r (D r));
1753 instance (Eq (r (D r))) => Eq (D r) where
1754 ZeroD == ZeroD = True
1755 (SuccD a) == (SuccD b) = a == b
1758 equalDC :: D [] -> D [] -> Bool;
1761 We need to prove (Eq (D [])). Here's how we go:
1765 by instance decl, holds if
1769 by instance decl of Eq, holds if
1771 where d2 = dfEqList d3
1774 But now we can "tie the knot" to give
1780 and it'll even run! The trick is to put the thing we are trying to prove
1781 (in this case Eq (D []) into the database before trying to prove its
1782 contributing clauses.
1785 %************************************************************************
1787 Reducing a single constraint
1789 %************************************************************************
1792 ---------------------------------------------
1793 reduceInst :: RedEnv -> Avails -> Inst -> TcM (Avails, LookupInstResult)
1794 reduceInst env avails (ImplicInst { tci_tyvars = tvs, tci_reft = reft, tci_loc = loc,
1795 tci_given = extra_givens, tci_wanted = wanteds })
1796 = reduceImplication env avails reft tvs extra_givens wanteds loc
1798 reduceInst env avails other_inst
1799 = do { result <- lookupSimpleInst other_inst
1800 ; return (avails, result) }
1804 ---------------------------------------------
1805 reduceImplication :: RedEnv
1807 -> Refinement -- May refine the givens; often empty
1808 -> [TcTyVar] -- Quantified type variables; all skolems
1809 -> [Inst] -- Extra givens; all rigid
1812 -> TcM (Avails, LookupInstResult)
1815 Suppose we are simplifying the constraint
1816 forall bs. extras => wanted
1817 in the context of an overall simplification problem with givens 'givens',
1818 and refinment 'reft'.
1821 * The refinement is often empty
1823 * The 'extra givens' need not mention any of the quantified type variables
1824 e.g. forall {}. Eq a => Eq [a]
1825 forall {}. C Int => D (Tree Int)
1827 This happens when you have something like
1829 T1 :: Eq a => a -> T a
1832 f x = ...(case x of { T1 v -> v==v })...
1835 -- ToDo: should we instantiate tvs? I think it's not necessary
1837 -- ToDo: what about improvement? There may be some improvement
1838 -- exposed as a result of the simplifications done by reduceList
1839 -- which are discarded if we back off.
1840 -- This is almost certainly Wrong, but we'll fix it when dealing
1841 -- better with equality constraints
1842 reduceImplication env orig_avails reft tvs extra_givens wanteds inst_loc
1843 = do { -- Add refined givens, and the extra givens
1844 (refined_red_givens, avails)
1845 <- if isEmptyRefinement reft then return (red_givens env, orig_avails)
1846 else foldlM (addRefinedGiven reft) ([], orig_avails) (red_givens env)
1847 ; avails <- foldlM addGiven avails extra_givens
1849 -- Solve the sub-problem
1850 ; let try_me inst = ReduceMe AddSCs -- Note [Freeness and implications]
1851 env' = env { red_givens = refined_red_givens ++ extra_givens
1852 , red_try_me = try_me }
1854 ; traceTc (text "reduceImplication" <+> vcat
1856 ppr (red_givens env), ppr extra_givens,
1857 ppr reft, ppr wanteds, ppr avails ])
1858 ; avails <- reduceList env' wanteds avails
1860 -- Extract the binding
1861 ; (binds, irreds) <- extractResults avails wanteds
1863 -- We always discard the extra avails we've generated;
1864 -- but we remember if we have done any (global) improvement
1865 ; let ret_avails = updateImprovement orig_avails avails
1867 ; if isEmptyLHsBinds binds then -- No progress
1868 return (ret_avails, NoInstance)
1870 { (implic_insts, bind) <- makeImplicationBind inst_loc tvs reft extra_givens irreds
1871 -- This binding is useless if the recursive simplification
1872 -- made no progress; but currently we don't try to optimise that
1873 -- case. After all, we only try hard to reduce at top level, or
1874 -- when inferring types.
1876 ; let dict_ids = map instToId extra_givens
1877 co = mkWpTyLams tvs <.> mkWpLams dict_ids <.> WpLet (binds `unionBags` bind)
1878 rhs = mkHsWrap co payload
1879 loc = instLocSpan inst_loc
1880 payload | isSingleton wanteds = HsVar (instToId (head wanteds))
1881 | otherwise = ExplicitTuple (map (L loc . HsVar . instToId) wanteds) Boxed
1883 -- If there are any irreds, we back off and return NoInstance
1884 ; return (ret_avails, GenInst implic_insts (L loc rhs))
1888 Note [Freeness and implications]
1889 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1890 It's hard to say when an implication constraint can be floated out. Consider
1891 forall {} Eq a => Foo [a]
1892 The (Foo [a]) doesn't mention any of the quantified variables, but it
1893 still might be partially satisfied by the (Eq a).
1895 There is a useful special case when it *is* easy to partition the
1896 constraints, namely when there are no 'givens'. Consider
1897 forall {a}. () => Bar b
1898 There are no 'givens', and so there is no reason to capture (Bar b).
1899 We can let it float out. But if there is even one constraint we
1900 must be much more careful:
1901 forall {a}. C a b => Bar (m b)
1902 because (C a b) might have a superclass (D b), from which we might
1903 deduce (Bar [b]) when m later gets instantiated to []. Ha!
1905 Here is an even more exotic example
1907 Now consider the constraint
1908 forall b. D Int b => C Int
1909 We can satisfy the (C Int) from the superclass of D, so we don't want
1910 to float the (C Int) out, even though it mentions no type variable in
1913 Note [Pruning the givens in an implication constraint]
1914 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1915 Suppose we are about to form the implication constraint
1916 forall tvs. Eq a => Ord b
1917 The (Eq a) cannot contribute to the (Ord b), because it has no access to
1918 the type variable 'b'. So we could filter out the (Eq a) from the givens.
1920 Doing so would be a bit tidier, but all the implication constraints get
1921 simplified away by the optimiser, so it's no great win. So I don't take
1922 advantage of that at the moment.
1924 If you do, BE CAREFUL of wobbly type variables.
1927 %************************************************************************
1929 Avails and AvailHow: the pool of evidence
1931 %************************************************************************
1935 data Avails = Avails !ImprovementDone !AvailEnv
1937 type ImprovementDone = Bool -- True <=> some unification has happened
1938 -- so some Irreds might now be reducible
1939 -- keys that are now
1941 type AvailEnv = FiniteMap Inst AvailHow
1943 = IsIrred -- Used for irreducible dictionaries,
1944 -- which are going to be lambda bound
1946 | Given TcId -- Used for dictionaries for which we have a binding
1947 -- e.g. those "given" in a signature
1949 | Rhs -- Used when there is a RHS
1950 (LHsExpr TcId) -- The RHS
1951 [Inst] -- Insts free in the RHS; we need these too
1953 instance Outputable Avails where
1956 pprAvails (Avails imp avails)
1957 = vcat [ ptext SLIT("Avails") <> (if imp then ptext SLIT("[improved]") else empty)
1958 , nest 2 (vcat [sep [ppr inst, nest 2 (equals <+> ppr avail)]
1959 | (inst,avail) <- fmToList avails ])]
1961 instance Outputable AvailHow where
1964 -------------------------
1965 pprAvail :: AvailHow -> SDoc
1966 pprAvail IsIrred = text "Irred"
1967 pprAvail (Given x) = text "Given" <+> ppr x
1968 pprAvail (Rhs rhs bs) = text "Rhs" <+> ppr rhs <+> braces (ppr bs)
1970 -------------------------
1971 extendAvailEnv :: AvailEnv -> Inst -> AvailHow -> AvailEnv
1972 extendAvailEnv env inst avail = addToFM env inst avail
1974 findAvailEnv :: AvailEnv -> Inst -> Maybe AvailHow
1975 findAvailEnv env wanted = lookupFM env wanted
1976 -- NB 1: the Ord instance of Inst compares by the class/type info
1977 -- *not* by unique. So
1978 -- d1::C Int == d2::C Int
1980 emptyAvails :: Avails
1981 emptyAvails = Avails False emptyFM
1983 findAvail :: Avails -> Inst -> Maybe AvailHow
1984 findAvail (Avails _ avails) wanted = findAvailEnv avails wanted
1986 elemAvails :: Inst -> Avails -> Bool
1987 elemAvails wanted (Avails _ avails) = wanted `elemFM` avails
1989 extendAvails :: Avails -> Inst -> AvailHow -> TcM Avails
1991 extendAvails avails@(Avails imp env) inst avail
1992 = do { imp1 <- tcImproveOne avails inst -- Do any improvement
1993 ; return (Avails (imp || imp1) (extendAvailEnv env inst avail)) }
1995 availsInsts :: Avails -> [Inst]
1996 availsInsts (Avails _ avails) = keysFM avails
1998 availsImproved (Avails imp _) = imp
2000 updateImprovement :: Avails -> Avails -> Avails
2001 -- (updateImprovement a1 a2) sets a1's improvement flag from a2
2002 updateImprovement (Avails _ avails1) (Avails imp2 _) = Avails imp2 avails1
2005 Extracting the bindings from a bunch of Avails.
2006 The bindings do *not* come back sorted in dependency order.
2007 We assume that they'll be wrapped in a big Rec, so that the
2008 dependency analyser can sort them out later
2011 extractResults :: Avails
2013 -> TcM ( TcDictBinds, -- Bindings
2014 [Inst]) -- Irreducible ones
2016 extractResults (Avails _ avails) wanteds
2017 = go avails emptyBag [] wanteds
2019 go :: AvailEnv -> TcDictBinds -> [Inst] -> [Inst]
2020 -> TcM (TcDictBinds, [Inst])
2021 go avails binds irreds []
2022 = returnM (binds, irreds)
2024 go avails binds irreds (w:ws)
2025 = case findAvailEnv avails w of
2026 Nothing -> pprTrace "Urk: extractResults" (ppr w) $
2027 go avails binds irreds ws
2029 Just IsIrred -> go (add_given avails w) binds (w:irreds) ws
2033 -> go avails binds irreds ws
2034 -- The sought Id can be one of the givens, via a superclass chain
2035 -- and then we definitely don't want to generate an x=x binding!
2038 -> go avails (addBind binds w (nlHsVar id)) irreds ws
2040 Just (Rhs rhs ws') -> go (add_given avails w) new_binds irreds (ws' ++ ws)
2042 new_binds = addBind binds w rhs
2044 add_given avails w = extendAvailEnv avails w (Given (instToId w))
2046 addBind binds inst rhs = binds `unionBags` unitBag (L (instSpan inst)
2047 (VarBind (instToId inst) rhs))
2051 Note [No superclasses for Stop]
2052 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2053 When we decide not to reduce an Inst -- the 'WhatToDo' --- we still
2054 add it to avails, so that any other equal Insts will be commoned up
2055 right here. However, we do *not* add superclasses. If we have
2058 but a is not bound here, then we *don't* want to derive dn from df
2059 here lest we lose sharing.
2062 addWanted :: WantSCs -> Avails -> Inst -> LHsExpr TcId -> [Inst] -> TcM Avails
2063 addWanted want_scs avails wanted rhs_expr wanteds
2064 = addAvailAndSCs want_scs avails wanted avail
2066 avail = Rhs rhs_expr wanteds
2068 addGiven :: Avails -> Inst -> TcM Avails
2069 addGiven avails given = addAvailAndSCs AddSCs avails given (Given (instToId given))
2070 -- Always add superclasses for 'givens'
2072 -- No ASSERT( not (given `elemAvails` avails) ) because in an instance
2073 -- decl for Ord t we can add both Ord t and Eq t as 'givens',
2074 -- so the assert isn't true
2076 addRefinedGiven :: Refinement -> ([Inst], Avails) -> Inst -> TcM ([Inst], Avails)
2077 addRefinedGiven reft (refined_givens, avails) given
2078 | isDict given -- We sometimes have 'given' methods, but they
2079 -- are always optional, so we can drop them
2080 , let pred = dictPred given
2081 , isRefineablePred pred -- See Note [ImplicInst rigidity]
2082 , Just (co, pred) <- refinePred reft pred
2083 = do { new_given <- newDictBndr (instLoc given) pred
2084 ; let rhs = L (instSpan given) $
2085 HsWrap (WpCo co) (HsVar (instToId given))
2086 ; avails <- addAvailAndSCs AddSCs avails new_given (Rhs rhs [given])
2087 ; return (new_given:refined_givens, avails) }
2088 -- ToDo: the superclasses of the original given all exist in Avails
2089 -- so we could really just cast them, but it's more awkward to do,
2090 -- and hopefully the optimiser will spot the duplicated work
2092 = return (refined_givens, avails)
2095 Note [ImplicInst rigidity]
2096 ~~~~~~~~~~~~~~~~~~~~~~~~~~
2098 C :: forall ab. (Eq a, Ord b) => b -> T a
2100 ...(case x of C v -> <body>)...
2102 From the case (where x::T ty) we'll get an implication constraint
2103 forall b. (Eq ty, Ord b) => <body-constraints>
2104 Now suppose <body-constraints> itself has an implication constraint
2106 forall c. <reft> => <payload>
2107 Then, we can certainly apply the refinement <reft> to the Ord b, becuase it is
2108 existential, but we probably should not apply it to the (Eq ty) because it may
2109 be wobbly. Hence the isRigidInst
2111 @Insts@ are ordered by their class/type info, rather than by their
2112 unique. This allows the context-reduction mechanism to use standard finite
2113 maps to do their stuff. It's horrible that this code is here, rather
2114 than with the Avails handling stuff in TcSimplify
2117 addIrred :: WantSCs -> Avails -> Inst -> TcM Avails
2118 addIrred want_scs avails irred = ASSERT2( not (irred `elemAvails` avails), ppr irred $$ ppr avails )
2119 addAvailAndSCs want_scs avails irred IsIrred
2121 addAvailAndSCs :: WantSCs -> Avails -> Inst -> AvailHow -> TcM Avails
2122 addAvailAndSCs want_scs avails inst avail
2123 | not (isClassDict inst) = extendAvails avails inst avail
2124 | NoSCs <- want_scs = extendAvails avails inst avail
2125 | otherwise = do { traceTc (text "addAvailAndSCs" <+> vcat [ppr inst, ppr deps])
2126 ; avails' <- extendAvails avails inst avail
2127 ; addSCs is_loop avails' inst }
2129 is_loop pred = any (`tcEqType` mkPredTy pred) dep_tys
2130 -- Note: this compares by *type*, not by Unique
2131 deps = findAllDeps (unitVarSet (instToId inst)) avail
2132 dep_tys = map idType (varSetElems deps)
2134 findAllDeps :: IdSet -> AvailHow -> IdSet
2135 -- Find all the Insts that this one depends on
2136 -- See Note [SUPERCLASS-LOOP 2]
2137 -- Watch out, though. Since the avails may contain loops
2138 -- (see Note [RECURSIVE DICTIONARIES]), so we need to track the ones we've seen so far
2139 findAllDeps so_far (Rhs _ kids) = foldl find_all so_far kids
2140 findAllDeps so_far other = so_far
2142 find_all :: IdSet -> Inst -> IdSet
2144 | kid_id `elemVarSet` so_far = so_far
2145 | Just avail <- findAvail avails kid = findAllDeps so_far' avail
2146 | otherwise = so_far'
2148 so_far' = extendVarSet so_far kid_id -- Add the new kid to so_far
2149 kid_id = instToId kid
2151 addSCs :: (TcPredType -> Bool) -> Avails -> Inst -> TcM Avails
2152 -- Add all the superclasses of the Inst to Avails
2153 -- The first param says "dont do this because the original thing
2154 -- depends on this one, so you'd build a loop"
2155 -- Invariant: the Inst is already in Avails.
2157 addSCs is_loop avails dict
2158 = ASSERT( isDict dict )
2159 do { sc_dicts <- newDictBndrs (instLoc dict) sc_theta'
2160 ; foldlM add_sc avails (zipEqual "add_scs" sc_dicts sc_sels) }
2162 (clas, tys) = getDictClassTys dict
2163 (tyvars, sc_theta, sc_sels, _) = classBigSig clas
2164 sc_theta' = substTheta (zipTopTvSubst tyvars tys) sc_theta
2166 add_sc avails (sc_dict, sc_sel)
2167 | is_loop (dictPred sc_dict) = return avails -- See Note [SUPERCLASS-LOOP 2]
2168 | is_given sc_dict = return avails
2169 | otherwise = do { avails' <- extendAvails avails sc_dict (Rhs sc_sel_rhs [dict])
2170 ; addSCs is_loop avails' sc_dict }
2172 sc_sel_rhs = L (instSpan dict) (HsWrap co_fn (HsVar sc_sel))
2173 co_fn = WpApp (instToId dict) <.> mkWpTyApps tys
2175 is_given :: Inst -> Bool
2176 is_given sc_dict = case findAvail avails sc_dict of
2177 Just (Given _) -> True -- Given is cheaper than superclass selection
2181 %************************************************************************
2183 \section{tcSimplifyTop: defaulting}
2185 %************************************************************************
2188 @tcSimplifyTop@ is called once per module to simplify all the constant
2189 and ambiguous Insts.
2191 We need to be careful of one case. Suppose we have
2193 instance Num a => Num (Foo a b) where ...
2195 and @tcSimplifyTop@ is given a constraint (Num (Foo x y)). Then it'll simplify
2196 to (Num x), and default x to Int. But what about y??
2198 It's OK: the final zonking stage should zap y to (), which is fine.
2202 tcSimplifyTop, tcSimplifyInteractive :: [Inst] -> TcM TcDictBinds
2203 tcSimplifyTop wanteds
2204 = tc_simplify_top doc False wanteds
2206 doc = text "tcSimplifyTop"
2208 tcSimplifyInteractive wanteds
2209 = tc_simplify_top doc True wanteds
2211 doc = text "tcSimplifyInteractive"
2213 -- The TcLclEnv should be valid here, solely to improve
2214 -- error message generation for the monomorphism restriction
2215 tc_simplify_top doc interactive wanteds
2216 = do { wanteds <- mapM zonkInst wanteds
2217 ; mapM_ zonkTopTyVar (varSetElems (tyVarsOfInsts wanteds))
2219 ; (irreds1, binds1) <- topCheckLoop doc wanteds
2221 ; if null irreds1 then
2224 -- OK, so there are some errors
2225 { -- Use the defaulting rules to do extra unification
2226 -- NB: irreds are already zonked
2227 ; dflags <- getDOpts
2228 ; disambiguate interactive dflags irreds1 -- Does unification
2229 ; (irreds2, binds2) <- topCheckLoop doc irreds1
2231 -- Deal with implicit parameter
2232 ; let (bad_ips, non_ips) = partition isIPDict irreds2
2233 (ambigs, others) = partition isTyVarDict non_ips
2235 ; topIPErrs bad_ips -- Can arise from f :: Int -> Int
2237 ; addNoInstanceErrs others
2238 ; addTopAmbigErrs ambigs
2240 ; return (binds1 `unionBags` binds2) }}
2243 If a dictionary constrains a type variable which is
2244 * not mentioned in the environment
2245 * and not mentioned in the type of the expression
2246 then it is ambiguous. No further information will arise to instantiate
2247 the type variable; nor will it be generalised and turned into an extra
2248 parameter to a function.
2250 It is an error for this to occur, except that Haskell provided for
2251 certain rules to be applied in the special case of numeric types.
2253 * at least one of its classes is a numeric class, and
2254 * all of its classes are numeric or standard
2255 then the type variable can be defaulted to the first type in the
2256 default-type list which is an instance of all the offending classes.
2258 So here is the function which does the work. It takes the ambiguous
2259 dictionaries and either resolves them (producing bindings) or
2260 complains. It works by splitting the dictionary list by type
2261 variable, and using @disambigOne@ to do the real business.
2263 @disambigOne@ assumes that its arguments dictionaries constrain all
2264 the same type variable.
2266 ADR Comment 20/6/94: I've changed the @CReturnable@ case to default to
2267 @()@ instead of @Int@. I reckon this is the Right Thing to do since
2268 the most common use of defaulting is code like:
2270 _ccall_ foo `seqPrimIO` bar
2272 Since we're not using the result of @foo@, the result if (presumably)
2276 disambiguate :: Bool -> DynFlags -> [Inst] -> TcM ()
2277 -- Just does unification to fix the default types
2278 -- The Insts are assumed to be pre-zonked
2279 disambiguate interactive dflags insts
2280 | null defaultable_groups
2281 = do { traceTc (text "disambigutate" <+> vcat [ppr unaries, ppr bad_tvs, ppr defaultable_groups])
2284 = do { -- Figure out what default types to use
2285 ; default_tys <- getDefaultTys extended_defaulting ovl_strings
2287 ; traceTc (text "disambigutate" <+> vcat [ppr unaries, ppr bad_tvs, ppr defaultable_groups])
2288 ; mapM_ (disambigGroup default_tys) defaultable_groups }
2290 extended_defaulting = interactive || dopt Opt_ExtendedDefaultRules dflags
2291 ovl_strings = dopt Opt_OverloadedStrings dflags
2293 unaries :: [(Inst,Class, TcTyVar)] -- (C tv) constraints
2294 bad_tvs :: TcTyVarSet -- Tyvars mentioned by *other* constraints
2295 (unaries, bad_tvs) = getDefaultableDicts insts
2297 -- Group by type variable
2298 defaultable_groups :: [[(Inst,Class,TcTyVar)]]
2299 defaultable_groups = filter defaultable_group (equivClasses cmp_tv unaries)
2300 cmp_tv (_,_,tv1) (_,_,tv2) = tv1 `compare` tv2
2302 defaultable_group :: [(Inst,Class,TcTyVar)] -> Bool
2303 defaultable_group ds@((_,_,tv):_)
2304 = isTyConableTyVar tv -- Note [Avoiding spurious errors]
2305 && not (tv `elemVarSet` bad_tvs)
2306 && defaultable_classes [c | (_,c,_) <- ds]
2307 defaultable_group [] = panic "defaultable_group"
2309 defaultable_classes clss
2310 | extended_defaulting = any isInteractiveClass clss
2311 | otherwise = all is_std_class clss && (any is_num_class clss)
2313 -- In interactive mode, or with -fextended-default-rules,
2314 -- we default Show a to Show () to avoid graututious errors on "show []"
2315 isInteractiveClass cls
2316 = is_num_class cls || (classKey cls `elem` [showClassKey, eqClassKey, ordClassKey])
2318 is_num_class cls = isNumericClass cls || (ovl_strings && (cls `hasKey` isStringClassKey))
2319 -- is_num_class adds IsString to the standard numeric classes,
2320 -- when -foverloaded-strings is enabled
2322 is_std_class cls = isStandardClass cls || (ovl_strings && (cls `hasKey` isStringClassKey))
2323 -- Similarly is_std_class
2325 disambigGroup :: [Type] -- The default types
2326 -> [(Inst,Class,TcTyVar)] -- All standard classes of form (C a)
2327 -> TcM () -- Just does unification, to fix the default types
2329 disambigGroup default_tys dicts
2330 = try_default default_tys
2332 (_,_,tyvar) = head dicts -- Should be non-empty
2333 classes = [c | (_,c,_) <- dicts]
2335 try_default [] = return ()
2336 try_default (default_ty : default_tys)
2337 = tryTcLIE_ (try_default default_tys) $
2338 do { tcSimplifyDefault [mkClassPred clas [default_ty] | clas <- classes]
2339 -- This may fail; then the tryTcLIE_ kicks in
2340 -- Failure here is caused by there being no type in the
2341 -- default list which can satisfy all the ambiguous classes.
2342 -- For example, if Real a is reqd, but the only type in the
2343 -- default list is Int.
2345 -- After this we can't fail
2346 ; warnDefault dicts default_ty
2347 ; unifyType default_ty (mkTyVarTy tyvar) }
2350 getDefaultTys :: Bool -> Bool -> TcM [Type]
2351 getDefaultTys extended_deflts ovl_strings
2352 = do { mb_defaults <- getDeclaredDefaultTys
2353 ; case mb_defaults of {
2354 Just tys -> return tys ; -- User-supplied defaults
2357 -- No use-supplied default
2358 -- Use [Integer, Double], plus modifications
2359 { integer_ty <- tcMetaTy integerTyConName
2360 ; checkWiredInTyCon doubleTyCon
2361 ; string_ty <- tcMetaTy stringTyConName
2362 ; return (opt_deflt extended_deflts unitTy
2363 -- Note [Default unitTy]
2365 [integer_ty,doubleTy]
2367 opt_deflt ovl_strings string_ty) } } }
2369 opt_deflt True ty = [ty]
2370 opt_deflt False ty = []
2373 Note [Default unitTy]
2374 ~~~~~~~~~~~~~~~~~~~~~
2375 In interative mode (or with -fextended-default-rules) we add () as the first type we
2376 try when defaulting. This has very little real impact, except in the following case.
2378 Text.Printf.printf "hello"
2379 This has type (forall a. IO a); it prints "hello", and returns 'undefined'. We don't
2380 want the GHCi repl loop to try to print that 'undefined'. The neatest thing is to
2381 default the 'a' to (), rather than to Integer (which is what would otherwise happen;
2382 and then GHCi doesn't attempt to print the (). So in interactive mode, we add
2383 () to the list of defaulting types. See Trac #1200.
2385 Note [Avoiding spurious errors]
2386 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2387 When doing the unification for defaulting, we check for skolem
2388 type variables, and simply don't default them. For example:
2389 f = (*) -- Monomorphic
2390 g :: Num a => a -> a
2392 Here, we get a complaint when checking the type signature for g,
2393 that g isn't polymorphic enough; but then we get another one when
2394 dealing with the (Num a) context arising from f's definition;
2395 we try to unify a with Int (to default it), but find that it's
2396 already been unified with the rigid variable from g's type sig
2399 %************************************************************************
2401 \subsection[simple]{@Simple@ versions}
2403 %************************************************************************
2405 Much simpler versions when there are no bindings to make!
2407 @tcSimplifyThetas@ simplifies class-type constraints formed by
2408 @deriving@ declarations and when specialising instances. We are
2409 only interested in the simplified bunch of class/type constraints.
2411 It simplifies to constraints of the form (C a b c) where
2412 a,b,c are type variables. This is required for the context of
2413 instance declarations.
2416 tcSimplifyDeriv :: InstOrigin
2418 -> ThetaType -- Wanted
2419 -> TcM ThetaType -- Needed
2420 -- Given instance (wanted) => C inst_ty
2421 -- Simplify 'wanted' as much as possible
2422 -- The inst_ty is needed only for the termination check
2424 tcSimplifyDeriv orig tyvars theta
2425 = do { (tvs, _, tenv) <- tcInstTyVars tyvars
2426 -- The main loop may do unification, and that may crash if
2427 -- it doesn't see a TcTyVar, so we have to instantiate. Sigh
2428 -- ToDo: what if two of them do get unified?
2429 ; wanteds <- newDictBndrsO orig (substTheta tenv theta)
2430 ; (irreds, _) <- topCheckLoop doc wanteds
2432 ; let rev_env = zipTopTvSubst tvs (mkTyVarTys tyvars)
2433 simpl_theta = substTheta rev_env (map dictPred irreds)
2434 -- This reverse-mapping is a pain, but the result
2435 -- should mention the original TyVars not TcTyVars
2437 -- NB: the caller will further check the tv_dicts for
2438 -- legal instance-declaration form
2440 ; return simpl_theta }
2442 doc = ptext SLIT("deriving classes for a data type")
2447 @tcSimplifyDefault@ just checks class-type constraints, essentially;
2448 used with \tr{default} declarations. We are only interested in
2449 whether it worked or not.
2452 tcSimplifyDefault :: ThetaType -- Wanted; has no type variables in it
2455 tcSimplifyDefault theta
2456 = newDictBndrsO DefaultOrigin theta `thenM` \ wanteds ->
2457 topCheckLoop doc wanteds `thenM` \ (irreds, _) ->
2458 addNoInstanceErrs irreds `thenM_`
2464 doc = ptext SLIT("default declaration")
2468 %************************************************************************
2470 \section{Errors and contexts}
2472 %************************************************************************
2474 ToDo: for these error messages, should we note the location as coming
2475 from the insts, or just whatever seems to be around in the monad just
2479 groupErrs :: ([Inst] -> TcM ()) -- Deal with one group
2480 -> [Inst] -- The offending Insts
2482 -- Group together insts with the same origin
2483 -- We want to report them together in error messages
2485 groupErrs report_err []
2487 groupErrs report_err (inst:insts)
2488 = do_one (inst:friends) `thenM_`
2489 groupErrs report_err others
2492 -- (It may seem a bit crude to compare the error messages,
2493 -- but it makes sure that we combine just what the user sees,
2494 -- and it avoids need equality on InstLocs.)
2495 (friends, others) = partition is_friend insts
2496 loc_msg = showSDoc (pprInstLoc (instLoc inst))
2497 is_friend friend = showSDoc (pprInstLoc (instLoc friend)) == loc_msg
2498 do_one insts = addInstCtxt (instLoc (head insts)) (report_err insts)
2499 -- Add location and context information derived from the Insts
2501 -- Add the "arising from..." part to a message about bunch of dicts
2502 addInstLoc :: [Inst] -> Message -> Message
2503 addInstLoc insts msg = msg $$ nest 2 (pprInstArising (head insts))
2505 addTopIPErrs :: [Name] -> [Inst] -> TcM ()
2506 addTopIPErrs bndrs []
2508 addTopIPErrs bndrs ips
2509 = do { dflags <- getDOpts
2510 ; addErrTcM (tidy_env, mk_msg dflags tidy_ips) }
2512 (tidy_env, tidy_ips) = tidyInsts ips
2514 = vcat [sep [ptext SLIT("Implicit parameters escape from"),
2515 nest 2 (ptext SLIT("the monomorphic top-level binding")
2516 <> plural bndrs <+> ptext SLIT("of")
2517 <+> pprBinders bndrs <> colon)],
2518 nest 2 (vcat (map ppr_ip ips)),
2519 monomorphism_fix dflags]
2520 ppr_ip ip = pprPred (dictPred ip) <+> pprInstArising ip
2522 topIPErrs :: [Inst] -> TcM ()
2524 = groupErrs report tidy_dicts
2526 (tidy_env, tidy_dicts) = tidyInsts dicts
2527 report dicts = addErrTcM (tidy_env, mk_msg dicts)
2528 mk_msg dicts = addInstLoc dicts (ptext SLIT("Unbound implicit parameter") <>
2529 plural tidy_dicts <+> pprDictsTheta tidy_dicts)
2531 addNoInstanceErrs :: [Inst] -- Wanted (can include implications)
2533 addNoInstanceErrs insts
2534 = do { let (tidy_env, tidy_insts) = tidyInsts insts
2535 ; reportNoInstances tidy_env Nothing tidy_insts }
2539 -> Maybe (InstLoc, [Inst]) -- Context
2540 -- Nothing => top level
2541 -- Just (d,g) => d describes the construct
2543 -> [Inst] -- What is wanted (can include implications)
2546 reportNoInstances tidy_env mb_what insts
2547 = groupErrs (report_no_instances tidy_env mb_what) insts
2549 report_no_instances tidy_env mb_what insts
2550 = do { inst_envs <- tcGetInstEnvs
2551 ; let (implics, insts1) = partition isImplicInst insts
2552 (insts2, overlaps) = partitionWith (check_overlap inst_envs) insts1
2553 ; traceTc (text "reportNoInstnces" <+> vcat
2554 [ppr implics, ppr insts1, ppr insts2])
2555 ; mapM_ complain_implic implics
2556 ; mapM_ (\doc -> addErrTcM (tidy_env, doc)) overlaps
2557 ; groupErrs complain_no_inst insts2 }
2559 complain_no_inst insts = addErrTcM (tidy_env, mk_no_inst_err insts)
2561 complain_implic inst -- Recurse!
2562 = reportNoInstances tidy_env
2563 (Just (tci_loc inst, tci_given inst))
2566 check_overlap :: (InstEnv,InstEnv) -> Inst -> Either Inst SDoc
2567 -- Right msg => overlap message
2568 -- Left inst => no instance
2569 check_overlap inst_envs wanted
2570 | not (isClassDict wanted) = Left wanted
2572 = case lookupInstEnv inst_envs clas tys of
2573 -- The case of exactly one match and no unifiers means
2574 -- a successful lookup. That can't happen here, becuase
2575 -- dicts only end up here if they didn't match in Inst.lookupInst
2577 ([m],[]) -> pprPanic "reportNoInstance" (ppr wanted)
2579 ([], _) -> Left wanted -- No match
2580 res -> Right (mk_overlap_msg wanted res)
2582 (clas,tys) = getDictClassTys wanted
2584 mk_overlap_msg dict (matches, unifiers)
2585 = vcat [ addInstLoc [dict] ((ptext SLIT("Overlapping instances for")
2586 <+> pprPred (dictPred dict))),
2587 sep [ptext SLIT("Matching instances") <> colon,
2588 nest 2 (vcat [pprInstances ispecs, pprInstances unifiers])],
2589 ASSERT( not (null matches) )
2590 if not (isSingleton matches)
2591 then -- Two or more matches
2593 else -- One match, plus some unifiers
2594 ASSERT( not (null unifiers) )
2595 parens (vcat [ptext SLIT("The choice depends on the instantiation of") <+>
2596 quotes (pprWithCommas ppr (varSetElems (tyVarsOfInst dict))),
2597 ptext SLIT("Use -fallow-incoherent-instances to use the first choice above")])]
2599 ispecs = [ispec | (ispec, _) <- matches]
2601 mk_no_inst_err insts
2602 | null insts = empty
2604 | Just (loc, givens) <- mb_what, -- Nested (type signatures, instance decls)
2605 not (isEmptyVarSet (tyVarsOfInsts insts))
2606 = vcat [ addInstLoc insts $
2607 sep [ ptext SLIT("Could not deduce") <+> pprDictsTheta insts
2608 , nest 2 $ ptext SLIT("from the context") <+> pprDictsTheta givens]
2609 , show_fixes (fix1 loc : fixes2) ]
2611 | otherwise -- Top level
2612 = vcat [ addInstLoc insts $
2613 ptext SLIT("No instance") <> plural insts
2614 <+> ptext SLIT("for") <+> pprDictsTheta insts
2615 , show_fixes fixes2 ]
2618 fix1 loc = sep [ ptext SLIT("add") <+> pprDictsTheta insts
2619 <+> ptext SLIT("to the context of"),
2620 nest 2 (ppr (instLocOrigin loc)) ]
2621 -- I'm not sure it helps to add the location
2622 -- nest 2 (ptext SLIT("at") <+> ppr (instLocSpan loc)) ]
2624 fixes2 | null instance_dicts = []
2625 | otherwise = [sep [ptext SLIT("add an instance declaration for"),
2626 pprDictsTheta instance_dicts]]
2627 instance_dicts = [d | d <- insts, isClassDict d, not (isTyVarDict d)]
2628 -- Insts for which it is worth suggesting an adding an instance declaration
2629 -- Exclude implicit parameters, and tyvar dicts
2631 show_fixes :: [SDoc] -> SDoc
2632 show_fixes [] = empty
2633 show_fixes (f:fs) = sep [ptext SLIT("Possible fix:"),
2634 nest 2 (vcat (f : map (ptext SLIT("or") <+>) fs))]
2636 addTopAmbigErrs dicts
2637 -- Divide into groups that share a common set of ambiguous tyvars
2638 = ifErrsM (return ()) $ -- Only report ambiguity if no other errors happened
2639 -- See Note [Avoiding spurious errors]
2640 mapM_ report (equivClasses cmp [(d, tvs_of d) | d <- tidy_dicts])
2642 (tidy_env, tidy_dicts) = tidyInsts dicts
2644 tvs_of :: Inst -> [TcTyVar]
2645 tvs_of d = varSetElems (tyVarsOfInst d)
2646 cmp (_,tvs1) (_,tvs2) = tvs1 `compare` tvs2
2648 report :: [(Inst,[TcTyVar])] -> TcM ()
2649 report pairs@((inst,tvs) : _) -- The pairs share a common set of ambiguous tyvars
2650 = mkMonomorphismMsg tidy_env tvs `thenM` \ (tidy_env, mono_msg) ->
2651 setSrcSpan (instSpan inst) $
2652 -- the location of the first one will do for the err message
2653 addErrTcM (tidy_env, msg $$ mono_msg)
2655 dicts = map fst pairs
2656 msg = sep [text "Ambiguous type variable" <> plural tvs <+>
2657 pprQuotedList tvs <+> in_msg,
2658 nest 2 (pprDictsInFull dicts)]
2659 in_msg = text "in the constraint" <> plural dicts <> colon
2660 report [] = panic "addTopAmbigErrs"
2663 mkMonomorphismMsg :: TidyEnv -> [TcTyVar] -> TcM (TidyEnv, Message)
2664 -- There's an error with these Insts; if they have free type variables
2665 -- it's probably caused by the monomorphism restriction.
2666 -- Try to identify the offending variable
2667 -- ASSUMPTION: the Insts are fully zonked
2668 mkMonomorphismMsg tidy_env inst_tvs
2669 = do { dflags <- getDOpts
2670 ; (tidy_env, docs) <- findGlobals (mkVarSet inst_tvs) tidy_env
2671 ; return (tidy_env, mk_msg dflags docs) }
2673 mk_msg _ _ | any isRuntimeUnk inst_tvs
2674 = vcat [ptext SLIT("Cannot resolve unknown runtime types:") <+>
2675 (pprWithCommas ppr inst_tvs),
2676 ptext SLIT("Use :print or :force to determine these types")]
2677 mk_msg _ [] = ptext SLIT("Probable fix: add a type signature that fixes these type variable(s)")
2678 -- This happens in things like
2679 -- f x = show (read "foo")
2680 -- where monomorphism doesn't play any role
2682 = vcat [ptext SLIT("Possible cause: the monomorphism restriction applied to the following:"),
2684 monomorphism_fix dflags]
2686 isRuntimeUnk :: TcTyVar -> Bool
2687 isRuntimeUnk x | SkolemTv RuntimeUnkSkol <- tcTyVarDetails x = True
2690 monomorphism_fix :: DynFlags -> SDoc
2691 monomorphism_fix dflags
2692 = ptext SLIT("Probable fix:") <+> vcat
2693 [ptext SLIT("give these definition(s) an explicit type signature"),
2694 if dopt Opt_MonomorphismRestriction dflags
2695 then ptext SLIT("or use -fno-monomorphism-restriction")
2696 else empty] -- Only suggest adding "-fno-monomorphism-restriction"
2697 -- if it is not already set!
2699 warnDefault ups default_ty
2700 = doptM Opt_WarnTypeDefaults `thenM` \ warn_flag ->
2701 addInstCtxt (instLoc (head (dicts))) (warnTc warn_flag warn_msg)
2703 dicts = [d | (d,_,_) <- ups]
2706 (_, tidy_dicts) = tidyInsts dicts
2707 warn_msg = vcat [ptext SLIT("Defaulting the following constraint(s) to type") <+>
2708 quotes (ppr default_ty),
2709 pprDictsInFull tidy_dicts]
2711 reduceDepthErr n stack
2712 = vcat [ptext SLIT("Context reduction stack overflow; size =") <+> int n,
2713 ptext SLIT("Use -fcontext-stack=N to increase stack size to N"),
2714 nest 4 (pprStack stack)]
2716 pprStack stack = vcat (map pprInstInFull stack)