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