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,
28 isDict, isClassDict, instName,
29 isStdClassTyVarDict, isMethodFor,
30 instToId, tyVarsOfInsts,
31 instBindingRequired, instCanBeGeneralised,
32 newDictsFromOld, instMentionsIPs,
33 getDictClassTys, isTyVarDict,
34 instLoc, pprInst, zonkInst, tidyInsts, tidyMoreInsts,
35 Inst, LIE, pprInsts, pprInstsInFull,
38 import TcEnv ( tcGetGlobalTyVars, tcGetInstEnv )
39 import InstEnv ( lookupInstEnv, classInstEnv, InstLookupResult(..) )
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 )
47 import NameSet ( mkNameSet )
48 import Class ( classBigSig )
49 import FunDeps ( oclose, grow, improve )
50 import PrelInfo ( isNumericClass, isCreturnableClass, isCcallishClass )
52 import Subst ( mkTopTyVarSubst, substTheta, substTy )
53 import TysWiredIn ( unitTy )
57 import ListSetOps ( equivClasses )
58 import Util ( zipEqual )
59 import List ( partition )
64 %************************************************************************
68 %************************************************************************
70 --------------------------------------
71 Notes on quantification
72 --------------------------------------
74 Suppose we are about to do a generalisation step.
79 C the constraints from that RHS
81 The game is to figure out
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
87 So we're going to infer the type
91 and float the constraints Ct further outwards.
93 Here are the things that *must* be true:
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
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.
104 BETWEEN THESE TWO BOUNDS, ANY Q WILL DO!
106 Example: class H x y | x->y where ...
108 fv(G) = {a} C = {H a b, H c d}
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}
114 So Q can be {c,d}, {b,c,d}
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.
121 -----------------------------------------
124 fv(T) the free type vars of T
126 oclose(vs,C) The result of extending the set of tyvars vs
127 using the functional dependencies from C
129 grow(vs,C) The result of extend the set of tyvars vs
130 using all conceivable links from C.
132 E.g. vs = {a}, C = {H [a] b, K (b,Int) c, Eq e}
133 Then grow(vs,C) = {a,b,c}
135 Note that grow(vs,C) `superset` grow(vs,simplify(C))
136 That is, simplfication can only shrink the result of grow.
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)
143 -----------------------------------------
147 Here's a good way to choose Q:
149 Q = grow( fv(T), C ) \ oclose( fv(G), C )
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.
156 Why grow( fv(T), C ) rather than fv(T)? Consider
158 class H x y | x->y where ...
163 If we used fv(T) = {c} we'd get the type
165 forall c. H c d => c -> b
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.
172 Why not oclose( fv(T), C )? Because we might not be able to see
173 all the functional dependencies yet:
175 class H x y | x->y where ...
176 instance H x y => Eq (T x y) where ...
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.
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.
191 --------------------------------------
193 --------------------------------------
195 It's very hard to be certain when a type is ambiguous. Consider
199 instance H x y => K (x,y)
201 Is this type ambiguous?
202 forall a b. (K (a,b), Eq b) => a -> a
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!
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 ...
214 You may say of this example that we should use the instance decl right
215 away, but you can't always do that:
217 class J a b where ...
218 instance J Int b where ...
220 f :: forall a b. J a b => a -> a
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.
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.
233 So here's the plan. We WARN about probable ambiguity if
235 fv(Cq) is not a subset of oclose(fv(T) union fv(G), C)
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.
241 Notice that we union before calling oclose. Here's an example:
243 class J a b c | a b -> c
247 forall b c. (J a b c) => b -> b
249 Only if we union {a} from G with {b} from T before using oclose,
250 do we see that c is fixed.
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.
258 Can we ever be *certain* about ambiguity? Yes: if there's a constraint
260 c in C such that fv(c) intersect (fv(G) union fv(T)) = EMPTY
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
268 instance H x y => K (x,y)
270 Is this type ambiguous?
271 forall a b. (K (a,b), Eq b) => a -> a
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
276 Cq = Ca union Cq' st fv(Ca) intersect (fv(Cq') union fv(T) union fv(G)) = EMPTY
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)
285 --------------------------------------
286 Notes on principal types
287 --------------------------------------
292 f x = let g y = op (y::Int) in True
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
299 --------------------------------------
300 Notes on implicit parameters
301 --------------------------------------
303 Question 1: can we "inherit" implicit parameters
304 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
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:
315 (so we get ?y from the context of f's definition), or
317 f :: (?y::Int) => Int -> Int
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.
325 BOTTOM LINE: you *must* quantify over implicit parameters. See
326 isFreeAndInheritable.
328 BUT WATCH OUT: for *expressions*, this isn't right. Consider:
332 This is perfectly reasonable. We do not want to insist on
334 (?x + 1) :: (?x::Int => Int)
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).
342 Question 2: type signatures
343 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
344 OK, so is it legal to give an explicit, user type signature to f, thus:
349 At first sight this seems reasonable, but it has the nasty property
350 that adding a type signature changes the dynamic semantics.
353 (let f x = (x::Int) + ?y
354 in (f 3, f 3 with ?y=5)) with ?y = 6
360 in (f 3, f 3 with ?y=5)) with ?y = 6
364 Indeed, simply inlining f (at the Haskell source level) would change the
367 Conclusion: the above type signature is illegal. You'll get a message
368 of the form "could not deduce (?y::Int) from ()".
371 Question 3: monomorphism
372 ~~~~~~~~~~~~~~~~~~~~~~~~
373 There's a nasty corner case when the monomorphism restriction bites:
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
382 Why does the momomorphism restriction say this? Because if you have
384 let z = x + ?y in z+z
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.
393 (A) Always generalise over implicit parameters
394 Bindings that fall under the monomorphism restriction can't
398 * Inlining remains valid
399 * No unexpected loss of sharing
400 * But simple bindings like
402 will be rejected, unless you add an explicit type signature
403 (to avoid the monomorphism restriction)
404 z :: (?y::Int) => Int
406 This seems unacceptable
408 (B) Monomorphism restriction "wins"
409 Bindings that fall under the monomorphism restriction can't
411 Always generalise over implicit parameters *except* for bindings
412 that fall under the monomorphism restriction
415 * Inlining isn't valid in general
416 * No unexpected loss of sharing
417 * Simple bindings like
419 accepted (get value of ?y from binding site)
421 (C) Always generalise over implicit parameters
422 Bindings that fall under the monomorphism restriction can't
423 be generalised, EXCEPT for implicit parameters
425 * Inlining remains valid
426 * Unexpected loss of sharing (from the extra generalisation)
427 * Simple bindings like
429 accepted (get value of ?y from occurrence sites)
434 None of these choices seems very satisfactory. But at least we should
435 decide which we want to do.
437 It's really not clear what is the Right Thing To Do. If you see
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.
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.
458 BOTTOM LINE: we choose (B) at present. See tcSimplifyRestricted
462 %************************************************************************
464 \subsection{tcSimplifyInfer}
466 %************************************************************************
468 tcSimplify is called when we *inferring* a type. Here's the overall game plan:
470 1. Compute Q = grow( fvs(T), C )
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
475 3. Try improvement, using functional dependencies
477 4. If Step 3 did any unification, repeat from step 1
478 (Unification can change the result of 'grow'.)
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.
485 For the guts, we need a loop, that alternates context reduction and
486 improvement with unification. E.g. Suppose we have
488 class C x y | x->y where ...
490 and tcSimplify is called with:
492 Then improvement unifies a with b, giving
495 If we need to unify anything, we rattle round the whole thing all over
502 -> TcTyVarSet -- fv(T); type vars
504 -> TcM ([TcTyVar], -- Tyvars to quantify (zonked)
506 TcDictBinds, -- Bindings
507 [TcId]) -- Dict Ids that must be bound here (zonked)
512 tcSimplifyInfer doc tau_tvs wanted_lie
513 = inferLoop doc (varSetElems tau_tvs)
514 (lieToList wanted_lie) `thenTc` \ (qtvs, frees, binds, irreds) ->
516 -- Check for non-generalisable insts
517 mapTc_ addCantGenErr (filter (not . instCanBeGeneralised) irreds) `thenTc_`
519 returnTc (qtvs, mkLIE frees, binds, map instToId irreds)
521 inferLoop doc tau_tvs wanteds
523 zonkTcTyVarsAndFV tau_tvs `thenNF_Tc` \ tau_tvs' ->
524 mapNF_Tc zonkInst wanteds `thenNF_Tc` \ wanteds' ->
525 tcGetGlobalTyVars `thenNF_Tc` \ gbl_tvs ->
527 preds = predsOfInsts wanteds'
528 qtvs = grow preds tau_tvs' `minusVarSet` oclose preds gbl_tvs
531 | isFreeAndInheritable qtvs inst = Free
532 | isClassDict inst = DontReduceUnlessConstant -- Dicts
533 | otherwise = ReduceMe -- Lits and Methods
536 reduceContext doc try_me [] wanteds' `thenTc` \ (no_improvement, frees, binds, irreds) ->
539 if no_improvement then
540 returnTc (varSetElems qtvs, frees, binds, irreds)
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]
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.
552 -- Hence the (irreds ++ frees)
554 inferLoop doc tau_tvs (irreds ++ frees) `thenTc` \ (qtvs1, frees1, binds1, irreds1) ->
555 returnTc (qtvs1, frees1, binds `AndMonoBinds` binds1, irreds1)
560 class If b t e r | b t e -> r
563 class Lte a b c | a b -> c where lte :: a -> b -> c
565 instance (Lte a b l,If l b a c) => Max a b c
567 Wanted: Max Z (S x) y
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)!
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")
582 = not (tyVarsOfInst inst `intersectsVarSet` qtvs)
586 %************************************************************************
588 \subsection{tcSimplifyCheck}
590 %************************************************************************
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.
598 -> [TcTyVar] -- Quantify over these
602 TcDictBinds) -- Bindings
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)
614 get_qtvs = zonkTcTyVarsAndFV qtvs
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
622 -> TcTyVarSet -- fv(T)
625 -> TcM ([TcTyVar], -- Variables over which to quantify
627 TcDictBinds) -- Bindings
629 tcSimplifyInferCheck doc tau_tvs givens wanted_lie
630 = tcSimplCheck doc isFreeAndInheritable get_qtvs givens wanted_lie
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
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)
643 get_qtvs = zonkTcTyVarsAndFV all_tvs `thenNF_Tc` \ all_tvs' ->
644 tcGetGlobalTyVars `thenNF_Tc` \ gbl_tvs ->
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
654 Here is the workhorse function for all three wrappers.
657 tcSimplCheck doc is_free get_qtvs givens wanted_lie
658 = check_loop givens (lieToList wanted_lie) `thenTc` \ (qtvs, frees, binds, irreds) ->
660 -- Complain about any irreducible ones
661 complainCheck doc givens irreds `thenNF_Tc_`
664 returnTc (qtvs, mkLIE frees, binds)
667 check_loop givens wanteds
669 mapNF_Tc zonkInst givens `thenNF_Tc` \ givens' ->
670 mapNF_Tc zonkInst wanteds `thenNF_Tc` \ wanteds' ->
671 get_qtvs `thenNF_Tc` \ qtvs' ->
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
680 reduceContext doc try_me givens' wanteds' `thenTc` \ (no_improvement, frees, binds, irreds) ->
683 if no_improvement then
684 returnTc (varSetElems qtvs', frees, binds, irreds)
686 check_loop givens' (irreds ++ frees) `thenTc` \ (qtvs', frees1, binds1, irreds1) ->
687 returnTc (qtvs', frees1, binds `AndMonoBinds` binds1, irreds1)
691 %************************************************************************
693 \subsection{tcSimplifyRestricted}
695 %************************************************************************
698 tcSimplifyRestricted -- Used for restricted binding groups
699 -- i.e. ones subject to the monomorphism restriction
701 -> TcTyVarSet -- Free in the type of the RHSs
702 -> LIE -- Free in the RHSs
703 -> TcM ([TcTyVar], -- Tyvars to quantify (zonked)
705 TcDictBinds) -- Bindings
707 tcSimplifyRestricted doc tau_tvs wanted_lie
708 = -- First squash out all methods, to find the constrained tyvars
709 -- We can't just take the free vars of wanted_lie because that'll
710 -- have methods that may incidentally mention entirely unconstrained variables
711 -- e.g. a call to f :: Eq a => a -> b -> b
712 -- Here, b is unconstrained. A good example would be
714 -- We want to infer the polymorphic type
715 -- foo :: forall b. b -> b
717 wanteds = lieToList wanted_lie
718 try_me inst = ReduceMe -- Reduce as far as we can. Don't stop at
719 -- dicts; the idea is to get rid of as many type
720 -- variables as possible, and we don't want to stop
721 -- at (say) Monad (ST s), because that reduces
722 -- immediately, with no constraint on s.
724 simpleReduceLoop doc try_me wanteds `thenTc` \ (_, _, constrained_dicts) ->
726 -- Next, figure out the tyvars we will quantify over
727 zonkTcTyVarsAndFV (varSetElems tau_tvs) `thenNF_Tc` \ tau_tvs' ->
728 tcGetGlobalTyVars `thenNF_Tc` \ gbl_tvs ->
730 constrained_tvs = tyVarsOfInsts constrained_dicts
731 qtvs = (tau_tvs' `minusVarSet` oclose (predsOfInsts constrained_dicts) gbl_tvs)
732 `minusVarSet` constrained_tvs
735 -- The first step may have squashed more methods than
736 -- necessary, so try again, this time knowing the exact
737 -- set of type variables to quantify over.
739 -- We quantify only over constraints that are captured by qtvs;
740 -- these will just be a subset of non-dicts. This in contrast
741 -- to normal inference (using isFreeAndInheritable) in which we quantify over
742 -- all *non-inheritable* constraints too. This implements choice
743 -- (B) under "implicit parameter and monomorphism" above.
744 mapNF_Tc zonkInst (lieToList wanted_lie) `thenNF_Tc` \ wanteds' ->
746 try_me inst | isFree qtvs inst = Free
747 | otherwise = ReduceMe
749 reduceContext doc try_me [] wanteds' `thenTc` \ (no_improvement, frees, binds, irreds) ->
750 ASSERT( no_improvement )
751 ASSERT( null irreds )
752 -- No need to loop because simpleReduceLoop will have
753 -- already done any improvement necessary
755 returnTc (varSetElems qtvs, mkLIE frees, binds)
759 %************************************************************************
761 \subsection{tcSimplifyToDicts}
763 %************************************************************************
765 On the LHS of transformation rules we only simplify methods and constants,
766 getting dictionaries. We want to keep all of them unsimplified, to serve
767 as the available stuff for the RHS of the rule.
769 The same thing is used for specialise pragmas. Consider
772 {-# SPECIALISE f :: Int -> Int #-}
775 The type checker generates a binding like:
777 f_spec = (f :: Int -> Int)
779 and we want to end up with
781 f_spec = _inline_me_ (f Int dNumInt)
783 But that means that we must simplify the Method for f to (f Int dNumInt)!
784 So tcSimplifyToDicts squeezes out all Methods.
786 IMPORTANT NOTE: we *don't* want to do superclass commoning up. Consider
788 fromIntegral :: (Integral a, Num b) => a -> b
789 {-# RULES "foo" fromIntegral = id :: Int -> Int #-}
791 Here, a=b=Int, and Num Int is a superclass of Integral Int. But we *dont*
795 fromIntegral Int Int dIntegralInt (scsel dIntegralInt) = id Int
797 because the scsel will mess up matching. Instead we want
799 forall dIntegralInt, dNumInt.
800 fromIntegral Int Int dIntegralInt dNumInt = id Int
802 Hence "DontReduce NoSCs"
805 tcSimplifyToDicts :: LIE -> TcM ([Inst], TcDictBinds)
806 tcSimplifyToDicts wanted_lie
807 = simpleReduceLoop doc try_me wanteds `thenTc` \ (frees, binds, irreds) ->
808 -- Since try_me doesn't look at types, we don't need to
809 -- do any zonking, so it's safe to call reduceContext directly
811 returnTc (irreds, binds)
814 doc = text "tcSimplifyToDicts"
815 wanteds = lieToList wanted_lie
817 -- Reduce methods and lits only; stop as soon as we get a dictionary
818 try_me inst | isDict inst = DontReduce NoSCs
819 | otherwise = ReduceMe
823 %************************************************************************
825 \subsection{Filtering at a dynamic binding}
827 %************************************************************************
832 we must discharge all the ?x constraints from B. We also do an improvement
833 step; if we have ?x::t1 and ?x::t2 we must unify t1, t2.
835 Actually, the constraints from B might improve the types in ?x. For example
837 f :: (?x::Int) => Char -> Char
840 then the constraint (?x::Int) arising from the call to f will
841 force the binding for ?x to be of type Int.
844 tcSimplifyIPs :: [Inst] -- The implicit parameters bound here
846 -> TcM (LIE, TcDictBinds)
847 tcSimplifyIPs given_ips wanted_lie
848 = simpl_loop given_ips wanteds `thenTc` \ (frees, binds) ->
849 returnTc (mkLIE frees, binds)
851 doc = text "tcSimplifyIPs" <+> ppr ip_names
852 wanteds = lieToList wanted_lie
853 ip_names = map instName given_ips
854 ip_set = mkNameSet ip_names
856 -- Simplify any methods that mention the implicit parameter
857 try_me inst | inst `instMentionsIPs` ip_set = ReduceMe
860 simpl_loop givens wanteds
861 = mapNF_Tc zonkInst givens `thenNF_Tc` \ givens' ->
862 mapNF_Tc zonkInst wanteds `thenNF_Tc` \ wanteds' ->
864 reduceContext doc try_me givens' wanteds' `thenTc` \ (no_improvement, frees, binds, irreds) ->
866 if no_improvement then
867 ASSERT( null irreds )
868 returnTc (frees, binds)
870 simpl_loop givens' (irreds ++ frees) `thenTc` \ (frees1, binds1) ->
871 returnTc (frees1, binds `AndMonoBinds` binds1)
875 %************************************************************************
877 \subsection[binds-for-local-funs]{@bindInstsOfLocalFuns@}
879 %************************************************************************
881 When doing a binding group, we may have @Insts@ of local functions.
882 For example, we might have...
884 let f x = x + 1 -- orig local function (overloaded)
885 f.1 = f Int -- two instances of f
890 The point is: we must drop the bindings for @f.1@ and @f.2@ here,
891 where @f@ is in scope; those @Insts@ must certainly not be passed
892 upwards towards the top-level. If the @Insts@ were binding-ified up
893 there, they would have unresolvable references to @f@.
895 We pass in an @init_lie@ of @Insts@ and a list of locally-bound @Ids@.
896 For each method @Inst@ in the @init_lie@ that mentions one of the
897 @Ids@, we create a binding. We return the remaining @Insts@ (in an
898 @LIE@), as well as the @HsBinds@ generated.
901 bindInstsOfLocalFuns :: LIE -> [TcId] -> TcM (LIE, TcMonoBinds)
903 bindInstsOfLocalFuns init_lie local_ids
904 | null overloaded_ids
906 = returnTc (init_lie, EmptyMonoBinds)
909 = simpleReduceLoop doc try_me wanteds `thenTc` \ (frees, binds, irreds) ->
910 ASSERT( null irreds )
911 returnTc (mkLIE frees, binds)
913 doc = text "bindInsts" <+> ppr local_ids
914 wanteds = lieToList init_lie
915 overloaded_ids = filter is_overloaded local_ids
916 is_overloaded id = isOverloadedTy (idType id)
918 overloaded_set = mkVarSet overloaded_ids -- There can occasionally be a lot of them
919 -- so it's worth building a set, so that
920 -- lookup (in isMethodFor) is faster
922 try_me inst | isMethodFor overloaded_set inst = ReduceMe
927 %************************************************************************
929 \subsection{Data types for the reduction mechanism}
931 %************************************************************************
933 The main control over context reduction is here
937 = ReduceMe -- Try to reduce this
938 -- If there's no instance, behave exactly like
939 -- DontReduce: add the inst to
940 -- the irreductible ones, but don't
941 -- produce an error message of any kind.
942 -- It might be quite legitimate such as (Eq a)!
944 | DontReduce WantSCs -- Return as irreducible
946 | DontReduceUnlessConstant -- Return as irreducible unless it can
947 -- be reduced to a constant in one step
949 | Free -- Return as free
951 data WantSCs = NoSCs | AddSCs -- Tells whether we should add the superclasses
952 -- of a predicate when adding it to the avails
958 type RedState = (Avails, -- What's available
959 [Inst]) -- Insts for which try_me returned Free
961 type Avails = FiniteMap Inst Avail
964 = Irred -- Used for irreducible dictionaries,
965 -- which are going to be lambda bound
967 | BoundTo TcId -- Used for dictionaries for which we have a binding
968 -- e.g. those "given" in a signature
970 | NoRhs -- Used for Insts like (CCallable f)
971 -- where no witness is required.
973 | Rhs -- Used when there is a RHS
975 [Inst] -- Insts free in the RHS; we need these too
977 pprAvails avails = vcat [ppr inst <+> equals <+> pprAvail avail
978 | (inst,avail) <- fmToList avails ]
980 instance Outputable Avail where
983 pprAvail NoRhs = text "<no rhs>"
984 pprAvail Irred = text "Irred"
985 pprAvail (BoundTo x) = text "Bound to" <+> ppr x
986 pprAvail (Rhs rhs bs) = ppr rhs <+> braces (ppr bs)
989 Extracting the bindings from a bunch of Avails.
990 The bindings do *not* come back sorted in dependency order.
991 We assume that they'll be wrapped in a big Rec, so that the
992 dependency analyser can sort them out later
996 bindsAndIrreds :: Avails
998 -> (TcDictBinds, -- Bindings
999 [Inst]) -- Irreducible ones
1001 bindsAndIrreds avails wanteds
1002 = go avails EmptyMonoBinds [] wanteds
1004 go avails binds irreds [] = (binds, irreds)
1006 go avails binds irreds (w:ws)
1007 = case lookupFM avails w of
1008 Nothing -> -- Free guys come out here
1009 -- (If we didn't do addFree we could use this as the
1010 -- criterion for free-ness, and pick up the free ones here too)
1011 go avails binds irreds ws
1013 Just NoRhs -> go avails binds irreds ws
1015 Just Irred -> go (addToFM avails w (BoundTo (instToId w))) binds (w:irreds) ws
1017 Just (BoundTo id) -> go avails new_binds irreds ws
1019 -- For implicit parameters, all occurrences share the same
1020 -- Id, so there is no need for synonym bindings
1021 new_binds | new_id == id = binds
1022 | otherwise = addBind binds new_id (HsVar id)
1025 Just (Rhs rhs ws') -> go avails' (addBind binds id rhs) irreds (ws' ++ ws)
1028 avails' = addToFM avails w (BoundTo id)
1030 addBind binds id rhs = binds `AndMonoBinds` VarMonoBind id rhs
1034 %************************************************************************
1036 \subsection[reduce]{@reduce@}
1038 %************************************************************************
1040 When the "what to do" predicate doesn't depend on the quantified type variables,
1041 matters are easier. We don't need to do any zonking, unless the improvement step
1042 does something, in which case we zonk before iterating.
1044 The "given" set is always empty.
1047 simpleReduceLoop :: SDoc
1048 -> (Inst -> WhatToDo) -- What to do, *not* based on the quantified type variables
1050 -> TcM ([Inst], -- Free
1052 [Inst]) -- Irreducible
1054 simpleReduceLoop doc try_me wanteds
1055 = mapNF_Tc zonkInst wanteds `thenNF_Tc` \ wanteds' ->
1056 reduceContext doc try_me [] wanteds' `thenTc` \ (no_improvement, frees, binds, irreds) ->
1057 if no_improvement then
1058 returnTc (frees, binds, irreds)
1060 simpleReduceLoop doc try_me (irreds ++ frees) `thenTc` \ (frees1, binds1, irreds1) ->
1061 returnTc (frees1, binds `AndMonoBinds` binds1, irreds1)
1067 reduceContext :: SDoc
1068 -> (Inst -> WhatToDo)
1071 -> NF_TcM (Bool, -- True <=> improve step did no unification
1073 TcDictBinds, -- Dictionary bindings
1074 [Inst]) -- Irreducible
1076 reduceContext doc try_me givens wanteds
1078 traceTc (text "reduceContext" <+> (vcat [
1079 text "----------------------",
1081 text "given" <+> ppr givens,
1082 text "wanted" <+> ppr wanteds,
1083 text "----------------------"
1086 -- Build the Avail mapping from "givens"
1087 foldlNF_Tc addGiven (emptyFM, []) givens `thenNF_Tc` \ init_state ->
1090 reduceList (0,[]) try_me wanteds init_state `thenNF_Tc` \ state@(avails, frees) ->
1092 -- Do improvement, using everything in avails
1093 -- In particular, avails includes all superclasses of everything
1094 tcImprove avails `thenTc` \ no_improvement ->
1096 traceTc (text "reduceContext end" <+> (vcat [
1097 text "----------------------",
1099 text "given" <+> ppr givens,
1100 text "wanted" <+> ppr wanteds,
1102 text "avails" <+> pprAvails avails,
1103 text "frees" <+> ppr frees,
1104 text "no_improvement =" <+> ppr no_improvement,
1105 text "----------------------"
1108 (binds, irreds) = bindsAndIrreds avails wanteds
1110 returnTc (no_improvement, frees, binds, irreds)
1113 = tcGetInstEnv `thenTc` \ inst_env ->
1115 preds = [ (pred, pp_loc)
1116 | inst <- keysFM avails,
1117 let pp_loc = pprInstLoc (instLoc inst),
1118 pred <- predsOfInst inst,
1121 -- Avails has all the superclasses etc (good)
1122 -- It also has all the intermediates of the deduction (good)
1123 -- It does not have duplicates (good)
1124 -- NB that (?x::t1) and (?x::t2) will be held separately in avails
1125 -- so that improve will see them separate
1126 eqns = improve (classInstEnv inst_env) preds
1131 traceTc (ptext SLIT("Improve:") <+> vcat (map ppr_eqn eqns)) `thenNF_Tc_`
1132 mapTc_ unify eqns `thenTc_`
1135 unify ((qtvs, t1, t2), doc)
1136 = tcAddErrCtxt doc $
1137 tcInstTyVars (varSetElems qtvs) `thenNF_Tc` \ (_, _, tenv) ->
1138 unifyTauTy (substTy tenv t1) (substTy tenv t2)
1139 ppr_eqn ((qtvs, t1, t2), doc)
1140 = vcat [ptext SLIT("forall") <+> braces (pprWithCommas ppr (varSetElems qtvs))
1141 <+> ppr t1 <+> ptext SLIT(":=:") <+> ppr t2,
1145 The main context-reduction function is @reduce@. Here's its game plan.
1148 reduceList :: (Int,[Inst]) -- Stack (for err msgs)
1149 -- along with its depth
1150 -> (Inst -> WhatToDo)
1157 try_me: given an inst, this function returns
1159 DontReduce return this in "irreds"
1160 Free return this in "frees"
1162 wanteds: The list of insts to reduce
1163 state: An accumulating parameter of type RedState
1164 that contains the state of the algorithm
1166 It returns a RedState.
1168 The (n,stack) pair is just used for error reporting.
1169 n is always the depth of the stack.
1170 The stack is the stack of Insts being reduced: to produce X
1171 I had to produce Y, to produce Y I had to produce Z, and so on.
1174 reduceList (n,stack) try_me wanteds state
1175 | n > opt_MaxContextReductionDepth
1176 = failWithTc (reduceDepthErr n stack)
1182 pprTrace "Jeepers! ReduceContext:" (reduceDepthMsg n stack)
1187 go [] state = returnTc state
1188 go (w:ws) state = reduce (n+1, w:stack) try_me w state `thenTc` \ state' ->
1191 -- Base case: we're done!
1192 reduce stack try_me wanted state
1193 -- It's the same as an existing inst, or a superclass thereof
1194 | isAvailable state wanted
1198 = case try_me wanted of {
1200 DontReduce want_scs -> addIrred want_scs state wanted
1202 ; DontReduceUnlessConstant -> -- It's irreducible (or at least should not be reduced)
1203 -- First, see if the inst can be reduced to a constant in one step
1204 try_simple (addIrred AddSCs) -- Assume want superclasses
1206 ; Free -> -- It's free so just chuck it upstairs
1207 -- First, see if the inst can be reduced to a constant in one step
1210 ; ReduceMe -> -- It should be reduced
1211 lookupInst wanted `thenNF_Tc` \ lookup_result ->
1212 case lookup_result of
1213 GenInst wanteds' rhs -> reduceList stack try_me wanteds' state `thenTc` \ state' ->
1214 addWanted state' wanted rhs wanteds'
1215 SimpleInst rhs -> addWanted state wanted rhs []
1217 NoInstance -> -- No such instance!
1218 -- Add it and its superclasses
1219 addIrred AddSCs state wanted
1223 try_simple do_this_otherwise
1224 = lookupInst wanted `thenNF_Tc` \ lookup_result ->
1225 case lookup_result of
1226 SimpleInst rhs -> addWanted state wanted rhs []
1227 other -> do_this_otherwise state wanted
1232 isAvailable :: RedState -> Inst -> Bool
1233 isAvailable (avails, _) wanted = wanted `elemFM` avails
1234 -- NB: the Ord instance of Inst compares by the class/type info
1235 -- *not* by unique. So
1236 -- d1::C Int == d2::C Int
1238 -------------------------
1239 addFree :: RedState -> Inst -> NF_TcM RedState
1240 -- When an Inst is tossed upstairs as 'free' we nevertheless add it
1241 -- to avails, so that any other equal Insts will be commoned up right
1242 -- here rather than also being tossed upstairs. This is really just
1243 -- an optimisation, and perhaps it is more trouble that it is worth,
1244 -- as the following comments show!
1246 -- NB1: do *not* add superclasses. If we have
1249 -- but a is not bound here, then we *don't* want to derive
1250 -- dn from df here lest we lose sharing.
1252 -- NB2: do *not* add the Inst to avails at all if it's a method.
1253 -- The following situation shows why this is bad:
1254 -- truncate :: forall a. RealFrac a => forall b. Integral b => a -> b
1255 -- From an application (truncate f i) we get
1256 -- t1 = truncate at f
1258 -- If we have also have a second occurrence of truncate, we get
1259 -- t3 = truncate at f
1261 -- When simplifying with i,f free, we might still notice that
1262 -- t1=t3; but alas, the binding for t2 (which mentions t1)
1263 -- will continue to float out!
1264 -- Solution: never put methods in avail till they are captured
1265 -- in which case addFree isn't used
1267 -- NB3: make sure that CCallable/CReturnable use NoRhs rather
1268 -- than BoundTo, else we end up with bogus bindings.
1269 -- c.f. instBindingRequired in addWanted
1270 addFree (avails, frees) free
1271 | isDict free = returnNF_Tc (addToFM avails free avail, free:frees)
1272 | otherwise = returnNF_Tc (avails, free:frees)
1274 avail | instBindingRequired free = BoundTo (instToId free)
1277 addWanted :: RedState -> Inst -> TcExpr -> [Inst] -> NF_TcM RedState
1278 addWanted state@(avails, frees) wanted rhs_expr wanteds
1279 -- Do *not* add superclasses as well. Here's an example of why not
1280 -- class Eq a => Foo a b
1281 -- instance Eq a => Foo [a] a
1282 -- If we are reducing
1284 -- we'll first deduce that it holds (via the instance decl). We
1285 -- must not then overwrite the Eq t constraint with a superclass selection!
1286 -- ToDo: this isn't entirely unsatisfactory, because
1287 -- we may also lose some entirely-legitimate sharing this way
1289 = ASSERT( not (isAvailable state wanted) )
1290 returnNF_Tc (addToFM avails wanted avail, frees)
1292 avail | instBindingRequired wanted = Rhs rhs_expr wanteds
1293 | otherwise = ASSERT( null wanteds ) NoRhs
1295 addGiven :: RedState -> Inst -> NF_TcM RedState
1296 addGiven state given = addAvailAndSCs state given (BoundTo (instToId given))
1298 addIrred :: WantSCs -> RedState -> Inst -> NF_TcM RedState
1299 addIrred NoSCs (avails,frees) irred = returnNF_Tc (addToFM avails irred Irred, frees)
1300 addIrred AddSCs state irred = addAvailAndSCs state irred Irred
1302 addAvailAndSCs :: RedState -> Inst -> Avail -> NF_TcM RedState
1303 addAvailAndSCs (avails, frees) wanted avail
1304 = add_avail_and_scs avails wanted avail `thenNF_Tc` \ avails' ->
1305 returnNF_Tc (avails', frees)
1307 ---------------------
1308 add_avail_and_scs :: Avails -> Inst -> Avail -> NF_TcM Avails
1309 add_avail_and_scs avails wanted avail
1310 = add_scs (addToFM avails wanted avail) wanted
1312 add_scs :: Avails -> Inst -> NF_TcM Avails
1313 -- Add all the superclasses of the Inst to Avails
1314 -- Invariant: the Inst is already in Avails.
1317 | not (isClassDict dict)
1318 = returnNF_Tc avails
1320 | otherwise -- It is a dictionary
1321 = newDictsFromOld dict sc_theta' `thenNF_Tc` \ sc_dicts ->
1322 foldlNF_Tc add_sc avails (zipEqual "add_scs" sc_dicts sc_sels)
1324 (clas, tys) = getDictClassTys dict
1325 (tyvars, sc_theta, sc_sels, _) = classBigSig clas
1326 sc_theta' = substTheta (mkTopTyVarSubst tyvars tys) sc_theta
1328 add_sc avails (sc_dict, sc_sel) -- Add it, and its superclasses
1329 = case lookupFM avails sc_dict of
1330 Just (BoundTo _) -> returnNF_Tc avails -- See Note [SUPER] below
1331 other -> add_avail_and_scs avails sc_dict avail
1333 sc_sel_rhs = DictApp (TyApp (HsVar sc_sel) tys) [instToId dict]
1334 avail = Rhs sc_sel_rhs [dict]
1337 Note [SUPER]. We have to be careful here. If we are *given* d1:Ord a,
1338 and want to deduce (d2:C [a]) where
1340 class Ord a => C a where
1341 instance Ord a => C [a] where ...
1343 Then we'll use the instance decl to deduce C [a] and then add the
1344 superclasses of C [a] to avails. But we must not overwrite the binding
1345 for d1:Ord a (which is given) with a superclass selection or we'll just
1346 build a loop! Hence looking for BoundTo. Crudely, BoundTo is cheaper
1350 %************************************************************************
1352 \section{tcSimplifyTop: defaulting}
1354 %************************************************************************
1357 If a dictionary constrains a type variable which is
1358 * not mentioned in the environment
1359 * and not mentioned in the type of the expression
1360 then it is ambiguous. No further information will arise to instantiate
1361 the type variable; nor will it be generalised and turned into an extra
1362 parameter to a function.
1364 It is an error for this to occur, except that Haskell provided for
1365 certain rules to be applied in the special case of numeric types.
1367 * at least one of its classes is a numeric class, and
1368 * all of its classes are numeric or standard
1369 then the type variable can be defaulted to the first type in the
1370 default-type list which is an instance of all the offending classes.
1372 So here is the function which does the work. It takes the ambiguous
1373 dictionaries and either resolves them (producing bindings) or
1374 complains. It works by splitting the dictionary list by type
1375 variable, and using @disambigOne@ to do the real business.
1377 @tcSimplifyTop@ is called once per module to simplify all the constant
1378 and ambiguous Insts.
1380 We need to be careful of one case. Suppose we have
1382 instance Num a => Num (Foo a b) where ...
1384 and @tcSimplifyTop@ is given a constraint (Num (Foo x y)). Then it'll simplify
1385 to (Num x), and default x to Int. But what about y??
1387 It's OK: the final zonking stage should zap y to (), which is fine.
1391 tcSimplifyTop :: LIE -> TcM TcDictBinds
1392 tcSimplifyTop wanted_lie
1393 = simpleReduceLoop (text "tcSimplTop") try_me wanteds `thenTc` \ (frees, binds, irreds) ->
1394 ASSERT( null frees )
1397 -- All the non-std ones are definite errors
1398 (stds, non_stds) = partition isStdClassTyVarDict irreds
1400 -- Group by type variable
1401 std_groups = equivClasses cmp_by_tyvar stds
1403 -- Pick the ones which its worth trying to disambiguate
1404 (std_oks, std_bads) = partition worth_a_try std_groups
1406 -- Have a try at disambiguation
1407 -- if the type variable isn't bound
1408 -- up with one of the non-standard classes
1409 worth_a_try group@(d:_) = not (non_std_tyvars `intersectsVarSet` tyVarsOfInst d)
1410 non_std_tyvars = unionVarSets (map tyVarsOfInst non_stds)
1412 -- Collect together all the bad guys
1413 bad_guys = non_stds ++ concat std_bads
1415 -- Disambiguate the ones that look feasible
1416 mapTc disambigGroup std_oks `thenTc` \ binds_ambig ->
1418 -- And complain about the ones that don't
1419 -- This group includes both non-existent instances
1420 -- e.g. Num (IO a) and Eq (Int -> Int)
1421 -- and ambiguous dictionaries
1423 addTopAmbigErrs bad_guys `thenNF_Tc_`
1425 returnTc (binds `andMonoBinds` andMonoBindList binds_ambig)
1427 wanteds = lieToList wanted_lie
1428 try_me inst = ReduceMe
1430 d1 `cmp_by_tyvar` d2 = get_tv d1 `compare` get_tv d2
1432 get_tv d = case getDictClassTys d of
1433 (clas, [ty]) -> tcGetTyVar "tcSimplify" ty
1434 get_clas d = case getDictClassTys d of
1435 (clas, [ty]) -> clas
1438 @disambigOne@ assumes that its arguments dictionaries constrain all
1439 the same type variable.
1441 ADR Comment 20/6/94: I've changed the @CReturnable@ case to default to
1442 @()@ instead of @Int@. I reckon this is the Right Thing to do since
1443 the most common use of defaulting is code like:
1445 _ccall_ foo `seqPrimIO` bar
1447 Since we're not using the result of @foo@, the result if (presumably)
1451 disambigGroup :: [Inst] -- All standard classes of form (C a)
1455 | any isNumericClass classes -- Guaranteed all standard classes
1456 -- see comment at the end of function for reasons as to
1457 -- why the defaulting mechanism doesn't apply to groups that
1458 -- include CCallable or CReturnable dicts.
1459 && not (any isCcallishClass classes)
1460 = -- THE DICTS OBEY THE DEFAULTABLE CONSTRAINT
1461 -- SO, TRY DEFAULT TYPES IN ORDER
1463 -- Failure here is caused by there being no type in the
1464 -- default list which can satisfy all the ambiguous classes.
1465 -- For example, if Real a is reqd, but the only type in the
1466 -- default list is Int.
1467 tcGetDefaultTys `thenNF_Tc` \ default_tys ->
1469 try_default [] -- No defaults work, so fail
1472 try_default (default_ty : default_tys)
1473 = tryTc_ (try_default default_tys) $ -- If default_ty fails, we try
1474 -- default_tys instead
1475 tcSimplifyCheckThetas [] theta `thenTc` \ _ ->
1478 theta = [mkClassPred clas [default_ty] | clas <- classes]
1480 -- See if any default works, and if so bind the type variable to it
1481 -- If not, add an AmbigErr
1482 recoverTc (addAmbigErrs dicts `thenNF_Tc_`
1483 returnTc EmptyMonoBinds) $
1485 try_default default_tys `thenTc` \ chosen_default_ty ->
1487 -- Bind the type variable and reduce the context, for real this time
1488 unifyTauTy chosen_default_ty (mkTyVarTy tyvar) `thenTc_`
1489 simpleReduceLoop (text "disambig" <+> ppr dicts)
1490 try_me dicts `thenTc` \ (frees, binds, ambigs) ->
1491 WARN( not (null frees && null ambigs), ppr frees $$ ppr ambigs )
1492 warnDefault dicts chosen_default_ty `thenTc_`
1495 | all isCreturnableClass classes
1496 = -- Default CCall stuff to (); we don't even both to check that () is an
1497 -- instance of CReturnable, because we know it is.
1498 unifyTauTy (mkTyVarTy tyvar) unitTy `thenTc_`
1499 returnTc EmptyMonoBinds
1501 | otherwise -- No defaults
1502 = addAmbigErrs dicts `thenNF_Tc_`
1503 returnTc EmptyMonoBinds
1506 try_me inst = ReduceMe -- This reduce should not fail
1507 tyvar = get_tv (head dicts) -- Should be non-empty
1508 classes = map get_clas dicts
1511 [Aside - why the defaulting mechanism is turned off when
1512 dealing with arguments and results to ccalls.
1514 When typechecking _ccall_s, TcExpr ensures that the external
1515 function is only passed arguments (and in the other direction,
1516 results) of a restricted set of 'native' types. This is
1517 implemented via the help of the pseudo-type classes,
1518 @CReturnable@ (CR) and @CCallable@ (CC.)
1520 The interaction between the defaulting mechanism for numeric
1521 values and CC & CR can be a bit puzzling to the user at times.
1530 What type has 'x' got here? That depends on the default list
1531 in operation, if it is equal to Haskell 98's default-default
1532 of (Integer, Double), 'x' has type Double, since Integer
1533 is not an instance of CR. If the default list is equal to
1534 Haskell 1.4's default-default of (Int, Double), 'x' has type
1537 To try to minimise the potential for surprises here, the
1538 defaulting mechanism is turned off in the presence of
1539 CCallable and CReturnable.
1544 %************************************************************************
1546 \subsection[simple]{@Simple@ versions}
1548 %************************************************************************
1550 Much simpler versions when there are no bindings to make!
1552 @tcSimplifyThetas@ simplifies class-type constraints formed by
1553 @deriving@ declarations and when specialising instances. We are
1554 only interested in the simplified bunch of class/type constraints.
1556 It simplifies to constraints of the form (C a b c) where
1557 a,b,c are type variables. This is required for the context of
1558 instance declarations.
1561 tcSimplifyThetas :: ThetaType -- Wanted
1562 -> TcM ThetaType -- Needed
1564 tcSimplifyThetas wanteds
1565 = doptsTc Opt_GlasgowExts `thenNF_Tc` \ glaExts ->
1566 reduceSimple [] wanteds `thenNF_Tc` \ irreds ->
1568 -- For multi-param Haskell, check that the returned dictionaries
1569 -- don't have any of the form (C Int Bool) for which
1570 -- we expect an instance here
1571 -- For Haskell 98, check that all the constraints are of the form C a,
1572 -- where a is a type variable
1573 bad_guys | glaExts = [pred | pred <- irreds,
1574 isEmptyVarSet (tyVarsOfPred pred)]
1575 | otherwise = [pred | pred <- irreds,
1576 not (isTyVarClassPred pred)]
1578 if null bad_guys then
1581 mapNF_Tc addNoInstErr bad_guys `thenNF_Tc_`
1585 @tcSimplifyCheckThetas@ just checks class-type constraints, essentially;
1586 used with \tr{default} declarations. We are only interested in
1587 whether it worked or not.
1590 tcSimplifyCheckThetas :: ThetaType -- Given
1591 -> ThetaType -- Wanted
1594 tcSimplifyCheckThetas givens wanteds
1595 = reduceSimple givens wanteds `thenNF_Tc` \ irreds ->
1599 mapNF_Tc addNoInstErr irreds `thenNF_Tc_`
1605 type AvailsSimple = FiniteMap PredType Bool
1606 -- True => irreducible
1607 -- False => given, or can be derived from a given or from an irreducible
1609 reduceSimple :: ThetaType -- Given
1610 -> ThetaType -- Wanted
1611 -> NF_TcM ThetaType -- Irreducible
1613 reduceSimple givens wanteds
1614 = reduce_simple (0,[]) givens_fm wanteds `thenNF_Tc` \ givens_fm' ->
1615 returnNF_Tc [pred | (pred,True) <- fmToList givens_fm']
1617 givens_fm = foldl addNonIrred emptyFM givens
1619 reduce_simple :: (Int,ThetaType) -- Stack
1622 -> NF_TcM AvailsSimple
1624 reduce_simple (n,stack) avails wanteds
1627 go avails [] = returnNF_Tc avails
1628 go avails (w:ws) = reduce_simple_help (n+1,w:stack) avails w `thenNF_Tc` \ avails' ->
1631 reduce_simple_help stack givens wanted
1632 | wanted `elemFM` givens
1633 = returnNF_Tc givens
1635 | Just (clas, tys) <- getClassPredTys_maybe wanted
1636 = lookupSimpleInst clas tys `thenNF_Tc` \ maybe_theta ->
1638 Nothing -> returnNF_Tc (addSimpleIrred givens wanted)
1639 Just theta -> reduce_simple stack (addNonIrred givens wanted) theta
1642 = returnNF_Tc (addSimpleIrred givens wanted)
1644 addSimpleIrred :: AvailsSimple -> PredType -> AvailsSimple
1645 addSimpleIrred givens pred
1646 = addSCs (addToFM givens pred True) pred
1648 addNonIrred :: AvailsSimple -> PredType -> AvailsSimple
1649 addNonIrred givens pred
1650 = addSCs (addToFM givens pred False) pred
1653 | not (isClassPred pred) = givens
1654 | otherwise = foldl add givens sc_theta
1656 Just (clas,tys) = getClassPredTys_maybe pred
1657 (tyvars, sc_theta_tmpl, _, _) = classBigSig clas
1658 sc_theta = substTheta (mkTopTyVarSubst tyvars tys) sc_theta_tmpl
1661 = case lookupFM givens ct of
1662 Nothing -> -- Add it and its superclasses
1663 addSCs (addToFM givens ct False) ct
1665 Just True -> -- Set its flag to False; superclasses already done
1666 addToFM givens ct False
1668 Just False -> -- Already done
1674 %************************************************************************
1676 \section{Errors and contexts}
1678 %************************************************************************
1680 ToDo: for these error messages, should we note the location as coming
1681 from the insts, or just whatever seems to be around in the monad just
1685 groupInsts :: [Inst] -> [[Inst]]
1686 -- Group together insts with the same origin
1687 -- We want to report them together in error messages
1689 groupInsts (inst:insts) = (inst:friends) : groupInsts others
1691 -- (It may seem a bit crude to compare the error messages,
1692 -- but it makes sure that we combine just what the user sees,
1693 -- and it avoids need equality on InstLocs.)
1694 (friends, others) = partition is_friend insts
1695 loc_msg = showSDoc (pprInstLoc (instLoc inst))
1696 is_friend friend = showSDoc (pprInstLoc (instLoc friend)) == loc_msg
1699 addTopAmbigErrs dicts
1700 = mapNF_Tc (addTopInstanceErrs tidy_env) (groupInsts no_insts) `thenNF_Tc_`
1701 mapNF_Tc (addTopIPErrs tidy_env) (groupInsts bad_ips) `thenNF_Tc_`
1702 mapNF_Tc (addAmbigErr tidy_env) ambigs `thenNF_Tc_`
1705 fixed_tvs = oclose (predsOfInsts tidy_dicts) emptyVarSet
1706 (tidy_env, tidy_dicts) = tidyInsts dicts
1707 (bad_ips, non_ips) = partition is_ip tidy_dicts
1708 (no_insts, ambigs) = partition no_inst non_ips
1709 is_ip d = any isIPPred (predsOfInst d)
1710 no_inst d = not (isTyVarDict d) || tyVarsOfInst d `subVarSet` fixed_tvs
1713 plural xs = char 's'
1715 addTopIPErrs tidy_env tidy_dicts
1716 = addInstErrTcM (instLoc (head tidy_dicts))
1718 ptext SLIT("Unbound implicit parameter") <> plural tidy_dicts <+> pprInsts tidy_dicts)
1720 -- Used for top-level irreducibles
1721 addTopInstanceErrs tidy_env tidy_dicts
1722 = addInstErrTcM (instLoc (head tidy_dicts))
1724 ptext SLIT("No instance") <> plural tidy_dicts <+>
1725 ptext SLIT("for") <+> pprInsts tidy_dicts)
1728 = mapNF_Tc (addAmbigErr tidy_env) tidy_dicts
1730 (tidy_env, tidy_dicts) = tidyInsts dicts
1732 addAmbigErr tidy_env tidy_dict
1733 = addInstErrTcM (instLoc tidy_dict)
1735 sep [text "Ambiguous type variable(s)" <+> pprQuotedList ambig_tvs,
1736 nest 4 (text "in the constraint" <+> quotes (pprInst tidy_dict))])
1738 ambig_tvs = varSetElems (tyVarsOfInst tidy_dict)
1740 warnDefault dicts default_ty
1741 = doptsTc Opt_WarnTypeDefaults `thenTc` \ warn_flag ->
1742 tcAddSrcLoc (get_loc (head dicts)) (warnTc warn_flag warn_msg)
1745 (_, tidy_dicts) = tidyInsts dicts
1746 get_loc i = case instLoc i of { (_,loc,_) -> loc }
1747 warn_msg = vcat [ptext SLIT("Defaulting the following constraint(s) to type") <+>
1748 quotes (ppr default_ty),
1749 pprInstsInFull tidy_dicts]
1751 complainCheck doc givens irreds
1752 = mapNF_Tc zonkInst given_dicts `thenNF_Tc` \ givens' ->
1753 mapNF_Tc (addNoInstanceErrs doc givens') (groupInsts irreds) `thenNF_Tc_`
1756 given_dicts = filter isDict givens
1757 -- Filter out methods, which are only added to
1758 -- the given set as an optimisation
1760 addNoInstanceErrs what_doc givens dicts
1761 = tcGetInstEnv `thenNF_Tc` \ inst_env ->
1763 (tidy_env1, tidy_givens) = tidyInsts givens
1764 (tidy_env2, tidy_dicts) = tidyMoreInsts tidy_env1 dicts
1766 doc = vcat [sep [herald <+> pprInsts tidy_dicts,
1767 nest 4 $ ptext SLIT("from the context") <+> pprInsts tidy_givens],
1769 ptext SLIT("Probable fix:"),
1773 herald = ptext SLIT("Could not") <+> unambig_doc <+> ptext SLIT("deduce")
1774 unambig_doc | ambig_overlap = ptext SLIT("unambiguously")
1777 -- The error message when we don't find a suitable instance
1778 -- is complicated by the fact that sometimes this is because
1779 -- there is no instance, and sometimes it's because there are
1780 -- too many instances (overlap). See the comments in TcEnv.lhs
1781 -- with the InstEnv stuff.
1784 | not ambig_overlap = empty
1786 = vcat [ptext SLIT("The choice of (overlapping) instance declaration"),
1787 nest 4 (ptext SLIT("depends on the instantiation of") <+>
1788 quotes (pprWithCommas ppr (varSetElems (tyVarsOfInsts tidy_dicts))))]
1790 fix1 = sep [ptext SLIT("Add") <+> pprInsts tidy_dicts,
1791 ptext SLIT("to the") <+> what_doc]
1793 fix2 | null instance_dicts
1796 = ptext SLIT("Or add an instance declaration for") <+> pprInsts instance_dicts
1798 instance_dicts = [d | d <- tidy_dicts, isClassDict d, not (isTyVarDict d)]
1799 -- Insts for which it is worth suggesting an adding an instance declaration
1800 -- Exclude implicit parameters, and tyvar dicts
1802 -- Checks for the ambiguous case when we have overlapping instances
1803 ambig_overlap = any ambig_overlap1 dicts
1806 = case lookupInstEnv inst_env clas tys of
1807 NoMatch ambig -> ambig
1811 (clas,tys) = getDictClassTys dict
1813 addInstErrTcM (instLoc (head dicts)) (tidy_env2, doc)
1815 -- Used for the ...Thetas variants; all top level
1817 = addErrTc (ptext SLIT("No instance for") <+> quotes (ppr pred))
1819 reduceDepthErr n stack
1820 = vcat [ptext SLIT("Context reduction stack overflow; size =") <+> int n,
1821 ptext SLIT("Use -fcontext-stack20 to increase stack size to (e.g.) 20"),
1822 nest 4 (pprInstsInFull stack)]
1824 reduceDepthMsg n stack = nest 4 (pprInstsInFull stack)
1826 -----------------------------------------------
1828 = addErrTc (sep [ptext SLIT("Cannot generalise these overloadings (in a _ccall_):"),
1829 nest 4 (ppr inst <+> pprInstLoc (instLoc inst))])