2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[TcSimplify]{TcSimplify}
10 tcSimplifyInfer, tcSimplifyInferCheck,
11 tcSimplifyCheck, tcSimplifyRestricted,
12 tcSimplifyToDicts, tcSimplifyIPs, tcSimplifyTop,
14 tcSimplifyThetas, tcSimplifyCheckThetas,
18 #include "HsVersions.h"
20 import HsSyn ( MonoBinds(..), HsExpr(..), andMonoBinds, andMonoBindList )
21 import TcHsSyn ( TcExpr, TcId,
22 TcMonoBinds, TcDictBinds
26 import Inst ( lookupInst, lookupSimpleInst, LookupInstResult(..),
27 tyVarsOfInst, predsOfInsts, predsOfInst,
29 isStdClassTyVarDict, isMethodFor,
30 instToId, tyVarsOfInsts,
31 ipNamesOfInsts, ipNamesOfInst,
32 instBindingRequired, instCanBeGeneralised,
34 getDictClassTys, isTyVarDict,
35 instLoc, pprInst, zonkInst, tidyInsts, tidyMoreInsts,
36 Inst, LIE, pprInsts, pprInstsInFull,
39 import TcEnv ( tcGetGlobalTyVars, tcGetInstEnv )
40 import InstEnv ( lookupInstEnv, classInstEnv, InstLookupResult(..) )
42 import TcMType ( zonkTcTyVarsAndFV, tcInstTyVars, unifyTauTy )
43 import TcType ( ThetaType, PredType, mkClassPred, isOverloadedTy,
44 mkTyVarTy, tcGetTyVar, isTyVarClassPred,
45 tyVarsOfPred, getClassPredTys_maybe, isClassPred, isIPPred,
46 inheritablePred, predHasFDs )
48 import NameSet ( NameSet, mkNameSet, elemNameSet )
49 import Class ( classBigSig )
50 import FunDeps ( oclose, grow, improve, pprEquationDoc )
51 import PrelInfo ( isNumericClass, isCreturnableClass, isCcallishClass )
53 import Subst ( mkTopTyVarSubst, substTheta, substTy )
54 import TysWiredIn ( unitTy )
58 import ListSetOps ( equivClasses )
59 import Util ( zipEqual )
60 import List ( partition )
65 %************************************************************************
69 %************************************************************************
71 --------------------------------------
72 Notes on quantification
73 --------------------------------------
75 Suppose we are about to do a generalisation step.
80 C the constraints from that RHS
82 The game is to figure out
84 Q the set of type variables over which to quantify
85 Ct the constraints we will *not* quantify over
86 Cq the constraints we will quantify over
88 So we're going to infer the type
92 and float the constraints Ct further outwards.
94 Here are the things that *must* be true:
96 (A) Q intersect fv(G) = EMPTY limits how big Q can be
97 (B) Q superset fv(Cq union T) \ oclose(fv(G),C) limits how small Q can be
99 (A) says we can't quantify over a variable that's free in the
100 environment. (B) says we must quantify over all the truly free
101 variables in T, else we won't get a sufficiently general type. We do
102 not *need* to quantify over any variable that is fixed by the free
103 vars of the environment G.
105 BETWEEN THESE TWO BOUNDS, ANY Q WILL DO!
107 Example: class H x y | x->y where ...
109 fv(G) = {a} C = {H a b, H c d}
112 (A) Q intersect {a} is empty
113 (B) Q superset {a,b,c,d} \ oclose({a}, C) = {a,b,c,d} \ {a,b} = {c,d}
115 So Q can be {c,d}, {b,c,d}
117 Other things being equal, however, we'd like to quantify over as few
118 variables as possible: smaller types, fewer type applications, more
119 constraints can get into Ct instead of Cq.
122 -----------------------------------------
125 fv(T) the free type vars of T
127 oclose(vs,C) The result of extending the set of tyvars vs
128 using the functional dependencies from C
130 grow(vs,C) The result of extend the set of tyvars vs
131 using all conceivable links from C.
133 E.g. vs = {a}, C = {H [a] b, K (b,Int) c, Eq e}
134 Then grow(vs,C) = {a,b,c}
136 Note that grow(vs,C) `superset` grow(vs,simplify(C))
137 That is, simplfication can only shrink the result of grow.
140 oclose is conservative one way: v `elem` oclose(vs,C) => v is definitely fixed by vs
141 grow is conservative the other way: if v might be fixed by vs => v `elem` grow(vs,C)
144 -----------------------------------------
148 Here's a good way to choose Q:
150 Q = grow( fv(T), C ) \ oclose( fv(G), C )
152 That is, quantify over all variable that that MIGHT be fixed by the
153 call site (which influences T), but which aren't DEFINITELY fixed by
154 G. This choice definitely quantifies over enough type variables,
155 albeit perhaps too many.
157 Why grow( fv(T), C ) rather than fv(T)? Consider
159 class H x y | x->y where ...
164 If we used fv(T) = {c} we'd get the type
166 forall c. H c d => c -> b
168 And then if the fn was called at several different c's, each of
169 which fixed d differently, we'd get a unification error, because
170 d isn't quantified. Solution: quantify d. So we must quantify
171 everything that might be influenced by c.
173 Why not oclose( fv(T), C )? Because we might not be able to see
174 all the functional dependencies yet:
176 class H x y | x->y where ...
177 instance H x y => Eq (T x y) where ...
182 Now oclose(fv(T),C) = {c}, because the functional dependency isn't
183 apparent yet, and that's wrong. We must really quantify over d too.
186 There really isn't any point in quantifying over any more than
187 grow( fv(T), C ), because the call sites can't possibly influence
188 any other type variables.
192 --------------------------------------
194 --------------------------------------
196 It's very hard to be certain when a type is ambiguous. Consider
200 instance H x y => K (x,y)
202 Is this type ambiguous?
203 forall a b. (K (a,b), Eq b) => a -> a
205 Looks like it! But if we simplify (K (a,b)) we get (H a b) and
206 now we see that a fixes b. So we can't tell about ambiguity for sure
207 without doing a full simplification. And even that isn't possible if
208 the context has some free vars that may get unified. Urgle!
210 Here's another example: is this ambiguous?
211 forall a b. Eq (T b) => a -> a
212 Not if there's an insance decl (with no context)
213 instance Eq (T b) where ...
215 You may say of this example that we should use the instance decl right
216 away, but you can't always do that:
218 class J a b where ...
219 instance J Int b where ...
221 f :: forall a b. J a b => a -> a
223 (Notice: no functional dependency in J's class decl.)
224 Here f's type is perfectly fine, provided f is only called at Int.
225 It's premature to complain when meeting f's signature, or even
226 when inferring a type for f.
230 However, we don't *need* to report ambiguity right away. It'll always
231 show up at the call site.... and eventually at main, which needs special
232 treatment. Nevertheless, reporting ambiguity promptly is an excellent thing.
234 So here's the plan. We WARN about probable ambiguity if
236 fv(Cq) is not a subset of oclose(fv(T) union fv(G), C)
238 (all tested before quantification).
239 That is, all the type variables in Cq must be fixed by the the variables
240 in the environment, or by the variables in the type.
242 Notice that we union before calling oclose. Here's an example:
244 class J a b c | a b -> c
248 forall b c. (J a b c) => b -> b
250 Only if we union {a} from G with {b} from T before using oclose,
251 do we see that c is fixed.
253 It's a bit vague exactly which C we should use for this oclose call. If we
254 don't fix enough variables we might complain when we shouldn't (see
255 the above nasty example). Nothing will be perfect. That's why we can
256 only issue a warning.
259 Can we ever be *certain* about ambiguity? Yes: if there's a constraint
261 c in C such that fv(c) intersect (fv(G) union fv(T)) = EMPTY
263 then c is a "bubble"; there's no way it can ever improve, and it's
264 certainly ambiguous. UNLESS it is a constant (sigh). And what about
269 instance H x y => K (x,y)
271 Is this type ambiguous?
272 forall a b. (K (a,b), Eq b) => a -> a
274 Urk. The (Eq b) looks "definitely ambiguous" but it isn't. What we are after
275 is a "bubble" that's a set of constraints
277 Cq = Ca union Cq' st fv(Ca) intersect (fv(Cq') union fv(T) union fv(G)) = EMPTY
279 Hence another idea. To decide Q start with fv(T) and grow it
280 by transitive closure in Cq (no functional dependencies involved).
281 Now partition Cq using Q, leaving the definitely-ambiguous and probably-ok.
282 The definitely-ambiguous can then float out, and get smashed at top level
283 (which squashes out the constants, like Eq (T a) above)
286 --------------------------------------
287 Notes on principal types
288 --------------------------------------
293 f x = let g y = op (y::Int) in True
295 Here the principal type of f is (forall a. a->a)
296 but we'll produce the non-principal type
297 f :: forall a. C Int => a -> a
300 --------------------------------------
301 Notes on implicit parameters
302 --------------------------------------
304 Question 1: can we "inherit" implicit parameters
305 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
310 where f is *not* a top-level binding.
311 From the RHS of f we'll get the constraint (?y::Int).
312 There are two types we might infer for f:
316 (so we get ?y from the context of f's definition), or
318 f :: (?y::Int) => Int -> Int
320 At first you might think the first was better, becuase then
321 ?y behaves like a free variable of the definition, rather than
322 having to be passed at each call site. But of course, the WHOLE
323 IDEA is that ?y should be passed at each call site (that's what
324 dynamic binding means) so we'd better infer the second.
326 BOTTOM LINE: when *inferring types* you *must* quantify
327 over implicit parameters. See the predicate isFreeWhenInferring.
330 Question 2: type signatures
331 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
332 BUT WATCH OUT: When you supply a type signature, we can't force you
333 to quantify over implicit parameters. For example:
337 This is perfectly reasonable. We do not want to insist on
339 (?x + 1) :: (?x::Int => Int)
341 That would be silly. Here, the definition site *is* the occurrence site,
342 so the above strictures don't apply. Hence the difference between
343 tcSimplifyCheck (which *does* allow implicit paramters to be inherited)
344 and tcSimplifyCheckBind (which does not).
346 What about when you supply a type signature for a binding?
347 Is it legal to give the following explicit, user type
348 signature to f, thus:
353 At first sight this seems reasonable, but it has the nasty property
354 that adding a type signature changes the dynamic semantics.
357 (let f x = (x::Int) + ?y
358 in (f 3, f 3 with ?y=5)) with ?y = 6
364 in (f 3, f 3 with ?y=5)) with ?y = 6
368 Indeed, simply inlining f (at the Haskell source level) would change the
371 Nevertheless, as Launchbury says (email Oct 01) we can't really give the
372 semantics for a Haskell program without knowing its typing, so if you
373 change the typing you may change the semantics.
375 To make things consistent in all cases where we are *checking* against
376 a supplied signature (as opposed to inferring a type), we adopt the
379 a signature does not need to quantify over implicit params.
381 [This represents a (rather marginal) change of policy since GHC 5.02,
382 which *required* an explicit signature to quantify over all implicit
383 params for the reasons mentioned above.]
385 But that raises a new question. Consider
387 Given (signature) ?x::Int
388 Wanted (inferred) ?x::Int, ?y::Bool
390 Clearly we want to discharge the ?x and float the ?y out. But
391 what is the criterion that distinguishes them? Clearly it isn't
392 what free type variables they have. The Right Thing seems to be
393 to float a constraint that
394 neither mentions any of the quantified type variables
395 nor any of the quantified implicit parameters
397 See the predicate isFreeWhenChecking.
400 Question 3: monomorphism
401 ~~~~~~~~~~~~~~~~~~~~~~~~
402 There's a nasty corner case when the monomorphism restriction bites:
406 The argument above suggests that we *must* generalise
407 over the ?y parameter, to get
408 z :: (?y::Int) => Int,
409 but the monomorphism restriction says that we *must not*, giving
411 Why does the momomorphism restriction say this? Because if you have
413 let z = x + ?y in z+z
415 you might not expect the addition to be done twice --- but it will if
416 we follow the argument of Question 2 and generalise over ?y.
422 (A) Always generalise over implicit parameters
423 Bindings that fall under the monomorphism restriction can't
427 * Inlining remains valid
428 * No unexpected loss of sharing
429 * But simple bindings like
431 will be rejected, unless you add an explicit type signature
432 (to avoid the monomorphism restriction)
433 z :: (?y::Int) => Int
435 This seems unacceptable
437 (B) Monomorphism restriction "wins"
438 Bindings that fall under the monomorphism restriction can't
440 Always generalise over implicit parameters *except* for bindings
441 that fall under the monomorphism restriction
444 * Inlining isn't valid in general
445 * No unexpected loss of sharing
446 * Simple bindings like
448 accepted (get value of ?y from binding site)
450 (C) Always generalise over implicit parameters
451 Bindings that fall under the monomorphism restriction can't
452 be generalised, EXCEPT for implicit parameters
454 * Inlining remains valid
455 * Unexpected loss of sharing (from the extra generalisation)
456 * Simple bindings like
458 accepted (get value of ?y from occurrence sites)
463 None of these choices seems very satisfactory. But at least we should
464 decide which we want to do.
466 It's really not clear what is the Right Thing To Do. If you see
470 would you expect the value of ?y to be got from the *occurrence sites*
471 of 'z', or from the valuue of ?y at the *definition* of 'z'? In the
472 case of function definitions, the answer is clearly the former, but
473 less so in the case of non-fucntion definitions. On the other hand,
474 if we say that we get the value of ?y from the definition site of 'z',
475 then inlining 'z' might change the semantics of the program.
477 Choice (C) really says "the monomorphism restriction doesn't apply
478 to implicit parameters". Which is fine, but remember that every
479 innocent binding 'x = ...' that mentions an implicit parameter in
480 the RHS becomes a *function* of that parameter, called at each
481 use of 'x'. Now, the chances are that there are no intervening 'with'
482 clauses that bind ?y, so a decent compiler should common up all
483 those function calls. So I think I strongly favour (C). Indeed,
484 one could make a similar argument for abolishing the monomorphism
485 restriction altogether.
487 BOTTOM LINE: we choose (B) at present. See tcSimplifyRestricted
491 %************************************************************************
493 \subsection{tcSimplifyInfer}
495 %************************************************************************
497 tcSimplify is called when we *inferring* a type. Here's the overall game plan:
499 1. Compute Q = grow( fvs(T), C )
501 2. Partition C based on Q into Ct and Cq. Notice that ambiguous
502 predicates will end up in Ct; we deal with them at the top level
504 3. Try improvement, using functional dependencies
506 4. If Step 3 did any unification, repeat from step 1
507 (Unification can change the result of 'grow'.)
509 Note: we don't reduce dictionaries in step 2. For example, if we have
510 Eq (a,b), we don't simplify to (Eq a, Eq b). So Q won't be different
511 after step 2. However note that we may therefore quantify over more
512 type variables than we absolutely have to.
514 For the guts, we need a loop, that alternates context reduction and
515 improvement with unification. E.g. Suppose we have
517 class C x y | x->y where ...
519 and tcSimplify is called with:
521 Then improvement unifies a with b, giving
524 If we need to unify anything, we rattle round the whole thing all over
531 -> TcTyVarSet -- fv(T); type vars
533 -> TcM ([TcTyVar], -- Tyvars to quantify (zonked)
535 TcDictBinds, -- Bindings
536 [TcId]) -- Dict Ids that must be bound here (zonked)
541 tcSimplifyInfer doc tau_tvs wanted_lie
542 = inferLoop doc (varSetElems tau_tvs)
543 (lieToList wanted_lie) `thenTc` \ (qtvs, frees, binds, irreds) ->
545 -- Check for non-generalisable insts
546 mapTc_ addCantGenErr (filter (not . instCanBeGeneralised) irreds) `thenTc_`
548 returnTc (qtvs, mkLIE frees, binds, map instToId irreds)
550 inferLoop doc tau_tvs wanteds
552 zonkTcTyVarsAndFV tau_tvs `thenNF_Tc` \ tau_tvs' ->
553 mapNF_Tc zonkInst wanteds `thenNF_Tc` \ wanteds' ->
554 tcGetGlobalTyVars `thenNF_Tc` \ gbl_tvs ->
556 preds = predsOfInsts wanteds'
557 qtvs = grow preds tau_tvs' `minusVarSet` oclose preds gbl_tvs
560 | isFreeWhenInferring qtvs inst = Free
561 | isClassDict inst = DontReduceUnlessConstant -- Dicts
562 | otherwise = ReduceMe -- Lits and Methods
565 reduceContext doc try_me [] wanteds' `thenTc` \ (no_improvement, frees, binds, irreds) ->
568 if no_improvement then
569 returnTc (varSetElems qtvs, frees, binds, irreds)
571 -- If improvement did some unification, we go round again. There
572 -- are two subtleties:
573 -- a) We start again with irreds, not wanteds
574 -- Using an instance decl might have introduced a fresh type variable
575 -- which might have been unified, so we'd get an infinite loop
576 -- if we started again with wanteds! See example [LOOP]
578 -- b) It's also essential to re-process frees, because unification
579 -- might mean that a type variable that looked free isn't now.
581 -- Hence the (irreds ++ frees)
583 -- However, NOTICE that when we are done, we might have some bindings, but
584 -- the final qtvs might be empty. See [NO TYVARS] below.
586 inferLoop doc tau_tvs (irreds ++ frees) `thenTc` \ (qtvs1, frees1, binds1, irreds1) ->
587 returnTc (qtvs1, frees1, binds `AndMonoBinds` binds1, irreds1)
592 class If b t e r | b t e -> r
595 class Lte a b c | a b -> c where lte :: a -> b -> c
597 instance (Lte a b l,If l b a c) => Max a b c
599 Wanted: Max Z (S x) y
601 Then we'll reduce using the Max instance to:
602 (Lte Z (S x) l, If l (S x) Z y)
603 and improve by binding l->T, after which we can do some reduction
604 on both the Lte and If constraints. What we *can't* do is start again
605 with (Max Z (S x) y)!
609 class Y a b | a -> b where
612 instance Y [[a]] a where
615 k :: X a -> X a -> X a
617 g :: Num a => [X a] -> [X a]
620 h ys = ys ++ map (k (y [[0]])) xs
622 The excitement comes when simplifying the bindings for h. Initially
623 try to simplify {y @ [[t1]] t2, 0 @ t1}, with initial qtvs = {t2}.
624 From this we get t1:=:t2, but also various bindings. We can't forget
625 the bindings (because of [LOOP]), but in fact t1 is what g is
628 The net effect of [NO TYVARS]
631 isFreeWhenInferring :: TyVarSet -> Inst -> Bool
632 isFreeWhenInferring qtvs inst
633 = isFreeWrtTyVars qtvs inst -- Constrains no quantified vars
634 && all inheritablePred (predsOfInst inst) -- And no implicit parameter involved
635 -- (see "Notes on implicit parameters")
637 isFreeWhenChecking :: TyVarSet -- Quantified tyvars
638 -> NameSet -- Quantified implicit parameters
640 isFreeWhenChecking qtvs ips inst
641 = isFreeWrtTyVars qtvs inst
642 && isFreeWrtIPs ips inst
644 isFreeWrtTyVars qtvs inst = not (tyVarsOfInst inst `intersectsVarSet` qtvs)
645 isFreeWrtIPs ips inst = not (any (`elemNameSet` ips) (ipNamesOfInst inst))
649 %************************************************************************
651 \subsection{tcSimplifyCheck}
653 %************************************************************************
655 @tcSimplifyCheck@ is used when we know exactly the set of variables
656 we are going to quantify over. For example, a class or instance declaration.
661 -> [TcTyVar] -- Quantify over these
665 TcDictBinds) -- Bindings
667 -- tcSimplifyCheck is used when checking expression type signatures,
668 -- class decls, instance decls etc.
669 -- Note that we psss isFree (not isFreeAndInheritable) to tcSimplCheck
670 -- It's important that we can float out non-inheritable predicates
671 -- Example: (?x :: Int) is ok!
672 tcSimplifyCheck doc qtvs givens wanted_lie
673 = tcSimplCheck doc get_qtvs
674 givens wanted_lie `thenTc` \ (qtvs', frees, binds) ->
675 returnTc (frees, binds)
677 get_qtvs = zonkTcTyVarsAndFV qtvs
680 -- tcSimplifyInferCheck is used when we know the constraints we are to simplify
681 -- against, but we don't know the type variables over which we are going to quantify.
682 -- This happens when we have a type signature for a mutually recursive group
685 -> TcTyVarSet -- fv(T)
688 -> TcM ([TcTyVar], -- Variables over which to quantify
690 TcDictBinds) -- Bindings
692 tcSimplifyInferCheck doc tau_tvs givens wanted_lie
693 = tcSimplCheck doc get_qtvs givens wanted_lie
695 -- Figure out which type variables to quantify over
696 -- You might think it should just be the signature tyvars,
697 -- but in bizarre cases you can get extra ones
698 -- f :: forall a. Num a => a -> a
699 -- f x = fst (g (x, head [])) + 1
701 -- Here we infer g :: forall a b. a -> b -> (b,a)
702 -- We don't want g to be monomorphic in b just because
703 -- f isn't quantified over b.
704 all_tvs = varSetElems (tau_tvs `unionVarSet` tyVarsOfInsts givens)
706 get_qtvs = zonkTcTyVarsAndFV all_tvs `thenNF_Tc` \ all_tvs' ->
707 tcGetGlobalTyVars `thenNF_Tc` \ gbl_tvs ->
709 qtvs = all_tvs' `minusVarSet` gbl_tvs
710 -- We could close gbl_tvs, but its not necessary for
711 -- soundness, and it'll only affect which tyvars, not which
712 -- dictionaries, we quantify over
717 Here is the workhorse function for all three wrappers.
720 tcSimplCheck doc get_qtvs givens wanted_lie
721 = check_loop givens (lieToList wanted_lie) `thenTc` \ (qtvs, frees, binds, irreds) ->
723 -- Complain about any irreducible ones
724 complainCheck doc givens irreds `thenNF_Tc_`
727 returnTc (qtvs, mkLIE frees, binds)
730 ip_set = mkNameSet (ipNamesOfInsts givens)
732 check_loop givens wanteds
734 mapNF_Tc zonkInst givens `thenNF_Tc` \ givens' ->
735 mapNF_Tc zonkInst wanteds `thenNF_Tc` \ wanteds' ->
736 get_qtvs `thenNF_Tc` \ qtvs' ->
740 -- When checking against a given signature we always reduce
741 -- until we find a match against something given, or can't reduce
742 try_me inst | isFreeWhenChecking qtvs' ip_set inst = Free
743 | otherwise = ReduceMe
745 reduceContext doc try_me givens' wanteds' `thenTc` \ (no_improvement, frees, binds, irreds) ->
748 if no_improvement then
749 returnTc (varSetElems qtvs', frees, binds, irreds)
751 check_loop givens' (irreds ++ frees) `thenTc` \ (qtvs', frees1, binds1, irreds1) ->
752 returnTc (qtvs', frees1, binds `AndMonoBinds` binds1, irreds1)
756 %************************************************************************
758 \subsection{tcSimplifyRestricted}
760 %************************************************************************
763 tcSimplifyRestricted -- Used for restricted binding groups
764 -- i.e. ones subject to the monomorphism restriction
766 -> TcTyVarSet -- Free in the type of the RHSs
767 -> LIE -- Free in the RHSs
768 -> TcM ([TcTyVar], -- Tyvars to quantify (zonked)
770 TcDictBinds) -- Bindings
772 tcSimplifyRestricted doc tau_tvs wanted_lie
773 = -- First squash out all methods, to find the constrained tyvars
774 -- We can't just take the free vars of wanted_lie because that'll
775 -- have methods that may incidentally mention entirely unconstrained variables
776 -- e.g. a call to f :: Eq a => a -> b -> b
777 -- Here, b is unconstrained. A good example would be
779 -- We want to infer the polymorphic type
780 -- foo :: forall b. b -> b
782 wanteds = lieToList wanted_lie
783 try_me inst = ReduceMe -- Reduce as far as we can. Don't stop at
784 -- dicts; the idea is to get rid of as many type
785 -- variables as possible, and we don't want to stop
786 -- at (say) Monad (ST s), because that reduces
787 -- immediately, with no constraint on s.
789 simpleReduceLoop doc try_me wanteds `thenTc` \ (_, _, constrained_dicts) ->
791 -- Next, figure out the tyvars we will quantify over
792 zonkTcTyVarsAndFV (varSetElems tau_tvs) `thenNF_Tc` \ tau_tvs' ->
793 tcGetGlobalTyVars `thenNF_Tc` \ gbl_tvs ->
795 constrained_tvs = tyVarsOfInsts constrained_dicts
796 qtvs = (tau_tvs' `minusVarSet` oclose (predsOfInsts constrained_dicts) gbl_tvs)
797 `minusVarSet` constrained_tvs
800 -- The first step may have squashed more methods than
801 -- necessary, so try again, this time knowing the exact
802 -- set of type variables to quantify over.
804 -- We quantify only over constraints that are captured by qtvs;
805 -- these will just be a subset of non-dicts. This in contrast
806 -- to normal inference (using isFreeWhenInferring) in which we quantify over
807 -- all *non-inheritable* constraints too. This implements choice
808 -- (B) under "implicit parameter and monomorphism" above.
810 -- Remember that we may need to do *some* simplification, to
811 -- (for example) squash {Monad (ST s)} into {}. It's not enough
812 -- just to float all constraints
813 mapNF_Tc zonkInst (lieToList wanted_lie) `thenNF_Tc` \ wanteds' ->
815 try_me inst | isFreeWrtTyVars qtvs inst = Free
816 | otherwise = ReduceMe
818 reduceContext doc try_me [] wanteds' `thenTc` \ (no_improvement, frees, binds, irreds) ->
819 ASSERT( no_improvement )
820 ASSERT( null irreds )
821 -- No need to loop because simpleReduceLoop will have
822 -- already done any improvement necessary
824 returnTc (varSetElems qtvs, mkLIE frees, binds)
828 %************************************************************************
830 \subsection{tcSimplifyToDicts}
832 %************************************************************************
834 On the LHS of transformation rules we only simplify methods and constants,
835 getting dictionaries. We want to keep all of them unsimplified, to serve
836 as the available stuff for the RHS of the rule.
838 The same thing is used for specialise pragmas. Consider
841 {-# SPECIALISE f :: Int -> Int #-}
844 The type checker generates a binding like:
846 f_spec = (f :: Int -> Int)
848 and we want to end up with
850 f_spec = _inline_me_ (f Int dNumInt)
852 But that means that we must simplify the Method for f to (f Int dNumInt)!
853 So tcSimplifyToDicts squeezes out all Methods.
855 IMPORTANT NOTE: we *don't* want to do superclass commoning up. Consider
857 fromIntegral :: (Integral a, Num b) => a -> b
858 {-# RULES "foo" fromIntegral = id :: Int -> Int #-}
860 Here, a=b=Int, and Num Int is a superclass of Integral Int. But we *dont*
864 fromIntegral Int Int dIntegralInt (scsel dIntegralInt) = id Int
866 because the scsel will mess up matching. Instead we want
868 forall dIntegralInt, dNumInt.
869 fromIntegral Int Int dIntegralInt dNumInt = id Int
871 Hence "DontReduce NoSCs"
874 tcSimplifyToDicts :: LIE -> TcM ([Inst], TcDictBinds)
875 tcSimplifyToDicts wanted_lie
876 = simpleReduceLoop doc try_me wanteds `thenTc` \ (frees, binds, irreds) ->
877 -- Since try_me doesn't look at types, we don't need to
878 -- do any zonking, so it's safe to call reduceContext directly
880 returnTc (irreds, binds)
883 doc = text "tcSimplifyToDicts"
884 wanteds = lieToList wanted_lie
886 -- Reduce methods and lits only; stop as soon as we get a dictionary
887 try_me inst | isDict inst = DontReduce NoSCs
888 | otherwise = ReduceMe
892 %************************************************************************
894 \subsection{Filtering at a dynamic binding}
896 %************************************************************************
901 we must discharge all the ?x constraints from B. We also do an improvement
902 step; if we have ?x::t1 and ?x::t2 we must unify t1, t2.
904 Actually, the constraints from B might improve the types in ?x. For example
906 f :: (?x::Int) => Char -> Char
909 then the constraint (?x::Int) arising from the call to f will
910 force the binding for ?x to be of type Int.
913 tcSimplifyIPs :: [Inst] -- The implicit parameters bound here
915 -> TcM (LIE, TcDictBinds)
916 tcSimplifyIPs given_ips wanted_lie
917 = simpl_loop given_ips wanteds `thenTc` \ (frees, binds) ->
918 returnTc (mkLIE frees, binds)
920 doc = text "tcSimplifyIPs" <+> ppr given_ips
921 wanteds = lieToList wanted_lie
922 ip_set = mkNameSet (ipNamesOfInsts given_ips)
924 -- Simplify any methods that mention the implicit parameter
925 try_me inst | isFreeWrtIPs ip_set inst = Free
926 | otherwise = ReduceMe
928 simpl_loop givens wanteds
929 = mapNF_Tc zonkInst givens `thenNF_Tc` \ givens' ->
930 mapNF_Tc zonkInst wanteds `thenNF_Tc` \ wanteds' ->
932 reduceContext doc try_me givens' wanteds' `thenTc` \ (no_improvement, frees, binds, irreds) ->
934 if no_improvement then
935 ASSERT( null irreds )
936 returnTc (frees, binds)
938 simpl_loop givens' (irreds ++ frees) `thenTc` \ (frees1, binds1) ->
939 returnTc (frees1, binds `AndMonoBinds` binds1)
943 %************************************************************************
945 \subsection[binds-for-local-funs]{@bindInstsOfLocalFuns@}
947 %************************************************************************
949 When doing a binding group, we may have @Insts@ of local functions.
950 For example, we might have...
952 let f x = x + 1 -- orig local function (overloaded)
953 f.1 = f Int -- two instances of f
958 The point is: we must drop the bindings for @f.1@ and @f.2@ here,
959 where @f@ is in scope; those @Insts@ must certainly not be passed
960 upwards towards the top-level. If the @Insts@ were binding-ified up
961 there, they would have unresolvable references to @f@.
963 We pass in an @init_lie@ of @Insts@ and a list of locally-bound @Ids@.
964 For each method @Inst@ in the @init_lie@ that mentions one of the
965 @Ids@, we create a binding. We return the remaining @Insts@ (in an
966 @LIE@), as well as the @HsBinds@ generated.
969 bindInstsOfLocalFuns :: LIE -> [TcId] -> TcM (LIE, TcMonoBinds)
971 bindInstsOfLocalFuns init_lie local_ids
972 | null overloaded_ids
974 = returnTc (init_lie, EmptyMonoBinds)
977 = simpleReduceLoop doc try_me wanteds `thenTc` \ (frees, binds, irreds) ->
978 ASSERT( null irreds )
979 returnTc (mkLIE frees, binds)
981 doc = text "bindInsts" <+> ppr local_ids
982 wanteds = lieToList init_lie
983 overloaded_ids = filter is_overloaded local_ids
984 is_overloaded id = isOverloadedTy (idType id)
986 overloaded_set = mkVarSet overloaded_ids -- There can occasionally be a lot of them
987 -- so it's worth building a set, so that
988 -- lookup (in isMethodFor) is faster
990 try_me inst | isMethodFor overloaded_set inst = ReduceMe
995 %************************************************************************
997 \subsection{Data types for the reduction mechanism}
999 %************************************************************************
1001 The main control over context reduction is here
1005 = ReduceMe -- Try to reduce this
1006 -- If there's no instance, behave exactly like
1007 -- DontReduce: add the inst to
1008 -- the irreductible ones, but don't
1009 -- produce an error message of any kind.
1010 -- It might be quite legitimate such as (Eq a)!
1012 | DontReduce WantSCs -- Return as irreducible
1014 | DontReduceUnlessConstant -- Return as irreducible unless it can
1015 -- be reduced to a constant in one step
1017 | Free -- Return as free
1019 data WantSCs = NoSCs | AddSCs -- Tells whether we should add the superclasses
1020 -- of a predicate when adding it to the avails
1026 type RedState = (Avails, -- What's available
1027 [Inst]) -- Insts for which try_me returned Free
1029 type Avails = FiniteMap Inst Avail
1032 = Irred -- Used for irreducible dictionaries,
1033 -- which are going to be lambda bound
1035 | BoundTo TcId -- Used for dictionaries for which we have a binding
1036 -- e.g. those "given" in a signature
1038 | NoRhs -- Used for Insts like (CCallable f)
1039 -- where no witness is required.
1041 | Rhs -- Used when there is a RHS
1043 [Inst] -- Insts free in the RHS; we need these too
1045 pprAvails avails = vcat [ppr inst <+> equals <+> pprAvail avail
1046 | (inst,avail) <- fmToList avails ]
1048 instance Outputable Avail where
1051 pprAvail NoRhs = text "<no rhs>"
1052 pprAvail Irred = text "Irred"
1053 pprAvail (BoundTo x) = text "Bound to" <+> ppr x
1054 pprAvail (Rhs rhs bs) = ppr rhs <+> braces (ppr bs)
1057 Extracting the bindings from a bunch of Avails.
1058 The bindings do *not* come back sorted in dependency order.
1059 We assume that they'll be wrapped in a big Rec, so that the
1060 dependency analyser can sort them out later
1064 bindsAndIrreds :: Avails
1066 -> (TcDictBinds, -- Bindings
1067 [Inst]) -- Irreducible ones
1069 bindsAndIrreds avails wanteds
1070 = go avails EmptyMonoBinds [] wanteds
1072 go avails binds irreds [] = (binds, irreds)
1074 go avails binds irreds (w:ws)
1075 = case lookupFM avails w of
1076 Nothing -> -- Free guys come out here
1077 -- (If we didn't do addFree we could use this as the
1078 -- criterion for free-ness, and pick up the free ones here too)
1079 go avails binds irreds ws
1081 Just NoRhs -> go avails binds irreds ws
1083 Just Irred -> go (addToFM avails w (BoundTo (instToId w))) binds (w:irreds) ws
1085 Just (BoundTo id) -> go avails new_binds irreds ws
1087 -- For implicit parameters, all occurrences share the same
1088 -- Id, so there is no need for synonym bindings
1089 new_binds | new_id == id = binds
1090 | otherwise = addBind binds new_id (HsVar id)
1093 Just (Rhs rhs ws') -> go avails' (addBind binds id rhs) irreds (ws' ++ ws)
1096 avails' = addToFM avails w (BoundTo id)
1098 addBind binds id rhs = binds `AndMonoBinds` VarMonoBind id rhs
1102 %************************************************************************
1104 \subsection[reduce]{@reduce@}
1106 %************************************************************************
1108 When the "what to do" predicate doesn't depend on the quantified type variables,
1109 matters are easier. We don't need to do any zonking, unless the improvement step
1110 does something, in which case we zonk before iterating.
1112 The "given" set is always empty.
1115 simpleReduceLoop :: SDoc
1116 -> (Inst -> WhatToDo) -- What to do, *not* based on the quantified type variables
1118 -> TcM ([Inst], -- Free
1120 [Inst]) -- Irreducible
1122 simpleReduceLoop doc try_me wanteds
1123 = mapNF_Tc zonkInst wanteds `thenNF_Tc` \ wanteds' ->
1124 reduceContext doc try_me [] wanteds' `thenTc` \ (no_improvement, frees, binds, irreds) ->
1125 if no_improvement then
1126 returnTc (frees, binds, irreds)
1128 simpleReduceLoop doc try_me (irreds ++ frees) `thenTc` \ (frees1, binds1, irreds1) ->
1129 returnTc (frees1, binds `AndMonoBinds` binds1, irreds1)
1135 reduceContext :: SDoc
1136 -> (Inst -> WhatToDo)
1139 -> NF_TcM (Bool, -- True <=> improve step did no unification
1141 TcDictBinds, -- Dictionary bindings
1142 [Inst]) -- Irreducible
1144 reduceContext doc try_me givens wanteds
1146 traceTc (text "reduceContext" <+> (vcat [
1147 text "----------------------",
1149 text "given" <+> ppr givens,
1150 text "wanted" <+> ppr wanteds,
1151 text "----------------------"
1154 -- Build the Avail mapping from "givens"
1155 foldlNF_Tc addGiven (emptyFM, []) givens `thenNF_Tc` \ init_state ->
1158 reduceList (0,[]) try_me wanteds init_state `thenNF_Tc` \ state@(avails, frees) ->
1160 -- Do improvement, using everything in avails
1161 -- In particular, avails includes all superclasses of everything
1162 tcImprove avails `thenTc` \ no_improvement ->
1164 traceTc (text "reduceContext end" <+> (vcat [
1165 text "----------------------",
1167 text "given" <+> ppr givens,
1168 text "wanted" <+> ppr wanteds,
1170 text "avails" <+> pprAvails avails,
1171 text "frees" <+> ppr frees,
1172 text "no_improvement =" <+> ppr no_improvement,
1173 text "----------------------"
1176 (binds, irreds) = bindsAndIrreds avails wanteds
1178 returnTc (no_improvement, frees, binds, irreds)
1181 = tcGetInstEnv `thenTc` \ inst_env ->
1183 preds = [ (pred, pp_loc)
1184 | inst <- keysFM avails,
1185 let pp_loc = pprInstLoc (instLoc inst),
1186 pred <- predsOfInst inst,
1189 -- Avails has all the superclasses etc (good)
1190 -- It also has all the intermediates of the deduction (good)
1191 -- It does not have duplicates (good)
1192 -- NB that (?x::t1) and (?x::t2) will be held separately in avails
1193 -- so that improve will see them separate
1194 eqns = improve (classInstEnv inst_env) preds
1199 traceTc (ptext SLIT("Improve:") <+> vcat (map pprEquationDoc eqns)) `thenNF_Tc_`
1200 mapTc_ unify eqns `thenTc_`
1203 unify ((qtvs, t1, t2), doc)
1204 = tcAddErrCtxt doc $
1205 tcInstTyVars (varSetElems qtvs) `thenNF_Tc` \ (_, _, tenv) ->
1206 unifyTauTy (substTy tenv t1) (substTy tenv t2)
1209 The main context-reduction function is @reduce@. Here's its game plan.
1212 reduceList :: (Int,[Inst]) -- Stack (for err msgs)
1213 -- along with its depth
1214 -> (Inst -> WhatToDo)
1221 try_me: given an inst, this function returns
1223 DontReduce return this in "irreds"
1224 Free return this in "frees"
1226 wanteds: The list of insts to reduce
1227 state: An accumulating parameter of type RedState
1228 that contains the state of the algorithm
1230 It returns a RedState.
1232 The (n,stack) pair is just used for error reporting.
1233 n is always the depth of the stack.
1234 The stack is the stack of Insts being reduced: to produce X
1235 I had to produce Y, to produce Y I had to produce Z, and so on.
1238 reduceList (n,stack) try_me wanteds state
1239 | n > opt_MaxContextReductionDepth
1240 = failWithTc (reduceDepthErr n stack)
1246 pprTrace "Jeepers! ReduceContext:" (reduceDepthMsg n stack)
1251 go [] state = returnTc state
1252 go (w:ws) state = reduce (n+1, w:stack) try_me w state `thenTc` \ state' ->
1255 -- Base case: we're done!
1256 reduce stack try_me wanted state
1257 -- It's the same as an existing inst, or a superclass thereof
1258 | isAvailable state wanted
1262 = case try_me wanted of {
1264 DontReduce want_scs -> addIrred want_scs state wanted
1266 ; DontReduceUnlessConstant -> -- It's irreducible (or at least should not be reduced)
1267 -- First, see if the inst can be reduced to a constant in one step
1268 try_simple (addIrred AddSCs) -- Assume want superclasses
1270 ; Free -> -- It's free so just chuck it upstairs
1271 -- First, see if the inst can be reduced to a constant in one step
1274 ; ReduceMe -> -- It should be reduced
1275 lookupInst wanted `thenNF_Tc` \ lookup_result ->
1276 case lookup_result of
1277 GenInst wanteds' rhs -> reduceList stack try_me wanteds' state `thenTc` \ state' ->
1278 addWanted state' wanted rhs wanteds'
1279 SimpleInst rhs -> addWanted state wanted rhs []
1281 NoInstance -> -- No such instance!
1282 -- Add it and its superclasses
1283 addIrred AddSCs state wanted
1287 try_simple do_this_otherwise
1288 = lookupInst wanted `thenNF_Tc` \ lookup_result ->
1289 case lookup_result of
1290 SimpleInst rhs -> addWanted state wanted rhs []
1291 other -> do_this_otherwise state wanted
1296 isAvailable :: RedState -> Inst -> Bool
1297 isAvailable (avails, _) wanted = wanted `elemFM` avails
1298 -- NB: the Ord instance of Inst compares by the class/type info
1299 -- *not* by unique. So
1300 -- d1::C Int == d2::C Int
1302 -------------------------
1303 addFree :: RedState -> Inst -> NF_TcM RedState
1304 -- When an Inst is tossed upstairs as 'free' we nevertheless add it
1305 -- to avails, so that any other equal Insts will be commoned up right
1306 -- here rather than also being tossed upstairs. This is really just
1307 -- an optimisation, and perhaps it is more trouble that it is worth,
1308 -- as the following comments show!
1310 -- NB1: do *not* add superclasses. If we have
1313 -- but a is not bound here, then we *don't* want to derive
1314 -- dn from df here lest we lose sharing.
1316 -- NB2: do *not* add the Inst to avails at all if it's a method.
1317 -- The following situation shows why this is bad:
1318 -- truncate :: forall a. RealFrac a => forall b. Integral b => a -> b
1319 -- From an application (truncate f i) we get
1320 -- t1 = truncate at f
1322 -- If we have also have a second occurrence of truncate, we get
1323 -- t3 = truncate at f
1325 -- When simplifying with i,f free, we might still notice that
1326 -- t1=t3; but alas, the binding for t2 (which mentions t1)
1327 -- will continue to float out!
1328 -- Solution: never put methods in avail till they are captured
1329 -- in which case addFree isn't used
1331 -- NB3: make sure that CCallable/CReturnable use NoRhs rather
1332 -- than BoundTo, else we end up with bogus bindings.
1333 -- c.f. instBindingRequired in addWanted
1334 addFree (avails, frees) free
1335 | isDict free = returnNF_Tc (addToFM avails free avail, free:frees)
1336 | otherwise = returnNF_Tc (avails, free:frees)
1338 avail | instBindingRequired free = BoundTo (instToId free)
1341 addWanted :: RedState -> Inst -> TcExpr -> [Inst] -> NF_TcM RedState
1342 addWanted state@(avails, frees) wanted rhs_expr wanteds
1343 -- Do *not* add superclasses as well. Here's an example of why not
1344 -- class Eq a => Foo a b
1345 -- instance Eq a => Foo [a] a
1346 -- If we are reducing
1348 -- we'll first deduce that it holds (via the instance decl). We
1349 -- must not then overwrite the Eq t constraint with a superclass selection!
1350 -- ToDo: this isn't entirely unsatisfactory, because
1351 -- we may also lose some entirely-legitimate sharing this way
1353 = ASSERT( not (isAvailable state wanted) )
1354 returnNF_Tc (addToFM avails wanted avail, frees)
1356 avail | instBindingRequired wanted = Rhs rhs_expr wanteds
1357 | otherwise = ASSERT( null wanteds ) NoRhs
1359 addGiven :: RedState -> Inst -> NF_TcM RedState
1360 addGiven state given = addAvailAndSCs state given (BoundTo (instToId given))
1362 addIrred :: WantSCs -> RedState -> Inst -> NF_TcM RedState
1363 addIrred NoSCs (avails,frees) irred = returnNF_Tc (addToFM avails irred Irred, frees)
1364 addIrred AddSCs state irred = addAvailAndSCs state irred Irred
1366 addAvailAndSCs :: RedState -> Inst -> Avail -> NF_TcM RedState
1367 addAvailAndSCs (avails, frees) wanted avail
1368 = add_avail_and_scs avails wanted avail `thenNF_Tc` \ avails' ->
1369 returnNF_Tc (avails', frees)
1371 ---------------------
1372 add_avail_and_scs :: Avails -> Inst -> Avail -> NF_TcM Avails
1373 add_avail_and_scs avails wanted avail
1374 = add_scs (addToFM avails wanted avail) wanted
1376 add_scs :: Avails -> Inst -> NF_TcM Avails
1377 -- Add all the superclasses of the Inst to Avails
1378 -- Invariant: the Inst is already in Avails.
1381 | not (isClassDict dict)
1382 = returnNF_Tc avails
1384 | otherwise -- It is a dictionary
1385 = newDictsFromOld dict sc_theta' `thenNF_Tc` \ sc_dicts ->
1386 foldlNF_Tc add_sc avails (zipEqual "add_scs" sc_dicts sc_sels)
1388 (clas, tys) = getDictClassTys dict
1389 (tyvars, sc_theta, sc_sels, _) = classBigSig clas
1390 sc_theta' = substTheta (mkTopTyVarSubst tyvars tys) sc_theta
1392 add_sc avails (sc_dict, sc_sel) -- Add it, and its superclasses
1393 = case lookupFM avails sc_dict of
1394 Just (BoundTo _) -> returnNF_Tc avails -- See Note [SUPER] below
1395 other -> add_avail_and_scs avails sc_dict avail
1397 sc_sel_rhs = DictApp (TyApp (HsVar sc_sel) tys) [instToId dict]
1398 avail = Rhs sc_sel_rhs [dict]
1401 Note [SUPER]. We have to be careful here. If we are *given* d1:Ord a,
1402 and want to deduce (d2:C [a]) where
1404 class Ord a => C a where
1405 instance Ord a => C [a] where ...
1407 Then we'll use the instance decl to deduce C [a] and then add the
1408 superclasses of C [a] to avails. But we must not overwrite the binding
1409 for d1:Ord a (which is given) with a superclass selection or we'll just
1410 build a loop! Hence looking for BoundTo. Crudely, BoundTo is cheaper
1414 %************************************************************************
1416 \section{tcSimplifyTop: defaulting}
1418 %************************************************************************
1421 If a dictionary constrains a type variable which is
1422 * not mentioned in the environment
1423 * and not mentioned in the type of the expression
1424 then it is ambiguous. No further information will arise to instantiate
1425 the type variable; nor will it be generalised and turned into an extra
1426 parameter to a function.
1428 It is an error for this to occur, except that Haskell provided for
1429 certain rules to be applied in the special case of numeric types.
1431 * at least one of its classes is a numeric class, and
1432 * all of its classes are numeric or standard
1433 then the type variable can be defaulted to the first type in the
1434 default-type list which is an instance of all the offending classes.
1436 So here is the function which does the work. It takes the ambiguous
1437 dictionaries and either resolves them (producing bindings) or
1438 complains. It works by splitting the dictionary list by type
1439 variable, and using @disambigOne@ to do the real business.
1441 @tcSimplifyTop@ is called once per module to simplify all the constant
1442 and ambiguous Insts.
1444 We need to be careful of one case. Suppose we have
1446 instance Num a => Num (Foo a b) where ...
1448 and @tcSimplifyTop@ is given a constraint (Num (Foo x y)). Then it'll simplify
1449 to (Num x), and default x to Int. But what about y??
1451 It's OK: the final zonking stage should zap y to (), which is fine.
1455 tcSimplifyTop :: LIE -> TcM TcDictBinds
1456 tcSimplifyTop wanted_lie
1457 = simpleReduceLoop (text "tcSimplTop") try_me wanteds `thenTc` \ (frees, binds, irreds) ->
1458 ASSERT( null frees )
1461 -- All the non-std ones are definite errors
1462 (stds, non_stds) = partition isStdClassTyVarDict irreds
1464 -- Group by type variable
1465 std_groups = equivClasses cmp_by_tyvar stds
1467 -- Pick the ones which its worth trying to disambiguate
1468 (std_oks, std_bads) = partition worth_a_try std_groups
1470 -- Have a try at disambiguation
1471 -- if the type variable isn't bound
1472 -- up with one of the non-standard classes
1473 worth_a_try group@(d:_) = not (non_std_tyvars `intersectsVarSet` tyVarsOfInst d)
1474 non_std_tyvars = unionVarSets (map tyVarsOfInst non_stds)
1476 -- Collect together all the bad guys
1477 bad_guys = non_stds ++ concat std_bads
1479 -- Disambiguate the ones that look feasible
1480 mapTc disambigGroup std_oks `thenTc` \ binds_ambig ->
1482 -- And complain about the ones that don't
1483 -- This group includes both non-existent instances
1484 -- e.g. Num (IO a) and Eq (Int -> Int)
1485 -- and ambiguous dictionaries
1487 addTopAmbigErrs bad_guys `thenNF_Tc_`
1489 returnTc (binds `andMonoBinds` andMonoBindList binds_ambig)
1491 wanteds = lieToList wanted_lie
1492 try_me inst = ReduceMe
1494 d1 `cmp_by_tyvar` d2 = get_tv d1 `compare` get_tv d2
1496 get_tv d = case getDictClassTys d of
1497 (clas, [ty]) -> tcGetTyVar "tcSimplify" ty
1498 get_clas d = case getDictClassTys d of
1499 (clas, [ty]) -> clas
1502 @disambigOne@ assumes that its arguments dictionaries constrain all
1503 the same type variable.
1505 ADR Comment 20/6/94: I've changed the @CReturnable@ case to default to
1506 @()@ instead of @Int@. I reckon this is the Right Thing to do since
1507 the most common use of defaulting is code like:
1509 _ccall_ foo `seqPrimIO` bar
1511 Since we're not using the result of @foo@, the result if (presumably)
1515 disambigGroup :: [Inst] -- All standard classes of form (C a)
1519 | any isNumericClass classes -- Guaranteed all standard classes
1520 -- see comment at the end of function for reasons as to
1521 -- why the defaulting mechanism doesn't apply to groups that
1522 -- include CCallable or CReturnable dicts.
1523 && not (any isCcallishClass classes)
1524 = -- THE DICTS OBEY THE DEFAULTABLE CONSTRAINT
1525 -- SO, TRY DEFAULT TYPES IN ORDER
1527 -- Failure here is caused by there being no type in the
1528 -- default list which can satisfy all the ambiguous classes.
1529 -- For example, if Real a is reqd, but the only type in the
1530 -- default list is Int.
1531 tcGetDefaultTys `thenNF_Tc` \ default_tys ->
1533 try_default [] -- No defaults work, so fail
1536 try_default (default_ty : default_tys)
1537 = tryTc_ (try_default default_tys) $ -- If default_ty fails, we try
1538 -- default_tys instead
1539 tcSimplifyCheckThetas [] theta `thenTc` \ _ ->
1542 theta = [mkClassPred clas [default_ty] | clas <- classes]
1544 -- See if any default works, and if so bind the type variable to it
1545 -- If not, add an AmbigErr
1546 recoverTc (addAmbigErrs dicts `thenNF_Tc_`
1547 returnTc EmptyMonoBinds) $
1549 try_default default_tys `thenTc` \ chosen_default_ty ->
1551 -- Bind the type variable and reduce the context, for real this time
1552 unifyTauTy chosen_default_ty (mkTyVarTy tyvar) `thenTc_`
1553 simpleReduceLoop (text "disambig" <+> ppr dicts)
1554 try_me dicts `thenTc` \ (frees, binds, ambigs) ->
1555 WARN( not (null frees && null ambigs), ppr frees $$ ppr ambigs )
1556 warnDefault dicts chosen_default_ty `thenTc_`
1559 | all isCreturnableClass classes
1560 = -- Default CCall stuff to (); we don't even both to check that () is an
1561 -- instance of CReturnable, because we know it is.
1562 unifyTauTy (mkTyVarTy tyvar) unitTy `thenTc_`
1563 returnTc EmptyMonoBinds
1565 | otherwise -- No defaults
1566 = addAmbigErrs dicts `thenNF_Tc_`
1567 returnTc EmptyMonoBinds
1570 try_me inst = ReduceMe -- This reduce should not fail
1571 tyvar = get_tv (head dicts) -- Should be non-empty
1572 classes = map get_clas dicts
1575 [Aside - why the defaulting mechanism is turned off when
1576 dealing with arguments and results to ccalls.
1578 When typechecking _ccall_s, TcExpr ensures that the external
1579 function is only passed arguments (and in the other direction,
1580 results) of a restricted set of 'native' types. This is
1581 implemented via the help of the pseudo-type classes,
1582 @CReturnable@ (CR) and @CCallable@ (CC.)
1584 The interaction between the defaulting mechanism for numeric
1585 values and CC & CR can be a bit puzzling to the user at times.
1594 What type has 'x' got here? That depends on the default list
1595 in operation, if it is equal to Haskell 98's default-default
1596 of (Integer, Double), 'x' has type Double, since Integer
1597 is not an instance of CR. If the default list is equal to
1598 Haskell 1.4's default-default of (Int, Double), 'x' has type
1601 To try to minimise the potential for surprises here, the
1602 defaulting mechanism is turned off in the presence of
1603 CCallable and CReturnable.
1608 %************************************************************************
1610 \subsection[simple]{@Simple@ versions}
1612 %************************************************************************
1614 Much simpler versions when there are no bindings to make!
1616 @tcSimplifyThetas@ simplifies class-type constraints formed by
1617 @deriving@ declarations and when specialising instances. We are
1618 only interested in the simplified bunch of class/type constraints.
1620 It simplifies to constraints of the form (C a b c) where
1621 a,b,c are type variables. This is required for the context of
1622 instance declarations.
1625 tcSimplifyThetas :: ThetaType -- Wanted
1626 -> TcM ThetaType -- Needed
1628 tcSimplifyThetas wanteds
1629 = doptsTc Opt_GlasgowExts `thenNF_Tc` \ glaExts ->
1630 reduceSimple [] wanteds `thenNF_Tc` \ irreds ->
1632 -- For multi-param Haskell, check that the returned dictionaries
1633 -- don't have any of the form (C Int Bool) for which
1634 -- we expect an instance here
1635 -- For Haskell 98, check that all the constraints are of the form C a,
1636 -- where a is a type variable
1637 bad_guys | glaExts = [pred | pred <- irreds,
1638 isEmptyVarSet (tyVarsOfPred pred)]
1639 | otherwise = [pred | pred <- irreds,
1640 not (isTyVarClassPred pred)]
1642 if null bad_guys then
1645 mapNF_Tc addNoInstErr bad_guys `thenNF_Tc_`
1649 @tcSimplifyCheckThetas@ just checks class-type constraints, essentially;
1650 used with \tr{default} declarations. We are only interested in
1651 whether it worked or not.
1654 tcSimplifyCheckThetas :: ThetaType -- Given
1655 -> ThetaType -- Wanted
1658 tcSimplifyCheckThetas givens wanteds
1659 = reduceSimple givens wanteds `thenNF_Tc` \ irreds ->
1663 mapNF_Tc addNoInstErr irreds `thenNF_Tc_`
1669 type AvailsSimple = FiniteMap PredType Bool
1670 -- True => irreducible
1671 -- False => given, or can be derived from a given or from an irreducible
1673 reduceSimple :: ThetaType -- Given
1674 -> ThetaType -- Wanted
1675 -> NF_TcM ThetaType -- Irreducible
1677 reduceSimple givens wanteds
1678 = reduce_simple (0,[]) givens_fm wanteds `thenNF_Tc` \ givens_fm' ->
1679 returnNF_Tc [pred | (pred,True) <- fmToList givens_fm']
1681 givens_fm = foldl addNonIrred emptyFM givens
1683 reduce_simple :: (Int,ThetaType) -- Stack
1686 -> NF_TcM AvailsSimple
1688 reduce_simple (n,stack) avails wanteds
1691 go avails [] = returnNF_Tc avails
1692 go avails (w:ws) = reduce_simple_help (n+1,w:stack) avails w `thenNF_Tc` \ avails' ->
1695 reduce_simple_help stack givens wanted
1696 | wanted `elemFM` givens
1697 = returnNF_Tc givens
1699 | Just (clas, tys) <- getClassPredTys_maybe wanted
1700 = lookupSimpleInst clas tys `thenNF_Tc` \ maybe_theta ->
1702 Nothing -> returnNF_Tc (addSimpleIrred givens wanted)
1703 Just theta -> reduce_simple stack (addNonIrred givens wanted) theta
1706 = returnNF_Tc (addSimpleIrred givens wanted)
1708 addSimpleIrred :: AvailsSimple -> PredType -> AvailsSimple
1709 addSimpleIrred givens pred
1710 = addSCs (addToFM givens pred True) pred
1712 addNonIrred :: AvailsSimple -> PredType -> AvailsSimple
1713 addNonIrred givens pred
1714 = addSCs (addToFM givens pred False) pred
1717 | not (isClassPred pred) = givens
1718 | otherwise = foldl add givens sc_theta
1720 Just (clas,tys) = getClassPredTys_maybe pred
1721 (tyvars, sc_theta_tmpl, _, _) = classBigSig clas
1722 sc_theta = substTheta (mkTopTyVarSubst tyvars tys) sc_theta_tmpl
1725 = case lookupFM givens ct of
1726 Nothing -> -- Add it and its superclasses
1727 addSCs (addToFM givens ct False) ct
1729 Just True -> -- Set its flag to False; superclasses already done
1730 addToFM givens ct False
1732 Just False -> -- Already done
1738 %************************************************************************
1740 \section{Errors and contexts}
1742 %************************************************************************
1744 ToDo: for these error messages, should we note the location as coming
1745 from the insts, or just whatever seems to be around in the monad just
1749 groupInsts :: [Inst] -> [[Inst]]
1750 -- Group together insts with the same origin
1751 -- We want to report them together in error messages
1753 groupInsts (inst:insts) = (inst:friends) : groupInsts others
1755 -- (It may seem a bit crude to compare the error messages,
1756 -- but it makes sure that we combine just what the user sees,
1757 -- and it avoids need equality on InstLocs.)
1758 (friends, others) = partition is_friend insts
1759 loc_msg = showSDoc (pprInstLoc (instLoc inst))
1760 is_friend friend = showSDoc (pprInstLoc (instLoc friend)) == loc_msg
1763 addTopAmbigErrs dicts
1764 = mapNF_Tc (addTopInstanceErrs tidy_env) (groupInsts no_insts) `thenNF_Tc_`
1765 mapNF_Tc (addTopIPErrs tidy_env) (groupInsts bad_ips) `thenNF_Tc_`
1766 mapNF_Tc (addAmbigErr tidy_env) ambigs `thenNF_Tc_`
1769 fixed_tvs = oclose (predsOfInsts tidy_dicts) emptyVarSet
1770 (tidy_env, tidy_dicts) = tidyInsts dicts
1771 (bad_ips, non_ips) = partition is_ip tidy_dicts
1772 (no_insts, ambigs) = partition no_inst non_ips
1773 is_ip d = any isIPPred (predsOfInst d)
1774 no_inst d = not (isTyVarDict d) || tyVarsOfInst d `subVarSet` fixed_tvs
1777 plural xs = char 's'
1779 addTopIPErrs tidy_env tidy_dicts
1780 = addInstErrTcM (instLoc (head tidy_dicts))
1782 ptext SLIT("Unbound implicit parameter") <> plural tidy_dicts <+> pprInsts tidy_dicts)
1784 -- Used for top-level irreducibles
1785 addTopInstanceErrs tidy_env tidy_dicts
1786 = addInstErrTcM (instLoc (head tidy_dicts))
1788 ptext SLIT("No instance") <> plural tidy_dicts <+>
1789 ptext SLIT("for") <+> pprInsts tidy_dicts)
1792 = mapNF_Tc (addAmbigErr tidy_env) tidy_dicts
1794 (tidy_env, tidy_dicts) = tidyInsts dicts
1796 addAmbigErr tidy_env tidy_dict
1797 = addInstErrTcM (instLoc tidy_dict)
1799 sep [text "Ambiguous type variable(s)" <+> pprQuotedList ambig_tvs,
1800 nest 4 (text "in the constraint" <+> quotes (pprInst tidy_dict))])
1802 ambig_tvs = varSetElems (tyVarsOfInst tidy_dict)
1804 warnDefault dicts default_ty
1805 = doptsTc Opt_WarnTypeDefaults `thenTc` \ warn_flag ->
1806 tcAddSrcLoc (get_loc (head dicts)) (warnTc warn_flag warn_msg)
1809 (_, tidy_dicts) = tidyInsts dicts
1810 get_loc i = case instLoc i of { (_,loc,_) -> loc }
1811 warn_msg = vcat [ptext SLIT("Defaulting the following constraint(s) to type") <+>
1812 quotes (ppr default_ty),
1813 pprInstsInFull tidy_dicts]
1815 complainCheck doc givens irreds
1816 = mapNF_Tc zonkInst given_dicts `thenNF_Tc` \ givens' ->
1817 mapNF_Tc (addNoInstanceErrs doc givens') (groupInsts irreds) `thenNF_Tc_`
1820 given_dicts = filter isDict givens
1821 -- Filter out methods, which are only added to
1822 -- the given set as an optimisation
1824 addNoInstanceErrs what_doc givens dicts
1825 = tcGetInstEnv `thenNF_Tc` \ inst_env ->
1827 (tidy_env1, tidy_givens) = tidyInsts givens
1828 (tidy_env2, tidy_dicts) = tidyMoreInsts tidy_env1 dicts
1830 doc = vcat [sep [herald <+> pprInsts tidy_dicts,
1831 nest 4 $ ptext SLIT("from the context") <+> pprInsts tidy_givens],
1833 ptext SLIT("Probable fix:"),
1837 herald = ptext SLIT("Could not") <+> unambig_doc <+> ptext SLIT("deduce")
1838 unambig_doc | ambig_overlap = ptext SLIT("unambiguously")
1841 -- The error message when we don't find a suitable instance
1842 -- is complicated by the fact that sometimes this is because
1843 -- there is no instance, and sometimes it's because there are
1844 -- too many instances (overlap). See the comments in TcEnv.lhs
1845 -- with the InstEnv stuff.
1848 | not ambig_overlap = empty
1850 = vcat [ptext SLIT("The choice of (overlapping) instance declaration"),
1851 nest 4 (ptext SLIT("depends on the instantiation of") <+>
1852 quotes (pprWithCommas ppr (varSetElems (tyVarsOfInsts tidy_dicts))))]
1854 fix1 = sep [ptext SLIT("Add") <+> pprInsts tidy_dicts,
1855 ptext SLIT("to the") <+> what_doc]
1857 fix2 | null instance_dicts
1860 = ptext SLIT("Or add an instance declaration for") <+> pprInsts instance_dicts
1862 instance_dicts = [d | d <- tidy_dicts, isClassDict d, not (isTyVarDict d)]
1863 -- Insts for which it is worth suggesting an adding an instance declaration
1864 -- Exclude implicit parameters, and tyvar dicts
1866 -- Checks for the ambiguous case when we have overlapping instances
1867 ambig_overlap = any ambig_overlap1 dicts
1870 = case lookupInstEnv inst_env clas tys of
1871 NoMatch ambig -> ambig
1875 (clas,tys) = getDictClassTys dict
1877 addInstErrTcM (instLoc (head dicts)) (tidy_env2, doc)
1879 -- Used for the ...Thetas variants; all top level
1881 = addErrTc (ptext SLIT("No instance for") <+> quotes (ppr pred))
1883 reduceDepthErr n stack
1884 = vcat [ptext SLIT("Context reduction stack overflow; size =") <+> int n,
1885 ptext SLIT("Use -fcontext-stack20 to increase stack size to (e.g.) 20"),
1886 nest 4 (pprInstsInFull stack)]
1888 reduceDepthMsg n stack = nest 4 (pprInstsInFull stack)
1890 -----------------------------------------------
1892 = addErrTc (sep [ptext SLIT("Cannot generalise these overloadings (in a _ccall_):"),
1893 nest 4 (ppr inst <+> pprInstLoc (instLoc inst))])