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