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