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