The Big INLINE Patch: totally reorganise way that INLINE pragmas work
[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                    = mkVarBind dict_irred_id rhs
1022                    | otherwise        
1023                    = L span $ 
1024                      PatBind { pat_lhs = lpat
1025                              , pat_rhs = unguardedGRHSs rhs 
1026                              , pat_rhs_ty = hsLPatType lpat
1027                              , bind_fvs = placeHolderNames 
1028                              }
1029
1030         ; traceTc $ text "makeImplicationBind" <+> ppr implic_inst
1031         ; return ([implic_inst], unitBag bind) 
1032         }
1033
1034 -----------------------------------------------------------
1035 tryHardCheckLoop :: SDoc
1036              -> [Inst]                  -- Wanted
1037              -> TcM ([Inst], TcDictBinds)
1038
1039 tryHardCheckLoop doc wanteds
1040   = do { (irreds,binds) <- checkLoop (mkInferRedEnv doc try_me) wanteds
1041        ; return (irreds,binds)
1042        }
1043   where
1044     try_me _ = ReduceMe
1045         -- Here's the try-hard bit
1046
1047 -----------------------------------------------------------
1048 gentleCheckLoop :: InstLoc
1049                -> [Inst]                -- Given
1050                -> [Inst]                -- Wanted
1051                -> TcM ([Inst], TcDictBinds)
1052
1053 gentleCheckLoop inst_loc givens wanteds
1054   = do { (irreds,binds) <- checkLoop env wanteds
1055        ; return (irreds,binds)
1056        }
1057   where
1058     env = mkRedEnv (pprInstLoc inst_loc) try_me givens
1059
1060     try_me inst | isMethodOrLit inst = ReduceMe
1061                 | otherwise          = Stop
1062         -- When checking against a given signature 
1063         -- we MUST be very gentle: Note [Check gently]
1064
1065 gentleInferLoop :: SDoc -> [Inst]
1066                 -> TcM ([Inst], TcDictBinds)
1067 gentleInferLoop doc wanteds
1068   = do  { (irreds, binds) <- checkLoop env wanteds
1069         ; return (irreds, binds) }
1070   where
1071     env = mkInferRedEnv doc try_me
1072     try_me inst | isMethodOrLit inst = ReduceMe
1073                 | otherwise          = Stop
1074 \end{code}
1075
1076 Note [Check gently]
1077 ~~~~~~~~~~~~~~~~~~~~
1078 We have to very careful about not simplifying too vigorously
1079 Example:  
1080   data T a where
1081     MkT :: a -> T [a]
1082
1083   f :: Show b => T b -> b
1084   f (MkT x) = show [x]
1085
1086 Inside the pattern match, which binds (a:*, x:a), we know that
1087         b ~ [a]
1088 Hence we have a dictionary for Show [a] available; and indeed we 
1089 need it.  We are going to build an implication contraint
1090         forall a. (b~[a]) => Show [a]
1091 Later, we will solve this constraint using the knowledge (Show b)
1092         
1093 But we MUST NOT reduce (Show [a]) to (Show a), else the whole
1094 thing becomes insoluble.  So we simplify gently (get rid of literals
1095 and methods only, plus common up equal things), deferring the real
1096 work until top level, when we solve the implication constraint
1097 with tryHardCheckLooop.
1098
1099
1100 \begin{code}
1101 -----------------------------------------------------------
1102 checkLoop :: RedEnv
1103           -> [Inst]                     -- Wanted
1104           -> TcM ([Inst], TcDictBinds) 
1105 -- Precondition: givens are completely rigid
1106 -- Postcondition: returned Insts are zonked
1107
1108 checkLoop env wanteds
1109   = go env wanteds
1110   where go env wanteds
1111           = do  {  -- We do need to zonk the givens; cf Note [Zonking RedEnv]
1112                 ; env'     <- zonkRedEnv env
1113                 ; wanteds' <- zonkInsts  wanteds
1114         
1115                 ; (improved, tybinds, binds, irreds) 
1116                     <- reduceContext env' wanteds'
1117                 ; execTcTyVarBinds tybinds
1118
1119                 ; if null irreds || not improved then
1120                     return (irreds, binds)
1121                   else do
1122         
1123                 -- If improvement did some unification, we go round again.
1124                 -- We start again with irreds, not wanteds
1125                 -- Using an instance decl might have introduced a fresh type
1126                 -- variable which might have been unified, so we'd get an 
1127                 -- infinite loop if we started again with wanteds!  
1128                 -- See Note [LOOP]
1129                 { (irreds1, binds1) <- go env' irreds
1130                 ; return (irreds1, binds `unionBags` binds1) } }
1131 \end{code}
1132
1133 Note [Zonking RedEnv]
1134 ~~~~~~~~~~~~~~~~~~~~~
1135 It might appear as if the givens in RedEnv are always rigid, but that is not
1136 necessarily the case for programs involving higher-rank types that have class
1137 contexts constraining the higher-rank variables.  An example from tc237 in the
1138 testsuite is
1139
1140   class Modular s a | s -> a
1141
1142   wim ::  forall a w. Integral a 
1143                         => a -> (forall s. Modular s a => M s w) -> w
1144   wim i k = error "urk"
1145
1146   test5  ::  (Modular s a, Integral a) => M s a
1147   test5  =   error "urk"
1148
1149   test4   =   wim 4 test4'
1150
1151 Notice how the variable 'a' of (Modular s a) in the rank-2 type of wim is
1152 quantified further outside.  When type checking test4, we have to check
1153 whether the signature of test5 is an instance of 
1154
1155   (forall s. Modular s a => M s w)
1156
1157 Consequently, we will get (Modular s t_a), where t_a is a TauTv into the
1158 givens. 
1159
1160 Given the FD of Modular in this example, class improvement will instantiate
1161 t_a to 'a', where 'a' is the skolem from test5's signatures (due to the
1162 Modular s a predicate in that signature).  If we don't zonk (Modular s t_a) in
1163 the givens, we will get into a loop as improveOne uses the unification engine
1164 Unify.tcUnifyTys, which doesn't know about mutable type variables.
1165
1166
1167 Note [LOOP]
1168 ~~~~~~~~~~~
1169         class If b t e r | b t e -> r
1170         instance If T t e t
1171         instance If F t e e
1172         class Lte a b c | a b -> c where lte :: a -> b -> c
1173         instance Lte Z b T
1174         instance (Lte a b l,If l b a c) => Max a b c
1175
1176 Wanted: Max Z (S x) y
1177
1178 Then we'll reduce using the Max instance to:
1179         (Lte Z (S x) l, If l (S x) Z y)
1180 and improve by binding l->T, after which we can do some reduction
1181 on both the Lte and If constraints.  What we *can't* do is start again
1182 with (Max Z (S x) y)!
1183
1184
1185
1186 %************************************************************************
1187 %*                                                                      *
1188                 tcSimplifySuperClasses
1189 %*                                                                      *
1190 %************************************************************************
1191
1192 Note [SUPERCLASS-LOOP 1]
1193 ~~~~~~~~~~~~~~~~~~~~~~~~
1194 We have to be very, very careful when generating superclasses, lest we
1195 accidentally build a loop. Here's an example:
1196
1197   class S a
1198
1199   class S a => C a where { opc :: a -> a }
1200   class S b => D b where { opd :: b -> b }
1201   
1202   instance C Int where
1203      opc = opd
1204   
1205   instance D Int where
1206      opd = opc
1207
1208 From (instance C Int) we get the constraint set {ds1:S Int, dd:D Int}
1209 Simplifying, we may well get:
1210         $dfCInt = :C ds1 (opd dd)
1211         dd  = $dfDInt
1212         ds1 = $p1 dd
1213 Notice that we spot that we can extract ds1 from dd.  
1214
1215 Alas!  Alack! We can do the same for (instance D Int):
1216
1217         $dfDInt = :D ds2 (opc dc)
1218         dc  = $dfCInt
1219         ds2 = $p1 dc
1220
1221 And now we've defined the superclass in terms of itself.
1222 Two more nasty cases are in
1223         tcrun021
1224         tcrun033
1225
1226 Solution: 
1227   - Satisfy the superclass context *all by itself* 
1228     (tcSimplifySuperClasses)
1229   - And do so completely; i.e. no left-over constraints
1230     to mix with the constraints arising from method declarations
1231
1232
1233 Note [Recursive instances and superclases]
1234 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1235 Consider this code, which arises in the context of "Scrap Your 
1236 Boilerplate with Class".  
1237
1238     class Sat a
1239     class Data ctx a
1240     instance  Sat (ctx Char)             => Data ctx Char
1241     instance (Sat (ctx [a]), Data ctx a) => Data ctx [a]
1242
1243     class Data Maybe a => Foo a
1244
1245     instance Foo t => Sat (Maybe t)
1246
1247     instance Data Maybe a => Foo a
1248     instance Foo a        => Foo [a]
1249     instance                 Foo [Char]
1250
1251 In the instance for Foo [a], when generating evidence for the superclasses
1252 (ie in tcSimplifySuperClasses) we need a superclass (Data Maybe [a]).
1253 Using the instance for Data, we therefore need
1254         (Sat (Maybe [a], Data Maybe a)
1255 But we are given (Foo a), and hence its superclass (Data Maybe a).
1256 So that leaves (Sat (Maybe [a])).  Using the instance for Sat means
1257 we need (Foo [a]).  And that is the very dictionary we are bulding
1258 an instance for!  So we must put that in the "givens".  So in this
1259 case we have
1260         Given:  Foo a, Foo [a]
1261         Watend: Data Maybe [a]
1262
1263 BUT we must *not not not* put the *superclasses* of (Foo [a]) in
1264 the givens, which is what 'addGiven' would normally do. Why? Because
1265 (Data Maybe [a]) is the superclass, so we'd "satisfy" the wanted 
1266 by selecting a superclass from Foo [a], which simply makes a loop.
1267
1268 On the other hand we *must* put the superclasses of (Foo a) in
1269 the givens, as you can see from the derivation described above.
1270
1271 Conclusion: in the very special case of tcSimplifySuperClasses
1272 we have one 'given' (namely the "this" dictionary) whose superclasses
1273 must not be added to 'givens' by addGiven.  
1274
1275 There is a complication though.  Suppose there are equalities
1276       instance (Eq a, a~b) => Num (a,b)
1277 Then we normalise the 'givens' wrt the equalities, so the original
1278 given "this" dictionary is cast to one of a different type.  So it's a
1279 bit trickier than before to identify the "special" dictionary whose
1280 superclasses must not be added. See test
1281    indexed-types/should_run/EqInInstance
1282
1283 We need a persistent property of the dictionary to record this
1284 special-ness.  Current I'm using the InstLocOrigin (a bit of a hack,
1285 but cool), which is maintained by dictionary normalisation.
1286 Specifically, the InstLocOrigin is
1287              NoScOrigin
1288 then the no-superclass thing kicks in.  WATCH OUT if you fiddle
1289 with InstLocOrigin!
1290
1291 \begin{code}
1292 tcSimplifySuperClasses
1293         :: InstLoc 
1294         -> Inst         -- The dict whose superclasses 
1295                         -- are being figured out
1296         -> [Inst]       -- Given 
1297         -> [Inst]       -- Wanted
1298         -> TcM TcDictBinds
1299 tcSimplifySuperClasses loc this givens sc_wanteds
1300   = do  { traceTc (text "tcSimplifySuperClasses")
1301
1302               -- Note [Recursive instances and superclases]
1303         ; no_sc_loc <- getInstLoc NoScOrigin
1304         ; let no_sc_this = setInstLoc this no_sc_loc
1305
1306         ; let env =  RedEnv { red_doc = pprInstLoc loc, 
1307                               red_try_me = try_me,
1308                               red_givens = no_sc_this : givens, 
1309                               red_stack = (0,[]),
1310                               red_improve = False }  -- No unification vars
1311
1312
1313         ; (irreds,binds1) <- checkLoop env sc_wanteds
1314         ; let (tidy_env, tidy_irreds) = tidyInsts irreds
1315         ; reportNoInstances tidy_env (Just (loc, givens)) [] tidy_irreds
1316         ; return binds1 }
1317   where
1318     try_me _ = ReduceMe  -- Try hard, so we completely solve the superclass 
1319                          -- constraints right here. See Note [SUPERCLASS-LOOP 1]
1320 \end{code}
1321
1322
1323 %************************************************************************
1324 %*                                                                      *
1325 \subsection{tcSimplifyRestricted}
1326 %*                                                                      *
1327 %************************************************************************
1328
1329 tcSimplifyRestricted infers which type variables to quantify for a 
1330 group of restricted bindings.  This isn't trivial.
1331
1332 Eg1:    id = \x -> x
1333         We want to quantify over a to get id :: forall a. a->a
1334         
1335 Eg2:    eq = (==)
1336         We do not want to quantify over a, because there's an Eq a 
1337         constraint, so we get eq :: a->a->Bool  (notice no forall)
1338
1339 So, assume:
1340         RHS has type 'tau', whose free tyvars are tau_tvs
1341         RHS has constraints 'wanteds'
1342
1343 Plan A (simple)
1344   Quantify over (tau_tvs \ ftvs(wanteds))
1345   This is bad. The constraints may contain (Monad (ST s))
1346   where we have         instance Monad (ST s) where...
1347   so there's no need to be monomorphic in s!
1348
1349   Also the constraint might be a method constraint,
1350   whose type mentions a perfectly innocent tyvar:
1351           op :: Num a => a -> b -> a
1352   Here, b is unconstrained.  A good example would be
1353         foo = op (3::Int)
1354   We want to infer the polymorphic type
1355         foo :: forall b. b -> b
1356
1357
1358 Plan B (cunning, used for a long time up to and including GHC 6.2)
1359   Step 1: Simplify the constraints as much as possible (to deal 
1360   with Plan A's problem).  Then set
1361         qtvs = tau_tvs \ ftvs( simplify( wanteds ) )
1362
1363   Step 2: Now simplify again, treating the constraint as 'free' if 
1364   it does not mention qtvs, and trying to reduce it otherwise.
1365   The reasons for this is to maximise sharing.
1366
1367   This fails for a very subtle reason.  Suppose that in the Step 2
1368   a constraint (Foo (Succ Zero) (Succ Zero) b) gets thrown upstairs as 'free'.
1369   In the Step 1 this constraint might have been simplified, perhaps to
1370   (Foo Zero Zero b), AND THEN THAT MIGHT BE IMPROVED, to bind 'b' to 'T'.
1371   This won't happen in Step 2... but that in turn might prevent some other
1372   constraint (Baz [a] b) being simplified (e.g. via instance Baz [a] T where {..}) 
1373   and that in turn breaks the invariant that no constraints are quantified over.
1374
1375   Test typecheck/should_compile/tc177 (which failed in GHC 6.2) demonstrates
1376   the problem.
1377
1378
1379 Plan C (brutal)
1380   Step 1: Simplify the constraints as much as possible (to deal 
1381   with Plan A's problem).  Then set
1382         qtvs = tau_tvs \ ftvs( simplify( wanteds ) )
1383   Return the bindings from Step 1.
1384   
1385
1386 A note about Plan C (arising from "bug" reported by George Russel March 2004)
1387 Consider this:
1388
1389       instance (HasBinary ty IO) => HasCodedValue ty
1390
1391       foo :: HasCodedValue a => String -> IO a
1392
1393       doDecodeIO :: HasCodedValue a => () -> () -> IO a
1394       doDecodeIO codedValue view  
1395         = let { act = foo "foo" } in  act
1396
1397 You might think this should work becuase the call to foo gives rise to a constraint
1398 (HasCodedValue t), which can be satisfied by the type sig for doDecodeIO.  But the
1399 restricted binding act = ... calls tcSimplifyRestricted, and PlanC simplifies the
1400 constraint using the (rather bogus) instance declaration, and now we are stuffed.
1401
1402 I claim this is not really a bug -- but it bit Sergey as well as George.  So here's
1403 plan D
1404
1405
1406 Plan D (a variant of plan B)
1407   Step 1: Simplify the constraints as much as possible (to deal 
1408   with Plan A's problem), BUT DO NO IMPROVEMENT.  Then set
1409         qtvs = tau_tvs \ ftvs( simplify( wanteds ) )
1410
1411   Step 2: Now simplify again, treating the constraint as 'free' if 
1412   it does not mention qtvs, and trying to reduce it otherwise.
1413
1414   The point here is that it's generally OK to have too few qtvs; that is,
1415   to make the thing more monomorphic than it could be.  We don't want to
1416   do that in the common cases, but in wierd cases it's ok: the programmer
1417   can always add a signature.  
1418
1419   Too few qtvs => too many wanteds, which is what happens if you do less
1420   improvement.
1421
1422
1423 \begin{code}
1424 tcSimplifyRestricted    -- Used for restricted binding groups
1425                         -- i.e. ones subject to the monomorphism restriction
1426         :: SDoc
1427         -> TopLevelFlag
1428         -> [Name]               -- Things bound in this group
1429         -> TcTyVarSet           -- Free in the type of the RHSs
1430         -> [Inst]               -- Free in the RHSs
1431         -> TcM ([TyVar],        -- Tyvars to quantify (zonked and quantified)
1432                 TcDictBinds)    -- Bindings
1433         -- tcSimpifyRestricted returns no constraints to
1434         -- quantify over; by definition there are none.
1435         -- They are all thrown back in the LIE
1436
1437 tcSimplifyRestricted doc top_lvl bndrs tau_tvs wanteds
1438         -- Zonk everything in sight
1439   = do  { traceTc (text "tcSimplifyRestricted")
1440         ; wanteds_z <- zonkInsts wanteds
1441
1442         -- 'ReduceMe': Reduce as far as we can.  Don't stop at
1443         -- dicts; the idea is to get rid of as many type
1444         -- variables as possible, and we don't want to stop
1445         -- at (say) Monad (ST s), because that reduces
1446         -- immediately, with no constraint on s.
1447         --
1448         -- BUT do no improvement!  See Plan D above
1449         -- HOWEVER, some unification may take place, if we instantiate
1450         --          a method Inst with an equality constraint
1451         ; let env = mkNoImproveRedEnv doc (\_ -> ReduceMe)
1452         ; (_imp, _tybinds, _binds, constrained_dicts) 
1453             <- reduceContext env wanteds_z
1454
1455         -- Next, figure out the tyvars we will quantify over
1456         ; tau_tvs' <- zonkTcTyVarsAndFV (varSetElems tau_tvs)
1457         ; gbl_tvs' <- tcGetGlobalTyVars
1458         ; constrained_dicts' <- zonkInsts constrained_dicts
1459
1460         ; let qtvs1 = tau_tvs' `minusVarSet` oclose (fdPredsOfInsts constrained_dicts) gbl_tvs'
1461                                 -- As in tcSimplifyInfer
1462
1463                 -- Do not quantify over constrained type variables:
1464                 -- this is the monomorphism restriction
1465               constrained_tvs' = tyVarsOfInsts constrained_dicts'
1466               qtvs = qtvs1 `minusVarSet` constrained_tvs'
1467               pp_bndrs = pprWithCommas (quotes . ppr) bndrs
1468
1469         -- Warn in the mono
1470         ; warn_mono <- doptM Opt_WarnMonomorphism
1471         ; warnTc (warn_mono && (constrained_tvs' `intersectsVarSet` qtvs1))
1472                  (vcat[ ptext (sLit "the Monomorphism Restriction applies to the binding")
1473                                 <> plural bndrs <+> ptext (sLit "for") <+> pp_bndrs,
1474                         ptext (sLit "Consider giving a type signature for") <+> pp_bndrs])
1475
1476         ; traceTc (text "tcSimplifyRestricted" <+> vcat [
1477                 pprInsts wanteds, pprInsts constrained_dicts',
1478                 ppr _binds,
1479                 ppr constrained_tvs', ppr tau_tvs', ppr qtvs ])
1480
1481         -- The first step may have squashed more methods than
1482         -- necessary, so try again, this time more gently, knowing the exact
1483         -- set of type variables to quantify over.
1484         --
1485         -- We quantify only over constraints that are captured by qtvs;
1486         -- these will just be a subset of non-dicts.  This in contrast
1487         -- to normal inference (using isFreeWhenInferring) in which we quantify over
1488         -- all *non-inheritable* constraints too.  This implements choice
1489         -- (B) under "implicit parameter and monomorphism" above.
1490         --
1491         -- Remember that we may need to do *some* simplification, to
1492         -- (for example) squash {Monad (ST s)} into {}.  It's not enough
1493         -- just to float all constraints
1494         --
1495         -- At top level, we *do* squash methods becuase we want to 
1496         -- expose implicit parameters to the test that follows
1497         ; let is_nested_group = isNotTopLevel top_lvl
1498               try_me inst | isFreeWrtTyVars qtvs inst,
1499                            (is_nested_group || isDict inst) = Stop
1500                           | otherwise                       = ReduceMe 
1501               env = mkNoImproveRedEnv doc try_me
1502         ; (_imp, tybinds, binds, irreds) <- reduceContext env wanteds_z
1503         ; execTcTyVarBinds tybinds
1504
1505         -- See "Notes on implicit parameters, Question 4: top level"
1506         ; ASSERT( all (isFreeWrtTyVars qtvs) irreds )   -- None should be captured
1507           if is_nested_group then
1508                 extendLIEs irreds
1509           else do { let (bad_ips, non_ips) = partition isIPDict irreds
1510                   ; addTopIPErrs bndrs bad_ips
1511                   ; extendLIEs non_ips }
1512
1513         ; qtvs' <- zonkQuantifiedTyVars (varSetElems qtvs)
1514         ; return (qtvs', binds) }
1515 \end{code}
1516
1517
1518 %************************************************************************
1519 %*                                                                      *
1520                 tcSimplifyRuleLhs
1521 %*                                                                      *
1522 %************************************************************************
1523
1524 On the LHS of transformation rules we only simplify methods and constants,
1525 getting dictionaries.  We want to keep all of them unsimplified, to serve
1526 as the available stuff for the RHS of the rule.
1527
1528 Example.  Consider the following left-hand side of a rule
1529         
1530         f (x == y) (y > z) = ...
1531
1532 If we typecheck this expression we get constraints
1533
1534         d1 :: Ord a, d2 :: Eq a
1535
1536 We do NOT want to "simplify" to the LHS
1537
1538         forall x::a, y::a, z::a, d1::Ord a.
1539           f ((==) (eqFromOrd d1) x y) ((>) d1 y z) = ...
1540
1541 Instead we want 
1542
1543         forall x::a, y::a, z::a, d1::Ord a, d2::Eq a.
1544           f ((==) d2 x y) ((>) d1 y z) = ...
1545
1546 Here is another example:
1547
1548         fromIntegral :: (Integral a, Num b) => a -> b
1549         {-# RULES "foo"  fromIntegral = id :: Int -> Int #-}
1550
1551 In the rule, a=b=Int, and Num Int is a superclass of Integral Int. But
1552 we *dont* want to get
1553
1554         forall dIntegralInt.
1555            fromIntegral Int Int dIntegralInt (scsel dIntegralInt) = id Int
1556
1557 because the scsel will mess up RULE matching.  Instead we want
1558
1559         forall dIntegralInt, dNumInt.
1560           fromIntegral Int Int dIntegralInt dNumInt = id Int
1561
1562 Even if we have 
1563
1564         g (x == y) (y == z) = ..
1565
1566 where the two dictionaries are *identical*, we do NOT WANT
1567
1568         forall x::a, y::a, z::a, d1::Eq a
1569           f ((==) d1 x y) ((>) d1 y z) = ...
1570
1571 because that will only match if the dict args are (visibly) equal.
1572 Instead we want to quantify over the dictionaries separately.
1573
1574 In short, tcSimplifyRuleLhs must *only* squash LitInst and MethInts, leaving
1575 all dicts unchanged, with absolutely no sharing.  It's simpler to do this
1576 from scratch, rather than further parameterise simpleReduceLoop etc.
1577 Simpler, maybe, but alas not simple (see Trac #2494)
1578
1579 * Type errors may give rise to an (unsatisfiable) equality constraint
1580
1581 * Applications of a higher-rank function on the LHS may give
1582   rise to an implication constraint, esp if there are unsatisfiable
1583   equality constraints inside.
1584
1585 \begin{code}
1586 tcSimplifyRuleLhs :: [Inst] -> TcM ([Inst], TcDictBinds)
1587 tcSimplifyRuleLhs wanteds
1588   = do  { wanteds' <- zonkInsts wanteds
1589         
1590                 -- Simplify equalities  
1591                 -- It's important to do this: Trac #3346 for example
1592         ; (_, wanteds'', tybinds, binds1) <- tcReduceEqs [] wanteds'
1593         ; execTcTyVarBinds tybinds
1594
1595                 -- Simplify other constraints
1596         ; (irreds, binds2) <- go [] emptyBag wanteds''
1597
1598                 -- Report anything that is left
1599         ; let (dicts, bad_irreds) = partition isDict irreds
1600         ; traceTc (text "tcSimplifyrulelhs" <+> pprInsts bad_irreds)
1601         ; addNoInstanceErrs (nub bad_irreds)
1602                 -- The nub removes duplicates, which has
1603                 -- not happened otherwise (see notes above)
1604
1605         ; return (dicts, binds1 `unionBags` binds2) }
1606   where
1607     go :: [Inst] -> TcDictBinds -> [Inst] -> TcM ([Inst], TcDictBinds)
1608     go irreds binds []
1609         = return (irreds, binds)
1610     go irreds binds (w:ws)
1611         | isDict w
1612         = go (w:irreds) binds ws
1613         | isImplicInst w        -- Have a go at reducing the implication
1614         = do { (binds1, irreds1) <- reduceImplication red_env w
1615              ; let (bad_irreds, ok_irreds) = partition isImplicInst irreds1
1616              ; go (bad_irreds ++ irreds) 
1617                   (binds `unionBags` binds1) 
1618                   (ok_irreds ++ ws)}
1619         | otherwise
1620         = do { w' <- zonkInst w  -- So that (3::Int) does not generate a call
1621                                  -- to fromInteger; this looks fragile to me
1622              ; lookup_result <- lookupSimpleInst w'
1623              ; case lookup_result of
1624                  NoInstance      -> go (w:irreds) binds ws
1625                  GenInst ws' rhs -> go irreds binds' (ws' ++ ws)
1626                         where
1627                           binds' = addInstToDictBind binds w rhs
1628           }
1629
1630         -- Sigh: we need to reduce inside implications
1631     red_env = mkInferRedEnv doc try_me
1632     doc = ptext (sLit "Implication constraint in RULE lhs")
1633     try_me inst | isMethodOrLit inst = ReduceMe
1634                 | otherwise          = Stop     -- Be gentle
1635 \end{code}
1636
1637 tcSimplifyBracket is used when simplifying the constraints arising from
1638 a Template Haskell bracket [| ... |].  We want to check that there aren't
1639 any constraints that can't be satisfied (e.g. Show Foo, where Foo has no
1640 Show instance), but we aren't otherwise interested in the results.
1641 Nor do we care about ambiguous dictionaries etc.  We will type check
1642 this bracket again at its usage site.
1643
1644 \begin{code}
1645 tcSimplifyBracket :: [Inst] -> TcM ()
1646 tcSimplifyBracket wanteds
1647   = do  { _ <- tryHardCheckLoop doc wanteds
1648         ; return () }
1649   where
1650     doc = text "tcSimplifyBracket"
1651 \end{code}
1652
1653
1654 %************************************************************************
1655 %*                                                                      *
1656 \subsection{Filtering at a dynamic binding}
1657 %*                                                                      *
1658 %************************************************************************
1659
1660 When we have
1661         let ?x = R in B
1662
1663 we must discharge all the ?x constraints from B.  We also do an improvement
1664 step; if we have ?x::t1 and ?x::t2 we must unify t1, t2.
1665
1666 Actually, the constraints from B might improve the types in ?x. For example
1667
1668         f :: (?x::Int) => Char -> Char
1669         let ?x = 3 in f 'c'
1670
1671 then the constraint (?x::Int) arising from the call to f will
1672 force the binding for ?x to be of type Int.
1673
1674 \begin{code}
1675 tcSimplifyIPs :: [Inst]         -- The implicit parameters bound here
1676               -> [Inst]         -- Wanted
1677               -> TcM TcDictBinds
1678         -- We need a loop so that we do improvement, and then
1679         -- (next time round) generate a binding to connect the two
1680         --      let ?x = e in ?x
1681         -- Here the two ?x's have different types, and improvement 
1682         -- makes them the same.
1683
1684 tcSimplifyIPs given_ips wanteds
1685   = do  { wanteds'   <- zonkInsts wanteds
1686         ; given_ips' <- zonkInsts given_ips
1687                 -- Unusually for checking, we *must* zonk the given_ips
1688
1689         ; let env = mkRedEnv doc try_me given_ips'
1690         ; (improved, tybinds, binds, irreds) <- reduceContext env wanteds'
1691         ; execTcTyVarBinds tybinds
1692
1693         ; if null irreds || not improved then 
1694                 ASSERT( all is_free irreds )
1695                 do { extendLIEs irreds
1696                    ; return binds }
1697           else do
1698         -- If improvement did some unification, we go round again.
1699         -- We start again with irreds, not wanteds
1700         -- Using an instance decl might have introduced a fresh type
1701         -- variable which might have been unified, so we'd get an 
1702         -- infinite loop if we started again with wanteds!  
1703         -- See Note [LOOP]
1704         { binds1 <- tcSimplifyIPs given_ips' irreds
1705         ; return $ binds `unionBags` binds1
1706         } }
1707   where
1708     doc    = text "tcSimplifyIPs" <+> ppr given_ips
1709     ip_set = mkNameSet (ipNamesOfInsts given_ips)
1710     is_free inst = isFreeWrtIPs ip_set inst
1711
1712         -- Simplify any methods that mention the implicit parameter
1713     try_me inst | is_free inst = Stop
1714                 | otherwise    = ReduceMe
1715 \end{code}
1716
1717
1718 %************************************************************************
1719 %*                                                                      *
1720 \subsection[binds-for-local-funs]{@bindInstsOfLocalFuns@}
1721 %*                                                                      *
1722 %************************************************************************
1723
1724 When doing a binding group, we may have @Insts@ of local functions.
1725 For example, we might have...
1726 \begin{verbatim}
1727 let f x = x + 1     -- orig local function (overloaded)
1728     f.1 = f Int     -- two instances of f
1729     f.2 = f Float
1730  in
1731     (f.1 5, f.2 6.7)
1732 \end{verbatim}
1733 The point is: we must drop the bindings for @f.1@ and @f.2@ here,
1734 where @f@ is in scope; those @Insts@ must certainly not be passed
1735 upwards towards the top-level.  If the @Insts@ were binding-ified up
1736 there, they would have unresolvable references to @f@.
1737
1738 We pass in an @init_lie@ of @Insts@ and a list of locally-bound @Ids@.
1739 For each method @Inst@ in the @init_lie@ that mentions one of the
1740 @Ids@, we create a binding.  We return the remaining @Insts@ (in an
1741 @LIE@), as well as the @HsBinds@ generated.
1742
1743 \begin{code}
1744 bindInstsOfLocalFuns :: [Inst] -> [TcId] -> TcM TcDictBinds
1745 -- Simlifies only MethodInsts, and generate only bindings of form 
1746 --      fm = f tys dicts
1747 -- We're careful not to even generate bindings of the form
1748 --      d1 = d2
1749 -- You'd think that'd be fine, but it interacts with what is
1750 -- arguably a bug in Match.tidyEqnInfo (see notes there)
1751
1752 bindInstsOfLocalFuns wanteds local_ids
1753   | null overloaded_ids = do
1754         -- Common case
1755     extendLIEs wanteds
1756     return emptyLHsBinds
1757
1758   | otherwise
1759   = do  { (irreds, binds) <- gentleInferLoop doc for_me
1760         ; extendLIEs not_for_me 
1761         ; extendLIEs irreds
1762         ; return binds }
1763   where
1764     doc              = text "bindInsts" <+> ppr local_ids
1765     overloaded_ids   = filter is_overloaded local_ids
1766     is_overloaded id = isOverloadedTy (idType id)
1767     (for_me, not_for_me) = partition (isMethodFor overloaded_set) wanteds
1768
1769     overloaded_set = mkVarSet overloaded_ids    -- There can occasionally be a lot of them
1770                                                 -- so it's worth building a set, so that
1771                                                 -- lookup (in isMethodFor) is faster
1772 \end{code}
1773
1774
1775 %************************************************************************
1776 %*                                                                      *
1777 \subsection{Data types for the reduction mechanism}
1778 %*                                                                      *
1779 %************************************************************************
1780
1781 The main control over context reduction is here
1782
1783 \begin{code}
1784 data RedEnv 
1785   = RedEnv { red_doc    :: SDoc                 -- The context
1786            , red_try_me :: Inst -> WhatToDo
1787            , red_improve :: Bool                -- True <=> do improvement
1788            , red_givens :: [Inst]               -- All guaranteed rigid
1789                                                 -- Always dicts & equalities
1790                                                 -- but see Note [Rigidity]
1791  
1792            , red_stack  :: (Int, [Inst])        -- Recursion stack (for err msg)
1793                                                 -- See Note [RedStack]
1794   }
1795
1796 -- Note [Rigidity]
1797 -- The red_givens are rigid so far as cmpInst is concerned.
1798 -- There is one case where they are not totally rigid, namely in tcSimplifyIPs
1799 --      let ?x = e in ...
1800 -- Here, the given is (?x::a), where 'a' is not necy a rigid type
1801 -- But that doesn't affect the comparison, which is based only on mame.
1802
1803 -- Note [RedStack]
1804 -- The red_stack pair (n,insts) pair is just used for error reporting.
1805 -- 'n' is always the depth of the stack.
1806 -- The 'insts' is the stack of Insts being reduced: to produce X
1807 -- I had to produce Y, to produce Y I had to produce Z, and so on.
1808
1809
1810 mkRedEnv :: SDoc -> (Inst -> WhatToDo) -> [Inst] -> RedEnv
1811 mkRedEnv doc try_me givens
1812   = RedEnv { red_doc = doc, red_try_me = try_me,
1813              red_givens = givens, 
1814              red_stack = (0,[]),
1815              red_improve = True }       
1816
1817 mkInferRedEnv :: SDoc -> (Inst -> WhatToDo) -> RedEnv
1818 -- No givens at all
1819 mkInferRedEnv doc try_me
1820   = RedEnv { red_doc = doc, red_try_me = try_me,
1821              red_givens = [], 
1822              red_stack = (0,[]),
1823              red_improve = True }       
1824
1825 mkNoImproveRedEnv :: SDoc -> (Inst -> WhatToDo) -> RedEnv
1826 -- Do not do improvement; no givens
1827 mkNoImproveRedEnv doc try_me
1828   = RedEnv { red_doc = doc, red_try_me = try_me,
1829              red_givens = [], 
1830              red_stack = (0,[]),
1831              red_improve = True }       
1832
1833 data WhatToDo
1834  = ReduceMe     -- Try to reduce this
1835                 -- If there's no instance, add the inst to the 
1836                 -- irreductible ones, but don't produce an error 
1837                 -- message of any kind.
1838                 -- It might be quite legitimate such as (Eq a)!
1839
1840  | Stop         -- Return as irreducible unless it can
1841                         -- be reduced to a constant in one step
1842                         -- Do not add superclasses; see 
1843
1844 data WantSCs = NoSCs | AddSCs   -- Tells whether we should add the superclasses
1845                                 -- of a predicate when adding it to the avails
1846         -- The reason for this flag is entirely the super-class loop problem
1847         -- Note [SUPER-CLASS LOOP 1]
1848
1849 zonkRedEnv :: RedEnv -> TcM RedEnv
1850 zonkRedEnv env
1851   = do { givens' <- mapM zonkInst (red_givens env)
1852        ; return $ env {red_givens = givens'}
1853        }
1854 \end{code}
1855
1856
1857 %************************************************************************
1858 %*                                                                      *
1859 \subsection[reduce]{@reduce@}
1860 %*                                                                      *
1861 %************************************************************************
1862
1863 Note [Ancestor Equalities]
1864 ~~~~~~~~~~~~~~~~~~~~~~~~~~
1865 During context reduction, we add to the wanted equalities also those
1866 equalities that (transitively) occur in superclass contexts of wanted
1867 class constraints.  Consider the following code
1868
1869   class a ~ Int => C a
1870   instance C Int
1871
1872 If (C a) is wanted, we want to add (a ~ Int), which will be discharged by
1873 substituting Int for a.  Hence, we ultimately want (C Int), which we
1874 discharge with the explicit instance.
1875
1876 \begin{code}
1877 reduceContext :: RedEnv
1878               -> [Inst]                 -- Wanted
1879               -> TcM (ImprovementDone,
1880                       TcTyVarBinds,     -- Type variable bindings
1881                       TcDictBinds,      -- Dictionary bindings
1882                       [Inst])           -- Irreducible
1883
1884 reduceContext env wanteds0
1885   = do  { traceTc (text "reduceContext" <+> (vcat [
1886              text "----------------------",
1887              red_doc env,
1888              text "given" <+> ppr (red_givens env),
1889              text "wanted" <+> ppr wanteds0,
1890              text "----------------------"
1891              ]))
1892
1893           -- We want to add as wanted equalities those that (transitively) 
1894           -- occur in superclass contexts of wanted class constraints.
1895           -- See Note [Ancestor Equalities]
1896         ; ancestor_eqs <- ancestorEqualities wanteds0
1897         ; traceTc $ text "reduceContext: ancestor eqs" <+> ppr ancestor_eqs
1898
1899           -- Normalise and solve all equality constraints as far as possible
1900           -- and normalise all dictionary constraints wrt to the reduced
1901           -- equalities.  The returned wanted constraints include the
1902           -- irreducible wanted equalities.
1903         ; let wanteds = wanteds0 ++ ancestor_eqs
1904               givens  = red_givens env
1905         ; (givens', 
1906            wanteds', 
1907            tybinds,
1908            normalise_binds) <- tcReduceEqs givens wanteds
1909         ; traceTc $ text "reduceContext: tcReduceEqs result" <+> vcat
1910                       [ppr givens', ppr wanteds', ppr tybinds, 
1911                        ppr normalise_binds]
1912
1913           -- Build the Avail mapping from "given_dicts"
1914         ; (init_state, _) <- getLIE $ do 
1915                 { init_state <- foldlM addGiven emptyAvails givens'
1916                 ; return init_state
1917                 }
1918
1919           -- Solve the *wanted* *dictionary* constraints (not implications)
1920           -- This may expose some further equational constraints in the course
1921           -- of improvement due to functional dependencies if any of the
1922           -- involved unifications gets deferred.
1923         ; let (wanted_implics, wanted_dicts) = partition isImplicInst wanteds'
1924         ; (avails, extra_eqs) <- getLIE (reduceList env wanted_dicts init_state)
1925                    -- The getLIE is reqd because reduceList does improvement
1926                    -- (via extendAvails) which may in turn do unification
1927         ; (dict_binds, 
1928            bound_dicts, 
1929            dict_irreds)       <- extractResults avails wanted_dicts
1930         ; traceTc $ text "reduceContext: extractResults" <+> vcat
1931                       [ppr avails, ppr wanted_dicts, ppr dict_binds]
1932
1933           -- Solve the wanted *implications*.  In doing so, we can provide
1934           -- as "given"   all the dicts that were originally given, 
1935           --              *or* for which we now have bindings, 
1936           --              *or* which are now irreds
1937           -- NB: Equality irreds need to be converted, as the recursive 
1938           --     invocation of the solver will still treat them as wanteds
1939           --     otherwise.
1940         ; let implic_env = env { red_givens 
1941                                    = givens ++ bound_dicts ++
1942                                      map wantedToLocalEqInst dict_irreds }
1943         ; (implic_binds_s, implic_irreds_s) 
1944             <- mapAndUnzipM (reduceImplication implic_env) wanted_implics
1945         ; let implic_binds  = unionManyBags implic_binds_s
1946               implic_irreds = concat implic_irreds_s
1947
1948           -- Collect all irreducible instances, and determine whether we should
1949           -- go round again.  We do so in either of two cases:
1950           -- (1) If dictionary reduction or equality solving led to
1951           --     improvement (i.e., bindings for type variables).
1952           -- (2) If we reduced dictionaries (i.e., got dictionary bindings),
1953           --     they may have exposed further opportunities to normalise
1954           --     family applications.  See Note [Dictionary Improvement]
1955           --
1956           -- NB: We do *not* go around for new extra_eqs.  Morally, we should,
1957           --     but we can't without risking non-termination (see #2688).  By
1958           --     not going around, we miss some legal programs mixing FDs and
1959           --     TFs, but we never claimed to support such programs in the
1960           --     current implementation anyway.
1961
1962         ; let all_irreds       = dict_irreds ++ implic_irreds ++ extra_eqs
1963               avails_improved  = availsImproved avails
1964               eq_improved      = anyBag (not . isCoVarBind) tybinds
1965               improvedFlexible = avails_improved || eq_improved
1966               reduced_dicts    = not (isEmptyBag dict_binds)
1967               improved         = improvedFlexible || reduced_dicts
1968               --
1969               improvedHint  = (if avails_improved then " [AVAILS]" else "") ++
1970                               (if eq_improved then " [EQ]" else "")
1971
1972         ; traceTc (text "reduceContext end" <+> (vcat [
1973              text "----------------------",
1974              red_doc env,
1975              text "given" <+> ppr givens,
1976              text "wanted" <+> ppr wanteds0,
1977              text "----",
1978              text "tybinds" <+> ppr tybinds,
1979              text "avails" <+> pprAvails avails,
1980              text "improved =" <+> ppr improved <+> text improvedHint,
1981              text "(all) irreds = " <+> ppr all_irreds,
1982              text "dict-binds = " <+> ppr dict_binds,
1983              text "implic-binds = " <+> ppr implic_binds,
1984              text "----------------------"
1985              ]))
1986
1987         ; return (improved, 
1988                   tybinds,
1989                   normalise_binds `unionBags` dict_binds 
1990                                   `unionBags` implic_binds, 
1991                   all_irreds) 
1992         }
1993   where
1994     isCoVarBind (TcTyVarBind tv _) = isCoVar tv
1995
1996 tcImproveOne :: Avails -> Inst -> TcM ImprovementDone
1997 tcImproveOne avails inst
1998   | not (isDict inst) = return False
1999   | otherwise
2000   = do  { inst_envs <- tcGetInstEnvs
2001         ; let eqns = improveOne (classInstances inst_envs)
2002                                 (dictPred inst, pprInstArising inst)
2003                                 [ (dictPred p, pprInstArising p)
2004                                 | p <- availsInsts avails, isDict p ]
2005                 -- Avails has all the superclasses etc (good)
2006                 -- It also has all the intermediates of the deduction (good)
2007                 -- It does not have duplicates (good)
2008                 -- NB that (?x::t1) and (?x::t2) will be held separately in 
2009                 --    avails so that improve will see them separate
2010         ; traceTc (text "improveOne" <+> ppr inst)
2011         ; unifyEqns eqns }
2012
2013 unifyEqns :: [(Equation, (PredType, SDoc), (PredType, SDoc))] 
2014           -> TcM ImprovementDone
2015 unifyEqns [] = return False
2016 unifyEqns eqns
2017   = do  { traceTc (ptext (sLit "Improve:") <+> vcat (map pprEquationDoc eqns))
2018         ; improved <- mapM unify eqns
2019         ; return $ or improved
2020         }
2021   where
2022     unify ((qtvs, pairs), what1, what2)
2023          = addErrCtxtM (mkEqnMsg what1 what2) $ 
2024              do { let freeTyVars = unionVarSets (map tvs_pr pairs) 
2025                                    `minusVarSet` qtvs
2026                 ; (_, _, tenv) <- tcInstTyVars (varSetElems qtvs)
2027                 ; mapM_ (unif_pr tenv) pairs
2028                 ; anyM isFilledMetaTyVar $ varSetElems freeTyVars
2029                 }
2030
2031     unif_pr tenv (ty1, ty2) = unifyType (substTy tenv ty1) (substTy tenv ty2)
2032
2033     tvs_pr (ty1, ty2) = tyVarsOfType ty1 `unionVarSet` tyVarsOfType ty2
2034
2035 pprEquationDoc :: (Equation, (PredType, SDoc), (PredType, SDoc)) -> SDoc
2036 pprEquationDoc (eqn, (p1, _), (p2, _)) 
2037   = vcat [pprEquation eqn, nest 2 (ppr p1), nest 2 (ppr p2)]
2038
2039 mkEqnMsg :: (TcPredType, SDoc) -> (TcPredType, SDoc) -> TidyEnv
2040          -> TcM (TidyEnv, SDoc)
2041 mkEqnMsg (pred1,from1) (pred2,from2) tidy_env
2042   = do  { pred1' <- zonkTcPredType pred1
2043         ; pred2' <- zonkTcPredType pred2
2044         ; let { pred1'' = tidyPred tidy_env pred1'
2045               ; pred2'' = tidyPred tidy_env pred2' }
2046         ; let msg = vcat [ptext (sLit "When using functional dependencies to combine"),
2047                           nest 2 (sep [ppr pred1'' <> comma, nest 2 from1]), 
2048                           nest 2 (sep [ppr pred2'' <> comma, nest 2 from2])]
2049         ; return (tidy_env, msg) }
2050 \end{code}
2051
2052 Note [Dictionary Improvement]
2053 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2054 In reduceContext, we first reduce equalities and then class constraints.
2055 However, the letter may expose further opportunities for the former.  Hence,
2056 we need to go around again if dictionary reduction produced any dictionary
2057 bindings.  The following example demonstrated the point:
2058
2059   data EX _x _y (p :: * -> *)
2060   data ANY
2061
2062   class Base p
2063
2064   class Base (Def p) => Prop p where
2065    type Def p
2066
2067   instance Base ()
2068   instance Prop () where
2069    type Def () = ()
2070
2071   instance (Base (Def (p ANY))) => Base (EX _x _y p)
2072   instance (Prop (p ANY)) => Prop (EX _x _y p) where
2073    type Def (EX _x _y p) = EX _x _y p
2074
2075   data FOO x
2076   instance Prop (FOO x) where
2077    type Def (FOO x) = ()
2078
2079   data BAR
2080   instance Prop BAR where
2081    type Def BAR = EX () () FOO
2082
2083 During checking the last instance declaration, we need to check the superclass
2084 cosntraint Base (Def BAR), which family normalisation reduced to 
2085 Base (EX () () FOO).  Chasing the instance for Base (EX _x _y p), gives us
2086 Base (Def (FOO ANY)), which again requires family normalisation of Def to
2087 Base () before we can finish.
2088
2089
2090 The main context-reduction function is @reduce@.  Here's its game plan.
2091
2092 \begin{code}
2093 reduceList :: RedEnv -> [Inst] -> Avails -> TcM Avails
2094 reduceList env@(RedEnv {red_stack = (n,stk)}) wanteds state
2095   = do  { traceTc (text "reduceList " <+> (ppr wanteds $$ ppr state))
2096         ; dopts <- getDOpts
2097         ; when (debugIsOn && (n > 8)) $ do
2098                 debugDumpTcRn (hang (ptext (sLit "Interesting! Context reduction stack depth") <+> int n) 
2099                              2 (ifPprDebug (nest 2 (pprStack stk))))
2100         ; if n >= ctxtStkDepth dopts then
2101             failWithTc (reduceDepthErr n stk)
2102           else
2103             go wanteds state }
2104   where
2105     go []     state = return state
2106     go (w:ws) state = do { state' <- reduce (env {red_stack = (n+1, w:stk)}) w state
2107                          ; go ws state' }
2108
2109     -- Base case: we're done!
2110 reduce :: RedEnv -> Inst -> Avails -> TcM Avails
2111 reduce env wanted avails
2112
2113     -- We don't reduce equalities here (and they must not end up as irreds
2114     -- in the Avails!)
2115   | isEqInst wanted
2116   = return avails
2117
2118     -- It's the same as an existing inst, or a superclass thereof
2119   | Just _ <- findAvail avails wanted
2120   = do { traceTc (text "reduce: found " <+> ppr wanted)
2121        ; return avails
2122        }
2123
2124   | otherwise
2125   = do  { traceTc (text "reduce" <+> ppr wanted $$ ppr avails)
2126         ; case red_try_me env wanted of {
2127             Stop -> try_simple (addIrred NoSCs);
2128                         -- See Note [No superclasses for Stop]
2129
2130             ReduceMe -> do      -- It should be reduced
2131                 { (avails, lookup_result) <- reduceInst env avails wanted
2132                 ; case lookup_result of
2133                     NoInstance -> addIrred AddSCs avails wanted
2134                              -- Add it and its superclasses
2135                              
2136                     GenInst [] rhs -> addWanted AddSCs avails wanted rhs []
2137
2138                     GenInst wanteds' rhs
2139                           -> do { avails1 <- addIrred NoSCs avails wanted
2140                                 ; avails2 <- reduceList env wanteds' avails1
2141                                 ; addWanted AddSCs avails2 wanted rhs wanteds' } }
2142                 -- Temporarily do addIrred *before* the reduceList, 
2143                 -- which has the effect of adding the thing we are trying
2144                 -- to prove to the database before trying to prove the things it
2145                 -- needs.  See note [RECURSIVE DICTIONARIES]
2146                 -- NB: we must not do an addWanted before, because that adds the
2147                 --     superclasses too, and that can lead to a spurious loop; see
2148                 --     the examples in [SUPERCLASS-LOOP]
2149                 -- So we do an addIrred before, and then overwrite it afterwards with addWanted
2150     } }
2151   where
2152         -- First, see if the inst can be reduced to a constant in one step
2153         -- Works well for literals (1::Int) and constant dictionaries (d::Num Int)
2154         -- Don't bother for implication constraints, which take real work
2155     try_simple do_this_otherwise
2156       = do { res <- lookupSimpleInst wanted
2157            ; case res of
2158                 GenInst [] rhs -> addWanted AddSCs avails wanted rhs []
2159                 _              -> do_this_otherwise avails wanted }
2160 \end{code}
2161
2162
2163 Note [RECURSIVE DICTIONARIES]
2164 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2165 Consider 
2166     data D r = ZeroD | SuccD (r (D r));
2167     
2168     instance (Eq (r (D r))) => Eq (D r) where
2169         ZeroD     == ZeroD     = True
2170         (SuccD a) == (SuccD b) = a == b
2171         _         == _         = False;
2172     
2173     equalDC :: D [] -> D [] -> Bool;
2174     equalDC = (==);
2175
2176 We need to prove (Eq (D [])).  Here's how we go:
2177
2178         d1 : Eq (D [])
2179
2180 by instance decl, holds if
2181         d2 : Eq [D []]
2182         where   d1 = dfEqD d2
2183
2184 by instance decl of Eq, holds if
2185         d3 : D []
2186         where   d2 = dfEqList d3
2187                 d1 = dfEqD d2
2188
2189 But now we can "tie the knot" to give
2190
2191         d3 = d1
2192         d2 = dfEqList d3
2193         d1 = dfEqD d2
2194
2195 and it'll even run!  The trick is to put the thing we are trying to prove
2196 (in this case Eq (D []) into the database before trying to prove its
2197 contributing clauses.
2198         
2199 Note [SUPERCLASS-LOOP 2]
2200 ~~~~~~~~~~~~~~~~~~~~~~~~
2201 We need to be careful when adding "the constaint we are trying to prove".
2202 Suppose we are *given* d1:Ord a, and want to deduce (d2:C [a]) where
2203
2204         class Ord a => C a where
2205         instance Ord [a] => C [a] where ...
2206
2207 Then we'll use the instance decl to deduce C [a] from Ord [a], and then add the
2208 superclasses of C [a] to avails.  But we must not overwrite the binding
2209 for Ord [a] (which is obtained from Ord a) with a superclass selection or we'll just
2210 build a loop! 
2211
2212 Here's another variant, immortalised in tcrun020
2213         class Monad m => C1 m
2214         class C1 m => C2 m x
2215         instance C2 Maybe Bool
2216 For the instance decl we need to build (C1 Maybe), and it's no good if
2217 we run around and add (C2 Maybe Bool) and its superclasses to the avails 
2218 before we search for C1 Maybe.
2219
2220 Here's another example 
2221         class Eq b => Foo a b
2222         instance Eq a => Foo [a] a
2223 If we are reducing
2224         (Foo [t] t)
2225
2226 we'll first deduce that it holds (via the instance decl).  We must not
2227 then overwrite the Eq t constraint with a superclass selection!
2228
2229 At first I had a gross hack, whereby I simply did not add superclass constraints
2230 in addWanted, though I did for addGiven and addIrred.  This was sub-optimal,
2231 becuase it lost legitimate superclass sharing, and it still didn't do the job:
2232 I found a very obscure program (now tcrun021) in which improvement meant the
2233 simplifier got two bites a the cherry... so something seemed to be an Stop
2234 first time, but reducible next time.
2235
2236 Now we implement the Right Solution, which is to check for loops directly 
2237 when adding superclasses.  It's a bit like the occurs check in unification.
2238
2239
2240
2241 %************************************************************************
2242 %*                                                                      *
2243                 Reducing a single constraint
2244 %*                                                                      *
2245 %************************************************************************
2246
2247 \begin{code}
2248 ---------------------------------------------
2249 reduceInst :: RedEnv -> Avails -> Inst -> TcM (Avails, LookupInstResult)
2250 reduceInst _ avails other_inst
2251   = do  { result <- lookupSimpleInst other_inst
2252         ; return (avails, result) }
2253 \end{code}
2254
2255 Note [Equational Constraints in Implication Constraints]
2256 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2257
2258 An implication constraint is of the form 
2259         Given => Wanted 
2260 where Given and Wanted may contain both equational and dictionary
2261 constraints. The delay and reduction of these two kinds of constraints
2262 is distinct:
2263
2264 -) In the generated code, wanted Dictionary constraints are wrapped up in an
2265    implication constraint that is created at the code site where the wanted
2266    dictionaries can be reduced via a let-binding. This let-bound implication
2267    constraint is deconstructed at the use-site of the wanted dictionaries.
2268
2269 -) While the reduction of equational constraints is also delayed, the delay
2270    is not manifest in the generated code. The required evidence is generated
2271    in the code directly at the use-site. There is no let-binding and deconstruction
2272    necessary. The main disadvantage is that we cannot exploit sharing as the
2273    same evidence may be generated at multiple use-sites. However, this disadvantage
2274    is limited because it only concerns coercions which are erased.
2275
2276 The different treatment is motivated by the different in representation. Dictionary
2277 constraints require manifest runtime dictionaries, while equations require coercions
2278 which are types.
2279
2280 \begin{code}
2281 ---------------------------------------------
2282 reduceImplication :: RedEnv
2283                   -> Inst
2284                   -> TcM (TcDictBinds, [Inst])
2285 \end{code}
2286
2287 Suppose we are simplifying the constraint
2288         forall bs. extras => wanted
2289 in the context of an overall simplification problem with givens 'givens'.
2290
2291 Note that
2292   * The 'givens' need not mention any of the quantified type variables
2293         e.g.    forall {}. Eq a => Eq [a]
2294                 forall {}. C Int => D (Tree Int)
2295
2296     This happens when you have something like
2297         data T a where
2298           T1 :: Eq a => a -> T a
2299
2300         f :: T a -> Int
2301         f x = ...(case x of { T1 v -> v==v })...
2302
2303 \begin{code}
2304         -- ToDo: should we instantiate tvs?  I think it's not necessary
2305         --
2306         -- Note on coercion variables:
2307         --
2308         --      The extra given coercion variables are bound at two different 
2309         --      sites:
2310         --
2311         --      -) in the creation context of the implication constraint        
2312         --              the solved equational constraints use these binders
2313         --
2314         --      -) at the solving site of the implication constraint
2315         --              the solved dictionaries use these binders;
2316         --              these binders are generated by reduceImplication
2317         --
2318         -- Note [Binders for equalities]
2319         -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2320         -- To reuse the binders of local/given equalities in the binders of 
2321         -- implication constraints, it is crucial that these given equalities
2322         -- always have the form
2323         --   cotv :: t1 ~ t2
2324         -- where cotv is a simple coercion type variable (and not a more
2325         -- complex coercion term).  We require that the extra_givens always
2326         -- have this form and exploit the special form when generating binders.
2327 reduceImplication env
2328         orig_implic@(ImplicInst { tci_name = name, tci_loc = inst_loc,
2329                                   tci_tyvars = tvs,
2330                                   tci_given = extra_givens, tci_wanted = wanteds
2331                                  })
2332   = do  {       -- Solve the sub-problem
2333         ; let try_me _ = ReduceMe  -- Note [Freeness and implications]
2334               env' = env { red_givens = extra_givens ++ red_givens env
2335                          , red_doc = sep [ptext (sLit "reduceImplication for") 
2336                                             <+> ppr name,
2337                                           nest 2 (parens $ ptext (sLit "within")
2338                                                            <+> red_doc env)]
2339                          , red_try_me = try_me }
2340
2341         ; traceTc (text "reduceImplication" <+> vcat
2342                         [ ppr (red_givens env), ppr extra_givens, 
2343                           ppr wanteds])
2344         ; (irreds, binds) <- checkLoop env' wanteds
2345
2346         ; traceTc (text "reduceImplication result" <+> vcat
2347                         [ppr irreds, ppr binds])
2348
2349         ; -- extract superclass binds
2350           --  (sc_binds,_) <- extractResults avails []
2351 --      ; traceTc (text "reduceImplication sc_binds" <+> vcat
2352 --                      [ppr sc_binds, ppr avails])
2353 --  
2354
2355         -- SLPJ Sept 07: what if improvement happened inside the checkLoop?
2356         -- Then we must iterate the outer loop too!
2357
2358         ; didntSolveWantedEqs <- allM wantedEqInstIsUnsolved wanteds
2359                                    -- we solve wanted eqs by side effect!
2360
2361             -- Progress is no longer measered by the number of bindings
2362             -- If there are any irreds, but no bindings and no solved
2363             -- equalities, we back off and do nothing
2364         ; let backOff = isEmptyLHsBinds binds &&   -- no new bindings
2365                         (not $ null irreds)   &&   -- but still some irreds
2366                         didntSolveWantedEqs        -- no instantiated cotv
2367
2368         ; if backOff then       -- No progress
2369                 return (emptyBag, [orig_implic])
2370           else do
2371         { (simpler_implic_insts, bind) 
2372             <- makeImplicationBind inst_loc tvs extra_givens irreds
2373                 -- This binding is useless if the recursive simplification
2374                 -- made no progress; but currently we don't try to optimise that
2375                 -- case.  After all, we only try hard to reduce at top level, or
2376                 -- when inferring types.
2377
2378         ; let   -- extract Id binders for dicts and CoTyVar binders for eqs;
2379                 -- see Note [Binders for equalities]
2380               (extra_eq_givens, extra_dict_givens) = partition isEqInst 
2381                                                                extra_givens
2382               eq_cotvs = map instToVar extra_eq_givens
2383               dict_ids = map instToId  extra_dict_givens 
2384
2385               co         = mkWpTyLams tvs
2386                            <.> mkWpTyLams eq_cotvs
2387                            <.> mkWpLams dict_ids
2388                            <.> WpLet (binds `unionBags` bind)
2389               rhs        = mkLHsWrap co payload
2390               loc        = instLocSpan inst_loc
2391                              -- wanted equalities are solved by updating their
2392                              -- cotv; we don't generate bindings for them
2393               dict_bndrs =   map (L loc . HsVar . instToId) 
2394                            . filter (not . isEqInst) 
2395                            $ wanteds
2396               payload    = mkBigLHsTup dict_bndrs
2397         
2398         ; traceTc (vcat [text "reduceImplication" <+> ppr name,
2399                          ppr simpler_implic_insts,
2400                          text "->" <+> ppr rhs])
2401         ; return (unitBag (L loc (VarBind { var_id= instToId orig_implic
2402                                           , var_rhs = rhs
2403                                           , var_inline = notNull dict_ids }
2404                                 -- See Note [Always inline implication constraints]
2405                           )),
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}