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