Add (a) CoreM monad, (b) new Annotations feature
[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.  That is the *whole* reason
1269 for the red_given_scs field in RedEnv, and the function argument to
1270 addGiven.
1271
1272 \begin{code}
1273 tcSimplifySuperClasses
1274         :: InstLoc 
1275         -> Inst         -- The dict whose superclasses 
1276                         -- are being figured out
1277         -> [Inst]       -- Given 
1278         -> [Inst]       -- Wanted
1279         -> TcM TcDictBinds
1280 tcSimplifySuperClasses loc this givens sc_wanteds
1281   = do  { traceTc (text "tcSimplifySuperClasses")
1282         ; (irreds,binds1) <- checkLoop env sc_wanteds
1283         ; let (tidy_env, tidy_irreds) = tidyInsts irreds
1284         ; reportNoInstances tidy_env (Just (loc, givens)) tidy_irreds
1285         ; return binds1 }
1286   where
1287     env =  RedEnv { red_doc = pprInstLoc loc, 
1288                     red_try_me = try_me,
1289                     red_givens = this:givens, 
1290                     red_given_scs = add_scs,
1291                     red_stack = (0,[]),
1292                     red_improve = False }  -- No unification vars
1293     add_scs g | g==this   = NoSCs
1294               | otherwise = AddSCs
1295
1296     try_me _ = ReduceMe  -- Try hard, so we completely solve the superclass 
1297                          -- constraints right here. See Note [SUPERCLASS-LOOP 1]
1298 \end{code}
1299
1300
1301 %************************************************************************
1302 %*                                                                      *
1303 \subsection{tcSimplifyRestricted}
1304 %*                                                                      *
1305 %************************************************************************
1306
1307 tcSimplifyRestricted infers which type variables to quantify for a 
1308 group of restricted bindings.  This isn't trivial.
1309
1310 Eg1:    id = \x -> x
1311         We want to quantify over a to get id :: forall a. a->a
1312         
1313 Eg2:    eq = (==)
1314         We do not want to quantify over a, because there's an Eq a 
1315         constraint, so we get eq :: a->a->Bool  (notice no forall)
1316
1317 So, assume:
1318         RHS has type 'tau', whose free tyvars are tau_tvs
1319         RHS has constraints 'wanteds'
1320
1321 Plan A (simple)
1322   Quantify over (tau_tvs \ ftvs(wanteds))
1323   This is bad. The constraints may contain (Monad (ST s))
1324   where we have         instance Monad (ST s) where...
1325   so there's no need to be monomorphic in s!
1326
1327   Also the constraint might be a method constraint,
1328   whose type mentions a perfectly innocent tyvar:
1329           op :: Num a => a -> b -> a
1330   Here, b is unconstrained.  A good example would be
1331         foo = op (3::Int)
1332   We want to infer the polymorphic type
1333         foo :: forall b. b -> b
1334
1335
1336 Plan B (cunning, used for a long time up to and including GHC 6.2)
1337   Step 1: Simplify the constraints as much as possible (to deal 
1338   with Plan A's problem).  Then set
1339         qtvs = tau_tvs \ ftvs( simplify( wanteds ) )
1340
1341   Step 2: Now simplify again, treating the constraint as 'free' if 
1342   it does not mention qtvs, and trying to reduce it otherwise.
1343   The reasons for this is to maximise sharing.
1344
1345   This fails for a very subtle reason.  Suppose that in the Step 2
1346   a constraint (Foo (Succ Zero) (Succ Zero) b) gets thrown upstairs as 'free'.
1347   In the Step 1 this constraint might have been simplified, perhaps to
1348   (Foo Zero Zero b), AND THEN THAT MIGHT BE IMPROVED, to bind 'b' to 'T'.
1349   This won't happen in Step 2... but that in turn might prevent some other
1350   constraint (Baz [a] b) being simplified (e.g. via instance Baz [a] T where {..}) 
1351   and that in turn breaks the invariant that no constraints are quantified over.
1352
1353   Test typecheck/should_compile/tc177 (which failed in GHC 6.2) demonstrates
1354   the problem.
1355
1356
1357 Plan C (brutal)
1358   Step 1: Simplify the constraints as much as possible (to deal 
1359   with Plan A's problem).  Then set
1360         qtvs = tau_tvs \ ftvs( simplify( wanteds ) )
1361   Return the bindings from Step 1.
1362   
1363
1364 A note about Plan C (arising from "bug" reported by George Russel March 2004)
1365 Consider this:
1366
1367       instance (HasBinary ty IO) => HasCodedValue ty
1368
1369       foo :: HasCodedValue a => String -> IO a
1370
1371       doDecodeIO :: HasCodedValue a => () -> () -> IO a
1372       doDecodeIO codedValue view  
1373         = let { act = foo "foo" } in  act
1374
1375 You might think this should work becuase the call to foo gives rise to a constraint
1376 (HasCodedValue t), which can be satisfied by the type sig for doDecodeIO.  But the
1377 restricted binding act = ... calls tcSimplifyRestricted, and PlanC simplifies the
1378 constraint using the (rather bogus) instance declaration, and now we are stuffed.
1379
1380 I claim this is not really a bug -- but it bit Sergey as well as George.  So here's
1381 plan D
1382
1383
1384 Plan D (a variant of plan B)
1385   Step 1: Simplify the constraints as much as possible (to deal 
1386   with Plan A's problem), BUT DO NO IMPROVEMENT.  Then set
1387         qtvs = tau_tvs \ ftvs( simplify( wanteds ) )
1388
1389   Step 2: Now simplify again, treating the constraint as 'free' if 
1390   it does not mention qtvs, and trying to reduce it otherwise.
1391
1392   The point here is that it's generally OK to have too few qtvs; that is,
1393   to make the thing more monomorphic than it could be.  We don't want to
1394   do that in the common cases, but in wierd cases it's ok: the programmer
1395   can always add a signature.  
1396
1397   Too few qtvs => too many wanteds, which is what happens if you do less
1398   improvement.
1399
1400
1401 \begin{code}
1402 tcSimplifyRestricted    -- Used for restricted binding groups
1403                         -- i.e. ones subject to the monomorphism restriction
1404         :: SDoc
1405         -> TopLevelFlag
1406         -> [Name]               -- Things bound in this group
1407         -> TcTyVarSet           -- Free in the type of the RHSs
1408         -> [Inst]               -- Free in the RHSs
1409         -> TcM ([TyVar],        -- Tyvars to quantify (zonked and quantified)
1410                 TcDictBinds)    -- Bindings
1411         -- tcSimpifyRestricted returns no constraints to
1412         -- quantify over; by definition there are none.
1413         -- They are all thrown back in the LIE
1414
1415 tcSimplifyRestricted doc top_lvl bndrs tau_tvs wanteds
1416         -- Zonk everything in sight
1417   = do  { traceTc (text "tcSimplifyRestricted")
1418         ; wanteds_z <- zonkInsts wanteds
1419
1420         -- 'ReduceMe': Reduce as far as we can.  Don't stop at
1421         -- dicts; the idea is to get rid of as many type
1422         -- variables as possible, and we don't want to stop
1423         -- at (say) Monad (ST s), because that reduces
1424         -- immediately, with no constraint on s.
1425         --
1426         -- BUT do no improvement!  See Plan D above
1427         -- HOWEVER, some unification may take place, if we instantiate
1428         --          a method Inst with an equality constraint
1429         ; let env = mkNoImproveRedEnv doc (\_ -> ReduceMe)
1430         ; (_imp, _binds, constrained_dicts) <- reduceContext env wanteds_z
1431
1432         -- Next, figure out the tyvars we will quantify over
1433         ; tau_tvs' <- zonkTcTyVarsAndFV (varSetElems tau_tvs)
1434         ; gbl_tvs' <- tcGetGlobalTyVars
1435         ; constrained_dicts' <- zonkInsts constrained_dicts
1436
1437         ; let qtvs1 = tau_tvs' `minusVarSet` oclose (fdPredsOfInsts constrained_dicts) gbl_tvs'
1438                                 -- As in tcSimplifyInfer
1439
1440                 -- Do not quantify over constrained type variables:
1441                 -- this is the monomorphism restriction
1442               constrained_tvs' = tyVarsOfInsts constrained_dicts'
1443               qtvs = qtvs1 `minusVarSet` constrained_tvs'
1444               pp_bndrs = pprWithCommas (quotes . ppr) bndrs
1445
1446         -- Warn in the mono
1447         ; warn_mono <- doptM Opt_WarnMonomorphism
1448         ; warnTc (warn_mono && (constrained_tvs' `intersectsVarSet` qtvs1))
1449                  (vcat[ ptext (sLit "the Monomorphism Restriction applies to the binding")
1450                                 <> plural bndrs <+> ptext (sLit "for") <+> pp_bndrs,
1451                         ptext (sLit "Consider giving a type signature for") <+> pp_bndrs])
1452
1453         ; traceTc (text "tcSimplifyRestricted" <+> vcat [
1454                 pprInsts wanteds, pprInsts constrained_dicts',
1455                 ppr _binds,
1456                 ppr constrained_tvs', ppr tau_tvs', ppr qtvs ])
1457
1458           -- Zonk wanteds again!  The first call to reduceContext may have
1459           -- instantiated some variables. 
1460           -- FIXME: If red_improve would work, we could propagate that into
1461           --        the equality solver, too, to prevent instantating any
1462           --        variables.
1463         ; wanteds_zz <- zonkInsts wanteds_z
1464
1465         -- The first step may have squashed more methods than
1466         -- necessary, so try again, this time more gently, knowing the exact
1467         -- set of type variables to quantify over.
1468         --
1469         -- We quantify only over constraints that are captured by qtvs;
1470         -- these will just be a subset of non-dicts.  This in contrast
1471         -- to normal inference (using isFreeWhenInferring) in which we quantify over
1472         -- all *non-inheritable* constraints too.  This implements choice
1473         -- (B) under "implicit parameter and monomorphism" above.
1474         --
1475         -- Remember that we may need to do *some* simplification, to
1476         -- (for example) squash {Monad (ST s)} into {}.  It's not enough
1477         -- just to float all constraints
1478         --
1479         -- At top level, we *do* squash methods becuase we want to 
1480         -- expose implicit parameters to the test that follows
1481         ; let is_nested_group = isNotTopLevel top_lvl
1482               try_me inst | isFreeWrtTyVars qtvs inst,
1483                            (is_nested_group || isDict inst) = Stop
1484                           | otherwise                       = ReduceMe 
1485               env = mkNoImproveRedEnv doc try_me
1486         ; (_imp, binds, irreds) <- reduceContext env wanteds_zz
1487
1488         -- See "Notes on implicit parameters, Question 4: top level"
1489         ; ASSERT( all (isFreeWrtTyVars qtvs) irreds )   -- None should be captured
1490           if is_nested_group then
1491                 extendLIEs irreds
1492           else do { let (bad_ips, non_ips) = partition isIPDict irreds
1493                   ; addTopIPErrs bndrs bad_ips
1494                   ; extendLIEs non_ips }
1495
1496         ; qtvs' <- zonkQuantifiedTyVars (varSetElems qtvs)
1497         ; return (qtvs', binds) }
1498 \end{code}
1499
1500
1501 %************************************************************************
1502 %*                                                                      *
1503                 tcSimplifyRuleLhs
1504 %*                                                                      *
1505 %************************************************************************
1506
1507 On the LHS of transformation rules we only simplify methods and constants,
1508 getting dictionaries.  We want to keep all of them unsimplified, to serve
1509 as the available stuff for the RHS of the rule.
1510
1511 Example.  Consider the following left-hand side of a rule
1512         
1513         f (x == y) (y > z) = ...
1514
1515 If we typecheck this expression we get constraints
1516
1517         d1 :: Ord a, d2 :: Eq a
1518
1519 We do NOT want to "simplify" to the LHS
1520
1521         forall x::a, y::a, z::a, d1::Ord a.
1522           f ((==) (eqFromOrd d1) x y) ((>) d1 y z) = ...
1523
1524 Instead we want 
1525
1526         forall x::a, y::a, z::a, d1::Ord a, d2::Eq a.
1527           f ((==) d2 x y) ((>) d1 y z) = ...
1528
1529 Here is another example:
1530
1531         fromIntegral :: (Integral a, Num b) => a -> b
1532         {-# RULES "foo"  fromIntegral = id :: Int -> Int #-}
1533
1534 In the rule, a=b=Int, and Num Int is a superclass of Integral Int. But
1535 we *dont* want to get
1536
1537         forall dIntegralInt.
1538            fromIntegral Int Int dIntegralInt (scsel dIntegralInt) = id Int
1539
1540 because the scsel will mess up RULE matching.  Instead we want
1541
1542         forall dIntegralInt, dNumInt.
1543           fromIntegral Int Int dIntegralInt dNumInt = id Int
1544
1545 Even if we have 
1546
1547         g (x == y) (y == z) = ..
1548
1549 where the two dictionaries are *identical*, we do NOT WANT
1550
1551         forall x::a, y::a, z::a, d1::Eq a
1552           f ((==) d1 x y) ((>) d1 y z) = ...
1553
1554 because that will only match if the dict args are (visibly) equal.
1555 Instead we want to quantify over the dictionaries separately.
1556
1557 In short, tcSimplifyRuleLhs must *only* squash LitInst and MethInts, leaving
1558 all dicts unchanged, with absolutely no sharing.  It's simpler to do this
1559 from scratch, rather than further parameterise simpleReduceLoop etc.
1560 Simpler, maybe, but alas not simple (see Trac #2494)
1561
1562 * Type errors may give rise to an (unsatisfiable) equality constraint
1563
1564 * Applications of a higher-rank function on the LHS may give
1565   rise to an implication constraint, esp if there are unsatisfiable
1566   equality constraints inside.
1567
1568 \begin{code}
1569 tcSimplifyRuleLhs :: [Inst] -> TcM ([Inst], TcDictBinds)
1570 tcSimplifyRuleLhs wanteds
1571   = do  { wanteds' <- zonkInsts wanteds
1572         ; (irreds, binds) <- go [] emptyBag wanteds'
1573         ; let (dicts, bad_irreds) = partition isDict irreds
1574         ; traceTc (text "tcSimplifyrulelhs" <+> pprInsts bad_irreds)
1575         ; addNoInstanceErrs (nub bad_irreds)
1576                 -- The nub removes duplicates, which has
1577                 -- not happened otherwise (see notes above)
1578         ; return (dicts, binds) }
1579   where
1580     go :: [Inst] -> TcDictBinds -> [Inst] -> TcM ([Inst], TcDictBinds)
1581     go irreds binds []
1582         = return (irreds, binds)
1583     go irreds binds (w:ws)
1584         | isDict w
1585         = go (w:irreds) binds ws
1586         | isImplicInst w        -- Have a go at reducing the implication
1587         = do { (binds1, irreds1) <- reduceImplication red_env w
1588              ; let (bad_irreds, ok_irreds) = partition isImplicInst irreds1
1589              ; go (bad_irreds ++ irreds) 
1590                   (binds `unionBags` binds1) 
1591                   (ok_irreds ++ ws)}
1592         | otherwise
1593         = do { w' <- zonkInst w  -- So that (3::Int) does not generate a call
1594                                  -- to fromInteger; this looks fragile to me
1595              ; lookup_result <- lookupSimpleInst w'
1596              ; case lookup_result of
1597                  NoInstance      -> go (w:irreds) binds ws
1598                  GenInst ws' rhs -> go irreds binds' (ws' ++ ws)
1599                         where
1600                           binds' = addInstToDictBind binds w rhs
1601           }
1602
1603         -- Sigh: we need to reduce inside implications
1604     red_env = mkInferRedEnv doc try_me
1605     doc = ptext (sLit "Implication constraint in RULE lhs")
1606     try_me inst | isMethodOrLit inst = ReduceMe
1607                 | otherwise          = Stop     -- Be gentle
1608 \end{code}
1609
1610 tcSimplifyBracket is used when simplifying the constraints arising from
1611 a Template Haskell bracket [| ... |].  We want to check that there aren't
1612 any constraints that can't be satisfied (e.g. Show Foo, where Foo has no
1613 Show instance), but we aren't otherwise interested in the results.
1614 Nor do we care about ambiguous dictionaries etc.  We will type check
1615 this bracket again at its usage site.
1616
1617 \begin{code}
1618 tcSimplifyBracket :: [Inst] -> TcM ()
1619 tcSimplifyBracket wanteds
1620   = do  { tryHardCheckLoop doc wanteds
1621         ; return () }
1622   where
1623     doc = text "tcSimplifyBracket"
1624 \end{code}
1625
1626
1627 %************************************************************************
1628 %*                                                                      *
1629 \subsection{Filtering at a dynamic binding}
1630 %*                                                                      *
1631 %************************************************************************
1632
1633 When we have
1634         let ?x = R in B
1635
1636 we must discharge all the ?x constraints from B.  We also do an improvement
1637 step; if we have ?x::t1 and ?x::t2 we must unify t1, t2.
1638
1639 Actually, the constraints from B might improve the types in ?x. For example
1640
1641         f :: (?x::Int) => Char -> Char
1642         let ?x = 3 in f 'c'
1643
1644 then the constraint (?x::Int) arising from the call to f will
1645 force the binding for ?x to be of type Int.
1646
1647 \begin{code}
1648 tcSimplifyIPs :: [Inst]         -- The implicit parameters bound here
1649               -> [Inst]         -- Wanted
1650               -> TcM TcDictBinds
1651         -- We need a loop so that we do improvement, and then
1652         -- (next time round) generate a binding to connect the two
1653         --      let ?x = e in ?x
1654         -- Here the two ?x's have different types, and improvement 
1655         -- makes them the same.
1656
1657 tcSimplifyIPs given_ips wanteds
1658   = do  { wanteds'   <- zonkInsts wanteds
1659         ; given_ips' <- zonkInsts given_ips
1660                 -- Unusually for checking, we *must* zonk the given_ips
1661
1662         ; let env = mkRedEnv doc try_me given_ips'
1663         ; (improved, binds, irreds) <- reduceContext env wanteds'
1664
1665         ; if null irreds || not improved then 
1666                 ASSERT( all is_free irreds )
1667                 do { extendLIEs irreds
1668                    ; return binds }
1669           else do
1670         -- If improvement did some unification, we go round again.
1671         -- We start again with irreds, not wanteds
1672         -- Using an instance decl might have introduced a fresh type
1673         -- variable which might have been unified, so we'd get an 
1674         -- infinite loop if we started again with wanteds!  
1675         -- See Note [LOOP]
1676         { binds1 <- tcSimplifyIPs given_ips' irreds
1677         ; return $ binds `unionBags` binds1
1678         } }
1679   where
1680     doc    = text "tcSimplifyIPs" <+> ppr given_ips
1681     ip_set = mkNameSet (ipNamesOfInsts given_ips)
1682     is_free inst = isFreeWrtIPs ip_set inst
1683
1684         -- Simplify any methods that mention the implicit parameter
1685     try_me inst | is_free inst = Stop
1686                 | otherwise    = ReduceMe
1687 \end{code}
1688
1689
1690 %************************************************************************
1691 %*                                                                      *
1692 \subsection[binds-for-local-funs]{@bindInstsOfLocalFuns@}
1693 %*                                                                      *
1694 %************************************************************************
1695
1696 When doing a binding group, we may have @Insts@ of local functions.
1697 For example, we might have...
1698 \begin{verbatim}
1699 let f x = x + 1     -- orig local function (overloaded)
1700     f.1 = f Int     -- two instances of f
1701     f.2 = f Float
1702  in
1703     (f.1 5, f.2 6.7)
1704 \end{verbatim}
1705 The point is: we must drop the bindings for @f.1@ and @f.2@ here,
1706 where @f@ is in scope; those @Insts@ must certainly not be passed
1707 upwards towards the top-level.  If the @Insts@ were binding-ified up
1708 there, they would have unresolvable references to @f@.
1709
1710 We pass in an @init_lie@ of @Insts@ and a list of locally-bound @Ids@.
1711 For each method @Inst@ in the @init_lie@ that mentions one of the
1712 @Ids@, we create a binding.  We return the remaining @Insts@ (in an
1713 @LIE@), as well as the @HsBinds@ generated.
1714
1715 \begin{code}
1716 bindInstsOfLocalFuns :: [Inst] -> [TcId] -> TcM TcDictBinds
1717 -- Simlifies only MethodInsts, and generate only bindings of form 
1718 --      fm = f tys dicts
1719 -- We're careful not to even generate bindings of the form
1720 --      d1 = d2
1721 -- You'd think that'd be fine, but it interacts with what is
1722 -- arguably a bug in Match.tidyEqnInfo (see notes there)
1723
1724 bindInstsOfLocalFuns wanteds local_ids
1725   | null overloaded_ids = do
1726         -- Common case
1727     extendLIEs wanteds
1728     return emptyLHsBinds
1729
1730   | otherwise
1731   = do  { (irreds, binds) <- gentleInferLoop doc for_me
1732         ; extendLIEs not_for_me 
1733         ; extendLIEs irreds
1734         ; return binds }
1735   where
1736     doc              = text "bindInsts" <+> ppr local_ids
1737     overloaded_ids   = filter is_overloaded local_ids
1738     is_overloaded id = isOverloadedTy (idType id)
1739     (for_me, not_for_me) = partition (isMethodFor overloaded_set) wanteds
1740
1741     overloaded_set = mkVarSet overloaded_ids    -- There can occasionally be a lot of them
1742                                                 -- so it's worth building a set, so that
1743                                                 -- lookup (in isMethodFor) is faster
1744 \end{code}
1745
1746
1747 %************************************************************************
1748 %*                                                                      *
1749 \subsection{Data types for the reduction mechanism}
1750 %*                                                                      *
1751 %************************************************************************
1752
1753 The main control over context reduction is here
1754
1755 \begin{code}
1756 data RedEnv 
1757   = RedEnv { red_doc    :: SDoc                 -- The context
1758            , red_try_me :: Inst -> WhatToDo
1759            , red_improve :: Bool                -- True <=> do improvement
1760            , red_givens :: [Inst]               -- All guaranteed rigid
1761                                                 -- Always dicts & equalities
1762                                                 -- but see Note [Rigidity]
1763  
1764            , red_given_scs :: Inst -> WantSCs   -- See Note [Recursive instances and superclases]
1765  
1766            , red_stack  :: (Int, [Inst])        -- Recursion stack (for err msg)
1767                                                 -- See Note [RedStack]
1768   }
1769
1770 -- Note [Rigidity]
1771 -- The red_givens are rigid so far as cmpInst is concerned.
1772 -- There is one case where they are not totally rigid, namely in tcSimplifyIPs
1773 --      let ?x = e in ...
1774 -- Here, the given is (?x::a), where 'a' is not necy a rigid type
1775 -- But that doesn't affect the comparison, which is based only on mame.
1776
1777 -- Note [RedStack]
1778 -- The red_stack pair (n,insts) pair is just used for error reporting.
1779 -- 'n' is always the depth of the stack.
1780 -- The 'insts' is the stack of Insts being reduced: to produce X
1781 -- I had to produce Y, to produce Y I had to produce Z, and so on.
1782
1783
1784 mkRedEnv :: SDoc -> (Inst -> WhatToDo) -> [Inst] -> RedEnv
1785 mkRedEnv doc try_me givens
1786   = RedEnv { red_doc = doc, red_try_me = try_me,
1787              red_givens = givens, 
1788              red_given_scs = const AddSCs,
1789              red_stack = (0,[]),
1790              red_improve = True }       
1791
1792 mkInferRedEnv :: SDoc -> (Inst -> WhatToDo) -> RedEnv
1793 -- No givens at all
1794 mkInferRedEnv doc try_me
1795   = RedEnv { red_doc = doc, red_try_me = try_me,
1796              red_givens = [], 
1797              red_given_scs = const AddSCs,
1798              red_stack = (0,[]),
1799              red_improve = True }       
1800
1801 mkNoImproveRedEnv :: SDoc -> (Inst -> WhatToDo) -> RedEnv
1802 -- Do not do improvement; no givens
1803 mkNoImproveRedEnv doc try_me
1804   = RedEnv { red_doc = doc, red_try_me = try_me,
1805              red_givens = [], 
1806              red_given_scs = const AddSCs,
1807              red_stack = (0,[]),
1808              red_improve = True }       
1809
1810 data WhatToDo
1811  = ReduceMe     -- Try to reduce this
1812                 -- If there's no instance, add the inst to the 
1813                 -- irreductible ones, but don't produce an error 
1814                 -- message of any kind.
1815                 -- It might be quite legitimate such as (Eq a)!
1816
1817  | Stop         -- Return as irreducible unless it can
1818                         -- be reduced to a constant in one step
1819                         -- Do not add superclasses; see 
1820
1821 data WantSCs = NoSCs | AddSCs   -- Tells whether we should add the superclasses
1822                                 -- of a predicate when adding it to the avails
1823         -- The reason for this flag is entirely the super-class loop problem
1824         -- Note [SUPER-CLASS LOOP 1]
1825
1826 zonkRedEnv :: RedEnv -> TcM RedEnv
1827 zonkRedEnv env
1828   = do { givens' <- mapM zonkInst (red_givens env)
1829        ; return $ env {red_givens = givens'}
1830        }
1831 \end{code}
1832
1833
1834 %************************************************************************
1835 %*                                                                      *
1836 \subsection[reduce]{@reduce@}
1837 %*                                                                      *
1838 %************************************************************************
1839
1840 Note [Ancestor Equalities]
1841 ~~~~~~~~~~~~~~~~~~~~~~~~~~
1842 During context reduction, we add to the wanted equalities also those
1843 equalities that (transitively) occur in superclass contexts of wanted
1844 class constraints.  Consider the following code
1845
1846   class a ~ Int => C a
1847   instance C Int
1848
1849 If (C a) is wanted, we want to add (a ~ Int), which will be discharged by
1850 substituting Int for a.  Hence, we ultimately want (C Int), which we
1851 discharge with the explicit instance.
1852
1853 \begin{code}
1854 reduceContext :: RedEnv
1855               -> [Inst]                 -- Wanted
1856               -> TcM (ImprovementDone,
1857                       TcDictBinds,      -- Dictionary bindings
1858                       [Inst])           -- Irreducible
1859
1860 reduceContext env wanteds0
1861   = do  { traceTc (text "reduceContext" <+> (vcat [
1862              text "----------------------",
1863              red_doc env,
1864              text "given" <+> ppr (red_givens env),
1865              text "wanted" <+> ppr wanteds0,
1866              text "----------------------"
1867              ]))
1868
1869           -- We want to add as wanted equalities those that (transitively) 
1870           -- occur in superclass contexts of wanted class constraints.
1871           -- See Note [Ancestor Equalities]
1872         ; ancestor_eqs <- ancestorEqualities wanteds0
1873         ; traceTc $ text "reduceContext: ancestor eqs" <+> ppr ancestor_eqs
1874
1875           -- Normalise and solve all equality constraints as far as possible
1876           -- and normalise all dictionary constraints wrt to the reduced
1877           -- equalities.  The returned wanted constraints include the
1878           -- irreducible wanted equalities.
1879         ; let wanteds = wanteds0 ++ ancestor_eqs
1880               givens  = red_givens env
1881         ; (givens', 
1882            wanteds', 
1883            normalise_binds,
1884            eq_improved)     <- tcReduceEqs givens wanteds
1885         ; traceTc $ text "reduceContext: tcReduceEqs result" <+> vcat
1886                       [ppr givens', ppr wanteds', ppr normalise_binds]
1887
1888           -- Build the Avail mapping from "given_dicts"
1889         ; (init_state, _) <- getLIE $ do 
1890                 { init_state <- foldlM (addGiven (red_given_scs env)) 
1891                                        emptyAvails givens'
1892                 ; return init_state
1893                 }
1894
1895           -- Solve the *wanted* *dictionary* constraints (not implications)
1896           -- This may expose some further equational constraints in the course
1897           -- of improvement due to functional dependencies if any of the
1898           -- involved unifications gets deferred.
1899         ; let (wanted_implics, wanted_dicts) = partition isImplicInst wanteds'
1900         ; (avails, extra_eqs) <- getLIE (reduceList env wanted_dicts init_state)
1901                    -- The getLIE is reqd because reduceList does improvement
1902                    -- (via extendAvails) which may in turn do unification
1903         ; (dict_binds, 
1904            bound_dicts, 
1905            dict_irreds)       <- extractResults avails wanted_dicts
1906         ; traceTc $ text "reduceContext: extractResults" <+> vcat
1907                       [ppr avails, ppr wanted_dicts, ppr dict_binds]
1908
1909           -- Solve the wanted *implications*.  In doing so, we can provide
1910           -- as "given"   all the dicts that were originally given, 
1911           --              *or* for which we now have bindings, 
1912           --              *or* which are now irreds
1913           -- NB: Equality irreds need to be converted, as the recursive 
1914           --     invocation of the solver will still treat them as wanteds
1915           --     otherwise.
1916         ; let implic_env = env { red_givens 
1917                                    = givens ++ bound_dicts ++
1918                                      map wantedToLocalEqInst dict_irreds }
1919         ; (implic_binds_s, implic_irreds_s) 
1920             <- mapAndUnzipM (reduceImplication implic_env) wanted_implics
1921         ; let implic_binds  = unionManyBags implic_binds_s
1922               implic_irreds = concat implic_irreds_s
1923
1924           -- Collect all irreducible instances, and determine whether we should
1925           -- go round again.  We do so in either of two cases:
1926           -- (1) If dictionary reduction or equality solving led to
1927           --     improvement (i.e., instantiated type variables).
1928           -- (2) If we reduced dictionaries (i.e., got dictionary bindings),
1929           --     they may have exposed further opportunities to normalise
1930           --     family applications.  See Note [Dictionary Improvement]
1931           --
1932           -- NB: We do *not* go around for new extra_eqs.  Morally, we should,
1933           --     but we can't without risking non-termination (see #2688).  By
1934           --     not going around, we miss some legal programs mixing FDs and
1935           --     TFs, but we never claimed to support such programs in the
1936           --     current implementation anyway.
1937
1938         ; let all_irreds       = dict_irreds ++ implic_irreds ++ extra_eqs
1939               avails_improved  = availsImproved avails
1940               improvedFlexible = avails_improved || eq_improved
1941               reduced_dicts    = not (isEmptyBag dict_binds)
1942               improved         = improvedFlexible || reduced_dicts
1943               --
1944               improvedHint  = (if avails_improved then " [AVAILS]" else "") ++
1945                               (if eq_improved then " [EQ]" else "")
1946
1947         ; traceTc (text "reduceContext end" <+> (vcat [
1948              text "----------------------",
1949              red_doc env,
1950              text "given" <+> ppr givens,
1951              text "wanted" <+> ppr wanteds0,
1952              text "----",
1953              text "avails" <+> pprAvails avails,
1954              text "improved =" <+> ppr improved <+> text improvedHint,
1955              text "(all) irreds = " <+> ppr all_irreds,
1956              text "dict-binds = " <+> ppr dict_binds,
1957              text "implic-binds = " <+> ppr implic_binds,
1958              text "----------------------"
1959              ]))
1960
1961         ; return (improved, 
1962                   normalise_binds `unionBags` dict_binds 
1963                                   `unionBags` implic_binds, 
1964                   all_irreds) 
1965         }
1966
1967 tcImproveOne :: Avails -> Inst -> TcM ImprovementDone
1968 tcImproveOne avails inst
1969   | not (isDict inst) = return False
1970   | otherwise
1971   = do  { inst_envs <- tcGetInstEnvs
1972         ; let eqns = improveOne (classInstances inst_envs)
1973                                 (dictPred inst, pprInstArising inst)
1974                                 [ (dictPred p, pprInstArising p)
1975                                 | p <- availsInsts avails, isDict p ]
1976                 -- Avails has all the superclasses etc (good)
1977                 -- It also has all the intermediates of the deduction (good)
1978                 -- It does not have duplicates (good)
1979                 -- NB that (?x::t1) and (?x::t2) will be held separately in 
1980                 --    avails so that improve will see them separate
1981         ; traceTc (text "improveOne" <+> ppr inst)
1982         ; unifyEqns eqns }
1983
1984 unifyEqns :: [(Equation, (PredType, SDoc), (PredType, SDoc))] 
1985           -> TcM ImprovementDone
1986 unifyEqns [] = return False
1987 unifyEqns eqns
1988   = do  { traceTc (ptext (sLit "Improve:") <+> vcat (map pprEquationDoc eqns))
1989         ; improved <- mapM unify eqns
1990         ; return $ or improved
1991         }
1992   where
1993     unify ((qtvs, pairs), what1, what2)
1994          = addErrCtxtM (mkEqnMsg what1 what2) $ 
1995              do { let freeTyVars = unionVarSets (map tvs_pr pairs) 
1996                                    `minusVarSet` qtvs
1997                 ; (_, _, tenv) <- tcInstTyVars (varSetElems qtvs)
1998                 ; mapM_ (unif_pr tenv) pairs
1999                 ; anyM isFilledMetaTyVar $ varSetElems freeTyVars
2000                 }
2001
2002     unif_pr tenv (ty1, ty2) = unifyType (substTy tenv ty1) (substTy tenv ty2)
2003
2004     tvs_pr (ty1, ty2) = tyVarsOfType ty1 `unionVarSet` tyVarsOfType ty2
2005
2006 pprEquationDoc :: (Equation, (PredType, SDoc), (PredType, SDoc)) -> SDoc
2007 pprEquationDoc (eqn, (p1, _), (p2, _)) 
2008   = vcat [pprEquation eqn, nest 2 (ppr p1), nest 2 (ppr p2)]
2009
2010 mkEqnMsg :: (TcPredType, SDoc) -> (TcPredType, SDoc) -> TidyEnv
2011          -> TcM (TidyEnv, SDoc)
2012 mkEqnMsg (pred1,from1) (pred2,from2) tidy_env
2013   = do  { pred1' <- zonkTcPredType pred1
2014         ; pred2' <- zonkTcPredType pred2
2015         ; let { pred1'' = tidyPred tidy_env pred1'
2016               ; pred2'' = tidyPred tidy_env pred2' }
2017         ; let msg = vcat [ptext (sLit "When using functional dependencies to combine"),
2018                           nest 2 (sep [ppr pred1'' <> comma, nest 2 from1]), 
2019                           nest 2 (sep [ppr pred2'' <> comma, nest 2 from2])]
2020         ; return (tidy_env, msg) }
2021 \end{code}
2022
2023 Note [Dictionary Improvement]
2024 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2025 In reduceContext, we first reduce equalities and then class constraints.
2026 However, the letter may expose further opportunities for the former.  Hence,
2027 we need to go around again if dictionary reduction produced any dictionary
2028 bindings.  The following example demonstrated the point:
2029
2030   data EX _x _y (p :: * -> *)
2031   data ANY
2032
2033   class Base p
2034
2035   class Base (Def p) => Prop p where
2036    type Def p
2037
2038   instance Base ()
2039   instance Prop () where
2040    type Def () = ()
2041
2042   instance (Base (Def (p ANY))) => Base (EX _x _y p)
2043   instance (Prop (p ANY)) => Prop (EX _x _y p) where
2044    type Def (EX _x _y p) = EX _x _y p
2045
2046   data FOO x
2047   instance Prop (FOO x) where
2048    type Def (FOO x) = ()
2049
2050   data BAR
2051   instance Prop BAR where
2052    type Def BAR = EX () () FOO
2053
2054 During checking the last instance declaration, we need to check the superclass
2055 cosntraint Base (Def BAR), which family normalisation reduced to 
2056 Base (EX () () FOO).  Chasing the instance for Base (EX _x _y p), gives us
2057 Base (Def (FOO ANY)), which again requires family normalisation of Def to
2058 Base () before we can finish.
2059
2060
2061 The main context-reduction function is @reduce@.  Here's its game plan.
2062
2063 \begin{code}
2064 reduceList :: RedEnv -> [Inst] -> Avails -> TcM Avails
2065 reduceList env@(RedEnv {red_stack = (n,stk)}) wanteds state
2066   = do  { traceTc (text "reduceList " <+> (ppr wanteds $$ ppr state))
2067         ; dopts <- getDOpts
2068         ; when (debugIsOn && (n > 8)) $ do
2069                 debugDumpTcRn (hang (ptext (sLit "Interesting! Context reduction stack depth") <+> int n) 
2070                              2 (ifPprDebug (nest 2 (pprStack stk))))
2071         ; if n >= ctxtStkDepth dopts then
2072             failWithTc (reduceDepthErr n stk)
2073           else
2074             go wanteds state }
2075   where
2076     go []     state = return state
2077     go (w:ws) state = do { state' <- reduce (env {red_stack = (n+1, w:stk)}) w state
2078                          ; go ws state' }
2079
2080     -- Base case: we're done!
2081 reduce :: RedEnv -> Inst -> Avails -> TcM Avails
2082 reduce env wanted avails
2083
2084     -- We don't reduce equalities here (and they must not end up as irreds
2085     -- in the Avails!)
2086   | isEqInst wanted
2087   = return avails
2088
2089     -- It's the same as an existing inst, or a superclass thereof
2090   | Just _ <- findAvail avails wanted
2091   = do { traceTc (text "reduce: found " <+> ppr wanted)
2092        ; return avails
2093        }
2094
2095   | otherwise
2096   = do  { traceTc (text "reduce" <+> ppr wanted $$ ppr avails)
2097         ; case red_try_me env wanted of {
2098             Stop -> try_simple (addIrred NoSCs);
2099                         -- See Note [No superclasses for Stop]
2100
2101             ReduceMe -> do      -- It should be reduced
2102                 { (avails, lookup_result) <- reduceInst env avails wanted
2103                 ; case lookup_result of
2104                     NoInstance -> addIrred AddSCs avails wanted
2105                              -- Add it and its superclasses
2106                              
2107                     GenInst [] rhs -> addWanted AddSCs avails wanted rhs []
2108
2109                     GenInst wanteds' rhs
2110                           -> do { avails1 <- addIrred NoSCs avails wanted
2111                                 ; avails2 <- reduceList env wanteds' avails1
2112                                 ; addWanted AddSCs avails2 wanted rhs wanteds' } }
2113                 -- Temporarily do addIrred *before* the reduceList, 
2114                 -- which has the effect of adding the thing we are trying
2115                 -- to prove to the database before trying to prove the things it
2116                 -- needs.  See note [RECURSIVE DICTIONARIES]
2117                 -- NB: we must not do an addWanted before, because that adds the
2118                 --     superclasses too, and that can lead to a spurious loop; see
2119                 --     the examples in [SUPERCLASS-LOOP]
2120                 -- So we do an addIrred before, and then overwrite it afterwards with addWanted
2121     } }
2122   where
2123         -- First, see if the inst can be reduced to a constant in one step
2124         -- Works well for literals (1::Int) and constant dictionaries (d::Num Int)
2125         -- Don't bother for implication constraints, which take real work
2126     try_simple do_this_otherwise
2127       = do { res <- lookupSimpleInst wanted
2128            ; case res of
2129                 GenInst [] rhs -> addWanted AddSCs avails wanted rhs []
2130                 _              -> do_this_otherwise avails wanted }
2131 \end{code}
2132
2133
2134 Note [RECURSIVE DICTIONARIES]
2135 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2136 Consider 
2137     data D r = ZeroD | SuccD (r (D r));
2138     
2139     instance (Eq (r (D r))) => Eq (D r) where
2140         ZeroD     == ZeroD     = True
2141         (SuccD a) == (SuccD b) = a == b
2142         _         == _         = False;
2143     
2144     equalDC :: D [] -> D [] -> Bool;
2145     equalDC = (==);
2146
2147 We need to prove (Eq (D [])).  Here's how we go:
2148
2149         d1 : Eq (D [])
2150
2151 by instance decl, holds if
2152         d2 : Eq [D []]
2153         where   d1 = dfEqD d2
2154
2155 by instance decl of Eq, holds if
2156         d3 : D []
2157         where   d2 = dfEqList d3
2158                 d1 = dfEqD d2
2159
2160 But now we can "tie the knot" to give
2161
2162         d3 = d1
2163         d2 = dfEqList d3
2164         d1 = dfEqD d2
2165
2166 and it'll even run!  The trick is to put the thing we are trying to prove
2167 (in this case Eq (D []) into the database before trying to prove its
2168 contributing clauses.
2169         
2170 Note [SUPERCLASS-LOOP 2]
2171 ~~~~~~~~~~~~~~~~~~~~~~~~
2172 We need to be careful when adding "the constaint we are trying to prove".
2173 Suppose we are *given* d1:Ord a, and want to deduce (d2:C [a]) where
2174
2175         class Ord a => C a where
2176         instance Ord [a] => C [a] where ...
2177
2178 Then we'll use the instance decl to deduce C [a] from Ord [a], and then add the
2179 superclasses of C [a] to avails.  But we must not overwrite the binding
2180 for Ord [a] (which is obtained from Ord a) with a superclass selection or we'll just
2181 build a loop! 
2182
2183 Here's another variant, immortalised in tcrun020
2184         class Monad m => C1 m
2185         class C1 m => C2 m x
2186         instance C2 Maybe Bool
2187 For the instance decl we need to build (C1 Maybe), and it's no good if
2188 we run around and add (C2 Maybe Bool) and its superclasses to the avails 
2189 before we search for C1 Maybe.
2190
2191 Here's another example 
2192         class Eq b => Foo a b
2193         instance Eq a => Foo [a] a
2194 If we are reducing
2195         (Foo [t] t)
2196
2197 we'll first deduce that it holds (via the instance decl).  We must not
2198 then overwrite the Eq t constraint with a superclass selection!
2199
2200 At first I had a gross hack, whereby I simply did not add superclass constraints
2201 in addWanted, though I did for addGiven and addIrred.  This was sub-optimal,
2202 becuase it lost legitimate superclass sharing, and it still didn't do the job:
2203 I found a very obscure program (now tcrun021) in which improvement meant the
2204 simplifier got two bites a the cherry... so something seemed to be an Stop
2205 first time, but reducible next time.
2206
2207 Now we implement the Right Solution, which is to check for loops directly 
2208 when adding superclasses.  It's a bit like the occurs check in unification.
2209
2210
2211
2212 %************************************************************************
2213 %*                                                                      *
2214                 Reducing a single constraint
2215 %*                                                                      *
2216 %************************************************************************
2217
2218 \begin{code}
2219 ---------------------------------------------
2220 reduceInst :: RedEnv -> Avails -> Inst -> TcM (Avails, LookupInstResult)
2221 reduceInst _ avails other_inst
2222   = do  { result <- lookupSimpleInst other_inst
2223         ; return (avails, result) }
2224 \end{code}
2225
2226 Note [Equational Constraints in Implication Constraints]
2227 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2228
2229 An implication constraint is of the form 
2230         Given => Wanted 
2231 where Given and Wanted may contain both equational and dictionary
2232 constraints. The delay and reduction of these two kinds of constraints
2233 is distinct:
2234
2235 -) In the generated code, wanted Dictionary constraints are wrapped up in an
2236    implication constraint that is created at the code site where the wanted
2237    dictionaries can be reduced via a let-binding. This let-bound implication
2238    constraint is deconstructed at the use-site of the wanted dictionaries.
2239
2240 -) While the reduction of equational constraints is also delayed, the delay
2241    is not manifest in the generated code. The required evidence is generated
2242    in the code directly at the use-site. There is no let-binding and deconstruction
2243    necessary. The main disadvantage is that we cannot exploit sharing as the
2244    same evidence may be generated at multiple use-sites. However, this disadvantage
2245    is limited because it only concerns coercions which are erased.
2246
2247 The different treatment is motivated by the different in representation. Dictionary
2248 constraints require manifest runtime dictionaries, while equations require coercions
2249 which are types.
2250
2251 \begin{code}
2252 ---------------------------------------------
2253 reduceImplication :: RedEnv
2254                   -> Inst
2255                   -> TcM (TcDictBinds, [Inst])
2256 \end{code}
2257
2258 Suppose we are simplifying the constraint
2259         forall bs. extras => wanted
2260 in the context of an overall simplification problem with givens 'givens'.
2261
2262 Note that
2263   * The 'givens' need not mention any of the quantified type variables
2264         e.g.    forall {}. Eq a => Eq [a]
2265                 forall {}. C Int => D (Tree Int)
2266
2267     This happens when you have something like
2268         data T a where
2269           T1 :: Eq a => a -> T a
2270
2271         f :: T a -> Int
2272         f x = ...(case x of { T1 v -> v==v })...
2273
2274 \begin{code}
2275         -- ToDo: should we instantiate tvs?  I think it's not necessary
2276         --
2277         -- Note on coercion variables:
2278         --
2279         --      The extra given coercion variables are bound at two different 
2280         --      sites:
2281         --
2282         --      -) in the creation context of the implication constraint        
2283         --              the solved equational constraints use these binders
2284         --
2285         --      -) at the solving site of the implication constraint
2286         --              the solved dictionaries use these binders;
2287         --              these binders are generated by reduceImplication
2288         --
2289         -- Note [Binders for equalities]
2290         -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2291         -- To reuse the binders of local/given equalities in the binders of 
2292         -- implication constraints, it is crucial that these given equalities
2293         -- always have the form
2294         --   cotv :: t1 ~ t2
2295         -- where cotv is a simple coercion type variable (and not a more
2296         -- complex coercion term).  We require that the extra_givens always
2297         -- have this form and exploit the special form when generating binders.
2298 reduceImplication env
2299         orig_implic@(ImplicInst { tci_name = name, tci_loc = inst_loc,
2300                                   tci_tyvars = tvs,
2301                                   tci_given = extra_givens, tci_wanted = wanteds
2302                                  })
2303   = do  {       -- Solve the sub-problem
2304         ; let try_me _ = ReduceMe  -- Note [Freeness and implications]
2305               env' = env { red_givens = extra_givens ++ red_givens env
2306                          , red_doc = sep [ptext (sLit "reduceImplication for") 
2307                                             <+> ppr name,
2308                                           nest 2 (parens $ ptext (sLit "within")
2309                                                            <+> red_doc env)]
2310                          , red_try_me = try_me }
2311
2312         ; traceTc (text "reduceImplication" <+> vcat
2313                         [ ppr (red_givens env), ppr extra_givens, 
2314                           ppr wanteds])
2315         ; (irreds, binds) <- checkLoop env' wanteds
2316
2317         ; traceTc (text "reduceImplication result" <+> vcat
2318                         [ppr irreds, ppr binds])
2319
2320         ; -- extract superclass binds
2321           --  (sc_binds,_) <- extractResults avails []
2322 --      ; traceTc (text "reduceImplication sc_binds" <+> vcat
2323 --                      [ppr sc_binds, ppr avails])
2324 --  
2325
2326         -- SLPJ Sept 07: what if improvement happened inside the checkLoop?
2327         -- Then we must iterate the outer loop too!
2328
2329         ; didntSolveWantedEqs <- allM wantedEqInstIsUnsolved wanteds
2330                                    -- we solve wanted eqs by side effect!
2331
2332             -- Progress is no longer measered by the number of bindings
2333             -- If there are any irreds, but no bindings and no solved
2334             -- equalities, we back off and do nothing
2335         ; let backOff = isEmptyLHsBinds binds &&   -- no new bindings
2336                         (not $ null irreds)   &&   -- but still some irreds
2337                         didntSolveWantedEqs        -- no instantiated cotv
2338
2339         ; if backOff then       -- No progress
2340                 return (emptyBag, [orig_implic])
2341           else do
2342         { (simpler_implic_insts, bind) 
2343             <- makeImplicationBind inst_loc tvs extra_givens irreds
2344                 -- This binding is useless if the recursive simplification
2345                 -- made no progress; but currently we don't try to optimise that
2346                 -- case.  After all, we only try hard to reduce at top level, or
2347                 -- when inferring types.
2348
2349         ; let   -- extract Id binders for dicts and CoTyVar binders for eqs;
2350                 -- see Note [Binders for equalities]
2351               (extra_eq_givens, extra_dict_givens) = partition isEqInst 
2352                                                                extra_givens
2353               eq_cotvs = map instToVar extra_eq_givens
2354               dict_ids = map instToId  extra_dict_givens 
2355
2356                         -- Note [Always inline implication constraints]
2357               wrap_inline | null dict_ids = idHsWrapper
2358                           | otherwise     = WpInline
2359               co         = wrap_inline
2360                            <.> mkWpTyLams tvs
2361                            <.> mkWpTyLams eq_cotvs
2362                            <.> mkWpLams dict_ids
2363                            <.> WpLet (binds `unionBags` bind)
2364               rhs        = mkLHsWrap co payload
2365               loc        = instLocSpan inst_loc
2366                              -- wanted equalities are solved by updating their
2367                              -- cotv; we don't generate bindings for them
2368               dict_bndrs =   map (L loc . HsVar . instToId) 
2369                            . filter (not . isEqInst) 
2370                            $ wanteds
2371               payload    = mkBigLHsTup dict_bndrs
2372
2373         
2374         ; traceTc (vcat [text "reduceImplication" <+> ppr name,
2375                          ppr simpler_implic_insts,
2376                          text "->" <+> ppr rhs])
2377         ; return (unitBag (L loc (VarBind (instToId orig_implic) rhs)),
2378                   simpler_implic_insts)
2379         } 
2380     }
2381 reduceImplication _ i = pprPanic "reduceImplication" (ppr i)
2382 \end{code}
2383
2384 Note [Always inline implication constraints]
2385 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2386 Suppose an implication constraint floats out of an INLINE function.
2387 Then although the implication has a single call site, it won't be 
2388 inlined.  And that is bad because it means that even if there is really
2389 *no* overloading (type signatures specify the exact types) there will
2390 still be dictionary passing in the resulting code.  To avert this,
2391 we mark the implication constraints themselves as INLINE, at least when
2392 there is no loss of sharing as a result.
2393
2394 Note [Freeness and implications]
2395 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2396 It's hard to say when an implication constraint can be floated out.  Consider
2397         forall {} Eq a => Foo [a]
2398 The (Foo [a]) doesn't mention any of the quantified variables, but it
2399 still might be partially satisfied by the (Eq a). 
2400
2401 There is a useful special case when it *is* easy to partition the 
2402 constraints, namely when there are no 'givens'.  Consider
2403         forall {a}. () => Bar b
2404 There are no 'givens', and so there is no reason to capture (Bar b).
2405 We can let it float out.  But if there is even one constraint we
2406 must be much more careful:
2407         forall {a}. C a b => Bar (m b)
2408 because (C a b) might have a superclass (D b), from which we might 
2409 deduce (Bar [b]) when m later gets instantiated to [].  Ha!
2410
2411 Here is an even more exotic example
2412         class C a => D a b
2413 Now consider the constraint
2414         forall b. D Int b => C Int
2415 We can satisfy the (C Int) from the superclass of D, so we don't want
2416 to float the (C Int) out, even though it mentions no type variable in
2417 the constraints!
2418
2419 One more example: the constraint
2420         class C a => D a b
2421         instance (C a, E c) => E (a,c)
2422
2423         constraint: forall b. D Int b => E (Int,c)
2424
2425 You might think that the (D Int b) can't possibly contribute
2426 to solving (E (Int,c)), since the latter mentions 'c'.  But 
2427 in fact it can, because solving the (E (Int,c)) constraint needs 
2428 dictionaries
2429         C Int, E c
2430 and the (C Int) can be satisfied from the superclass of (D Int b).
2431 So we must still not float (E (Int,c)) out.
2432
2433 To think about: special cases for unary type classes?
2434
2435 Note [Pruning the givens in an implication constraint]
2436 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2437 Suppose we are about to form the implication constraint
2438         forall tvs.  Eq a => Ord b
2439 The (Eq a) cannot contribute to the (Ord b), because it has no access to
2440 the type variable 'b'.  So we could filter out the (Eq a) from the givens.
2441 But BE CAREFUL of the examples above in [Freeness and implications].
2442
2443 Doing so would be a bit tidier, but all the implication constraints get
2444 simplified away by the optimiser, so it's no great win.   So I don't take
2445 advantage of that at the moment.
2446
2447 If you do, BE CAREFUL of wobbly type variables.
2448
2449
2450 %************************************************************************
2451 %*                                                                      *
2452                 Avails and AvailHow: the pool of evidence
2453 %*                                                                      *
2454 %************************************************************************
2455
2456
2457 \begin{code}
2458 data Avails = Avails !ImprovementDone !AvailEnv
2459
2460 type ImprovementDone = Bool     -- True <=> some unification has happened
2461                                 -- so some Irreds might now be reducible
2462                                 -- keys that are now 
2463
2464 type AvailEnv = FiniteMap Inst AvailHow
2465 data AvailHow
2466   = IsIrred             -- Used for irreducible dictionaries,
2467                         -- which are going to be lambda bound
2468
2469   | Given Inst          -- Used for dictionaries for which we have a binding
2470                         -- e.g. those "given" in a signature
2471
2472   | Rhs                 -- Used when there is a RHS
2473         (LHsExpr TcId)  -- The RHS
2474         [Inst]          -- Insts free in the RHS; we need these too
2475
2476 instance Outputable Avails where
2477   ppr = pprAvails
2478
2479 pprAvails :: Avails -> SDoc
2480 pprAvails (Avails imp avails)
2481   = vcat [ ptext (sLit "Avails") <> (if imp then ptext (sLit "[improved]") else empty)
2482          , nest 2 $ braces $ 
2483            vcat [ sep [ppr inst, nest 2 (equals <+> ppr avail)]
2484                 | (inst,avail) <- fmToList avails ]]
2485
2486 instance Outputable AvailHow where
2487     ppr = pprAvail
2488
2489 -------------------------
2490 pprAvail :: AvailHow -> SDoc
2491 pprAvail IsIrred        = text "Irred"
2492 pprAvail (Given x)      = text "Given" <+> ppr x
2493 pprAvail (Rhs rhs bs)   = sep [text "Rhs" <+> ppr bs,
2494                                nest 2 (ppr rhs)]
2495
2496 -------------------------
2497 extendAvailEnv :: AvailEnv -> Inst -> AvailHow -> AvailEnv
2498 extendAvailEnv env inst avail = addToFM env inst avail
2499
2500 findAvailEnv :: AvailEnv -> Inst -> Maybe AvailHow
2501 findAvailEnv env wanted = lookupFM env wanted
2502         -- NB 1: the Ord instance of Inst compares by the class/type info
2503         --  *not* by unique.  So
2504         --      d1::C Int ==  d2::C Int
2505
2506 emptyAvails :: Avails
2507 emptyAvails = Avails False emptyFM
2508
2509 findAvail :: Avails -> Inst -> Maybe AvailHow
2510 findAvail (Avails _ avails) wanted = findAvailEnv avails wanted
2511
2512 elemAvails :: Inst -> Avails -> Bool
2513 elemAvails wanted (Avails _ avails) = wanted `elemFM` avails
2514
2515 extendAvails :: Avails -> Inst -> AvailHow -> TcM Avails
2516 -- Does improvement
2517 extendAvails avails@(Avails imp env) inst avail
2518   = do  { imp1 <- tcImproveOne avails inst      -- Do any improvement
2519         ; return (Avails (imp || imp1) (extendAvailEnv env inst avail)) }
2520
2521 availsInsts :: Avails -> [Inst]
2522 availsInsts (Avails _ avails) = keysFM avails
2523
2524 availsImproved :: Avails -> ImprovementDone
2525 availsImproved (Avails imp _) = imp
2526 \end{code}
2527
2528 Extracting the bindings from a bunch of Avails.
2529 The bindings do *not* come back sorted in dependency order.
2530 We assume that they'll be wrapped in a big Rec, so that the
2531 dependency analyser can sort them out later
2532
2533 \begin{code}
2534 type DoneEnv = FiniteMap Inst [Id]
2535 -- Tracks which things we have evidence for
2536
2537 extractResults :: Avails
2538                -> [Inst]                -- Wanted
2539                -> TcM (TcDictBinds,     -- Bindings
2540                        [Inst],          -- The insts bound by the bindings
2541                        [Inst])          -- Irreducible ones
2542                         -- Note [Reducing implication constraints]
2543
2544 extractResults (Avails _ avails) wanteds
2545   = go emptyBag [] [] emptyFM wanteds
2546   where
2547     go  :: TcDictBinds  -- Bindings for dicts
2548         -> [Inst]       -- Bound by the bindings
2549         -> [Inst]       -- Irreds
2550         -> DoneEnv      -- Has an entry for each inst in the above three sets
2551         -> [Inst]       -- Wanted
2552         -> TcM (TcDictBinds, [Inst], [Inst])
2553     go binds bound_dicts irreds _ [] 
2554       = return (binds, bound_dicts, irreds)
2555
2556     go binds bound_dicts irreds done (w:ws)
2557       | isEqInst w
2558       = go binds bound_dicts (w:irreds) done' ws
2559
2560       | Just done_ids@(done_id : rest_done_ids) <- lookupFM done w
2561       = if w_id `elem` done_ids then
2562            go binds bound_dicts irreds done ws
2563         else
2564            go (add_bind (nlHsVar done_id)) bound_dicts irreds
2565               (addToFM done w (done_id : w_id : rest_done_ids)) ws
2566
2567       | otherwise       -- Not yet done
2568       = case findAvailEnv avails w of
2569           Nothing -> pprTrace "Urk: extractResults" (ppr w) $
2570                      go binds bound_dicts irreds done ws
2571
2572           Just IsIrred -> go binds bound_dicts (w:irreds) done' ws
2573
2574           Just (Rhs rhs ws') -> go (add_bind rhs) (w:bound_dicts) irreds done' (ws' ++ ws)
2575
2576           Just (Given g) -> go binds' bound_dicts irreds (addToFM done w [g_id]) ws 
2577                 where
2578                   g_id = instToId g
2579                   binds' | w_id == g_id = binds
2580                          | otherwise    = add_bind (nlHsVar g_id)
2581       where
2582         w_id  = instToId w      
2583         done' = addToFM done w [w_id]
2584         add_bind rhs = addInstToDictBind binds w rhs
2585 \end{code}
2586
2587
2588 Note [No superclasses for Stop]
2589 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2590 When we decide not to reduce an Inst -- the 'WhatToDo' --- we still
2591 add it to avails, so that any other equal Insts will be commoned up
2592 right here.  However, we do *not* add superclasses.  If we have
2593         df::Floating a
2594         dn::Num a
2595 but a is not bound here, then we *don't* want to derive dn from df
2596 here lest we lose sharing.
2597
2598 \begin{code}
2599 addWanted :: WantSCs -> Avails -> Inst -> LHsExpr TcId -> [Inst] -> TcM Avails
2600 addWanted want_scs avails wanted rhs_expr wanteds
2601   = addAvailAndSCs want_scs avails wanted avail
2602   where
2603     avail = Rhs rhs_expr wanteds
2604
2605 addGiven :: (Inst -> WantSCs) -> Avails -> Inst -> TcM Avails
2606 addGiven want_scs avails given = addAvailAndSCs (want_scs given) avails given (Given given)
2607         -- Conditionally add superclasses for 'givens'
2608         -- See Note [Recursive instances and superclases]
2609         --
2610         -- No ASSERT( not (given `elemAvails` avails) ) because in an instance
2611         -- decl for Ord t we can add both Ord t and Eq t as 'givens', 
2612         -- so the assert isn't true
2613 \end{code}
2614
2615 \begin{code}
2616 addIrred :: WantSCs -> Avails -> Inst -> TcM Avails
2617 addIrred want_scs avails irred = ASSERT2( not (irred `elemAvails` avails), ppr irred $$ ppr avails )
2618                                  addAvailAndSCs want_scs avails irred IsIrred
2619
2620 addAvailAndSCs :: WantSCs -> Avails -> Inst -> AvailHow -> TcM Avails
2621 addAvailAndSCs want_scs avails inst avail
2622   | not (isClassDict inst) = extendAvails avails inst avail
2623   | NoSCs <- want_scs      = extendAvails avails inst avail
2624   | otherwise              = do { traceTc (text "addAvailAndSCs" <+> vcat [ppr inst, ppr deps])
2625                                 ; avails' <- extendAvails avails inst avail
2626                                 ; addSCs is_loop avails' inst }
2627   where
2628     is_loop pred = any (`tcEqType` mkPredTy pred) dep_tys
2629                         -- Note: this compares by *type*, not by Unique
2630     deps         = findAllDeps (unitVarSet (instToVar inst)) avail
2631     dep_tys      = map idType (varSetElems deps)
2632
2633     findAllDeps :: IdSet -> AvailHow -> IdSet
2634     -- Find all the Insts that this one depends on
2635     -- See Note [SUPERCLASS-LOOP 2]
2636     -- Watch out, though.  Since the avails may contain loops 
2637     -- (see Note [RECURSIVE DICTIONARIES]), so we need to track the ones we've seen so far
2638     findAllDeps so_far (Rhs _ kids) = foldl find_all so_far kids
2639     findAllDeps so_far _            = so_far
2640
2641     find_all :: IdSet -> Inst -> IdSet
2642     find_all so_far kid
2643       | isEqInst kid                       = so_far
2644       | kid_id `elemVarSet` so_far         = so_far
2645       | Just avail <- findAvail avails kid = findAllDeps so_far' avail
2646       | otherwise                          = so_far'
2647       where
2648         so_far' = extendVarSet so_far kid_id    -- Add the new kid to so_far
2649         kid_id = instToId kid
2650
2651 addSCs :: (TcPredType -> Bool) -> Avails -> Inst -> TcM Avails
2652         -- Add all the superclasses of the Inst to Avails
2653         -- The first param says "don't do this because the original thing
2654         --      depends on this one, so you'd build a loop"
2655         -- Invariant: the Inst is already in Avails.
2656
2657 addSCs is_loop avails dict
2658   = ASSERT( isDict dict )
2659     do  { sc_dicts <- newDictBndrs (instLoc dict) sc_theta'
2660         ; foldlM add_sc avails (zipEqual "add_scs" sc_dicts sc_sels) }
2661   where
2662     (clas, tys) = getDictClassTys dict
2663     (tyvars, sc_theta, sc_sels, _) = classBigSig clas
2664     sc_theta' = filter (not . isEqPred) $
2665                   substTheta (zipTopTvSubst tyvars tys) sc_theta
2666
2667     add_sc avails (sc_dict, sc_sel)
2668       | is_loop (dictPred sc_dict) = return avails      -- See Note [SUPERCLASS-LOOP 2]
2669       | is_given sc_dict           = return avails
2670       | otherwise                  = do { avails' <- extendAvails avails sc_dict (Rhs sc_sel_rhs [dict])
2671                                         ; addSCs is_loop avails' sc_dict }
2672       where
2673         sc_sel_rhs = L (instSpan dict) (HsWrap co_fn (HsVar sc_sel))
2674         co_fn      = WpApp (instToVar dict) <.> mkWpTyApps tys
2675
2676     is_given :: Inst -> Bool
2677     is_given sc_dict = case findAvail avails sc_dict of
2678                           Just (Given _) -> True        -- Given is cheaper than superclass selection
2679                           _              -> False
2680
2681 -- From the a set of insts obtain all equalities that (transitively) occur in
2682 -- superclass contexts of class constraints (aka the ancestor equalities). 
2683 --
2684 ancestorEqualities :: [Inst] -> TcM [Inst]
2685 ancestorEqualities
2686   =   mapM mkWantedEqInst               -- turn only equality predicates..
2687     . filter isEqPred                   -- ..into wanted equality insts
2688     . bagToList 
2689     . addAEsToBag emptyBag              -- collect the superclass constraints..
2690     . map dictPred                      -- ..of all predicates in a bag
2691     . filter isClassDict
2692   where
2693     addAEsToBag :: Bag PredType -> [PredType] -> Bag PredType
2694     addAEsToBag bag []           = bag
2695     addAEsToBag bag (pred:preds)
2696       | pred `elemBag` bag = addAEsToBag bag         preds
2697       | isEqPred pred      = addAEsToBag bagWithPred preds
2698       | isClassPred pred   = addAEsToBag bagWithPred predsWithSCs
2699       | otherwise          = addAEsToBag bag         preds
2700       where
2701         bagWithPred  = bag `snocBag` pred
2702         predsWithSCs = preds ++ substTheta (zipTopTvSubst tyvars tys) sc_theta
2703         --
2704         (tyvars, sc_theta, _, _) = classBigSig clas
2705         (clas, tys)              = getClassPredTys pred 
2706 \end{code}
2707
2708
2709 %************************************************************************
2710 %*                                                                      *
2711 \section{tcSimplifyTop: defaulting}
2712 %*                                                                      *
2713 %************************************************************************
2714
2715
2716 @tcSimplifyTop@ is called once per module to simplify all the constant
2717 and ambiguous Insts.
2718
2719 We need to be careful of one case.  Suppose we have
2720
2721         instance Num a => Num (Foo a b) where ...
2722
2723 and @tcSimplifyTop@ is given a constraint (Num (Foo x y)).  Then it'll simplify
2724 to (Num x), and default x to Int.  But what about y??
2725
2726 It's OK: the final zonking stage should zap y to (), which is fine.
2727
2728
2729 \begin{code}
2730 tcSimplifyTop, tcSimplifyInteractive :: [Inst] -> TcM TcDictBinds
2731 tcSimplifyTop wanteds
2732   = tc_simplify_top doc False wanteds
2733   where 
2734     doc = text "tcSimplifyTop"
2735
2736 tcSimplifyInteractive wanteds
2737   = tc_simplify_top doc True wanteds
2738   where 
2739     doc = text "tcSimplifyInteractive"
2740
2741 -- The TcLclEnv should be valid here, solely to improve
2742 -- error message generation for the monomorphism restriction
2743 tc_simplify_top :: SDoc -> Bool -> [Inst] -> TcM (Bag (LHsBind TcId))
2744 tc_simplify_top doc interactive wanteds
2745   = do  { dflags <- getDOpts
2746         ; wanteds <- zonkInsts wanteds
2747         ; mapM_ zonkTopTyVar (varSetElems (tyVarsOfInsts wanteds))
2748
2749         ; traceTc (text "tc_simplify_top 0: " <+> ppr wanteds)
2750         ; (irreds1, binds1) <- tryHardCheckLoop doc1 wanteds
2751 --      ; (irreds1, binds1) <- gentleInferLoop doc1 wanteds
2752         ; traceTc (text "tc_simplify_top 1: " <+> ppr irreds1)
2753         ; (irreds2, binds2) <- approximateImplications doc2 (\_ -> True) irreds1
2754         ; traceTc (text "tc_simplify_top 2: " <+> ppr irreds2)
2755
2756                 -- Use the defaulting rules to do extra unification
2757                 -- NB: irreds2 are already zonked
2758         ; (irreds3, binds3) <- disambiguate doc3 interactive dflags irreds2
2759
2760                 -- Deal with implicit parameters
2761         ; let (bad_ips, non_ips) = partition isIPDict irreds3
2762               (ambigs, others)   = partition isTyVarDict non_ips
2763
2764         ; topIPErrs bad_ips     -- Can arise from   f :: Int -> Int
2765                                 --                  f x = x + ?y
2766         ; addNoInstanceErrs others
2767         ; addTopAmbigErrs ambigs        
2768
2769         ; return (binds1 `unionBags` binds2 `unionBags` binds3) }
2770   where
2771     doc1 = doc <+> ptext (sLit "(first round)")
2772     doc2 = doc <+> ptext (sLit "(approximate)")
2773     doc3 = doc <+> ptext (sLit "(disambiguate)")
2774 \end{code}
2775
2776 If a dictionary constrains a type variable which is
2777         * not mentioned in the environment
2778         * and not mentioned in the type of the expression
2779 then it is ambiguous. No further information will arise to instantiate
2780 the type variable; nor will it be generalised and turned into an extra
2781 parameter to a function.
2782
2783 It is an error for this to occur, except that Haskell provided for
2784 certain rules to be applied in the special case of numeric types.
2785 Specifically, if
2786         * at least one of its classes is a numeric class, and
2787         * all of its classes are numeric or standard
2788 then the type variable can be defaulted to the first type in the
2789 default-type list which is an instance of all the offending classes.
2790
2791 So here is the function which does the work.  It takes the ambiguous
2792 dictionaries and either resolves them (producing bindings) or
2793 complains.  It works by splitting the dictionary list by type
2794 variable, and using @disambigOne@ to do the real business.
2795
2796 @disambigOne@ assumes that its arguments dictionaries constrain all
2797 the same type variable.
2798
2799 ADR Comment 20/6/94: I've changed the @CReturnable@ case to default to
2800 @()@ instead of @Int@.  I reckon this is the Right Thing to do since
2801 the most common use of defaulting is code like:
2802 \begin{verbatim}
2803         _ccall_ foo     `seqPrimIO` bar
2804 \end{verbatim}
2805 Since we're not using the result of @foo@, the result if (presumably)
2806 @void@.
2807
2808 \begin{code}
2809 disambiguate :: SDoc -> Bool -> DynFlags -> [Inst] -> TcM ([Inst], TcDictBinds)
2810         -- Just does unification to fix the default types
2811         -- The Insts are assumed to be pre-zonked
2812 disambiguate doc interactive dflags insts
2813   | null insts
2814   = return (insts, emptyBag)
2815
2816   | null defaultable_groups
2817   = do  { traceTc (text "disambigutate, no defaultable groups" <+> vcat [ppr unaries, ppr insts, ppr bad_tvs, ppr defaultable_groups])
2818         ; return (insts, emptyBag) }
2819
2820   | otherwise
2821   = do  {       -- Figure out what default types to use
2822           default_tys <- getDefaultTys extended_defaulting ovl_strings
2823
2824         ; traceTc (text "disambiguate1" <+> vcat [ppr insts, ppr unaries, ppr bad_tvs, ppr defaultable_groups])
2825         ; mapM_ (disambigGroup default_tys) defaultable_groups
2826
2827         -- disambigGroup does unification, hence try again
2828         ; tryHardCheckLoop doc insts }
2829
2830   where
2831    extended_defaulting = interactive || dopt Opt_ExtendedDefaultRules dflags
2832    ovl_strings = dopt Opt_OverloadedStrings dflags
2833
2834    unaries :: [(Inst, Class, TcTyVar)]  -- (C tv) constraints
2835    bad_tvs :: TcTyVarSet  -- Tyvars mentioned by *other* constraints
2836    (unaries, bad_tvs_s) = partitionWith find_unary insts 
2837    bad_tvs              = unionVarSets bad_tvs_s
2838
2839         -- Finds unary type-class constraints
2840    find_unary d@(Dict {tci_pred = ClassP cls [ty]})
2841         | Just tv <- tcGetTyVar_maybe ty = Left (d,cls,tv)
2842    find_unary inst                       = Right (tyVarsOfInst inst)
2843
2844                 -- Group by type variable
2845    defaultable_groups :: [[(Inst,Class,TcTyVar)]]
2846    defaultable_groups = filter defaultable_group (equivClasses cmp_tv unaries)
2847    cmp_tv (_,_,tv1) (_,_,tv2) = tv1 `compare` tv2
2848
2849    defaultable_group :: [(Inst,Class,TcTyVar)] -> Bool
2850    defaultable_group ds@((_,_,tv):_)
2851         =  isTyConableTyVar tv  -- Note [Avoiding spurious errors]
2852         && not (tv `elemVarSet` bad_tvs)
2853         && defaultable_classes [c | (_,c,_) <- ds]
2854    defaultable_group [] = panic "defaultable_group"
2855
2856    defaultable_classes clss 
2857         | extended_defaulting = any isInteractiveClass clss
2858         | otherwise           = all is_std_class clss && (any is_num_class clss)
2859
2860         -- In interactive mode, or with -XExtendedDefaultRules,
2861         -- we default Show a to Show () to avoid graututious errors on "show []"
2862    isInteractiveClass cls 
2863         = is_num_class cls || (classKey cls `elem` [showClassKey, eqClassKey, ordClassKey])
2864
2865    is_num_class cls = isNumericClass cls || (ovl_strings && (cls `hasKey` isStringClassKey))
2866         -- is_num_class adds IsString to the standard numeric classes, 
2867         -- when -foverloaded-strings is enabled
2868
2869    is_std_class cls = isStandardClass cls || (ovl_strings && (cls `hasKey` isStringClassKey))
2870         -- Similarly is_std_class
2871
2872 -----------------------
2873 disambigGroup :: [Type]                 -- The default types
2874               -> [(Inst,Class,TcTyVar)] -- All standard classes of form (C a)
2875               -> TcM () -- Just does unification, to fix the default types
2876
2877 disambigGroup default_tys dicts
2878   = try_default default_tys
2879   where
2880     (_,_,tyvar) = ASSERT(not (null dicts)) head dicts   -- Should be non-empty
2881     classes = [c | (_,c,_) <- dicts]
2882
2883     try_default [] = return ()
2884     try_default (default_ty : default_tys)
2885       = tryTcLIE_ (try_default default_tys) $
2886         do { tcSimplifyDefault [mkClassPred clas [default_ty] | clas <- classes]
2887                 -- This may fail; then the tryTcLIE_ kicks in
2888                 -- Failure here is caused by there being no type in the
2889                 -- default list which can satisfy all the ambiguous classes.
2890                 -- For example, if Real a is reqd, but the only type in the
2891                 -- default list is Int.
2892
2893                 -- After this we can't fail
2894            ; warnDefault dicts default_ty
2895            ; unifyType default_ty (mkTyVarTy tyvar) 
2896            ; return () -- TOMDO: do something with the coercion
2897            }
2898
2899
2900 -----------------------
2901 getDefaultTys :: Bool -> Bool -> TcM [Type]
2902 getDefaultTys extended_deflts ovl_strings
2903   = do  { mb_defaults <- getDeclaredDefaultTys
2904         ; case mb_defaults of {
2905            Just tys -> return tys ;     -- User-supplied defaults
2906            Nothing  -> do
2907
2908         -- No use-supplied default
2909         -- Use [Integer, Double], plus modifications
2910         { integer_ty <- tcMetaTy integerTyConName
2911         ; checkWiredInTyCon doubleTyCon
2912         ; string_ty <- tcMetaTy stringTyConName
2913         ; return (opt_deflt extended_deflts unitTy
2914                         -- Note [Default unitTy]
2915                         ++
2916                   [integer_ty,doubleTy]
2917                         ++
2918                   opt_deflt ovl_strings string_ty) } } }
2919   where
2920     opt_deflt True  ty = [ty]
2921     opt_deflt False _  = []
2922 \end{code}
2923
2924 Note [Default unitTy]
2925 ~~~~~~~~~~~~~~~~~~~~~
2926 In interative mode (or with -XExtendedDefaultRules) we add () as the first type we
2927 try when defaulting.  This has very little real impact, except in the following case.
2928 Consider: 
2929         Text.Printf.printf "hello"
2930 This has type (forall a. IO a); it prints "hello", and returns 'undefined'.  We don't
2931 want the GHCi repl loop to try to print that 'undefined'.  The neatest thing is to
2932 default the 'a' to (), rather than to Integer (which is what would otherwise happen;
2933 and then GHCi doesn't attempt to print the ().  So in interactive mode, we add
2934 () to the list of defaulting types.  See Trac #1200.
2935
2936 Note [Avoiding spurious errors]
2937 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2938 When doing the unification for defaulting, we check for skolem
2939 type variables, and simply don't default them.  For example:
2940    f = (*)      -- Monomorphic
2941    g :: Num a => a -> a
2942    g x = f x x
2943 Here, we get a complaint when checking the type signature for g,
2944 that g isn't polymorphic enough; but then we get another one when
2945 dealing with the (Num a) context arising from f's definition;
2946 we try to unify a with Int (to default it), but find that it's
2947 already been unified with the rigid variable from g's type sig
2948
2949
2950 %************************************************************************
2951 %*                                                                      *
2952 \subsection[simple]{@Simple@ versions}
2953 %*                                                                      *
2954 %************************************************************************
2955
2956 Much simpler versions when there are no bindings to make!
2957
2958 @tcSimplifyThetas@ simplifies class-type constraints formed by
2959 @deriving@ declarations and when specialising instances.  We are
2960 only interested in the simplified bunch of class/type constraints.
2961
2962 It simplifies to constraints of the form (C a b c) where
2963 a,b,c are type variables.  This is required for the context of
2964 instance declarations.
2965
2966 \begin{code}
2967 tcSimplifyDeriv :: InstOrigin
2968                 -> [TyVar]      
2969                 -> ThetaType            -- Wanted
2970                 -> TcM ThetaType        -- Needed
2971 -- Given  instance (wanted) => C inst_ty 
2972 -- Simplify 'wanted' as much as possible
2973
2974 tcSimplifyDeriv orig tyvars theta
2975   = do  { (tvs, _, tenv) <- tcInstTyVars tyvars
2976         -- The main loop may do unification, and that may crash if 
2977         -- it doesn't see a TcTyVar, so we have to instantiate. Sigh
2978         -- ToDo: what if two of them do get unified?
2979         ; wanteds <- newDictBndrsO orig (substTheta tenv theta)
2980         ; (irreds, _) <- tryHardCheckLoop doc wanteds
2981
2982         ; let (tv_dicts, others) = partition ok irreds
2983         ; addNoInstanceErrs others
2984         -- See Note [Exotic derived instance contexts] in TcMType
2985
2986         ; let rev_env = zipTopTvSubst tvs (mkTyVarTys tyvars)
2987               simpl_theta = substTheta rev_env (map dictPred tv_dicts)
2988                 -- This reverse-mapping is a pain, but the result
2989                 -- should mention the original TyVars not TcTyVars
2990
2991         ; return simpl_theta }
2992   where
2993     doc = ptext (sLit "deriving classes for a data type")
2994
2995     ok dict | isDict dict = validDerivPred (dictPred dict)
2996             | otherwise   = False
2997 \end{code}
2998
2999
3000 @tcSimplifyDefault@ just checks class-type constraints, essentially;
3001 used with \tr{default} declarations.  We are only interested in
3002 whether it worked or not.
3003
3004 \begin{code}
3005 tcSimplifyDefault :: ThetaType  -- Wanted; has no type variables in it
3006                   -> TcM ()
3007
3008 tcSimplifyDefault theta = do
3009     wanteds <- newDictBndrsO DefaultOrigin theta
3010     (irreds, _) <- tryHardCheckLoop doc wanteds
3011     addNoInstanceErrs  irreds
3012     if null irreds then
3013         return ()
3014      else
3015         traceTc (ptext (sLit "tcSimplifyDefault failing")) >> failM
3016   where
3017     doc = ptext (sLit "default declaration")
3018 \end{code}
3019
3020 @tcSimplifyStagedExpr@ performs a simplification but does so at a new
3021 stage. This is used when typechecking annotations and splices.
3022
3023 \begin{code}
3024
3025 tcSimplifyStagedExpr :: ThStage -> TcM a -> TcM (a, TcDictBinds)
3026 -- Type check an expression that runs at a top level stage as if
3027 --   it were going to be spliced and then simplify it
3028 tcSimplifyStagedExpr stage tc_action
3029   = setStage stage $ do { 
3030         -- Typecheck the expression
3031           (thing', lie) <- getLIE tc_action
3032         
3033         -- Solve the constraints
3034         ; const_binds <- tcSimplifyTop lie
3035         
3036         ; return (thing', const_binds) }
3037
3038 \end{code}
3039
3040
3041 %************************************************************************
3042 %*                                                                      *
3043 \section{Errors and contexts}
3044 %*                                                                      *
3045 %************************************************************************
3046
3047 ToDo: for these error messages, should we note the location as coming
3048 from the insts, or just whatever seems to be around in the monad just
3049 now?
3050
3051 \begin{code}
3052 groupErrs :: ([Inst] -> TcM ()) -- Deal with one group
3053           -> [Inst]             -- The offending Insts
3054           -> TcM ()
3055 -- Group together insts with the same origin
3056 -- We want to report them together in error messages
3057
3058 groupErrs _ [] 
3059   = return ()
3060 groupErrs report_err (inst:insts)
3061   = do  { do_one (inst:friends)
3062         ; groupErrs report_err others }
3063   where
3064         -- (It may seem a bit crude to compare the error messages,
3065         --  but it makes sure that we combine just what the user sees,
3066         --  and it avoids need equality on InstLocs.)
3067    (friends, others) = partition is_friend insts
3068    loc_msg           = showSDoc (pprInstLoc (instLoc inst))
3069    is_friend friend  = showSDoc (pprInstLoc (instLoc friend)) == loc_msg
3070    do_one insts = addInstCtxt (instLoc (head insts)) (report_err insts)
3071                 -- Add location and context information derived from the Insts
3072
3073 -- Add the "arising from..." part to a message about bunch of dicts
3074 addInstLoc :: [Inst] -> Message -> Message
3075 addInstLoc insts msg = msg $$ nest 2 (pprInstArising (head insts))
3076
3077 addTopIPErrs :: [Name] -> [Inst] -> TcM ()
3078 addTopIPErrs _ [] 
3079   = return ()
3080 addTopIPErrs bndrs ips
3081   = do  { dflags <- getDOpts
3082         ; addErrTcM (tidy_env, mk_msg dflags tidy_ips) }
3083   where
3084     (tidy_env, tidy_ips) = tidyInsts ips
3085     mk_msg dflags ips 
3086         = vcat [sep [ptext (sLit "Implicit parameters escape from"),
3087                 nest 2 (ptext (sLit "the monomorphic top-level binding") 
3088                                             <> plural bndrs <+> ptext (sLit "of")
3089                                             <+> pprBinders bndrs <> colon)],
3090                 nest 2 (vcat (map ppr_ip ips)),
3091                 monomorphism_fix dflags]
3092     ppr_ip ip = pprPred (dictPred ip) <+> pprInstArising ip
3093
3094 topIPErrs :: [Inst] -> TcM ()
3095 topIPErrs dicts
3096   = groupErrs report tidy_dicts
3097   where
3098     (tidy_env, tidy_dicts) = tidyInsts dicts
3099     report dicts = addErrTcM (tidy_env, mk_msg dicts)
3100     mk_msg dicts = addInstLoc dicts (ptext (sLit "Unbound implicit parameter") <> 
3101                                      plural tidy_dicts <+> pprDictsTheta tidy_dicts)
3102
3103 addNoInstanceErrs :: [Inst]     -- Wanted (can include implications)
3104                   -> TcM ()     
3105 addNoInstanceErrs insts
3106   = do  { let (tidy_env, tidy_insts) = tidyInsts insts
3107         ; reportNoInstances tidy_env Nothing tidy_insts }
3108
3109 reportNoInstances 
3110         :: TidyEnv
3111         -> Maybe (InstLoc, [Inst])      -- Context
3112                         -- Nothing => top level
3113                         -- Just (d,g) => d describes the construct
3114                         --               with givens g
3115         -> [Inst]       -- What is wanted (can include implications)
3116         -> TcM ()       
3117
3118 reportNoInstances tidy_env mb_what insts 
3119   = groupErrs (report_no_instances tidy_env mb_what) insts
3120
3121 report_no_instances :: TidyEnv -> Maybe (InstLoc, [Inst]) -> [Inst] -> TcM ()
3122 report_no_instances tidy_env mb_what insts
3123   = do { inst_envs <- tcGetInstEnvs
3124        ; let (implics, insts1)  = partition isImplicInst insts
3125              (insts2, overlaps) = partitionWith (check_overlap inst_envs) insts1
3126              (eqInsts, insts3)  = partition isEqInst insts2
3127        ; traceTc (text "reportNoInstances" <+> vcat 
3128                        [ppr insts, ppr implics, ppr insts1, ppr insts2])
3129        ; mapM_ complain_implic implics
3130        ; mapM_ (\doc -> addErrTcM (tidy_env, doc)) overlaps
3131        ; groupErrs complain_no_inst insts3 
3132        ; mapM_ (addErrTcM . mk_eq_err) eqInsts
3133        }
3134   where
3135     complain_no_inst insts = addErrTcM (tidy_env, mk_no_inst_err insts)
3136
3137     complain_implic inst        -- Recurse!
3138       = reportNoInstances tidy_env 
3139                           (Just (tci_loc inst, tci_given inst)) 
3140                           (tci_wanted inst)
3141
3142     check_overlap :: (InstEnv,InstEnv) -> Inst -> Either Inst SDoc
3143         -- Right msg  => overlap message
3144         -- Left  inst => no instance
3145     check_overlap inst_envs wanted
3146         | not (isClassDict wanted) = Left wanted
3147         | otherwise
3148         = case lookupInstEnv inst_envs clas tys of
3149                 ([], _) -> Left wanted          -- No match
3150                 -- The case of exactly one match and no unifiers means a
3151                 -- successful lookup.  That can't happen here, because dicts
3152                 -- only end up here if they didn't match in Inst.lookupInst
3153                 ([_],[])
3154                  | debugIsOn -> pprPanic "reportNoInstance" (ppr wanted)
3155                 res -> Right (mk_overlap_msg wanted res)
3156           where
3157             (clas,tys) = getDictClassTys wanted
3158
3159     mk_overlap_msg dict (matches, unifiers)
3160       = ASSERT( not (null matches) )
3161         vcat [  addInstLoc [dict] ((ptext (sLit "Overlapping instances for") 
3162                                         <+> pprPred (dictPred dict))),
3163                 sep [ptext (sLit "Matching instances") <> colon,
3164                      nest 2 (vcat [pprInstances ispecs, pprInstances unifiers])],
3165                 if not (isSingleton matches)
3166                 then    -- Two or more matches
3167                      empty
3168                 else    -- One match, plus some unifiers
3169                 ASSERT( not (null unifiers) )
3170                 parens (vcat [ptext (sLit "The choice depends on the instantiation of") <+>
3171                                  quotes (pprWithCommas ppr (varSetElems (tyVarsOfInst dict))),
3172                               ptext (sLit "To pick the first instance above, use -XIncoherentInstances"),
3173                               ptext (sLit "when compiling the other instance declarations")])]
3174       where
3175         ispecs = [ispec | (ispec, _) <- matches]
3176
3177     mk_eq_err :: Inst -> (TidyEnv, SDoc)
3178     mk_eq_err inst = misMatchMsg tidy_env (eqInstTys inst)
3179
3180     mk_no_inst_err insts
3181       | null insts = empty
3182
3183       | Just (loc, givens) <- mb_what,   -- Nested (type signatures, instance decls)
3184         not (isEmptyVarSet (tyVarsOfInsts insts))
3185       = vcat [ addInstLoc insts $
3186                sep [ ptext (sLit "Could not deduce") <+> pprDictsTheta insts
3187                    , nest 2 $ ptext (sLit "from the context") <+> pprDictsTheta givens]
3188              , show_fixes (fix1 loc : fixes2) ]
3189
3190       | otherwise       -- Top level 
3191       = vcat [ addInstLoc insts $
3192                ptext (sLit "No instance") <> plural insts
3193                     <+> ptext (sLit "for") <+> pprDictsTheta insts
3194              , show_fixes fixes2 ]
3195
3196       where
3197         fix1 loc = sep [ ptext (sLit "add") <+> pprDictsTheta insts
3198                                  <+> ptext (sLit "to the context of"),
3199                          nest 2 (ppr (instLocOrigin loc)) ]
3200                          -- I'm not sure it helps to add the location
3201                          -- nest 2 (ptext (sLit "at") <+> ppr (instLocSpan loc)) ]
3202
3203         fixes2 | null instance_dicts = []
3204                | otherwise           = [sep [ptext (sLit "add an instance declaration for"),
3205                                         pprDictsTheta instance_dicts]]
3206         instance_dicts = [d | d <- insts, isClassDict d, not (isTyVarDict d)]
3207                 -- Insts for which it is worth suggesting an adding an instance declaration
3208                 -- Exclude implicit parameters, and tyvar dicts
3209
3210         show_fixes :: [SDoc] -> SDoc
3211         show_fixes []     = empty
3212         show_fixes (f:fs) = sep [ptext (sLit "Possible fix:"), 
3213                                  nest 2 (vcat (f : map (ptext (sLit "or") <+>) fs))]
3214
3215 addTopAmbigErrs :: [Inst] -> TcRn ()
3216 addTopAmbigErrs dicts
3217 -- Divide into groups that share a common set of ambiguous tyvars
3218   = ifErrsM (return ()) $       -- Only report ambiguity if no other errors happened
3219                                 -- See Note [Avoiding spurious errors]
3220     mapM_ report (equivClasses cmp [(d, tvs_of d) | d <- tidy_dicts])
3221   where
3222     (tidy_env, tidy_dicts) = tidyInsts dicts
3223
3224     tvs_of :: Inst -> [TcTyVar]
3225     tvs_of d = varSetElems (tyVarsOfInst d)
3226     cmp (_,tvs1) (_,tvs2) = tvs1 `compare` tvs2
3227     
3228     report :: [(Inst,[TcTyVar])] -> TcM ()
3229     report pairs@((inst,tvs) : _) = do  -- The pairs share a common set of ambiguous tyvars
3230           (tidy_env, mono_msg) <- mkMonomorphismMsg tidy_env tvs
3231           setSrcSpan (instSpan inst) $
3232                 -- the location of the first one will do for the err message
3233            addErrTcM (tidy_env, msg $$ mono_msg)
3234         where
3235           dicts = map fst pairs
3236           msg = sep [text "Ambiguous type variable" <> plural tvs <+> 
3237                           pprQuotedList tvs <+> in_msg,
3238                      nest 2 (pprDictsInFull dicts)]
3239           in_msg = text "in the constraint" <> plural dicts <> colon
3240     report [] = panic "addTopAmbigErrs"
3241
3242
3243 mkMonomorphismMsg :: TidyEnv -> [TcTyVar] -> TcM (TidyEnv, Message)
3244 -- There's an error with these Insts; if they have free type variables
3245 -- it's probably caused by the monomorphism restriction. 
3246 -- Try to identify the offending variable
3247 -- ASSUMPTION: the Insts are fully zonked
3248 mkMonomorphismMsg tidy_env inst_tvs
3249   = do  { dflags <- getDOpts
3250         ; (tidy_env, docs) <- findGlobals (mkVarSet inst_tvs) tidy_env
3251         ; return (tidy_env, mk_msg dflags docs) }
3252   where
3253     mk_msg _ _ | any isRuntimeUnk inst_tvs
3254         =  vcat [ptext (sLit "Cannot resolve unknown runtime types:") <+>
3255                    (pprWithCommas ppr inst_tvs),
3256                 ptext (sLit "Use :print or :force to determine these types")]
3257     mk_msg _ []   = ptext (sLit "Probable fix: add a type signature that fixes these type variable(s)")
3258                         -- This happens in things like
3259                         --      f x = show (read "foo")
3260                         -- where monomorphism doesn't play any role
3261     mk_msg dflags docs 
3262         = vcat [ptext (sLit "Possible cause: the monomorphism restriction applied to the following:"),
3263                 nest 2 (vcat docs),
3264                 monomorphism_fix dflags]
3265
3266 monomorphism_fix :: DynFlags -> SDoc
3267 monomorphism_fix dflags
3268   = ptext (sLit "Probable fix:") <+> vcat
3269         [ptext (sLit "give these definition(s) an explicit type signature"),
3270          if dopt Opt_MonomorphismRestriction dflags
3271            then ptext (sLit "or use -XNoMonomorphismRestriction")
3272            else empty]  -- Only suggest adding "-XNoMonomorphismRestriction"
3273                         -- if it is not already set!
3274     
3275 warnDefault :: [(Inst, Class, Var)] -> Type -> TcM ()
3276 warnDefault ups default_ty = do
3277     warn_flag <- doptM Opt_WarnTypeDefaults
3278     addInstCtxt (instLoc (head (dicts))) (warnTc warn_flag warn_msg)
3279   where
3280     dicts = [d | (d,_,_) <- ups]
3281
3282         -- Tidy them first
3283     (_, tidy_dicts) = tidyInsts dicts
3284     warn_msg  = vcat [ptext (sLit "Defaulting the following constraint(s) to type") <+>
3285                                 quotes (ppr default_ty),
3286                       pprDictsInFull tidy_dicts]
3287
3288 reduceDepthErr :: Int -> [Inst] -> SDoc
3289 reduceDepthErr n stack
3290   = vcat [ptext (sLit "Context reduction stack overflow; size =") <+> int n,
3291           ptext (sLit "Use -fcontext-stack=N to increase stack size to N"),
3292           nest 4 (pprStack stack)]
3293
3294 pprStack :: [Inst] -> SDoc
3295 pprStack stack = vcat (map pprInstInFull stack)
3296 \end{code}