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