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