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