Three improvements to Template Haskell (fixes #3467)
[ghc-hetmet.git] / compiler / typecheck / TcSimplify.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 %
5
6 TcSimplify
7
8 \begin{code}
9 module TcSimplify (
10         tcSimplifyInfer, tcSimplifyInferCheck,
11         tcSimplifyCheck, tcSimplifyRestricted,
12         tcSimplifyRuleLhs, tcSimplifyIPs, 
13         tcSimplifySuperClasses,
14         tcSimplifyTop, tcSimplifyInteractive,
15         tcSimplifyBracket, tcSimplifyCheckPat,
16
17         tcSimplifyDeriv, tcSimplifyDefault,
18         bindInstsOfLocalFuns, 
19         
20         misMatchMsg
21     ) where
22
23 #include "HsVersions.h"
24
25 import {-# SOURCE #-} TcUnify( unifyType )
26 import HsSyn
27
28 import TcRnMonad
29 import TcHsSyn  ( hsLPatType )
30 import Inst
31 import TcEnv
32 import InstEnv
33 import TcType
34 import TcMType
35 import TcIface
36 import TcTyFuns
37 import DsUtils  -- Big-tuple functions
38 import Var
39 import Id
40 import Name
41 import NameSet
42 import Class
43 import FunDeps
44 import PrelInfo
45 import PrelNames
46 import TysWiredIn
47 import ErrUtils
48 import BasicTypes
49 import VarSet
50 import VarEnv
51 import FiniteMap
52 import Bag
53 import Outputable
54 import ListSetOps
55 import Util
56 import SrcLoc
57 import DynFlags
58 import FastString
59
60 import Control.Monad
61 import Data.List
62 \end{code}
63
64
65 %************************************************************************
66 %*                                                                      *
67 \subsection{NOTES}
68 %*                                                                      *
69 %************************************************************************
70
71         --------------------------------------
72         Notes on functional dependencies (a bug)
73         --------------------------------------
74
75 Consider this:
76
77         class C a b | a -> b
78         class D a b | a -> b
79
80         instance D a b => C a b -- Undecidable 
81                                 -- (Not sure if it's crucial to this eg)
82         f :: C a b => a -> Bool
83         f _ = True
84         
85         g :: C a b => a -> Bool
86         g = f
87
88 Here f typechecks, but g does not!!  Reason: before doing improvement,
89 we reduce the (C a b1) constraint from the call of f to (D a b1).
90
91 Here is a more complicated example:
92
93 @
94   > class Foo a b | a->b
95   >
96   > class Bar a b | a->b
97   >
98   > data Obj = Obj
99   >
100   > instance Bar Obj Obj
101   >
102   > instance (Bar a b) => Foo a b
103   >
104   > foo:: (Foo a b) => a -> String
105   > foo _ = "works"
106   >
107   > runFoo:: (forall a b. (Foo a b) => a -> w) -> w
108   > runFoo f = f Obj
109
110   *Test> runFoo foo
111
112   <interactive>:1:
113       Could not deduce (Bar a b) from the context (Foo a b)
114         arising from use of `foo' at <interactive>:1
115       Probable fix:
116           Add (Bar a b) to the expected type of an expression
117       In the first argument of `runFoo', namely `foo'
118       In the definition of `it': it = runFoo foo
119
120   Why all of the sudden does GHC need the constraint Bar a b? The
121   function foo didn't ask for that...
122 @
123
124 The trouble is that to type (runFoo foo), GHC has to solve the problem:
125
126         Given constraint        Foo a b
127         Solve constraint        Foo a b'
128
129 Notice that b and b' aren't the same.  To solve this, just do
130 improvement and then they are the same.  But GHC currently does
131         simplify constraints
132         apply improvement
133         and loop
134
135 That is usually fine, but it isn't here, because it sees that Foo a b is
136 not the same as Foo a b', and so instead applies the instance decl for
137 instance Bar a b => Foo a b.  And that's where the Bar constraint comes
138 from.
139
140 The Right Thing is to improve whenever the constraint set changes at
141 all.  Not hard in principle, but it'll take a bit of fiddling to do.  
142
143 Note [Choosing which variables to quantify]
144 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
145 Suppose we are about to do a generalisation step.  We have in our hand
146
147         G       the environment
148         T       the type of the RHS
149         C       the constraints from that RHS
150
151 The game is to figure out
152
153         Q       the set of type variables over which to quantify
154         Ct      the constraints we will *not* quantify over
155         Cq      the constraints we will quantify over
156
157 So we're going to infer the type
158
159         forall Q. Cq => T
160
161 and float the constraints Ct further outwards.
162
163 Here are the things that *must* be true:
164
165  (A)    Q intersect fv(G) = EMPTY                       limits how big Q can be
166  (B)    Q superset fv(Cq union T) \ oclose(fv(G),C)     limits how small Q can be
167
168  (A) says we can't quantify over a variable that's free in the environment. 
169  (B) says we must quantify over all the truly free variables in T, else 
170      we won't get a sufficiently general type.  
171
172 We do not *need* to quantify over any variable that is fixed by the
173 free vars of the environment G.
174
175         BETWEEN THESE TWO BOUNDS, ANY Q WILL DO!
176
177 Example:        class H x y | x->y where ...
178
179         fv(G) = {a}     C = {H a b, H c d}
180                         T = c -> b
181
182         (A)  Q intersect {a} is empty
183         (B)  Q superset {a,b,c,d} \ oclose({a}, C) = {a,b,c,d} \ {a,b} = {c,d}
184
185         So Q can be {c,d}, {b,c,d}
186
187 In particular, it's perfectly OK to quantify over more type variables
188 than strictly necessary; there is no need to quantify over 'b', since
189 it is determined by 'a' which is free in the envt, but it's perfectly
190 OK to do so.  However we must not quantify over 'a' itself.
191
192 Other things being equal, however, we'd like to quantify over as few
193 variables as possible: smaller types, fewer type applications, more
194 constraints can get into Ct instead of Cq.  Here's a good way to
195 choose Q:
196
197         Q = grow( fv(T), C ) \ oclose( fv(G), C )
198
199 That is, quantify over all variable that that MIGHT be fixed by the
200 call site (which influences T), but which aren't DEFINITELY fixed by
201 G.  This choice definitely quantifies over enough type variables,
202 albeit perhaps too many.
203
204 Why grow( fv(T), C ) rather than fv(T)?  Consider
205
206         class H x y | x->y where ...
207
208         T = c->c
209         C = (H c d)
210
211   If we used fv(T) = {c} we'd get the type
212
213         forall c. H c d => c -> b
214
215   And then if the fn was called at several different c's, each of
216   which fixed d differently, we'd get a unification error, because
217   d isn't quantified.  Solution: quantify d.  So we must quantify
218   everything that might be influenced by c.
219
220 Why not oclose( fv(T), C )?  Because we might not be able to see
221 all the functional dependencies yet:
222
223         class H x y | x->y where ...
224         instance H x y => Eq (T x y) where ...
225
226         T = c->c
227         C = (Eq (T c d))
228
229 Now oclose(fv(T),C) = {c}, because the functional dependency isn't
230 apparent yet, and that's wrong.  We must really quantify over d too.
231
232 There really isn't any point in quantifying over any more than
233 grow( fv(T), C ), because the call sites can't possibly influence
234 any other type variables.
235
236
237
238 -------------------------------------
239         Note [Ambiguity]
240 -------------------------------------
241
242 It's very hard to be certain when a type is ambiguous.  Consider
243
244         class K x
245         class H x y | x -> y
246         instance H x y => K (x,y)
247
248 Is this type ambiguous?
249         forall a b. (K (a,b), Eq b) => a -> a
250
251 Looks like it!  But if we simplify (K (a,b)) we get (H a b) and
252 now we see that a fixes b.  So we can't tell about ambiguity for sure
253 without doing a full simplification.  And even that isn't possible if
254 the context has some free vars that may get unified.  Urgle!
255
256 Here's another example: is this ambiguous?
257         forall a b. Eq (T b) => a -> a
258 Not if there's an insance decl (with no context)
259         instance Eq (T b) where ...
260
261 You may say of this example that we should use the instance decl right
262 away, but you can't always do that:
263
264         class J a b where ...
265         instance J Int b where ...
266
267         f :: forall a b. J a b => a -> a
268
269 (Notice: no functional dependency in J's class decl.)
270 Here f's type is perfectly fine, provided f is only called at Int.
271 It's premature to complain when meeting f's signature, or even
272 when inferring a type for f.
273
274
275
276 However, we don't *need* to report ambiguity right away.  It'll always
277 show up at the call site.... and eventually at main, which needs special
278 treatment.  Nevertheless, reporting ambiguity promptly is an excellent thing.
279
280 So here's the plan.  We WARN about probable ambiguity if
281
282         fv(Cq) is not a subset of  oclose(fv(T) union fv(G), C)
283
284 (all tested before quantification).
285 That is, all the type variables in Cq must be fixed by the the variables
286 in the environment, or by the variables in the type.
287
288 Notice that we union before calling oclose.  Here's an example:
289
290         class J a b c | a b -> c
291         fv(G) = {a}
292
293 Is this ambiguous?
294         forall b c. (J a b c) => b -> b
295
296 Only if we union {a} from G with {b} from T before using oclose,
297 do we see that c is fixed.
298
299 It's a bit vague exactly which C we should use for this oclose call.  If we
300 don't fix enough variables we might complain when we shouldn't (see
301 the above nasty example).  Nothing will be perfect.  That's why we can
302 only issue a warning.
303
304
305 Can we ever be *certain* about ambiguity?  Yes: if there's a constraint
306
307         c in C such that fv(c) intersect (fv(G) union fv(T)) = EMPTY
308
309 then c is a "bubble"; there's no way it can ever improve, and it's
310 certainly ambiguous.  UNLESS it is a constant (sigh).  And what about
311 the nasty example?
312
313         class K x
314         class H x y | x -> y
315         instance H x y => K (x,y)
316
317 Is this type ambiguous?
318         forall a b. (K (a,b), Eq b) => a -> a
319
320 Urk.  The (Eq b) looks "definitely ambiguous" but it isn't.  What we are after
321 is a "bubble" that's a set of constraints
322
323         Cq = Ca union Cq'  st  fv(Ca) intersect (fv(Cq') union fv(T) union fv(G)) = EMPTY
324
325 Hence another idea.  To decide Q start with fv(T) and grow it
326 by transitive closure in Cq (no functional dependencies involved).
327 Now partition Cq using Q, leaving the definitely-ambiguous and probably-ok.
328 The definitely-ambiguous can then float out, and get smashed at top level
329 (which squashes out the constants, like Eq (T a) above)
330
331
332         --------------------------------------
333                 Notes on principal types
334         --------------------------------------
335
336     class C a where
337       op :: a -> a
338
339     f x = let g y = op (y::Int) in True
340
341 Here the principal type of f is (forall a. a->a)
342 but we'll produce the non-principal type
343     f :: forall a. C Int => a -> a
344
345
346         --------------------------------------
347         The need for forall's in constraints
348         --------------------------------------
349
350 [Exchange on Haskell Cafe 5/6 Dec 2000]
351
352   class C t where op :: t -> Bool
353   instance C [t] where op x = True
354
355   p y = (let f :: c -> Bool; f x = op (y >> return x) in f, y ++ [])
356   q y = (y ++ [], let f :: c -> Bool; f x = op (y >> return x) in f)
357
358 The definitions of p and q differ only in the order of the components in
359 the pair on their right-hand sides.  And yet:
360
361   ghc and "Typing Haskell in Haskell" reject p, but accept q;
362   Hugs rejects q, but accepts p;
363   hbc rejects both p and q;
364   nhc98 ... (Malcolm, can you fill in the blank for us!).
365
366 The type signature for f forces context reduction to take place, and
367 the results of this depend on whether or not the type of y is known,
368 which in turn depends on which component of the pair the type checker
369 analyzes first.  
370
371 Solution: if y::m a, float out the constraints
372         Monad m, forall c. C (m c)
373 When m is later unified with [], we can solve both constraints.
374
375
376         --------------------------------------
377                 Notes on implicit parameters
378         --------------------------------------
379
380 Note [Inheriting implicit parameters]
381 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
382 Consider this:
383
384         f x = (x::Int) + ?y
385
386 where f is *not* a top-level binding.
387 From the RHS of f we'll get the constraint (?y::Int).
388 There are two types we might infer for f:
389
390         f :: Int -> Int
391
392 (so we get ?y from the context of f's definition), or
393
394         f :: (?y::Int) => Int -> Int
395
396 At first you might think the first was better, becuase then
397 ?y behaves like a free variable of the definition, rather than
398 having to be passed at each call site.  But of course, the WHOLE
399 IDEA is that ?y should be passed at each call site (that's what
400 dynamic binding means) so we'd better infer the second.
401
402 BOTTOM LINE: when *inferring types* you *must* quantify 
403 over implicit parameters. See the predicate isFreeWhenInferring.
404
405
406 Note [Implicit parameters and ambiguity] 
407 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
408 Only a *class* predicate can give rise to ambiguity
409 An *implicit parameter* cannot.  For example:
410         foo :: (?x :: [a]) => Int
411         foo = length ?x
412 is fine.  The call site will suppply a particular 'x'
413
414 Furthermore, the type variables fixed by an implicit parameter
415 propagate to the others.  E.g.
416         foo :: (Show a, ?x::[a]) => Int
417         foo = show (?x++?x)
418 The type of foo looks ambiguous.  But it isn't, because at a call site
419 we might have
420         let ?x = 5::Int in foo
421 and all is well.  In effect, implicit parameters are, well, parameters,
422 so we can take their type variables into account as part of the
423 "tau-tvs" stuff.  This is done in the function 'FunDeps.grow'.
424
425
426 Question 2: type signatures
427 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
428 BUT WATCH OUT: When you supply a type signature, we can't force you
429 to quantify over implicit parameters.  For example:
430
431         (?x + 1) :: Int
432
433 This is perfectly reasonable.  We do not want to insist on
434
435         (?x + 1) :: (?x::Int => Int)
436
437 That would be silly.  Here, the definition site *is* the occurrence site,
438 so the above strictures don't apply.  Hence the difference between
439 tcSimplifyCheck (which *does* allow implicit paramters to be inherited)
440 and tcSimplifyCheckBind (which does not).
441
442 What about when you supply a type signature for a binding?
443 Is it legal to give the following explicit, user type 
444 signature to f, thus:
445
446         f :: Int -> Int
447         f x = (x::Int) + ?y
448
449 At first sight this seems reasonable, but it has the nasty property
450 that adding a type signature changes the dynamic semantics.
451 Consider this:
452
453         (let f x = (x::Int) + ?y
454          in (f 3, f 3 with ?y=5))  with ?y = 6
455
456                 returns (3+6, 3+5)
457 vs
458         (let f :: Int -> Int
459              f x = x + ?y
460          in (f 3, f 3 with ?y=5))  with ?y = 6
461
462                 returns (3+6, 3+6)
463
464 Indeed, simply inlining f (at the Haskell source level) would change the
465 dynamic semantics.
466
467 Nevertheless, as Launchbury says (email Oct 01) we can't really give the
468 semantics for a Haskell program without knowing its typing, so if you 
469 change the typing you may change the semantics.
470
471 To make things consistent in all cases where we are *checking* against
472 a supplied signature (as opposed to inferring a type), we adopt the
473 rule: 
474
475         a signature does not need to quantify over implicit params.
476
477 [This represents a (rather marginal) change of policy since GHC 5.02,
478 which *required* an explicit signature to quantify over all implicit
479 params for the reasons mentioned above.]
480
481 But that raises a new question.  Consider 
482
483         Given (signature)       ?x::Int
484         Wanted (inferred)       ?x::Int, ?y::Bool
485
486 Clearly we want to discharge the ?x and float the ?y out.  But
487 what is the criterion that distinguishes them?  Clearly it isn't
488 what free type variables they have.  The Right Thing seems to be
489 to float a constraint that
490         neither mentions any of the quantified type variables
491         nor any of the quantified implicit parameters
492
493 See the predicate isFreeWhenChecking.
494
495
496 Question 3: monomorphism
497 ~~~~~~~~~~~~~~~~~~~~~~~~
498 There's a nasty corner case when the monomorphism restriction bites:
499
500         z = (x::Int) + ?y
501
502 The argument above suggests that we *must* generalise
503 over the ?y parameter, to get
504         z :: (?y::Int) => Int,
505 but the monomorphism restriction says that we *must not*, giving
506         z :: Int.
507 Why does the momomorphism restriction say this?  Because if you have
508
509         let z = x + ?y in z+z
510
511 you might not expect the addition to be done twice --- but it will if
512 we follow the argument of Question 2 and generalise over ?y.
513
514
515 Question 4: top level
516 ~~~~~~~~~~~~~~~~~~~~~
517 At the top level, monomorhism makes no sense at all.
518
519     module Main where
520         main = let ?x = 5 in print foo
521
522         foo = woggle 3
523
524         woggle :: (?x :: Int) => Int -> Int
525         woggle y = ?x + y
526
527 We definitely don't want (foo :: Int) with a top-level implicit parameter
528 (?x::Int) becuase there is no way to bind it.  
529
530
531 Possible choices
532 ~~~~~~~~~~~~~~~~
533 (A) Always generalise over implicit parameters
534     Bindings that fall under the monomorphism restriction can't
535         be generalised
536
537     Consequences:
538         * Inlining remains valid
539         * No unexpected loss of sharing
540         * But simple bindings like
541                 z = ?y + 1
542           will be rejected, unless you add an explicit type signature
543           (to avoid the monomorphism restriction)
544                 z :: (?y::Int) => Int
545                 z = ?y + 1
546           This seems unacceptable
547
548 (B) Monomorphism restriction "wins"
549     Bindings that fall under the monomorphism restriction can't
550         be generalised
551     Always generalise over implicit parameters *except* for bindings
552         that fall under the monomorphism restriction
553
554     Consequences
555         * Inlining isn't valid in general
556         * No unexpected loss of sharing
557         * Simple bindings like
558                 z = ?y + 1
559           accepted (get value of ?y from binding site)
560
561 (C) Always generalise over implicit parameters
562     Bindings that fall under the monomorphism restriction can't
563         be generalised, EXCEPT for implicit parameters
564     Consequences
565         * Inlining remains valid
566         * Unexpected loss of sharing (from the extra generalisation)
567         * Simple bindings like
568                 z = ?y + 1
569           accepted (get value of ?y from occurrence sites)
570
571
572 Discussion
573 ~~~~~~~~~~
574 None of these choices seems very satisfactory.  But at least we should
575 decide which we want to do.
576
577 It's really not clear what is the Right Thing To Do.  If you see
578
579         z = (x::Int) + ?y
580
581 would you expect the value of ?y to be got from the *occurrence sites*
582 of 'z', or from the valuue of ?y at the *definition* of 'z'?  In the
583 case of function definitions, the answer is clearly the former, but
584 less so in the case of non-fucntion definitions.   On the other hand,
585 if we say that we get the value of ?y from the definition site of 'z',
586 then inlining 'z' might change the semantics of the program.
587
588 Choice (C) really says "the monomorphism restriction doesn't apply
589 to implicit parameters".  Which is fine, but remember that every
590 innocent binding 'x = ...' that mentions an implicit parameter in
591 the RHS becomes a *function* of that parameter, called at each
592 use of 'x'.  Now, the chances are that there are no intervening 'with'
593 clauses that bind ?y, so a decent compiler should common up all
594 those function calls.  So I think I strongly favour (C).  Indeed,
595 one could make a similar argument for abolishing the monomorphism
596 restriction altogether.
597
598 BOTTOM LINE: we choose (B) at present.  See tcSimplifyRestricted
599
600
601
602 %************************************************************************
603 %*                                                                      *
604 \subsection{tcSimplifyInfer}
605 %*                                                                      *
606 %************************************************************************
607
608 tcSimplify is called when we *inferring* a type.  Here's the overall game plan:
609
610     1. Compute Q = grow( fvs(T), C )
611
612     2. Partition C based on Q into Ct and Cq.  Notice that ambiguous
613        predicates will end up in Ct; we deal with them at the top level
614
615     3. Try improvement, using functional dependencies
616
617     4. If Step 3 did any unification, repeat from step 1
618        (Unification can change the result of 'grow'.)
619
620 Note: we don't reduce dictionaries in step 2.  For example, if we have
621 Eq (a,b), we don't simplify to (Eq a, Eq b).  So Q won't be different
622 after step 2.  However note that we may therefore quantify over more
623 type variables than we absolutely have to.
624
625 For the guts, we need a loop, that alternates context reduction and
626 improvement with unification.  E.g. Suppose we have
627
628         class C x y | x->y where ...
629
630 and tcSimplify is called with:
631         (C Int a, C Int b)
632 Then improvement unifies a with b, giving
633         (C Int a, C Int a)
634
635 If we need to unify anything, we rattle round the whole thing all over
636 again.
637
638
639 \begin{code}
640 tcSimplifyInfer
641         :: SDoc
642         -> TcTyVarSet           -- fv(T); type vars
643         -> [Inst]               -- Wanted
644         -> TcM ([TcTyVar],      -- Tyvars to quantify (zonked and quantified)
645                 [Inst],         -- Dict Ids that must be bound here (zonked)
646                 TcDictBinds)    -- Bindings
647         -- Any free (escaping) Insts are tossed into the environment
648 \end{code}
649
650
651 \begin{code}
652 tcSimplifyInfer doc tau_tvs wanted
653   = do  { tau_tvs1 <- zonkTcTyVarsAndFV (varSetElems tau_tvs)
654         ; wanted'  <- mapM zonkInst wanted      -- Zonk before deciding quantified tyvars
655         ; gbl_tvs  <- tcGetGlobalTyVars
656         ; let preds1   = fdPredsOfInsts wanted'
657               gbl_tvs1 = oclose preds1 gbl_tvs
658               qtvs     = growInstsTyVars wanted' tau_tvs1 `minusVarSet` gbl_tvs1
659                         -- See Note [Choosing which variables to quantify]
660
661                 -- To maximise sharing, remove from consideration any 
662                 -- constraints that don't mention qtvs at all
663         ; let (free, bound) = partition (isFreeWhenInferring qtvs) wanted'
664         ; extendLIEs free
665
666                 -- To make types simple, reduce as much as possible
667         ; traceTc (text "infer" <+> (ppr preds1 $$ ppr (growInstsTyVars wanted' tau_tvs1) $$ ppr gbl_tvs $$ 
668                    ppr gbl_tvs1 $$ ppr free $$ ppr bound))
669         ; (irreds1, binds1) <- tryHardCheckLoop doc bound
670
671                 -- Note [Inference and implication constraints]
672         ; let want_dict d = tyVarsOfInst d `intersectsVarSet` qtvs
673         ; (irreds2, binds2) <- approximateImplications doc want_dict irreds1
674
675                 -- Now work out all over again which type variables to quantify,
676                 -- exactly in the same way as before, but starting from irreds2.  Why?
677                 -- a) By now improvment may have taken place, and we must *not*
678                 --    quantify over any variable free in the environment
679                 --    tc137 (function h inside g) is an example
680                 --
681                 -- b) Do not quantify over constraints that *now* do not
682                 --    mention quantified type variables, because they are
683                 --    simply ambiguous (or might be bound further out).  Example:
684                 --      f :: Eq b => a -> (a, b)
685                 --      g x = fst (f x)
686                 --    From the RHS of g we get the MethodInst f77 :: alpha -> (alpha, beta)
687                 --    We decide to quantify over 'alpha' alone, but free1 does not include f77
688                 --    because f77 mentions 'alpha'.  Then reducing leaves only the (ambiguous)
689                 --    constraint (Eq beta), which we dump back into the free set
690                 --    See test tcfail181
691                 --
692                 -- c) irreds may contain type variables not previously mentioned,
693                 --    e.g.  instance D a x => Foo [a] 
694                 --          wanteds = Foo [a]
695                 --       Then after simplifying we'll get (D a x), and x is fresh
696                 --       We must quantify over x else it'll be totally unbound
697         ; tau_tvs2 <- zonkTcTyVarsAndFV (varSetElems tau_tvs1)
698         ; gbl_tvs2 <- zonkTcTyVarsAndFV (varSetElems gbl_tvs1)
699                 -- Note that we start from gbl_tvs1
700                 -- We use tcGetGlobalTyVars, then oclose wrt preds2, because
701                 -- we've already put some of the original preds1 into frees
702                 -- E.g.         wanteds = C a b   (where a->b)
703                 --              gbl_tvs = {a}
704                 --              tau_tvs = {b}
705                 -- Then b is fixed by gbl_tvs, so (C a b) will be in free, and
706                 -- irreds2 will be empty.  But we don't want to generalise over b!
707         ; let preds2 = fdPredsOfInsts irreds2   -- irreds2 is zonked
708               qtvs   = growInstsTyVars irreds2 tau_tvs2 `minusVarSet` oclose preds2 gbl_tvs2
709                 ---------------------------------------------------
710                 -- BUG WARNING: there's a nasty bug lurking here
711                 -- fdPredsOfInsts may return preds that mention variables quantified in
712                 -- one of the implication constraints in irreds2; and that is clearly wrong:
713                 -- we might quantify over too many variables through accidental capture
714                 ---------------------------------------------------
715         ; let (free, irreds3) = partition (isFreeWhenInferring qtvs) irreds2
716         ; extendLIEs free
717
718                 -- Turn the quantified meta-type variables into real type variables
719         ; qtvs2 <- zonkQuantifiedTyVars (varSetElems qtvs)
720
721                 -- We can't abstract over any remaining unsolved 
722                 -- implications so instead just float them outwards. Ugh.
723         ; let (q_dicts0, implics) = partition isAbstractableInst irreds3
724         ; loc <- getInstLoc (ImplicOrigin doc)
725         ; implic_bind <- bindIrreds loc qtvs2 q_dicts0 implics
726
727                 -- Prepare equality instances for quantification
728         ; let (q_eqs0,q_dicts) = partition isEqInst q_dicts0
729         ; q_eqs <- mapM finalizeEqInst q_eqs0
730
731         ; return (qtvs2, q_eqs ++ q_dicts, binds1 `unionBags` binds2 `unionBags` implic_bind) }
732         -- NB: when we are done, we might have some bindings, but
733         -- the final qtvs might be empty.  See Note [NO TYVARS] below.
734
735 approximateImplications :: SDoc -> (Inst -> Bool) -> [Inst] -> TcM ([Inst], TcDictBinds)
736 -- Note [Inference and implication constraints]
737 -- Given a bunch of Dict and ImplicInsts, try to approximate the implications by
738 --      - fetching any dicts inside them that are free
739 --      - using those dicts as cruder constraints, to solve the implications
740 --      - returning the extra ones too
741
742 approximateImplications doc want_dict irreds
743   | null extra_dicts 
744   = return (irreds, emptyBag)
745   | otherwise
746   = do  { extra_dicts' <- mapM cloneDict extra_dicts
747         ; tryHardCheckLoop doc (extra_dicts' ++ irreds) }
748                 -- By adding extra_dicts', we make them 
749                 -- available to solve the implication constraints
750   where 
751     extra_dicts = get_dicts (filter isImplicInst irreds)
752
753     get_dicts :: [Inst] -> [Inst]       -- Returns only Dicts
754         -- Find the wanted constraints in implication constraints that satisfy
755         -- want_dict, and are not bound by forall's in the constraint itself
756     get_dicts ds = concatMap get_dict ds
757
758     get_dict d@(Dict {}) | want_dict d = [d]
759                          | otherwise   = []
760     get_dict (ImplicInst {tci_tyvars = tvs, tci_wanted = wanteds})
761         = [ d | let tv_set = mkVarSet tvs
762               , d <- get_dicts wanteds 
763               , not (tyVarsOfInst d `intersectsVarSet` tv_set)]
764     get_dict i@(EqInst {}) | want_dict i = [i]
765                            | otherwise   = [] 
766     get_dict other = pprPanic "approximateImplications" (ppr other)
767 \end{code}
768
769 Note [Inference and implication constraints]
770 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
771 Suppose we have a wanted implication constraint (perhaps arising from
772 a nested pattern match) like
773         C a => D [a]
774 and we are now trying to quantify over 'a' when inferring the type for
775 a function.  In principle it's possible that there might be an instance
776         instance (C a, E a) => D [a]
777 so the context (E a) would suffice.  The Right Thing is to abstract over
778 the implication constraint, but we don't do that (a) because it'll be
779 surprising to programmers and (b) because we don't have the machinery to deal
780 with 'given' implications.
781
782 So our best approximation is to make (D [a]) part of the inferred
783 context, so we can use that to discharge the implication. Hence
784 the strange function get_dicts in approximateImplications.
785
786 The common cases are more clear-cut, when we have things like
787         forall a. C a => C b
788 Here, abstracting over (C b) is not an approximation at all -- but see
789 Note [Freeness and implications].
790  
791 See Trac #1430 and test tc228.
792
793
794 \begin{code}
795 -----------------------------------------------------------
796 -- tcSimplifyInferCheck is used when we know the constraints we are to simplify
797 -- against, but we don't know the type variables over which we are going to quantify.
798 -- This happens when we have a type signature for a mutually recursive group
799 tcSimplifyInferCheck
800          :: InstLoc
801          -> TcTyVarSet          -- fv(T)
802          -> [Inst]              -- Given
803          -> [Inst]              -- Wanted
804          -> TcM ([TyVar],       -- Fully zonked, and quantified
805                  TcDictBinds)   -- Bindings
806
807 tcSimplifyInferCheck loc tau_tvs givens wanteds
808   = do  { traceTc (text "tcSimplifyInferCheck <-" <+> ppr wanteds)
809         ; (irreds, binds) <- gentleCheckLoop loc givens wanteds
810
811         -- Figure out which type variables to quantify over
812         -- You might think it should just be the signature tyvars,
813         -- but in bizarre cases you can get extra ones
814         --      f :: forall a. Num a => a -> a
815         --      f x = fst (g (x, head [])) + 1
816         --      g a b = (b,a)
817         -- Here we infer g :: forall a b. a -> b -> (b,a)
818         -- We don't want g to be monomorphic in b just because
819         -- f isn't quantified over b.
820         ; let all_tvs = varSetElems (tau_tvs `unionVarSet` tyVarsOfInsts givens)
821         ; all_tvs <- zonkTcTyVarsAndFV all_tvs
822         ; gbl_tvs <- tcGetGlobalTyVars
823         ; let qtvs = varSetElems (all_tvs `minusVarSet` gbl_tvs)
824                 -- We could close gbl_tvs, but its not necessary for
825                 -- soundness, and it'll only affect which tyvars, not which
826                 -- dictionaries, we quantify over
827
828         ; qtvs' <- zonkQuantifiedTyVars qtvs
829
830                 -- Now we are back to normal (c.f. tcSimplCheck)
831         ; implic_bind <- bindIrreds loc qtvs' givens irreds
832
833         ; traceTc (text "tcSimplifyInferCheck ->" <+> ppr (implic_bind))
834         ; return (qtvs', binds `unionBags` implic_bind) }
835 \end{code}
836
837 Note [Squashing methods]
838 ~~~~~~~~~~~~~~~~~~~~~~~~~
839 Be careful if you want to float methods more:
840         truncate :: forall a. RealFrac a => forall b. Integral b => a -> b
841 From an application (truncate f i) we get
842         t1 = truncate at f
843         t2 = t1 at i
844 If we have also have a second occurrence of truncate, we get
845         t3 = truncate at f
846         t4 = t3 at i
847 When simplifying with i,f free, we might still notice that
848 t1=t3; but alas, the binding for t2 (which mentions t1)
849 may continue to float out!
850
851
852 Note [NO TYVARS]
853 ~~~~~~~~~~~~~~~~~
854         class Y a b | a -> b where
855             y :: a -> X b
856         
857         instance Y [[a]] a where
858             y ((x:_):_) = X x
859         
860         k :: X a -> X a -> X a
861
862         g :: Num a => [X a] -> [X a]
863         g xs = h xs
864             where
865             h ys = ys ++ map (k (y [[0]])) xs
866
867 The excitement comes when simplifying the bindings for h.  Initially
868 try to simplify {y @ [[t1]] t2, 0 @ t1}, with initial qtvs = {t2}.
869 From this we get t1~t2, but also various bindings.  We can't forget
870 the bindings (because of [LOOP]), but in fact t1 is what g is
871 polymorphic in.  
872
873 The net effect of [NO TYVARS] 
874
875 \begin{code}
876 isFreeWhenInferring :: TyVarSet -> Inst -> Bool
877 isFreeWhenInferring qtvs inst
878   =  isFreeWrtTyVars qtvs inst  -- Constrains no quantified vars
879   && isInheritableInst inst     -- and no implicit parameter involved
880                                 --   see Note [Inheriting implicit parameters]
881
882 {-      No longer used (with implication constraints)
883 isFreeWhenChecking :: TyVarSet  -- Quantified tyvars
884                    -> NameSet   -- Quantified implicit parameters
885                    -> Inst -> Bool
886 isFreeWhenChecking qtvs ips inst
887   =  isFreeWrtTyVars qtvs inst
888   && isFreeWrtIPs    ips inst
889 -}
890
891 isFreeWrtTyVars :: VarSet -> Inst -> Bool
892 isFreeWrtTyVars qtvs inst = tyVarsOfInst inst `disjointVarSet` qtvs
893 isFreeWrtIPs :: NameSet -> Inst -> Bool
894 isFreeWrtIPs     ips inst = not (any (`elemNameSet` ips) (ipNamesOfInst inst))
895 \end{code}
896
897
898 %************************************************************************
899 %*                                                                      *
900 \subsection{tcSimplifyCheck}
901 %*                                                                      *
902 %************************************************************************
903
904 @tcSimplifyCheck@ is used when we know exactly the set of variables
905 we are going to quantify over.  For example, a class or instance declaration.
906
907 \begin{code}
908 -----------------------------------------------------------
909 -- tcSimplifyCheck is used when checking expression type signatures,
910 -- class decls, instance decls etc.
911 tcSimplifyCheck :: InstLoc
912                 -> [TcTyVar]            -- Quantify over these
913                 -> [Inst]               -- Given
914                 -> [Inst]               -- Wanted
915                 -> TcM TcDictBinds      -- Bindings
916 tcSimplifyCheck loc qtvs givens wanteds 
917   = ASSERT( all isTcTyVar qtvs && all isSkolemTyVar qtvs )
918     do  { traceTc (text "tcSimplifyCheck")
919         ; (irreds, binds) <- gentleCheckLoop loc givens wanteds
920         ; implic_bind <- bindIrreds loc qtvs givens irreds
921         ; return (binds `unionBags` implic_bind) }
922
923 -----------------------------------------------------------
924 -- tcSimplifyCheckPat is used for existential pattern match
925 tcSimplifyCheckPat :: InstLoc
926                    -> [TcTyVar]         -- Quantify over these
927                    -> [Inst]            -- Given
928                    -> [Inst]            -- Wanted
929                    -> TcM TcDictBinds   -- Bindings
930 tcSimplifyCheckPat loc qtvs givens wanteds
931   = ASSERT( all isTcTyVar qtvs && all isSkolemTyVar qtvs )
932     do  { traceTc (text "tcSimplifyCheckPat")
933         ; (irreds, binds) <- gentleCheckLoop loc givens wanteds
934         ; implic_bind <- bindIrredsR loc qtvs givens irreds
935         ; return (binds `unionBags` implic_bind) }
936
937 -----------------------------------------------------------
938 bindIrreds :: InstLoc -> [TcTyVar]
939            -> [Inst] -> [Inst]
940            -> TcM TcDictBinds
941 bindIrreds loc qtvs givens irreds 
942   = bindIrredsR loc qtvs givens irreds
943
944 bindIrredsR :: InstLoc -> [TcTyVar] -> [Inst] -> [Inst] -> TcM TcDictBinds      
945 -- Make a binding that binds 'irreds', by generating an implication
946 -- constraint for them, *and* throwing the constraint into the LIE
947 bindIrredsR loc qtvs givens irreds
948   | null irreds
949   = return emptyBag
950   | otherwise
951   = do  { let givens' = filter isAbstractableInst givens
952                 -- The givens can (redundantly) include methods
953                 -- We want to retain both EqInsts and Dicts
954                 -- There should be no implicadtion constraints
955                 -- See Note [Pruning the givens in an implication constraint]
956
957            -- If there are no 'givens', then it's safe to 
958            -- partition the 'wanteds' by their qtvs, thereby trimming irreds
959            -- See Note [Freeness and implications]
960         ; irreds' <- if null givens'
961                      then do
962                         { let qtv_set = mkVarSet qtvs
963                               (frees, real_irreds) = partition (isFreeWrtTyVars qtv_set) irreds
964                         ; extendLIEs frees
965                         ; return real_irreds }
966                      else return irreds
967         
968         ; (implics, bind) <- makeImplicationBind loc qtvs givens' irreds'
969                         -- This call does the real work
970                         -- If irreds' is empty, it does something sensible
971         ; extendLIEs implics
972         ; return bind } 
973
974
975 makeImplicationBind :: InstLoc -> [TcTyVar]
976                     -> [Inst] -> [Inst]
977                     -> TcM ([Inst], TcDictBinds)
978 -- Make a binding that binds 'irreds', by generating an implication
979 -- constraint for them.
980 --
981 -- The binding looks like
982 --      (ir1, .., irn) = f qtvs givens
983 -- where f is (evidence for) the new implication constraint
984 --      f :: forall qtvs. givens => (ir1, .., irn)
985 -- qtvs includes coercion variables
986 --
987 -- This binding must line up the 'rhs' in reduceImplication
988 makeImplicationBind loc all_tvs
989                     givens      -- Guaranteed all Dicts or EqInsts
990                     irreds
991  | null irreds                  -- If there are no irreds, we are done
992  = return ([], emptyBag)
993  | otherwise                    -- Otherwise we must generate a binding
994  = do   { uniq <- newUnique 
995         ; span <- getSrcSpanM
996         ; let (eq_givens, dict_givens) = partition isEqInst givens
997
998                 -- extract equality binders
999               eq_cotvs = map eqInstType eq_givens
1000
1001                 -- make the implication constraint instance
1002               name = mkInternalName uniq (mkVarOcc "ic") span
1003               implic_inst = ImplicInst { tci_name = name,
1004                                          tci_tyvars = all_tvs, 
1005                                          tci_given = eq_givens ++ dict_givens,
1006                                                        -- same order as binders
1007                                          tci_wanted = irreds, 
1008                                          tci_loc = loc }
1009
1010                 -- create binders for the irreducible dictionaries
1011               dict_irreds    = filter (not . isEqInst) irreds
1012               dict_irred_ids = map instToId dict_irreds
1013               lpat = mkBigLHsPatTup (map (L span . VarPat) dict_irred_ids)
1014
1015                 -- create the binding
1016               rhs  = L span (mkHsWrap co (HsVar (instToId implic_inst)))
1017               co   =     mkWpApps (map instToId dict_givens)
1018                      <.> mkWpTyApps eq_cotvs
1019                      <.> mkWpTyApps (mkTyVarTys all_tvs)
1020               bind | [dict_irred_id] <- dict_irred_ids  
1021                    = VarBind dict_irred_id rhs
1022                    | otherwise        
1023                    = PatBind { pat_lhs = lpat
1024                              , pat_rhs = unguardedGRHSs rhs 
1025                              , pat_rhs_ty = hsLPatType lpat
1026                              , bind_fvs = placeHolderNames 
1027                              }
1028
1029         ; traceTc $ text "makeImplicationBind" <+> ppr implic_inst
1030         ; return ([implic_inst], unitBag (L span bind)) 
1031         }
1032
1033 -----------------------------------------------------------
1034 tryHardCheckLoop :: SDoc
1035              -> [Inst]                  -- Wanted
1036              -> TcM ([Inst], TcDictBinds)
1037
1038 tryHardCheckLoop doc wanteds
1039   = do { (irreds,binds) <- checkLoop (mkInferRedEnv doc try_me) wanteds
1040        ; return (irreds,binds)
1041        }
1042   where
1043     try_me _ = ReduceMe
1044         -- Here's the try-hard bit
1045
1046 -----------------------------------------------------------
1047 gentleCheckLoop :: InstLoc
1048                -> [Inst]                -- Given
1049                -> [Inst]                -- Wanted
1050                -> TcM ([Inst], TcDictBinds)
1051
1052 gentleCheckLoop inst_loc givens wanteds
1053   = do { (irreds,binds) <- checkLoop env wanteds
1054        ; return (irreds,binds)
1055        }
1056   where
1057     env = mkRedEnv (pprInstLoc inst_loc) try_me givens
1058
1059     try_me inst | isMethodOrLit inst = ReduceMe
1060                 | otherwise          = Stop
1061         -- When checking against a given signature 
1062         -- we MUST be very gentle: Note [Check gently]
1063
1064 gentleInferLoop :: SDoc -> [Inst]
1065                 -> TcM ([Inst], TcDictBinds)
1066 gentleInferLoop doc wanteds
1067   = do  { (irreds, binds) <- checkLoop env wanteds
1068         ; return (irreds, binds) }
1069   where
1070     env = mkInferRedEnv doc try_me
1071     try_me inst | isMethodOrLit inst = ReduceMe
1072                 | otherwise          = Stop
1073 \end{code}
1074
1075 Note [Check gently]
1076 ~~~~~~~~~~~~~~~~~~~~
1077 We have to very careful about not simplifying too vigorously
1078 Example:  
1079   data T a where
1080     MkT :: a -> T [a]
1081
1082   f :: Show b => T b -> b
1083   f (MkT x) = show [x]
1084
1085 Inside the pattern match, which binds (a:*, x:a), we know that
1086         b ~ [a]
1087 Hence we have a dictionary for Show [a] available; and indeed we 
1088 need it.  We are going to build an implication contraint
1089         forall a. (b~[a]) => Show [a]
1090 Later, we will solve this constraint using the knowledge (Show b)
1091         
1092 But we MUST NOT reduce (Show [a]) to (Show a), else the whole
1093 thing becomes insoluble.  So we simplify gently (get rid of literals
1094 and methods only, plus common up equal things), deferring the real
1095 work until top level, when we solve the implication constraint
1096 with tryHardCheckLooop.
1097
1098
1099 \begin{code}
1100 -----------------------------------------------------------
1101 checkLoop :: RedEnv
1102           -> [Inst]                     -- Wanted
1103           -> TcM ([Inst], TcDictBinds) 
1104 -- Precondition: givens are completely rigid
1105 -- Postcondition: returned Insts are zonked
1106
1107 checkLoop env wanteds
1108   = go env wanteds
1109   where go env wanteds
1110           = do  {  -- We do need to zonk the givens; cf Note [Zonking RedEnv]
1111                 ; env'     <- zonkRedEnv env
1112                 ; wanteds' <- zonkInsts  wanteds
1113         
1114                 ; (improved, tybinds, binds, irreds) 
1115                     <- reduceContext env' wanteds'
1116                 ; execTcTyVarBinds tybinds
1117
1118                 ; if null irreds || not improved then
1119                     return (irreds, binds)
1120                   else do
1121         
1122                 -- If improvement did some unification, we go round again.
1123                 -- We start again with irreds, not wanteds
1124                 -- Using an instance decl might have introduced a fresh type
1125                 -- variable which might have been unified, so we'd get an 
1126                 -- infinite loop if we started again with wanteds!  
1127                 -- See Note [LOOP]
1128                 { (irreds1, binds1) <- go env' irreds
1129                 ; return (irreds1, binds `unionBags` binds1) } }
1130 \end{code}
1131
1132 Note [Zonking RedEnv]
1133 ~~~~~~~~~~~~~~~~~~~~~
1134 It might appear as if the givens in RedEnv are always rigid, but that is not
1135 necessarily the case for programs involving higher-rank types that have class
1136 contexts constraining the higher-rank variables.  An example from tc237 in the
1137 testsuite is
1138
1139   class Modular s a | s -> a
1140
1141   wim ::  forall a w. Integral a 
1142                         => a -> (forall s. Modular s a => M s w) -> w
1143   wim i k = error "urk"
1144
1145   test5  ::  (Modular s a, Integral a) => M s a
1146   test5  =   error "urk"
1147
1148   test4   =   wim 4 test4'
1149
1150 Notice how the variable 'a' of (Modular s a) in the rank-2 type of wim is
1151 quantified further outside.  When type checking test4, we have to check
1152 whether the signature of test5 is an instance of 
1153
1154   (forall s. Modular s a => M s w)
1155
1156 Consequently, we will get (Modular s t_a), where t_a is a TauTv into the
1157 givens. 
1158
1159 Given the FD of Modular in this example, class improvement will instantiate
1160 t_a to 'a', where 'a' is the skolem from test5's signatures (due to the
1161 Modular s a predicate in that signature).  If we don't zonk (Modular s t_a) in
1162 the givens, we will get into a loop as improveOne uses the unification engine
1163 Unify.tcUnifyTys, which doesn't know about mutable type variables.
1164
1165
1166 Note [LOOP]
1167 ~~~~~~~~~~~
1168         class If b t e r | b t e -> r
1169         instance If T t e t
1170         instance If F t e e
1171         class Lte a b c | a b -> c where lte :: a -> b -> c
1172         instance Lte Z b T
1173         instance (Lte a b l,If l b a c) => Max a b c
1174
1175 Wanted: Max Z (S x) y
1176
1177 Then we'll reduce using the Max instance to:
1178         (Lte Z (S x) l, If l (S x) Z y)
1179 and improve by binding l->T, after which we can do some reduction
1180 on both the Lte and If constraints.  What we *can't* do is start again
1181 with (Max Z (S x) y)!
1182
1183
1184
1185 %************************************************************************
1186 %*                                                                      *
1187                 tcSimplifySuperClasses
1188 %*                                                                      *
1189 %************************************************************************
1190
1191 Note [SUPERCLASS-LOOP 1]
1192 ~~~~~~~~~~~~~~~~~~~~~~~~
1193 We have to be very, very careful when generating superclasses, lest we
1194 accidentally build a loop. Here's an example:
1195
1196   class S a
1197
1198   class S a => C a where { opc :: a -> a }
1199   class S b => D b where { opd :: b -> b }
1200   
1201   instance C Int where
1202      opc = opd
1203   
1204   instance D Int where
1205      opd = opc
1206
1207 From (instance C Int) we get the constraint set {ds1:S Int, dd:D Int}
1208 Simplifying, we may well get:
1209         $dfCInt = :C ds1 (opd dd)
1210         dd  = $dfDInt
1211         ds1 = $p1 dd
1212 Notice that we spot that we can extract ds1 from dd.  
1213
1214 Alas!  Alack! We can do the same for (instance D Int):
1215
1216         $dfDInt = :D ds2 (opc dc)
1217         dc  = $dfCInt
1218         ds2 = $p1 dc
1219
1220 And now we've defined the superclass in terms of itself.
1221 Two more nasty cases are in
1222         tcrun021
1223         tcrun033
1224
1225 Solution: 
1226   - Satisfy the superclass context *all by itself* 
1227     (tcSimplifySuperClasses)
1228   - And do so completely; i.e. no left-over constraints
1229     to mix with the constraints arising from method declarations
1230
1231
1232 Note [Recursive instances and superclases]
1233 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1234 Consider this code, which arises in the context of "Scrap Your 
1235 Boilerplate with Class".  
1236
1237     class Sat a
1238     class Data ctx a
1239     instance  Sat (ctx Char)             => Data ctx Char
1240     instance (Sat (ctx [a]), Data ctx a) => Data ctx [a]
1241
1242     class Data Maybe a => Foo a
1243
1244     instance Foo t => Sat (Maybe t)
1245
1246     instance Data Maybe a => Foo a
1247     instance Foo a        => Foo [a]
1248     instance                 Foo [Char]
1249
1250 In the instance for Foo [a], when generating evidence for the superclasses
1251 (ie in tcSimplifySuperClasses) we need a superclass (Data Maybe [a]).
1252 Using the instance for Data, we therefore need
1253         (Sat (Maybe [a], Data Maybe a)
1254 But we are given (Foo a), and hence its superclass (Data Maybe a).
1255 So that leaves (Sat (Maybe [a])).  Using the instance for Sat means
1256 we need (Foo [a]).  And that is the very dictionary we are bulding
1257 an instance for!  So we must put that in the "givens".  So in this
1258 case we have
1259         Given:  Foo a, Foo [a]
1260         Watend: Data Maybe [a]
1261
1262 BUT we must *not not not* put the *superclasses* of (Foo [a]) in
1263 the givens, which is what 'addGiven' would normally do. Why? Because
1264 (Data Maybe [a]) is the superclass, so we'd "satisfy" the wanted 
1265 by selecting a superclass from Foo [a], which simply makes a loop.
1266
1267 On the other hand we *must* put the superclasses of (Foo a) in
1268 the givens, as you can see from the derivation described above.
1269
1270 Conclusion: in the very special case of tcSimplifySuperClasses
1271 we have one 'given' (namely the "this" dictionary) whose superclasses
1272 must not be added to 'givens' by addGiven.  
1273
1274 There is a complication though.  Suppose there are equalities
1275       instance (Eq a, a~b) => Num (a,b)
1276 Then we normalise the 'givens' wrt the equalities, so the original
1277 given "this" dictionary is cast to one of a different type.  So it's a
1278 bit trickier than before to identify the "special" dictionary whose
1279 superclasses must not be added. See test
1280    indexed-types/should_run/EqInInstance
1281
1282 We need a persistent property of the dictionary to record this
1283 special-ness.  Current I'm using the InstLocOrigin (a bit of a hack,
1284 but cool), which is maintained by dictionary normalisation.
1285 Specifically, the InstLocOrigin is
1286              NoScOrigin
1287 then the no-superclass thing kicks in.  WATCH OUT if you fiddle
1288 with InstLocOrigin!
1289
1290 \begin{code}
1291 tcSimplifySuperClasses
1292         :: InstLoc 
1293         -> Inst         -- The dict whose superclasses 
1294                         -- are being figured out
1295         -> [Inst]       -- Given 
1296         -> [Inst]       -- Wanted
1297         -> TcM TcDictBinds
1298 tcSimplifySuperClasses loc this givens sc_wanteds
1299   = do  { traceTc (text "tcSimplifySuperClasses")
1300
1301               -- Note [Recursive instances and superclases]
1302         ; no_sc_loc <- getInstLoc NoScOrigin
1303         ; let no_sc_this = setInstLoc this no_sc_loc
1304
1305         ; let env =  RedEnv { red_doc = pprInstLoc loc, 
1306                               red_try_me = try_me,
1307                               red_givens = no_sc_this : givens, 
1308                               red_stack = (0,[]),
1309                               red_improve = False }  -- No unification vars
1310
1311
1312         ; (irreds,binds1) <- checkLoop env sc_wanteds
1313         ; let (tidy_env, tidy_irreds) = tidyInsts irreds
1314         ; reportNoInstances tidy_env (Just (loc, givens)) [] tidy_irreds
1315         ; return binds1 }
1316   where
1317     try_me _ = ReduceMe  -- Try hard, so we completely solve the superclass 
1318                          -- constraints right here. See Note [SUPERCLASS-LOOP 1]
1319 \end{code}
1320
1321
1322 %************************************************************************
1323 %*                                                                      *
1324 \subsection{tcSimplifyRestricted}
1325 %*                                                                      *
1326 %************************************************************************
1327
1328 tcSimplifyRestricted infers which type variables to quantify for a 
1329 group of restricted bindings.  This isn't trivial.
1330
1331 Eg1:    id = \x -> x
1332         We want to quantify over a to get id :: forall a. a->a
1333         
1334 Eg2:    eq = (==)
1335         We do not want to quantify over a, because there's an Eq a 
1336         constraint, so we get eq :: a->a->Bool  (notice no forall)
1337
1338 So, assume:
1339         RHS has type 'tau', whose free tyvars are tau_tvs
1340         RHS has constraints 'wanteds'
1341
1342 Plan A (simple)
1343   Quantify over (tau_tvs \ ftvs(wanteds))
1344   This is bad. The constraints may contain (Monad (ST s))
1345   where we have         instance Monad (ST s) where...
1346   so there's no need to be monomorphic in s!
1347
1348   Also the constraint might be a method constraint,
1349   whose type mentions a perfectly innocent tyvar:
1350           op :: Num a => a -> b -> a
1351   Here, b is unconstrained.  A good example would be
1352         foo = op (3::Int)
1353   We want to infer the polymorphic type
1354         foo :: forall b. b -> b
1355
1356
1357 Plan B (cunning, used for a long time up to and including GHC 6.2)
1358   Step 1: Simplify the constraints as much as possible (to deal 
1359   with Plan A's problem).  Then set
1360         qtvs = tau_tvs \ ftvs( simplify( wanteds ) )
1361
1362   Step 2: Now simplify again, treating the constraint as 'free' if 
1363   it does not mention qtvs, and trying to reduce it otherwise.
1364   The reasons for this is to maximise sharing.
1365
1366   This fails for a very subtle reason.  Suppose that in the Step 2
1367   a constraint (Foo (Succ Zero) (Succ Zero) b) gets thrown upstairs as 'free'.
1368   In the Step 1 this constraint might have been simplified, perhaps to
1369   (Foo Zero Zero b), AND THEN THAT MIGHT BE IMPROVED, to bind 'b' to 'T'.
1370   This won't happen in Step 2... but that in turn might prevent some other
1371   constraint (Baz [a] b) being simplified (e.g. via instance Baz [a] T where {..}) 
1372   and that in turn breaks the invariant that no constraints are quantified over.
1373
1374   Test typecheck/should_compile/tc177 (which failed in GHC 6.2) demonstrates
1375   the problem.
1376
1377
1378 Plan C (brutal)
1379   Step 1: Simplify the constraints as much as possible (to deal 
1380   with Plan A's problem).  Then set
1381         qtvs = tau_tvs \ ftvs( simplify( wanteds ) )
1382   Return the bindings from Step 1.
1383   
1384
1385 A note about Plan C (arising from "bug" reported by George Russel March 2004)
1386 Consider this:
1387
1388       instance (HasBinary ty IO) => HasCodedValue ty
1389
1390       foo :: HasCodedValue a => String -> IO a
1391
1392       doDecodeIO :: HasCodedValue a => () -> () -> IO a
1393       doDecodeIO codedValue view  
1394         = let { act = foo "foo" } in  act
1395
1396 You might think this should work becuase the call to foo gives rise to a constraint
1397 (HasCodedValue t), which can be satisfied by the type sig for doDecodeIO.  But the
1398 restricted binding act = ... calls tcSimplifyRestricted, and PlanC simplifies the
1399 constraint using the (rather bogus) instance declaration, and now we are stuffed.
1400
1401 I claim this is not really a bug -- but it bit Sergey as well as George.  So here's
1402 plan D
1403
1404
1405 Plan D (a variant of plan B)
1406   Step 1: Simplify the constraints as much as possible (to deal 
1407   with Plan A's problem), BUT DO NO IMPROVEMENT.  Then set
1408         qtvs = tau_tvs \ ftvs( simplify( wanteds ) )
1409
1410   Step 2: Now simplify again, treating the constraint as 'free' if 
1411   it does not mention qtvs, and trying to reduce it otherwise.
1412
1413   The point here is that it's generally OK to have too few qtvs; that is,
1414   to make the thing more monomorphic than it could be.  We don't want to
1415   do that in the common cases, but in wierd cases it's ok: the programmer
1416   can always add a signature.  
1417
1418   Too few qtvs => too many wanteds, which is what happens if you do less
1419   improvement.
1420
1421
1422 \begin{code}
1423 tcSimplifyRestricted    -- Used for restricted binding groups
1424                         -- i.e. ones subject to the monomorphism restriction
1425         :: SDoc
1426         -> TopLevelFlag
1427         -> [Name]               -- Things bound in this group
1428         -> TcTyVarSet           -- Free in the type of the RHSs
1429         -> [Inst]               -- Free in the RHSs
1430         -> TcM ([TyVar],        -- Tyvars to quantify (zonked and quantified)
1431                 TcDictBinds)    -- Bindings
1432         -- tcSimpifyRestricted returns no constraints to
1433         -- quantify over; by definition there are none.
1434         -- They are all thrown back in the LIE
1435
1436 tcSimplifyRestricted doc top_lvl bndrs tau_tvs wanteds
1437         -- Zonk everything in sight
1438   = do  { traceTc (text "tcSimplifyRestricted")
1439         ; wanteds_z <- zonkInsts wanteds
1440
1441         -- 'ReduceMe': Reduce as far as we can.  Don't stop at
1442         -- dicts; the idea is to get rid of as many type
1443         -- variables as possible, and we don't want to stop
1444         -- at (say) Monad (ST s), because that reduces
1445         -- immediately, with no constraint on s.
1446         --
1447         -- BUT do no improvement!  See Plan D above
1448         -- HOWEVER, some unification may take place, if we instantiate
1449         --          a method Inst with an equality constraint
1450         ; let env = mkNoImproveRedEnv doc (\_ -> ReduceMe)
1451         ; (_imp, _tybinds, _binds, constrained_dicts) 
1452             <- reduceContext env wanteds_z
1453
1454         -- Next, figure out the tyvars we will quantify over
1455         ; tau_tvs' <- zonkTcTyVarsAndFV (varSetElems tau_tvs)
1456         ; gbl_tvs' <- tcGetGlobalTyVars
1457         ; constrained_dicts' <- zonkInsts constrained_dicts
1458
1459         ; let qtvs1 = tau_tvs' `minusVarSet` oclose (fdPredsOfInsts constrained_dicts) gbl_tvs'
1460                                 -- As in tcSimplifyInfer
1461
1462                 -- Do not quantify over constrained type variables:
1463                 -- this is the monomorphism restriction
1464               constrained_tvs' = tyVarsOfInsts constrained_dicts'
1465               qtvs = qtvs1 `minusVarSet` constrained_tvs'
1466               pp_bndrs = pprWithCommas (quotes . ppr) bndrs
1467
1468         -- Warn in the mono
1469         ; warn_mono <- doptM Opt_WarnMonomorphism
1470         ; warnTc (warn_mono && (constrained_tvs' `intersectsVarSet` qtvs1))
1471                  (vcat[ ptext (sLit "the Monomorphism Restriction applies to the binding")
1472                                 <> plural bndrs <+> ptext (sLit "for") <+> pp_bndrs,
1473                         ptext (sLit "Consider giving a type signature for") <+> pp_bndrs])
1474
1475         ; traceTc (text "tcSimplifyRestricted" <+> vcat [
1476                 pprInsts wanteds, pprInsts constrained_dicts',
1477                 ppr _binds,
1478                 ppr constrained_tvs', ppr tau_tvs', ppr qtvs ])
1479
1480         -- The first step may have squashed more methods than
1481         -- necessary, so try again, this time more gently, knowing the exact
1482         -- set of type variables to quantify over.
1483         --
1484         -- We quantify only over constraints that are captured by qtvs;
1485         -- these will just be a subset of non-dicts.  This in contrast
1486         -- to normal inference (using isFreeWhenInferring) in which we quantify over
1487         -- all *non-inheritable* constraints too.  This implements choice
1488         -- (B) under "implicit parameter and monomorphism" above.
1489         --
1490         -- Remember that we may need to do *some* simplification, to
1491         -- (for example) squash {Monad (ST s)} into {}.  It's not enough
1492         -- just to float all constraints
1493         --
1494         -- At top level, we *do* squash methods becuase we want to 
1495         -- expose implicit parameters to the test that follows
1496         ; let is_nested_group = isNotTopLevel top_lvl
1497               try_me inst | isFreeWrtTyVars qtvs inst,
1498                            (is_nested_group || isDict inst) = Stop
1499                           | otherwise                       = ReduceMe 
1500               env = mkNoImproveRedEnv doc try_me
1501         ; (_imp, tybinds, binds, irreds) <- reduceContext env wanteds_z
1502         ; execTcTyVarBinds tybinds
1503
1504         -- See "Notes on implicit parameters, Question 4: top level"
1505         ; ASSERT( all (isFreeWrtTyVars qtvs) irreds )   -- None should be captured
1506           if is_nested_group then
1507                 extendLIEs irreds
1508           else do { let (bad_ips, non_ips) = partition isIPDict irreds
1509                   ; addTopIPErrs bndrs bad_ips
1510                   ; extendLIEs non_ips }
1511
1512         ; qtvs' <- zonkQuantifiedTyVars (varSetElems qtvs)
1513         ; return (qtvs', binds) }
1514 \end{code}
1515
1516
1517 %************************************************************************
1518 %*                                                                      *
1519                 tcSimplifyRuleLhs
1520 %*                                                                      *
1521 %************************************************************************
1522
1523 On the LHS of transformation rules we only simplify methods and constants,
1524 getting dictionaries.  We want to keep all of them unsimplified, to serve
1525 as the available stuff for the RHS of the rule.
1526
1527 Example.  Consider the following left-hand side of a rule
1528         
1529         f (x == y) (y > z) = ...
1530
1531 If we typecheck this expression we get constraints
1532
1533         d1 :: Ord a, d2 :: Eq a
1534
1535 We do NOT want to "simplify" to the LHS
1536
1537         forall x::a, y::a, z::a, d1::Ord a.
1538           f ((==) (eqFromOrd d1) x y) ((>) d1 y z) = ...
1539
1540 Instead we want 
1541
1542         forall x::a, y::a, z::a, d1::Ord a, d2::Eq a.
1543           f ((==) d2 x y) ((>) d1 y z) = ...
1544
1545 Here is another example:
1546
1547         fromIntegral :: (Integral a, Num b) => a -> b
1548         {-# RULES "foo"  fromIntegral = id :: Int -> Int #-}
1549
1550 In the rule, a=b=Int, and Num Int is a superclass of Integral Int. But
1551 we *dont* want to get
1552
1553         forall dIntegralInt.
1554            fromIntegral Int Int dIntegralInt (scsel dIntegralInt) = id Int
1555
1556 because the scsel will mess up RULE matching.  Instead we want
1557
1558         forall dIntegralInt, dNumInt.
1559           fromIntegral Int Int dIntegralInt dNumInt = id Int
1560
1561 Even if we have 
1562
1563         g (x == y) (y == z) = ..
1564
1565 where the two dictionaries are *identical*, we do NOT WANT
1566
1567         forall x::a, y::a, z::a, d1::Eq a
1568           f ((==) d1 x y) ((>) d1 y z) = ...
1569
1570 because that will only match if the dict args are (visibly) equal.
1571 Instead we want to quantify over the dictionaries separately.
1572
1573 In short, tcSimplifyRuleLhs must *only* squash LitInst and MethInts, leaving
1574 all dicts unchanged, with absolutely no sharing.  It's simpler to do this
1575 from scratch, rather than further parameterise simpleReduceLoop etc.
1576 Simpler, maybe, but alas not simple (see Trac #2494)
1577
1578 * Type errors may give rise to an (unsatisfiable) equality constraint
1579
1580 * Applications of a higher-rank function on the LHS may give
1581   rise to an implication constraint, esp if there are unsatisfiable
1582   equality constraints inside.
1583
1584 \begin{code}
1585 tcSimplifyRuleLhs :: [Inst] -> TcM ([Inst], TcDictBinds)
1586 tcSimplifyRuleLhs wanteds
1587   = do  { wanteds' <- zonkInsts wanteds
1588         
1589                 -- Simplify equalities  
1590                 -- It's important to do this: Trac #3346 for example
1591         ; (_, wanteds'', tybinds, binds1) <- tcReduceEqs [] wanteds'
1592         ; execTcTyVarBinds tybinds
1593
1594                 -- Simplify other constraints
1595         ; (irreds, binds2) <- go [] emptyBag wanteds''
1596
1597                 -- Report anything that is left
1598         ; let (dicts, bad_irreds) = partition isDict irreds
1599         ; traceTc (text "tcSimplifyrulelhs" <+> pprInsts bad_irreds)
1600         ; addNoInstanceErrs (nub bad_irreds)
1601                 -- The nub removes duplicates, which has
1602                 -- not happened otherwise (see notes above)
1603
1604         ; return (dicts, binds1 `unionBags` binds2) }
1605   where
1606     go :: [Inst] -> TcDictBinds -> [Inst] -> TcM ([Inst], TcDictBinds)
1607     go irreds binds []
1608         = return (irreds, binds)
1609     go irreds binds (w:ws)
1610         | isDict w
1611         = go (w:irreds) binds ws
1612         | isImplicInst w        -- Have a go at reducing the implication
1613         = do { (binds1, irreds1) <- reduceImplication red_env w
1614              ; let (bad_irreds, ok_irreds) = partition isImplicInst irreds1
1615              ; go (bad_irreds ++ irreds) 
1616                   (binds `unionBags` binds1) 
1617                   (ok_irreds ++ ws)}
1618         | otherwise
1619         = do { w' <- zonkInst w  -- So that (3::Int) does not generate a call
1620                                  -- to fromInteger; this looks fragile to me
1621              ; lookup_result <- lookupSimpleInst w'
1622              ; case lookup_result of
1623                  NoInstance      -> go (w:irreds) binds ws
1624                  GenInst ws' rhs -> go irreds binds' (ws' ++ ws)
1625                         where
1626                           binds' = addInstToDictBind binds w rhs
1627           }
1628
1629         -- Sigh: we need to reduce inside implications
1630     red_env = mkInferRedEnv doc try_me
1631     doc = ptext (sLit "Implication constraint in RULE lhs")
1632     try_me inst | isMethodOrLit inst = ReduceMe
1633                 | otherwise          = Stop     -- Be gentle
1634 \end{code}
1635
1636 tcSimplifyBracket is used when simplifying the constraints arising from
1637 a Template Haskell bracket [| ... |].  We want to check that there aren't
1638 any constraints that can't be satisfied (e.g. Show Foo, where Foo has no
1639 Show instance), but we aren't otherwise interested in the results.
1640 Nor do we care about ambiguous dictionaries etc.  We will type check
1641 this bracket again at its usage site.
1642
1643 \begin{code}
1644 tcSimplifyBracket :: [Inst] -> TcM ()
1645 tcSimplifyBracket wanteds
1646   = do  { _ <- tryHardCheckLoop doc wanteds
1647         ; return () }
1648   where
1649     doc = text "tcSimplifyBracket"
1650 \end{code}
1651
1652
1653 %************************************************************************
1654 %*                                                                      *
1655 \subsection{Filtering at a dynamic binding}
1656 %*                                                                      *
1657 %************************************************************************
1658
1659 When we have
1660         let ?x = R in B
1661
1662 we must discharge all the ?x constraints from B.  We also do an improvement
1663 step; if we have ?x::t1 and ?x::t2 we must unify t1, t2.
1664
1665 Actually, the constraints from B might improve the types in ?x. For example
1666
1667         f :: (?x::Int) => Char -> Char
1668         let ?x = 3 in f 'c'
1669
1670 then the constraint (?x::Int) arising from the call to f will
1671 force the binding for ?x to be of type Int.
1672
1673 \begin{code}
1674 tcSimplifyIPs :: [Inst]         -- The implicit parameters bound here
1675               -> [Inst]         -- Wanted
1676               -> TcM TcDictBinds
1677         -- We need a loop so that we do improvement, and then
1678         -- (next time round) generate a binding to connect the two
1679         --      let ?x = e in ?x
1680         -- Here the two ?x's have different types, and improvement 
1681         -- makes them the same.
1682
1683 tcSimplifyIPs given_ips wanteds
1684   = do  { wanteds'   <- zonkInsts wanteds
1685         ; given_ips' <- zonkInsts given_ips
1686                 -- Unusually for checking, we *must* zonk the given_ips
1687
1688         ; let env = mkRedEnv doc try_me given_ips'
1689         ; (improved, tybinds, binds, irreds) <- reduceContext env wanteds'
1690         ; execTcTyVarBinds tybinds
1691
1692         ; if null irreds || not improved then 
1693                 ASSERT( all is_free irreds )
1694                 do { extendLIEs irreds
1695                    ; return binds }
1696           else do
1697         -- If improvement did some unification, we go round again.
1698         -- We start again with irreds, not wanteds
1699         -- Using an instance decl might have introduced a fresh type
1700         -- variable which might have been unified, so we'd get an 
1701         -- infinite loop if we started again with wanteds!  
1702         -- See Note [LOOP]
1703         { binds1 <- tcSimplifyIPs given_ips' irreds
1704         ; return $ binds `unionBags` binds1
1705         } }
1706   where
1707     doc    = text "tcSimplifyIPs" <+> ppr given_ips
1708     ip_set = mkNameSet (ipNamesOfInsts given_ips)
1709     is_free inst = isFreeWrtIPs ip_set inst
1710
1711         -- Simplify any methods that mention the implicit parameter
1712     try_me inst | is_free inst = Stop
1713                 | otherwise    = ReduceMe
1714 \end{code}
1715
1716
1717 %************************************************************************
1718 %*                                                                      *
1719 \subsection[binds-for-local-funs]{@bindInstsOfLocalFuns@}
1720 %*                                                                      *
1721 %************************************************************************
1722
1723 When doing a binding group, we may have @Insts@ of local functions.
1724 For example, we might have...
1725 \begin{verbatim}
1726 let f x = x + 1     -- orig local function (overloaded)
1727     f.1 = f Int     -- two instances of f
1728     f.2 = f Float
1729  in
1730     (f.1 5, f.2 6.7)
1731 \end{verbatim}
1732 The point is: we must drop the bindings for @f.1@ and @f.2@ here,
1733 where @f@ is in scope; those @Insts@ must certainly not be passed
1734 upwards towards the top-level.  If the @Insts@ were binding-ified up
1735 there, they would have unresolvable references to @f@.
1736
1737 We pass in an @init_lie@ of @Insts@ and a list of locally-bound @Ids@.
1738 For each method @Inst@ in the @init_lie@ that mentions one of the
1739 @Ids@, we create a binding.  We return the remaining @Insts@ (in an
1740 @LIE@), as well as the @HsBinds@ generated.
1741
1742 \begin{code}
1743 bindInstsOfLocalFuns :: [Inst] -> [TcId] -> TcM TcDictBinds
1744 -- Simlifies only MethodInsts, and generate only bindings of form 
1745 --      fm = f tys dicts
1746 -- We're careful not to even generate bindings of the form
1747 --      d1 = d2
1748 -- You'd think that'd be fine, but it interacts with what is
1749 -- arguably a bug in Match.tidyEqnInfo (see notes there)
1750
1751 bindInstsOfLocalFuns wanteds local_ids
1752   | null overloaded_ids = do
1753         -- Common case
1754     extendLIEs wanteds
1755     return emptyLHsBinds
1756
1757   | otherwise
1758   = do  { (irreds, binds) <- gentleInferLoop doc for_me
1759         ; extendLIEs not_for_me 
1760         ; extendLIEs irreds
1761         ; return binds }
1762   where
1763     doc              = text "bindInsts" <+> ppr local_ids
1764     overloaded_ids   = filter is_overloaded local_ids
1765     is_overloaded id = isOverloadedTy (idType id)
1766     (for_me, not_for_me) = partition (isMethodFor overloaded_set) wanteds
1767
1768     overloaded_set = mkVarSet overloaded_ids    -- There can occasionally be a lot of them
1769                                                 -- so it's worth building a set, so that
1770                                                 -- lookup (in isMethodFor) is faster
1771 \end{code}
1772
1773
1774 %************************************************************************
1775 %*                                                                      *
1776 \subsection{Data types for the reduction mechanism}
1777 %*                                                                      *
1778 %************************************************************************
1779
1780 The main control over context reduction is here
1781
1782 \begin{code}
1783 data RedEnv 
1784   = RedEnv { red_doc    :: SDoc                 -- The context
1785            , red_try_me :: Inst -> WhatToDo
1786            , red_improve :: Bool                -- True <=> do improvement
1787            , red_givens :: [Inst]               -- All guaranteed rigid
1788                                                 -- Always dicts & equalities
1789                                                 -- but see Note [Rigidity]
1790  
1791            , red_stack  :: (Int, [Inst])        -- Recursion stack (for err msg)
1792                                                 -- See Note [RedStack]
1793   }
1794
1795 -- Note [Rigidity]
1796 -- The red_givens are rigid so far as cmpInst is concerned.
1797 -- There is one case where they are not totally rigid, namely in tcSimplifyIPs
1798 --      let ?x = e in ...
1799 -- Here, the given is (?x::a), where 'a' is not necy a rigid type
1800 -- But that doesn't affect the comparison, which is based only on mame.
1801
1802 -- Note [RedStack]
1803 -- The red_stack pair (n,insts) pair is just used for error reporting.
1804 -- 'n' is always the depth of the stack.
1805 -- The 'insts' is the stack of Insts being reduced: to produce X
1806 -- I had to produce Y, to produce Y I had to produce Z, and so on.
1807
1808
1809 mkRedEnv :: SDoc -> (Inst -> WhatToDo) -> [Inst] -> RedEnv
1810 mkRedEnv doc try_me givens
1811   = RedEnv { red_doc = doc, red_try_me = try_me,
1812              red_givens = givens, 
1813              red_stack = (0,[]),
1814              red_improve = True }       
1815
1816 mkInferRedEnv :: SDoc -> (Inst -> WhatToDo) -> RedEnv
1817 -- No givens at all
1818 mkInferRedEnv doc try_me
1819   = RedEnv { red_doc = doc, red_try_me = try_me,
1820              red_givens = [], 
1821              red_stack = (0,[]),
1822              red_improve = True }       
1823
1824 mkNoImproveRedEnv :: SDoc -> (Inst -> WhatToDo) -> RedEnv
1825 -- Do not do improvement; no givens
1826 mkNoImproveRedEnv doc try_me
1827   = RedEnv { red_doc = doc, red_try_me = try_me,
1828              red_givens = [], 
1829              red_stack = (0,[]),
1830              red_improve = True }       
1831
1832 data WhatToDo
1833  = ReduceMe     -- Try to reduce this
1834                 -- If there's no instance, add the inst to the 
1835                 -- irreductible ones, but don't produce an error 
1836                 -- message of any kind.
1837                 -- It might be quite legitimate such as (Eq a)!
1838
1839  | Stop         -- Return as irreducible unless it can
1840                         -- be reduced to a constant in one step
1841                         -- Do not add superclasses; see 
1842
1843 data WantSCs = NoSCs | AddSCs   -- Tells whether we should add the superclasses
1844                                 -- of a predicate when adding it to the avails
1845         -- The reason for this flag is entirely the super-class loop problem
1846         -- Note [SUPER-CLASS LOOP 1]
1847
1848 zonkRedEnv :: RedEnv -> TcM RedEnv
1849 zonkRedEnv env
1850   = do { givens' <- mapM zonkInst (red_givens env)
1851        ; return $ env {red_givens = givens'}
1852        }
1853 \end{code}
1854
1855
1856 %************************************************************************
1857 %*                                                                      *
1858 \subsection[reduce]{@reduce@}
1859 %*                                                                      *
1860 %************************************************************************
1861
1862 Note [Ancestor Equalities]
1863 ~~~~~~~~~~~~~~~~~~~~~~~~~~
1864 During context reduction, we add to the wanted equalities also those
1865 equalities that (transitively) occur in superclass contexts of wanted
1866 class constraints.  Consider the following code
1867
1868   class a ~ Int => C a
1869   instance C Int
1870
1871 If (C a) is wanted, we want to add (a ~ Int), which will be discharged by
1872 substituting Int for a.  Hence, we ultimately want (C Int), which we
1873 discharge with the explicit instance.
1874
1875 \begin{code}
1876 reduceContext :: RedEnv
1877               -> [Inst]                 -- Wanted
1878               -> TcM (ImprovementDone,
1879                       TcTyVarBinds,     -- Type variable bindings
1880                       TcDictBinds,      -- Dictionary bindings
1881                       [Inst])           -- Irreducible
1882
1883 reduceContext env wanteds0
1884   = do  { traceTc (text "reduceContext" <+> (vcat [
1885              text "----------------------",
1886              red_doc env,
1887              text "given" <+> ppr (red_givens env),
1888              text "wanted" <+> ppr wanteds0,
1889              text "----------------------"
1890              ]))
1891
1892           -- We want to add as wanted equalities those that (transitively) 
1893           -- occur in superclass contexts of wanted class constraints.
1894           -- See Note [Ancestor Equalities]
1895         ; ancestor_eqs <- ancestorEqualities wanteds0
1896         ; traceTc $ text "reduceContext: ancestor eqs" <+> ppr ancestor_eqs
1897
1898           -- Normalise and solve all equality constraints as far as possible
1899           -- and normalise all dictionary constraints wrt to the reduced
1900           -- equalities.  The returned wanted constraints include the
1901           -- irreducible wanted equalities.
1902         ; let wanteds = wanteds0 ++ ancestor_eqs
1903               givens  = red_givens env
1904         ; (givens', 
1905            wanteds', 
1906            tybinds,
1907            normalise_binds) <- tcReduceEqs givens wanteds
1908         ; traceTc $ text "reduceContext: tcReduceEqs result" <+> vcat
1909                       [ppr givens', ppr wanteds', ppr tybinds, 
1910                        ppr normalise_binds]
1911
1912           -- Build the Avail mapping from "given_dicts"
1913         ; (init_state, _) <- getLIE $ do 
1914                 { init_state <- foldlM addGiven emptyAvails givens'
1915                 ; return init_state
1916                 }
1917
1918           -- Solve the *wanted* *dictionary* constraints (not implications)
1919           -- This may expose some further equational constraints in the course
1920           -- of improvement due to functional dependencies if any of the
1921           -- involved unifications gets deferred.
1922         ; let (wanted_implics, wanted_dicts) = partition isImplicInst wanteds'
1923         ; (avails, extra_eqs) <- getLIE (reduceList env wanted_dicts init_state)
1924                    -- The getLIE is reqd because reduceList does improvement
1925                    -- (via extendAvails) which may in turn do unification
1926         ; (dict_binds, 
1927            bound_dicts, 
1928            dict_irreds)       <- extractResults avails wanted_dicts
1929         ; traceTc $ text "reduceContext: extractResults" <+> vcat
1930                       [ppr avails, ppr wanted_dicts, ppr dict_binds]
1931
1932           -- Solve the wanted *implications*.  In doing so, we can provide
1933           -- as "given"   all the dicts that were originally given, 
1934           --              *or* for which we now have bindings, 
1935           --              *or* which are now irreds
1936           -- NB: Equality irreds need to be converted, as the recursive 
1937           --     invocation of the solver will still treat them as wanteds
1938           --     otherwise.
1939         ; let implic_env = env { red_givens 
1940                                    = givens ++ bound_dicts ++
1941                                      map wantedToLocalEqInst dict_irreds }
1942         ; (implic_binds_s, implic_irreds_s) 
1943             <- mapAndUnzipM (reduceImplication implic_env) wanted_implics
1944         ; let implic_binds  = unionManyBags implic_binds_s
1945               implic_irreds = concat implic_irreds_s
1946
1947           -- Collect all irreducible instances, and determine whether we should
1948           -- go round again.  We do so in either of two cases:
1949           -- (1) If dictionary reduction or equality solving led to
1950           --     improvement (i.e., bindings for type variables).
1951           -- (2) If we reduced dictionaries (i.e., got dictionary bindings),
1952           --     they may have exposed further opportunities to normalise
1953           --     family applications.  See Note [Dictionary Improvement]
1954           --
1955           -- NB: We do *not* go around for new extra_eqs.  Morally, we should,
1956           --     but we can't without risking non-termination (see #2688).  By
1957           --     not going around, we miss some legal programs mixing FDs and
1958           --     TFs, but we never claimed to support such programs in the
1959           --     current implementation anyway.
1960
1961         ; let all_irreds       = dict_irreds ++ implic_irreds ++ extra_eqs
1962               avails_improved  = availsImproved avails
1963               eq_improved      = anyBag (not . isCoVarBind) tybinds
1964               improvedFlexible = avails_improved || eq_improved
1965               reduced_dicts    = not (isEmptyBag dict_binds)
1966               improved         = improvedFlexible || reduced_dicts
1967               --
1968               improvedHint  = (if avails_improved then " [AVAILS]" else "") ++
1969                               (if eq_improved then " [EQ]" else "")
1970
1971         ; traceTc (text "reduceContext end" <+> (vcat [
1972              text "----------------------",
1973              red_doc env,
1974              text "given" <+> ppr givens,
1975              text "wanted" <+> ppr wanteds0,
1976              text "----",
1977              text "tybinds" <+> ppr tybinds,
1978              text "avails" <+> pprAvails avails,
1979              text "improved =" <+> ppr improved <+> text improvedHint,
1980              text "(all) irreds = " <+> ppr all_irreds,
1981              text "dict-binds = " <+> ppr dict_binds,
1982              text "implic-binds = " <+> ppr implic_binds,
1983              text "----------------------"
1984              ]))
1985
1986         ; return (improved, 
1987                   tybinds,
1988                   normalise_binds `unionBags` dict_binds 
1989                                   `unionBags` implic_binds, 
1990                   all_irreds) 
1991         }
1992   where
1993     isCoVarBind (TcTyVarBind tv _) = isCoVar tv
1994
1995 tcImproveOne :: Avails -> Inst -> TcM ImprovementDone
1996 tcImproveOne avails inst
1997   | not (isDict inst) = return False
1998   | otherwise
1999   = do  { inst_envs <- tcGetInstEnvs
2000         ; let eqns = improveOne (classInstances inst_envs)
2001                                 (dictPred inst, pprInstArising inst)
2002                                 [ (dictPred p, pprInstArising p)
2003                                 | p <- availsInsts avails, isDict p ]
2004                 -- Avails has all the superclasses etc (good)
2005                 -- It also has all the intermediates of the deduction (good)
2006                 -- It does not have duplicates (good)
2007                 -- NB that (?x::t1) and (?x::t2) will be held separately in 
2008                 --    avails so that improve will see them separate
2009         ; traceTc (text "improveOne" <+> ppr inst)
2010         ; unifyEqns eqns }
2011
2012 unifyEqns :: [(Equation, (PredType, SDoc), (PredType, SDoc))] 
2013           -> TcM ImprovementDone
2014 unifyEqns [] = return False
2015 unifyEqns eqns
2016   = do  { traceTc (ptext (sLit "Improve:") <+> vcat (map pprEquationDoc eqns))
2017         ; improved <- mapM unify eqns
2018         ; return $ or improved
2019         }
2020   where
2021     unify ((qtvs, pairs), what1, what2)
2022          = addErrCtxtM (mkEqnMsg what1 what2) $ 
2023              do { let freeTyVars = unionVarSets (map tvs_pr pairs) 
2024                                    `minusVarSet` qtvs
2025                 ; (_, _, tenv) <- tcInstTyVars (varSetElems qtvs)
2026                 ; mapM_ (unif_pr tenv) pairs
2027                 ; anyM isFilledMetaTyVar $ varSetElems freeTyVars
2028                 }
2029
2030     unif_pr tenv (ty1, ty2) = unifyType (substTy tenv ty1) (substTy tenv ty2)
2031
2032     tvs_pr (ty1, ty2) = tyVarsOfType ty1 `unionVarSet` tyVarsOfType ty2
2033
2034 pprEquationDoc :: (Equation, (PredType, SDoc), (PredType, SDoc)) -> SDoc
2035 pprEquationDoc (eqn, (p1, _), (p2, _)) 
2036   = vcat [pprEquation eqn, nest 2 (ppr p1), nest 2 (ppr p2)]
2037
2038 mkEqnMsg :: (TcPredType, SDoc) -> (TcPredType, SDoc) -> TidyEnv
2039          -> TcM (TidyEnv, SDoc)
2040 mkEqnMsg (pred1,from1) (pred2,from2) tidy_env
2041   = do  { pred1' <- zonkTcPredType pred1
2042         ; pred2' <- zonkTcPredType pred2
2043         ; let { pred1'' = tidyPred tidy_env pred1'
2044               ; pred2'' = tidyPred tidy_env pred2' }
2045         ; let msg = vcat [ptext (sLit "When using functional dependencies to combine"),
2046                           nest 2 (sep [ppr pred1'' <> comma, nest 2 from1]), 
2047                           nest 2 (sep [ppr pred2'' <> comma, nest 2 from2])]
2048         ; return (tidy_env, msg) }
2049 \end{code}
2050
2051 Note [Dictionary Improvement]
2052 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2053 In reduceContext, we first reduce equalities and then class constraints.
2054 However, the letter may expose further opportunities for the former.  Hence,
2055 we need to go around again if dictionary reduction produced any dictionary
2056 bindings.  The following example demonstrated the point:
2057
2058   data EX _x _y (p :: * -> *)
2059   data ANY
2060
2061   class Base p
2062
2063   class Base (Def p) => Prop p where
2064    type Def p
2065
2066   instance Base ()
2067   instance Prop () where
2068    type Def () = ()
2069
2070   instance (Base (Def (p ANY))) => Base (EX _x _y p)
2071   instance (Prop (p ANY)) => Prop (EX _x _y p) where
2072    type Def (EX _x _y p) = EX _x _y p
2073
2074   data FOO x
2075   instance Prop (FOO x) where
2076    type Def (FOO x) = ()
2077
2078   data BAR
2079   instance Prop BAR where
2080    type Def BAR = EX () () FOO
2081
2082 During checking the last instance declaration, we need to check the superclass
2083 cosntraint Base (Def BAR), which family normalisation reduced to 
2084 Base (EX () () FOO).  Chasing the instance for Base (EX _x _y p), gives us
2085 Base (Def (FOO ANY)), which again requires family normalisation of Def to
2086 Base () before we can finish.
2087
2088
2089 The main context-reduction function is @reduce@.  Here's its game plan.
2090
2091 \begin{code}
2092 reduceList :: RedEnv -> [Inst] -> Avails -> TcM Avails
2093 reduceList env@(RedEnv {red_stack = (n,stk)}) wanteds state
2094   = do  { traceTc (text "reduceList " <+> (ppr wanteds $$ ppr state))
2095         ; dopts <- getDOpts
2096         ; when (debugIsOn && (n > 8)) $ do
2097                 debugDumpTcRn (hang (ptext (sLit "Interesting! Context reduction stack depth") <+> int n) 
2098                              2 (ifPprDebug (nest 2 (pprStack stk))))
2099         ; if n >= ctxtStkDepth dopts then
2100             failWithTc (reduceDepthErr n stk)
2101           else
2102             go wanteds state }
2103   where
2104     go []     state = return state
2105     go (w:ws) state = do { state' <- reduce (env {red_stack = (n+1, w:stk)}) w state
2106                          ; go ws state' }
2107
2108     -- Base case: we're done!
2109 reduce :: RedEnv -> Inst -> Avails -> TcM Avails
2110 reduce env wanted avails
2111
2112     -- We don't reduce equalities here (and they must not end up as irreds
2113     -- in the Avails!)
2114   | isEqInst wanted
2115   = return avails
2116
2117     -- It's the same as an existing inst, or a superclass thereof
2118   | Just _ <- findAvail avails wanted
2119   = do { traceTc (text "reduce: found " <+> ppr wanted)
2120        ; return avails
2121        }
2122
2123   | otherwise
2124   = do  { traceTc (text "reduce" <+> ppr wanted $$ ppr avails)
2125         ; case red_try_me env wanted of {
2126             Stop -> try_simple (addIrred NoSCs);
2127                         -- See Note [No superclasses for Stop]
2128
2129             ReduceMe -> do      -- It should be reduced
2130                 { (avails, lookup_result) <- reduceInst env avails wanted
2131                 ; case lookup_result of
2132                     NoInstance -> addIrred AddSCs avails wanted
2133                              -- Add it and its superclasses
2134                              
2135                     GenInst [] rhs -> addWanted AddSCs avails wanted rhs []
2136
2137                     GenInst wanteds' rhs
2138                           -> do { avails1 <- addIrred NoSCs avails wanted
2139                                 ; avails2 <- reduceList env wanteds' avails1
2140                                 ; addWanted AddSCs avails2 wanted rhs wanteds' } }
2141                 -- Temporarily do addIrred *before* the reduceList, 
2142                 -- which has the effect of adding the thing we are trying
2143                 -- to prove to the database before trying to prove the things it
2144                 -- needs.  See note [RECURSIVE DICTIONARIES]
2145                 -- NB: we must not do an addWanted before, because that adds the
2146                 --     superclasses too, and that can lead to a spurious loop; see
2147                 --     the examples in [SUPERCLASS-LOOP]
2148                 -- So we do an addIrred before, and then overwrite it afterwards with addWanted
2149     } }
2150   where
2151         -- First, see if the inst can be reduced to a constant in one step
2152         -- Works well for literals (1::Int) and constant dictionaries (d::Num Int)
2153         -- Don't bother for implication constraints, which take real work
2154     try_simple do_this_otherwise
2155       = do { res <- lookupSimpleInst wanted
2156            ; case res of
2157                 GenInst [] rhs -> addWanted AddSCs avails wanted rhs []
2158                 _              -> do_this_otherwise avails wanted }
2159 \end{code}
2160
2161
2162 Note [RECURSIVE DICTIONARIES]
2163 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2164 Consider 
2165     data D r = ZeroD | SuccD (r (D r));
2166     
2167     instance (Eq (r (D r))) => Eq (D r) where
2168         ZeroD     == ZeroD     = True
2169         (SuccD a) == (SuccD b) = a == b
2170         _         == _         = False;
2171     
2172     equalDC :: D [] -> D [] -> Bool;
2173     equalDC = (==);
2174
2175 We need to prove (Eq (D [])).  Here's how we go:
2176
2177         d1 : Eq (D [])
2178
2179 by instance decl, holds if
2180         d2 : Eq [D []]
2181         where   d1 = dfEqD d2
2182
2183 by instance decl of Eq, holds if
2184         d3 : D []
2185         where   d2 = dfEqList d3
2186                 d1 = dfEqD d2
2187
2188 But now we can "tie the knot" to give
2189
2190         d3 = d1
2191         d2 = dfEqList d3
2192         d1 = dfEqD d2
2193
2194 and it'll even run!  The trick is to put the thing we are trying to prove
2195 (in this case Eq (D []) into the database before trying to prove its
2196 contributing clauses.
2197         
2198 Note [SUPERCLASS-LOOP 2]
2199 ~~~~~~~~~~~~~~~~~~~~~~~~
2200 We need to be careful when adding "the constaint we are trying to prove".
2201 Suppose we are *given* d1:Ord a, and want to deduce (d2:C [a]) where
2202
2203         class Ord a => C a where
2204         instance Ord [a] => C [a] where ...
2205
2206 Then we'll use the instance decl to deduce C [a] from Ord [a], and then add the
2207 superclasses of C [a] to avails.  But we must not overwrite the binding
2208 for Ord [a] (which is obtained from Ord a) with a superclass selection or we'll just
2209 build a loop! 
2210
2211 Here's another variant, immortalised in tcrun020
2212         class Monad m => C1 m
2213         class C1 m => C2 m x
2214         instance C2 Maybe Bool
2215 For the instance decl we need to build (C1 Maybe), and it's no good if
2216 we run around and add (C2 Maybe Bool) and its superclasses to the avails 
2217 before we search for C1 Maybe.
2218
2219 Here's another example 
2220         class Eq b => Foo a b
2221         instance Eq a => Foo [a] a
2222 If we are reducing
2223         (Foo [t] t)
2224
2225 we'll first deduce that it holds (via the instance decl).  We must not
2226 then overwrite the Eq t constraint with a superclass selection!
2227
2228 At first I had a gross hack, whereby I simply did not add superclass constraints
2229 in addWanted, though I did for addGiven and addIrred.  This was sub-optimal,
2230 becuase it lost legitimate superclass sharing, and it still didn't do the job:
2231 I found a very obscure program (now tcrun021) in which improvement meant the
2232 simplifier got two bites a the cherry... so something seemed to be an Stop
2233 first time, but reducible next time.
2234
2235 Now we implement the Right Solution, which is to check for loops directly 
2236 when adding superclasses.  It's a bit like the occurs check in unification.
2237
2238
2239
2240 %************************************************************************
2241 %*                                                                      *
2242                 Reducing a single constraint
2243 %*                                                                      *
2244 %************************************************************************
2245
2246 \begin{code}
2247 ---------------------------------------------
2248 reduceInst :: RedEnv -> Avails -> Inst -> TcM (Avails, LookupInstResult)
2249 reduceInst _ avails other_inst
2250   = do  { result <- lookupSimpleInst other_inst
2251         ; return (avails, result) }
2252 \end{code}
2253
2254 Note [Equational Constraints in Implication Constraints]
2255 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2256
2257 An implication constraint is of the form 
2258         Given => Wanted 
2259 where Given and Wanted may contain both equational and dictionary
2260 constraints. The delay and reduction of these two kinds of constraints
2261 is distinct:
2262
2263 -) In the generated code, wanted Dictionary constraints are wrapped up in an
2264    implication constraint that is created at the code site where the wanted
2265    dictionaries can be reduced via a let-binding. This let-bound implication
2266    constraint is deconstructed at the use-site of the wanted dictionaries.
2267
2268 -) While the reduction of equational constraints is also delayed, the delay
2269    is not manifest in the generated code. The required evidence is generated
2270    in the code directly at the use-site. There is no let-binding and deconstruction
2271    necessary. The main disadvantage is that we cannot exploit sharing as the
2272    same evidence may be generated at multiple use-sites. However, this disadvantage
2273    is limited because it only concerns coercions which are erased.
2274
2275 The different treatment is motivated by the different in representation. Dictionary
2276 constraints require manifest runtime dictionaries, while equations require coercions
2277 which are types.
2278
2279 \begin{code}
2280 ---------------------------------------------
2281 reduceImplication :: RedEnv
2282                   -> Inst
2283                   -> TcM (TcDictBinds, [Inst])
2284 \end{code}
2285
2286 Suppose we are simplifying the constraint
2287         forall bs. extras => wanted
2288 in the context of an overall simplification problem with givens 'givens'.
2289
2290 Note that
2291   * The 'givens' need not mention any of the quantified type variables
2292         e.g.    forall {}. Eq a => Eq [a]
2293                 forall {}. C Int => D (Tree Int)
2294
2295     This happens when you have something like
2296         data T a where
2297           T1 :: Eq a => a -> T a
2298
2299         f :: T a -> Int
2300         f x = ...(case x of { T1 v -> v==v })...
2301
2302 \begin{code}
2303         -- ToDo: should we instantiate tvs?  I think it's not necessary
2304         --
2305         -- Note on coercion variables:
2306         --
2307         --      The extra given coercion variables are bound at two different 
2308         --      sites:
2309         --
2310         --      -) in the creation context of the implication constraint        
2311         --              the solved equational constraints use these binders
2312         --
2313         --      -) at the solving site of the implication constraint
2314         --              the solved dictionaries use these binders;
2315         --              these binders are generated by reduceImplication
2316         --
2317         -- Note [Binders for equalities]
2318         -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2319         -- To reuse the binders of local/given equalities in the binders of 
2320         -- implication constraints, it is crucial that these given equalities
2321         -- always have the form
2322         --   cotv :: t1 ~ t2
2323         -- where cotv is a simple coercion type variable (and not a more
2324         -- complex coercion term).  We require that the extra_givens always
2325         -- have this form and exploit the special form when generating binders.
2326 reduceImplication env
2327         orig_implic@(ImplicInst { tci_name = name, tci_loc = inst_loc,
2328                                   tci_tyvars = tvs,
2329                                   tci_given = extra_givens, tci_wanted = wanteds
2330                                  })
2331   = do  {       -- Solve the sub-problem
2332         ; let try_me _ = ReduceMe  -- Note [Freeness and implications]
2333               env' = env { red_givens = extra_givens ++ red_givens env
2334                          , red_doc = sep [ptext (sLit "reduceImplication for") 
2335                                             <+> ppr name,
2336                                           nest 2 (parens $ ptext (sLit "within")
2337                                                            <+> red_doc env)]
2338                          , red_try_me = try_me }
2339
2340         ; traceTc (text "reduceImplication" <+> vcat
2341                         [ ppr (red_givens env), ppr extra_givens, 
2342                           ppr wanteds])
2343         ; (irreds, binds) <- checkLoop env' wanteds
2344
2345         ; traceTc (text "reduceImplication result" <+> vcat
2346                         [ppr irreds, ppr binds])
2347
2348         ; -- extract superclass binds
2349           --  (sc_binds,_) <- extractResults avails []
2350 --      ; traceTc (text "reduceImplication sc_binds" <+> vcat
2351 --                      [ppr sc_binds, ppr avails])
2352 --  
2353
2354         -- SLPJ Sept 07: what if improvement happened inside the checkLoop?
2355         -- Then we must iterate the outer loop too!
2356
2357         ; didntSolveWantedEqs <- allM wantedEqInstIsUnsolved wanteds
2358                                    -- we solve wanted eqs by side effect!
2359
2360             -- Progress is no longer measered by the number of bindings
2361             -- If there are any irreds, but no bindings and no solved
2362             -- equalities, we back off and do nothing
2363         ; let backOff = isEmptyLHsBinds binds &&   -- no new bindings
2364                         (not $ null irreds)   &&   -- but still some irreds
2365                         didntSolveWantedEqs        -- no instantiated cotv
2366
2367         ; if backOff then       -- No progress
2368                 return (emptyBag, [orig_implic])
2369           else do
2370         { (simpler_implic_insts, bind) 
2371             <- makeImplicationBind inst_loc tvs extra_givens irreds
2372                 -- This binding is useless if the recursive simplification
2373                 -- made no progress; but currently we don't try to optimise that
2374                 -- case.  After all, we only try hard to reduce at top level, or
2375                 -- when inferring types.
2376
2377         ; let   -- extract Id binders for dicts and CoTyVar binders for eqs;
2378                 -- see Note [Binders for equalities]
2379               (extra_eq_givens, extra_dict_givens) = partition isEqInst 
2380                                                                extra_givens
2381               eq_cotvs = map instToVar extra_eq_givens
2382               dict_ids = map instToId  extra_dict_givens 
2383
2384                         -- Note [Always inline implication constraints]
2385               wrap_inline | null dict_ids = idHsWrapper
2386                           | otherwise     = WpInline
2387               co         = wrap_inline
2388                            <.> mkWpTyLams tvs
2389                            <.> mkWpTyLams eq_cotvs
2390                            <.> mkWpLams dict_ids
2391                            <.> WpLet (binds `unionBags` bind)
2392               rhs        = mkLHsWrap co payload
2393               loc        = instLocSpan inst_loc
2394                              -- wanted equalities are solved by updating their
2395                              -- cotv; we don't generate bindings for them
2396               dict_bndrs =   map (L loc . HsVar . instToId) 
2397                            . filter (not . isEqInst) 
2398                            $ wanteds
2399               payload    = mkBigLHsTup dict_bndrs
2400
2401         
2402         ; traceTc (vcat [text "reduceImplication" <+> ppr name,
2403                          ppr simpler_implic_insts,
2404                          text "->" <+> ppr rhs])
2405         ; return (unitBag (L loc (VarBind (instToId orig_implic) rhs)),
2406                   simpler_implic_insts)
2407         } 
2408     }
2409 reduceImplication _ i = pprPanic "reduceImplication" (ppr i)
2410 \end{code}
2411
2412 Note [Always inline implication constraints]
2413 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2414 Suppose an implication constraint floats out of an INLINE function.
2415 Then although the implication has a single call site, it won't be 
2416 inlined.  And that is bad because it means that even if there is really
2417 *no* overloading (type signatures specify the exact types) there will
2418 still be dictionary passing in the resulting code.  To avert this,
2419 we mark the implication constraints themselves as INLINE, at least when
2420 there is no loss of sharing as a result.
2421
2422 Note [Freeness and implications]
2423 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2424 It's hard to say when an implication constraint can be floated out.  Consider
2425         forall {} Eq a => Foo [a]
2426 The (Foo [a]) doesn't mention any of the quantified variables, but it
2427 still might be partially satisfied by the (Eq a). 
2428
2429 There is a useful special case when it *is* easy to partition the 
2430 constraints, namely when there are no 'givens'.  Consider
2431         forall {a}. () => Bar b
2432 There are no 'givens', and so there is no reason to capture (Bar b).
2433 We can let it float out.  But if there is even one constraint we
2434 must be much more careful:
2435         forall {a}. C a b => Bar (m b)
2436 because (C a b) might have a superclass (D b), from which we might 
2437 deduce (Bar [b]) when m later gets instantiated to [].  Ha!
2438
2439 Here is an even more exotic example
2440         class C a => D a b
2441 Now consider the constraint
2442         forall b. D Int b => C Int
2443 We can satisfy the (C Int) from the superclass of D, so we don't want
2444 to float the (C Int) out, even though it mentions no type variable in
2445 the constraints!
2446
2447 One more example: the constraint
2448         class C a => D a b
2449         instance (C a, E c) => E (a,c)
2450
2451         constraint: forall b. D Int b => E (Int,c)
2452
2453 You might think that the (D Int b) can't possibly contribute
2454 to solving (E (Int,c)), since the latter mentions 'c'.  But 
2455 in fact it can, because solving the (E (Int,c)) constraint needs 
2456 dictionaries
2457         C Int, E c
2458 and the (C Int) can be satisfied from the superclass of (D Int b).
2459 So we must still not float (E (Int,c)) out.
2460
2461 To think about: special cases for unary type classes?
2462
2463 Note [Pruning the givens in an implication constraint]
2464 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2465 Suppose we are about to form the implication constraint
2466         forall tvs.  Eq a => Ord b
2467 The (Eq a) cannot contribute to the (Ord b), because it has no access to
2468 the type variable 'b'.  So we could filter out the (Eq a) from the givens.
2469 But BE CAREFUL of the examples above in [Freeness and implications].
2470
2471 Doing so would be a bit tidier, but all the implication constraints get
2472 simplified away by the optimiser, so it's no great win.   So I don't take
2473 advantage of that at the moment.
2474
2475 If you do, BE CAREFUL of wobbly type variables.
2476
2477
2478 %************************************************************************
2479 %*                                                                      *
2480                 Avails and AvailHow: the pool of evidence
2481 %*                                                                      *
2482 %************************************************************************
2483
2484
2485 \begin{code}
2486 data Avails = Avails !ImprovementDone !AvailEnv
2487
2488 type ImprovementDone = Bool     -- True <=> some unification has happened
2489                                 -- so some Irreds might now be reducible
2490                                 -- keys that are now 
2491
2492 type AvailEnv = FiniteMap Inst AvailHow
2493 data AvailHow
2494   = IsIrred             -- Used for irreducible dictionaries,
2495                         -- which are going to be lambda bound
2496
2497   | Given Inst          -- Used for dictionaries for which we have a binding
2498                         -- e.g. those "given" in a signature
2499
2500   | Rhs                 -- Used when there is a RHS
2501         (LHsExpr TcId)  -- The RHS
2502         [Inst]          -- Insts free in the RHS; we need these too
2503
2504 instance Outputable Avails where
2505   ppr = pprAvails
2506
2507 pprAvails :: Avails -> SDoc
2508 pprAvails (Avails imp avails)
2509   = vcat [ ptext (sLit "Avails") <> (if imp then ptext (sLit "[improved]") else empty)
2510          , nest 2 $ braces $ 
2511            vcat [ sep [ppr inst, nest 2 (equals <+> ppr avail)]
2512                 | (inst,avail) <- fmToList avails ]]
2513
2514 instance Outputable AvailHow where
2515     ppr = pprAvail
2516
2517 -------------------------
2518 pprAvail :: AvailHow -> SDoc
2519 pprAvail IsIrred        = text "Irred"
2520 pprAvail (Given x)      = text "Given" <+> ppr x
2521 pprAvail (Rhs rhs bs)   = sep [text "Rhs" <+> ppr bs,
2522                                nest 2 (ppr rhs)]
2523
2524 -------------------------
2525 extendAvailEnv :: AvailEnv -> Inst -> AvailHow -> AvailEnv
2526 extendAvailEnv env inst avail = addToFM env inst avail
2527
2528 findAvailEnv :: AvailEnv -> Inst -> Maybe AvailHow
2529 findAvailEnv env wanted = lookupFM env wanted
2530         -- NB 1: the Ord instance of Inst compares by the class/type info
2531         --  *not* by unique.  So
2532         --      d1::C Int ==  d2::C Int
2533
2534 emptyAvails :: Avails
2535 emptyAvails = Avails False emptyFM
2536
2537 findAvail :: Avails -> Inst -> Maybe AvailHow
2538 findAvail (Avails _ avails) wanted = findAvailEnv avails wanted
2539
2540 elemAvails :: Inst -> Avails -> Bool
2541 elemAvails wanted (Avails _ avails) = wanted `elemFM` avails
2542
2543 extendAvails :: Avails -> Inst -> AvailHow -> TcM Avails
2544 -- Does improvement
2545 extendAvails avails@(Avails imp env) inst avail
2546   = do  { imp1 <- tcImproveOne avails inst      -- Do any improvement
2547         ; return (Avails (imp || imp1) (extendAvailEnv env inst avail)) }
2548
2549 availsInsts :: Avails -> [Inst]
2550 availsInsts (Avails _ avails) = keysFM avails
2551
2552 availsImproved :: Avails -> ImprovementDone
2553 availsImproved (Avails imp _) = imp
2554 \end{code}
2555
2556 Extracting the bindings from a bunch of Avails.
2557 The bindings do *not* come back sorted in dependency order.
2558 We assume that they'll be wrapped in a big Rec, so that the
2559 dependency analyser can sort them out later
2560
2561 \begin{code}
2562 type DoneEnv = FiniteMap Inst [Id]
2563 -- Tracks which things we have evidence for
2564
2565 extractResults :: Avails
2566                -> [Inst]                -- Wanted
2567                -> TcM (TcDictBinds,     -- Bindings
2568                        [Inst],          -- The insts bound by the bindings
2569                        [Inst])          -- Irreducible ones
2570                         -- Note [Reducing implication constraints]
2571
2572 extractResults (Avails _ avails) wanteds
2573   = go emptyBag [] [] emptyFM wanteds
2574   where
2575     go  :: TcDictBinds  -- Bindings for dicts
2576         -> [Inst]       -- Bound by the bindings
2577         -> [Inst]       -- Irreds
2578         -> DoneEnv      -- Has an entry for each inst in the above three sets
2579         -> [Inst]       -- Wanted
2580         -> TcM (TcDictBinds, [Inst], [Inst])
2581     go binds bound_dicts irreds _ [] 
2582       = return (binds, bound_dicts, irreds)
2583
2584     go binds bound_dicts irreds done (w:ws)
2585       | isEqInst w
2586       = go binds bound_dicts (w:irreds) done' ws
2587
2588       | Just done_ids@(done_id : rest_done_ids) <- lookupFM done w
2589       = if w_id `elem` done_ids then
2590            go binds bound_dicts irreds done ws
2591         else
2592            go (add_bind (nlHsVar done_id)) bound_dicts irreds
2593               (addToFM done w (done_id : w_id : rest_done_ids)) ws
2594
2595       | otherwise       -- Not yet done
2596       = case findAvailEnv avails w of
2597           Nothing -> pprTrace "Urk: extractResults" (ppr w) $
2598                      go binds bound_dicts irreds done ws
2599
2600           Just IsIrred -> go binds bound_dicts (w:irreds) done' ws
2601
2602           Just (Rhs rhs ws') -> go (add_bind rhs) (w:bound_dicts) irreds done' (ws' ++ ws)
2603
2604           Just (Given g) -> go binds' bound_dicts irreds (addToFM done w [g_id]) ws 
2605                 where
2606                   g_id = instToId g
2607                   binds' | w_id == g_id = binds
2608                          | otherwise    = add_bind (nlHsVar g_id)
2609       where
2610         w_id  = instToId w      
2611         done' = addToFM done w [w_id]
2612         add_bind rhs = addInstToDictBind binds w rhs
2613 \end{code}
2614
2615
2616 Note [No superclasses for Stop]
2617 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2618 When we decide not to reduce an Inst -- the 'WhatToDo' --- we still
2619 add it to avails, so that any other equal Insts will be commoned up
2620 right here.  However, we do *not* add superclasses.  If we have
2621         df::Floating a
2622         dn::Num a
2623 but a is not bound here, then we *don't* want to derive dn from df
2624 here lest we lose sharing.
2625
2626 \begin{code}
2627 addWanted :: WantSCs -> Avails -> Inst -> LHsExpr TcId -> [Inst] -> TcM Avails
2628 addWanted want_scs avails wanted rhs_expr wanteds
2629   = addAvailAndSCs want_scs avails wanted avail
2630   where
2631     avail = Rhs rhs_expr wanteds
2632
2633 addGiven :: Avails -> Inst -> TcM Avails
2634 addGiven avails given 
2635   = addAvailAndSCs want_scs avails given (Given given)
2636   where
2637     want_scs = case instLocOrigin (instLoc given) of
2638                  NoScOrigin -> NoSCs
2639                  _other     -> AddSCs
2640         -- Conditionally add superclasses for 'given'
2641         -- See Note [Recursive instances and superclases]
2642
2643   -- No ASSERT( not (given `elemAvails` avails) ) because in an
2644   -- instance decl for Ord t we can add both Ord t and Eq t as
2645   -- 'givens', so the assert isn't true
2646 \end{code}
2647
2648 \begin{code}
2649 addIrred :: WantSCs -> Avails -> Inst -> TcM Avails
2650 addIrred want_scs avails irred = ASSERT2( not (irred `elemAvails` avails), ppr irred $$ ppr avails )
2651                                  addAvailAndSCs want_scs avails irred IsIrred
2652
2653 addAvailAndSCs :: WantSCs -> Avails -> Inst -> AvailHow -> TcM Avails
2654 addAvailAndSCs want_scs avails inst avail
2655   | not (isClassDict inst) = extendAvails avails inst avail
2656   | NoSCs <- want_scs      = extendAvails avails inst avail
2657   | otherwise              = do { traceTc (text "addAvailAndSCs" <+> vcat [ppr inst, ppr deps])
2658                                 ; avails' <- extendAvails avails inst avail
2659                                 ; addSCs is_loop avails' inst }
2660   where
2661     is_loop pred = any (`tcEqType` mkPredTy pred) dep_tys
2662                         -- Note: this compares by *type*, not by Unique
2663     deps         = findAllDeps (unitVarSet (instToVar inst)) avail
2664     dep_tys      = map idType (varSetElems deps)
2665
2666     findAllDeps :: IdSet -> AvailHow -> IdSet
2667     -- Find all the Insts that this one depends on
2668     -- See Note [SUPERCLASS-LOOP 2]
2669     -- Watch out, though.  Since the avails may contain loops 
2670     -- (see Note [RECURSIVE DICTIONARIES]), so we need to track the ones we've seen so far
2671     findAllDeps so_far (Rhs _ kids) = foldl find_all so_far kids
2672     findAllDeps so_far _            = so_far
2673
2674     find_all :: IdSet -> Inst -> IdSet
2675     find_all so_far kid
2676       | isEqInst kid                       = so_far
2677       | kid_id `elemVarSet` so_far         = so_far
2678       | Just avail <- findAvail avails kid = findAllDeps so_far' avail
2679       | otherwise                          = so_far'
2680       where
2681         so_far' = extendVarSet so_far kid_id    -- Add the new kid to so_far
2682         kid_id = instToId kid
2683
2684 addSCs :: (TcPredType -> Bool) -> Avails -> Inst -> TcM Avails
2685         -- Add all the superclasses of the Inst to Avails
2686         -- The first param says "don't do this because the original thing
2687         --      depends on this one, so you'd build a loop"
2688         -- Invariant: the Inst is already in Avails.
2689
2690 addSCs is_loop avails dict
2691   = ASSERT( isDict dict )
2692     do  { sc_dicts <- newDictBndrs (instLoc dict) sc_theta'
2693         ; foldlM add_sc avails (zipEqual "add_scs" sc_dicts sc_sels) }
2694   where
2695     (clas, tys) = getDictClassTys dict
2696     (tyvars, sc_theta, sc_sels, _) = classBigSig clas
2697     sc_theta' = filter (not . isEqPred) $
2698                   substTheta (zipTopTvSubst tyvars tys) sc_theta
2699
2700     add_sc avails (sc_dict, sc_sel)
2701       | is_loop (dictPred sc_dict) = return avails      -- See Note [SUPERCLASS-LOOP 2]
2702       | is_given sc_dict           = return avails
2703       | otherwise                  = do { avails' <- extendAvails avails sc_dict (Rhs sc_sel_rhs [dict])
2704                                         ; addSCs is_loop avails' sc_dict }
2705       where
2706         sc_sel_rhs = L (instSpan dict) (HsWrap co_fn (HsVar sc_sel))
2707         co_fn      = WpApp (instToVar dict) <.> mkWpTyApps tys
2708
2709     is_given :: Inst -> Bool
2710     is_given sc_dict = case findAvail avails sc_dict of
2711                           Just (Given _) -> True        -- Given is cheaper than superclass selection
2712                           _              -> False
2713
2714 -- From the a set of insts obtain all equalities that (transitively) occur in
2715 -- superclass contexts of class constraints (aka the ancestor equalities). 
2716 --
2717 ancestorEqualities :: [Inst] -> TcM [Inst]
2718 ancestorEqualities
2719   =   mapM mkWantedEqInst               -- turn only equality predicates..
2720     . filter isEqPred                   -- ..into wanted equality insts
2721     . bagToList 
2722     . addAEsToBag emptyBag              -- collect the superclass constraints..
2723     . map dictPred                      -- ..of all predicates in a bag
2724     . filter isClassDict
2725   where
2726     addAEsToBag :: Bag PredType -> [PredType] -> Bag PredType
2727     addAEsToBag bag []           = bag
2728     addAEsToBag bag (pred:preds)
2729       | pred `elemBag` bag = addAEsToBag bag         preds
2730       | isEqPred pred      = addAEsToBag bagWithPred preds
2731       | isClassPred pred   = addAEsToBag bagWithPred predsWithSCs
2732       | otherwise          = addAEsToBag bag         preds
2733       where
2734         bagWithPred  = bag `snocBag` pred
2735         predsWithSCs = preds ++ substTheta (zipTopTvSubst tyvars tys) sc_theta
2736         --
2737         (tyvars, sc_theta, _, _) = classBigSig clas
2738         (clas, tys)              = getClassPredTys pred 
2739 \end{code}
2740
2741
2742 %************************************************************************
2743 %*                                                                      *
2744 \section{tcSimplifyTop: defaulting}
2745 %*                                                                      *
2746 %************************************************************************
2747
2748
2749 @tcSimplifyTop@ is called once per module to simplify all the constant
2750 and ambiguous Insts.
2751
2752 We need to be careful of one case.  Suppose we have
2753
2754         instance Num a => Num (Foo a b) where ...
2755
2756 and @tcSimplifyTop@ is given a constraint (Num (Foo x y)).  Then it'll simplify
2757 to (Num x), and default x to Int.  But what about y??
2758
2759 It's OK: the final zonking stage should zap y to (), which is fine.
2760
2761
2762 \begin{code}
2763 tcSimplifyTop, tcSimplifyInteractive :: [Inst] -> TcM TcDictBinds
2764 tcSimplifyTop wanteds
2765   = tc_simplify_top doc False wanteds
2766   where 
2767     doc = text "tcSimplifyTop"
2768
2769 tcSimplifyInteractive wanteds
2770   = tc_simplify_top doc True wanteds
2771   where 
2772     doc = text "tcSimplifyInteractive"
2773
2774 -- The TcLclEnv should be valid here, solely to improve
2775 -- error message generation for the monomorphism restriction
2776 tc_simplify_top :: SDoc -> Bool -> [Inst] -> TcM (Bag (LHsBind TcId))
2777 tc_simplify_top doc interactive wanteds
2778   = do  { dflags <- getDOpts
2779         ; wanteds <- zonkInsts wanteds
2780         ; mapM_ zonkTopTyVar (varSetElems (tyVarsOfInsts wanteds))
2781
2782         ; traceTc (text "tc_simplify_top 0: " <+> ppr wanteds)
2783         ; (irreds1, binds1) <- tryHardCheckLoop doc1 wanteds
2784 --      ; (irreds1, binds1) <- gentleInferLoop doc1 wanteds
2785         ; traceTc (text "tc_simplify_top 1: " <+> ppr irreds1)
2786         ; (irreds2, binds2) <- approximateImplications doc2 (\_ -> True) irreds1
2787         ; traceTc (text "tc_simplify_top 2: " <+> ppr irreds2)
2788
2789                 -- Use the defaulting rules to do extra unification
2790                 -- NB: irreds2 are already zonked
2791         ; (irreds3, binds3) <- disambiguate doc3 interactive dflags irreds2
2792
2793                 -- Deal with implicit parameters
2794         ; let (bad_ips, non_ips) = partition isIPDict irreds3
2795               (ambigs, others)   = partition isTyVarDict non_ips
2796
2797         ; topIPErrs bad_ips     -- Can arise from   f :: Int -> Int
2798                                 --                  f x = x + ?y
2799         ; addNoInstanceErrs others
2800         ; addTopAmbigErrs ambigs        
2801
2802         ; return (binds1 `unionBags` binds2 `unionBags` binds3) }
2803   where
2804     doc1 = doc <+> ptext (sLit "(first round)")
2805     doc2 = doc <+> ptext (sLit "(approximate)")
2806     doc3 = doc <+> ptext (sLit "(disambiguate)")
2807 \end{code}
2808
2809 If a dictionary constrains a type variable which is
2810         * not mentioned in the environment
2811         * and not mentioned in the type of the expression
2812 then it is ambiguous. No further information will arise to instantiate
2813 the type variable; nor will it be generalised and turned into an extra
2814 parameter to a function.
2815
2816 It is an error for this to occur, except that Haskell provided for
2817 certain rules to be applied in the special case of numeric types.
2818 Specifically, if
2819         * at least one of its classes is a numeric class, and
2820         * all of its classes are numeric or standard
2821 then the type variable can be defaulted to the first type in the
2822 default-type list which is an instance of all the offending classes.
2823
2824 So here is the function which does the work.  It takes the ambiguous
2825 dictionaries and either resolves them (producing bindings) or
2826 complains.  It works by splitting the dictionary list by type
2827 variable, and using @disambigOne@ to do the real business.
2828
2829 @disambigOne@ assumes that its arguments dictionaries constrain all
2830 the same type variable.
2831
2832 ADR Comment 20/6/94: I've changed the @CReturnable@ case to default to
2833 @()@ instead of @Int@.  I reckon this is the Right Thing to do since
2834 the most common use of defaulting is code like:
2835 \begin{verbatim}
2836         _ccall_ foo     `seqPrimIO` bar
2837 \end{verbatim}
2838 Since we're not using the result of @foo@, the result if (presumably)
2839 @void@.
2840
2841 \begin{code}
2842 disambiguate :: SDoc -> Bool -> DynFlags -> [Inst] -> TcM ([Inst], TcDictBinds)
2843         -- Just does unification to fix the default types
2844         -- The Insts are assumed to be pre-zonked
2845 disambiguate doc interactive dflags insts
2846   | null insts
2847   = return (insts, emptyBag)
2848
2849   | null defaultable_groups
2850   = do  { traceTc (text "disambigutate, no defaultable groups" <+> vcat [ppr unaries, ppr insts, ppr bad_tvs, ppr defaultable_groups])
2851         ; return (insts, emptyBag) }
2852
2853   | otherwise
2854   = do  {       -- Figure out what default types to use
2855           default_tys <- getDefaultTys extended_defaulting ovl_strings
2856
2857         ; traceTc (text "disambiguate1" <+> vcat [ppr insts, ppr unaries, ppr bad_tvs, ppr defaultable_groups])
2858         ; mapM_ (disambigGroup default_tys) defaultable_groups
2859
2860         -- disambigGroup does unification, hence try again
2861         ; tryHardCheckLoop doc insts }
2862
2863   where
2864    extended_defaulting = interactive || dopt Opt_ExtendedDefaultRules dflags
2865                        -- See also Trac #1974
2866    ovl_strings = dopt Opt_OverloadedStrings dflags
2867
2868    unaries :: [(Inst, Class, TcTyVar)]  -- (C tv) constraints
2869    bad_tvs :: TcTyVarSet  -- Tyvars mentioned by *other* constraints
2870    (unaries, bad_tvs_s) = partitionWith find_unary insts 
2871    bad_tvs              = unionVarSets bad_tvs_s
2872
2873         -- Finds unary type-class constraints
2874    find_unary d@(Dict {tci_pred = ClassP cls [ty]})
2875         | Just tv <- tcGetTyVar_maybe ty = Left (d,cls,tv)
2876    find_unary inst                       = Right (tyVarsOfInst inst)
2877
2878                 -- Group by type variable
2879    defaultable_groups :: [[(Inst,Class,TcTyVar)]]
2880    defaultable_groups = filter defaultable_group (equivClasses cmp_tv unaries)
2881    cmp_tv (_,_,tv1) (_,_,tv2) = tv1 `compare` tv2
2882
2883    defaultable_group :: [(Inst,Class,TcTyVar)] -> Bool
2884    defaultable_group ds@((_,_,tv):_)
2885         =  isTyConableTyVar tv  -- Note [Avoiding spurious errors]
2886         && not (tv `elemVarSet` bad_tvs)
2887         && defaultable_classes [c | (_,c,_) <- ds]
2888    defaultable_group [] = panic "defaultable_group"
2889
2890    defaultable_classes clss 
2891         | extended_defaulting = any isInteractiveClass clss
2892         | otherwise           = all is_std_class clss && (any is_num_class clss)
2893
2894         -- In interactive mode, or with -XExtendedDefaultRules,
2895         -- we default Show a to Show () to avoid graututious errors on "show []"
2896    isInteractiveClass cls 
2897         = is_num_class cls || (classKey cls `elem` [showClassKey, eqClassKey, ordClassKey])
2898
2899    is_num_class cls = isNumericClass cls || (ovl_strings && (cls `hasKey` isStringClassKey))
2900         -- is_num_class adds IsString to the standard numeric classes, 
2901         -- when -foverloaded-strings is enabled
2902
2903    is_std_class cls = isStandardClass cls || (ovl_strings && (cls `hasKey` isStringClassKey))
2904         -- Similarly is_std_class
2905
2906 -----------------------
2907 disambigGroup :: [Type]                 -- The default types
2908               -> [(Inst,Class,TcTyVar)] -- All standard classes of form (C a)
2909               -> TcM () -- Just does unification, to fix the default types
2910
2911 disambigGroup default_tys dicts
2912   = do { mb_chosen_ty <- try_default default_tys
2913        ; case mb_chosen_ty of
2914             Nothing        -> return ()
2915             Just chosen_ty -> do { _ <- unifyType chosen_ty (mkTyVarTy tyvar) 
2916                                  ; warnDefault dicts chosen_ty } }
2917   where
2918     (_,_,tyvar) = ASSERT(not (null dicts)) head dicts   -- Should be non-empty
2919     classes = [c | (_,c,_) <- dicts]
2920
2921     try_default [] = return Nothing
2922     try_default (default_ty : default_tys)
2923       = tryTcLIE_ (try_default default_tys) $
2924         do { tcSimplifyDefault [mkClassPred clas [default_ty] | clas <- classes]
2925                 -- This may fail; then the tryTcLIE_ kicks in
2926                 -- Failure here is caused by there being no type in the
2927                 -- default list which can satisfy all the ambiguous classes.
2928                 -- For example, if Real a is reqd, but the only type in the
2929                 -- default list is Int.
2930
2931            ; return (Just default_ty) -- TOMDO: do something with the coercion
2932            }
2933
2934
2935 -----------------------
2936 getDefaultTys :: Bool -> Bool -> TcM [Type]
2937 getDefaultTys extended_deflts ovl_strings
2938   = do  { mb_defaults <- getDeclaredDefaultTys
2939         ; case mb_defaults of {
2940            Just tys -> return tys ;     -- User-supplied defaults
2941            Nothing  -> do
2942
2943         -- No use-supplied default
2944         -- Use [Integer, Double], plus modifications
2945         { integer_ty <- tcMetaTy integerTyConName
2946         ; checkWiredInTyCon doubleTyCon
2947         ; string_ty <- tcMetaTy stringTyConName
2948         ; return (opt_deflt extended_deflts unitTy
2949                         -- Note [Default unitTy]
2950                         ++
2951                   [integer_ty,doubleTy]
2952                         ++
2953                   opt_deflt ovl_strings string_ty) } } }
2954   where
2955     opt_deflt True  ty = [ty]
2956     opt_deflt False _  = []
2957 \end{code}
2958
2959 Note [Default unitTy]
2960 ~~~~~~~~~~~~~~~~~~~~~
2961 In interative mode (or with -XExtendedDefaultRules) we add () as the first type we
2962 try when defaulting.  This has very little real impact, except in the following case.
2963 Consider: 
2964         Text.Printf.printf "hello"
2965 This has type (forall a. IO a); it prints "hello", and returns 'undefined'.  We don't
2966 want the GHCi repl loop to try to print that 'undefined'.  The neatest thing is to
2967 default the 'a' to (), rather than to Integer (which is what would otherwise happen;
2968 and then GHCi doesn't attempt to print the ().  So in interactive mode, we add
2969 () to the list of defaulting types.  See Trac #1200.
2970
2971 Note [Avoiding spurious errors]
2972 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2973 When doing the unification for defaulting, we check for skolem
2974 type variables, and simply don't default them.  For example:
2975    f = (*)      -- Monomorphic
2976    g :: Num a => a -> a
2977    g x = f x x
2978 Here, we get a complaint when checking the type signature for g,
2979 that g isn't polymorphic enough; but then we get another one when
2980 dealing with the (Num a) context arising from f's definition;
2981 we try to unify a with Int (to default it), but find that it's
2982 already been unified with the rigid variable from g's type sig
2983
2984
2985 %************************************************************************
2986 %*                                                                      *
2987 \subsection[simple]{@Simple@ versions}
2988 %*                                                                      *
2989 %************************************************************************
2990
2991 Much simpler versions when there are no bindings to make!
2992
2993 @tcSimplifyThetas@ simplifies class-type constraints formed by
2994 @deriving@ declarations and when specialising instances.  We are
2995 only interested in the simplified bunch of class/type constraints.
2996
2997 It simplifies to constraints of the form (C a b c) where
2998 a,b,c are type variables.  This is required for the context of
2999 instance declarations.
3000
3001 \begin{code}
3002 tcSimplifyDeriv :: InstOrigin
3003                 -> [TyVar]      
3004                 -> ThetaType            -- Wanted
3005                 -> TcM ThetaType        -- Needed
3006 -- Given  instance (wanted) => C inst_ty 
3007 -- Simplify 'wanted' as much as possible
3008
3009 tcSimplifyDeriv orig tyvars theta
3010   = do  { (tvs, _, tenv) <- tcInstTyVars tyvars
3011         -- The main loop may do unification, and that may crash if 
3012         -- it doesn't see a TcTyVar, so we have to instantiate. Sigh
3013         -- ToDo: what if two of them do get unified?
3014         ; wanteds <- newDictBndrsO orig (substTheta tenv theta)
3015         ; (irreds, _) <- tryHardCheckLoop doc wanteds
3016
3017         ; let (tv_dicts, others) = partition ok irreds
3018               (tidy_env, tidy_insts) = tidyInsts others
3019         ; reportNoInstances tidy_env Nothing [alt_fix] tidy_insts
3020         -- See Note [Exotic derived instance contexts] in TcMType
3021
3022         ; let rev_env = zipTopTvSubst tvs (mkTyVarTys tyvars)
3023               simpl_theta = substTheta rev_env (map dictPred tv_dicts)
3024                 -- This reverse-mapping is a pain, but the result
3025                 -- should mention the original TyVars not TcTyVars
3026
3027         ; return simpl_theta }
3028   where
3029     doc = ptext (sLit "deriving classes for a data type")
3030
3031     ok dict | isDict dict = validDerivPred (dictPred dict)
3032             | otherwise   = False
3033     alt_fix = vcat [ptext (sLit "use a standalone 'deriving instance' declaration instead,"),
3034                     ptext (sLit "so you can specify the instance context yourself")]
3035 \end{code}
3036
3037
3038 @tcSimplifyDefault@ just checks class-type constraints, essentially;
3039 used with \tr{default} declarations.  We are only interested in
3040 whether it worked or not.
3041
3042 \begin{code}
3043 tcSimplifyDefault :: ThetaType  -- Wanted; has no type variables in it
3044                   -> TcM ()
3045
3046 tcSimplifyDefault theta = do
3047     wanteds <- newDictBndrsO DefaultOrigin theta
3048     (irreds, _) <- tryHardCheckLoop doc wanteds
3049     addNoInstanceErrs irreds
3050     if null irreds then
3051         return ()
3052      else
3053         traceTc (ptext (sLit "tcSimplifyDefault failing")) >> failM
3054   where
3055     doc = ptext (sLit "default declaration")
3056 \end{code}
3057
3058
3059
3060 %************************************************************************
3061 %*                                                                      *
3062 \section{Errors and contexts}
3063 %*                                                                      *
3064 %************************************************************************
3065
3066 ToDo: for these error messages, should we note the location as coming
3067 from the insts, or just whatever seems to be around in the monad just
3068 now?
3069
3070 \begin{code}
3071 groupErrs :: ([Inst] -> TcM ()) -- Deal with one group
3072           -> [Inst]             -- The offending Insts
3073           -> TcM ()
3074 -- Group together insts with the same origin
3075 -- We want to report them together in error messages
3076
3077 groupErrs _ [] 
3078   = return ()
3079 groupErrs report_err (inst:insts)
3080   = do  { do_one (inst:friends)
3081         ; groupErrs report_err others }
3082   where
3083         -- (It may seem a bit crude to compare the error messages,
3084         --  but it makes sure that we combine just what the user sees,
3085         --  and it avoids need equality on InstLocs.)
3086    (friends, others) = partition is_friend insts
3087    loc_msg           = showSDoc (pprInstLoc (instLoc inst))
3088    is_friend friend  = showSDoc (pprInstLoc (instLoc friend)) == loc_msg
3089    do_one insts = setInstCtxt (instLoc (head insts)) (report_err insts)
3090                 -- Add location and context information derived from the Insts
3091
3092 -- Add the "arising from..." part to a message about bunch of dicts
3093 addInstLoc :: [Inst] -> Message -> Message
3094 addInstLoc insts msg = msg $$ nest 2 (pprInstArising (head insts))
3095
3096 addTopIPErrs :: [Name] -> [Inst] -> TcM ()
3097 addTopIPErrs _ [] 
3098   = return ()
3099 addTopIPErrs bndrs ips
3100   = do  { dflags <- getDOpts
3101         ; addErrTcM (tidy_env, mk_msg dflags tidy_ips) }
3102   where
3103     (tidy_env, tidy_ips) = tidyInsts ips
3104     mk_msg dflags ips 
3105         = vcat [sep [ptext (sLit "Implicit parameters escape from"),
3106                 nest 2 (ptext (sLit "the monomorphic top-level binding") 
3107                                             <> plural bndrs <+> ptext (sLit "of")
3108                                             <+> pprBinders bndrs <> colon)],
3109                 nest 2 (vcat (map ppr_ip ips)),
3110                 monomorphism_fix dflags]
3111     ppr_ip ip = pprPred (dictPred ip) <+> pprInstArising ip
3112
3113 topIPErrs :: [Inst] -> TcM ()
3114 topIPErrs dicts
3115   = groupErrs report tidy_dicts
3116   where
3117     (tidy_env, tidy_dicts) = tidyInsts dicts
3118     report dicts = addErrTcM (tidy_env, mk_msg dicts)
3119     mk_msg dicts = addInstLoc dicts (ptext (sLit "Unbound implicit parameter") <> 
3120                                      plural tidy_dicts <+> pprDictsTheta tidy_dicts)
3121
3122 addNoInstanceErrs :: [Inst]     -- Wanted (can include implications)
3123                   -> TcM ()     
3124 addNoInstanceErrs insts
3125   = do  { let (tidy_env, tidy_insts) = tidyInsts insts
3126         ; reportNoInstances tidy_env Nothing [] tidy_insts }
3127
3128 reportNoInstances 
3129         :: TidyEnv
3130         -> Maybe (InstLoc, [Inst])      -- Context
3131                         -- Nothing => top level
3132                         -- Just (d,g) => d describes the construct
3133                         --               with givens g
3134         -> [SDoc]       -- Alternative fix for no-such-instance
3135         -> [Inst]       -- What is wanted (can include implications)
3136         -> TcM ()       
3137
3138 reportNoInstances tidy_env mb_what alt_fix insts 
3139   = groupErrs (report_no_instances tidy_env mb_what alt_fix) insts
3140
3141 report_no_instances :: TidyEnv -> Maybe (InstLoc, [Inst]) -> [SDoc] -> [Inst] -> TcM ()
3142 report_no_instances tidy_env mb_what alt_fixes insts
3143   = do { inst_envs <- tcGetInstEnvs
3144        ; let (implics, insts1)  = partition isImplicInst insts
3145              (insts2, overlaps) = partitionWith (check_overlap inst_envs) insts1
3146              (eqInsts, insts3)  = partition isEqInst insts2
3147        ; traceTc (text "reportNoInstances" <+> vcat 
3148                        [ppr insts, ppr implics, ppr insts1, ppr insts2])
3149        ; mapM_ complain_implic implics
3150        ; mapM_ (\doc -> addErrTcM (tidy_env, doc)) overlaps
3151        ; groupErrs complain_no_inst insts3 
3152        ; mapM_ (addErrTcM . mk_eq_err) eqInsts
3153        }
3154   where
3155     complain_no_inst insts = addErrTcM (tidy_env, mk_no_inst_err insts)
3156
3157     complain_implic inst        -- Recurse!
3158       = reportNoInstances tidy_env 
3159                           (Just (tci_loc inst, tci_given inst)) 
3160                           alt_fixes (tci_wanted inst)
3161
3162     check_overlap :: (InstEnv,InstEnv) -> Inst -> Either Inst SDoc
3163         -- Right msg  => overlap message
3164         -- Left  inst => no instance
3165     check_overlap inst_envs wanted
3166         | not (isClassDict wanted) = Left wanted
3167         | otherwise
3168         = case lookupInstEnv inst_envs clas tys of
3169                 ([], _) -> Left wanted          -- No match
3170                 -- The case of exactly one match and no unifiers means a
3171                 -- successful lookup.  That can't happen here, because dicts
3172                 -- only end up here if they didn't match in Inst.lookupInst
3173                 ([_],[])
3174                  | debugIsOn -> pprPanic "reportNoInstance" (ppr wanted)
3175                 res -> Right (mk_overlap_msg wanted res)
3176           where
3177             (clas,tys) = getDictClassTys wanted
3178
3179     mk_overlap_msg dict (matches, unifiers)
3180       = ASSERT( not (null matches) )
3181         vcat [  addInstLoc [dict] ((ptext (sLit "Overlapping instances for") 
3182                                         <+> pprPred (dictPred dict))),
3183                 sep [ptext (sLit "Matching instances") <> colon,
3184                      nest 2 (vcat [pprInstances ispecs, pprInstances unifiers])],
3185                 if not (isSingleton matches)
3186                 then    -- Two or more matches
3187                      empty
3188                 else    -- One match, plus some unifiers
3189                 ASSERT( not (null unifiers) )
3190                 parens (vcat [ptext (sLit "The choice depends on the instantiation of") <+>
3191                                  quotes (pprWithCommas ppr (varSetElems (tyVarsOfInst dict))),
3192                               ptext (sLit "To pick the first instance above, use -XIncoherentInstances"),
3193                               ptext (sLit "when compiling the other instance declarations")])]
3194       where
3195         ispecs = [ispec | (ispec, _) <- matches]
3196
3197     mk_eq_err :: Inst -> (TidyEnv, SDoc)
3198     mk_eq_err inst = misMatchMsg tidy_env (eqInstTys inst)
3199
3200     mk_no_inst_err insts
3201       | null insts = empty
3202
3203       | Just (loc, givens) <- mb_what,   -- Nested (type signatures, instance decls)
3204         not (isEmptyVarSet (tyVarsOfInsts insts))
3205       = vcat [ addInstLoc insts $
3206                sep [ ptext (sLit "Could not deduce") <+> pprDictsTheta insts
3207                    , nest 2 $ ptext (sLit "from the context") <+> pprDictsTheta givens]
3208              , show_fixes (fix1 loc : fixes2 ++ alt_fixes) ]
3209
3210       | otherwise       -- Top level 
3211       = vcat [ addInstLoc insts $
3212                ptext (sLit "No instance") <> plural insts
3213                     <+> ptext (sLit "for") <+> pprDictsTheta insts
3214              , show_fixes (fixes2 ++ alt_fixes) ]
3215
3216       where
3217         fix1 loc = sep [ ptext (sLit "add") <+> pprDictsTheta insts
3218                                  <+> ptext (sLit "to the context of"),
3219                          nest 2 (ppr (instLocOrigin loc)) ]
3220                          -- I'm not sure it helps to add the location
3221                          -- nest 2 (ptext (sLit "at") <+> ppr (instLocSpan loc)) ]
3222
3223         fixes2 | null instance_dicts = []
3224                | otherwise           = [sep [ptext (sLit "add an instance declaration for"),
3225                                         pprDictsTheta instance_dicts]]
3226         instance_dicts = [d | d <- insts, isClassDict d, not (isTyVarDict d)]
3227                 -- Insts for which it is worth suggesting an adding an instance declaration
3228                 -- Exclude implicit parameters, and tyvar dicts
3229
3230         show_fixes :: [SDoc] -> SDoc
3231         show_fixes []     = empty
3232         show_fixes (f:fs) = sep [ptext (sLit "Possible fix:"), 
3233                                  nest 2 (vcat (f : map (ptext (sLit "or") <+>) fs))]
3234
3235 addTopAmbigErrs :: [Inst] -> TcRn ()
3236 addTopAmbigErrs dicts
3237 -- Divide into groups that share a common set of ambiguous tyvars
3238   = ifErrsM (return ()) $       -- Only report ambiguity if no other errors happened
3239                                 -- See Note [Avoiding spurious errors]
3240     mapM_ report (equivClasses cmp [(d, tvs_of d) | d <- tidy_dicts])
3241   where
3242     (tidy_env, tidy_dicts) = tidyInsts dicts
3243
3244     tvs_of :: Inst -> [TcTyVar]
3245     tvs_of d = varSetElems (tyVarsOfInst d)
3246     cmp (_,tvs1) (_,tvs2) = tvs1 `compare` tvs2
3247     
3248     report :: [(Inst,[TcTyVar])] -> TcM ()
3249     report pairs@((inst,tvs) : _) = do  -- The pairs share a common set of ambiguous tyvars
3250           (tidy_env, mono_msg) <- mkMonomorphismMsg tidy_env tvs
3251           setSrcSpan (instSpan inst) $
3252                 -- the location of the first one will do for the err message
3253            addErrTcM (tidy_env, msg $$ mono_msg)
3254         where
3255           dicts = map fst pairs
3256           msg = sep [text "Ambiguous type variable" <> plural tvs <+> 
3257                           pprQuotedList tvs <+> in_msg,
3258                      nest 2 (pprDictsInFull dicts)]
3259           in_msg = text "in the constraint" <> plural dicts <> colon
3260     report [] = panic "addTopAmbigErrs"
3261
3262
3263 mkMonomorphismMsg :: TidyEnv -> [TcTyVar] -> TcM (TidyEnv, Message)
3264 -- There's an error with these Insts; if they have free type variables
3265 -- it's probably caused by the monomorphism restriction. 
3266 -- Try to identify the offending variable
3267 -- ASSUMPTION: the Insts are fully zonked
3268 mkMonomorphismMsg tidy_env inst_tvs
3269   = do  { dflags <- getDOpts
3270         ; (tidy_env, docs) <- findGlobals (mkVarSet inst_tvs) tidy_env
3271         ; return (tidy_env, mk_msg dflags docs) }
3272   where
3273     mk_msg _ _ | any isRuntimeUnk inst_tvs
3274         =  vcat [ptext (sLit "Cannot resolve unknown runtime types:") <+>
3275                    (pprWithCommas ppr inst_tvs),
3276                 ptext (sLit "Use :print or :force to determine these types")]
3277     mk_msg _ []   = ptext (sLit "Probable fix: add a type signature that fixes these type variable(s)")
3278                         -- This happens in things like
3279                         --      f x = show (read "foo")
3280                         -- where monomorphism doesn't play any role
3281     mk_msg dflags docs 
3282         = vcat [ptext (sLit "Possible cause: the monomorphism restriction applied to the following:"),
3283                 nest 2 (vcat docs),
3284                 monomorphism_fix dflags]
3285
3286 monomorphism_fix :: DynFlags -> SDoc
3287 monomorphism_fix dflags
3288   = ptext (sLit "Probable fix:") <+> vcat
3289         [ptext (sLit "give these definition(s) an explicit type signature"),
3290          if dopt Opt_MonomorphismRestriction dflags
3291            then ptext (sLit "or use -XNoMonomorphismRestriction")
3292            else empty]  -- Only suggest adding "-XNoMonomorphismRestriction"
3293                         -- if it is not already set!
3294     
3295 warnDefault :: [(Inst, Class, Var)] -> Type -> TcM ()
3296 warnDefault ups default_ty = do
3297     warn_flag <- doptM Opt_WarnTypeDefaults
3298     setInstCtxt (instLoc (head (dicts))) (warnTc warn_flag warn_msg)
3299   where
3300     dicts = [d | (d,_,_) <- ups]
3301
3302         -- Tidy them first
3303     (_, tidy_dicts) = tidyInsts dicts
3304     warn_msg  = vcat [ptext (sLit "Defaulting the following constraint(s) to type") <+>
3305                                 quotes (ppr default_ty),
3306                       pprDictsInFull tidy_dicts]
3307
3308 reduceDepthErr :: Int -> [Inst] -> SDoc
3309 reduceDepthErr n stack
3310   = vcat [ptext (sLit "Context reduction stack overflow; size =") <+> int n,
3311           ptext (sLit "Use -fcontext-stack=N to increase stack size to N"),
3312           nest 4 (pprStack stack)]
3313
3314 pprStack :: [Inst] -> SDoc
3315 pprStack stack = vcat (map pprInstInFull stack)
3316 \end{code}