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