Fix Trac #2045: use big-tuple machiney for implication constraints
[ghc-hetmet.git] / compiler / typecheck / TcSimplify.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 %
5
6 TcSimplify
7
8 \begin{code}
9 {-# OPTIONS -w #-}
10 -- The above warning supression flag is a temporary kludge.
11 -- While working on this module you are encouraged to remove it and fix
12 -- any warnings in the module. See
13 --     http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
14 -- for details
15
16 module TcSimplify (
17         tcSimplifyInfer, tcSimplifyInferCheck,
18         tcSimplifyCheck, tcSimplifyRestricted,
19         tcSimplifyRuleLhs, tcSimplifyIPs, 
20         tcSimplifySuperClasses,
21         tcSimplifyTop, tcSimplifyInteractive,
22         tcSimplifyBracket, tcSimplifyCheckPat,
23
24         tcSimplifyDeriv, tcSimplifyDefault,
25         bindInstsOfLocalFuns, 
26
27         misMatchMsg
28     ) where
29
30 #include "HsVersions.h"
31
32 import {-# SOURCE #-} TcUnify( unifyType )
33 import HsSyn
34
35 import TcRnMonad
36 import TcHsSyn  ( hsLPatType )
37 import Inst
38 import TcEnv
39 import InstEnv
40 import TcType
41 import TcMType
42 import TcIface
43 import TcTyFuns
44 import DsUtils  -- Big-tuple functions
45 import TypeRep
46 import Var
47 import Name
48 import NameSet
49 import Class
50 import FunDeps
51 import PrelInfo
52 import PrelNames
53 import Type
54 import TysWiredIn
55 import ErrUtils
56 import BasicTypes
57 import VarSet
58 import VarEnv
59 import Module
60 import FiniteMap
61 import Bag
62 import Outputable
63 import Maybes
64 import ListSetOps
65 import Util
66 import UniqSet
67 import SrcLoc
68 import DynFlags
69 import FastString
70
71 import Control.Monad
72 import Data.List
73 \end{code}
74
75
76 %************************************************************************
77 %*                                                                      *
78 \subsection{NOTES}
79 %*                                                                      *
80 %************************************************************************
81
82         --------------------------------------
83         Notes on functional dependencies (a bug)
84         --------------------------------------
85
86 Consider this:
87
88         class C a b | a -> b
89         class D a b | a -> b
90
91         instance D a b => C a b -- Undecidable 
92                                 -- (Not sure if it's crucial to this eg)
93         f :: C a b => a -> Bool
94         f _ = True
95         
96         g :: C a b => a -> Bool
97         g = f
98
99 Here f typechecks, but g does not!!  Reason: before doing improvement,
100 we reduce the (C a b1) constraint from the call of f to (D a b1).
101
102 Here is a more complicated example:
103
104 | > class Foo a b | a->b
105 | >
106 | > class Bar a b | a->b
107 | >
108 | > data Obj = Obj
109 | >
110 | > instance Bar Obj Obj
111 | >
112 | > instance (Bar a b) => Foo a b
113 | >
114 | > foo:: (Foo a b) => a -> String
115 | > foo _ = "works"
116 | >
117 | > runFoo:: (forall a b. (Foo a b) => a -> w) -> w
118 | > runFoo f = f Obj
119
120 | *Test> runFoo foo
121
122 | <interactive>:1:
123 |     Could not deduce (Bar a b) from the context (Foo a b)
124 |       arising from use of `foo' at <interactive>:1
125 |     Probable fix:
126 |         Add (Bar a b) to the expected type of an expression
127 |     In the first argument of `runFoo', namely `foo'
128 |     In the definition of `it': it = runFoo foo
129
130 | Why all of the sudden does GHC need the constraint Bar a b? The
131 | function foo didn't ask for that... 
132
133 The trouble is that to type (runFoo foo), GHC has to solve the problem:
134
135         Given constraint        Foo a b
136         Solve constraint        Foo a b'
137
138 Notice that b and b' aren't the same.  To solve this, just do
139 improvement and then they are the same.  But GHC currently does
140         simplify constraints
141         apply improvement
142         and loop
143
144 That is usually fine, but it isn't here, because it sees that Foo a b is
145 not the same as Foo a b', and so instead applies the instance decl for
146 instance Bar a b => Foo a b.  And that's where the Bar constraint comes
147 from.
148
149 The Right Thing is to improve whenever the constraint set changes at
150 all.  Not hard in principle, but it'll take a bit of fiddling to do.  
151
152 Note [Choosing which variables to quantify]
153 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
154 Suppose we are about to do a generalisation step.  We have in our hand
155
156         G       the environment
157         T       the type of the RHS
158         C       the constraints from that RHS
159
160 The game is to figure out
161
162         Q       the set of type variables over which to quantify
163         Ct      the constraints we will *not* quantify over
164         Cq      the constraints we will quantify over
165
166 So we're going to infer the type
167
168         forall Q. Cq => T
169
170 and float the constraints Ct further outwards.
171
172 Here are the things that *must* be true:
173
174  (A)    Q intersect fv(G) = EMPTY                       limits how big Q can be
175  (B)    Q superset fv(Cq union T) \ oclose(fv(G),C)     limits how small Q can be
176
177  (A) says we can't quantify over a variable that's free in the environment. 
178  (B) says we must quantify over all the truly free variables in T, else 
179      we won't get a sufficiently general type.  
180
181 We do not *need* to quantify over any variable that is fixed by the
182 free vars of the environment G.
183
184         BETWEEN THESE TWO BOUNDS, ANY Q WILL DO!
185
186 Example:        class H x y | x->y where ...
187
188         fv(G) = {a}     C = {H a b, H c d}
189                         T = c -> b
190
191         (A)  Q intersect {a} is empty
192         (B)  Q superset {a,b,c,d} \ oclose({a}, C) = {a,b,c,d} \ {a,b} = {c,d}
193
194         So Q can be {c,d}, {b,c,d}
195
196 In particular, it's perfectly OK to quantify over more type variables
197 than strictly necessary; there is no need to quantify over 'b', since
198 it is determined by 'a' which is free in the envt, but it's perfectly
199 OK to do so.  However we must not quantify over 'a' itself.
200
201 Other things being equal, however, we'd like to quantify over as few
202 variables as possible: smaller types, fewer type applications, more
203 constraints can get into Ct instead of Cq.  Here's a good way to
204 choose Q:
205
206         Q = grow( fv(T), C ) \ oclose( fv(G), C )
207
208 That is, quantify over all variable that that MIGHT be fixed by the
209 call site (which influences T), but which aren't DEFINITELY fixed by
210 G.  This choice definitely quantifies over enough type variables,
211 albeit perhaps too many.
212
213 Why grow( fv(T), C ) rather than fv(T)?  Consider
214
215         class H x y | x->y where ...
216
217         T = c->c
218         C = (H c d)
219
220   If we used fv(T) = {c} we'd get the type
221
222         forall c. H c d => c -> b
223
224   And then if the fn was called at several different c's, each of
225   which fixed d differently, we'd get a unification error, because
226   d isn't quantified.  Solution: quantify d.  So we must quantify
227   everything that might be influenced by c.
228
229 Why not oclose( fv(T), C )?  Because we might not be able to see
230 all the functional dependencies yet:
231
232         class H x y | x->y where ...
233         instance H x y => Eq (T x y) where ...
234
235         T = c->c
236         C = (Eq (T c d))
237
238 Now oclose(fv(T),C) = {c}, because the functional dependency isn't
239 apparent yet, and that's wrong.  We must really quantify over d too.
240
241 There really isn't any point in quantifying over any more than
242 grow( fv(T), C ), because the call sites can't possibly influence
243 any other type variables.
244
245
246
247 -------------------------------------
248         Note [Ambiguity]
249 -------------------------------------
250
251 It's very hard to be certain when a type is ambiguous.  Consider
252
253         class K x
254         class H x y | x -> y
255         instance H x y => K (x,y)
256
257 Is this type ambiguous?
258         forall a b. (K (a,b), Eq b) => a -> a
259
260 Looks like it!  But if we simplify (K (a,b)) we get (H a b) and
261 now we see that a fixes b.  So we can't tell about ambiguity for sure
262 without doing a full simplification.  And even that isn't possible if
263 the context has some free vars that may get unified.  Urgle!
264
265 Here's another example: is this ambiguous?
266         forall a b. Eq (T b) => a -> a
267 Not if there's an insance decl (with no context)
268         instance Eq (T b) where ...
269
270 You may say of this example that we should use the instance decl right
271 away, but you can't always do that:
272
273         class J a b where ...
274         instance J Int b where ...
275
276         f :: forall a b. J a b => a -> a
277
278 (Notice: no functional dependency in J's class decl.)
279 Here f's type is perfectly fine, provided f is only called at Int.
280 It's premature to complain when meeting f's signature, or even
281 when inferring a type for f.
282
283
284
285 However, we don't *need* to report ambiguity right away.  It'll always
286 show up at the call site.... and eventually at main, which needs special
287 treatment.  Nevertheless, reporting ambiguity promptly is an excellent thing.
288
289 So here's the plan.  We WARN about probable ambiguity if
290
291         fv(Cq) is not a subset of  oclose(fv(T) union fv(G), C)
292
293 (all tested before quantification).
294 That is, all the type variables in Cq must be fixed by the the variables
295 in the environment, or by the variables in the type.
296
297 Notice that we union before calling oclose.  Here's an example:
298
299         class J a b c | a b -> c
300         fv(G) = {a}
301
302 Is this ambiguous?
303         forall b c. (J a b c) => b -> b
304
305 Only if we union {a} from G with {b} from T before using oclose,
306 do we see that c is fixed.
307
308 It's a bit vague exactly which C we should use for this oclose call.  If we
309 don't fix enough variables we might complain when we shouldn't (see
310 the above nasty example).  Nothing will be perfect.  That's why we can
311 only issue a warning.
312
313
314 Can we ever be *certain* about ambiguity?  Yes: if there's a constraint
315
316         c in C such that fv(c) intersect (fv(G) union fv(T)) = EMPTY
317
318 then c is a "bubble"; there's no way it can ever improve, and it's
319 certainly ambiguous.  UNLESS it is a constant (sigh).  And what about
320 the nasty example?
321
322         class K x
323         class H x y | x -> y
324         instance H x y => K (x,y)
325
326 Is this type ambiguous?
327         forall a b. (K (a,b), Eq b) => a -> a
328
329 Urk.  The (Eq b) looks "definitely ambiguous" but it isn't.  What we are after
330 is a "bubble" that's a set of constraints
331
332         Cq = Ca union Cq'  st  fv(Ca) intersect (fv(Cq') union fv(T) union fv(G)) = EMPTY
333
334 Hence another idea.  To decide Q start with fv(T) and grow it
335 by transitive closure in Cq (no functional dependencies involved).
336 Now partition Cq using Q, leaving the definitely-ambiguous and probably-ok.
337 The definitely-ambiguous can then float out, and get smashed at top level
338 (which squashes out the constants, like Eq (T a) above)
339
340
341         --------------------------------------
342                 Notes on principal types
343         --------------------------------------
344
345     class C a where
346       op :: a -> a
347
348     f x = let g y = op (y::Int) in True
349
350 Here the principal type of f is (forall a. a->a)
351 but we'll produce the non-principal type
352     f :: forall a. C Int => a -> a
353
354
355         --------------------------------------
356         The need for forall's in constraints
357         --------------------------------------
358
359 [Exchange on Haskell Cafe 5/6 Dec 2000]
360
361   class C t where op :: t -> Bool
362   instance C [t] where op x = True
363
364   p y = (let f :: c -> Bool; f x = op (y >> return x) in f, y ++ [])
365   q y = (y ++ [], let f :: c -> Bool; f x = op (y >> return x) in f)
366
367 The definitions of p and q differ only in the order of the components in
368 the pair on their right-hand sides.  And yet:
369
370   ghc and "Typing Haskell in Haskell" reject p, but accept q;
371   Hugs rejects q, but accepts p;
372   hbc rejects both p and q;
373   nhc98 ... (Malcolm, can you fill in the blank for us!).
374
375 The type signature for f forces context reduction to take place, and
376 the results of this depend on whether or not the type of y is known,
377 which in turn depends on which component of the pair the type checker
378 analyzes first.  
379
380 Solution: if y::m a, float out the constraints
381         Monad m, forall c. C (m c)
382 When m is later unified with [], we can solve both constraints.
383
384
385         --------------------------------------
386                 Notes on implicit parameters
387         --------------------------------------
388
389 Note [Inheriting implicit parameters]
390 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
391 Consider this:
392
393         f x = (x::Int) + ?y
394
395 where f is *not* a top-level binding.
396 From the RHS of f we'll get the constraint (?y::Int).
397 There are two types we might infer for f:
398
399         f :: Int -> Int
400
401 (so we get ?y from the context of f's definition), or
402
403         f :: (?y::Int) => Int -> Int
404
405 At first you might think the first was better, becuase then
406 ?y behaves like a free variable of the definition, rather than
407 having to be passed at each call site.  But of course, the WHOLE
408 IDEA is that ?y should be passed at each call site (that's what
409 dynamic binding means) so we'd better infer the second.
410
411 BOTTOM LINE: when *inferring types* you *must* quantify 
412 over implicit parameters. See the predicate isFreeWhenInferring.
413
414
415 Note [Implicit parameters and ambiguity] 
416 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
417 Only a *class* predicate can give rise to ambiguity
418 An *implicit parameter* cannot.  For example:
419         foo :: (?x :: [a]) => Int
420         foo = length ?x
421 is fine.  The call site will suppply a particular 'x'
422
423 Furthermore, the type variables fixed by an implicit parameter
424 propagate to the others.  E.g.
425         foo :: (Show a, ?x::[a]) => Int
426         foo = show (?x++?x)
427 The type of foo looks ambiguous.  But it isn't, because at a call site
428 we might have
429         let ?x = 5::Int in foo
430 and all is well.  In effect, implicit parameters are, well, parameters,
431 so we can take their type variables into account as part of the
432 "tau-tvs" stuff.  This is done in the function 'FunDeps.grow'.
433
434
435 Question 2: type signatures
436 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
437 BUT WATCH OUT: When you supply a type signature, we can't force you
438 to quantify over implicit parameters.  For example:
439
440         (?x + 1) :: Int
441
442 This is perfectly reasonable.  We do not want to insist on
443
444         (?x + 1) :: (?x::Int => Int)
445
446 That would be silly.  Here, the definition site *is* the occurrence site,
447 so the above strictures don't apply.  Hence the difference between
448 tcSimplifyCheck (which *does* allow implicit paramters to be inherited)
449 and tcSimplifyCheckBind (which does not).
450
451 What about when you supply a type signature for a binding?
452 Is it legal to give the following explicit, user type 
453 signature to f, thus:
454
455         f :: Int -> Int
456         f x = (x::Int) + ?y
457
458 At first sight this seems reasonable, but it has the nasty property
459 that adding a type signature changes the dynamic semantics.
460 Consider this:
461
462         (let f x = (x::Int) + ?y
463          in (f 3, f 3 with ?y=5))  with ?y = 6
464
465                 returns (3+6, 3+5)
466 vs
467         (let f :: Int -> Int
468              f x = x + ?y
469          in (f 3, f 3 with ?y=5))  with ?y = 6
470
471                 returns (3+6, 3+6)
472
473 Indeed, simply inlining f (at the Haskell source level) would change the
474 dynamic semantics.
475
476 Nevertheless, as Launchbury says (email Oct 01) we can't really give the
477 semantics for a Haskell program without knowing its typing, so if you 
478 change the typing you may change the semantics.
479
480 To make things consistent in all cases where we are *checking* against
481 a supplied signature (as opposed to inferring a type), we adopt the
482 rule: 
483
484         a signature does not need to quantify over implicit params.
485
486 [This represents a (rather marginal) change of policy since GHC 5.02,
487 which *required* an explicit signature to quantify over all implicit
488 params for the reasons mentioned above.]
489
490 But that raises a new question.  Consider 
491
492         Given (signature)       ?x::Int
493         Wanted (inferred)       ?x::Int, ?y::Bool
494
495 Clearly we want to discharge the ?x and float the ?y out.  But
496 what is the criterion that distinguishes them?  Clearly it isn't
497 what free type variables they have.  The Right Thing seems to be
498 to float a constraint that
499         neither mentions any of the quantified type variables
500         nor any of the quantified implicit parameters
501
502 See the predicate isFreeWhenChecking.
503
504
505 Question 3: monomorphism
506 ~~~~~~~~~~~~~~~~~~~~~~~~
507 There's a nasty corner case when the monomorphism restriction bites:
508
509         z = (x::Int) + ?y
510
511 The argument above suggests that we *must* generalise
512 over the ?y parameter, to get
513         z :: (?y::Int) => Int,
514 but the monomorphism restriction says that we *must not*, giving
515         z :: Int.
516 Why does the momomorphism restriction say this?  Because if you have
517
518         let z = x + ?y in z+z
519
520 you might not expect the addition to be done twice --- but it will if
521 we follow the argument of Question 2 and generalise over ?y.
522
523
524 Question 4: top level
525 ~~~~~~~~~~~~~~~~~~~~~
526 At the top level, monomorhism makes no sense at all.
527
528     module Main where
529         main = let ?x = 5 in print foo
530
531         foo = woggle 3
532
533         woggle :: (?x :: Int) => Int -> Int
534         woggle y = ?x + y
535
536 We definitely don't want (foo :: Int) with a top-level implicit parameter
537 (?x::Int) becuase there is no way to bind it.  
538
539
540 Possible choices
541 ~~~~~~~~~~~~~~~~
542 (A) Always generalise over implicit parameters
543     Bindings that fall under the monomorphism restriction can't
544         be generalised
545
546     Consequences:
547         * Inlining remains valid
548         * No unexpected loss of sharing
549         * But simple bindings like
550                 z = ?y + 1
551           will be rejected, unless you add an explicit type signature
552           (to avoid the monomorphism restriction)
553                 z :: (?y::Int) => Int
554                 z = ?y + 1
555           This seems unacceptable
556
557 (B) Monomorphism restriction "wins"
558     Bindings that fall under the monomorphism restriction can't
559         be generalised
560     Always generalise over implicit parameters *except* for bindings
561         that fall under the monomorphism restriction
562
563     Consequences
564         * Inlining isn't valid in general
565         * No unexpected loss of sharing
566         * Simple bindings like
567                 z = ?y + 1
568           accepted (get value of ?y from binding site)
569
570 (C) Always generalise over implicit parameters
571     Bindings that fall under the monomorphism restriction can't
572         be generalised, EXCEPT for implicit parameters
573     Consequences
574         * Inlining remains valid
575         * Unexpected loss of sharing (from the extra generalisation)
576         * Simple bindings like
577                 z = ?y + 1
578           accepted (get value of ?y from occurrence sites)
579
580
581 Discussion
582 ~~~~~~~~~~
583 None of these choices seems very satisfactory.  But at least we should
584 decide which we want to do.
585
586 It's really not clear what is the Right Thing To Do.  If you see
587
588         z = (x::Int) + ?y
589
590 would you expect the value of ?y to be got from the *occurrence sites*
591 of 'z', or from the valuue of ?y at the *definition* of 'z'?  In the
592 case of function definitions, the answer is clearly the former, but
593 less so in the case of non-fucntion definitions.   On the other hand,
594 if we say that we get the value of ?y from the definition site of 'z',
595 then inlining 'z' might change the semantics of the program.
596
597 Choice (C) really says "the monomorphism restriction doesn't apply
598 to implicit parameters".  Which is fine, but remember that every
599 innocent binding 'x = ...' that mentions an implicit parameter in
600 the RHS becomes a *function* of that parameter, called at each
601 use of 'x'.  Now, the chances are that there are no intervening 'with'
602 clauses that bind ?y, so a decent compiler should common up all
603 those function calls.  So I think I strongly favour (C).  Indeed,
604 one could make a similar argument for abolishing the monomorphism
605 restriction altogether.
606
607 BOTTOM LINE: we choose (B) at present.  See tcSimplifyRestricted
608
609
610
611 %************************************************************************
612 %*                                                                      *
613 \subsection{tcSimplifyInfer}
614 %*                                                                      *
615 %************************************************************************
616
617 tcSimplify is called when we *inferring* a type.  Here's the overall game plan:
618
619     1. Compute Q = grow( fvs(T), C )
620
621     2. Partition C based on Q into Ct and Cq.  Notice that ambiguous
622        predicates will end up in Ct; we deal with them at the top level
623
624     3. Try improvement, using functional dependencies
625
626     4. If Step 3 did any unification, repeat from step 1
627        (Unification can change the result of 'grow'.)
628
629 Note: we don't reduce dictionaries in step 2.  For example, if we have
630 Eq (a,b), we don't simplify to (Eq a, Eq b).  So Q won't be different
631 after step 2.  However note that we may therefore quantify over more
632 type variables than we absolutely have to.
633
634 For the guts, we need a loop, that alternates context reduction and
635 improvement with unification.  E.g. Suppose we have
636
637         class C x y | x->y where ...
638
639 and tcSimplify is called with:
640         (C Int a, C Int b)
641 Then improvement unifies a with b, giving
642         (C Int a, C Int a)
643
644 If we need to unify anything, we rattle round the whole thing all over
645 again.
646
647
648 \begin{code}
649 tcSimplifyInfer
650         :: SDoc
651         -> TcTyVarSet           -- fv(T); type vars
652         -> [Inst]               -- Wanted
653         -> TcM ([TcTyVar],      -- Tyvars to quantify (zonked and quantified)
654                 [Inst],         -- Dict Ids that must be bound here (zonked)
655                 TcDictBinds)    -- Bindings
656         -- Any free (escaping) Insts are tossed into the environment
657 \end{code}
658
659
660 \begin{code}
661 tcSimplifyInfer doc tau_tvs wanted
662   = do  { tau_tvs1 <- zonkTcTyVarsAndFV (varSetElems tau_tvs)
663         ; wanted'  <- mapM zonkInst wanted      -- Zonk before deciding quantified tyvars
664         ; gbl_tvs  <- tcGetGlobalTyVars
665         ; let preds1   = fdPredsOfInsts wanted'
666               gbl_tvs1 = oclose preds1 gbl_tvs
667               qtvs     = grow preds1 tau_tvs1 `minusVarSet` gbl_tvs1
668                         -- See Note [Choosing which variables to quantify]
669
670                 -- To maximise sharing, remove from consideration any 
671                 -- constraints that don't mention qtvs at all
672         ; let (free, bound) = partition (isFreeWhenInferring qtvs) wanted'
673         ; extendLIEs free
674
675                 -- To make types simple, reduce as much as possible
676         ; traceTc (text "infer" <+> (ppr preds1 $$ ppr (grow preds1 tau_tvs1) $$ ppr gbl_tvs $$ 
677                    ppr gbl_tvs1 $$ ppr free $$ ppr bound))
678         ; (irreds1, binds1) <- tryHardCheckLoop doc bound
679
680                 -- Note [Inference and implication constraints]
681         ; let want_dict d = tyVarsOfInst d `intersectsVarSet` qtvs
682         ; (irreds2, binds2) <- approximateImplications doc want_dict irreds1
683
684                 -- Now work out all over again which type variables to quantify,
685                 -- exactly in the same way as before, but starting from irreds2.  Why?
686                 -- a) By now improvment may have taken place, and we must *not*
687                 --    quantify over any variable free in the environment
688                 --    tc137 (function h inside g) is an example
689                 --
690                 -- b) Do not quantify over constraints that *now* do not
691                 --    mention quantified type variables, because they are
692                 --    simply ambiguous (or might be bound further out).  Example:
693                 --      f :: Eq b => a -> (a, b)
694                 --      g x = fst (f x)
695                 --    From the RHS of g we get the MethodInst f77 :: alpha -> (alpha, beta)
696                 --    We decide to quantify over 'alpha' alone, but free1 does not include f77
697                 --    because f77 mentions 'alpha'.  Then reducing leaves only the (ambiguous)
698                 --    constraint (Eq beta), which we dump back into the free set
699                 --    See test tcfail181
700                 --
701                 -- c) irreds may contain type variables not previously mentioned,
702                 --    e.g.  instance D a x => Foo [a] 
703                 --          wanteds = Foo [a]
704                 --       Then after simplifying we'll get (D a x), and x is fresh
705                 --       We must quantify over x else it'll be totally unbound
706         ; tau_tvs2 <- zonkTcTyVarsAndFV (varSetElems tau_tvs1)
707         ; gbl_tvs2 <- zonkTcTyVarsAndFV (varSetElems gbl_tvs1)
708                 -- Note that we start from gbl_tvs1
709                 -- We use tcGetGlobalTyVars, then oclose wrt preds2, because
710                 -- we've already put some of the original preds1 into frees
711                 -- E.g.         wanteds = C a b   (where a->b)
712                 --              gbl_tvs = {a}
713                 --              tau_tvs = {b}
714                 -- Then b is fixed by gbl_tvs, so (C a b) will be in free, and
715                 -- irreds2 will be empty.  But we don't want to generalise over b!
716         ; let preds2 = fdPredsOfInsts irreds2   -- irreds2 is zonked
717               qtvs   = grow preds2 tau_tvs2 `minusVarSet` oclose preds2 gbl_tvs2
718         ; let (free, irreds3) = partition (isFreeWhenInferring qtvs) irreds2
719         ; extendLIEs free
720
721                 -- Turn the quantified meta-type variables into real type variables
722         ; qtvs2 <- zonkQuantifiedTyVars (varSetElems qtvs)
723
724                 -- We can't abstract over any remaining unsolved 
725                 -- implications so instead just float them outwards. Ugh.
726         ; let (q_dicts0, implics) = partition isAbstractableInst irreds3
727         ; loc <- getInstLoc (ImplicOrigin doc)
728         ; implic_bind <- bindIrreds loc qtvs2 q_dicts0 implics
729
730                 -- Prepare equality instances for quantification
731         ; let (q_eqs0,q_dicts) = partition isEqInst q_dicts0
732         ; q_eqs <- mapM finalizeEqInst q_eqs0
733
734         ; return (qtvs2, q_eqs ++ q_dicts, binds1 `unionBags` binds2 `unionBags` implic_bind) }
735         -- NB: when we are done, we might have some bindings, but
736         -- the final qtvs might be empty.  See Note [NO TYVARS] below.
737
738 approximateImplications :: SDoc -> (Inst -> Bool) -> [Inst] -> TcM ([Inst], TcDictBinds)
739 -- Note [Inference and implication constraints]
740 -- Given a bunch of Dict and ImplicInsts, try to approximate the implications by
741 --      - fetching any dicts inside them that are free
742 --      - using those dicts as cruder constraints, to solve the implications
743 --      - returning the extra ones too
744
745 approximateImplications doc want_dict irreds
746   | null extra_dicts 
747   = return (irreds, emptyBag)
748   | otherwise
749   = do  { extra_dicts' <- mapM cloneDict extra_dicts
750         ; tryHardCheckLoop doc (extra_dicts' ++ irreds) }
751                 -- By adding extra_dicts', we make them 
752                 -- available to solve the implication constraints
753   where 
754     extra_dicts = get_dicts (filter isImplicInst irreds)
755
756     get_dicts :: [Inst] -> [Inst]       -- Returns only Dicts
757         -- Find the wanted constraints in implication constraints that satisfy
758         -- want_dict, and are not bound by forall's in the constraint itself
759     get_dicts ds = concatMap get_dict ds
760
761     get_dict d@(Dict {}) | want_dict d = [d]
762                          | otherwise   = []
763     get_dict (ImplicInst {tci_tyvars = tvs, tci_wanted = wanteds})
764         = [ d | let tv_set = mkVarSet tvs
765               , d <- get_dicts wanteds 
766               , not (tyVarsOfInst d `intersectsVarSet` tv_set)]
767     get_dict i@(EqInst {}) | want_dict i = [i]
768                            | otherwise   = [] 
769     get_dict other = pprPanic "approximateImplications" (ppr other)
770 \end{code}
771
772 Note [Inference and implication constraints]
773 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
774 Suppose we have a wanted implication constraint (perhaps arising from
775 a nested pattern match) like
776         C a => D [a]
777 and we are now trying to quantify over 'a' when inferring the type for
778 a function.  In principle it's possible that there might be an instance
779         instance (C a, E a) => D [a]
780 so the context (E a) would suffice.  The Right Thing is to abstract over
781 the implication constraint, but we don't do that (a) because it'll be
782 surprising to programmers and (b) because we don't have the machinery to deal
783 with 'given' implications.
784
785 So our best approximation is to make (D [a]) part of the inferred
786 context, so we can use that to discharge the implication. Hence
787 the strange function get_dicts in approximateImplications.
788
789 The common cases are more clear-cut, when we have things like
790         forall a. C a => C b
791 Here, abstracting over (C b) is not an approximation at all -- but see
792 Note [Freeness and implications].
793  
794 See Trac #1430 and test tc228.
795
796
797 \begin{code}
798 -----------------------------------------------------------
799 -- tcSimplifyInferCheck is used when we know the constraints we are to simplify
800 -- against, but we don't know the type variables over which we are going to quantify.
801 -- This happens when we have a type signature for a mutually recursive group
802 tcSimplifyInferCheck
803          :: InstLoc
804          -> TcTyVarSet          -- fv(T)
805          -> [Inst]              -- Given
806          -> [Inst]              -- Wanted
807          -> TcM ([TyVar],       -- Fully zonked, and quantified
808                  TcDictBinds)   -- Bindings
809
810 tcSimplifyInferCheck loc tau_tvs givens wanteds
811   = do  { traceTc (text "tcSimplifyInferCheck <-" <+> ppr wanteds)
812         ; (irreds, binds) <- gentleCheckLoop loc givens wanteds
813
814         -- Figure out which type variables to quantify over
815         -- You might think it should just be the signature tyvars,
816         -- but in bizarre cases you can get extra ones
817         --      f :: forall a. Num a => a -> a
818         --      f x = fst (g (x, head [])) + 1
819         --      g a b = (b,a)
820         -- Here we infer g :: forall a b. a -> b -> (b,a)
821         -- We don't want g to be monomorphic in b just because
822         -- f isn't quantified over b.
823         ; let all_tvs = varSetElems (tau_tvs `unionVarSet` tyVarsOfInsts givens)
824         ; all_tvs <- zonkTcTyVarsAndFV all_tvs
825         ; gbl_tvs <- tcGetGlobalTyVars
826         ; let qtvs = varSetElems (all_tvs `minusVarSet` gbl_tvs)
827                 -- We could close gbl_tvs, but its not necessary for
828                 -- soundness, and it'll only affect which tyvars, not which
829                 -- dictionaries, we quantify over
830
831         ; qtvs' <- zonkQuantifiedTyVars qtvs
832
833                 -- Now we are back to normal (c.f. tcSimplCheck)
834         ; implic_bind <- bindIrreds loc qtvs' givens irreds
835
836         ; traceTc (text "tcSimplifyInferCheck ->" <+> ppr (implic_bind))
837         ; return (qtvs', binds `unionBags` implic_bind) }
838 \end{code}
839
840 Note [Squashing methods]
841 ~~~~~~~~~~~~~~~~~~~~~~~~~
842 Be careful if you want to float methods more:
843         truncate :: forall a. RealFrac a => forall b. Integral b => a -> b
844 From an application (truncate f i) we get
845         t1 = truncate at f
846         t2 = t1 at i
847 If we have also have a second occurrence of truncate, we get
848         t3 = truncate at f
849         t4 = t3 at i
850 When simplifying with i,f free, we might still notice that
851 t1=t3; but alas, the binding for t2 (which mentions t1)
852 may continue to float out!
853
854
855 Note [NO TYVARS]
856 ~~~~~~~~~~~~~~~~~
857         class Y a b | a -> b where
858             y :: a -> X b
859         
860         instance Y [[a]] a where
861             y ((x:_):_) = X x
862         
863         k :: X a -> X a -> X a
864
865         g :: Num a => [X a] -> [X a]
866         g xs = h xs
867             where
868             h ys = ys ++ map (k (y [[0]])) xs
869
870 The excitement comes when simplifying the bindings for h.  Initially
871 try to simplify {y @ [[t1]] t2, 0 @ t1}, with initial qtvs = {t2}.
872 From this we get t1:=:t2, but also various bindings.  We can't forget
873 the bindings (because of [LOOP]), but in fact t1 is what g is
874 polymorphic in.  
875
876 The net effect of [NO TYVARS] 
877
878 \begin{code}
879 isFreeWhenInferring :: TyVarSet -> Inst -> Bool
880 isFreeWhenInferring qtvs inst
881   =  isFreeWrtTyVars qtvs inst  -- Constrains no quantified vars
882   && isInheritableInst inst     -- and no implicit parameter involved
883                                 --   see Note [Inheriting implicit parameters]
884
885 {-      No longer used (with implication constraints)
886 isFreeWhenChecking :: TyVarSet  -- Quantified tyvars
887                    -> NameSet   -- Quantified implicit parameters
888                    -> Inst -> Bool
889 isFreeWhenChecking qtvs ips inst
890   =  isFreeWrtTyVars qtvs inst
891   && isFreeWrtIPs    ips inst
892 -}
893
894 isFreeWrtTyVars qtvs inst = tyVarsOfInst inst `disjointVarSet` qtvs
895 isFreeWrtIPs     ips inst = not (any (`elemNameSet` ips) (ipNamesOfInst inst))
896 \end{code}
897
898
899 %************************************************************************
900 %*                                                                      *
901 \subsection{tcSimplifyCheck}
902 %*                                                                      *
903 %************************************************************************
904
905 @tcSimplifyCheck@ is used when we know exactly the set of variables
906 we are going to quantify over.  For example, a class or instance declaration.
907
908 \begin{code}
909 -----------------------------------------------------------
910 -- tcSimplifyCheck is used when checking expression type signatures,
911 -- class decls, instance decls etc.
912 tcSimplifyCheck :: InstLoc
913                 -> [TcTyVar]            -- Quantify over these
914                 -> [Inst]               -- Given
915                 -> [Inst]               -- Wanted
916                 -> TcM TcDictBinds      -- Bindings
917 tcSimplifyCheck loc qtvs givens wanteds 
918   = ASSERT( all isTcTyVar qtvs && all isSkolemTyVar qtvs )
919     do  { traceTc (text "tcSimplifyCheck")
920         ; (irreds, binds) <- gentleCheckLoop loc givens wanteds
921         ; implic_bind <- bindIrreds loc qtvs givens irreds
922         ; return (binds `unionBags` implic_bind) }
923
924 -----------------------------------------------------------
925 -- tcSimplifyCheckPat is used for existential pattern match
926 tcSimplifyCheckPat :: InstLoc
927                    -> [TcTyVar]         -- Quantify over these
928                    -> [Inst]            -- Given
929                    -> [Inst]            -- Wanted
930                    -> TcM TcDictBinds   -- Bindings
931 tcSimplifyCheckPat loc qtvs givens wanteds
932   = ASSERT( all isTcTyVar qtvs && all isSkolemTyVar qtvs )
933     do  { traceTc (text "tcSimplifyCheckPat")
934         ; (irreds, binds) <- gentleCheckLoop loc givens wanteds
935         ; implic_bind <- bindIrredsR loc qtvs givens irreds
936         ; return (binds `unionBags` implic_bind) }
937
938 -----------------------------------------------------------
939 bindIrreds :: InstLoc -> [TcTyVar]
940            -> [Inst] -> [Inst]
941            -> TcM TcDictBinds
942 bindIrreds loc qtvs givens irreds 
943   = bindIrredsR loc qtvs givens irreds
944
945 bindIrredsR :: InstLoc -> [TcTyVar] -> [Inst] -> [Inst] -> TcM TcDictBinds      
946 -- Make a binding that binds 'irreds', by generating an implication
947 -- constraint for them, *and* throwing the constraint into the LIE
948 bindIrredsR loc qtvs givens irreds
949   | null irreds
950   = return emptyBag
951   | otherwise
952   = do  { let givens' = filter isAbstractableInst givens
953                 -- The givens can (redundantly) include methods
954                 -- We want to retain both EqInsts and Dicts
955                 -- There should be no implicadtion constraints
956                 -- See Note [Pruning the givens in an implication constraint]
957
958            -- If there are no 'givens', then it's safe to 
959            -- partition the 'wanteds' by their qtvs, thereby trimming irreds
960            -- See Note [Freeness and implications]
961         ; irreds' <- if null givens'
962                      then do
963                         { let qtv_set = mkVarSet qtvs
964                               (frees, real_irreds) = partition (isFreeWrtTyVars qtv_set) irreds
965                         ; extendLIEs frees
966                         ; return real_irreds }
967                      else return irreds
968         
969         ; (implics, bind) <- makeImplicationBind loc qtvs givens' irreds'
970                         -- This call does the real work
971                         -- If irreds' is empty, it does something sensible
972         ; extendLIEs implics
973         ; return bind } 
974
975
976 makeImplicationBind :: InstLoc -> [TcTyVar]
977                     -> [Inst] -> [Inst]
978                     -> TcM ([Inst], TcDictBinds)
979 -- Make a binding that binds 'irreds', by generating an implication
980 -- constraint for them, *and* throwing the constraint into the LIE
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. {reft} givens => (ir1, .., irn)
985 -- qtvs includes coercion variables
986 --
987 -- This binding must line up the 'rhs' in reduceImplication
988 makeImplicationBind loc all_tvs
989                     givens      -- Guaranteed all Dicts
990                                 -- or EqInsts
991                     irreds
992  | null irreds                  -- If there are no irreds, we are done
993  = return ([], emptyBag)
994  | otherwise                    -- Otherwise we must generate a binding
995  = do   { uniq <- newUnique 
996         ; span <- getSrcSpanM
997         ; let (eq_givens, dict_givens) = partition isEqInst givens
998               eq_tyvar_cos = mkTyVarTys (varSetElems $ tyVarsOfTypes $ map eqInstType eq_givens)
999                 -- Urgh! See line 2187 or thereabouts.  I believe that all these
1000                 -- 'givens' must be a simple CoVar.  This MUST be cleaned up.
1001
1002         ; let 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                                          tci_wanted = irreds, tci_loc = loc }
1007         ; let   -- only create binder for dict_irreds
1008               (eq_irreds, dict_irreds) = partition isEqInst irreds
1009               n_dict_irreds = length dict_irreds
1010               dict_irred_ids = map instToId dict_irreds
1011               lpat = mkBigLHsPatTup (map (L span . VarPat) dict_irred_ids)
1012               rhs = L span (mkHsWrap co (HsVar (instToId implic_inst)))
1013               co  = mkWpApps (map instToId dict_givens)
1014                     <.> mkWpTyApps eq_tyvar_cos
1015                     <.> mkWpTyApps (mkTyVarTys all_tvs)
1016               bind | [dict_irred_id] <- dict_irred_ids  = VarBind dict_irred_id rhs
1017                    | otherwise        = PatBind { pat_lhs = lpat, 
1018                                                   pat_rhs = unguardedGRHSs rhs, 
1019                                                   pat_rhs_ty = hsLPatType lpat,
1020                                                   bind_fvs = placeHolderNames }
1021         ; traceTc $ text "makeImplicationBind" <+> ppr implic_inst
1022         ; return ([implic_inst], unitBag (L span bind)) 
1023         }
1024
1025 -----------------------------------------------------------
1026 tryHardCheckLoop :: SDoc
1027              -> [Inst]                  -- Wanted
1028              -> TcM ([Inst], TcDictBinds)
1029
1030 tryHardCheckLoop doc wanteds
1031   = do { (irreds,binds) <- checkLoop (mkRedEnv doc try_me []) wanteds
1032        ; return (irreds,binds)
1033        }
1034   where
1035     try_me inst = ReduceMe AddSCs
1036         -- Here's the try-hard bit
1037
1038 -----------------------------------------------------------
1039 gentleCheckLoop :: InstLoc
1040                -> [Inst]                -- Given
1041                -> [Inst]                -- Wanted
1042                -> TcM ([Inst], TcDictBinds)
1043
1044 gentleCheckLoop inst_loc givens wanteds
1045   = do { (irreds,binds) <- checkLoop env wanteds
1046        ; return (irreds,binds)
1047        }
1048   where
1049     env = mkRedEnv (pprInstLoc inst_loc) try_me givens
1050
1051     try_me inst | isMethodOrLit inst = ReduceMe AddSCs
1052                 | otherwise          = Stop
1053         -- When checking against a given signature 
1054         -- we MUST be very gentle: Note [Check gently]
1055
1056 gentleInferLoop :: SDoc -> [Inst]
1057                 -> TcM ([Inst], TcDictBinds)
1058 gentleInferLoop doc wanteds
1059   = do  { (irreds, binds) <- checkLoop env wanteds
1060         ; return (irreds, binds) }
1061   where
1062     env = mkRedEnv doc try_me []
1063     try_me inst | isMethodOrLit inst = ReduceMe AddSCs
1064                 | otherwise          = Stop
1065 \end{code}
1066
1067 Note [Check gently]
1068 ~~~~~~~~~~~~~~~~~~~~
1069 We have to very careful about not simplifying too vigorously
1070 Example:  
1071   data T a where
1072     MkT :: a -> T [a]
1073
1074   f :: Show b => T b -> b
1075   f (MkT x) = show [x]
1076
1077 Inside the pattern match, which binds (a:*, x:a), we know that
1078         b ~ [a]
1079 Hence we have a dictionary for Show [a] available; and indeed we 
1080 need it.  We are going to build an implication contraint
1081         forall a. (b~[a]) => Show [a]
1082 Later, we will solve this constraint using the knowledge (Show b)
1083         
1084 But we MUST NOT reduce (Show [a]) to (Show a), else the whole
1085 thing becomes insoluble.  So we simplify gently (get rid of literals
1086 and methods only, plus common up equal things), deferring the real
1087 work until top level, when we solve the implication constraint
1088 with tryHardCheckLooop.
1089
1090
1091 \begin{code}
1092 -----------------------------------------------------------
1093 checkLoop :: RedEnv
1094           -> [Inst]                     -- Wanted
1095           -> TcM ([Inst], TcDictBinds) 
1096 -- Precondition: givens are completely rigid
1097 -- Postcondition: returned Insts are zonked
1098
1099 checkLoop env wanteds
1100   = go env wanteds (return ())
1101   where go env wanteds elim_skolems
1102           = do  {  -- We do need to zonk the givens; cf Note [Zonking RedEnv]
1103                 ; env'     <- zonkRedEnv env
1104                 ; wanteds' <- zonkInsts  wanteds
1105         
1106                 ; (improved, binds, irreds, elim_more_skolems)
1107                     <- reduceContext env' wanteds'
1108                 ; let elim_skolems' = elim_skolems >> elim_more_skolems
1109
1110                 ; if not improved then
1111                     elim_skolems' >> return (irreds, binds)
1112                   else do
1113         
1114                 -- If improvement did some unification, we go round again.
1115                 -- We start again with irreds, not wanteds
1116                 -- Using an instance decl might have introduced a fresh type
1117                 -- variable which might have been unified, so we'd get an 
1118                 -- infinite loop if we started again with wanteds!  
1119                 -- See Note [LOOP]
1120                 { (irreds1, binds1) <- go env' irreds elim_skolems'
1121                 ; return (irreds1, binds `unionBags` binds1) } }
1122 \end{code}
1123
1124 Note [Zonking RedEnv]
1125 ~~~~~~~~~~~~~~~~~~~~~
1126 It might appear as if the givens in RedEnv are always rigid, but that is not
1127 necessarily the case for programs involving higher-rank types that have class
1128 contexts constraining the higher-rank variables.  An example from tc237 in the
1129 testsuite is
1130
1131   class Modular s a | s -> a
1132
1133   wim ::  forall a w. Integral a 
1134                         => a -> (forall s. Modular s a => M s w) -> w
1135   wim i k = error "urk"
1136
1137   test5  ::  (Modular s a, Integral a) => M s a
1138   test5  =   error "urk"
1139
1140   test4   =   wim 4 test4'
1141
1142 Notice how the variable 'a' of (Modular s a) in the rank-2 type of wim is
1143 quantified further outside.  When type checking test4, we have to check
1144 whether the signature of test5 is an instance of 
1145
1146   (forall s. Modular s a => M s w)
1147
1148 Consequently, we will get (Modular s t_a), where t_a is a TauTv into the
1149 givens. 
1150
1151 Given the FD of Modular in this example, class improvement will instantiate
1152 t_a to 'a', where 'a' is the skolem from test5's signatures (due to the
1153 Modular s a predicate in that signature).  If we don't zonk (Modular s t_a) in
1154 the givens, we will get into a loop as improveOne uses the unification engine
1155 Unify.tcUnifyTys, which doesn't know about mutable type variables.
1156
1157
1158 Note [LOOP]
1159 ~~~~~~~~~~~
1160         class If b t e r | b t e -> r
1161         instance If T t e t
1162         instance If F t e e
1163         class Lte a b c | a b -> c where lte :: a -> b -> c
1164         instance Lte Z b T
1165         instance (Lte a b l,If l b a c) => Max a b c
1166
1167 Wanted: Max Z (S x) y
1168
1169 Then we'll reduce using the Max instance to:
1170         (Lte Z (S x) l, If l (S x) Z y)
1171 and improve by binding l->T, after which we can do some reduction
1172 on both the Lte and If constraints.  What we *can't* do is start again
1173 with (Max Z (S x) y)!
1174
1175
1176
1177 %************************************************************************
1178 %*                                                                      *
1179                 tcSimplifySuperClasses
1180 %*                                                                      *
1181 %************************************************************************
1182
1183 Note [SUPERCLASS-LOOP 1]
1184 ~~~~~~~~~~~~~~~~~~~~~~~~
1185 We have to be very, very careful when generating superclasses, lest we
1186 accidentally build a loop. Here's an example:
1187
1188   class S a
1189
1190   class S a => C a where { opc :: a -> a }
1191   class S b => D b where { opd :: b -> b }
1192   
1193   instance C Int where
1194      opc = opd
1195   
1196   instance D Int where
1197      opd = opc
1198
1199 From (instance C Int) we get the constraint set {ds1:S Int, dd:D Int}
1200 Simplifying, we may well get:
1201         $dfCInt = :C ds1 (opd dd)
1202         dd  = $dfDInt
1203         ds1 = $p1 dd
1204 Notice that we spot that we can extract ds1 from dd.  
1205
1206 Alas!  Alack! We can do the same for (instance D Int):
1207
1208         $dfDInt = :D ds2 (opc dc)
1209         dc  = $dfCInt
1210         ds2 = $p1 dc
1211
1212 And now we've defined the superclass in terms of itself.
1213
1214 Solution: never generate a superclass selectors at all when
1215 satisfying the superclass context of an instance declaration.
1216
1217 Two more nasty cases are in
1218         tcrun021
1219         tcrun033
1220
1221 \begin{code}
1222 tcSimplifySuperClasses 
1223         :: InstLoc 
1224         -> [Inst]       -- Given 
1225         -> [Inst]       -- Wanted
1226         -> TcM TcDictBinds
1227 tcSimplifySuperClasses loc givens sc_wanteds
1228   = do  { traceTc (text "tcSimplifySuperClasses")
1229         ; (irreds,binds1) <- checkLoop env sc_wanteds
1230         ; let (tidy_env, tidy_irreds) = tidyInsts irreds
1231         ; reportNoInstances tidy_env (Just (loc, givens)) tidy_irreds
1232         ; return binds1 }
1233   where
1234     env = mkRedEnv (pprInstLoc loc) try_me givens
1235     try_me inst = ReduceMe NoSCs
1236         -- Like tryHardCheckLoop, but with NoSCs
1237 \end{code}
1238
1239
1240 %************************************************************************
1241 %*                                                                      *
1242 \subsection{tcSimplifyRestricted}
1243 %*                                                                      *
1244 %************************************************************************
1245
1246 tcSimplifyRestricted infers which type variables to quantify for a 
1247 group of restricted bindings.  This isn't trivial.
1248
1249 Eg1:    id = \x -> x
1250         We want to quantify over a to get id :: forall a. a->a
1251         
1252 Eg2:    eq = (==)
1253         We do not want to quantify over a, because there's an Eq a 
1254         constraint, so we get eq :: a->a->Bool  (notice no forall)
1255
1256 So, assume:
1257         RHS has type 'tau', whose free tyvars are tau_tvs
1258         RHS has constraints 'wanteds'
1259
1260 Plan A (simple)
1261   Quantify over (tau_tvs \ ftvs(wanteds))
1262   This is bad. The constraints may contain (Monad (ST s))
1263   where we have         instance Monad (ST s) where...
1264   so there's no need to be monomorphic in s!
1265
1266   Also the constraint might be a method constraint,
1267   whose type mentions a perfectly innocent tyvar:
1268           op :: Num a => a -> b -> a
1269   Here, b is unconstrained.  A good example would be
1270         foo = op (3::Int)
1271   We want to infer the polymorphic type
1272         foo :: forall b. b -> b
1273
1274
1275 Plan B (cunning, used for a long time up to and including GHC 6.2)
1276   Step 1: Simplify the constraints as much as possible (to deal 
1277   with Plan A's problem).  Then set
1278         qtvs = tau_tvs \ ftvs( simplify( wanteds ) )
1279
1280   Step 2: Now simplify again, treating the constraint as 'free' if 
1281   it does not mention qtvs, and trying to reduce it otherwise.
1282   The reasons for this is to maximise sharing.
1283
1284   This fails for a very subtle reason.  Suppose that in the Step 2
1285   a constraint (Foo (Succ Zero) (Succ Zero) b) gets thrown upstairs as 'free'.
1286   In the Step 1 this constraint might have been simplified, perhaps to
1287   (Foo Zero Zero b), AND THEN THAT MIGHT BE IMPROVED, to bind 'b' to 'T'.
1288   This won't happen in Step 2... but that in turn might prevent some other
1289   constraint (Baz [a] b) being simplified (e.g. via instance Baz [a] T where {..}) 
1290   and that in turn breaks the invariant that no constraints are quantified over.
1291
1292   Test typecheck/should_compile/tc177 (which failed in GHC 6.2) demonstrates
1293   the problem.
1294
1295
1296 Plan C (brutal)
1297   Step 1: Simplify the constraints as much as possible (to deal 
1298   with Plan A's problem).  Then set
1299         qtvs = tau_tvs \ ftvs( simplify( wanteds ) )
1300   Return the bindings from Step 1.
1301   
1302
1303 A note about Plan C (arising from "bug" reported by George Russel March 2004)
1304 Consider this:
1305
1306       instance (HasBinary ty IO) => HasCodedValue ty
1307
1308       foo :: HasCodedValue a => String -> IO a
1309
1310       doDecodeIO :: HasCodedValue a => () -> () -> IO a
1311       doDecodeIO codedValue view  
1312         = let { act = foo "foo" } in  act
1313
1314 You might think this should work becuase the call to foo gives rise to a constraint
1315 (HasCodedValue t), which can be satisfied by the type sig for doDecodeIO.  But the
1316 restricted binding act = ... calls tcSimplifyRestricted, and PlanC simplifies the
1317 constraint using the (rather bogus) instance declaration, and now we are stuffed.
1318
1319 I claim this is not really a bug -- but it bit Sergey as well as George.  So here's
1320 plan D
1321
1322
1323 Plan D (a variant of plan B)
1324   Step 1: Simplify the constraints as much as possible (to deal 
1325   with Plan A's problem), BUT DO NO IMPROVEMENT.  Then set
1326         qtvs = tau_tvs \ ftvs( simplify( wanteds ) )
1327
1328   Step 2: Now simplify again, treating the constraint as 'free' if 
1329   it does not mention qtvs, and trying to reduce it otherwise.
1330
1331   The point here is that it's generally OK to have too few qtvs; that is,
1332   to make the thing more monomorphic than it could be.  We don't want to
1333   do that in the common cases, but in wierd cases it's ok: the programmer
1334   can always add a signature.  
1335
1336   Too few qtvs => too many wanteds, which is what happens if you do less
1337   improvement.
1338
1339
1340 \begin{code}
1341 tcSimplifyRestricted    -- Used for restricted binding groups
1342                         -- i.e. ones subject to the monomorphism restriction
1343         :: SDoc
1344         -> TopLevelFlag
1345         -> [Name]               -- Things bound in this group
1346         -> TcTyVarSet           -- Free in the type of the RHSs
1347         -> [Inst]               -- Free in the RHSs
1348         -> TcM ([TyVar],        -- Tyvars to quantify (zonked and quantified)
1349                 TcDictBinds)    -- Bindings
1350         -- tcSimpifyRestricted returns no constraints to
1351         -- quantify over; by definition there are none.
1352         -- They are all thrown back in the LIE
1353
1354 tcSimplifyRestricted doc top_lvl bndrs tau_tvs wanteds
1355         -- Zonk everything in sight
1356   = do  { traceTc (text "tcSimplifyRestricted")
1357         ; wanteds' <- zonkInsts wanteds
1358
1359         -- 'ReduceMe': Reduce as far as we can.  Don't stop at
1360         -- dicts; the idea is to get rid of as many type
1361         -- variables as possible, and we don't want to stop
1362         -- at (say) Monad (ST s), because that reduces
1363         -- immediately, with no constraint on s.
1364         --
1365         -- BUT do no improvement!  See Plan D above
1366         -- HOWEVER, some unification may take place, if we instantiate
1367         --          a method Inst with an equality constraint
1368         ; let env = mkNoImproveRedEnv doc (\i -> ReduceMe AddSCs)
1369         ; (_imp, _binds, constrained_dicts, elim_skolems) 
1370             <- reduceContext env wanteds'
1371         ; elim_skolems
1372
1373         -- Next, figure out the tyvars we will quantify over
1374         ; tau_tvs' <- zonkTcTyVarsAndFV (varSetElems tau_tvs)
1375         ; gbl_tvs' <- tcGetGlobalTyVars
1376         ; constrained_dicts' <- zonkInsts constrained_dicts
1377
1378         ; let qtvs1 = tau_tvs' `minusVarSet` oclose (fdPredsOfInsts constrained_dicts) gbl_tvs'
1379                                 -- As in tcSimplifyInfer
1380
1381                 -- Do not quantify over constrained type variables:
1382                 -- this is the monomorphism restriction
1383               constrained_tvs' = tyVarsOfInsts constrained_dicts'
1384               qtvs = qtvs1 `minusVarSet` constrained_tvs'
1385               pp_bndrs = pprWithCommas (quotes . ppr) bndrs
1386
1387         -- Warn in the mono
1388         ; warn_mono <- doptM Opt_WarnMonomorphism
1389         ; warnTc (warn_mono && (constrained_tvs' `intersectsVarSet` qtvs1))
1390                  (vcat[ ptext (sLit "the Monomorphism Restriction applies to the binding")
1391                                 <> plural bndrs <+> ptext (sLit "for") <+> pp_bndrs,
1392                         ptext (sLit "Consider giving a type signature for") <+> pp_bndrs])
1393
1394         ; traceTc (text "tcSimplifyRestricted" <+> vcat [
1395                 pprInsts wanteds, pprInsts constrained_dicts',
1396                 ppr _binds,
1397                 ppr constrained_tvs', ppr tau_tvs', ppr qtvs ])
1398
1399         -- The first step may have squashed more methods than
1400         -- necessary, so try again, this time more gently, knowing the exact
1401         -- set of type variables to quantify over.
1402         --
1403         -- We quantify only over constraints that are captured by qtvs;
1404         -- these will just be a subset of non-dicts.  This in contrast
1405         -- to normal inference (using isFreeWhenInferring) in which we quantify over
1406         -- all *non-inheritable* constraints too.  This implements choice
1407         -- (B) under "implicit parameter and monomorphism" above.
1408         --
1409         -- Remember that we may need to do *some* simplification, to
1410         -- (for example) squash {Monad (ST s)} into {}.  It's not enough
1411         -- just to float all constraints
1412         --
1413         -- At top level, we *do* squash methods becuase we want to 
1414         -- expose implicit parameters to the test that follows
1415         ; let is_nested_group = isNotTopLevel top_lvl
1416               try_me inst | isFreeWrtTyVars qtvs inst,
1417                            (is_nested_group || isDict inst) = Stop
1418                           | otherwise            = ReduceMe AddSCs
1419               env = mkNoImproveRedEnv doc try_me
1420         ; (_imp, binds, irreds, elim_skolems) <- reduceContext env wanteds'
1421         ; elim_skolems
1422
1423         -- See "Notes on implicit parameters, Question 4: top level"
1424         ; ASSERT( all (isFreeWrtTyVars qtvs) irreds )   -- None should be captured
1425           if is_nested_group then
1426                 extendLIEs irreds
1427           else do { let (bad_ips, non_ips) = partition isIPDict irreds
1428                   ; addTopIPErrs bndrs bad_ips
1429                   ; extendLIEs non_ips }
1430
1431         ; qtvs' <- zonkQuantifiedTyVars (varSetElems qtvs)
1432         ; return (qtvs', binds) }
1433 \end{code}
1434
1435
1436 %************************************************************************
1437 %*                                                                      *
1438                 tcSimplifyRuleLhs
1439 %*                                                                      *
1440 %************************************************************************
1441
1442 On the LHS of transformation rules we only simplify methods and constants,
1443 getting dictionaries.  We want to keep all of them unsimplified, to serve
1444 as the available stuff for the RHS of the rule.
1445
1446 Example.  Consider the following left-hand side of a rule
1447         
1448         f (x == y) (y > z) = ...
1449
1450 If we typecheck this expression we get constraints
1451
1452         d1 :: Ord a, d2 :: Eq a
1453
1454 We do NOT want to "simplify" to the LHS
1455
1456         forall x::a, y::a, z::a, d1::Ord a.
1457           f ((==) (eqFromOrd d1) x y) ((>) d1 y z) = ...
1458
1459 Instead we want 
1460
1461         forall x::a, y::a, z::a, d1::Ord a, d2::Eq a.
1462           f ((==) d2 x y) ((>) d1 y z) = ...
1463
1464 Here is another example:
1465
1466         fromIntegral :: (Integral a, Num b) => a -> b
1467         {-# RULES "foo"  fromIntegral = id :: Int -> Int #-}
1468
1469 In the rule, a=b=Int, and Num Int is a superclass of Integral Int. But
1470 we *dont* want to get
1471
1472         forall dIntegralInt.
1473            fromIntegral Int Int dIntegralInt (scsel dIntegralInt) = id Int
1474
1475 because the scsel will mess up RULE matching.  Instead we want
1476
1477         forall dIntegralInt, dNumInt.
1478           fromIntegral Int Int dIntegralInt dNumInt = id Int
1479
1480 Even if we have 
1481
1482         g (x == y) (y == z) = ..
1483
1484 where the two dictionaries are *identical*, we do NOT WANT
1485
1486         forall x::a, y::a, z::a, d1::Eq a
1487           f ((==) d1 x y) ((>) d1 y z) = ...
1488
1489 because that will only match if the dict args are (visibly) equal.
1490 Instead we want to quantify over the dictionaries separately.
1491
1492 In short, tcSimplifyRuleLhs must *only* squash LitInst and MethInts, leaving
1493 all dicts unchanged, with absolutely no sharing.  It's simpler to do this
1494 from scratch, rather than further parameterise simpleReduceLoop etc
1495
1496 \begin{code}
1497 tcSimplifyRuleLhs :: [Inst] -> TcM ([Inst], TcDictBinds)
1498 tcSimplifyRuleLhs wanteds
1499   = go [] emptyBag wanteds
1500   where
1501     go dicts binds []
1502         = return (dicts, binds)
1503     go dicts binds (w:ws)
1504         | isDict w
1505         = go (w:dicts) binds ws
1506         | otherwise
1507         = do { w' <- zonkInst w  -- So that (3::Int) does not generate a call
1508                                  -- to fromInteger; this looks fragile to me
1509              ; lookup_result <- lookupSimpleInst w'
1510              ; case lookup_result of
1511                  GenInst ws' rhs -> 
1512                    go dicts (addInstToDictBind binds w rhs) (ws' ++ ws)
1513                  NoInstance      -> pprPanic "tcSimplifyRuleLhs" (ppr w)
1514           }
1515 \end{code}
1516
1517 tcSimplifyBracket is used when simplifying the constraints arising from
1518 a Template Haskell bracket [| ... |].  We want to check that there aren't
1519 any constraints that can't be satisfied (e.g. Show Foo, where Foo has no
1520 Show instance), but we aren't otherwise interested in the results.
1521 Nor do we care about ambiguous dictionaries etc.  We will type check
1522 this bracket again at its usage site.
1523
1524 \begin{code}
1525 tcSimplifyBracket :: [Inst] -> TcM ()
1526 tcSimplifyBracket wanteds
1527   = do  { tryHardCheckLoop doc wanteds
1528         ; return () }
1529   where
1530     doc = text "tcSimplifyBracket"
1531 \end{code}
1532
1533
1534 %************************************************************************
1535 %*                                                                      *
1536 \subsection{Filtering at a dynamic binding}
1537 %*                                                                      *
1538 %************************************************************************
1539
1540 When we have
1541         let ?x = R in B
1542
1543 we must discharge all the ?x constraints from B.  We also do an improvement
1544 step; if we have ?x::t1 and ?x::t2 we must unify t1, t2.
1545
1546 Actually, the constraints from B might improve the types in ?x. For example
1547
1548         f :: (?x::Int) => Char -> Char
1549         let ?x = 3 in f 'c'
1550
1551 then the constraint (?x::Int) arising from the call to f will
1552 force the binding for ?x to be of type Int.
1553
1554 \begin{code}
1555 tcSimplifyIPs :: [Inst]         -- The implicit parameters bound here
1556               -> [Inst]         -- Wanted
1557               -> TcM TcDictBinds
1558         -- We need a loop so that we do improvement, and then
1559         -- (next time round) generate a binding to connect the two
1560         --      let ?x = e in ?x
1561         -- Here the two ?x's have different types, and improvement 
1562         -- makes them the same.
1563
1564 tcSimplifyIPs given_ips wanteds
1565   = do  { wanteds'   <- zonkInsts wanteds
1566         ; given_ips' <- zonkInsts given_ips
1567                 -- Unusually for checking, we *must* zonk the given_ips
1568
1569         ; let env = mkRedEnv doc try_me given_ips'
1570         ; (improved, binds, irreds, elim_skolems) <- reduceContext env wanteds'
1571         ; elim_skolems
1572
1573         ; if not improved then 
1574                 ASSERT( all is_free irreds )
1575                 do { extendLIEs irreds
1576                    ; return binds }
1577           else
1578                 tcSimplifyIPs given_ips wanteds }
1579   where
1580     doc    = text "tcSimplifyIPs" <+> ppr given_ips
1581     ip_set = mkNameSet (ipNamesOfInsts given_ips)
1582     is_free inst = isFreeWrtIPs ip_set inst
1583
1584         -- Simplify any methods that mention the implicit parameter
1585     try_me inst | is_free inst = Stop
1586                 | otherwise    = ReduceMe NoSCs
1587 \end{code}
1588
1589
1590 %************************************************************************
1591 %*                                                                      *
1592 \subsection[binds-for-local-funs]{@bindInstsOfLocalFuns@}
1593 %*                                                                      *
1594 %************************************************************************
1595
1596 When doing a binding group, we may have @Insts@ of local functions.
1597 For example, we might have...
1598 \begin{verbatim}
1599 let f x = x + 1     -- orig local function (overloaded)
1600     f.1 = f Int     -- two instances of f
1601     f.2 = f Float
1602  in
1603     (f.1 5, f.2 6.7)
1604 \end{verbatim}
1605 The point is: we must drop the bindings for @f.1@ and @f.2@ here,
1606 where @f@ is in scope; those @Insts@ must certainly not be passed
1607 upwards towards the top-level.  If the @Insts@ were binding-ified up
1608 there, they would have unresolvable references to @f@.
1609
1610 We pass in an @init_lie@ of @Insts@ and a list of locally-bound @Ids@.
1611 For each method @Inst@ in the @init_lie@ that mentions one of the
1612 @Ids@, we create a binding.  We return the remaining @Insts@ (in an
1613 @LIE@), as well as the @HsBinds@ generated.
1614
1615 \begin{code}
1616 bindInstsOfLocalFuns :: [Inst] -> [TcId] -> TcM TcDictBinds
1617 -- Simlifies only MethodInsts, and generate only bindings of form 
1618 --      fm = f tys dicts
1619 -- We're careful not to even generate bindings of the form
1620 --      d1 = d2
1621 -- You'd think that'd be fine, but it interacts with what is
1622 -- arguably a bug in Match.tidyEqnInfo (see notes there)
1623
1624 bindInstsOfLocalFuns wanteds local_ids
1625   | null overloaded_ids = do
1626         -- Common case
1627     extendLIEs wanteds
1628     return emptyLHsBinds
1629
1630   | otherwise
1631   = do  { (irreds, binds) <- gentleInferLoop doc for_me
1632         ; extendLIEs not_for_me 
1633         ; extendLIEs irreds
1634         ; return binds }
1635   where
1636     doc              = text "bindInsts" <+> ppr local_ids
1637     overloaded_ids   = filter is_overloaded local_ids
1638     is_overloaded id = isOverloadedTy (idType id)
1639     (for_me, not_for_me) = partition (isMethodFor overloaded_set) wanteds
1640
1641     overloaded_set = mkVarSet overloaded_ids    -- There can occasionally be a lot of them
1642                                                 -- so it's worth building a set, so that
1643                                                 -- lookup (in isMethodFor) is faster
1644 \end{code}
1645
1646
1647 %************************************************************************
1648 %*                                                                      *
1649 \subsection{Data types for the reduction mechanism}
1650 %*                                                                      *
1651 %************************************************************************
1652
1653 The main control over context reduction is here
1654
1655 \begin{code}
1656 data RedEnv 
1657   = RedEnv { red_doc    :: SDoc                 -- The context
1658            , red_try_me :: Inst -> WhatToDo
1659            , red_improve :: Bool                -- True <=> do improvement
1660            , red_givens :: [Inst]               -- All guaranteed rigid
1661                                                 -- Always dicts
1662                                                 -- but see Note [Rigidity]
1663            , red_stack  :: (Int, [Inst])        -- Recursion stack (for err msg)
1664                                                 -- See Note [RedStack]
1665   }
1666
1667 -- Note [Rigidity]
1668 -- The red_givens are rigid so far as cmpInst is concerned.
1669 -- There is one case where they are not totally rigid, namely in tcSimplifyIPs
1670 --      let ?x = e in ...
1671 -- Here, the given is (?x::a), where 'a' is not necy a rigid type
1672 -- But that doesn't affect the comparison, which is based only on mame.
1673
1674 -- Note [RedStack]
1675 -- The red_stack pair (n,insts) pair is just used for error reporting.
1676 -- 'n' is always the depth of the stack.
1677 -- The 'insts' is the stack of Insts being reduced: to produce X
1678 -- I had to produce Y, to produce Y I had to produce Z, and so on.
1679
1680
1681 mkRedEnv :: SDoc -> (Inst -> WhatToDo) -> [Inst] -> RedEnv
1682 mkRedEnv doc try_me givens
1683   = RedEnv { red_doc = doc, red_try_me = try_me,
1684              red_givens = givens, 
1685              red_stack = (0,[]),
1686              red_improve = True }       
1687
1688 mkNoImproveRedEnv :: SDoc -> (Inst -> WhatToDo) -> RedEnv
1689 -- Do not do improvement; no givens
1690 mkNoImproveRedEnv doc try_me
1691   = RedEnv { red_doc = doc, red_try_me = try_me,
1692              red_givens = [], 
1693              red_stack = (0,[]),
1694              red_improve = True }       
1695
1696 data WhatToDo
1697  = ReduceMe WantSCs     -- Try to reduce this
1698                         -- If there's no instance, add the inst to the 
1699                         -- irreductible ones, but don't produce an error 
1700                         -- message of any kind.
1701                         -- It might be quite legitimate such as (Eq a)!
1702
1703  | Stop         -- Return as irreducible unless it can
1704                         -- be reduced to a constant in one step
1705                         -- Do not add superclasses; see 
1706
1707 data WantSCs = NoSCs | AddSCs   -- Tells whether we should add the superclasses
1708                                 -- of a predicate when adding it to the avails
1709         -- The reason for this flag is entirely the super-class loop problem
1710         -- Note [SUPER-CLASS LOOP 1]
1711
1712 zonkRedEnv :: RedEnv -> TcM RedEnv
1713 zonkRedEnv env
1714   = do { givens' <- mapM zonkInst (red_givens env)
1715        ; return $ env {red_givens = givens'}
1716        }
1717 \end{code}
1718
1719
1720 %************************************************************************
1721 %*                                                                      *
1722 \subsection[reduce]{@reduce@}
1723 %*                                                                      *
1724 %************************************************************************
1725
1726 Note [Ancestor Equalities]
1727 ~~~~~~~~~~~~~~~~~~~~~~~~~~
1728 During context reduction, we add to the wanted equalities also those
1729 equalities that (transitively) occur in superclass contexts of wanted
1730 class constraints.  Consider the following code
1731
1732   class a ~ Int => C a
1733   instance C Int
1734
1735 If (C a) is wanted, we want to add (a ~ Int), which will be discharged by
1736 substituting Int for a.  Hence, we ultimately want (C Int), which we
1737 discharge with the explicit instance.
1738
1739 \begin{code}
1740 reduceContext :: RedEnv
1741               -> [Inst]                 -- Wanted
1742               -> TcM (ImprovementDone,
1743                       TcDictBinds,      -- Dictionary bindings
1744                       [Inst],           -- Irreducible
1745                       TcM ())           -- Undo skolems from SkolemOccurs
1746
1747 reduceContext env wanteds
1748   = do  { traceTc (text "reduceContext" <+> (vcat [
1749              text "----------------------",
1750              red_doc env,
1751              text "given" <+> ppr (red_givens env),
1752              text "wanted" <+> ppr wanteds,
1753              text "----------------------"
1754              ]))
1755
1756
1757         ; let givens                       = red_givens env
1758               (given_eqs0, given_dicts0)   = partition isEqInst givens
1759               (wanted_eqs0, wanted_non_eqs) = partition isEqInst wanteds
1760               (wanted_implics0, wanted_dicts) = partition isImplicInst wanted_non_eqs
1761
1762           -- We want to add as wanted equalities those that (transitively) 
1763           -- occur in superclass contexts of wanted class constraints.
1764           -- See Note [Ancestor Equalities]
1765         ; ancestor_eqs <- ancestorEqualities wanted_dicts
1766         ; let wanted_eqs = wanted_eqs0 ++ ancestor_eqs
1767         ; traceTc $ text "reduceContext: ancestor eqs" <+> ppr ancestor_eqs
1768
1769           -- 1. Normalise the *given* *equality* constraints
1770         ; (given_eqs, eliminate_skolems) <- normaliseGivenEqs given_eqs0
1771
1772           -- 2. Normalise the *given* *dictionary* constraints
1773           --    wrt. the toplevel and given equations
1774         ; (given_dicts, given_binds) <- normaliseGivenDicts given_eqs
1775                                                             given_dicts0
1776
1777           -- 5. Build the Avail mapping from "given_dicts"
1778         ; (init_state, extra_givens) <- getLIE $ do 
1779                 { init_state <- foldlM addGiven emptyAvails given_dicts
1780                 ; return init_state
1781                 }
1782
1783         -- *** ToDo: what to do with the "extra_givens"?  For the
1784         -- moment I'm simply discarding them, which is probably wrong
1785
1786           -- 6. Solve the *wanted* *dictionary* constraints (not implications)
1787           --    This may expose some further equational constraints...
1788         ; (avails, extra_eqs) <- getLIE (reduceList env wanted_dicts init_state)
1789         ; (dict_binds, bound_dicts, dict_irreds) 
1790             <- extractResults avails wanted_dicts
1791         ; traceTc $ text "reduceContext extractresults" <+> vcat
1792                       [ppr avails, ppr wanted_dicts, ppr dict_binds]
1793
1794           -- Solve the wanted *implications*.  In doing so, we can provide
1795           -- as "given"   all the dicts that were originally given, 
1796           --              *or* for which we now have bindings, 
1797           --              *or* which are now irreds
1798         ; let implic_env = env { red_givens = givens ++ bound_dicts 
1799                                               ++ dict_irreds }
1800         ; (implic_binds_s, implic_irreds_s) 
1801             <- mapAndUnzipM (reduceImplication implic_env) wanted_implics0
1802         ; let implic_binds  = unionManyBags implic_binds_s
1803               implic_irreds = concat implic_irreds_s
1804
1805           -- Normalise the wanted equality constraints
1806         ; eq_irreds <- normaliseWantedEqs given_eqs (wanted_eqs ++ extra_eqs)
1807
1808           -- Normalise the wanted dictionaries
1809         ; let irreds = dict_irreds ++ implic_irreds
1810               eqs    = eq_irreds ++ given_eqs
1811         ; (norm_irreds, normalise_binds) <- normaliseWantedDicts eqs irreds
1812                 
1813           -- Figure out whether we should go round again.  We do so in either
1814           -- two cases:
1815           -- (1) If any of the mutable tyvars in givens or irreds has been
1816           --     filled in by improvement, there is merit in going around 
1817           --     again, because we may make further progress.
1818           -- (2) If we managed to normalise any dicts, there is merit in going
1819           --     around gain, because reduceList may be able to get further.
1820           -- 
1821           -- ToDo: We may have exposed new
1822           --       equality constraints and should probably go round again
1823           --       then as well.  But currently we are dropping them on the
1824           --       floor anyway.
1825
1826         ; let all_irreds = norm_irreds ++ eq_irreds
1827         ; improvedMetaTy <- anyM isFilledMetaTyVar $ varSetElems $
1828                             tyVarsOfInsts (givens ++ all_irreds)
1829         ; let improvedDicts = not $ isEmptyBag normalise_binds
1830               improved      = improvedMetaTy || improvedDicts
1831
1832         -- The old plan (fragile)
1833         -- improveed   = availsImproved avails 
1834         --               || (not $ isEmptyBag normalise_binds1)
1835         --               || (not $ isEmptyBag normalise_binds2)
1836         --               || (any isEqInst irreds)
1837
1838         ; traceTc (text "reduceContext end" <+> (vcat [
1839              text "----------------------",
1840              red_doc env,
1841              text "given" <+> ppr givens,
1842              text "given_eqs" <+> ppr given_eqs,
1843              text "wanted" <+> ppr wanteds,
1844              text "wanted_dicts" <+> ppr wanted_dicts,
1845              text "----",
1846              text "avails" <+> pprAvails avails,
1847              text "improved =" <+> ppr improved,
1848              text "(all) irreds = " <+> ppr all_irreds,
1849              text "dict-binds = " <+> ppr dict_binds,
1850              text "implic-binds = " <+> ppr implic_binds,
1851              text "----------------------"
1852              ]))
1853
1854         ; return (improved, 
1855                   given_binds `unionBags` normalise_binds
1856                               `unionBags` dict_binds 
1857                               `unionBags` implic_binds, 
1858                   all_irreds,
1859                   eliminate_skolems) 
1860         }
1861
1862 tcImproveOne :: Avails -> Inst -> TcM ImprovementDone
1863 tcImproveOne avails inst
1864   | not (isDict inst) = return False
1865   | otherwise
1866   = do  { inst_envs <- tcGetInstEnvs
1867         ; let eqns = improveOne (classInstances inst_envs)
1868                                 (dictPred inst, pprInstArising inst)
1869                                 [ (dictPred p, pprInstArising p)
1870                                 | p <- availsInsts avails, isDict p ]
1871                 -- Avails has all the superclasses etc (good)
1872                 -- It also has all the intermediates of the deduction (good)
1873                 -- It does not have duplicates (good)
1874                 -- NB that (?x::t1) and (?x::t2) will be held separately in avails
1875                 --    so that improve will see them separate
1876         ; traceTc (text "improveOne" <+> ppr inst)
1877         ; unifyEqns eqns }
1878
1879 unifyEqns :: [(Equation,(PredType,SDoc),(PredType,SDoc))] 
1880           -> TcM ImprovementDone
1881 unifyEqns [] = return False
1882 unifyEqns eqns
1883   = do  { traceTc (ptext (sLit "Improve:") <+> vcat (map pprEquationDoc eqns))
1884         ; mapM_ unify eqns
1885         ; return True }
1886   where
1887     unify ((qtvs, pairs), what1, what2)
1888          = addErrCtxtM (mkEqnMsg what1 what2) $ do
1889            (_, _, tenv) <- tcInstTyVars (varSetElems qtvs)
1890            mapM_ (unif_pr tenv) pairs
1891     unif_pr tenv (ty1,ty2) =  unifyType (substTy tenv ty1) (substTy tenv ty2)
1892
1893 pprEquationDoc (eqn, (p1,w1), (p2,w2)) = vcat [pprEquation eqn, nest 2 (ppr p1), nest 2 (ppr p2)]
1894
1895 mkEqnMsg (pred1,from1) (pred2,from2) tidy_env
1896   = do  { pred1' <- zonkTcPredType pred1; pred2' <- zonkTcPredType pred2
1897         ; let { pred1'' = tidyPred tidy_env pred1'; pred2'' = tidyPred tidy_env pred2' }
1898         ; let msg = vcat [ptext (sLit "When using functional dependencies to combine"),
1899                           nest 2 (sep [ppr pred1'' <> comma, nest 2 from1]), 
1900                           nest 2 (sep [ppr pred2'' <> comma, nest 2 from2])]
1901         ; return (tidy_env, msg) }
1902 \end{code}
1903
1904 The main context-reduction function is @reduce@.  Here's its game plan.
1905
1906 \begin{code}
1907 reduceList :: RedEnv -> [Inst] -> Avails -> TcM Avails
1908 reduceList env@(RedEnv {red_stack = (n,stk)}) wanteds state
1909   = do  { traceTc (text "reduceList " <+> (ppr wanteds $$ ppr state))
1910         ; dopts <- getDOpts
1911         ; when (debugIsOn && (n > 8)) $ do
1912                 debugDumpTcRn (hang (ptext (sLit "Interesting! Context reduction stack depth") <+> int n) 
1913                              2 (ifPprDebug (nest 2 (pprStack stk))))
1914         ; if n >= ctxtStkDepth dopts then
1915             failWithTc (reduceDepthErr n stk)
1916           else
1917             go wanteds state }
1918   where
1919     go []     state = return state
1920     go (w:ws) state = do { state' <- reduce (env {red_stack = (n+1, w:stk)}) w state
1921                          ; go ws state' }
1922
1923     -- Base case: we're done!
1924 reduce env wanted avails
1925     -- It's the same as an existing inst, or a superclass thereof
1926   | Just avail <- findAvail avails wanted
1927   = do { traceTc (text "reduce: found " <+> ppr wanted)
1928        ; return avails
1929        }
1930
1931   | otherwise
1932   = do  { traceTc (text "reduce" <+> ppr wanted $$ ppr avails)
1933         ; case red_try_me env wanted of {
1934             Stop -> try_simple (addIrred NoSCs);
1935                         -- See Note [No superclasses for Stop]
1936
1937             ReduceMe want_scs -> do     -- It should be reduced
1938                 { (avails, lookup_result) <- reduceInst env avails wanted
1939                 ; case lookup_result of
1940                     NoInstance -> addIrred want_scs avails wanted
1941                              -- Add it and its superclasses
1942                              
1943                     GenInst [] rhs -> addWanted want_scs avails wanted rhs []
1944
1945                     GenInst wanteds' rhs
1946                           -> do { avails1 <- addIrred NoSCs avails wanted
1947                                 ; avails2 <- reduceList env wanteds' avails1
1948                                 ; addWanted want_scs avails2 wanted rhs wanteds' } }
1949                 -- Temporarily do addIrred *before* the reduceList, 
1950                 -- which has the effect of adding the thing we are trying
1951                 -- to prove to the database before trying to prove the things it
1952                 -- needs.  See note [RECURSIVE DICTIONARIES]
1953                 -- NB: we must not do an addWanted before, because that adds the
1954                 --     superclasses too, and that can lead to a spurious loop; see
1955                 --     the examples in [SUPERCLASS-LOOP]
1956                 -- So we do an addIrred before, and then overwrite it afterwards with addWanted
1957     } }
1958   where
1959         -- First, see if the inst can be reduced to a constant in one step
1960         -- Works well for literals (1::Int) and constant dictionaries (d::Num Int)
1961         -- Don't bother for implication constraints, which take real work
1962     try_simple do_this_otherwise
1963       = do { res <- lookupSimpleInst wanted
1964            ; case res of
1965                 GenInst [] rhs -> addWanted AddSCs avails wanted rhs []
1966                 other          -> do_this_otherwise avails wanted }
1967 \end{code}
1968
1969
1970 Note [SUPERCLASS-LOOP 2]
1971 ~~~~~~~~~~~~~~~~~~~~~~~~
1972 But the above isn't enough.  Suppose we are *given* d1:Ord a,
1973 and want to deduce (d2:C [a]) where
1974
1975         class Ord a => C a where
1976         instance Ord [a] => C [a] where ...
1977
1978 Then we'll use the instance decl to deduce C [a] from Ord [a], and then add the
1979 superclasses of C [a] to avails.  But we must not overwrite the binding
1980 for Ord [a] (which is obtained from Ord a) with a superclass selection or we'll just
1981 build a loop! 
1982
1983 Here's another variant, immortalised in tcrun020
1984         class Monad m => C1 m
1985         class C1 m => C2 m x
1986         instance C2 Maybe Bool
1987 For the instance decl we need to build (C1 Maybe), and it's no good if
1988 we run around and add (C2 Maybe Bool) and its superclasses to the avails 
1989 before we search for C1 Maybe.
1990
1991 Here's another example 
1992         class Eq b => Foo a b
1993         instance Eq a => Foo [a] a
1994 If we are reducing
1995         (Foo [t] t)
1996
1997 we'll first deduce that it holds (via the instance decl).  We must not
1998 then overwrite the Eq t constraint with a superclass selection!
1999
2000 At first I had a gross hack, whereby I simply did not add superclass constraints
2001 in addWanted, though I did for addGiven and addIrred.  This was sub-optimal,
2002 becuase it lost legitimate superclass sharing, and it still didn't do the job:
2003 I found a very obscure program (now tcrun021) in which improvement meant the
2004 simplifier got two bites a the cherry... so something seemed to be an Stop
2005 first time, but reducible next time.
2006
2007 Now we implement the Right Solution, which is to check for loops directly 
2008 when adding superclasses.  It's a bit like the occurs check in unification.
2009
2010
2011 Note [RECURSIVE DICTIONARIES]
2012 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2013 Consider 
2014     data D r = ZeroD | SuccD (r (D r));
2015     
2016     instance (Eq (r (D r))) => Eq (D r) where
2017         ZeroD     == ZeroD     = True
2018         (SuccD a) == (SuccD b) = a == b
2019         _         == _         = False;
2020     
2021     equalDC :: D [] -> D [] -> Bool;
2022     equalDC = (==);
2023
2024 We need to prove (Eq (D [])).  Here's how we go:
2025
2026         d1 : Eq (D [])
2027
2028 by instance decl, holds if
2029         d2 : Eq [D []]
2030         where   d1 = dfEqD d2
2031
2032 by instance decl of Eq, holds if
2033         d3 : D []
2034         where   d2 = dfEqList d3
2035                 d1 = dfEqD d2
2036
2037 But now we can "tie the knot" to give
2038
2039         d3 = d1
2040         d2 = dfEqList d3
2041         d1 = dfEqD d2
2042
2043 and it'll even run!  The trick is to put the thing we are trying to prove
2044 (in this case Eq (D []) into the database before trying to prove its
2045 contributing clauses.
2046         
2047
2048 %************************************************************************
2049 %*                                                                      *
2050                 Reducing a single constraint
2051 %*                                                                      *
2052 %************************************************************************
2053
2054 \begin{code}
2055 ---------------------------------------------
2056 reduceInst :: RedEnv -> Avails -> Inst -> TcM (Avails, LookupInstResult)
2057 reduceInst env avails other_inst
2058   = do  { result <- lookupSimpleInst other_inst
2059         ; return (avails, result) }
2060 \end{code}
2061
2062 Note [Equational Constraints in Implication Constraints]
2063 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2064
2065 An implication constraint is of the form 
2066         Given => Wanted 
2067 where Given and Wanted may contain both equational and dictionary
2068 constraints. The delay and reduction of these two kinds of constraints
2069 is distinct:
2070
2071 -) In the generated code, wanted Dictionary constraints are wrapped up in an
2072    implication constraint that is created at the code site where the wanted
2073    dictionaries can be reduced via a let-binding. This let-bound implication
2074    constraint is deconstructed at the use-site of the wanted dictionaries.
2075
2076 -) While the reduction of equational constraints is also delayed, the delay
2077    is not manifest in the generated code. The required evidence is generated
2078    in the code directly at the use-site. There is no let-binding and deconstruction
2079    necessary. The main disadvantage is that we cannot exploit sharing as the
2080    same evidence may be generated at multiple use-sites. However, this disadvantage
2081    is limited because it only concerns coercions which are erased.
2082
2083 The different treatment is motivated by the different in representation. Dictionary
2084 constraints require manifest runtime dictionaries, while equations require coercions
2085 which are types.
2086
2087 \begin{code}
2088 ---------------------------------------------
2089 reduceImplication :: RedEnv
2090                   -> Inst
2091                   -> TcM (TcDictBinds, [Inst])
2092 \end{code}
2093
2094 Suppose we are simplifying the constraint
2095         forall bs. extras => wanted
2096 in the context of an overall simplification problem with givens 'givens'.
2097
2098 Note that
2099   * The 'givens' need not mention any of the quantified type variables
2100         e.g.    forall {}. Eq a => Eq [a]
2101                 forall {}. C Int => D (Tree Int)
2102
2103     This happens when you have something like
2104         data T a where
2105           T1 :: Eq a => a -> T a
2106
2107         f :: T a -> Int
2108         f x = ...(case x of { T1 v -> v==v })...
2109
2110 \begin{code}
2111         -- ToDo: should we instantiate tvs?  I think it's not necessary
2112         --
2113         -- Note on coercion variables:
2114         --
2115         --      The extra given coercion variables are bound at two different sites:
2116         --      -) in the creation context of the implication constraint        
2117         --              the solved equational constraints use these binders
2118         --
2119         --      -) at the solving site of the implication constraint
2120         --              the solved dictionaries use these binders               
2121         --              these binders are generated by reduceImplication
2122         --
2123 reduceImplication env
2124         orig_implic@(ImplicInst { tci_name = name, tci_loc = inst_loc,
2125                                   tci_tyvars = tvs,
2126                                   tci_given = extra_givens, tci_wanted = wanteds })
2127   = do  {       -- Solve the sub-problem
2128         ; let try_me inst = ReduceMe AddSCs  -- Note [Freeness and implications]
2129               env' = env { red_givens = extra_givens ++ red_givens env
2130                          , red_doc = sep [ptext (sLit "reduceImplication for") 
2131                                             <+> ppr name,
2132                                           nest 2 (parens $ ptext (sLit "within")
2133                                                            <+> red_doc env)]
2134                          , red_try_me = try_me }
2135
2136         ; traceTc (text "reduceImplication" <+> vcat
2137                         [ ppr (red_givens env), ppr extra_givens, 
2138                           ppr wanteds])
2139         ; (irreds, binds) <- checkLoop env' wanteds
2140         ; let   (extra_eq_givens, extra_dict_givens) = partition isEqInst extra_givens
2141                         -- SLPJ Sept 07: I think this is bogus; currently
2142                         -- there are no Eqinsts in extra_givens
2143                 dict_ids = map instToId extra_dict_givens 
2144
2145                 -- Note [Reducing implication constraints]
2146                 -- Tom -- update note, put somewhere!
2147
2148         ; traceTc (text "reduceImplication result" <+> vcat
2149                         [ppr irreds, ppr binds])
2150
2151         ; -- extract superclass binds
2152           --  (sc_binds,_) <- extractResults avails []
2153 --      ; traceTc (text "reduceImplication sc_binds" <+> vcat
2154 --                      [ppr sc_binds, ppr avails])
2155 --  
2156
2157         -- SLPJ Sept 07: what if improvement happened inside the checkLoop?
2158         -- Then we must iterate the outer loop too!
2159
2160         ; traceTc (text "reduceImplication condition" <+> ppr ((isEmptyLHsBinds binds) || (null irreds)))
2161
2162 --      Progress is no longer measered by the number of bindings
2163         ; if (isEmptyLHsBinds binds) && (not $ null irreds) then        -- No progress
2164                 -- If there are any irreds, we back off and do nothing
2165                 return (emptyBag, [orig_implic])
2166           else do
2167         { (simpler_implic_insts, bind) 
2168             <- makeImplicationBind inst_loc tvs extra_givens irreds
2169                 -- This binding is useless if the recursive simplification
2170                 -- made no progress; but currently we don't try to optimise that
2171                 -- case.  After all, we only try hard to reduce at top level, or
2172                 -- when inferring types.
2173
2174         ; let   dict_wanteds = filter (not . isEqInst) wanteds
2175                 -- TOMDO: given equational constraints bug!
2176                 --  we need a different evidence for given
2177                 --  equations depending on whether we solve
2178                 --  dictionary constraints or equational constraints
2179
2180                 eq_tyvars = varSetElems $ tyVarsOfTypes $ map eqInstType extra_eq_givens
2181                         -- SLPJ Sept07: this looks Utterly Wrong to me, but I think
2182                         --              that current extra_givens has no EqInsts, so
2183                         --              it makes no difference
2184                 co  = wrap_inline       -- Note [Always inline implication constraints]
2185                       <.> mkWpTyLams tvs
2186                       <.> mkWpLams eq_tyvars
2187                       <.> mkWpLams dict_ids
2188                       <.> WpLet (binds `unionBags` bind)
2189                 wrap_inline | null dict_ids = idHsWrapper
2190                             | otherwise     = WpInline
2191                 rhs = mkLHsWrap co payload
2192                 loc = instLocSpan inst_loc
2193                 payload = mkBigLHsTup (map (L loc . HsVar . instToId) dict_wanteds)
2194
2195         
2196         ; traceTc (vcat [text "reduceImplication" <+> ppr name,
2197                          ppr simpler_implic_insts,
2198                          text "->" <+> ppr rhs])
2199         ; return (unitBag (L loc (VarBind (instToId orig_implic) rhs)),
2200                   simpler_implic_insts)
2201         } 
2202     }
2203 \end{code}
2204
2205 Note [Always inline implication constraints]
2206 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2207 Suppose an implication constraint floats out of an INLINE function.
2208 Then although the implication has a single call site, it won't be 
2209 inlined.  And that is bad because it means that even if there is really
2210 *no* overloading (type signatures specify the exact types) there will
2211 still be dictionary passing in the resulting code.  To avert this,
2212 we mark the implication constraints themselves as INLINE, at least when
2213 there is no loss of sharing as a result.
2214
2215 Note [Freeness and implications]
2216 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2217 It's hard to say when an implication constraint can be floated out.  Consider
2218         forall {} Eq a => Foo [a]
2219 The (Foo [a]) doesn't mention any of the quantified variables, but it
2220 still might be partially satisfied by the (Eq a). 
2221
2222 There is a useful special case when it *is* easy to partition the 
2223 constraints, namely when there are no 'givens'.  Consider
2224         forall {a}. () => Bar b
2225 There are no 'givens', and so there is no reason to capture (Bar b).
2226 We can let it float out.  But if there is even one constraint we
2227 must be much more careful:
2228         forall {a}. C a b => Bar (m b)
2229 because (C a b) might have a superclass (D b), from which we might 
2230 deduce (Bar [b]) when m later gets instantiated to [].  Ha!
2231
2232 Here is an even more exotic example
2233         class C a => D a b
2234 Now consider the constraint
2235         forall b. D Int b => C Int
2236 We can satisfy the (C Int) from the superclass of D, so we don't want
2237 to float the (C Int) out, even though it mentions no type variable in
2238 the constraints!
2239
2240 One more example: the constraint
2241         class C a => D a b
2242         instance (C a, E c) => E (a,c)
2243
2244         constraint: forall b. D Int b => E (Int,c)
2245
2246 You might think that the (D Int b) can't possibly contribute
2247 to solving (E (Int,c)), since the latter mentions 'c'.  But 
2248 in fact it can, because solving the (E (Int,c)) constraint needs 
2249 dictionaries
2250         C Int, E c
2251 and the (C Int) can be satisfied from the superclass of (D Int b).
2252 So we must still not float (E (Int,c)) out.
2253
2254 To think about: special cases for unary type classes?
2255
2256 Note [Pruning the givens in an implication constraint]
2257 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2258 Suppose we are about to form the implication constraint
2259         forall tvs.  Eq a => Ord b
2260 The (Eq a) cannot contribute to the (Ord b), because it has no access to
2261 the type variable 'b'.  So we could filter out the (Eq a) from the givens.
2262 But BE CAREFUL of the examples above in [Freeness and implications].
2263
2264 Doing so would be a bit tidier, but all the implication constraints get
2265 simplified away by the optimiser, so it's no great win.   So I don't take
2266 advantage of that at the moment.
2267
2268 If you do, BE CAREFUL of wobbly type variables.
2269
2270
2271 %************************************************************************
2272 %*                                                                      *
2273                 Avails and AvailHow: the pool of evidence
2274 %*                                                                      *
2275 %************************************************************************
2276
2277
2278 \begin{code}
2279 data Avails = Avails !ImprovementDone !AvailEnv
2280
2281 type ImprovementDone = Bool     -- True <=> some unification has happened
2282                                 -- so some Irreds might now be reducible
2283                                 -- keys that are now 
2284
2285 type AvailEnv = FiniteMap Inst AvailHow
2286 data AvailHow
2287   = IsIrred             -- Used for irreducible dictionaries,
2288                         -- which are going to be lambda bound
2289
2290   | Given Inst          -- Used for dictionaries for which we have a binding
2291                         -- e.g. those "given" in a signature
2292
2293   | Rhs                 -- Used when there is a RHS
2294         (LHsExpr TcId)  -- The RHS
2295         [Inst]          -- Insts free in the RHS; we need these too
2296
2297 instance Outputable Avails where
2298   ppr = pprAvails
2299
2300 pprAvails (Avails imp avails)
2301   = vcat [ ptext (sLit "Avails") <> (if imp then ptext (sLit "[improved]") else empty)
2302          , nest 2 $ braces $ 
2303            vcat [ sep [ppr inst, nest 2 (equals <+> ppr avail)]
2304                 | (inst,avail) <- fmToList avails ]]
2305
2306 instance Outputable AvailHow where
2307     ppr = pprAvail
2308
2309 -------------------------
2310 pprAvail :: AvailHow -> SDoc
2311 pprAvail IsIrred        = text "Irred"
2312 pprAvail (Given x)      = text "Given" <+> ppr x
2313 pprAvail (Rhs rhs bs)   = sep [text "Rhs" <+> ppr bs,
2314                                nest 2 (ppr rhs)]
2315
2316 -------------------------
2317 extendAvailEnv :: AvailEnv -> Inst -> AvailHow -> AvailEnv
2318 extendAvailEnv env inst avail = addToFM env inst avail
2319
2320 findAvailEnv :: AvailEnv -> Inst -> Maybe AvailHow
2321 findAvailEnv env wanted = lookupFM env wanted
2322         -- NB 1: the Ord instance of Inst compares by the class/type info
2323         --  *not* by unique.  So
2324         --      d1::C Int ==  d2::C Int
2325
2326 emptyAvails :: Avails
2327 emptyAvails = Avails False emptyFM
2328
2329 findAvail :: Avails -> Inst -> Maybe AvailHow
2330 findAvail (Avails _ avails) wanted = findAvailEnv avails wanted
2331
2332 elemAvails :: Inst -> Avails -> Bool
2333 elemAvails wanted (Avails _ avails) = wanted `elemFM` avails
2334
2335 extendAvails :: Avails -> Inst -> AvailHow -> TcM Avails
2336 -- Does improvement
2337 extendAvails avails@(Avails imp env) inst avail
2338   = do  { imp1 <- tcImproveOne avails inst      -- Do any improvement
2339         ; return (Avails (imp || imp1) (extendAvailEnv env inst avail)) }
2340
2341 availsInsts :: Avails -> [Inst]
2342 availsInsts (Avails _ avails) = keysFM avails
2343
2344 availsImproved (Avails imp _) = imp
2345
2346 updateImprovement :: Avails -> Avails -> Avails
2347 -- (updateImprovement a1 a2) sets a1's improvement flag from a2
2348 updateImprovement (Avails _ avails1) (Avails imp2 _) = Avails imp2 avails1
2349 \end{code}
2350
2351 Extracting the bindings from a bunch of Avails.
2352 The bindings do *not* come back sorted in dependency order.
2353 We assume that they'll be wrapped in a big Rec, so that the
2354 dependency analyser can sort them out later
2355
2356 \begin{code}
2357 type DoneEnv = FiniteMap Inst [Id]
2358 -- Tracks which things we have evidence for
2359
2360 extractResults :: Avails
2361                -> [Inst]                -- Wanted
2362                -> TcM (TcDictBinds,     -- Bindings
2363                        [Inst],          -- The insts bound by the bindings
2364                        [Inst])          -- Irreducible ones
2365                         -- Note [Reducing implication constraints]
2366
2367 extractResults (Avails _ avails) wanteds
2368   = go emptyBag [] [] emptyFM wanteds
2369   where
2370     go  :: TcDictBinds  -- Bindings for dicts
2371         -> [Inst]       -- Bound by the bindings
2372         -> [Inst]       -- Irreds
2373         -> DoneEnv      -- Has an entry for each inst in the above three sets
2374         -> [Inst]       -- Wanted
2375         -> TcM (TcDictBinds, [Inst], [Inst])
2376     go binds bound_dicts irreds done [] 
2377       = return (binds, bound_dicts, irreds)
2378
2379     go binds bound_dicts irreds done (w:ws)
2380       | Just done_ids@(done_id : rest_done_ids) <- lookupFM done w
2381       = if w_id `elem` done_ids then
2382            go binds bound_dicts irreds done ws
2383         else
2384            go (add_bind (nlHsVar done_id)) bound_dicts irreds
2385               (addToFM done w (done_id : w_id : rest_done_ids)) ws
2386
2387       | otherwise       -- Not yet done
2388       = case findAvailEnv avails w of
2389           Nothing -> pprTrace "Urk: extractResults" (ppr w) $
2390                      go binds bound_dicts irreds done ws
2391
2392           Just IsIrred -> go binds bound_dicts (w:irreds) done' ws
2393
2394           Just (Rhs rhs ws') -> go (add_bind rhs) (w:bound_dicts) irreds done' (ws' ++ ws)
2395
2396           Just (Given g) -> go binds' bound_dicts irreds (addToFM done w [g_id]) ws 
2397                 where
2398                   g_id = instToId g
2399                   binds' | w_id == g_id = binds
2400                          | otherwise    = add_bind (nlHsVar g_id)
2401       where
2402         w_id  = instToId w      
2403         done' = addToFM done w [w_id]
2404         add_bind rhs = addInstToDictBind binds w rhs
2405 \end{code}
2406
2407
2408 Note [No superclasses for Stop]
2409 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2410 When we decide not to reduce an Inst -- the 'WhatToDo' --- we still
2411 add it to avails, so that any other equal Insts will be commoned up
2412 right here.  However, we do *not* add superclasses.  If we have
2413         df::Floating a
2414         dn::Num a
2415 but a is not bound here, then we *don't* want to derive dn from df
2416 here lest we lose sharing.
2417
2418 \begin{code}
2419 addWanted :: WantSCs -> Avails -> Inst -> LHsExpr TcId -> [Inst] -> TcM Avails
2420 addWanted want_scs avails wanted rhs_expr wanteds
2421   = addAvailAndSCs want_scs avails wanted avail
2422   where
2423     avail = Rhs rhs_expr wanteds
2424
2425 addGiven :: Avails -> Inst -> TcM Avails
2426 addGiven avails given = addAvailAndSCs AddSCs avails given (Given given)
2427         -- Always add superclasses for 'givens'
2428         --
2429         -- No ASSERT( not (given `elemAvails` avails) ) because in an instance
2430         -- decl for Ord t we can add both Ord t and Eq t as 'givens', 
2431         -- so the assert isn't true
2432 \end{code}
2433
2434 \begin{code}
2435 addIrred :: WantSCs -> Avails -> Inst -> TcM Avails
2436 addIrred want_scs avails irred = ASSERT2( not (irred `elemAvails` avails), ppr irred $$ ppr avails )
2437                                  addAvailAndSCs want_scs avails irred IsIrred
2438
2439 addAvailAndSCs :: WantSCs -> Avails -> Inst -> AvailHow -> TcM Avails
2440 addAvailAndSCs want_scs avails inst avail
2441   | not (isClassDict inst) = extendAvails avails inst avail
2442   | NoSCs <- want_scs      = extendAvails avails inst avail
2443   | otherwise              = do { traceTc (text "addAvailAndSCs" <+> vcat [ppr inst, ppr deps])
2444                                 ; avails' <- extendAvails avails inst avail
2445                                 ; addSCs is_loop avails' inst }
2446   where
2447     is_loop pred = any (`tcEqType` mkPredTy pred) dep_tys
2448                         -- Note: this compares by *type*, not by Unique
2449     deps         = findAllDeps (unitVarSet (instToVar inst)) avail
2450     dep_tys      = map idType (varSetElems deps)
2451
2452     findAllDeps :: IdSet -> AvailHow -> IdSet
2453     -- Find all the Insts that this one depends on
2454     -- See Note [SUPERCLASS-LOOP 2]
2455     -- Watch out, though.  Since the avails may contain loops 
2456     -- (see Note [RECURSIVE DICTIONARIES]), so we need to track the ones we've seen so far
2457     findAllDeps so_far (Rhs _ kids) = foldl find_all so_far kids
2458     findAllDeps so_far other        = so_far
2459
2460     find_all :: IdSet -> Inst -> IdSet
2461     find_all so_far kid
2462       | isEqInst kid                       = so_far
2463       | kid_id `elemVarSet` so_far         = so_far
2464       | Just avail <- findAvail avails kid = findAllDeps so_far' avail
2465       | otherwise                          = so_far'
2466       where
2467         so_far' = extendVarSet so_far kid_id    -- Add the new kid to so_far
2468         kid_id = instToId kid
2469
2470 addSCs :: (TcPredType -> Bool) -> Avails -> Inst -> TcM Avails
2471         -- Add all the superclasses of the Inst to Avails
2472         -- The first param says "don't do this because the original thing
2473         --      depends on this one, so you'd build a loop"
2474         -- Invariant: the Inst is already in Avails.
2475
2476 addSCs is_loop avails dict
2477   = ASSERT( isDict dict )
2478     do  { sc_dicts <- newDictBndrs (instLoc dict) sc_theta'
2479         ; foldlM add_sc avails (zipEqual "add_scs" sc_dicts sc_sels) }
2480   where
2481     (clas, tys) = getDictClassTys dict
2482     (tyvars, sc_theta, sc_sels, _) = classBigSig clas
2483     sc_theta' = filter (not . isEqPred) $
2484                   substTheta (zipTopTvSubst tyvars tys) sc_theta
2485
2486     add_sc avails (sc_dict, sc_sel)
2487       | is_loop (dictPred sc_dict) = return avails      -- See Note [SUPERCLASS-LOOP 2]
2488       | is_given sc_dict           = return avails
2489       | otherwise                  = do { avails' <- extendAvails avails sc_dict (Rhs sc_sel_rhs [dict])
2490                                         ; addSCs is_loop avails' sc_dict }
2491       where
2492         sc_sel_rhs = L (instSpan dict) (HsWrap co_fn (HsVar sc_sel))
2493         co_fn      = WpApp (instToVar dict) <.> mkWpTyApps tys
2494
2495     is_given :: Inst -> Bool
2496     is_given sc_dict = case findAvail avails sc_dict of
2497                           Just (Given _) -> True        -- Given is cheaper than superclass selection
2498                           other          -> False       
2499
2500 -- From the a set of insts obtain all equalities that (transitively) occur in
2501 -- superclass contexts of class constraints (aka the ancestor equalities). 
2502 --
2503 ancestorEqualities :: [Inst] -> TcM [Inst]
2504 ancestorEqualities
2505   =   mapM mkWantedEqInst               -- turn only equality predicates..
2506     . filter isEqPred                   -- ..into wanted equality insts
2507     . bagToList 
2508     . addAEsToBag emptyBag              -- collect the superclass constraints..
2509     . map dictPred                      -- ..of all predicates in a bag
2510     . filter isClassDict
2511   where
2512     addAEsToBag :: Bag PredType -> [PredType] -> Bag PredType
2513     addAEsToBag bag []           = bag
2514     addAEsToBag bag (pred:preds)
2515       | pred `elemBag` bag = addAEsToBag bag         preds
2516       | isEqPred pred      = addAEsToBag bagWithPred preds
2517       | isClassPred pred   = addAEsToBag bagWithPred predsWithSCs
2518       | otherwise          = addAEsToBag bag         preds
2519       where
2520         bagWithPred  = bag `snocBag` pred
2521         predsWithSCs = preds ++ substTheta (zipTopTvSubst tyvars tys) sc_theta
2522         --
2523         (tyvars, sc_theta, _, _) = classBigSig clas
2524         (clas, tys)              = getClassPredTys pred 
2525 \end{code}
2526
2527
2528 %************************************************************************
2529 %*                                                                      *
2530 \section{tcSimplifyTop: defaulting}
2531 %*                                                                      *
2532 %************************************************************************
2533
2534
2535 @tcSimplifyTop@ is called once per module to simplify all the constant
2536 and ambiguous Insts.
2537
2538 We need to be careful of one case.  Suppose we have
2539
2540         instance Num a => Num (Foo a b) where ...
2541
2542 and @tcSimplifyTop@ is given a constraint (Num (Foo x y)).  Then it'll simplify
2543 to (Num x), and default x to Int.  But what about y??
2544
2545 It's OK: the final zonking stage should zap y to (), which is fine.
2546
2547
2548 \begin{code}
2549 tcSimplifyTop, tcSimplifyInteractive :: [Inst] -> TcM TcDictBinds
2550 tcSimplifyTop wanteds
2551   = tc_simplify_top doc False wanteds
2552   where 
2553     doc = text "tcSimplifyTop"
2554
2555 tcSimplifyInteractive wanteds
2556   = tc_simplify_top doc True wanteds
2557   where 
2558     doc = text "tcSimplifyInteractive"
2559
2560 -- The TcLclEnv should be valid here, solely to improve
2561 -- error message generation for the monomorphism restriction
2562 tc_simplify_top doc interactive wanteds
2563   = do  { dflags <- getDOpts
2564         ; wanteds <- zonkInsts wanteds
2565         ; mapM_ zonkTopTyVar (varSetElems (tyVarsOfInsts wanteds))
2566
2567         ; traceTc (text "tc_simplify_top 0: " <+> ppr wanteds)
2568         ; (irreds1, binds1) <- tryHardCheckLoop doc1 wanteds
2569 --      ; (irreds1, binds1) <- gentleInferLoop doc1 wanteds
2570         ; traceTc (text "tc_simplify_top 1: " <+> ppr irreds1)
2571         ; (irreds2, binds2) <- approximateImplications doc2 (\d -> True) irreds1
2572         ; traceTc (text "tc_simplify_top 2: " <+> ppr irreds2)
2573
2574                 -- Use the defaulting rules to do extra unification
2575                 -- NB: irreds2 are already zonked
2576         ; (irreds3, binds3) <- disambiguate doc3 interactive dflags irreds2
2577
2578                 -- Deal with implicit parameters
2579         ; let (bad_ips, non_ips) = partition isIPDict irreds3
2580               (ambigs, others)   = partition isTyVarDict non_ips
2581
2582         ; topIPErrs bad_ips     -- Can arise from   f :: Int -> Int
2583                                 --                  f x = x + ?y
2584         ; addNoInstanceErrs others
2585         ; addTopAmbigErrs ambigs        
2586
2587         ; return (binds1 `unionBags` binds2 `unionBags` binds3) }
2588   where
2589     doc1 = doc <+> ptext (sLit "(first round)")
2590     doc2 = doc <+> ptext (sLit "(approximate)")
2591     doc3 = doc <+> ptext (sLit "(disambiguate)")
2592 \end{code}
2593
2594 If a dictionary constrains a type variable which is
2595         * not mentioned in the environment
2596         * and not mentioned in the type of the expression
2597 then it is ambiguous. No further information will arise to instantiate
2598 the type variable; nor will it be generalised and turned into an extra
2599 parameter to a function.
2600
2601 It is an error for this to occur, except that Haskell provided for
2602 certain rules to be applied in the special case of numeric types.
2603 Specifically, if
2604         * at least one of its classes is a numeric class, and
2605         * all of its classes are numeric or standard
2606 then the type variable can be defaulted to the first type in the
2607 default-type list which is an instance of all the offending classes.
2608
2609 So here is the function which does the work.  It takes the ambiguous
2610 dictionaries and either resolves them (producing bindings) or
2611 complains.  It works by splitting the dictionary list by type
2612 variable, and using @disambigOne@ to do the real business.
2613
2614 @disambigOne@ assumes that its arguments dictionaries constrain all
2615 the same type variable.
2616
2617 ADR Comment 20/6/94: I've changed the @CReturnable@ case to default to
2618 @()@ instead of @Int@.  I reckon this is the Right Thing to do since
2619 the most common use of defaulting is code like:
2620 \begin{verbatim}
2621         _ccall_ foo     `seqPrimIO` bar
2622 \end{verbatim}
2623 Since we're not using the result of @foo@, the result if (presumably)
2624 @void@.
2625
2626 \begin{code}
2627 disambiguate :: SDoc -> Bool -> DynFlags -> [Inst] -> TcM ([Inst], TcDictBinds)
2628         -- Just does unification to fix the default types
2629         -- The Insts are assumed to be pre-zonked
2630 disambiguate doc interactive dflags insts
2631   | null insts
2632   = return (insts, emptyBag)
2633
2634   | null defaultable_groups
2635   = do  { traceTc (text "disambigutate, no defaultable groups" <+> vcat [ppr unaries, ppr insts, ppr bad_tvs, ppr defaultable_groups])
2636         ; return (insts, emptyBag) }
2637
2638   | otherwise
2639   = do  {       -- Figure out what default types to use
2640           default_tys <- getDefaultTys extended_defaulting ovl_strings
2641
2642         ; traceTc (text "disambiguate1" <+> vcat [ppr insts, ppr unaries, ppr bad_tvs, ppr defaultable_groups])
2643         ; mapM_ (disambigGroup default_tys) defaultable_groups
2644
2645         -- disambigGroup does unification, hence try again
2646         ; tryHardCheckLoop doc insts }
2647
2648   where
2649    extended_defaulting = interactive || dopt Opt_ExtendedDefaultRules dflags
2650    ovl_strings = dopt Opt_OverloadedStrings dflags
2651
2652    unaries :: [(Inst, Class, TcTyVar)]  -- (C tv) constraints
2653    bad_tvs :: TcTyVarSet  -- Tyvars mentioned by *other* constraints
2654    (unaries, bad_tvs_s) = partitionWith find_unary insts 
2655    bad_tvs              = unionVarSets bad_tvs_s
2656
2657         -- Finds unary type-class constraints
2658    find_unary d@(Dict {tci_pred = ClassP cls [ty]})
2659         | Just tv <- tcGetTyVar_maybe ty = Left (d,cls,tv)
2660    find_unary inst                       = Right (tyVarsOfInst inst)
2661
2662                 -- Group by type variable
2663    defaultable_groups :: [[(Inst,Class,TcTyVar)]]
2664    defaultable_groups = filter defaultable_group (equivClasses cmp_tv unaries)
2665    cmp_tv (_,_,tv1) (_,_,tv2) = tv1 `compare` tv2
2666
2667    defaultable_group :: [(Inst,Class,TcTyVar)] -> Bool
2668    defaultable_group ds@((_,_,tv):_)
2669         =  isTyConableTyVar tv  -- Note [Avoiding spurious errors]
2670         && not (tv `elemVarSet` bad_tvs)
2671         && defaultable_classes [c | (_,c,_) <- ds]
2672    defaultable_group [] = panic "defaultable_group"
2673
2674    defaultable_classes clss 
2675         | extended_defaulting = any isInteractiveClass clss
2676         | otherwise           = all is_std_class clss && (any is_num_class clss)
2677
2678         -- In interactive mode, or with -fextended-default-rules,
2679         -- we default Show a to Show () to avoid graututious errors on "show []"
2680    isInteractiveClass cls 
2681         = is_num_class cls || (classKey cls `elem` [showClassKey, eqClassKey, ordClassKey])
2682
2683    is_num_class cls = isNumericClass cls || (ovl_strings && (cls `hasKey` isStringClassKey))
2684         -- is_num_class adds IsString to the standard numeric classes, 
2685         -- when -foverloaded-strings is enabled
2686
2687    is_std_class cls = isStandardClass cls || (ovl_strings && (cls `hasKey` isStringClassKey))
2688         -- Similarly is_std_class
2689
2690 -----------------------
2691 disambigGroup :: [Type]                 -- The default types
2692               -> [(Inst,Class,TcTyVar)] -- All standard classes of form (C a)
2693               -> TcM () -- Just does unification, to fix the default types
2694
2695 disambigGroup default_tys dicts
2696   = try_default default_tys
2697   where
2698     (_,_,tyvar) = ASSERT(not (null dicts)) head dicts   -- Should be non-empty
2699     classes = [c | (_,c,_) <- dicts]
2700
2701     try_default [] = return ()
2702     try_default (default_ty : default_tys)
2703       = tryTcLIE_ (try_default default_tys) $
2704         do { tcSimplifyDefault [mkClassPred clas [default_ty] | clas <- classes]
2705                 -- This may fail; then the tryTcLIE_ kicks in
2706                 -- Failure here is caused by there being no type in the
2707                 -- default list which can satisfy all the ambiguous classes.
2708                 -- For example, if Real a is reqd, but the only type in the
2709                 -- default list is Int.
2710
2711                 -- After this we can't fail
2712            ; warnDefault dicts default_ty
2713            ; unifyType default_ty (mkTyVarTy tyvar) 
2714            ; return () -- TOMDO: do something with the coercion
2715            }
2716
2717
2718 -----------------------
2719 getDefaultTys :: Bool -> Bool -> TcM [Type]
2720 getDefaultTys extended_deflts ovl_strings
2721   = do  { mb_defaults <- getDeclaredDefaultTys
2722         ; case mb_defaults of {
2723            Just tys -> return tys ;     -- User-supplied defaults
2724            Nothing  -> do
2725
2726         -- No use-supplied default
2727         -- Use [Integer, Double], plus modifications
2728         { integer_ty <- tcMetaTy integerTyConName
2729         ; checkWiredInTyCon doubleTyCon
2730         ; string_ty <- tcMetaTy stringTyConName
2731         ; return (opt_deflt extended_deflts unitTy
2732                         -- Note [Default unitTy]
2733                         ++
2734                   [integer_ty,doubleTy]
2735                         ++
2736                   opt_deflt ovl_strings string_ty) } } }
2737   where
2738     opt_deflt True  ty = [ty]
2739     opt_deflt False ty = []
2740 \end{code}
2741
2742 Note [Default unitTy]
2743 ~~~~~~~~~~~~~~~~~~~~~
2744 In interative mode (or with -fextended-default-rules) we add () as the first type we
2745 try when defaulting.  This has very little real impact, except in the following case.
2746 Consider: 
2747         Text.Printf.printf "hello"
2748 This has type (forall a. IO a); it prints "hello", and returns 'undefined'.  We don't
2749 want the GHCi repl loop to try to print that 'undefined'.  The neatest thing is to
2750 default the 'a' to (), rather than to Integer (which is what would otherwise happen;
2751 and then GHCi doesn't attempt to print the ().  So in interactive mode, we add
2752 () to the list of defaulting types.  See Trac #1200.
2753
2754 Note [Avoiding spurious errors]
2755 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2756 When doing the unification for defaulting, we check for skolem
2757 type variables, and simply don't default them.  For example:
2758    f = (*)      -- Monomorphic
2759    g :: Num a => a -> a
2760    g x = f x x
2761 Here, we get a complaint when checking the type signature for g,
2762 that g isn't polymorphic enough; but then we get another one when
2763 dealing with the (Num a) context arising from f's definition;
2764 we try to unify a with Int (to default it), but find that it's
2765 already been unified with the rigid variable from g's type sig
2766
2767
2768 %************************************************************************
2769 %*                                                                      *
2770 \subsection[simple]{@Simple@ versions}
2771 %*                                                                      *
2772 %************************************************************************
2773
2774 Much simpler versions when there are no bindings to make!
2775
2776 @tcSimplifyThetas@ simplifies class-type constraints formed by
2777 @deriving@ declarations and when specialising instances.  We are
2778 only interested in the simplified bunch of class/type constraints.
2779
2780 It simplifies to constraints of the form (C a b c) where
2781 a,b,c are type variables.  This is required for the context of
2782 instance declarations.
2783
2784 \begin{code}
2785 tcSimplifyDeriv :: InstOrigin
2786                 -> [TyVar]      
2787                 -> ThetaType            -- Wanted
2788                 -> TcM ThetaType        -- Needed
2789 -- Given  instance (wanted) => C inst_ty 
2790 -- Simplify 'wanted' as much as possible
2791
2792 tcSimplifyDeriv orig tyvars theta
2793   = do  { (tvs, _, tenv) <- tcInstTyVars tyvars
2794         -- The main loop may do unification, and that may crash if 
2795         -- it doesn't see a TcTyVar, so we have to instantiate. Sigh
2796         -- ToDo: what if two of them do get unified?
2797         ; wanteds <- newDictBndrsO orig (substTheta tenv theta)
2798         ; (irreds, _) <- tryHardCheckLoop doc wanteds
2799
2800         ; let (tv_dicts, others) = partition ok irreds
2801         ; addNoInstanceErrs others
2802         -- See Note [Exotic derived instance contexts] in TcMType
2803
2804         ; let rev_env = zipTopTvSubst tvs (mkTyVarTys tyvars)
2805               simpl_theta = substTheta rev_env (map dictPred tv_dicts)
2806                 -- This reverse-mapping is a pain, but the result
2807                 -- should mention the original TyVars not TcTyVars
2808
2809         ; return simpl_theta }
2810   where
2811     doc = ptext (sLit "deriving classes for a data type")
2812
2813     ok dict | isDict dict = validDerivPred (dictPred dict)
2814             | otherwise   = False
2815 \end{code}
2816
2817
2818 @tcSimplifyDefault@ just checks class-type constraints, essentially;
2819 used with \tr{default} declarations.  We are only interested in
2820 whether it worked or not.
2821
2822 \begin{code}
2823 tcSimplifyDefault :: ThetaType  -- Wanted; has no type variables in it
2824                   -> TcM ()
2825
2826 tcSimplifyDefault theta = do
2827     wanteds <- newDictBndrsO DefaultOrigin theta
2828     (irreds, _) <- tryHardCheckLoop doc wanteds
2829     addNoInstanceErrs  irreds
2830     if null irreds then
2831         return ()
2832      else
2833         traceTc (ptext (sLit "tcSimplifyDefault failing")) >> failM
2834   where
2835     doc = ptext (sLit "default declaration")
2836 \end{code}
2837
2838
2839 %************************************************************************
2840 %*                                                                      *
2841 \section{Errors and contexts}
2842 %*                                                                      *
2843 %************************************************************************
2844
2845 ToDo: for these error messages, should we note the location as coming
2846 from the insts, or just whatever seems to be around in the monad just
2847 now?
2848
2849 \begin{code}
2850 groupErrs :: ([Inst] -> TcM ()) -- Deal with one group
2851           -> [Inst]             -- The offending Insts
2852           -> TcM ()
2853 -- Group together insts with the same origin
2854 -- We want to report them together in error messages
2855
2856 groupErrs report_err [] 
2857   = return ()
2858 groupErrs report_err (inst:insts)
2859   = do  { do_one (inst:friends)
2860         ; groupErrs report_err others }
2861   where
2862         -- (It may seem a bit crude to compare the error messages,
2863         --  but it makes sure that we combine just what the user sees,
2864         --  and it avoids need equality on InstLocs.)
2865    (friends, others) = partition is_friend insts
2866    loc_msg           = showSDoc (pprInstLoc (instLoc inst))
2867    is_friend friend  = showSDoc (pprInstLoc (instLoc friend)) == loc_msg
2868    do_one insts = addInstCtxt (instLoc (head insts)) (report_err insts)
2869                 -- Add location and context information derived from the Insts
2870
2871 -- Add the "arising from..." part to a message about bunch of dicts
2872 addInstLoc :: [Inst] -> Message -> Message
2873 addInstLoc insts msg = msg $$ nest 2 (pprInstArising (head insts))
2874
2875 addTopIPErrs :: [Name] -> [Inst] -> TcM ()
2876 addTopIPErrs bndrs [] 
2877   = return ()
2878 addTopIPErrs bndrs ips
2879   = do  { dflags <- getDOpts
2880         ; addErrTcM (tidy_env, mk_msg dflags tidy_ips) }
2881   where
2882     (tidy_env, tidy_ips) = tidyInsts ips
2883     mk_msg dflags ips 
2884         = vcat [sep [ptext (sLit "Implicit parameters escape from"),
2885                 nest 2 (ptext (sLit "the monomorphic top-level binding") 
2886                                             <> plural bndrs <+> ptext (sLit "of")
2887                                             <+> pprBinders bndrs <> colon)],
2888                 nest 2 (vcat (map ppr_ip ips)),
2889                 monomorphism_fix dflags]
2890     ppr_ip ip = pprPred (dictPred ip) <+> pprInstArising ip
2891
2892 topIPErrs :: [Inst] -> TcM ()
2893 topIPErrs dicts
2894   = groupErrs report tidy_dicts
2895   where
2896     (tidy_env, tidy_dicts) = tidyInsts dicts
2897     report dicts = addErrTcM (tidy_env, mk_msg dicts)
2898     mk_msg dicts = addInstLoc dicts (ptext (sLit "Unbound implicit parameter") <> 
2899                                      plural tidy_dicts <+> pprDictsTheta tidy_dicts)
2900
2901 addNoInstanceErrs :: [Inst]     -- Wanted (can include implications)
2902                   -> TcM ()     
2903 addNoInstanceErrs insts
2904   = do  { let (tidy_env, tidy_insts) = tidyInsts insts
2905         ; reportNoInstances tidy_env Nothing tidy_insts }
2906
2907 reportNoInstances 
2908         :: TidyEnv
2909         -> Maybe (InstLoc, [Inst])      -- Context
2910                         -- Nothing => top level
2911                         -- Just (d,g) => d describes the construct
2912                         --               with givens g
2913         -> [Inst]       -- What is wanted (can include implications)
2914         -> TcM ()       
2915
2916 reportNoInstances tidy_env mb_what insts 
2917   = groupErrs (report_no_instances tidy_env mb_what) insts
2918
2919 report_no_instances tidy_env mb_what insts
2920   = do { inst_envs <- tcGetInstEnvs
2921        ; let (implics, insts1)  = partition isImplicInst insts
2922              (insts2, overlaps) = partitionWith (check_overlap inst_envs) insts1
2923              (eqInsts, insts3)  = partition isEqInst insts2
2924        ; traceTc (text "reportNoInstances" <+> vcat 
2925                        [ppr insts, ppr implics, ppr insts1, ppr insts2])
2926        ; mapM_ complain_implic implics
2927        ; mapM_ (\doc -> addErrTcM (tidy_env, doc)) overlaps
2928        ; groupErrs complain_no_inst insts3 
2929        ; mapM_ (addErrTcM . mk_eq_err) eqInsts
2930        }
2931   where
2932     complain_no_inst insts = addErrTcM (tidy_env, mk_no_inst_err insts)
2933
2934     complain_implic inst        -- Recurse!
2935       = reportNoInstances tidy_env 
2936                           (Just (tci_loc inst, tci_given inst)) 
2937                           (tci_wanted inst)
2938
2939     check_overlap :: (InstEnv,InstEnv) -> Inst -> Either Inst SDoc
2940         -- Right msg  => overlap message
2941         -- Left  inst => no instance
2942     check_overlap inst_envs wanted
2943         | not (isClassDict wanted) = Left wanted
2944         | otherwise
2945         = case lookupInstEnv inst_envs clas tys of
2946                 ([], _) -> Left wanted          -- No match
2947                 -- The case of exactly one match and no unifiers means a
2948                 -- successful lookup.  That can't happen here, because dicts
2949                 -- only end up here if they didn't match in Inst.lookupInst
2950                 ([m],[])
2951                  | debugIsOn -> pprPanic "reportNoInstance" (ppr wanted)
2952                 res -> Right (mk_overlap_msg wanted res)
2953           where
2954             (clas,tys) = getDictClassTys wanted
2955
2956     mk_overlap_msg dict (matches, unifiers)
2957       = ASSERT( not (null matches) )
2958         vcat [  addInstLoc [dict] ((ptext (sLit "Overlapping instances for") 
2959                                         <+> pprPred (dictPred dict))),
2960                 sep [ptext (sLit "Matching instances") <> colon,
2961                      nest 2 (vcat [pprInstances ispecs, pprInstances unifiers])],
2962                 if not (isSingleton matches)
2963                 then    -- Two or more matches
2964                      empty
2965                 else    -- One match, plus some unifiers
2966                 ASSERT( not (null unifiers) )
2967                 parens (vcat [ptext (sLit "The choice depends on the instantiation of") <+>
2968                                  quotes (pprWithCommas ppr (varSetElems (tyVarsOfInst dict))),
2969                               ptext (sLit "To pick the first instance above, use -fallow-incoherent-instances"),
2970                               ptext (sLit "when compiling the other instance declarations")])]
2971       where
2972         ispecs = [ispec | (ispec, _) <- matches]
2973
2974     mk_eq_err :: Inst -> (TidyEnv, SDoc)
2975     mk_eq_err inst = misMatchMsg tidy_env (eqInstTys inst)
2976
2977     mk_no_inst_err insts
2978       | null insts = empty
2979
2980       | Just (loc, givens) <- mb_what,   -- Nested (type signatures, instance decls)
2981         not (isEmptyVarSet (tyVarsOfInsts insts))
2982       = vcat [ addInstLoc insts $
2983                sep [ ptext (sLit "Could not deduce") <+> pprDictsTheta insts
2984                    , nest 2 $ ptext (sLit "from the context") <+> pprDictsTheta givens]
2985              , show_fixes (fix1 loc : fixes2) ]
2986
2987       | otherwise       -- Top level 
2988       = vcat [ addInstLoc insts $
2989                ptext (sLit "No instance") <> plural insts
2990                     <+> ptext (sLit "for") <+> pprDictsTheta insts
2991              , show_fixes fixes2 ]
2992
2993       where
2994         fix1 loc = sep [ ptext (sLit "add") <+> pprDictsTheta insts
2995                                  <+> ptext (sLit "to the context of"),
2996                          nest 2 (ppr (instLocOrigin loc)) ]
2997                          -- I'm not sure it helps to add the location
2998                          -- nest 2 (ptext (sLit "at") <+> ppr (instLocSpan loc)) ]
2999
3000         fixes2 | null instance_dicts = []
3001                | otherwise           = [sep [ptext (sLit "add an instance declaration for"),
3002                                         pprDictsTheta instance_dicts]]
3003         instance_dicts = [d | d <- insts, isClassDict d, not (isTyVarDict d)]
3004                 -- Insts for which it is worth suggesting an adding an instance declaration
3005                 -- Exclude implicit parameters, and tyvar dicts
3006
3007         show_fixes :: [SDoc] -> SDoc
3008         show_fixes []     = empty
3009         show_fixes (f:fs) = sep [ptext (sLit "Possible fix:"), 
3010                                  nest 2 (vcat (f : map (ptext (sLit "or") <+>) fs))]
3011
3012 addTopAmbigErrs dicts
3013 -- Divide into groups that share a common set of ambiguous tyvars
3014   = ifErrsM (return ()) $       -- Only report ambiguity if no other errors happened
3015                                 -- See Note [Avoiding spurious errors]
3016     mapM_ report (equivClasses cmp [(d, tvs_of d) | d <- tidy_dicts])
3017   where
3018     (tidy_env, tidy_dicts) = tidyInsts dicts
3019
3020     tvs_of :: Inst -> [TcTyVar]
3021     tvs_of d = varSetElems (tyVarsOfInst d)
3022     cmp (_,tvs1) (_,tvs2) = tvs1 `compare` tvs2
3023     
3024     report :: [(Inst,[TcTyVar])] -> TcM ()
3025     report pairs@((inst,tvs) : _) = do  -- The pairs share a common set of ambiguous tyvars
3026           (tidy_env, mono_msg) <- mkMonomorphismMsg tidy_env tvs
3027           setSrcSpan (instSpan inst) $
3028                 -- the location of the first one will do for the err message
3029            addErrTcM (tidy_env, msg $$ mono_msg)
3030         where
3031           dicts = map fst pairs
3032           msg = sep [text "Ambiguous type variable" <> plural tvs <+> 
3033                           pprQuotedList tvs <+> in_msg,
3034                      nest 2 (pprDictsInFull dicts)]
3035           in_msg = text "in the constraint" <> plural dicts <> colon
3036     report [] = panic "addTopAmbigErrs"
3037
3038
3039 mkMonomorphismMsg :: TidyEnv -> [TcTyVar] -> TcM (TidyEnv, Message)
3040 -- There's an error with these Insts; if they have free type variables
3041 -- it's probably caused by the monomorphism restriction. 
3042 -- Try to identify the offending variable
3043 -- ASSUMPTION: the Insts are fully zonked
3044 mkMonomorphismMsg tidy_env inst_tvs
3045   = do  { dflags <- getDOpts
3046         ; (tidy_env, docs) <- findGlobals (mkVarSet inst_tvs) tidy_env
3047         ; return (tidy_env, mk_msg dflags docs) }
3048   where
3049     mk_msg _ _ | any isRuntimeUnk inst_tvs
3050         =  vcat [ptext (sLit "Cannot resolve unknown runtime types:") <+>
3051                    (pprWithCommas ppr inst_tvs),
3052                 ptext (sLit "Use :print or :force to determine these types")]
3053     mk_msg _ []   = ptext (sLit "Probable fix: add a type signature that fixes these type variable(s)")
3054                         -- This happens in things like
3055                         --      f x = show (read "foo")
3056                         -- where monomorphism doesn't play any role
3057     mk_msg dflags docs 
3058         = vcat [ptext (sLit "Possible cause: the monomorphism restriction applied to the following:"),
3059                 nest 2 (vcat docs),
3060                 monomorphism_fix dflags]
3061
3062 monomorphism_fix :: DynFlags -> SDoc
3063 monomorphism_fix dflags
3064   = ptext (sLit "Probable fix:") <+> vcat
3065         [ptext (sLit "give these definition(s) an explicit type signature"),
3066          if dopt Opt_MonomorphismRestriction dflags
3067            then ptext (sLit "or use -fno-monomorphism-restriction")
3068            else empty]  -- Only suggest adding "-fno-monomorphism-restriction"
3069                         -- if it is not already set!
3070     
3071 warnDefault ups default_ty = do
3072     warn_flag <- doptM Opt_WarnTypeDefaults
3073     addInstCtxt (instLoc (head (dicts))) (warnTc warn_flag warn_msg)
3074   where
3075     dicts = [d | (d,_,_) <- ups]
3076
3077         -- Tidy them first
3078     (_, tidy_dicts) = tidyInsts dicts
3079     warn_msg  = vcat [ptext (sLit "Defaulting the following constraint(s) to type") <+>
3080                                 quotes (ppr default_ty),
3081                       pprDictsInFull tidy_dicts]
3082
3083 reduceDepthErr n stack
3084   = vcat [ptext (sLit "Context reduction stack overflow; size =") <+> int n,
3085           ptext (sLit "Use -fcontext-stack=N to increase stack size to N"),
3086           nest 4 (pprStack stack)]
3087
3088 pprStack stack = vcat (map pprInstInFull stack)
3089 \end{code}