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