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