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