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