[project @ 2001-05-03 12:33:50 by simonpj]
[ghc-hetmet.git] / ghc / compiler / typecheck / TcSimplify.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[TcSimplify]{TcSimplify}
5
6
7
8 \begin{code}
9 module TcSimplify (
10         tcSimplifyInfer, tcSimplifyInferCheck, tcSimplifyCheck,
11         tcSimplifyRestricted,
12         tcSimplifyToDicts, tcSimplifyIPs, tcSimplifyTop, 
13
14         tcSimplifyThetas, tcSimplifyCheckThetas,
15         bindInstsOfLocalFuns
16     ) where
17
18 #include "HsVersions.h"
19
20 import HsSyn            ( MonoBinds(..), HsExpr(..), andMonoBinds, andMonoBindList )
21 import TcHsSyn          ( TcExpr, TcId, 
22                           TcMonoBinds, TcDictBinds
23                         )
24
25 import TcMonad
26 import Inst             ( lookupInst, lookupSimpleInst, LookupInstResult(..),
27                           tyVarsOfInst, predsOfInsts, predsOfInst,
28                           isDict, isClassDict, instName,
29                           isStdClassTyVarDict, isMethodFor,
30                           instToId, tyVarsOfInsts,
31                           instBindingRequired, instCanBeGeneralised,
32                           newDictsFromOld, instMentionsIPs,
33                           getDictClassTys, isTyVarDict,
34                           instLoc, pprInst, zonkInst, tidyInsts,
35                           Inst, LIE, pprInsts, pprInstsInFull,
36                           mkLIE, lieToList 
37                         )
38 import TcEnv            ( tcGetGlobalTyVars, tcGetInstEnv )
39 import InstEnv          ( lookupInstEnv, classInstEnv, InstLookupResult(..) )
40
41 import TcType           ( zonkTcTyVarsAndFV, tcInstTyVars )
42 import TcUnify          ( unifyTauTy )
43 import Id               ( idType )
44 import NameSet          ( mkNameSet )
45 import Class            ( classBigSig )
46 import FunDeps          ( oclose, grow, improve )
47 import PrelInfo         ( isNumericClass, isCreturnableClass, isCcallishClass )
48
49 import Type             ( ThetaType, PredType, mkClassPred,
50                           mkTyVarTy, getTyVar, isTyVarClassPred,
51                           splitSigmaTy, tyVarsOfPred,
52                           getClassPredTys_maybe, isClassPred, isIPPred,
53                           inheritablePred, predHasFDs
54                         )
55 import Subst            ( mkTopTyVarSubst, substTheta, substTy )
56 import TysWiredIn       ( unitTy )
57 import VarSet
58 import FiniteMap
59 import Outputable
60 import ListSetOps       ( equivClasses )
61 import Util             ( zipEqual )
62 import List             ( partition )
63 import CmdLineOpts
64 \end{code}
65
66
67 %************************************************************************
68 %*                                                                      *
69 \subsection{NOTES}
70 %*                                                                      *
71 %************************************************************************
72
73         --------------------------------------  
74                 Notes on quantification
75         --------------------------------------  
76
77 Suppose we are about to do a generalisation step.
78 We have in our hand
79
80         G       the environment
81         T       the type of the RHS
82         C       the constraints from that RHS
83
84 The game is to figure out
85
86         Q       the set of type variables over which to quantify
87         Ct      the constraints we will *not* quantify over
88         Cq      the constraints we will quantify over
89
90 So we're going to infer the type
91
92         forall Q. Cq => T
93
94 and float the constraints Ct further outwards.  
95
96 Here are the things that *must* be true:
97
98  (A)    Q intersect fv(G) = EMPTY                       limits how big Q can be
99  (B)    Q superset fv(Cq union T) \ oclose(fv(G),C)     limits how small Q can be
100
101 (A) says we can't quantify over a variable that's free in the
102 environment.  (B) says we must quantify over all the truly free
103 variables in T, else we won't get a sufficiently general type.  We do
104 not *need* to quantify over any variable that is fixed by the free
105 vars of the environment G.
106
107         BETWEEN THESE TWO BOUNDS, ANY Q WILL DO!
108
109 Example:        class H x y | x->y where ...
110
111         fv(G) = {a}     C = {H a b, H c d}
112                         T = c -> b
113
114         (A)  Q intersect {a} is empty
115         (B)  Q superset {a,b,c,d} \ oclose({a}, C) = {a,b,c,d} \ {a,b} = {c,d}
116
117         So Q can be {c,d}, {b,c,d}
118
119 Other things being equal, however, we'd like to quantify over as few
120 variables as possible: smaller types, fewer type applications, more
121 constraints can get into Ct instead of Cq.
122
123
124 -----------------------------------------
125 We will make use of
126
127   fv(T)         the free type vars of T
128
129   oclose(vs,C)  The result of extending the set of tyvars vs
130                 using the functional dependencies from C
131
132   grow(vs,C)    The result of extend the set of tyvars vs
133                 using all conceivable links from C.  
134
135                 E.g. vs = {a}, C = {H [a] b, K (b,Int) c, Eq e}
136                 Then grow(vs,C) = {a,b,c}
137
138                 Note that grow(vs,C) `superset` grow(vs,simplify(C))
139                 That is, simplfication can only shrink the result of grow.
140
141 Notice that 
142    oclose is conservative one way:      v `elem` oclose(vs,C) => v is definitely fixed by vs
143    grow is conservative the other way:  if v might be fixed by vs => v `elem` grow(vs,C)
144
145
146 -----------------------------------------
147
148 Choosing Q
149 ~~~~~~~~~~
150 Here's a good way to choose Q:
151
152         Q = grow( fv(T), C ) \ oclose( fv(G), C )
153
154 That is, quantify over all variable that that MIGHT be fixed by the
155 call site (which influences T), but which aren't DEFINITELY fixed by
156 G.  This choice definitely quantifies over enough type variables,
157 albeit perhaps too many.
158
159 Why grow( fv(T), C ) rather than fv(T)?  Consider
160
161         class H x y | x->y where ...
162         
163         T = c->c
164         C = (H c d)
165
166   If we used fv(T) = {c} we'd get the type
167
168         forall c. H c d => c -> b
169
170   And then if the fn was called at several different c's, each of 
171   which fixed d differently, we'd get a unification error, because
172   d isn't quantified.  Solution: quantify d.  So we must quantify
173   everything that might be influenced by c.
174
175 Why not oclose( fv(T), C )?  Because we might not be able to see
176 all the functional dependencies yet:
177
178         class H x y | x->y where ...
179         instance H x y => Eq (T x y) where ...
180
181         T = c->c
182         C = (Eq (T c d))
183
184   Now oclose(fv(T),C) = {c}, because the functional dependency isn't
185   apparent yet, and that's wrong.  We must really quantify over d too.
186
187
188 There really isn't any point in quantifying over any more than
189 grow( fv(T), C ), because the call sites can't possibly influence
190 any other type variables.
191
192
193
194         --------------------------------------  
195                 Notes on ambiguity  
196         --------------------------------------  
197
198 It's very hard to be certain when a type is ambiguous.  Consider
199
200         class K x
201         class H x y | x -> y
202         instance H x y => K (x,y)
203
204 Is this type ambiguous?
205         forall a b. (K (a,b), Eq b) => a -> a
206
207 Looks like it!  But if we simplify (K (a,b)) we get (H a b) and
208 now we see that a fixes b.  So we can't tell about ambiguity for sure
209 without doing a full simplification.  And even that isn't possible if
210 the context has some free vars that may get unified.  Urgle!
211
212 Here's another example: is this ambiguous?
213         forall a b. Eq (T b) => a -> a
214 Not if there's an insance decl (with no context)
215         instance Eq (T b) where ...
216
217 You may say of this example that we should use the instance decl right
218 away, but you can't always do that:
219
220         class J a b where ...
221         instance J Int b where ...
222
223         f :: forall a b. J a b => a -> a
224
225 (Notice: no functional dependency in J's class decl.)
226 Here f's type is perfectly fine, provided f is only called at Int.
227 It's premature to complain when meeting f's signature, or even
228 when inferring a type for f.
229
230
231
232 However, we don't *need* to report ambiguity right away.  It'll always
233 show up at the call site.... and eventually at main, which needs special
234 treatment.  Nevertheless, reporting ambiguity promptly is an excellent thing.
235
236 So here's the plan.  We WARN about probable ambiguity if
237
238         fv(Cq) is not a subset of  oclose(fv(T) union fv(G), C)
239
240 (all tested before quantification).
241 That is, all the type variables in Cq must be fixed by the the variables
242 in the environment, or by the variables in the type.  
243
244 Notice that we union before calling oclose.  Here's an example:
245
246         class J a b c | a b -> c
247         fv(G) = {a}
248
249 Is this ambiguous?
250         forall b c. (J a b c) => b -> b
251
252 Only if we union {a} from G with {b} from T before using oclose,
253 do we see that c is fixed.  
254
255 It's a bit vague exactly which C we should use for this oclose call.  If we 
256 don't fix enough variables we might complain when we shouldn't (see
257 the above nasty example).  Nothing will be perfect.  That's why we can
258 only issue a warning.
259
260
261 Can we ever be *certain* about ambiguity?  Yes: if there's a constraint
262
263         c in C such that fv(c) intersect (fv(G) union fv(T)) = EMPTY
264
265 then c is a "bubble"; there's no way it can ever improve, and it's 
266 certainly ambiguous.  UNLESS it is a constant (sigh).  And what about
267 the nasty example?
268
269         class K x
270         class H x y | x -> y
271         instance H x y => K (x,y)
272
273 Is this type ambiguous?
274         forall a b. (K (a,b), Eq b) => a -> a
275
276 Urk.  The (Eq b) looks "definitely ambiguous" but it isn't.  What we are after
277 is a "bubble" that's a set of constraints
278
279         Cq = Ca union Cq'  st  fv(Ca) intersect (fv(Cq') union fv(T) union fv(G)) = EMPTY
280
281 Hence another idea.  To decide Q start with fv(T) and grow it
282 by transitive closure in Cq (no functional dependencies involved).
283 Now partition Cq using Q, leaving the definitely-ambiguous and probably-ok.
284 The definitely-ambiguous can then float out, and get smashed at top level
285 (which squashes out the constants, like Eq (T a) above)
286
287
288         --------------------------------------  
289                 Notes on principal types
290         --------------------------------------  
291
292     class C a where
293       op :: a -> a
294     
295     f x = let g y = op (y::Int) in True
296
297 Here the principal type of f is (forall a. a->a)
298 but we'll produce the non-principal type
299     f :: forall a. C Int => a -> a
300
301
302         --------------------------------------  
303                 Notes on implicit parameters
304         --------------------------------------  
305
306 Question 1: can we "inherit" implicit parameters
307 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
308 Consider this:
309
310         f x = (x::Int) + ?y
311
312 where f is *not* a top-level binding.
313 From the RHS of f we'll get the constraint (?y::Int).
314 There are two types we might infer for f:
315
316         f :: Int -> Int
317
318 (so we get ?y from the context of f's definition), or
319
320         f :: (?y::Int) => Int -> Int
321
322 At first you might think the first was better, becuase then
323 ?y behaves like a free variable of the definition, rather than
324 having to be passed at each call site.  But of course, the WHOLE
325 IDEA is that ?y should be passed at each call site (that's what
326 dynamic binding means) so we'd better infer the second.
327
328 BOTTOM LINE: you *must* quantify over implicit parameters.
329
330
331 Question 2: type signatures
332 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
333 OK, so it it legal to give an explicit, user type signature to f, thus:
334
335         f :: Int -> Int
336         f x = (x::Int) + ?y
337
338 At first sight this seems reasonable, but it has the nasty property
339 that adding a type signature changes the dynamic semantics.=20
340 Consider this:
341
342         (let f x = (x::Int) + ?y
343          in (f 3, f 3 with ?y=5))  with ?y = 6
344
345                 returns (3+6, 3+5)
346 vs
347         (let f :: Int -> Int=20
348              f x = x + ?y
349          in (f 3, f 3 with ?y=5))  with ?y = 6
350
351                 returns (3+6, 3+6)
352
353 Indeed, simply inlining f (at the Haskell source level) would change the
354 dynamic semantics.
355
356 Conclusion: the above type signature is illegal.  You'll get a message
357 of the form "could not deduce (?y::Int) from ()".
358
359
360 Question 3: monomorphism
361 ~~~~~~~~~~~~~~~~~~~~~~~~
362 There's a nasty corner case when the monomorphism restriction bites:
363
364         z = (x::Int) + ?y
365
366 The argument above suggests that we *must* generalise=20
367 over the ?y parameter, to get=20
368         z :: (?y::Int) => Int,
369 but the monomorphism restriction says that we *must not*, giving
370         z :: Int. =20
371 Why does the momomorphism restriction say this?  Because if you have
372
373         let z = x + ?y in z+z
374
375 you might not expect the addition to be done twice --- but it will if
376 we follow the argument of Question 2 and generalise over ?y.
377
378
379
380 Possible choices
381 ~~~~~~~~~~~~~~~~
382 (A) Always generalise over implicit parameters
383     Bindings that fall under the monomorphism restriction can't
384         be generalised
385
386     Consequences:
387         * Inlning remains valid
388         * No unexpected loss of sharing
389         * But simple bindings like
390                 z = ?y + 1
391           will be rejected, unless you add an explicit type signature
392           (to avoid the monomorphism restriction)
393                 z :: (?y::Int) => Int
394                 z = ?y + 1
395           This seems unacceptable
396
397 (B) Monomorphism restriction "wins"
398     Bindings that fall under the monomorphism restriction can't
399         be generalised
400     Always generalise over implicit parameters *except* for bindings
401         that fall under the monomorphism restriction
402
403     Consequences
404         * Inlining isn't valid in general
405         * No unexpected loss of sharing
406         * Simple bindings like
407                 z = ?y + 1
408           accepted (get value of ?y from binding site)
409
410 (C) Always generalise over implicit parameters
411     Bindings that fall under the monomorphism restriction can't
412         be generalised, EXCEPT for implicit parameters
413     Consequences
414         * Inlining remains valid
415         * Unexpected loss of sharing (from the extra generalisation)
416         * Simple bindings like
417                 z = ?y + 1
418           accepted (get value of ?y from occurrence sites)
419
420
421 Discussion
422 ~~~~~~~~~~
423 None of these choices seems very satisfactory.  But at least we should
424 decide which we want to do.
425
426 It's really not clear what is the Right Thing To Do.  If you see
427
428         z = (x::Int) + ?y
429
430 would you expect the value of ?y to be got from the *occurrence sites*
431 of 'z', or from the valuue of ?y at the *definition* of 'z'?  In the
432 case of function definitions, the answer is clearly the former, but
433 less so in the case of non-fucntion definitions.   On the other hand,
434 if we say that we get the value of ?y from the definition site of 'z',
435 then inlining 'z' might change the semantics of the program.
436
437 Choice (C) really says "the monomorphism restriction doesn't apply
438 to implicit parameters".  Which is fine, but remember that every=20
439 innocent binding 'x = ...' that mentions an implicit parameter in
440 the RHS becomes a *function* of that parameter, called at each
441 use of 'x'.  Now, the chances are that there are no intervening 'with'
442 clauses that bind ?y, so a decent compiler should common up all=20
443 those function calls.  So I think I strongly favour (C).  Indeed,
444 one could make a similar argument for abolishing the monomorphism
445 restriction altogether.
446
447 BOTTOM LINE: we choose (B) at present.  See tcSimplifyRestricted
448
449         
450
451 %************************************************************************
452 %*                                                                      *
453 \subsection{tcSimplifyInfer}
454 %*                                                                      *
455 %************************************************************************
456
457 tcSimplify is called when we *inferring* a type.  Here's the overall game plan:
458
459     1. Compute Q = grow( fvs(T), C )
460     
461     2. Partition C based on Q into Ct and Cq.  Notice that ambiguous 
462        predicates will end up in Ct; we deal with them at the top level
463     
464     3. Try improvement, using functional dependencies
465     
466     4. If Step 3 did any unification, repeat from step 1
467        (Unification can change the result of 'grow'.)
468
469 Note: we don't reduce dictionaries in step 2.  For example, if we have
470 Eq (a,b), we don't simplify to (Eq a, Eq b).  So Q won't be different 
471 after step 2.  However note that we may therefore quantify over more
472 type variables than we absolutely have to.
473
474 For the guts, we need a loop, that alternates context reduction and
475 improvement with unification.  E.g. Suppose we have
476
477         class C x y | x->y where ...
478     
479 and tcSimplify is called with:
480         (C Int a, C Int b)
481 Then improvement unifies a with b, giving
482         (C Int a, C Int a)
483
484 If we need to unify anything, we rattle round the whole thing all over
485 again. 
486
487
488 \begin{code}
489 tcSimplifyInfer
490         :: SDoc 
491         -> [TcTyVar]            -- fv(T); type vars 
492         -> LIE                  -- Wanted
493         -> TcM ([TcTyVar],      -- Tyvars to quantify (zonked)
494                 LIE,            -- Free
495                 TcDictBinds,    -- Bindings
496                 [TcId])         -- Dict Ids that must be bound here (zonked)
497 \end{code}
498
499
500 \begin{code}
501 tcSimplifyInfer doc tau_tvs wanted_lie
502   = inferLoop doc tau_tvs (lieToList wanted_lie)        `thenTc` \ (qtvs, frees, binds, irreds) ->
503
504         -- Check for non-generalisable insts
505     mapTc_ addCantGenErr (filter (not . instCanBeGeneralised) irreds)   `thenTc_`
506
507     returnTc (qtvs, mkLIE frees, binds, map instToId irreds)
508
509 inferLoop doc tau_tvs wanteds
510   =     -- Step 1
511     zonkTcTyVarsAndFV tau_tvs           `thenNF_Tc` \ tau_tvs' ->
512     mapNF_Tc zonkInst wanteds           `thenNF_Tc` \ wanteds' ->
513     tcGetGlobalTyVars                   `thenNF_Tc` \ gbl_tvs ->
514     let
515         preds = predsOfInsts wanteds'
516         qtvs  = grow preds tau_tvs' `minusVarSet` oclose preds gbl_tvs
517         
518         try_me inst     
519           | isFreeAndInheritable qtvs inst = Free
520           | isClassDict inst               = DontReduceUnlessConstant   -- Dicts
521           | otherwise                      = ReduceMe                   -- Lits and Methods
522     in
523                 -- Step 2
524     reduceContext doc try_me [] wanteds'    `thenTc` \ (no_improvement, frees, binds, irreds) ->
525         
526                 -- Step 3
527     if no_improvement then
528         returnTc (varSetElems qtvs, frees, binds, irreds)
529     else
530         -- If improvement did some unification, we go round again.  There
531         -- are two subtleties:
532         --   a) We start again with irreds, not wanteds
533         --      Using an instance decl might have introduced a fresh type variable
534         --      which might have been unified, so we'd get an infinite loop
535         --      if we started again with wanteds!  See example [LOOP]
536         --
537         --   b) It's also essential to re-process frees, because unification
538         --      might mean that a type variable that looked free isn't now.
539         --
540         -- Hence the (irreds ++ frees)
541
542         inferLoop doc tau_tvs (irreds ++ frees) `thenTc` \ (qtvs1, frees1, binds1, irreds1) ->
543         returnTc (qtvs1, frees1, binds `AndMonoBinds` binds1, irreds1)
544 \end{code}      
545
546 Example [LOOP]
547
548         class If b t e r | b t e -> r
549         instance If T t e t
550         instance If F t e e
551         class Lte a b c | a b -> c where lte :: a -> b -> c
552         instance Lte Z b T
553         instance (Lte a b l,If l b a c) => Max a b c
554
555 Wanted: Max Z (S x) y
556
557 Then we'll reduce using the Max instance to:
558         (Lte Z (S x) l, If l (S x) Z y)
559 and improve by binding l->T, after which we can do some reduction 
560 on both the Lte and If constraints.  What we *can't* do is start again
561 with (Max Z (S x) y)!
562
563 \begin{code}
564 isFreeAndInheritable qtvs inst
565   =  isFree qtvs inst                                   -- Constrains no quantified vars
566   && all inheritablePred (predsOfInst inst)             -- And no implicit parameter involved
567                                                         -- (see "Notes on implicit parameters")
568
569 isFree qtvs inst = not (tyVarsOfInst inst `intersectsVarSet` qtvs)
570 \end{code}
571
572
573 %************************************************************************
574 %*                                                                      *
575 \subsection{tcSimplifyCheck}
576 %*                                                                      *
577 %************************************************************************
578
579 @tcSimplifyCheck@ is used when we know exactly the set of variables
580 we are going to quantify over.  For example, a class or instance declaration.
581
582 \begin{code}
583 tcSimplifyCheck
584          :: SDoc 
585          -> [TcTyVar]           -- Quantify over these
586          -> [Inst]              -- Given
587          -> LIE                 -- Wanted
588          -> TcM (LIE,           -- Free
589                  TcDictBinds)   -- Bindings
590
591 tcSimplifyCheck doc qtvs givens wanted_lie
592   = checkLoop doc qtvs givens (lieToList wanted_lie)    `thenTc` \ (frees, binds, irreds) ->
593
594         -- Complain about any irreducible ones
595     complainCheck doc givens irreds             `thenNF_Tc_`
596
597         -- Done
598     returnTc (mkLIE frees, binds)
599
600 checkLoop doc qtvs givens wanteds
601   =             -- Step 1
602     zonkTcTyVarsAndFV qtvs              `thenNF_Tc` \ qtvs' ->
603     mapNF_Tc zonkInst givens            `thenNF_Tc` \ givens' ->
604     mapNF_Tc zonkInst wanteds           `thenNF_Tc` \ wanteds' ->
605
606                 -- Step 2
607     let
608         -- When checking against a given signature we always reduce
609         -- until we find a match against something given, or can't reduce
610         try_me inst | isFreeAndInheritable qtvs' inst = Free
611                     | otherwise                       = ReduceMe 
612     in
613     reduceContext doc try_me givens' wanteds'   `thenTc` \ (no_improvement, frees, binds, irreds) ->
614         
615                 -- Step 3
616     if no_improvement then
617         returnTc (frees, binds, irreds)
618     else
619         checkLoop doc qtvs givens' (irreds ++ frees)    `thenTc` \ (frees1, binds1, irreds1) ->
620         returnTc (frees1, binds `AndMonoBinds` binds1, irreds1)
621
622 complainCheck doc givens irreds
623   = mapNF_Tc zonkInst given_dicts                       `thenNF_Tc` \ givens' ->
624     mapNF_Tc (addNoInstanceErr doc given_dicts) irreds  `thenNF_Tc_`
625     returnTc ()
626   where
627     given_dicts = filter isDict givens
628         -- Filter out methods, which are only added to 
629         -- the given set as an optimisation
630 \end{code}
631
632
633 %************************************************************************
634 %*                                                                      *
635 \subsection{tcSimplifyRestricted}
636 %*                                                                      *
637 %************************************************************************
638
639 \begin{code}
640 tcSimplifyRestricted    -- Used for restricted binding groups
641         :: SDoc 
642         -> [TcTyVar]            -- Free in the type of the RHSs
643         -> LIE                  -- Free in the RHSs
644         -> TcM ([TcTyVar],      -- Tyvars to quantify (zonked)
645                 LIE,            -- Free
646                 TcDictBinds)    -- Bindings
647
648 tcSimplifyRestricted doc tau_tvs wanted_lie
649   =     -- First squash out all methods, to find the constrained tyvars
650         -- We can't just take the free vars of wanted_lie because that'll 
651         -- have methods that may incidentally mention entirely unconstrained variables
652         --      e.g. a call to  f :: Eq a => a -> b -> b
653         -- Here, b is unconstrained.  A good example would be
654         --      foo = f (3::Int)
655         -- We want to infer the polymorphic type
656         --      foo :: forall b. b -> b
657     tcSimplifyToDicts wanted_lie        `thenTc` \ (dicts, _) ->
658     let
659         constrained_tvs = tyVarsOfInsts dicts
660     in
661
662         -- Next, figure out the tyvars we will quantify over
663     zonkTcTyVarsAndFV tau_tvs           `thenNF_Tc` \ tau_tvs' ->
664     tcGetGlobalTyVars                   `thenNF_Tc` \ gbl_tvs ->
665     let
666         qtvs = (tau_tvs' `minusVarSet` oclose (predsOfInsts dicts) gbl_tvs)
667                          `minusVarSet` constrained_tvs
668     in
669
670         -- The first step may have squashed more methods than
671         -- necessary, so try again, this time knowing the exact
672         -- set of type variables to quantify over.
673         --
674         -- We quantify only over constraints that are captured by qtvs; 
675         -- these will just be a subset of non-dicts.  This in contrast
676         -- to normal inference (using isFreeAndInheritable) in which we quantify over 
677         -- all *non-inheritable* constraints too.  This implements choice 
678         -- (B) under "implicit parameter and monomorphism" above.
679     mapNF_Tc zonkInst (lieToList wanted_lie)    `thenNF_Tc` \ wanteds' ->
680     let
681         try_me inst | isFree qtvs inst = Free
682                     | otherwise        = ReduceMe
683     in
684     reduceContext doc try_me [] wanteds'        `thenTc` \ (no_improvement, frees, binds, irreds) ->
685     ASSERT( no_improvement )
686     ASSERT( null irreds )
687         -- No need to loop because tcSimplifyToDicts will have
688         -- already done any improvement necessary
689
690     returnTc (varSetElems qtvs, mkLIE frees, binds)
691 \end{code}
692
693
694 %************************************************************************
695 %*                                                                      *
696 \subsection{tcSimplifyAndCheck}
697 %*                                                                      *
698 %************************************************************************
699
700 @tcSimplifyInferCheck@ is used when we know the constraints we are to simplify
701 against, but we don't know the type variables over which we are going to quantify.
702 This happens when we have a type signature for a mutually recursive
703 group.
704
705 \begin{code}
706 tcSimplifyInferCheck
707          :: SDoc 
708          -> [TcTyVar]           -- fv(T)
709          -> [Inst]              -- Given
710          -> LIE                 -- Wanted
711          -> TcM ([TcTyVar],     -- Variables over which to quantify
712                  LIE,           -- Free
713                  TcDictBinds)   -- Bindings
714
715 tcSimplifyInferCheck doc tau_tvs givens wanted
716   = inferCheckLoop doc tau_tvs givens (lieToList wanted)        `thenTc` \ (qtvs, frees, binds, irreds) ->
717
718         -- Complain about any irreducible ones
719     complainCheck doc givens irreds             `thenNF_Tc_`
720
721         -- Done
722     returnTc (qtvs, mkLIE frees, binds)
723
724 inferCheckLoop doc tau_tvs givens wanteds
725   =     -- Step 1
726     zonkTcTyVarsAndFV tau_tvs           `thenNF_Tc` \ tau_tvs' ->
727     mapNF_Tc zonkInst givens            `thenNF_Tc` \ givens' ->
728     mapNF_Tc zonkInst wanteds           `thenNF_Tc` \ wanteds' ->
729     tcGetGlobalTyVars                   `thenNF_Tc` \ gbl_tvs ->
730
731     let
732         -- Figure out what we are going to generalise over
733         -- You might think it should just be the signature tyvars,
734         -- but in bizarre cases you can get extra ones
735         --      f :: forall a. Num a => a -> a
736         --      f x = fst (g (x, head [])) + 1
737         --      g a b = (b,a)
738         -- Here we infer g :: forall a b. a -> b -> (b,a)
739         -- We don't want g to be monomorphic in b just because
740         -- f isn't quantified over b.
741         qtvs    = (tau_tvs' `unionVarSet` tyVarsOfInsts givens') `minusVarSet` gbl_tvs
742                         -- We could close gbl_tvs, but its not necessary for
743                         -- soundness, and it'll only affect which tyvars, not which 
744                         -- dictionaries, we quantify over
745
746               -- When checking against a given signature we always reduce
747               -- until we find a match against something given, or can't reduce
748         try_me inst | isFreeAndInheritable qtvs inst  = Free
749                     | otherwise                       = ReduceMe 
750     in
751                 -- Step 2
752     reduceContext doc try_me givens' wanteds'    `thenTc` \ (no_improvement, frees, binds, irreds) ->
753         
754                 -- Step 3
755     if no_improvement then
756         returnTc (varSetElems qtvs, frees, binds, irreds)
757     else
758         inferCheckLoop doc tau_tvs givens' (irreds ++ frees)    `thenTc` \ (qtvs1, frees1, binds1, irreds1) ->
759         returnTc (qtvs1, frees1, binds `AndMonoBinds` binds1, irreds1)
760 \end{code}
761
762
763 %************************************************************************
764 %*                                                                      *
765 \subsection{tcSimplifyToDicts}
766 %*                                                                      *
767 %************************************************************************
768
769 On the LHS of transformation rules we only simplify methods and constants,
770 getting dictionaries.  We want to keep all of them unsimplified, to serve
771 as the available stuff for the RHS of the rule.
772
773 The same thing is used for specialise pragmas. Consider
774         
775         f :: Num a => a -> a
776         {-# SPECIALISE f :: Int -> Int #-}
777         f = ...
778
779 The type checker generates a binding like:
780
781         f_spec = (f :: Int -> Int)
782
783 and we want to end up with
784
785         f_spec = _inline_me_ (f Int dNumInt)
786
787 But that means that we must simplify the Method for f to (f Int dNumInt)! 
788 So tcSimplifyToDicts squeezes out all Methods.
789
790 IMPORTANT NOTE:  we *don't* want to do superclass commoning up.  Consider
791
792         fromIntegral :: (Integral a, Num b) => a -> b
793         {-# RULES "foo"  fromIntegral = id :: Int -> Int #-}
794
795 Here, a=b=Int, and Num Int is a superclass of Integral Int. But we *dont* 
796 want to get
797
798         forall dIntegralInt.
799         fromIntegral Int Int dIntegralInt (scsel dIntegralInt) = id Int
800
801 because the scsel will mess up matching.  Instead we want
802
803         forall dIntegralInt, dNumInt.
804         fromIntegral Int Int dIntegralInt dNumInt = id Int
805
806 Hence "DontReduce NoSCs"
807
808 \begin{code}
809 tcSimplifyToDicts :: LIE -> TcM ([Inst], TcDictBinds)
810 tcSimplifyToDicts wanted_lie
811   = simpleReduceLoop doc try_me wanteds         `thenTc` \ (frees, binds, irreds) ->
812         -- Since try_me doesn't look at types, we don't need to 
813         -- do any zonking, so it's safe to call reduceContext directly
814     ASSERT( null frees )
815     returnTc (irreds, binds)
816
817   where
818     doc = text "tcSimplifyToDicts"
819     wanteds = lieToList wanted_lie
820
821         -- Reduce methods and lits only; stop as soon as we get a dictionary
822     try_me inst | isDict inst = DontReduce NoSCs
823                 | otherwise   = ReduceMe
824 \end{code}
825
826
827 %************************************************************************
828 %*                                                                      *
829 \subsection{Filtering at a dynamic binding}
830 %*                                                                      *
831 %************************************************************************
832
833 When we have
834         let ?x = R in B
835
836 we must discharge all the ?x constraints from B.  We also do an improvement
837 step; if we have ?x::t1 and ?x::t2 we must unify t1, t2.  
838
839 Actually, the constraints from B might improve the types in ?x. For example
840
841         f :: (?x::Int) => Char -> Char
842         let ?x = 3 in f 'c'
843
844 then the constraint (?x::Int) arising from the call to f will 
845 force the binding for ?x to be of type Int.
846
847 \begin{code}
848 tcSimplifyIPs :: [Inst]         -- The implicit parameters bound here
849               -> LIE
850               -> TcM (LIE, TcDictBinds)
851 tcSimplifyIPs given_ips wanted_lie
852   = simpl_loop given_ips wanteds        `thenTc` \ (frees, binds) ->
853     returnTc (mkLIE frees, binds)
854   where
855     doc      = text "tcSimplifyIPs" <+> ppr ip_names
856     wanteds  = lieToList wanted_lie
857     ip_names = map instName given_ips
858     ip_set   = mkNameSet ip_names
859   
860         -- Simplify any methods that mention the implicit parameter
861     try_me inst | inst `instMentionsIPs` ip_set = ReduceMe
862                 | otherwise                     = Free
863
864     simpl_loop givens wanteds
865       = mapNF_Tc zonkInst givens                `thenNF_Tc` \ givens' ->
866         mapNF_Tc zonkInst wanteds               `thenNF_Tc` \ wanteds' ->
867   
868         reduceContext doc try_me givens' wanteds'    `thenTc` \ (no_improvement, frees, binds, irreds) ->
869
870         if no_improvement then
871             ASSERT( null irreds )
872             returnTc (frees, binds)
873         else
874             simpl_loop givens' (irreds ++ frees)        `thenTc` \ (frees1, binds1) ->
875             returnTc (frees1, binds `AndMonoBinds` binds1)
876 \end{code}
877
878
879 %************************************************************************
880 %*                                                                      *
881 \subsection[binds-for-local-funs]{@bindInstsOfLocalFuns@}
882 %*                                                                      *
883 %************************************************************************
884
885 When doing a binding group, we may have @Insts@ of local functions.
886 For example, we might have...
887 \begin{verbatim}
888 let f x = x + 1     -- orig local function (overloaded)
889     f.1 = f Int     -- two instances of f
890     f.2 = f Float
891  in
892     (f.1 5, f.2 6.7)
893 \end{verbatim}
894 The point is: we must drop the bindings for @f.1@ and @f.2@ here,
895 where @f@ is in scope; those @Insts@ must certainly not be passed
896 upwards towards the top-level.  If the @Insts@ were binding-ified up
897 there, they would have unresolvable references to @f@.
898
899 We pass in an @init_lie@ of @Insts@ and a list of locally-bound @Ids@.
900 For each method @Inst@ in the @init_lie@ that mentions one of the
901 @Ids@, we create a binding.  We return the remaining @Insts@ (in an
902 @LIE@), as well as the @HsBinds@ generated.
903
904 \begin{code}
905 bindInstsOfLocalFuns :: LIE -> [TcId] -> TcM (LIE, TcMonoBinds)
906
907 bindInstsOfLocalFuns init_lie local_ids
908   | null overloaded_ids 
909         -- Common case
910   = returnTc (init_lie, EmptyMonoBinds)
911
912   | otherwise
913   = simpleReduceLoop doc try_me wanteds         `thenTc` \ (frees, binds, irreds) -> 
914     ASSERT( null irreds )
915     returnTc (mkLIE frees, binds)
916   where
917     doc              = text "bindInsts" <+> ppr local_ids
918     wanteds          = lieToList init_lie
919     overloaded_ids   = filter is_overloaded local_ids
920     is_overloaded id = case splitSigmaTy (idType id) of
921                           (_, theta, _) -> not (null theta)
922
923     overloaded_set = mkVarSet overloaded_ids    -- There can occasionally be a lot of them
924                                                 -- so it's worth building a set, so that 
925                                                 -- lookup (in isMethodFor) is faster
926
927     try_me inst | isMethodFor overloaded_set inst = ReduceMe
928                 | otherwise                       = Free
929 \end{code}
930
931
932 %************************************************************************
933 %*                                                                      *
934 \subsection{Data types for the reduction mechanism}
935 %*                                                                      *
936 %************************************************************************
937
938 The main control over context reduction is here
939
940 \begin{code}
941 data WhatToDo 
942  = ReduceMe             -- Try to reduce this
943                         -- If there's no instance, behave exactly like
944                         -- DontReduce: add the inst to 
945                         -- the irreductible ones, but don't 
946                         -- produce an error message of any kind.
947                         -- It might be quite legitimate such as (Eq a)!
948
949  | DontReduce WantSCs           -- Return as irreducible 
950
951  | DontReduceUnlessConstant     -- Return as irreducible unless it can
952                                 -- be reduced to a constant in one step
953
954  | Free                   -- Return as free
955
956 data WantSCs = NoSCs | AddSCs   -- Tells whether we should add the superclasses
957                                 -- of a predicate when adding it to the avails
958 \end{code}
959
960
961
962 \begin{code}
963 type RedState = (Avails,        -- What's available
964                  [Inst])        -- Insts for which try_me returned Free
965
966 type Avails = FiniteMap Inst Avail
967
968 data Avail
969   = Irred               -- Used for irreducible dictionaries,
970                         -- which are going to be lambda bound
971
972   | BoundTo TcId        -- Used for dictionaries for which we have a binding
973                         -- e.g. those "given" in a signature
974
975   | NoRhs               -- Used for Insts like (CCallable f)
976                         -- where no witness is required.
977
978   | Rhs                 -- Used when there is a RHS 
979         TcExpr          -- The RHS
980         [Inst]          -- Insts free in the RHS; we need these too
981
982 pprAvails avails = vcat [ppr inst <+> equals <+> pprAvail avail
983                         | (inst,avail) <- fmToList avails ]
984
985 instance Outputable Avail where
986     ppr = pprAvail
987
988 pprAvail NoRhs        = text "<no rhs>"
989 pprAvail Irred        = text "Irred"
990 pprAvail (BoundTo x)  = text "Bound to" <+> ppr x
991 pprAvail (Rhs rhs bs) = ppr rhs <+> braces (ppr bs)
992 \end{code}
993
994 Extracting the bindings from a bunch of Avails.
995 The bindings do *not* come back sorted in dependency order.
996 We assume that they'll be wrapped in a big Rec, so that the
997 dependency analyser can sort them out later
998
999 The loop startes
1000 \begin{code}
1001 bindsAndIrreds :: Avails
1002                -> [Inst]                -- Wanted
1003                -> (TcDictBinds,         -- Bindings
1004                    [Inst])              -- Irreducible ones
1005
1006 bindsAndIrreds avails wanteds
1007   = go avails EmptyMonoBinds [] wanteds
1008   where
1009     go avails binds irreds [] = (binds, irreds)
1010
1011     go avails binds irreds (w:ws)
1012       = case lookupFM avails w of
1013           Nothing    -> -- Free guys come out here
1014                         -- (If we didn't do addFree we could use this as the
1015                         --  criterion for free-ness, and pick up the free ones here too)
1016                         go avails binds irreds ws
1017
1018           Just NoRhs -> go avails binds irreds ws
1019
1020           Just Irred -> go (addToFM avails w (BoundTo (instToId w))) binds (w:irreds) ws
1021
1022           Just (BoundTo id) -> go avails new_binds irreds ws
1023                             where
1024                                 -- For implicit parameters, all occurrences share the same
1025                                 -- Id, so there is no need for synonym bindings
1026                                new_binds | new_id == id = binds
1027                                          | otherwise    = addBind binds new_id (HsVar id)
1028                                new_id   = instToId w
1029
1030           Just (Rhs rhs ws') -> go avails' (addBind binds id rhs) irreds (ws' ++ ws)
1031                              where
1032                                 id       = instToId w
1033                                 avails'  = addToFM avails w (BoundTo id)
1034
1035 addBind binds id rhs = binds `AndMonoBinds` VarMonoBind id rhs
1036 \end{code}
1037
1038
1039 %************************************************************************
1040 %*                                                                      *
1041 \subsection[reduce]{@reduce@}
1042 %*                                                                      *
1043 %************************************************************************
1044
1045 When the "what to do" predicate doesn't depend on the quantified type variables,
1046 matters are easier.  We don't need to do any zonking, unless the improvement step
1047 does something, in which case we zonk before iterating.
1048
1049 The "given" set is always empty.
1050
1051 \begin{code}
1052 simpleReduceLoop :: SDoc
1053                  -> (Inst -> WhatToDo)          -- What to do, *not* based on the quantified type variables
1054                  -> [Inst]                      -- Wanted
1055                  -> TcM ([Inst],                -- Free
1056                          TcDictBinds,
1057                          [Inst])                -- Irreducible
1058
1059 simpleReduceLoop doc try_me wanteds
1060   = mapNF_Tc zonkInst wanteds                   `thenNF_Tc` \ wanteds' ->
1061     reduceContext doc try_me [] wanteds'        `thenTc` \ (no_improvement, frees, binds, irreds) ->
1062     if no_improvement then
1063         returnTc (frees, binds, irreds)
1064     else
1065         simpleReduceLoop doc try_me (irreds ++ frees)   `thenTc` \ (frees1, binds1, irreds1) ->
1066         returnTc (frees1, binds `AndMonoBinds` binds1, irreds1)
1067 \end{code}      
1068
1069
1070
1071 \begin{code}
1072 reduceContext :: SDoc
1073               -> (Inst -> WhatToDo)
1074               -> [Inst]                 -- Given
1075               -> [Inst]                 -- Wanted
1076               -> NF_TcM (Bool,          -- True <=> improve step did no unification
1077                          [Inst],        -- Free
1078                          TcDictBinds,   -- Dictionary bindings
1079                          [Inst])        -- Irreducible
1080
1081 reduceContext doc try_me givens wanteds
1082   =
1083     traceTc (text "reduceContext" <+> (vcat [
1084              text "----------------------",
1085              doc,
1086              text "given" <+> ppr givens,
1087              text "wanted" <+> ppr wanteds,
1088              text "----------------------"
1089              ]))                                        `thenNF_Tc_`
1090
1091         -- Build the Avail mapping from "givens"
1092     foldlNF_Tc addGiven (emptyFM, []) givens            `thenNF_Tc` \ init_state ->
1093
1094         -- Do the real work
1095     reduceList (0,[]) try_me wanteds init_state         `thenNF_Tc` \ state@(avails, frees) ->
1096
1097         -- Do improvement, using everything in avails
1098         -- In particular, avails includes all superclasses of everything
1099     tcImprove avails                                    `thenTc` \ no_improvement ->
1100
1101     traceTc (text "reduceContext end" <+> (vcat [
1102              text "----------------------",
1103              doc,
1104              text "given" <+> ppr givens,
1105              text "wanted" <+> ppr wanteds,
1106              text "----", 
1107              text "avails" <+> pprAvails avails,
1108              text "frees" <+> ppr frees,
1109              text "no_improvement =" <+> ppr no_improvement,
1110              text "----------------------"
1111              ]))                                        `thenNF_Tc_`
1112      let
1113         (binds, irreds) = bindsAndIrreds avails wanteds
1114      in
1115      returnTc (no_improvement, frees, binds, irreds)
1116
1117 tcImprove avails
1118  =  tcGetInstEnv                                `thenTc` \ inst_env ->
1119     let
1120         preds = [ (pred, pp_loc)
1121                 | inst <- keysFM avails,
1122                   let pp_loc = pprInstLoc (instLoc inst),
1123                   pred <- predsOfInst inst,
1124                   predHasFDs pred
1125                 ]
1126                 -- Avails has all the superclasses etc (good)
1127                 -- It also has all the intermediates of the deduction (good)
1128                 -- It does not have duplicates (good)
1129                 -- NB that (?x::t1) and (?x::t2) will be held separately in avails
1130                 --    so that improve will see them separate
1131         eqns  = improve (classInstEnv inst_env) preds
1132      in
1133      if null eqns then
1134         returnTc True
1135      else
1136         traceTc (ptext SLIT("Improve:") <+> vcat (map ppr_eqn eqns))    `thenNF_Tc_`
1137         mapTc_ unify eqns       `thenTc_`
1138         returnTc False
1139   where
1140     unify ((qtvs, t1, t2), doc)
1141          = tcAddErrCtxt doc                     $
1142            tcInstTyVars (varSetElems qtvs)      `thenNF_Tc` \ (_, _, tenv) ->
1143            unifyTauTy (substTy tenv t1) (substTy tenv t2)
1144     ppr_eqn ((qtvs, t1, t2), doc)
1145         = vcat [ptext SLIT("forall") <+> braces (pprWithCommas ppr (varSetElems qtvs))
1146                                      <+> ppr t1 <+> equals <+> ppr t2,
1147                 doc]
1148 \end{code}
1149
1150 The main context-reduction function is @reduce@.  Here's its game plan.
1151
1152 \begin{code}
1153 reduceList :: (Int,[Inst])              -- Stack (for err msgs)
1154                                         -- along with its depth
1155            -> (Inst -> WhatToDo)
1156            -> [Inst]
1157            -> RedState
1158            -> TcM RedState
1159 \end{code}
1160
1161 @reduce@ is passed
1162      try_me:    given an inst, this function returns
1163                   Reduce       reduce this
1164                   DontReduce   return this in "irreds"
1165                   Free         return this in "frees"
1166
1167      wanteds:   The list of insts to reduce
1168      state:     An accumulating parameter of type RedState 
1169                 that contains the state of the algorithm
1170  
1171   It returns a RedState.
1172
1173 The (n,stack) pair is just used for error reporting.  
1174 n is always the depth of the stack.
1175 The stack is the stack of Insts being reduced: to produce X
1176 I had to produce Y, to produce Y I had to produce Z, and so on.
1177
1178 \begin{code}
1179 reduceList (n,stack) try_me wanteds state
1180   | n > opt_MaxContextReductionDepth
1181   = failWithTc (reduceDepthErr n stack)
1182
1183   | otherwise
1184   =
1185 #ifdef DEBUG
1186    (if n > 8 then
1187         pprTrace "Jeepers! ReduceContext:" (reduceDepthMsg n stack)
1188     else (\x->x))
1189 #endif
1190     go wanteds state
1191   where
1192     go []     state = returnTc state
1193     go (w:ws) state = reduce (n+1, w:stack) try_me w state      `thenTc` \ state' ->
1194                       go ws state'
1195
1196     -- Base case: we're done!
1197 reduce stack try_me wanted state
1198     -- It's the same as an existing inst, or a superclass thereof
1199   | isAvailable state wanted
1200   = returnTc state
1201
1202   | otherwise
1203   = case try_me wanted of {
1204
1205       DontReduce want_scs -> addIrred want_scs state wanted
1206
1207     ; DontReduceUnlessConstant ->    -- It's irreducible (or at least should not be reduced)
1208                                      -- First, see if the inst can be reduced to a constant in one step
1209         try_simple (addIrred AddSCs)    -- Assume want superclasses
1210
1211     ; Free ->   -- It's free so just chuck it upstairs
1212                 -- First, see if the inst can be reduced to a constant in one step
1213         try_simple addFree
1214
1215     ; ReduceMe ->               -- It should be reduced
1216         lookupInst wanted             `thenNF_Tc` \ lookup_result ->
1217         case lookup_result of
1218             GenInst wanteds' rhs -> reduceList stack try_me wanteds' state      `thenTc` \ state' -> 
1219                                     addWanted state' wanted rhs wanteds'
1220             SimpleInst rhs       -> addWanted state wanted rhs []
1221
1222             NoInstance ->    -- No such instance! 
1223                              -- Add it and its superclasses
1224                              addIrred AddSCs state wanted
1225
1226     }
1227   where
1228     try_simple do_this_otherwise
1229       = lookupInst wanted         `thenNF_Tc` \ lookup_result ->
1230         case lookup_result of
1231             SimpleInst rhs -> addWanted state wanted rhs []
1232             other          -> do_this_otherwise state wanted
1233 \end{code}
1234
1235
1236 \begin{code}
1237 isAvailable :: RedState -> Inst -> Bool
1238 isAvailable (avails, _) wanted = wanted `elemFM` avails
1239         -- NB: the Ord instance of Inst compares by the class/type info
1240         -- *not* by unique.  So 
1241         --      d1::C Int ==  d2::C Int
1242
1243 -------------------------
1244 addFree :: RedState -> Inst -> NF_TcM RedState
1245         -- When an Inst is tossed upstairs as 'free' we nevertheless add it
1246         -- to avails, so that any other equal Insts will be commoned up right
1247         -- here rather than also being tossed upstairs.  This is really just
1248         -- an optimisation, and perhaps it is more trouble that it is worth,
1249         -- as the following comments show!
1250         --
1251         -- NB1: do *not* add superclasses.  If we have
1252         --      df::Floating a
1253         --      dn::Num a
1254         -- but a is not bound here, then we *don't* want to derive 
1255         -- dn from df here lest we lose sharing.
1256         --
1257         -- NB2: do *not* add the Inst to avails at all if it's a method.
1258         -- The following situation shows why this is bad:
1259         --      truncate :: forall a. RealFrac a => forall b. Integral b => a -> b
1260         -- From an application (truncate f i) we get
1261         --      t1 = truncate at f 
1262         --      t2 = t1 at i
1263         -- If we have also have a second occurrence of truncate, we get
1264         --      t3 = truncate at f
1265         --      t4 = t3 at i
1266         -- When simplifying with i,f free, we might still notice that
1267         --   t1=t3; but alas, the binding for t2 (which mentions t1)
1268         --   will continue to float out!
1269         -- Solution: never put methods in avail till they are captured
1270         -- in which case addFree isn't used
1271         --
1272         -- NB3: make sure that CCallable/CReturnable use NoRhs rather
1273         --      than BoundTo, else we end up with bogus bindings.
1274         --      c.f. instBindingRequired in addWanted
1275 addFree (avails, frees) free
1276   | isDict free = returnNF_Tc (addToFM avails free avail, free:frees)
1277   | otherwise   = returnNF_Tc (avails,                    free:frees)
1278   where
1279     avail | instBindingRequired free = BoundTo (instToId free)
1280           | otherwise                = NoRhs
1281
1282 addWanted :: RedState -> Inst -> TcExpr -> [Inst] -> NF_TcM RedState
1283 addWanted state@(avails, frees) wanted rhs_expr wanteds
1284 -- Do *not* add superclasses as well.  Here's an example of why not
1285 --      class Eq a => Foo a b 
1286 --      instance Eq a => Foo [a] a
1287 -- If we are reducing
1288 --      (Foo [t] t)
1289 -- we'll first deduce that it holds (via the instance decl).  We  
1290 -- must not then overwrite the Eq t constraint with a superclass selection!
1291 --      ToDo: this isn't entirely unsatisfactory, because
1292 --            we may also lose some entirely-legitimate sharing this way
1293
1294   = ASSERT( not (isAvailable state wanted) )
1295     returnNF_Tc (addToFM avails wanted avail, frees)
1296   where 
1297     avail | instBindingRequired wanted = Rhs rhs_expr wanteds
1298           | otherwise                  = ASSERT( null wanteds ) NoRhs
1299
1300 addGiven :: RedState -> Inst -> NF_TcM RedState
1301 addGiven state given = addAvailAndSCs state given (BoundTo (instToId given))
1302
1303 addIrred :: WantSCs -> RedState -> Inst -> NF_TcM RedState
1304 addIrred NoSCs  (avails,frees) irred = returnNF_Tc (addToFM avails irred Irred, frees)
1305 addIrred AddSCs state          irred = addAvailAndSCs state irred Irred
1306
1307 addAvailAndSCs :: RedState -> Inst -> Avail -> NF_TcM RedState
1308 addAvailAndSCs (avails, frees) wanted avail
1309   = add_avail_and_scs avails wanted avail       `thenNF_Tc` \ avails' ->
1310     returnNF_Tc (avails', frees)
1311
1312 ---------------------
1313 add_avail_and_scs :: Avails -> Inst -> Avail -> NF_TcM Avails
1314 add_avail_and_scs avails wanted avail
1315   = add_scs (addToFM avails wanted avail) wanted
1316
1317 add_scs :: Avails -> Inst -> NF_TcM Avails
1318         -- Add all the superclasses of the Inst to Avails
1319         -- Invariant: the Inst is already in Avails.
1320
1321 add_scs avails dict
1322   | not (isClassDict dict)
1323   = returnNF_Tc avails
1324
1325   | otherwise   -- It is a dictionary
1326   = newDictsFromOld dict sc_theta'      `thenNF_Tc` \ sc_dicts ->
1327     foldlNF_Tc add_sc avails (zipEqual "add_scs" sc_dicts sc_sels)
1328   where
1329     (clas, tys) = getDictClassTys dict
1330     (tyvars, sc_theta, sc_sels, _) = classBigSig clas
1331     sc_theta' = substTheta (mkTopTyVarSubst tyvars tys) sc_theta
1332
1333     add_sc avails (sc_dict, sc_sel)     -- Add it, and its superclasses
1334       = case lookupFM avails sc_dict of
1335           Just (BoundTo _) -> returnNF_Tc avails        -- See Note [SUPER] below
1336           other            -> add_avail_and_scs avails sc_dict avail
1337       where
1338         sc_sel_rhs = DictApp (TyApp (HsVar sc_sel) tys) [instToId dict]
1339         avail      = Rhs sc_sel_rhs [dict]
1340 \end{code}
1341
1342 Note [SUPER].  We have to be careful here.  If we are *given* d1:Ord a,
1343 and want to deduce (d2:C [a]) where
1344
1345         class Ord a => C a where
1346         instance Ord a => C [a] where ...
1347
1348 Then we'll use the instance decl to deduce C [a] and then add the 
1349 superclasses of C [a] to avails.  But we must not overwrite the binding
1350 for d1:Ord a (which is given) with a superclass selection or we'll just
1351 build a loop!  Hence looking for BoundTo.  Crudely, BoundTo is cheaper
1352 than a selection.
1353
1354
1355 %************************************************************************
1356 %*                                                                      *
1357 \section{tcSimplifyTop: defaulting}
1358 %*                                                                      *
1359 %************************************************************************
1360
1361
1362 If a dictionary constrains a type variable which is
1363         * not mentioned in the environment
1364         * and not mentioned in the type of the expression
1365 then it is ambiguous. No further information will arise to instantiate
1366 the type variable; nor will it be generalised and turned into an extra
1367 parameter to a function.
1368
1369 It is an error for this to occur, except that Haskell provided for
1370 certain rules to be applied in the special case of numeric types.
1371 Specifically, if
1372         * at least one of its classes is a numeric class, and
1373         * all of its classes are numeric or standard
1374 then the type variable can be defaulted to the first type in the
1375 default-type list which is an instance of all the offending classes.
1376
1377 So here is the function which does the work.  It takes the ambiguous
1378 dictionaries and either resolves them (producing bindings) or
1379 complains.  It works by splitting the dictionary list by type
1380 variable, and using @disambigOne@ to do the real business.
1381
1382 @tcSimplifyTop@ is called once per module to simplify all the constant
1383 and ambiguous Insts.
1384
1385 We need to be careful of one case.  Suppose we have
1386
1387         instance Num a => Num (Foo a b) where ...
1388
1389 and @tcSimplifyTop@ is given a constraint (Num (Foo x y)).  Then it'll simplify
1390 to (Num x), and default x to Int.  But what about y??  
1391
1392 It's OK: the final zonking stage should zap y to (), which is fine.
1393
1394
1395 \begin{code}
1396 tcSimplifyTop :: LIE -> TcM TcDictBinds
1397 tcSimplifyTop wanted_lie
1398   = simpleReduceLoop (text "tcSimplTop") try_me wanteds `thenTc` \ (frees, binds, irreds) ->
1399     ASSERT( null frees )
1400
1401     let
1402                 -- All the non-std ones are definite errors
1403         (stds, non_stds) = partition isStdClassTyVarDict irreds
1404         
1405                 -- Group by type variable
1406         std_groups = equivClasses cmp_by_tyvar stds
1407
1408                 -- Pick the ones which its worth trying to disambiguate
1409         (std_oks, std_bads) = partition worth_a_try std_groups
1410
1411                 -- Have a try at disambiguation 
1412                 -- if the type variable isn't bound
1413                 -- up with one of the non-standard classes
1414         worth_a_try group@(d:_) = not (non_std_tyvars `intersectsVarSet` tyVarsOfInst d)
1415         non_std_tyvars          = unionVarSets (map tyVarsOfInst non_stds)
1416
1417                 -- Collect together all the bad guys
1418         bad_guys = non_stds ++ concat std_bads
1419     in
1420         -- Disambiguate the ones that look feasible
1421     mapTc disambigGroup std_oks         `thenTc` \ binds_ambig ->
1422
1423         -- And complain about the ones that don't
1424         -- This group includes both non-existent instances 
1425         --      e.g. Num (IO a) and Eq (Int -> Int)
1426         -- and ambiguous dictionaries
1427         --      e.g. Num a
1428     addTopAmbigErrs bad_guys            `thenNF_Tc_`
1429
1430     returnTc (binds `andMonoBinds` andMonoBindList binds_ambig)
1431   where
1432     wanteds     = lieToList wanted_lie
1433     try_me inst = ReduceMe
1434
1435     d1 `cmp_by_tyvar` d2 = get_tv d1 `compare` get_tv d2
1436
1437 get_tv d   = case getDictClassTys d of
1438                    (clas, [ty]) -> getTyVar "tcSimplifyTop" ty
1439 get_clas d = case getDictClassTys d of
1440                    (clas, [ty]) -> clas
1441 \end{code}
1442
1443 @disambigOne@ assumes that its arguments dictionaries constrain all
1444 the same type variable.
1445
1446 ADR Comment 20/6/94: I've changed the @CReturnable@ case to default to
1447 @()@ instead of @Int@.  I reckon this is the Right Thing to do since
1448 the most common use of defaulting is code like:
1449 \begin{verbatim}
1450         _ccall_ foo     `seqPrimIO` bar
1451 \end{verbatim}
1452 Since we're not using the result of @foo@, the result if (presumably)
1453 @void@.
1454
1455 \begin{code}
1456 disambigGroup :: [Inst] -- All standard classes of form (C a)
1457               -> TcM TcDictBinds
1458
1459 disambigGroup dicts
1460   |   any isNumericClass classes        -- Guaranteed all standard classes
1461           -- see comment at the end of function for reasons as to 
1462           -- why the defaulting mechanism doesn't apply to groups that
1463           -- include CCallable or CReturnable dicts.
1464    && not (any isCcallishClass classes)
1465   =     -- THE DICTS OBEY THE DEFAULTABLE CONSTRAINT
1466         -- SO, TRY DEFAULT TYPES IN ORDER
1467
1468         -- Failure here is caused by there being no type in the
1469         -- default list which can satisfy all the ambiguous classes.
1470         -- For example, if Real a is reqd, but the only type in the
1471         -- default list is Int.
1472     tcGetDefaultTys                     `thenNF_Tc` \ default_tys ->
1473     let
1474       try_default []    -- No defaults work, so fail
1475         = failTc
1476
1477       try_default (default_ty : default_tys)
1478         = tryTc_ (try_default default_tys) $    -- If default_ty fails, we try
1479                                                 -- default_tys instead
1480           tcSimplifyCheckThetas [] theta        `thenTc` \ _ ->
1481           returnTc default_ty
1482         where
1483           theta = [mkClassPred clas [default_ty] | clas <- classes]
1484     in
1485         -- See if any default works, and if so bind the type variable to it
1486         -- If not, add an AmbigErr
1487     recoverTc (addAmbigErrs dicts                       `thenNF_Tc_` 
1488                returnTc EmptyMonoBinds) $
1489
1490     try_default default_tys                     `thenTc` \ chosen_default_ty ->
1491
1492         -- Bind the type variable and reduce the context, for real this time
1493     unifyTauTy chosen_default_ty (mkTyVarTy tyvar)      `thenTc_`
1494     simpleReduceLoop (text "disambig" <+> ppr dicts)
1495                      try_me dicts                       `thenTc` \ (frees, binds, ambigs) ->
1496     WARN( not (null frees && null ambigs), ppr frees $$ ppr ambigs )
1497     warnDefault dicts chosen_default_ty                 `thenTc_`
1498     returnTc binds
1499
1500   | all isCreturnableClass classes
1501   =     -- Default CCall stuff to (); we don't even both to check that () is an 
1502         -- instance of CReturnable, because we know it is.
1503     unifyTauTy (mkTyVarTy tyvar) unitTy    `thenTc_`
1504     returnTc EmptyMonoBinds
1505     
1506   | otherwise -- No defaults
1507   = addAmbigErrs dicts  `thenNF_Tc_`
1508     returnTc EmptyMonoBinds
1509
1510   where
1511     try_me inst = ReduceMe                      -- This reduce should not fail
1512     tyvar       = get_tv (head dicts)           -- Should be non-empty
1513     classes     = map get_clas dicts
1514 \end{code}
1515
1516 [Aside - why the defaulting mechanism is turned off when
1517  dealing with arguments and results to ccalls.
1518
1519 When typechecking _ccall_s, TcExpr ensures that the external
1520 function is only passed arguments (and in the other direction,
1521 results) of a restricted set of 'native' types. This is
1522 implemented via the help of the pseudo-type classes,
1523 @CReturnable@ (CR) and @CCallable@ (CC.)
1524  
1525 The interaction between the defaulting mechanism for numeric
1526 values and CC & CR can be a bit puzzling to the user at times.
1527 For example,
1528
1529     x <- _ccall_ f
1530     if (x /= 0) then
1531        _ccall_ g x
1532      else
1533        return ()
1534
1535 What type has 'x' got here? That depends on the default list
1536 in operation, if it is equal to Haskell 98's default-default
1537 of (Integer, Double), 'x' has type Double, since Integer
1538 is not an instance of CR. If the default list is equal to
1539 Haskell 1.4's default-default of (Int, Double), 'x' has type
1540 Int. 
1541
1542 To try to minimise the potential for surprises here, the
1543 defaulting mechanism is turned off in the presence of
1544 CCallable and CReturnable.
1545
1546 ]
1547
1548
1549 %************************************************************************
1550 %*                                                                      *
1551 \subsection[simple]{@Simple@ versions}
1552 %*                                                                      *
1553 %************************************************************************
1554
1555 Much simpler versions when there are no bindings to make!
1556
1557 @tcSimplifyThetas@ simplifies class-type constraints formed by
1558 @deriving@ declarations and when specialising instances.  We are
1559 only interested in the simplified bunch of class/type constraints.
1560
1561 It simplifies to constraints of the form (C a b c) where
1562 a,b,c are type variables.  This is required for the context of
1563 instance declarations.
1564
1565 \begin{code}
1566 tcSimplifyThetas :: ThetaType           -- Wanted
1567                  -> TcM ThetaType               -- Needed
1568
1569 tcSimplifyThetas wanteds
1570   = doptsTc Opt_GlasgowExts             `thenNF_Tc` \ glaExts ->
1571     reduceSimple [] wanteds             `thenNF_Tc` \ irreds ->
1572     let
1573         -- For multi-param Haskell, check that the returned dictionaries
1574         -- don't have any of the form (C Int Bool) for which
1575         -- we expect an instance here
1576         -- For Haskell 98, check that all the constraints are of the form C a,
1577         -- where a is a type variable
1578         bad_guys | glaExts   = [pred | pred <- irreds, 
1579                                        isEmptyVarSet (tyVarsOfPred pred)]
1580                  | otherwise = [pred | pred <- irreds, 
1581                                        not (isTyVarClassPred pred)]
1582     in
1583     if null bad_guys then
1584         returnTc irreds
1585     else
1586        mapNF_Tc addNoInstErr bad_guys           `thenNF_Tc_`
1587        failTc
1588 \end{code}
1589
1590 @tcSimplifyCheckThetas@ just checks class-type constraints, essentially;
1591 used with \tr{default} declarations.  We are only interested in
1592 whether it worked or not.
1593
1594 \begin{code}
1595 tcSimplifyCheckThetas :: ThetaType      -- Given
1596                       -> ThetaType      -- Wanted
1597                       -> TcM ()
1598
1599 tcSimplifyCheckThetas givens wanteds
1600   = reduceSimple givens wanteds    `thenNF_Tc`  \ irreds ->
1601     if null irreds then
1602        returnTc ()
1603     else
1604        mapNF_Tc addNoInstErr irreds             `thenNF_Tc_`
1605        failTc
1606 \end{code}
1607
1608
1609 \begin{code}
1610 type AvailsSimple = FiniteMap PredType Bool
1611                     -- True  => irreducible 
1612                     -- False => given, or can be derived from a given or from an irreducible
1613
1614 reduceSimple :: ThetaType                       -- Given
1615              -> ThetaType                       -- Wanted
1616              -> NF_TcM ThetaType                -- Irreducible
1617
1618 reduceSimple givens wanteds
1619   = reduce_simple (0,[]) givens_fm wanteds      `thenNF_Tc` \ givens_fm' ->
1620     returnNF_Tc [pred | (pred,True) <- fmToList givens_fm']
1621   where
1622     givens_fm     = foldl addNonIrred emptyFM givens
1623
1624 reduce_simple :: (Int,ThetaType)                -- Stack
1625               -> AvailsSimple
1626               -> ThetaType
1627               -> NF_TcM AvailsSimple
1628
1629 reduce_simple (n,stack) avails wanteds
1630   = go avails wanteds
1631   where
1632     go avails []     = returnNF_Tc avails
1633     go avails (w:ws) = reduce_simple_help (n+1,w:stack) avails w        `thenNF_Tc` \ avails' ->
1634                        go avails' ws
1635
1636 reduce_simple_help stack givens wanted
1637   | wanted `elemFM` givens
1638   = returnNF_Tc givens
1639
1640   | Just (clas, tys) <- getClassPredTys_maybe wanted
1641   = lookupSimpleInst clas tys   `thenNF_Tc` \ maybe_theta ->
1642     case maybe_theta of
1643       Nothing ->    returnNF_Tc (addSimpleIrred givens wanted)
1644       Just theta -> reduce_simple stack (addNonIrred givens wanted) theta
1645
1646   | otherwise
1647   = returnNF_Tc (addSimpleIrred givens wanted)
1648
1649 addSimpleIrred :: AvailsSimple -> PredType -> AvailsSimple
1650 addSimpleIrred givens pred
1651   = addSCs (addToFM givens pred True) pred
1652
1653 addNonIrred :: AvailsSimple -> PredType -> AvailsSimple
1654 addNonIrred givens pred
1655   = addSCs (addToFM givens pred False) pred
1656
1657 addSCs givens pred
1658   | not (isClassPred pred) = givens
1659   | otherwise              = foldl add givens sc_theta
1660  where
1661    Just (clas,tys) = getClassPredTys_maybe pred
1662    (tyvars, sc_theta_tmpl, _, _) = classBigSig clas
1663    sc_theta = substTheta (mkTopTyVarSubst tyvars tys) sc_theta_tmpl
1664
1665    add givens ct
1666      = case lookupFM givens ct of
1667        Nothing    -> -- Add it and its superclasses
1668                      addSCs (addToFM givens ct False) ct
1669
1670        Just True  -> -- Set its flag to False; superclasses already done
1671                      addToFM givens ct False
1672
1673        Just False -> -- Already done
1674                      givens
1675                            
1676 \end{code}
1677
1678
1679 %************************************************************************
1680 %*                                                                      *
1681 \section{Errors and contexts}
1682 %*                                                                      *
1683 %************************************************************************
1684
1685 ToDo: for these error messages, should we note the location as coming
1686 from the insts, or just whatever seems to be around in the monad just
1687 now?
1688
1689 \begin{code}
1690 addTopAmbigErrs dicts
1691   = mapNF_Tc complain tidy_dicts
1692   where
1693     fixed_tvs = oclose (predsOfInsts tidy_dicts) emptyVarSet
1694     (tidy_env, tidy_dicts) = tidyInsts dicts
1695     complain d | any isIPPred (predsOfInst d)         = addTopIPErr tidy_env d
1696                | not (isTyVarDict d) ||
1697                  tyVarsOfInst d `subVarSet` fixed_tvs = addTopInstanceErr tidy_env d
1698                | otherwise                            = addAmbigErr tidy_env d
1699
1700 addTopIPErr tidy_env tidy_dict
1701   = addInstErrTcM (instLoc tidy_dict) 
1702         (tidy_env, 
1703          ptext SLIT("Unbound implicit parameter") <+> quotes (pprInst tidy_dict))
1704
1705 -- Used for top-level irreducibles
1706 addTopInstanceErr tidy_env tidy_dict
1707   = addInstErrTcM (instLoc tidy_dict) 
1708         (tidy_env, 
1709          ptext SLIT("No instance for") <+> quotes (pprInst tidy_dict))
1710
1711 addAmbigErrs dicts
1712   = mapNF_Tc (addAmbigErr tidy_env) tidy_dicts
1713   where
1714     (tidy_env, tidy_dicts) = tidyInsts dicts
1715
1716 addAmbigErr tidy_env tidy_dict
1717   = addInstErrTcM (instLoc tidy_dict)
1718         (tidy_env,
1719          sep [text "Ambiguous type variable(s)" <+> pprQuotedList ambig_tvs,
1720               nest 4 (text "in the constraint" <+> quotes (pprInst tidy_dict))])
1721   where
1722     ambig_tvs = varSetElems (tyVarsOfInst tidy_dict)
1723
1724 warnDefault dicts default_ty
1725   = doptsTc Opt_WarnTypeDefaults  `thenTc` \ warn_flag ->
1726     tcAddSrcLoc (get_loc (head dicts)) (warnTc warn_flag warn_msg)
1727   where
1728         -- Tidy them first
1729     (_, tidy_dicts) = tidyInsts dicts
1730     get_loc i = case instLoc i of { (_,loc,_) -> loc }
1731     warn_msg  = vcat [ptext SLIT("Defaulting the following constraint(s) to type") <+> 
1732                                 quotes (ppr default_ty),
1733                       pprInstsInFull tidy_dicts]
1734
1735 -- The error message when we don't find a suitable instance
1736 -- is complicated by the fact that sometimes this is because
1737 -- there is no instance, and sometimes it's because there are
1738 -- too many instances (overlap).  See the comments in TcEnv.lhs
1739 -- with the InstEnv stuff.
1740 addNoInstanceErr what_doc givens dict
1741   = tcGetInstEnv        `thenNF_Tc` \ inst_env ->
1742     let
1743         doc = vcat [sep [herald <+> quotes (pprInst tidy_dict),
1744                          nest 4 $ ptext SLIT("from the context") <+> pprInsts tidy_givens],
1745                     ambig_doc,
1746                     ptext SLIT("Probable fix:"),
1747                     nest 4 fix1,
1748                     nest 4 fix2]
1749     
1750         herald = ptext SLIT("Could not") <+> unambig_doc <+> ptext SLIT("deduce")
1751         unambig_doc | ambig_overlap = ptext SLIT("unambiguously")       
1752                     | otherwise     = empty
1753     
1754         ambig_doc 
1755             | not ambig_overlap = empty
1756             | otherwise             
1757             = vcat [ptext SLIT("The choice of (overlapping) instance declaration"),
1758                     nest 4 (ptext SLIT("depends on the instantiation of") <+> 
1759                             quotes (pprWithCommas ppr (varSetElems (tyVarsOfInst tidy_dict))))]
1760     
1761         fix1 = sep [ptext SLIT("Add") <+> quotes (pprInst tidy_dict),
1762                     ptext SLIT("to the") <+> what_doc]
1763     
1764         fix2 | isTyVarDict dict 
1765              || not (isClassDict dict)  -- Don't suggest adding instance declarations for implicit parameters
1766              || ambig_overlap 
1767              = empty
1768              | otherwise
1769              = ptext SLIT("Or add an instance declaration for") <+> quotes (pprInst tidy_dict)
1770     
1771         (tidy_env, tidy_dict:tidy_givens) = tidyInsts (dict:givens)
1772     
1773             -- Checks for the ambiguous case when we have overlapping instances
1774         ambig_overlap | isClassDict dict
1775                       = case lookupInstEnv inst_env clas tys of
1776                             NoMatch ambig -> ambig
1777                             other         -> False
1778                       | otherwise = False
1779                       where
1780                         (clas,tys) = getDictClassTys dict
1781     in
1782     addInstErrTcM (instLoc dict) (tidy_env, doc)
1783
1784 -- Used for the ...Thetas variants; all top level
1785 addNoInstErr pred
1786   = addErrTc (ptext SLIT("No instance for") <+> quotes (ppr pred))
1787
1788 reduceDepthErr n stack
1789   = vcat [ptext SLIT("Context reduction stack overflow; size =") <+> int n,
1790           ptext SLIT("Use -fcontext-stack20 to increase stack size to (e.g.) 20"),
1791           nest 4 (pprInstsInFull stack)]
1792
1793 reduceDepthMsg n stack = nest 4 (pprInstsInFull stack)
1794
1795 -----------------------------------------------
1796 addCantGenErr inst
1797   = addErrTc (sep [ptext SLIT("Cannot generalise these overloadings (in a _ccall_):"), 
1798                    nest 4 (ppr inst <+> pprInstLoc (instLoc inst))])
1799 \end{code}