[project @ 2004-04-02 13:16:07 by simonpj]
[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(..), LHsBinds, HsExpr(..), LHsExpr, pprLHsBinds )
25 import TcHsSyn          ( TcId, TcDictBinds, mkHsApp, mkHsTyApp, mkHsDictApp )
26
27 import TcRnMonad
28 import Inst             ( lookupInst, LookupInstResult(..),
29                           tyVarsOfInst, fdPredsOfInsts, fdPredsOfInst, newDicts,
30                           isDict, isClassDict, isLinearInst, linearInstType,
31                           isStdClassTyVarDict, isMethodFor, isMethod,
32                           instToId, tyVarsOfInsts,  cloneDict,
33                           ipNamesOfInsts, ipNamesOfInst, dictPred,
34                           instBindingRequired,
35                           newDictsFromOld, tcInstClassOp,
36                           getDictClassTys, isTyVarDict,
37                           instLoc, zonkInst, tidyInsts, tidyMoreInsts,
38                           Inst, pprInsts, pprDictsInFull, pprInstInFull, tcGetInstEnvs,
39                           isIPDict, 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, TyVarDetails(VanillaTv),
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 Subst            ( mkTopTyVarSubst, 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, ppr (grow preds tau_tvs'), ppr qtvs])      `thenM_`
655                 -- Step 2
656     reduceContext doc try_me [] wanteds'    `thenM` \ (no_improvement, frees, binds, irreds) ->
657
658                 -- Step 3
659     if no_improvement then
660         returnM (varSetElems qtvs, frees, binds, irreds)
661     else
662         -- If improvement did some unification, we go round again.  There
663         -- are two subtleties:
664         --   a) We start again with irreds, not wanteds
665         --      Using an instance decl might have introduced a fresh type variable
666         --      which might have been unified, so we'd get an infinite loop
667         --      if we started again with wanteds!  See example [LOOP]
668         --
669         --   b) It's also essential to re-process frees, because unification
670         --      might mean that a type variable that looked free isn't now.
671         --
672         -- Hence the (irreds ++ frees)
673
674         -- However, NOTICE that when we are done, we might have some bindings, but
675         -- the final qtvs might be empty.  See [NO TYVARS] below.
676                                 
677         inferLoop doc tau_tvs (irreds ++ frees) `thenM` \ (qtvs1, frees1, binds1, irreds1) ->
678         returnM (qtvs1, frees1, binds `unionBags` binds1, irreds1)
679 \end{code}
680
681 Example [LOOP]
682
683         class If b t e r | b t e -> r
684         instance If T t e t
685         instance If F t e e
686         class Lte a b c | a b -> c where lte :: a -> b -> c
687         instance Lte Z b T
688         instance (Lte a b l,If l b a c) => Max a b c
689
690 Wanted: Max Z (S x) y
691
692 Then we'll reduce using the Max instance to:
693         (Lte Z (S x) l, If l (S x) Z y)
694 and improve by binding l->T, after which we can do some reduction
695 on both the Lte and If constraints.  What we *can't* do is start again
696 with (Max Z (S x) y)!
697
698 [NO TYVARS]
699
700         class Y a b | a -> b where
701             y :: a -> X b
702         
703         instance Y [[a]] a where
704             y ((x:_):_) = X x
705         
706         k :: X a -> X a -> X a
707
708         g :: Num a => [X a] -> [X a]
709         g xs = h xs
710             where
711             h ys = ys ++ map (k (y [[0]])) xs
712
713 The excitement comes when simplifying the bindings for h.  Initially
714 try to simplify {y @ [[t1]] t2, 0 @ t1}, with initial qtvs = {t2}.
715 From this we get t1:=:t2, but also various bindings.  We can't forget
716 the bindings (because of [LOOP]), but in fact t1 is what g is
717 polymorphic in.  
718
719 The net effect of [NO TYVARS] 
720
721 \begin{code}
722 isFreeWhenInferring :: TyVarSet -> Inst -> Bool
723 isFreeWhenInferring qtvs inst
724   =  isFreeWrtTyVars qtvs inst          -- Constrains no quantified vars
725   && isInheritableInst inst             -- And no implicit parameter involved
726                                         -- (see "Notes on implicit parameters")
727
728 isFreeWhenChecking :: TyVarSet  -- Quantified tyvars
729                    -> NameSet   -- Quantified implicit parameters
730                    -> Inst -> Bool
731 isFreeWhenChecking qtvs ips inst
732   =  isFreeWrtTyVars qtvs inst
733   && isFreeWrtIPs    ips inst
734
735 isFreeWrtTyVars qtvs inst = not (tyVarsOfInst inst `intersectsVarSet` qtvs)
736 isFreeWrtIPs     ips inst = not (any (`elemNameSet` ips) (ipNamesOfInst inst))
737 \end{code}
738
739
740 %************************************************************************
741 %*                                                                      *
742 \subsection{tcSimplifyCheck}
743 %*                                                                      *
744 %************************************************************************
745
746 @tcSimplifyCheck@ is used when we know exactly the set of variables
747 we are going to quantify over.  For example, a class or instance declaration.
748
749 \begin{code}
750 tcSimplifyCheck
751          :: SDoc
752          -> [TcTyVar]           -- Quantify over these
753          -> [Inst]              -- Given
754          -> [Inst]              -- Wanted
755          -> TcM TcDictBinds     -- Bindings
756
757 -- tcSimplifyCheck is used when checking expression type signatures,
758 -- class decls, instance decls etc.
759 --
760 -- NB: tcSimplifyCheck does not consult the
761 --      global type variables in the environment; so you don't
762 --      need to worry about setting them before calling tcSimplifyCheck
763 tcSimplifyCheck doc qtvs givens wanted_lie
764   = tcSimplCheck doc get_qtvs
765                  givens wanted_lie      `thenM` \ (qtvs', binds) ->
766     returnM binds
767   where
768     get_qtvs = zonkTcTyVarsAndFV qtvs
769
770
771 -- tcSimplifyInferCheck is used when we know the constraints we are to simplify
772 -- against, but we don't know the type variables over which we are going to quantify.
773 -- This happens when we have a type signature for a mutually recursive group
774 tcSimplifyInferCheck
775          :: SDoc
776          -> TcTyVarSet          -- fv(T)
777          -> [Inst]              -- Given
778          -> [Inst]              -- Wanted
779          -> TcM ([TcTyVar],     -- Variables over which to quantify
780                  TcDictBinds)   -- Bindings
781
782 tcSimplifyInferCheck doc tau_tvs givens wanted_lie
783   = tcSimplCheck doc get_qtvs givens wanted_lie
784   where
785         -- Figure out which type variables to quantify over
786         -- You might think it should just be the signature tyvars,
787         -- but in bizarre cases you can get extra ones
788         --      f :: forall a. Num a => a -> a
789         --      f x = fst (g (x, head [])) + 1
790         --      g a b = (b,a)
791         -- Here we infer g :: forall a b. a -> b -> (b,a)
792         -- We don't want g to be monomorphic in b just because
793         -- f isn't quantified over b.
794     all_tvs = varSetElems (tau_tvs `unionVarSet` tyVarsOfInsts givens)
795
796     get_qtvs = zonkTcTyVarsAndFV all_tvs        `thenM` \ all_tvs' ->
797                tcGetGlobalTyVars                `thenM` \ gbl_tvs ->
798                let
799                   qtvs = all_tvs' `minusVarSet` gbl_tvs
800                         -- We could close gbl_tvs, but its not necessary for
801                         -- soundness, and it'll only affect which tyvars, not which
802                         -- dictionaries, we quantify over
803                in
804                returnM qtvs
805 \end{code}
806
807 Here is the workhorse function for all three wrappers.
808
809 \begin{code}
810 tcSimplCheck doc get_qtvs givens wanted_lie
811   = check_loop givens wanted_lie        `thenM` \ (qtvs, frees, binds, irreds) ->
812
813         -- Complain about any irreducible ones
814     mappM zonkInst given_dicts_and_ips                          `thenM` \ givens' ->
815     groupErrs (addNoInstanceErrs (Just doc) givens') irreds     `thenM_`
816
817         -- Done
818     extendLIEs frees            `thenM_`
819     returnM (qtvs, binds)
820
821   where
822     given_dicts_and_ips = filter (not . isMethod) givens
823         -- For error reporting, filter out methods, which are 
824         -- only added to the given set as an optimisation
825
826     ip_set = mkNameSet (ipNamesOfInsts givens)
827
828     check_loop givens wanteds
829       =         -- Step 1
830         mappM zonkInst givens   `thenM` \ givens' ->
831         mappM zonkInst wanteds  `thenM` \ wanteds' ->
832         get_qtvs                `thenM` \ qtvs' ->
833
834                     -- Step 2
835         let
836             -- When checking against a given signature we always reduce
837             -- until we find a match against something given, or can't reduce
838             try_me inst | isFreeWhenChecking qtvs' ip_set inst = Free
839                         | otherwise                            = ReduceMe
840         in
841         reduceContext doc try_me givens' wanteds'       `thenM` \ (no_improvement, frees, binds, irreds) ->
842
843                     -- Step 3
844         if no_improvement then
845             returnM (varSetElems qtvs', frees, binds, irreds)
846         else
847             check_loop givens' (irreds ++ frees)        `thenM` \ (qtvs', frees1, binds1, irreds1) ->
848             returnM (qtvs', frees1, binds `unionBags` binds1, irreds1)
849 \end{code}
850
851
852 %************************************************************************
853 %*                                                                      *
854 \subsection{tcSimplifyRestricted}
855 %*                                                                      *
856 %************************************************************************
857
858 tcSimplifyRestricted infers which type variables to quantify for a 
859 group of restricted bindings.  This isn't trivial.
860
861 Eg1:    id = \x -> x
862         We want to quantify over a to get id :: forall a. a->a
863         
864 Eg2:    eq = (==)
865         We do not want to quantify over a, because there's an Eq a 
866         constraint, so we get eq :: a->a->Bool  (notice no forall)
867
868 So, assume:
869         RHS has type 'tau', whose free tyvars are tau_tvs
870         RHS has constraints 'wanteds'
871
872 Plan A (simple)
873   Quantify over (tau_tvs \ ftvs(wanteds))
874   This is bad. The constraints may contain (Monad (ST s))
875   where we have         instance Monad (ST s) where...
876   so there's no need to be monomorphic in s!
877
878   Also the constraint might be a method constraint,
879   whose type mentions a perfectly innocent tyvar:
880           op :: Num a => a -> b -> a
881   Here, b is unconstrained.  A good example would be
882         foo = op (3::Int)
883   We want to infer the polymorphic type
884         foo :: forall b. b -> b
885
886
887 Plan B (cunning, used for a long time up to and including GHC 6.2)
888   Step 1: Simplify the constraints as much as possible (to deal 
889   with Plan A's problem).  Then set
890         qtvs = tau_tvs \ ftvs( simplify( wanteds ) )
891
892   Step 2: Now simplify again, treating the constraint as 'free' if 
893   it does not mention qtvs, and trying to reduce it otherwise.
894   The reasons for this is to maximise sharing.
895
896   This fails for a very subtle reason.  Suppose that in the Step 2
897   a constraint (Foo (Succ Zero) (Succ Zero) b) gets thrown upstairs as 'free'.
898   In the Step 1 this constraint might have been simplified, perhaps to
899   (Foo Zero Zero b), AND THEN THAT MIGHT BE IMPROVED, to bind 'b' to 'T'.
900   This won't happen in Step 2... but that in turn might prevent some other
901   constraint mentioning 'b' from being simplified... and that in turn
902   breaks the invariant that no constraints are quantified over.
903
904   Test typecheck/should_compile/tc177 (which failed in GHC 6.2) demonstrates
905   the problem.
906
907
908 Plan C (brutal)
909   Step 1: Simplify the constraints as much as possible (to deal 
910   with Plan A's problem).  Then set
911         qtvs = tau_tvs \ ftvs( simplify( wanteds ) )
912   Return the bindings from Step 1.
913   
914
915 A note about Plan C (arising from "bug" reported by George Russel March 2004)
916 Consider this:
917
918       instance (HasBinary ty IO) => HasCodedValue ty
919
920       foo :: HasCodedValue a => String -> IO a
921
922       doDecodeIO :: HasCodedValue a => () -> () -> IO a
923       doDecodeIO codedValue view  
924         = let { act = foo "foo" } in  act
925
926 You might think this should work becuase the call to foo gives rise to a constraint
927 (HasCodedValue t), which can be satisfied by the type sig for doDecodeIO.  But the
928 restricted binding act = ... calls tcSimplifyRestricted, and PlanC simplifies the
929 constraint using the (rather bogus) instance declaration, and now we are stuffed.
930 I claim this is not really a bug.  
931
932 \begin{code}
933 tcSimplifyRestricted    -- Used for restricted binding groups
934                         -- i.e. ones subject to the monomorphism restriction
935         :: SDoc
936         -> TcTyVarSet           -- Free in the type of the RHSs
937         -> [Inst]               -- Free in the RHSs
938         -> TcM ([TcTyVar],      -- Tyvars to quantify (zonked)
939                 TcDictBinds)    -- Bindings
940         -- tcSimpifyRestricted returns no constraints to
941         -- quantify over; by definition there are none.
942         -- They are all thrown back in the LIE
943
944 tcSimplifyRestricted doc tau_tvs wanteds
945         -- 'reduceMe': Reduce as far as we can.  Don't stop at
946         -- dicts; the idea is to get rid of as many type
947         -- variables as possible, and we don't want to stop
948         -- at (say) Monad (ST s), because that reduces
949         -- immediately, with no constraint on s.
950   = simpleReduceLoop doc reduceMe wanteds       `thenM` \ (frees, binds, irreds) ->
951     ASSERT( null frees )
952
953         -- Next, figure out the tyvars we will quantify over
954     zonkTcTyVarsAndFV (varSetElems tau_tvs)     `thenM` \ tau_tvs' ->
955     tcGetGlobalTyVars                           `thenM` \ gbl_tvs ->
956     let
957         constrained_tvs = tyVarsOfInsts irreds
958         qtvs = (tau_tvs' `minusVarSet` constrained_tvs)
959                          `minusVarSet` oclose (fdPredsOfInsts irreds) gbl_tvs
960                 -- The second minusVarSet arranges not to quantify over
961                 -- any tyvars that are functionally determined by ones in
962                 -- the environment
963     in
964     traceTc (text "tcSimplifyRestricted" <+> vcat [
965                 pprInsts wanteds, pprInsts frees, pprInsts irreds,
966                 pprLHsBinds binds,
967                 ppr constrained_tvs, ppr tau_tvs', ppr qtvs ])  `thenM_`
968
969     extendLIEs irreds                                           `thenM_`
970     returnM (varSetElems qtvs, binds)
971 \end{code}
972
973
974 %************************************************************************
975 %*                                                                      *
976 \subsection{tcSimplifyToDicts}
977 %*                                                                      *
978 %************************************************************************
979
980 On the LHS of transformation rules we only simplify methods and constants,
981 getting dictionaries.  We want to keep all of them unsimplified, to serve
982 as the available stuff for the RHS of the rule.
983
984 The same thing is used for specialise pragmas. Consider
985
986         f :: Num a => a -> a
987         {-# SPECIALISE f :: Int -> Int #-}
988         f = ...
989
990 The type checker generates a binding like:
991
992         f_spec = (f :: Int -> Int)
993
994 and we want to end up with
995
996         f_spec = _inline_me_ (f Int dNumInt)
997
998 But that means that we must simplify the Method for f to (f Int dNumInt)!
999 So tcSimplifyToDicts squeezes out all Methods.
1000
1001 IMPORTANT NOTE:  we *don't* want to do superclass commoning up.  Consider
1002
1003         fromIntegral :: (Integral a, Num b) => a -> b
1004         {-# RULES "foo"  fromIntegral = id :: Int -> Int #-}
1005
1006 Here, a=b=Int, and Num Int is a superclass of Integral Int. But we *dont*
1007 want to get
1008
1009         forall dIntegralInt.
1010         fromIntegral Int Int dIntegralInt (scsel dIntegralInt) = id Int
1011
1012 because the scsel will mess up matching.  Instead we want
1013
1014         forall dIntegralInt, dNumInt.
1015         fromIntegral Int Int dIntegralInt dNumInt = id Int
1016
1017 Hence "DontReduce NoSCs"
1018
1019 \begin{code}
1020 tcSimplifyToDicts :: [Inst] -> TcM (TcDictBinds)
1021 tcSimplifyToDicts wanteds
1022   = simpleReduceLoop doc try_me wanteds         `thenM` \ (frees, binds, irreds) ->
1023         -- Since try_me doesn't look at types, we don't need to
1024         -- do any zonking, so it's safe to call reduceContext directly
1025     ASSERT( null frees )
1026     extendLIEs irreds           `thenM_`
1027     returnM binds
1028
1029   where
1030     doc = text "tcSimplifyToDicts"
1031
1032         -- Reduce methods and lits only; stop as soon as we get a dictionary
1033     try_me inst | isDict inst = DontReduce NoSCs        -- See notes above for why NoSCs
1034                 | otherwise   = ReduceMe
1035 \end{code}
1036
1037
1038
1039 tcSimplifyBracket is used when simplifying the constraints arising from
1040 a Template Haskell bracket [| ... |].  We want to check that there aren't
1041 any constraints that can't be satisfied (e.g. Show Foo, where Foo has no
1042 Show instance), but we aren't otherwise interested in the results.
1043 Nor do we care about ambiguous dictionaries etc.  We will type check
1044 this bracket again at its usage site.
1045
1046 \begin{code}
1047 tcSimplifyBracket :: [Inst] -> TcM ()
1048 tcSimplifyBracket wanteds
1049   = simpleReduceLoop doc reduceMe wanteds       `thenM_`
1050     returnM ()
1051   where
1052     doc = text "tcSimplifyBracket"
1053 \end{code}
1054
1055
1056 %************************************************************************
1057 %*                                                                      *
1058 \subsection{Filtering at a dynamic binding}
1059 %*                                                                      *
1060 %************************************************************************
1061
1062 When we have
1063         let ?x = R in B
1064
1065 we must discharge all the ?x constraints from B.  We also do an improvement
1066 step; if we have ?x::t1 and ?x::t2 we must unify t1, t2.
1067
1068 Actually, the constraints from B might improve the types in ?x. For example
1069
1070         f :: (?x::Int) => Char -> Char
1071         let ?x = 3 in f 'c'
1072
1073 then the constraint (?x::Int) arising from the call to f will
1074 force the binding for ?x to be of type Int.
1075
1076 \begin{code}
1077 tcSimplifyIPs :: [Inst]         -- The implicit parameters bound here
1078               -> [Inst]         -- Wanted
1079               -> TcM TcDictBinds
1080 tcSimplifyIPs given_ips wanteds
1081   = simpl_loop given_ips wanteds        `thenM` \ (frees, binds) ->
1082     extendLIEs frees                    `thenM_`
1083     returnM binds
1084   where
1085     doc      = text "tcSimplifyIPs" <+> ppr given_ips
1086     ip_set   = mkNameSet (ipNamesOfInsts given_ips)
1087
1088         -- Simplify any methods that mention the implicit parameter
1089     try_me inst | isFreeWrtIPs ip_set inst = Free
1090                 | otherwise                = ReduceMe
1091
1092     simpl_loop givens wanteds
1093       = mappM zonkInst givens           `thenM` \ givens' ->
1094         mappM zonkInst wanteds          `thenM` \ wanteds' ->
1095
1096         reduceContext doc try_me givens' wanteds'    `thenM` \ (no_improvement, frees, binds, irreds) ->
1097
1098         if no_improvement then
1099             ASSERT( null irreds )
1100             returnM (frees, binds)
1101         else
1102             simpl_loop givens' (irreds ++ frees)        `thenM` \ (frees1, binds1) ->
1103             returnM (frees1, binds `unionBags` binds1)
1104 \end{code}
1105
1106
1107 %************************************************************************
1108 %*                                                                      *
1109 \subsection[binds-for-local-funs]{@bindInstsOfLocalFuns@}
1110 %*                                                                      *
1111 %************************************************************************
1112
1113 When doing a binding group, we may have @Insts@ of local functions.
1114 For example, we might have...
1115 \begin{verbatim}
1116 let f x = x + 1     -- orig local function (overloaded)
1117     f.1 = f Int     -- two instances of f
1118     f.2 = f Float
1119  in
1120     (f.1 5, f.2 6.7)
1121 \end{verbatim}
1122 The point is: we must drop the bindings for @f.1@ and @f.2@ here,
1123 where @f@ is in scope; those @Insts@ must certainly not be passed
1124 upwards towards the top-level.  If the @Insts@ were binding-ified up
1125 there, they would have unresolvable references to @f@.
1126
1127 We pass in an @init_lie@ of @Insts@ and a list of locally-bound @Ids@.
1128 For each method @Inst@ in the @init_lie@ that mentions one of the
1129 @Ids@, we create a binding.  We return the remaining @Insts@ (in an
1130 @LIE@), as well as the @HsBinds@ generated.
1131
1132 \begin{code}
1133 bindInstsOfLocalFuns :: [Inst] -> [TcId] -> TcM (LHsBinds TcId)
1134
1135 bindInstsOfLocalFuns wanteds local_ids
1136   | null overloaded_ids
1137         -- Common case
1138   = extendLIEs wanteds          `thenM_`
1139     returnM emptyBag
1140
1141   | otherwise
1142   = simpleReduceLoop doc try_me wanteds         `thenM` \ (frees, binds, irreds) ->
1143     ASSERT( null irreds )
1144     extendLIEs frees            `thenM_`
1145     returnM binds
1146   where
1147     doc              = text "bindInsts" <+> ppr local_ids
1148     overloaded_ids   = filter is_overloaded local_ids
1149     is_overloaded id = isOverloadedTy (idType id)
1150
1151     overloaded_set = mkVarSet overloaded_ids    -- There can occasionally be a lot of them
1152                                                 -- so it's worth building a set, so that
1153                                                 -- lookup (in isMethodFor) is faster
1154
1155     try_me inst | isMethodFor overloaded_set inst = ReduceMe
1156                 | otherwise                       = Free
1157 \end{code}
1158
1159
1160 %************************************************************************
1161 %*                                                                      *
1162 \subsection{Data types for the reduction mechanism}
1163 %*                                                                      *
1164 %************************************************************************
1165
1166 The main control over context reduction is here
1167
1168 \begin{code}
1169 data WhatToDo
1170  = ReduceMe             -- Try to reduce this
1171                         -- If there's no instance, behave exactly like
1172                         -- DontReduce: add the inst to
1173                         -- the irreductible ones, but don't
1174                         -- produce an error message of any kind.
1175                         -- It might be quite legitimate such as (Eq a)!
1176
1177  | DontReduce WantSCs           -- Return as irreducible
1178
1179  | DontReduceUnlessConstant     -- Return as irreducible unless it can
1180                                 -- be reduced to a constant in one step
1181
1182  | Free                   -- Return as free
1183
1184 reduceMe :: Inst -> WhatToDo
1185 reduceMe inst = ReduceMe
1186
1187 data WantSCs = NoSCs | AddSCs   -- Tells whether we should add the superclasses
1188                                 -- of a predicate when adding it to the avails
1189 \end{code}
1190
1191
1192
1193 \begin{code}
1194 type Avails = FiniteMap Inst Avail
1195
1196 data Avail
1197   = IsFree              -- Used for free Insts
1198   | Irred               -- Used for irreducible dictionaries,
1199                         -- which are going to be lambda bound
1200
1201   | Given TcId          -- Used for dictionaries for which we have a binding
1202                         -- e.g. those "given" in a signature
1203           Bool          -- True <=> actually consumed (splittable IPs only)
1204
1205   | NoRhs               -- Used for Insts like (CCallable f)
1206                         -- where no witness is required.
1207                         -- ToDo: remove?
1208
1209   | Rhs                 -- Used when there is a RHS
1210         (LHsExpr TcId)  -- The RHS
1211         [Inst]          -- Insts free in the RHS; we need these too
1212
1213   | Linear              -- Splittable Insts only.
1214         Int             -- The Int is always 2 or more; indicates how
1215                         -- many copies are required
1216         Inst            -- The splitter
1217         Avail           -- Where the "master copy" is
1218
1219   | LinRhss             -- Splittable Insts only; this is used only internally
1220                         --      by extractResults, where a Linear 
1221                         --      is turned into an LinRhss
1222         [LHsExpr TcId]  -- A supply of suitable RHSs
1223
1224 pprAvails avails = vcat [sep [ppr inst, nest 2 (equals <+> pprAvail avail)]
1225                         | (inst,avail) <- fmToList avails ]
1226
1227 instance Outputable Avail where
1228     ppr = pprAvail
1229
1230 pprAvail NoRhs          = text "<no rhs>"
1231 pprAvail IsFree         = text "Free"
1232 pprAvail Irred          = text "Irred"
1233 pprAvail (Given x b)    = text "Given" <+> ppr x <+> 
1234                           if b then text "(used)" else empty
1235 pprAvail (Rhs rhs bs)   = text "Rhs" <+> ppr rhs <+> braces (ppr bs)
1236 pprAvail (Linear n i a) = text "Linear" <+> ppr n <+> braces (ppr i) <+> ppr a
1237 pprAvail (LinRhss rhss) = text "LinRhss" <+> ppr rhss
1238 \end{code}
1239
1240 Extracting the bindings from a bunch of Avails.
1241 The bindings do *not* come back sorted in dependency order.
1242 We assume that they'll be wrapped in a big Rec, so that the
1243 dependency analyser can sort them out later
1244
1245 The loop startes
1246 \begin{code}
1247 extractResults :: Avails
1248                -> [Inst]                -- Wanted
1249                -> TcM (TcDictBinds,     -- Bindings
1250                         [Inst],         -- Irreducible ones
1251                         [Inst])         -- Free ones
1252
1253 extractResults avails wanteds
1254   = go avails emptyBag [] [] wanteds
1255   where
1256     go avails binds irreds frees [] 
1257       = returnM (binds, irreds, frees)
1258
1259     go avails binds irreds frees (w:ws)
1260       = case lookupFM avails w of
1261           Nothing    -> pprTrace "Urk: extractResults" (ppr w) $
1262                         go avails binds irreds frees ws
1263
1264           Just NoRhs  -> go avails               binds irreds     frees     ws
1265           Just IsFree -> go (add_free avails w)  binds irreds     (w:frees) ws
1266           Just Irred  -> go (add_given avails w) binds (w:irreds) frees     ws
1267
1268           Just (Given id _) -> go avails new_binds irreds frees ws
1269                             where
1270                                new_binds | id == instToId w = binds
1271                                          | otherwise        = addBind binds w (L (instSpan w) (HsVar id))
1272                 -- The sought Id can be one of the givens, via a superclass chain
1273                 -- and then we definitely don't want to generate an x=x binding!
1274
1275           Just (Rhs rhs ws') -> go (add_given avails w) new_binds irreds frees (ws' ++ ws)
1276                              where
1277                                 new_binds = addBind binds w rhs
1278
1279           Just (Linear n split_inst avail)      -- Transform Linear --> LinRhss
1280             -> get_root irreds frees avail w            `thenM` \ (irreds', frees', root_id) ->
1281                split n (instToId split_inst) root_id w  `thenM` \ (binds', rhss) ->
1282                go (addToFM avails w (LinRhss rhss))
1283                   (binds `unionBags` binds')
1284                   irreds' frees' (split_inst : w : ws)
1285
1286           Just (LinRhss (rhs:rhss))             -- Consume one of the Rhss
1287                 -> go new_avails new_binds irreds frees ws
1288                 where           
1289                    new_binds  = addBind binds w rhs
1290                    new_avails = addToFM avails w (LinRhss rhss)
1291
1292     get_root irreds frees (Given id _) w = returnM (irreds, frees, id)
1293     get_root irreds frees Irred        w = cloneDict w  `thenM` \ w' ->
1294                                            returnM (w':irreds, frees, instToId w')
1295     get_root irreds frees IsFree       w = cloneDict w  `thenM` \ w' ->
1296                                            returnM (irreds, w':frees, instToId w')
1297
1298     add_given avails w 
1299         | instBindingRequired w = addToFM avails w (Given (instToId w) True)
1300         | otherwise             = addToFM avails w NoRhs
1301         -- NB: make sure that CCallable/CReturnable use NoRhs rather
1302         --      than Given, else we end up with bogus bindings.
1303
1304     add_free avails w | isMethod w = avails
1305                       | otherwise  = add_given avails w
1306         -- NB: Hack alert!  
1307         -- Do *not* replace Free by Given if it's a method.
1308         -- The following situation shows why this is bad:
1309         --      truncate :: forall a. RealFrac a => forall b. Integral b => a -> b
1310         -- From an application (truncate f i) we get
1311         --      t1 = truncate at f
1312         --      t2 = t1 at i
1313         -- If we have also have a second occurrence of truncate, we get
1314         --      t3 = truncate at f
1315         --      t4 = t3 at i
1316         -- When simplifying with i,f free, we might still notice that
1317         --   t1=t3; but alas, the binding for t2 (which mentions t1)
1318         --   will continue to float out!
1319         -- (split n i a) returns: n rhss
1320         --                        auxiliary bindings
1321         --                        1 or 0 insts to add to irreds
1322
1323
1324 split :: Int -> TcId -> TcId -> Inst 
1325       -> TcM (TcDictBinds, [LHsExpr TcId])
1326 -- (split n split_id root_id wanted) returns
1327 --      * a list of 'n' expressions, all of which witness 'avail'
1328 --      * a bunch of auxiliary bindings to support these expressions
1329 --      * one or zero insts needed to witness the whole lot
1330 --        (maybe be zero if the initial Inst is a Given)
1331 --
1332 -- NB: 'wanted' is just a template
1333
1334 split n split_id root_id wanted
1335   = go n
1336   where
1337     ty      = linearInstType wanted
1338     pair_ty = mkTyConApp pairTyCon [ty,ty]
1339     id      = instToId wanted
1340     occ     = getOccName id
1341     loc     = getSrcLoc id
1342     span    = instSpan wanted
1343
1344     go 1 = returnM (emptyBag, [L span $ HsVar root_id])
1345
1346     go n = go ((n+1) `div` 2)           `thenM` \ (binds1, rhss) ->
1347            expand n rhss                `thenM` \ (binds2, rhss') ->
1348            returnM (binds1 `unionBags` binds2, rhss')
1349
1350         -- (expand n rhss) 
1351         -- Given ((n+1)/2) rhss, make n rhss, using auxiliary bindings
1352         --  e.g.  expand 3 [rhs1, rhs2]
1353         --        = ( { x = split rhs1 },
1354         --            [fst x, snd x, rhs2] )
1355     expand n rhss
1356         | n `rem` 2 == 0 = go rhss      -- n is even
1357         | otherwise      = go (tail rhss)       `thenM` \ (binds', rhss') ->
1358                            returnM (binds', head rhss : rhss')
1359         where
1360           go rhss = mapAndUnzipM do_one rhss    `thenM` \ (binds', rhss') ->
1361                     returnM (listToBag binds', concat rhss')
1362
1363           do_one rhs = newUnique                        `thenM` \ uniq -> 
1364                        tcLookupId fstName               `thenM` \ fst_id ->
1365                        tcLookupId sndName               `thenM` \ snd_id ->
1366                        let 
1367                           x = mkUserLocal occ uniq pair_ty loc
1368                        in
1369                        returnM (L span (VarBind x (mk_app span split_id rhs)),
1370                                 [mk_fs_app span fst_id ty x, mk_fs_app span snd_id ty x])
1371
1372 mk_fs_app span id ty var = L span (HsVar id) `mkHsTyApp` [ty,ty] `mkHsApp` (L span (HsVar var))
1373
1374 mk_app span id rhs = L span (HsApp (L span (HsVar id)) rhs)
1375
1376 addBind binds inst rhs = binds `unionBags` unitBag (L (instLocSrcSpan (instLoc inst)) 
1377                                                       (VarBind (instToId inst) rhs))
1378 instSpan wanted = instLocSrcSpan (instLoc wanted)
1379 \end{code}
1380
1381
1382 %************************************************************************
1383 %*                                                                      *
1384 \subsection[reduce]{@reduce@}
1385 %*                                                                      *
1386 %************************************************************************
1387
1388 When the "what to do" predicate doesn't depend on the quantified type variables,
1389 matters are easier.  We don't need to do any zonking, unless the improvement step
1390 does something, in which case we zonk before iterating.
1391
1392 The "given" set is always empty.
1393
1394 \begin{code}
1395 simpleReduceLoop :: SDoc
1396                  -> (Inst -> WhatToDo)          -- What to do, *not* based on the quantified type variables
1397                  -> [Inst]                      -- Wanted
1398                  -> TcM ([Inst],                -- Free
1399                          TcDictBinds,
1400                          [Inst])                -- Irreducible
1401
1402 simpleReduceLoop doc try_me wanteds
1403   = mappM zonkInst wanteds                      `thenM` \ wanteds' ->
1404     reduceContext doc try_me [] wanteds'        `thenM` \ (no_improvement, frees, binds, irreds) ->
1405     if no_improvement then
1406         returnM (frees, binds, irreds)
1407     else
1408         simpleReduceLoop doc try_me (irreds ++ frees)   `thenM` \ (frees1, binds1, irreds1) ->
1409         returnM (frees1, binds `unionBags` binds1, irreds1)
1410 \end{code}
1411
1412
1413
1414 \begin{code}
1415 reduceContext :: SDoc
1416               -> (Inst -> WhatToDo)
1417               -> [Inst]                 -- Given
1418               -> [Inst]                 -- Wanted
1419               -> TcM (Bool,             -- True <=> improve step did no unification
1420                          [Inst],        -- Free
1421                          TcDictBinds,   -- Dictionary bindings
1422                          [Inst])        -- Irreducible
1423
1424 reduceContext doc try_me givens wanteds
1425   =
1426     traceTc (text "reduceContext" <+> (vcat [
1427              text "----------------------",
1428              doc,
1429              text "given" <+> ppr givens,
1430              text "wanted" <+> ppr wanteds,
1431              text "----------------------"
1432              ]))                                        `thenM_`
1433
1434         -- Build the Avail mapping from "givens"
1435     foldlM addGiven emptyFM givens                      `thenM` \ init_state ->
1436
1437         -- Do the real work
1438     reduceList (0,[]) try_me wanteds init_state         `thenM` \ avails ->
1439
1440         -- Do improvement, using everything in avails
1441         -- In particular, avails includes all superclasses of everything
1442     tcImprove avails                                    `thenM` \ no_improvement ->
1443
1444     extractResults avails wanteds                       `thenM` \ (binds, irreds, frees) ->
1445
1446     traceTc (text "reduceContext end" <+> (vcat [
1447              text "----------------------",
1448              doc,
1449              text "given" <+> ppr givens,
1450              text "wanted" <+> ppr wanteds,
1451              text "----",
1452              text "avails" <+> pprAvails avails,
1453              text "frees" <+> ppr frees,
1454              text "no_improvement =" <+> ppr no_improvement,
1455              text "----------------------"
1456              ]))                                        `thenM_`
1457
1458     returnM (no_improvement, frees, binds, irreds)
1459
1460 tcImprove :: Avails -> TcM Bool         -- False <=> no change
1461 -- Perform improvement using all the predicates in Avails
1462 tcImprove avails
1463  =  tcGetInstEnvs                       `thenM` \ (home_ie, pkg_ie) ->
1464     let
1465         preds = [ (pred, pp_loc)
1466                 | inst <- keysFM avails,
1467                   let pp_loc = pprInstLoc (instLoc inst),
1468                   pred <- fdPredsOfInst inst
1469                 ]
1470                 -- Avails has all the superclasses etc (good)
1471                 -- It also has all the intermediates of the deduction (good)
1472                 -- It does not have duplicates (good)
1473                 -- NB that (?x::t1) and (?x::t2) will be held separately in avails
1474                 --    so that improve will see them separate
1475         eqns = improve get_insts preds
1476         get_insts clas = classInstances home_ie clas ++ classInstances pkg_ie clas
1477      in
1478      if null eqns then
1479         returnM True
1480      else
1481         traceTc (ptext SLIT("Improve:") <+> vcat (map pprEquationDoc eqns))     `thenM_`
1482         mappM_ unify eqns       `thenM_`
1483         returnM False
1484   where
1485     unify ((qtvs, t1, t2), doc)
1486          = addErrCtxt doc                               $
1487            tcInstTyVars VanillaTv (varSetElems qtvs)    `thenM` \ (_, _, tenv) ->
1488            unifyTauTy (substTy tenv t1) (substTy tenv t2)
1489 \end{code}
1490
1491 The main context-reduction function is @reduce@.  Here's its game plan.
1492
1493 \begin{code}
1494 reduceList :: (Int,[Inst])              -- Stack (for err msgs)
1495                                         -- along with its depth
1496            -> (Inst -> WhatToDo)
1497            -> [Inst]
1498            -> Avails
1499            -> TcM Avails
1500 \end{code}
1501
1502 @reduce@ is passed
1503      try_me:    given an inst, this function returns
1504                   Reduce       reduce this
1505                   DontReduce   return this in "irreds"
1506                   Free         return this in "frees"
1507
1508      wanteds:   The list of insts to reduce
1509      state:     An accumulating parameter of type Avails
1510                 that contains the state of the algorithm
1511
1512   It returns a Avails.
1513
1514 The (n,stack) pair is just used for error reporting.
1515 n is always the depth of the stack.
1516 The stack is the stack of Insts being reduced: to produce X
1517 I had to produce Y, to produce Y I had to produce Z, and so on.
1518
1519 \begin{code}
1520 reduceList (n,stack) try_me wanteds state
1521   | n > opt_MaxContextReductionDepth
1522   = failWithTc (reduceDepthErr n stack)
1523
1524   | otherwise
1525   =
1526 #ifdef DEBUG
1527    (if n > 8 then
1528         pprTrace "Interesting! Context reduction stack deeper than 8:" 
1529                  (nest 2 (pprStack stack))
1530     else (\x->x))
1531 #endif
1532     go wanteds state
1533   where
1534     go []     state = returnM state
1535     go (w:ws) state = reduce (n+1, w:stack) try_me w state      `thenM` \ state' ->
1536                       go ws state'
1537
1538     -- Base case: we're done!
1539 reduce stack try_me wanted avails
1540     -- It's the same as an existing inst, or a superclass thereof
1541   | Just avail <- isAvailable avails wanted
1542   = if isLinearInst wanted then
1543         addLinearAvailable avails avail wanted  `thenM` \ (avails', wanteds') ->
1544         reduceList stack try_me wanteds' avails'
1545     else
1546         returnM avails          -- No op for non-linear things
1547
1548   | otherwise
1549   = case try_me wanted of {
1550
1551       DontReduce want_scs -> addIrred want_scs avails wanted
1552
1553     ; DontReduceUnlessConstant ->    -- It's irreducible (or at least should not be reduced)
1554                                      -- First, see if the inst can be reduced to a constant in one step
1555         try_simple (addIrred AddSCs)    -- Assume want superclasses
1556
1557     ; Free ->   -- It's free so just chuck it upstairs
1558                 -- First, see if the inst can be reduced to a constant in one step
1559         try_simple addFree
1560
1561     ; ReduceMe ->               -- It should be reduced
1562         lookupInst wanted             `thenM` \ lookup_result ->
1563         case lookup_result of
1564             GenInst wanteds' rhs -> addIrred NoSCs avails wanted                `thenM` \ avails1 ->
1565                                     reduceList stack try_me wanteds' avails1    `thenM` \ avails2 ->
1566                                     addWanted avails2 wanted rhs wanteds'
1567                 -- Experiment with temporarily doing addIrred *before* the reduceList, 
1568                 -- which has the effect of adding the thing we are trying
1569                 -- to prove to the database before trying to prove the things it
1570                 -- needs.  See note [RECURSIVE DICTIONARIES]
1571                 -- NB: we must not do an addWanted before, because that adds the
1572                 --     superclasses too, and thaat can lead to a spurious loop; see
1573                 --     the examples in [SUPERCLASS-LOOP]
1574                 -- So we do an addIrred before, and then overwrite it afterwards with addWanted
1575
1576             SimpleInst rhs       -> addWanted avails wanted rhs []
1577
1578             NoInstance ->    -- No such instance!
1579                              -- Add it and its superclasses
1580                              addIrred AddSCs avails wanted
1581     }
1582   where
1583     try_simple do_this_otherwise
1584       = lookupInst wanted         `thenM` \ lookup_result ->
1585         case lookup_result of
1586             SimpleInst rhs -> addWanted avails wanted rhs []
1587             other          -> do_this_otherwise avails wanted
1588 \end{code}
1589
1590
1591 \begin{code}
1592 -------------------------
1593 isAvailable :: Avails -> Inst -> Maybe Avail
1594 isAvailable avails wanted = lookupFM avails wanted
1595         -- NB 1: the Ord instance of Inst compares by the class/type info
1596         -- *not* by unique.  So
1597         --      d1::C Int ==  d2::C Int
1598
1599 addLinearAvailable :: Avails -> Avail -> Inst -> TcM (Avails, [Inst])
1600 addLinearAvailable avails avail wanted
1601         -- avails currently maps [wanted -> avail]
1602         -- Extend avails to reflect a neeed for an extra copy of avail
1603
1604   | Just avail' <- split_avail avail
1605   = returnM (addToFM avails wanted avail', [])
1606
1607   | otherwise
1608   = tcLookupId splitName                        `thenM` \ split_id ->
1609     tcInstClassOp (instLoc wanted) split_id 
1610                   [linearInstType wanted]       `thenM` \ split_inst ->
1611     returnM (addToFM avails wanted (Linear 2 split_inst avail), [split_inst])
1612
1613   where
1614     split_avail :: Avail -> Maybe Avail
1615         -- (Just av) if there's a modified version of avail that
1616         --           we can use to replace avail in avails
1617         -- Nothing   if there isn't, so we need to create a Linear
1618     split_avail (Linear n i a)              = Just (Linear (n+1) i a)
1619     split_avail (Given id used) | not used  = Just (Given id True)
1620                                 | otherwise = Nothing
1621     split_avail Irred                       = Nothing
1622     split_avail IsFree                      = Nothing
1623     split_avail other = pprPanic "addLinearAvailable" (ppr avail $$ ppr wanted $$ ppr avails)
1624                   
1625 -------------------------
1626 addFree :: Avails -> Inst -> TcM Avails
1627         -- When an Inst is tossed upstairs as 'free' we nevertheless add it
1628         -- to avails, so that any other equal Insts will be commoned up right
1629         -- here rather than also being tossed upstairs.  This is really just
1630         -- an optimisation, and perhaps it is more trouble that it is worth,
1631         -- as the following comments show!
1632         --
1633         -- NB: do *not* add superclasses.  If we have
1634         --      df::Floating a
1635         --      dn::Num a
1636         -- but a is not bound here, then we *don't* want to derive
1637         -- dn from df here lest we lose sharing.
1638         --
1639 addFree avails free = returnM (addToFM avails free IsFree)
1640
1641 addWanted :: Avails -> Inst -> LHsExpr TcId -> [Inst] -> TcM Avails
1642 addWanted avails wanted rhs_expr wanteds
1643   = addAvailAndSCs avails wanted avail
1644   where
1645     avail | instBindingRequired wanted = Rhs rhs_expr wanteds
1646           | otherwise                  = ASSERT( null wanteds ) NoRhs
1647
1648 addGiven :: Avails -> Inst -> TcM Avails
1649 addGiven avails given = addAvailAndSCs avails given (Given (instToId given) False)
1650         -- No ASSERT( not (given `elemFM` avails) ) because in an instance
1651         -- decl for Ord t we can add both Ord t and Eq t as 'givens', 
1652         -- so the assert isn't true
1653
1654 addIrred :: WantSCs -> Avails -> Inst -> TcM Avails
1655 addIrred NoSCs  avails irred = returnM (addToFM avails irred Irred)
1656 addIrred AddSCs avails irred = ASSERT2( not (irred `elemFM` avails), ppr irred $$ ppr avails )
1657                                addAvailAndSCs avails irred Irred
1658
1659 addAvailAndSCs :: Avails -> Inst -> Avail -> TcM Avails
1660 addAvailAndSCs avails inst avail
1661   | not (isClassDict inst) = returnM avails1
1662   | otherwise              = traceTc (text "addAvailAndSCs" <+> vcat [ppr inst, ppr deps]) `thenM_`
1663                              addSCs is_loop avails1 inst 
1664   where
1665     avails1      = addToFM avails inst avail
1666     is_loop inst = any (`tcEqType` idType (instToId inst)) dep_tys
1667                         -- Note: this compares by *type*, not by Unique
1668     deps         = findAllDeps emptyVarSet avail
1669     dep_tys      = map idType (varSetElems deps)
1670
1671     findAllDeps :: IdSet -> Avail -> IdSet
1672     -- Find all the Insts that this one depends on
1673     -- See Note [SUPERCLASS-LOOP]
1674     -- Watch out, though.  Since the avails may contain loops 
1675     -- (see Note [RECURSIVE DICTIONARIES]), so we need to track the ones we've seen so far
1676     findAllDeps so_far (Rhs _ kids) 
1677       = foldl findAllDeps
1678               (extendVarSetList so_far (map instToId kids))     -- Add the kids to so_far
1679               [a | Just a <- map (lookupFM avails) kids]        -- Find the kids' Avail
1680     findAllDeps so_far other = so_far
1681
1682
1683 addSCs :: (Inst -> Bool) -> Avails -> Inst -> TcM Avails
1684         -- Add all the superclasses of the Inst to Avails
1685         -- The first param says "dont do this because the original thing
1686         --      depends on this one, so you'd build a loop"
1687         -- Invariant: the Inst is already in Avails.
1688
1689 addSCs is_loop avails dict
1690   = newDictsFromOld dict sc_theta'      `thenM` \ sc_dicts ->
1691     foldlM add_sc avails (zipEqual "add_scs" sc_dicts sc_sels)
1692   where
1693     (clas, tys) = getDictClassTys dict
1694     (tyvars, sc_theta, sc_sels, _) = classBigSig clas
1695     sc_theta' = substTheta (mkTopTyVarSubst tyvars tys) sc_theta
1696
1697     add_sc avails (sc_dict, sc_sel)     -- Add it, and its superclasses
1698       | add_me sc_dict = addSCs is_loop avails' sc_dict
1699       | otherwise      = returnM avails
1700       where
1701         sc_sel_rhs = mkHsDictApp (mkHsTyApp (L (instSpan dict) (HsVar sc_sel)) tys) [instToId dict]
1702         avails'    = addToFM avails sc_dict (Rhs sc_sel_rhs [dict])
1703
1704     add_me :: Inst -> Bool
1705     add_me sc_dict
1706         | is_loop sc_dict = False       -- See Note [SUPERCLASS-LOOP]
1707         | otherwise       = case lookupFM avails sc_dict of
1708                                 Just (Given _ _) -> False       -- Given is cheaper than superclass selection
1709                                 other            -> True        
1710 \end{code}
1711
1712 Note [SUPERCLASS-LOOP]: Checking for loops
1713 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1714 We have to be careful here.  If we are *given* d1:Ord a,
1715 and want to deduce (d2:C [a]) where
1716
1717         class Ord a => C a where
1718         instance Ord a => C [a] where ...
1719
1720 Then we'll use the instance decl to deduce C [a] and then add the
1721 superclasses of C [a] to avails.  But we must not overwrite the binding
1722 for d1:Ord a (which is given) with a superclass selection or we'll just
1723 build a loop! 
1724
1725 Here's another variant, immortalised in tcrun020
1726         class Monad m => C1 m
1727         class C1 m => C2 m x
1728         instance C2 Maybe Bool
1729 For the instance decl we need to build (C1 Maybe), and it's no good if
1730 we run around and add (C2 Maybe Bool) and its superclasses to the avails 
1731 before we search for C1 Maybe.
1732
1733 Here's another example 
1734         class Eq b => Foo a b
1735         instance Eq a => Foo [a] a
1736 If we are reducing
1737         (Foo [t] t)
1738
1739 we'll first deduce that it holds (via the instance decl).  We must not
1740 then overwrite the Eq t constraint with a superclass selection!
1741
1742 At first I had a gross hack, whereby I simply did not add superclass constraints
1743 in addWanted, though I did for addGiven and addIrred.  This was sub-optimal,
1744 becuase it lost legitimate superclass sharing, and it still didn't do the job:
1745 I found a very obscure program (now tcrun021) in which improvement meant the
1746 simplifier got two bites a the cherry... so something seemed to be an Irred
1747 first time, but reducible next time.
1748
1749 Now we implement the Right Solution, which is to check for loops directly 
1750 when adding superclasses.  It's a bit like the occurs check in unification.
1751
1752
1753 Note [RECURSIVE DICTIONARIES]
1754 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1755 Consider 
1756     data D r = ZeroD | SuccD (r (D r));
1757     
1758     instance (Eq (r (D r))) => Eq (D r) where
1759         ZeroD     == ZeroD     = True
1760         (SuccD a) == (SuccD b) = a == b
1761         _         == _         = False;
1762     
1763     equalDC :: D [] -> D [] -> Bool;
1764     equalDC = (==);
1765
1766 We need to prove (Eq (D [])).  Here's how we go:
1767
1768         d1 : Eq (D [])
1769
1770 by instance decl, holds if
1771         d2 : Eq [D []]
1772         where   d1 = dfEqD d2
1773
1774 by instance decl of Eq, holds if
1775         d3 : D []
1776         where   d2 = dfEqList d3
1777                 d1 = dfEqD d2
1778
1779 But now we can "tie the knot" to give
1780
1781         d3 = d1
1782         d2 = dfEqList d3
1783         d1 = dfEqD d2
1784
1785 and it'll even run!  The trick is to put the thing we are trying to prove
1786 (in this case Eq (D []) into the database before trying to prove its
1787 contributing clauses.
1788         
1789
1790 %************************************************************************
1791 %*                                                                      *
1792 \section{tcSimplifyTop: defaulting}
1793 %*                                                                      *
1794 %************************************************************************
1795
1796
1797 @tcSimplifyTop@ is called once per module to simplify all the constant
1798 and ambiguous Insts.
1799
1800 We need to be careful of one case.  Suppose we have
1801
1802         instance Num a => Num (Foo a b) where ...
1803
1804 and @tcSimplifyTop@ is given a constraint (Num (Foo x y)).  Then it'll simplify
1805 to (Num x), and default x to Int.  But what about y??
1806
1807 It's OK: the final zonking stage should zap y to (), which is fine.
1808
1809
1810 \begin{code}
1811 tcSimplifyTop, tcSimplifyInteractive :: [Inst] -> TcM TcDictBinds
1812 tcSimplifyTop         wanteds = tc_simplify_top False {- Not interactive loop -} wanteds
1813 tcSimplifyInteractive wanteds = tc_simplify_top True  {- Interactive loop -}     wanteds
1814
1815
1816 -- The TcLclEnv should be valid here, solely to improve
1817 -- error message generation for the monomorphism restriction
1818 tc_simplify_top is_interactive wanteds
1819   = getLclEnv                                                   `thenM` \ lcl_env ->
1820     traceTc (text "tcSimplifyTop" <+> ppr (lclEnvElts lcl_env)) `thenM_`
1821     simpleReduceLoop (text "tcSimplTop") reduceMe wanteds       `thenM` \ (frees, binds, irreds) ->
1822     ASSERT( null frees )
1823
1824     let
1825                 -- All the non-std ones are definite errors
1826         (stds, non_stds) = partition isStdClassTyVarDict irreds
1827
1828                 -- Group by type variable
1829         std_groups = equivClasses cmp_by_tyvar stds
1830
1831                 -- Pick the ones which its worth trying to disambiguate
1832                 -- namely, the onese whose type variable isn't bound
1833                 -- up with one of the non-standard classes
1834         (std_oks, std_bads)     = partition worth_a_try std_groups
1835         worth_a_try group@(d:_) = not (non_std_tyvars `intersectsVarSet` tyVarsOfInst d)
1836         non_std_tyvars          = unionVarSets (map tyVarsOfInst non_stds)
1837
1838                 -- Collect together all the bad guys
1839         bad_guys               = non_stds ++ concat std_bads
1840         (bad_ips, non_ips)     = partition isIPDict bad_guys
1841         (no_insts, ambigs)     = partition no_inst non_ips
1842         no_inst d              = not (isTyVarDict d) 
1843         -- Previously, there was a more elaborate no_inst definition:
1844         --      no_inst d = not (isTyVarDict d) || tyVarsOfInst d `subVarSet` fixed_tvs
1845         --      fixed_tvs = oclose (fdPredsOfInsts tidy_dicts) emptyVarSet
1846         -- But that seems over-elaborate to me; it only bites for class decls with
1847         -- fundeps like this:           class C a b | -> b where ...
1848     in
1849
1850         -- Report definite errors
1851     groupErrs (addNoInstanceErrs Nothing []) no_insts   `thenM_`
1852     addTopIPErrs bad_ips                                `thenM_`
1853
1854         -- Deal with ambiguity errors, but only if
1855         -- if there has not been an error so far; errors often
1856         -- give rise to spurious ambiguous Insts
1857     ifErrsM (returnM []) (
1858         
1859         -- Complain about the ones that don't fall under
1860         -- the Haskell rules for disambiguation
1861         -- This group includes both non-existent instances
1862         --      e.g. Num (IO a) and Eq (Int -> Int)
1863         -- and ambiguous dictionaries
1864         --      e.g. Num a
1865         addTopAmbigErrs ambigs          `thenM_`
1866
1867         -- Disambiguate the ones that look feasible
1868         mappM (disambigGroup is_interactive) std_oks
1869     )                                   `thenM` \ binds_ambig ->
1870
1871     returnM (binds `unionBags` unionManyBags binds_ambig)
1872
1873 ----------------------------------
1874 d1 `cmp_by_tyvar` d2 = get_tv d1 `compare` get_tv d2
1875
1876 get_tv d   = case getDictClassTys d of
1877                    (clas, [ty]) -> tcGetTyVar "tcSimplify" ty
1878 get_clas d = case getDictClassTys d of
1879                    (clas, [ty]) -> clas
1880 \end{code}
1881
1882 If a dictionary constrains a type variable which is
1883         * not mentioned in the environment
1884         * and not mentioned in the type of the expression
1885 then it is ambiguous. No further information will arise to instantiate
1886 the type variable; nor will it be generalised and turned into an extra
1887 parameter to a function.
1888
1889 It is an error for this to occur, except that Haskell provided for
1890 certain rules to be applied in the special case of numeric types.
1891 Specifically, if
1892         * at least one of its classes is a numeric class, and
1893         * all of its classes are numeric or standard
1894 then the type variable can be defaulted to the first type in the
1895 default-type list which is an instance of all the offending classes.
1896
1897 So here is the function which does the work.  It takes the ambiguous
1898 dictionaries and either resolves them (producing bindings) or
1899 complains.  It works by splitting the dictionary list by type
1900 variable, and using @disambigOne@ to do the real business.
1901
1902 @disambigOne@ assumes that its arguments dictionaries constrain all
1903 the same type variable.
1904
1905 ADR Comment 20/6/94: I've changed the @CReturnable@ case to default to
1906 @()@ instead of @Int@.  I reckon this is the Right Thing to do since
1907 the most common use of defaulting is code like:
1908 \begin{verbatim}
1909         _ccall_ foo     `seqPrimIO` bar
1910 \end{verbatim}
1911 Since we're not using the result of @foo@, the result if (presumably)
1912 @void@.
1913
1914 \begin{code}
1915 disambigGroup :: Bool   -- True <=> simplifying at top-level interactive loop
1916               -> [Inst] -- All standard classes of form (C a)
1917               -> TcM TcDictBinds
1918
1919 disambigGroup is_interactive dicts
1920   |   any std_default_class classes     -- Guaranteed all standard classes
1921   =     -- THE DICTS OBEY THE DEFAULTABLE CONSTRAINT
1922         -- SO, TRY DEFAULT TYPES IN ORDER
1923
1924         -- Failure here is caused by there being no type in the
1925         -- default list which can satisfy all the ambiguous classes.
1926         -- For example, if Real a is reqd, but the only type in the
1927         -- default list is Int.
1928     get_default_tys                     `thenM` \ default_tys ->
1929     let
1930       try_default []    -- No defaults work, so fail
1931         = failM
1932
1933       try_default (default_ty : default_tys)
1934         = tryTcLIE_ (try_default default_tys) $ -- If default_ty fails, we try
1935                                                 -- default_tys instead
1936           tcSimplifyDefault theta               `thenM` \ _ ->
1937           returnM default_ty
1938         where
1939           theta = [mkClassPred clas [default_ty] | clas <- classes]
1940     in
1941         -- See if any default works
1942     tryM (try_default default_tys)      `thenM` \ mb_ty ->
1943     case mb_ty of
1944         Left  _                 -> bomb_out
1945         Right chosen_default_ty -> choose_default chosen_default_ty
1946
1947   | otherwise                           -- No defaults
1948   = bomb_out
1949
1950   where
1951     tyvar   = get_tv (head dicts)       -- Should be non-empty
1952     classes = map get_clas dicts
1953
1954     std_default_class cls
1955       =  isNumericClass cls
1956       || (is_interactive && 
1957           classKey cls `elem` [showClassKey, eqClassKey, ordClassKey])
1958                 -- In interactive mode, we default Show a to Show ()
1959                 -- to avoid graututious errors on "show []"
1960
1961     choose_default default_ty   -- Commit to tyvar = default_ty
1962       = -- Bind the type variable 
1963         unifyTauTy default_ty (mkTyVarTy tyvar) `thenM_`
1964         -- and reduce the context, for real this time
1965         simpleReduceLoop (text "disambig" <+> ppr dicts)
1966                      reduceMe dicts                     `thenM` \ (frees, binds, ambigs) ->
1967         WARN( not (null frees && null ambigs), ppr frees $$ ppr ambigs )
1968         warnDefault dicts default_ty                    `thenM_`
1969         returnM binds
1970
1971     bomb_out = addTopAmbigErrs dicts    `thenM_`
1972                returnM emptyBag
1973
1974 get_default_tys
1975   = do  { mb_defaults <- getDefaultTys
1976         ; case mb_defaults of
1977                 Just tys -> return tys
1978                 Nothing  ->     -- No use-supplied default;
1979                                 -- use [Integer, Double]
1980                             do { integer_ty <- tcMetaTy integerTyConName
1981                                ; return [integer_ty, doubleTy] } }
1982 \end{code}
1983
1984 [Aside - why the defaulting mechanism is turned off when
1985  dealing with arguments and results to ccalls.
1986
1987 When typechecking _ccall_s, TcExpr ensures that the external
1988 function is only passed arguments (and in the other direction,
1989 results) of a restricted set of 'native' types. This is
1990 implemented via the help of the pseudo-type classes,
1991 @CReturnable@ (CR) and @CCallable@ (CC.)
1992
1993 The interaction between the defaulting mechanism for numeric
1994 values and CC & CR can be a bit puzzling to the user at times.
1995 For example,
1996
1997     x <- _ccall_ f
1998     if (x /= 0) then
1999        _ccall_ g x
2000      else
2001        return ()
2002
2003 What type has 'x' got here? That depends on the default list
2004 in operation, if it is equal to Haskell 98's default-default
2005 of (Integer, Double), 'x' has type Double, since Integer
2006 is not an instance of CR. If the default list is equal to
2007 Haskell 1.4's default-default of (Int, Double), 'x' has type
2008 Int.
2009
2010 To try to minimise the potential for surprises here, the
2011 defaulting mechanism is turned off in the presence of
2012 CCallable and CReturnable.
2013
2014 End of aside]
2015
2016
2017 %************************************************************************
2018 %*                                                                      *
2019 \subsection[simple]{@Simple@ versions}
2020 %*                                                                      *
2021 %************************************************************************
2022
2023 Much simpler versions when there are no bindings to make!
2024
2025 @tcSimplifyThetas@ simplifies class-type constraints formed by
2026 @deriving@ declarations and when specialising instances.  We are
2027 only interested in the simplified bunch of class/type constraints.
2028
2029 It simplifies to constraints of the form (C a b c) where
2030 a,b,c are type variables.  This is required for the context of
2031 instance declarations.
2032
2033 \begin{code}
2034 tcSimplifyDeriv :: [TyVar]      
2035                 -> ThetaType            -- Wanted
2036                 -> TcM ThetaType        -- Needed
2037
2038 tcSimplifyDeriv tyvars theta
2039   = tcInstTyVars VanillaTv tyvars                       `thenM` \ (tvs, _, tenv) ->
2040         -- The main loop may do unification, and that may crash if 
2041         -- it doesn't see a TcTyVar, so we have to instantiate. Sigh
2042         -- ToDo: what if two of them do get unified?
2043     newDicts DataDeclOrigin (substTheta tenv theta)     `thenM` \ wanteds ->
2044     simpleReduceLoop doc reduceMe wanteds               `thenM` \ (frees, _, irreds) ->
2045     ASSERT( null frees )                        -- reduceMe never returns Free
2046
2047     doptM Opt_AllowUndecidableInstances         `thenM` \ undecidable_ok ->
2048     let
2049         tv_set      = mkVarSet tvs
2050
2051         (bad_insts, ok_insts) = partition is_bad_inst irreds
2052         is_bad_inst dict 
2053            = let pred = dictPred dict   -- reduceMe squashes all non-dicts
2054              in isEmptyVarSet (tyVarsOfPred pred)
2055                   -- Things like (Eq T) are bad
2056              || (not undecidable_ok && not (isTyVarClassPred pred))
2057                   -- The returned dictionaries should be of form (C a b)
2058                   --    (where a, b are type variables).  
2059                   -- We allow non-tyvar dicts if we had -fallow-undecidable-instances,
2060                   -- but note that risks non-termination in the 'deriving' context-inference
2061                   -- fixpoint loop.   It is useful for situations like
2062                   --    data Min h a = E | M a (h a)
2063                   -- which gives the instance decl
2064                   --    instance (Eq a, Eq (h a)) => Eq (Min h a)
2065   
2066         simpl_theta = map dictPred ok_insts
2067         weird_preds = [pred | pred <- simpl_theta
2068                             , not (tyVarsOfPred pred `subVarSet` tv_set)]  
2069           -- Check for a bizarre corner case, when the derived instance decl should
2070           -- have form  instance C a b => D (T a) where ...
2071           -- Note that 'b' isn't a parameter of T.  This gives rise to all sorts
2072           -- of problems; in particular, it's hard to compare solutions for
2073           -- equality when finding the fixpoint.  So I just rule it out for now.
2074   
2075         rev_env = mkTopTyVarSubst tvs (mkTyVarTys tyvars)
2076                 -- This reverse-mapping is a Royal Pain, 
2077                 -- but the result should mention TyVars not TcTyVars
2078     in
2079    
2080     addNoInstanceErrs Nothing [] bad_insts              `thenM_`
2081     mapM_ (addErrTc . badDerivedPred) weird_preds       `thenM_`
2082     checkAmbiguity tvs simpl_theta tv_set               `thenM_`
2083     returnM (substTheta rev_env simpl_theta)
2084   where
2085     doc    = ptext SLIT("deriving classes for a data type")
2086 \end{code}
2087
2088 @tcSimplifyDefault@ just checks class-type constraints, essentially;
2089 used with \tr{default} declarations.  We are only interested in
2090 whether it worked or not.
2091
2092 \begin{code}
2093 tcSimplifyDefault :: ThetaType  -- Wanted; has no type variables in it
2094                   -> TcM ()
2095
2096 tcSimplifyDefault theta
2097   = newDicts DataDeclOrigin theta               `thenM` \ wanteds ->
2098     simpleReduceLoop doc reduceMe wanteds       `thenM` \ (frees, _, irreds) ->
2099     ASSERT( null frees )        -- try_me never returns Free
2100     addNoInstanceErrs Nothing []  irreds        `thenM_`
2101     if null irreds then
2102         returnM ()
2103     else
2104         failM
2105   where
2106     doc = ptext SLIT("default declaration")
2107 \end{code}
2108
2109
2110 %************************************************************************
2111 %*                                                                      *
2112 \section{Errors and contexts}
2113 %*                                                                      *
2114 %************************************************************************
2115
2116 ToDo: for these error messages, should we note the location as coming
2117 from the insts, or just whatever seems to be around in the monad just
2118 now?
2119
2120 \begin{code}
2121 groupErrs :: ([Inst] -> TcM ()) -- Deal with one group
2122           -> [Inst]             -- The offending Insts
2123           -> TcM ()
2124 -- Group together insts with the same origin
2125 -- We want to report them together in error messages
2126
2127 groupErrs report_err [] 
2128   = returnM ()
2129 groupErrs report_err (inst:insts) 
2130   = do_one (inst:friends)               `thenM_`
2131     groupErrs report_err others
2132
2133   where
2134         -- (It may seem a bit crude to compare the error messages,
2135         --  but it makes sure that we combine just what the user sees,
2136         --  and it avoids need equality on InstLocs.)
2137    (friends, others) = partition is_friend insts
2138    loc_msg           = showSDoc (pprInstLoc (instLoc inst))
2139    is_friend friend  = showSDoc (pprInstLoc (instLoc friend)) == loc_msg
2140    do_one insts = addInstCtxt (instLoc (head insts)) (report_err insts)
2141                 -- Add location and context information derived from the Insts
2142
2143 -- Add the "arising from..." part to a message about bunch of dicts
2144 addInstLoc :: [Inst] -> Message -> Message
2145 addInstLoc insts msg = msg $$ nest 2 (pprInstLoc (instLoc (head insts)))
2146
2147 plural [x] = empty
2148 plural xs  = char 's'
2149
2150 addTopIPErrs dicts
2151   = groupErrs report tidy_dicts
2152   where
2153     (tidy_env, tidy_dicts) = tidyInsts dicts
2154     report dicts = addErrTcM (tidy_env, mk_msg dicts)
2155     mk_msg dicts = addInstLoc dicts (ptext SLIT("Unbound implicit parameter") <> 
2156                                      plural tidy_dicts <+> pprDictsTheta tidy_dicts)
2157
2158 addNoInstanceErrs :: Maybe SDoc -- Nothing => top level
2159                                 -- Just d => d describes the construct
2160                   -> [Inst]     -- What is given by the context or type sig
2161                   -> [Inst]     -- What is wanted
2162                   -> TcM ()     
2163 addNoInstanceErrs mb_what givens [] 
2164   = returnM ()
2165 addNoInstanceErrs mb_what givens dicts
2166   =     -- Some of the dicts are here because there is no instances
2167         -- and some because there are too many instances (overlap)
2168         -- The first thing we do is separate them
2169     getDOpts            `thenM` \ dflags ->
2170     tcGetInstEnvs       `thenM` \ inst_envs ->
2171     let
2172         (tidy_env1, tidy_givens) = tidyInsts givens
2173         (tidy_env2, tidy_dicts)  = tidyMoreInsts tidy_env1 dicts
2174
2175         -- Run through the dicts, generating a message for each
2176         -- overlapping one, but simply accumulating all the 
2177         -- no-instance ones so they can be reported as a group
2178         (overlap_doc, no_inst_dicts) = foldl check_overlap (empty, []) tidy_dicts
2179         check_overlap (overlap_doc, no_inst_dicts) dict 
2180           | not (isClassDict dict) = (overlap_doc, dict : no_inst_dicts)
2181           | otherwise
2182           = case lookupInstEnv dflags inst_envs clas tys of
2183                 -- The case of exactly one match and no unifiers means
2184                 -- a successful lookup.  That can't happen here.
2185 #ifdef DEBUG
2186                 ([m],[]) -> pprPanic "addNoInstanceErrs" (ppr dict)
2187 #endif
2188                 ([], _)  -> (overlap_doc, dict : no_inst_dicts)         -- No match
2189                 res      -> (mk_overlap_msg dict res $$ overlap_doc, no_inst_dicts)
2190           where
2191             (clas,tys) = getDictClassTys dict
2192     in
2193         
2194         -- Now generate a good message for the no-instance bunch
2195     mk_probable_fix tidy_env2 mb_what no_inst_dicts     `thenM` \ (tidy_env3, probable_fix) ->
2196     let
2197         no_inst_doc | null no_inst_dicts = empty
2198                     | otherwise = vcat [addInstLoc no_inst_dicts heading, probable_fix]
2199         heading | null givens = ptext SLIT("No instance") <> plural no_inst_dicts <+> 
2200                                 ptext SLIT("for") <+> pprDictsTheta no_inst_dicts
2201                 | otherwise   = sep [ptext SLIT("Could not deduce") <+> pprDictsTheta no_inst_dicts,
2202                                      nest 2 $ ptext SLIT("from the context") <+> pprDictsTheta tidy_givens]
2203     in
2204         -- And emit both the non-instance and overlap messages
2205     addErrTcM (tidy_env3, no_inst_doc $$ overlap_doc)
2206   where
2207     mk_overlap_msg dict (matches, unifiers)
2208       = vcat [  addInstLoc [dict] ((ptext SLIT("Overlapping instances for") 
2209                                         <+> pprPred (dictPred dict))),
2210                 sep [ptext SLIT("Matching instances") <> colon,
2211                      nest 2 (pprDFuns (dfuns ++ unifiers))],
2212                 ASSERT( not (null matches) )
2213                 if not (isSingleton matches)
2214                 then    -- Two or more matches
2215                      empty
2216                 else    -- One match, plus some unifiers
2217                 ASSERT( not (null unifiers) )
2218                 parens (vcat [ptext SLIT("The choice depends on the instantiation of") <+>
2219                                  quotes (pprWithCommas ppr (varSetElems (tyVarsOfInst dict))),
2220                               ptext SLIT("Use -fallow-incoherent-instances to use the first choice above")])]
2221       where
2222         dfuns = [df | (_, (_,_,df)) <- matches]
2223
2224     mk_probable_fix tidy_env Nothing dicts      -- Top level
2225       = mkMonomorphismMsg tidy_env dicts
2226     mk_probable_fix tidy_env (Just what) dicts  -- Nested (type signatures, instance decls)
2227       = returnM (tidy_env, sep [ptext SLIT("Probable fix:"), nest 2 fix1, nest 2 fix2])
2228       where
2229         fix1 = sep [ptext SLIT("Add") <+> pprDictsTheta dicts,
2230                     ptext SLIT("to the") <+> what]
2231
2232         fix2 | null instance_dicts = empty
2233              | otherwise           = ptext SLIT("Or add an instance declaration for")
2234                                      <+> pprDictsTheta instance_dicts
2235         instance_dicts = [d | d <- dicts, isClassDict d, not (isTyVarDict d)]
2236                 -- Insts for which it is worth suggesting an adding an instance declaration
2237                 -- Exclude implicit parameters, and tyvar dicts
2238
2239
2240 addTopAmbigErrs dicts
2241 -- Divide into groups that share a common set of ambiguous tyvars
2242   = mapM report (equivClasses cmp [(d, tvs_of d) | d <- tidy_dicts])
2243   where
2244     (tidy_env, tidy_dicts) = tidyInsts dicts
2245
2246     tvs_of :: Inst -> [TcTyVar]
2247     tvs_of d = varSetElems (tyVarsOfInst d)
2248     cmp (_,tvs1) (_,tvs2) = tvs1 `compare` tvs2
2249     
2250     report :: [(Inst,[TcTyVar])] -> TcM ()
2251     report pairs@((inst,tvs) : _)       -- The pairs share a common set of ambiguous tyvars
2252         = mkMonomorphismMsg tidy_env dicts      `thenM` \ (tidy_env, mono_msg) ->
2253           addSrcSpan (instLocSrcSpan (instLoc inst)) $
2254                 -- the location of the first one will do for the err message
2255           addErrTcM (tidy_env, msg $$ mono_msg)
2256         where
2257           dicts = map fst pairs
2258           msg = sep [text "Ambiguous type variable" <> plural tvs <+> 
2259                              pprQuotedList tvs <+> in_msg,
2260                      nest 2 (pprDictsInFull dicts)]
2261           in_msg | isSingleton dicts = text "in the top-level constraint:"
2262                  | otherwise         = text "in these top-level constraints:"
2263
2264
2265 mkMonomorphismMsg :: TidyEnv -> [Inst] -> TcM (TidyEnv, Message)
2266 -- There's an error with these Insts; if they have free type variables
2267 -- it's probably caused by the monomorphism restriction. 
2268 -- Try to identify the offending variable
2269 -- ASSUMPTION: the Insts are fully zonked
2270 mkMonomorphismMsg tidy_env insts
2271   | isEmptyVarSet inst_tvs
2272   = returnM (tidy_env, empty)
2273   | otherwise
2274   = findGlobals inst_tvs tidy_env       `thenM` \ (tidy_env, docs) ->
2275     returnM (tidy_env, mk_msg docs)
2276
2277   where
2278     inst_tvs = tyVarsOfInsts insts
2279
2280     mk_msg []   = empty         -- This happens in things like
2281                                 --      f x = show (read "foo")
2282                                 -- whre monomorphism doesn't play any role
2283     mk_msg docs = vcat [ptext SLIT("Possible cause: the monomorphism restriction applied to the following:"),
2284                         nest 2 (vcat docs),
2285                         ptext SLIT("Probable fix: give these definition(s) an explicit type signature")]
2286     
2287 warnDefault dicts default_ty
2288   = doptM Opt_WarnTypeDefaults  `thenM` \ warn_flag ->
2289     addInstCtxt (instLoc (head dicts)) (warnTc warn_flag warn_msg)
2290   where
2291         -- Tidy them first
2292     (_, tidy_dicts) = tidyInsts dicts
2293     warn_msg  = vcat [ptext SLIT("Defaulting the following constraint(s) to type") <+>
2294                                 quotes (ppr default_ty),
2295                       pprDictsInFull tidy_dicts]
2296
2297 -- Used for the ...Thetas variants; all top level
2298 badDerivedPred pred
2299   = vcat [ptext SLIT("Can't derive instances where the instance context mentions"),
2300           ptext SLIT("type variables that are not data type parameters"),
2301           nest 2 (ptext SLIT("Offending constraint:") <+> ppr pred)]
2302
2303 reduceDepthErr n stack
2304   = vcat [ptext SLIT("Context reduction stack overflow; size =") <+> int n,
2305           ptext SLIT("Use -fcontext-stack20 to increase stack size to (e.g.) 20"),
2306           nest 4 (pprStack stack)]
2307
2308 pprStack stack = vcat (map pprInstInFull stack)
2309 \end{code}