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