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