2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[TcSimplify]{TcSimplify}
10 tcSimplifyInfer, tcSimplifyInferCheck,
11 tcSimplifyCheck, tcSimplifyRestricted,
12 tcSimplifyToDicts, tcSimplifyIPs, tcSimplifyTop,
15 tcSimplifyDeriv, tcSimplifyDefault,
19 #include "HsVersions.h"
21 import {-# SOURCE #-} TcUnify( unifyTauTy )
23 import HsSyn ( MonoBinds(..), HsExpr(..), andMonoBinds, andMonoBindList )
24 import TcHsSyn ( TcExpr, TcId,
25 TcMonoBinds, TcDictBinds
29 import Inst ( lookupInst, LookupInstResult(..),
30 tyVarsOfInst, fdPredsOfInsts, fdPredsOfInst, newDicts,
31 isDict, isClassDict, isLinearInst, linearInstType,
32 isStdClassTyVarDict, isMethodFor, isMethod,
33 instToId, tyVarsOfInsts, cloneDict,
34 ipNamesOfInsts, ipNamesOfInst, dictPred,
35 instBindingRequired, instCanBeGeneralised,
36 newDictsFromOld, tcInstClassOp,
37 getDictClassTys, isTyVarDict,
38 instLoc, zonkInst, tidyInsts, tidyMoreInsts,
39 Inst, pprInsts, pprInstsInFull,
40 isIPDict, isInheritableInst
42 import TcEnv ( tcGetGlobalTyVars, tcGetInstEnv, tcLookupId, findGlobals )
43 import InstEnv ( lookupInstEnv, classInstEnv, InstLookupResult(..) )
44 import TcMType ( zonkTcTyVarsAndFV, tcInstTyVars, checkAmbiguity )
45 import TcType ( TcTyVar, TcTyVarSet, ThetaType, TyVarDetails(VanillaTv),
46 mkClassPred, isOverloadedTy, mkTyConApp,
47 mkTyVarTy, tcGetTyVar, isTyVarClassPred, mkTyVarTys,
49 import Id ( idType, mkUserLocal )
51 import Name ( getOccName, getSrcLoc )
52 import NameSet ( NameSet, mkNameSet, elemNameSet )
53 import Class ( classBigSig )
54 import FunDeps ( oclose, grow, improve, pprEquationDoc )
55 import PrelInfo ( isNumericClass, isCreturnableClass, isCcallishClass )
56 import PrelNames ( splitName, fstName, sndName )
58 import Subst ( mkTopTyVarSubst, substTheta, substTy )
59 import TysWiredIn ( unitTy, pairTyCon )
60 import ErrUtils ( Message )
62 import VarEnv ( TidyEnv )
65 import ListSetOps ( equivClasses )
66 import Util ( zipEqual, isSingleton )
67 import List ( partition )
72 %************************************************************************
76 %************************************************************************
78 --------------------------------------
79 Notes on quantification
80 --------------------------------------
82 Suppose we are about to do a generalisation step.
87 C the constraints from that RHS
89 The game is to figure out
91 Q the set of type variables over which to quantify
92 Ct the constraints we will *not* quantify over
93 Cq the constraints we will quantify over
95 So we're going to infer the type
99 and float the constraints Ct further outwards.
101 Here are the things that *must* be true:
103 (A) Q intersect fv(G) = EMPTY limits how big Q can be
104 (B) Q superset fv(Cq union T) \ oclose(fv(G),C) limits how small Q can be
106 (A) says we can't quantify over a variable that's free in the
107 environment. (B) says we must quantify over all the truly free
108 variables in T, else we won't get a sufficiently general type. We do
109 not *need* to quantify over any variable that is fixed by the free
110 vars of the environment G.
112 BETWEEN THESE TWO BOUNDS, ANY Q WILL DO!
114 Example: class H x y | x->y where ...
116 fv(G) = {a} C = {H a b, H c d}
119 (A) Q intersect {a} is empty
120 (B) Q superset {a,b,c,d} \ oclose({a}, C) = {a,b,c,d} \ {a,b} = {c,d}
122 So Q can be {c,d}, {b,c,d}
124 Other things being equal, however, we'd like to quantify over as few
125 variables as possible: smaller types, fewer type applications, more
126 constraints can get into Ct instead of Cq.
129 -----------------------------------------
132 fv(T) the free type vars of T
134 oclose(vs,C) The result of extending the set of tyvars vs
135 using the functional dependencies from C
137 grow(vs,C) The result of extend the set of tyvars vs
138 using all conceivable links from C.
140 E.g. vs = {a}, C = {H [a] b, K (b,Int) c, Eq e}
141 Then grow(vs,C) = {a,b,c}
143 Note that grow(vs,C) `superset` grow(vs,simplify(C))
144 That is, simplfication can only shrink the result of grow.
147 oclose is conservative one way: v `elem` oclose(vs,C) => v is definitely fixed by vs
148 grow is conservative the other way: if v might be fixed by vs => v `elem` grow(vs,C)
151 -----------------------------------------
155 Here's a good way to choose Q:
157 Q = grow( fv(T), C ) \ oclose( fv(G), C )
159 That is, quantify over all variable that that MIGHT be fixed by the
160 call site (which influences T), but which aren't DEFINITELY fixed by
161 G. This choice definitely quantifies over enough type variables,
162 albeit perhaps too many.
164 Why grow( fv(T), C ) rather than fv(T)? Consider
166 class H x y | x->y where ...
171 If we used fv(T) = {c} we'd get the type
173 forall c. H c d => c -> b
175 And then if the fn was called at several different c's, each of
176 which fixed d differently, we'd get a unification error, because
177 d isn't quantified. Solution: quantify d. So we must quantify
178 everything that might be influenced by c.
180 Why not oclose( fv(T), C )? Because we might not be able to see
181 all the functional dependencies yet:
183 class H x y | x->y where ...
184 instance H x y => Eq (T x y) where ...
189 Now oclose(fv(T),C) = {c}, because the functional dependency isn't
190 apparent yet, and that's wrong. We must really quantify over d too.
193 There really isn't any point in quantifying over any more than
194 grow( fv(T), C ), because the call sites can't possibly influence
195 any other type variables.
199 --------------------------------------
201 --------------------------------------
203 It's very hard to be certain when a type is ambiguous. Consider
207 instance H x y => K (x,y)
209 Is this type ambiguous?
210 forall a b. (K (a,b), Eq b) => a -> a
212 Looks like it! But if we simplify (K (a,b)) we get (H a b) and
213 now we see that a fixes b. So we can't tell about ambiguity for sure
214 without doing a full simplification. And even that isn't possible if
215 the context has some free vars that may get unified. Urgle!
217 Here's another example: is this ambiguous?
218 forall a b. Eq (T b) => a -> a
219 Not if there's an insance decl (with no context)
220 instance Eq (T b) where ...
222 You may say of this example that we should use the instance decl right
223 away, but you can't always do that:
225 class J a b where ...
226 instance J Int b where ...
228 f :: forall a b. J a b => a -> a
230 (Notice: no functional dependency in J's class decl.)
231 Here f's type is perfectly fine, provided f is only called at Int.
232 It's premature to complain when meeting f's signature, or even
233 when inferring a type for f.
237 However, we don't *need* to report ambiguity right away. It'll always
238 show up at the call site.... and eventually at main, which needs special
239 treatment. Nevertheless, reporting ambiguity promptly is an excellent thing.
241 So here's the plan. We WARN about probable ambiguity if
243 fv(Cq) is not a subset of oclose(fv(T) union fv(G), C)
245 (all tested before quantification).
246 That is, all the type variables in Cq must be fixed by the the variables
247 in the environment, or by the variables in the type.
249 Notice that we union before calling oclose. Here's an example:
251 class J a b c | a b -> c
255 forall b c. (J a b c) => b -> b
257 Only if we union {a} from G with {b} from T before using oclose,
258 do we see that c is fixed.
260 It's a bit vague exactly which C we should use for this oclose call. If we
261 don't fix enough variables we might complain when we shouldn't (see
262 the above nasty example). Nothing will be perfect. That's why we can
263 only issue a warning.
266 Can we ever be *certain* about ambiguity? Yes: if there's a constraint
268 c in C such that fv(c) intersect (fv(G) union fv(T)) = EMPTY
270 then c is a "bubble"; there's no way it can ever improve, and it's
271 certainly ambiguous. UNLESS it is a constant (sigh). And what about
276 instance H x y => K (x,y)
278 Is this type ambiguous?
279 forall a b. (K (a,b), Eq b) => a -> a
281 Urk. The (Eq b) looks "definitely ambiguous" but it isn't. What we are after
282 is a "bubble" that's a set of constraints
284 Cq = Ca union Cq' st fv(Ca) intersect (fv(Cq') union fv(T) union fv(G)) = EMPTY
286 Hence another idea. To decide Q start with fv(T) and grow it
287 by transitive closure in Cq (no functional dependencies involved).
288 Now partition Cq using Q, leaving the definitely-ambiguous and probably-ok.
289 The definitely-ambiguous can then float out, and get smashed at top level
290 (which squashes out the constants, like Eq (T a) above)
293 --------------------------------------
294 Notes on principal types
295 --------------------------------------
300 f x = let g y = op (y::Int) in True
302 Here the principal type of f is (forall a. a->a)
303 but we'll produce the non-principal type
304 f :: forall a. C Int => a -> a
307 --------------------------------------
308 Notes on implicit parameters
309 --------------------------------------
311 Question 1: can we "inherit" implicit parameters
312 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
317 where f is *not* a top-level binding.
318 From the RHS of f we'll get the constraint (?y::Int).
319 There are two types we might infer for f:
323 (so we get ?y from the context of f's definition), or
325 f :: (?y::Int) => Int -> Int
327 At first you might think the first was better, becuase then
328 ?y behaves like a free variable of the definition, rather than
329 having to be passed at each call site. But of course, the WHOLE
330 IDEA is that ?y should be passed at each call site (that's what
331 dynamic binding means) so we'd better infer the second.
333 BOTTOM LINE: when *inferring types* you *must* quantify
334 over implicit parameters. See the predicate isFreeWhenInferring.
337 Question 2: type signatures
338 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
339 BUT WATCH OUT: When you supply a type signature, we can't force you
340 to quantify over implicit parameters. For example:
344 This is perfectly reasonable. We do not want to insist on
346 (?x + 1) :: (?x::Int => Int)
348 That would be silly. Here, the definition site *is* the occurrence site,
349 so the above strictures don't apply. Hence the difference between
350 tcSimplifyCheck (which *does* allow implicit paramters to be inherited)
351 and tcSimplifyCheckBind (which does not).
353 What about when you supply a type signature for a binding?
354 Is it legal to give the following explicit, user type
355 signature to f, thus:
360 At first sight this seems reasonable, but it has the nasty property
361 that adding a type signature changes the dynamic semantics.
364 (let f x = (x::Int) + ?y
365 in (f 3, f 3 with ?y=5)) with ?y = 6
371 in (f 3, f 3 with ?y=5)) with ?y = 6
375 Indeed, simply inlining f (at the Haskell source level) would change the
378 Nevertheless, as Launchbury says (email Oct 01) we can't really give the
379 semantics for a Haskell program without knowing its typing, so if you
380 change the typing you may change the semantics.
382 To make things consistent in all cases where we are *checking* against
383 a supplied signature (as opposed to inferring a type), we adopt the
386 a signature does not need to quantify over implicit params.
388 [This represents a (rather marginal) change of policy since GHC 5.02,
389 which *required* an explicit signature to quantify over all implicit
390 params for the reasons mentioned above.]
392 But that raises a new question. Consider
394 Given (signature) ?x::Int
395 Wanted (inferred) ?x::Int, ?y::Bool
397 Clearly we want to discharge the ?x and float the ?y out. But
398 what is the criterion that distinguishes them? Clearly it isn't
399 what free type variables they have. The Right Thing seems to be
400 to float a constraint that
401 neither mentions any of the quantified type variables
402 nor any of the quantified implicit parameters
404 See the predicate isFreeWhenChecking.
407 Question 3: monomorphism
408 ~~~~~~~~~~~~~~~~~~~~~~~~
409 There's a nasty corner case when the monomorphism restriction bites:
413 The argument above suggests that we *must* generalise
414 over the ?y parameter, to get
415 z :: (?y::Int) => Int,
416 but the monomorphism restriction says that we *must not*, giving
418 Why does the momomorphism restriction say this? Because if you have
420 let z = x + ?y in z+z
422 you might not expect the addition to be done twice --- but it will if
423 we follow the argument of Question 2 and generalise over ?y.
429 (A) Always generalise over implicit parameters
430 Bindings that fall under the monomorphism restriction can't
434 * Inlining remains valid
435 * No unexpected loss of sharing
436 * But simple bindings like
438 will be rejected, unless you add an explicit type signature
439 (to avoid the monomorphism restriction)
440 z :: (?y::Int) => Int
442 This seems unacceptable
444 (B) Monomorphism restriction "wins"
445 Bindings that fall under the monomorphism restriction can't
447 Always generalise over implicit parameters *except* for bindings
448 that fall under the monomorphism restriction
451 * Inlining isn't valid in general
452 * No unexpected loss of sharing
453 * Simple bindings like
455 accepted (get value of ?y from binding site)
457 (C) Always generalise over implicit parameters
458 Bindings that fall under the monomorphism restriction can't
459 be generalised, EXCEPT for implicit parameters
461 * Inlining remains valid
462 * Unexpected loss of sharing (from the extra generalisation)
463 * Simple bindings like
465 accepted (get value of ?y from occurrence sites)
470 None of these choices seems very satisfactory. But at least we should
471 decide which we want to do.
473 It's really not clear what is the Right Thing To Do. If you see
477 would you expect the value of ?y to be got from the *occurrence sites*
478 of 'z', or from the valuue of ?y at the *definition* of 'z'? In the
479 case of function definitions, the answer is clearly the former, but
480 less so in the case of non-fucntion definitions. On the other hand,
481 if we say that we get the value of ?y from the definition site of 'z',
482 then inlining 'z' might change the semantics of the program.
484 Choice (C) really says "the monomorphism restriction doesn't apply
485 to implicit parameters". Which is fine, but remember that every
486 innocent binding 'x = ...' that mentions an implicit parameter in
487 the RHS becomes a *function* of that parameter, called at each
488 use of 'x'. Now, the chances are that there are no intervening 'with'
489 clauses that bind ?y, so a decent compiler should common up all
490 those function calls. So I think I strongly favour (C). Indeed,
491 one could make a similar argument for abolishing the monomorphism
492 restriction altogether.
494 BOTTOM LINE: we choose (B) at present. See tcSimplifyRestricted
498 %************************************************************************
500 \subsection{tcSimplifyInfer}
502 %************************************************************************
504 tcSimplify is called when we *inferring* a type. Here's the overall game plan:
506 1. Compute Q = grow( fvs(T), C )
508 2. Partition C based on Q into Ct and Cq. Notice that ambiguous
509 predicates will end up in Ct; we deal with them at the top level
511 3. Try improvement, using functional dependencies
513 4. If Step 3 did any unification, repeat from step 1
514 (Unification can change the result of 'grow'.)
516 Note: we don't reduce dictionaries in step 2. For example, if we have
517 Eq (a,b), we don't simplify to (Eq a, Eq b). So Q won't be different
518 after step 2. However note that we may therefore quantify over more
519 type variables than we absolutely have to.
521 For the guts, we need a loop, that alternates context reduction and
522 improvement with unification. E.g. Suppose we have
524 class C x y | x->y where ...
526 and tcSimplify is called with:
528 Then improvement unifies a with b, giving
531 If we need to unify anything, we rattle round the whole thing all over
538 -> TcTyVarSet -- fv(T); type vars
540 -> TcM ([TcTyVar], -- Tyvars to quantify (zonked)
541 TcDictBinds, -- Bindings
542 [TcId]) -- Dict Ids that must be bound here (zonked)
543 -- Any free (escaping) Insts are tossed into the environment
548 tcSimplifyInfer doc tau_tvs wanted_lie
549 = inferLoop doc (varSetElems tau_tvs)
550 wanted_lie `thenM` \ (qtvs, frees, binds, irreds) ->
552 -- Check for non-generalisable insts
553 mappM_ addCantGenErr (filter (not . instCanBeGeneralised) irreds) `thenM_`
555 extendLIEs frees `thenM_`
556 returnM (qtvs, binds, map instToId irreds)
558 inferLoop doc tau_tvs wanteds
560 zonkTcTyVarsAndFV tau_tvs `thenM` \ tau_tvs' ->
561 mappM zonkInst wanteds `thenM` \ wanteds' ->
562 tcGetGlobalTyVars `thenM` \ gbl_tvs ->
564 preds = fdPredsOfInsts wanteds'
565 qtvs = grow preds tau_tvs' `minusVarSet` oclose preds gbl_tvs
568 | isFreeWhenInferring qtvs inst = Free
569 | isClassDict inst = DontReduceUnlessConstant -- Dicts
570 | otherwise = ReduceMe -- Lits and Methods
572 traceTc (text "infloop" <+> vcat [ppr tau_tvs', ppr wanteds', ppr preds, ppr (grow preds tau_tvs'), ppr qtvs]) `thenM_`
574 reduceContext doc try_me [] wanteds' `thenM` \ (no_improvement, frees, binds, irreds) ->
577 if no_improvement then
578 returnM (varSetElems qtvs, frees, binds, irreds)
580 -- If improvement did some unification, we go round again. There
581 -- are two subtleties:
582 -- a) We start again with irreds, not wanteds
583 -- Using an instance decl might have introduced a fresh type variable
584 -- which might have been unified, so we'd get an infinite loop
585 -- if we started again with wanteds! See example [LOOP]
587 -- b) It's also essential to re-process frees, because unification
588 -- might mean that a type variable that looked free isn't now.
590 -- Hence the (irreds ++ frees)
592 -- However, NOTICE that when we are done, we might have some bindings, but
593 -- the final qtvs might be empty. See [NO TYVARS] below.
595 inferLoop doc tau_tvs (irreds ++ frees) `thenM` \ (qtvs1, frees1, binds1, irreds1) ->
596 returnM (qtvs1, frees1, binds `AndMonoBinds` binds1, irreds1)
601 class If b t e r | b t e -> r
604 class Lte a b c | a b -> c where lte :: a -> b -> c
606 instance (Lte a b l,If l b a c) => Max a b c
608 Wanted: Max Z (S x) y
610 Then we'll reduce using the Max instance to:
611 (Lte Z (S x) l, If l (S x) Z y)
612 and improve by binding l->T, after which we can do some reduction
613 on both the Lte and If constraints. What we *can't* do is start again
614 with (Max Z (S x) y)!
618 class Y a b | a -> b where
621 instance Y [[a]] a where
624 k :: X a -> X a -> X a
626 g :: Num a => [X a] -> [X a]
629 h ys = ys ++ map (k (y [[0]])) xs
631 The excitement comes when simplifying the bindings for h. Initially
632 try to simplify {y @ [[t1]] t2, 0 @ t1}, with initial qtvs = {t2}.
633 From this we get t1:=:t2, but also various bindings. We can't forget
634 the bindings (because of [LOOP]), but in fact t1 is what g is
637 The net effect of [NO TYVARS]
640 isFreeWhenInferring :: TyVarSet -> Inst -> Bool
641 isFreeWhenInferring qtvs inst
642 = isFreeWrtTyVars qtvs inst -- Constrains no quantified vars
643 && isInheritableInst inst -- And no implicit parameter involved
644 -- (see "Notes on implicit parameters")
646 isFreeWhenChecking :: TyVarSet -- Quantified tyvars
647 -> NameSet -- Quantified implicit parameters
649 isFreeWhenChecking qtvs ips inst
650 = isFreeWrtTyVars qtvs inst
651 && isFreeWrtIPs ips inst
653 isFreeWrtTyVars qtvs inst = not (tyVarsOfInst inst `intersectsVarSet` qtvs)
654 isFreeWrtIPs ips inst = not (any (`elemNameSet` ips) (ipNamesOfInst inst))
658 %************************************************************************
660 \subsection{tcSimplifyCheck}
662 %************************************************************************
664 @tcSimplifyCheck@ is used when we know exactly the set of variables
665 we are going to quantify over. For example, a class or instance declaration.
670 -> [TcTyVar] -- Quantify over these
673 -> TcM TcDictBinds -- Bindings
675 -- tcSimplifyCheck is used when checking expression type signatures,
676 -- class decls, instance decls etc.
678 -- NB: tcSimplifyCheck does not consult the
679 -- global type variables in the environment; so you don't
680 -- need to worry about setting them before calling tcSimplifyCheck
681 tcSimplifyCheck doc qtvs givens wanted_lie
682 = tcSimplCheck doc get_qtvs
683 givens wanted_lie `thenM` \ (qtvs', binds) ->
686 get_qtvs = zonkTcTyVarsAndFV qtvs
689 -- tcSimplifyInferCheck is used when we know the constraints we are to simplify
690 -- against, but we don't know the type variables over which we are going to quantify.
691 -- This happens when we have a type signature for a mutually recursive group
694 -> TcTyVarSet -- fv(T)
697 -> TcM ([TcTyVar], -- Variables over which to quantify
698 TcDictBinds) -- Bindings
700 tcSimplifyInferCheck doc tau_tvs givens wanted_lie
701 = tcSimplCheck doc get_qtvs givens wanted_lie
703 -- Figure out which type variables to quantify over
704 -- You might think it should just be the signature tyvars,
705 -- but in bizarre cases you can get extra ones
706 -- f :: forall a. Num a => a -> a
707 -- f x = fst (g (x, head [])) + 1
709 -- Here we infer g :: forall a b. a -> b -> (b,a)
710 -- We don't want g to be monomorphic in b just because
711 -- f isn't quantified over b.
712 all_tvs = varSetElems (tau_tvs `unionVarSet` tyVarsOfInsts givens)
714 get_qtvs = zonkTcTyVarsAndFV all_tvs `thenM` \ all_tvs' ->
715 tcGetGlobalTyVars `thenM` \ gbl_tvs ->
717 qtvs = all_tvs' `minusVarSet` gbl_tvs
718 -- We could close gbl_tvs, but its not necessary for
719 -- soundness, and it'll only affect which tyvars, not which
720 -- dictionaries, we quantify over
725 Here is the workhorse function for all three wrappers.
728 tcSimplCheck doc get_qtvs givens wanted_lie
729 = check_loop givens wanted_lie `thenM` \ (qtvs, frees, binds, irreds) ->
731 -- Complain about any irreducible ones
732 complainCheck doc givens irreds `thenM_`
735 extendLIEs frees `thenM_`
736 returnM (qtvs, binds)
739 ip_set = mkNameSet (ipNamesOfInsts givens)
741 check_loop givens wanteds
743 mappM zonkInst givens `thenM` \ givens' ->
744 mappM zonkInst wanteds `thenM` \ wanteds' ->
745 get_qtvs `thenM` \ qtvs' ->
749 -- When checking against a given signature we always reduce
750 -- until we find a match against something given, or can't reduce
751 try_me inst | isFreeWhenChecking qtvs' ip_set inst = Free
752 | otherwise = ReduceMe
754 reduceContext doc try_me givens' wanteds' `thenM` \ (no_improvement, frees, binds, irreds) ->
757 if no_improvement then
758 returnM (varSetElems qtvs', frees, binds, irreds)
760 check_loop givens' (irreds ++ frees) `thenM` \ (qtvs', frees1, binds1, irreds1) ->
761 returnM (qtvs', frees1, binds `AndMonoBinds` binds1, irreds1)
765 %************************************************************************
767 \subsection{tcSimplifyRestricted}
769 %************************************************************************
772 tcSimplifyRestricted -- Used for restricted binding groups
773 -- i.e. ones subject to the monomorphism restriction
775 -> TcTyVarSet -- Free in the type of the RHSs
776 -> [Inst] -- Free in the RHSs
777 -> TcM ([TcTyVar], -- Tyvars to quantify (zonked)
778 TcDictBinds) -- Bindings
780 tcSimplifyRestricted doc tau_tvs wanteds
781 = -- First squash out all methods, to find the constrained tyvars
782 -- We can't just take the free vars of wanted_lie because that'll
783 -- have methods that may incidentally mention entirely unconstrained variables
784 -- e.g. a call to f :: Eq a => a -> b -> b
785 -- Here, b is unconstrained. A good example would be
787 -- We want to infer the polymorphic type
788 -- foo :: forall b. b -> b
790 -- 'reduceMe': Reduce as far as we can. Don't stop at
791 -- dicts; the idea is to get rid of as many type
792 -- variables as possible, and we don't want to stop
793 -- at (say) Monad (ST s), because that reduces
794 -- immediately, with no constraint on s.
795 simpleReduceLoop doc reduceMe wanteds `thenM` \ (foo_frees, foo_binds, constrained_dicts) ->
797 -- Next, figure out the tyvars we will quantify over
798 zonkTcTyVarsAndFV (varSetElems tau_tvs) `thenM` \ tau_tvs' ->
799 tcGetGlobalTyVars `thenM` \ gbl_tvs ->
801 constrained_tvs = tyVarsOfInsts constrained_dicts
802 qtvs = (tau_tvs' `minusVarSet` oclose (fdPredsOfInsts constrained_dicts) gbl_tvs)
803 `minusVarSet` constrained_tvs
805 traceTc (text "tcSimplifyRestricted" <+> vcat [
806 pprInsts wanteds, pprInsts foo_frees, pprInsts constrained_dicts,
808 ppr constrained_tvs, ppr tau_tvs', ppr qtvs ]) `thenM_`
810 -- The first step may have squashed more methods than
811 -- necessary, so try again, this time knowing the exact
812 -- set of type variables to quantify over.
814 -- We quantify only over constraints that are captured by qtvs;
815 -- these will just be a subset of non-dicts. This in contrast
816 -- to normal inference (using isFreeWhenInferring) in which we quantify over
817 -- all *non-inheritable* constraints too. This implements choice
818 -- (B) under "implicit parameter and monomorphism" above.
820 -- Remember that we may need to do *some* simplification, to
821 -- (for example) squash {Monad (ST s)} into {}. It's not enough
822 -- just to float all constraints
823 restrict_loop doc qtvs wanteds
824 -- We still need a loop because improvement can take place
825 -- E.g. if we have (C (T a)) and the instance decl
826 -- instance D Int b => C (T a) where ...
827 -- and there's a functional dependency for D. Then we may improve
828 -- the tyep variable 'b'.
830 restrict_loop doc qtvs wanteds
831 = mappM zonkInst wanteds `thenM` \ wanteds' ->
832 zonkTcTyVarsAndFV (varSetElems qtvs) `thenM` \ qtvs' ->
834 try_me inst | isFreeWrtTyVars qtvs' inst = Free
835 | otherwise = ReduceMe
837 reduceContext doc try_me [] wanteds' `thenM` \ (no_improvement, frees, binds, irreds) ->
838 if no_improvement then
839 ASSERT( null irreds )
840 extendLIEs frees `thenM_`
841 returnM (varSetElems qtvs', binds)
843 restrict_loop doc qtvs' (irreds ++ frees) `thenM` \ (qtvs1, binds1) ->
844 returnM (qtvs1, binds `AndMonoBinds` binds1)
848 %************************************************************************
850 \subsection{tcSimplifyToDicts}
852 %************************************************************************
854 On the LHS of transformation rules we only simplify methods and constants,
855 getting dictionaries. We want to keep all of them unsimplified, to serve
856 as the available stuff for the RHS of the rule.
858 The same thing is used for specialise pragmas. Consider
861 {-# SPECIALISE f :: Int -> Int #-}
864 The type checker generates a binding like:
866 f_spec = (f :: Int -> Int)
868 and we want to end up with
870 f_spec = _inline_me_ (f Int dNumInt)
872 But that means that we must simplify the Method for f to (f Int dNumInt)!
873 So tcSimplifyToDicts squeezes out all Methods.
875 IMPORTANT NOTE: we *don't* want to do superclass commoning up. Consider
877 fromIntegral :: (Integral a, Num b) => a -> b
878 {-# RULES "foo" fromIntegral = id :: Int -> Int #-}
880 Here, a=b=Int, and Num Int is a superclass of Integral Int. But we *dont*
884 fromIntegral Int Int dIntegralInt (scsel dIntegralInt) = id Int
886 because the scsel will mess up matching. Instead we want
888 forall dIntegralInt, dNumInt.
889 fromIntegral Int Int dIntegralInt dNumInt = id Int
891 Hence "DontReduce NoSCs"
894 tcSimplifyToDicts :: [Inst] -> TcM (TcDictBinds)
895 tcSimplifyToDicts wanteds
896 = simpleReduceLoop doc try_me wanteds `thenM` \ (frees, binds, irreds) ->
897 -- Since try_me doesn't look at types, we don't need to
898 -- do any zonking, so it's safe to call reduceContext directly
900 extendLIEs irreds `thenM_`
904 doc = text "tcSimplifyToDicts"
906 -- Reduce methods and lits only; stop as soon as we get a dictionary
907 try_me inst | isDict inst = DontReduce NoSCs
908 | otherwise = ReduceMe
913 tcSimplifyBracket is used when simplifying the constraints arising from
914 a Template Haskell bracket [| ... |]. We want to check that there aren't
915 any constraints that can't be satisfied (e.g. Show Foo, where Foo has no
916 Show instance), but we aren't otherwise interested in the results.
917 Nor do we care about ambiguous dictionaries etc. We will type check
918 this bracket again at its usage site.
921 tcSimplifyBracket :: [Inst] -> TcM ()
922 tcSimplifyBracket wanteds
923 = simpleReduceLoop doc reduceMe wanteds `thenM_`
926 doc = text "tcSimplifyBracket"
930 %************************************************************************
932 \subsection{Filtering at a dynamic binding}
934 %************************************************************************
939 we must discharge all the ?x constraints from B. We also do an improvement
940 step; if we have ?x::t1 and ?x::t2 we must unify t1, t2.
942 Actually, the constraints from B might improve the types in ?x. For example
944 f :: (?x::Int) => Char -> Char
947 then the constraint (?x::Int) arising from the call to f will
948 force the binding for ?x to be of type Int.
951 tcSimplifyIPs :: [Inst] -- The implicit parameters bound here
954 tcSimplifyIPs given_ips wanteds
955 = simpl_loop given_ips wanteds `thenM` \ (frees, binds) ->
956 extendLIEs frees `thenM_`
959 doc = text "tcSimplifyIPs" <+> ppr given_ips
960 ip_set = mkNameSet (ipNamesOfInsts given_ips)
962 -- Simplify any methods that mention the implicit parameter
963 try_me inst | isFreeWrtIPs ip_set inst = Free
964 | otherwise = ReduceMe
966 simpl_loop givens wanteds
967 = mappM zonkInst givens `thenM` \ givens' ->
968 mappM zonkInst wanteds `thenM` \ wanteds' ->
970 reduceContext doc try_me givens' wanteds' `thenM` \ (no_improvement, frees, binds, irreds) ->
972 if no_improvement then
973 ASSERT( null irreds )
974 returnM (frees, binds)
976 simpl_loop givens' (irreds ++ frees) `thenM` \ (frees1, binds1) ->
977 returnM (frees1, binds `AndMonoBinds` binds1)
981 %************************************************************************
983 \subsection[binds-for-local-funs]{@bindInstsOfLocalFuns@}
985 %************************************************************************
987 When doing a binding group, we may have @Insts@ of local functions.
988 For example, we might have...
990 let f x = x + 1 -- orig local function (overloaded)
991 f.1 = f Int -- two instances of f
996 The point is: we must drop the bindings for @f.1@ and @f.2@ here,
997 where @f@ is in scope; those @Insts@ must certainly not be passed
998 upwards towards the top-level. If the @Insts@ were binding-ified up
999 there, they would have unresolvable references to @f@.
1001 We pass in an @init_lie@ of @Insts@ and a list of locally-bound @Ids@.
1002 For each method @Inst@ in the @init_lie@ that mentions one of the
1003 @Ids@, we create a binding. We return the remaining @Insts@ (in an
1004 @LIE@), as well as the @HsBinds@ generated.
1007 bindInstsOfLocalFuns :: [Inst] -> [TcId] -> TcM TcMonoBinds
1009 bindInstsOfLocalFuns wanteds local_ids
1010 | null overloaded_ids
1012 = extendLIEs wanteds `thenM_`
1013 returnM EmptyMonoBinds
1016 = simpleReduceLoop doc try_me wanteds `thenM` \ (frees, binds, irreds) ->
1017 ASSERT( null irreds )
1018 extendLIEs frees `thenM_`
1021 doc = text "bindInsts" <+> ppr local_ids
1022 overloaded_ids = filter is_overloaded local_ids
1023 is_overloaded id = isOverloadedTy (idType id)
1025 overloaded_set = mkVarSet overloaded_ids -- There can occasionally be a lot of them
1026 -- so it's worth building a set, so that
1027 -- lookup (in isMethodFor) is faster
1029 try_me inst | isMethodFor overloaded_set inst = ReduceMe
1034 %************************************************************************
1036 \subsection{Data types for the reduction mechanism}
1038 %************************************************************************
1040 The main control over context reduction is here
1044 = ReduceMe -- Try to reduce this
1045 -- If there's no instance, behave exactly like
1046 -- DontReduce: add the inst to
1047 -- the irreductible ones, but don't
1048 -- produce an error message of any kind.
1049 -- It might be quite legitimate such as (Eq a)!
1051 | DontReduce WantSCs -- Return as irreducible
1053 | DontReduceUnlessConstant -- Return as irreducible unless it can
1054 -- be reduced to a constant in one step
1056 | Free -- Return as free
1058 reduceMe :: Inst -> WhatToDo
1059 reduceMe inst = ReduceMe
1061 data WantSCs = NoSCs | AddSCs -- Tells whether we should add the superclasses
1062 -- of a predicate when adding it to the avails
1068 type Avails = FiniteMap Inst Avail
1071 = IsFree -- Used for free Insts
1072 | Irred -- Used for irreducible dictionaries,
1073 -- which are going to be lambda bound
1075 | Given TcId -- Used for dictionaries for which we have a binding
1076 -- e.g. those "given" in a signature
1077 Bool -- True <=> actually consumed (splittable IPs only)
1079 | NoRhs -- Used for Insts like (CCallable f)
1080 -- where no witness is required.
1082 | Rhs -- Used when there is a RHS
1084 [Inst] -- Insts free in the RHS; we need these too
1086 | Linear -- Splittable Insts only.
1087 Int -- The Int is always 2 or more; indicates how
1088 -- many copies are required
1089 Inst -- The splitter
1090 Avail -- Where the "master copy" is
1092 | LinRhss -- Splittable Insts only; this is used only internally
1093 -- by extractResults, where a Linear
1094 -- is turned into an LinRhss
1095 [TcExpr] -- A supply of suitable RHSs
1097 pprAvails avails = vcat [sep [ppr inst, nest 2 (equals <+> pprAvail avail)]
1098 | (inst,avail) <- fmToList avails ]
1100 instance Outputable Avail where
1103 pprAvail NoRhs = text "<no rhs>"
1104 pprAvail IsFree = text "Free"
1105 pprAvail Irred = text "Irred"
1106 pprAvail (Given x b) = text "Given" <+> ppr x <+>
1107 if b then text "(used)" else empty
1108 pprAvail (Rhs rhs bs) = text "Rhs" <+> ppr rhs <+> braces (ppr bs)
1109 pprAvail (Linear n i a) = text "Linear" <+> ppr n <+> braces (ppr i) <+> ppr a
1110 pprAvail (LinRhss rhss) = text "LinRhss" <+> ppr rhss
1113 Extracting the bindings from a bunch of Avails.
1114 The bindings do *not* come back sorted in dependency order.
1115 We assume that they'll be wrapped in a big Rec, so that the
1116 dependency analyser can sort them out later
1120 extractResults :: Avails
1122 -> TcM (TcDictBinds, -- Bindings
1123 [Inst], -- Irreducible ones
1124 [Inst]) -- Free ones
1126 extractResults avails wanteds
1127 = go avails EmptyMonoBinds [] [] wanteds
1129 go avails binds irreds frees []
1130 = returnM (binds, irreds, frees)
1132 go avails binds irreds frees (w:ws)
1133 = case lookupFM avails w of
1134 Nothing -> pprTrace "Urk: extractResults" (ppr w) $
1135 go avails binds irreds frees ws
1137 Just NoRhs -> go avails binds irreds frees ws
1138 Just IsFree -> go (add_free avails w) binds irreds (w:frees) ws
1139 Just Irred -> go (add_given avails w) binds (w:irreds) frees ws
1141 Just (Given id _) -> go avails new_binds irreds frees ws
1143 new_binds | id == instToId w = binds
1144 | otherwise = addBind binds w (HsVar id)
1145 -- The sought Id can be one of the givens, via a superclass chain
1146 -- and then we definitely don't want to generate an x=x binding!
1148 Just (Rhs rhs ws') -> go (add_given avails w) new_binds irreds frees (ws' ++ ws)
1150 new_binds = addBind binds w rhs
1152 Just (Linear n split_inst avail) -- Transform Linear --> LinRhss
1153 -> get_root irreds frees avail w `thenM` \ (irreds', frees', root_id) ->
1154 split n (instToId split_inst) root_id w `thenM` \ (binds', rhss) ->
1155 go (addToFM avails w (LinRhss rhss))
1156 (binds `AndMonoBinds` binds')
1157 irreds' frees' (split_inst : w : ws)
1159 Just (LinRhss (rhs:rhss)) -- Consume one of the Rhss
1160 -> go new_avails new_binds irreds frees ws
1162 new_binds = addBind binds w rhs
1163 new_avails = addToFM avails w (LinRhss rhss)
1165 get_root irreds frees (Given id _) w = returnM (irreds, frees, id)
1166 get_root irreds frees Irred w = cloneDict w `thenM` \ w' ->
1167 returnM (w':irreds, frees, instToId w')
1168 get_root irreds frees IsFree w = cloneDict w `thenM` \ w' ->
1169 returnM (irreds, w':frees, instToId w')
1172 | instBindingRequired w = addToFM avails w (Given (instToId w) True)
1173 | otherwise = addToFM avails w NoRhs
1174 -- NB: make sure that CCallable/CReturnable use NoRhs rather
1175 -- than Given, else we end up with bogus bindings.
1177 add_free avails w | isMethod w = avails
1178 | otherwise = add_given avails w
1180 -- Do *not* replace Free by Given if it's a method.
1181 -- The following situation shows why this is bad:
1182 -- truncate :: forall a. RealFrac a => forall b. Integral b => a -> b
1183 -- From an application (truncate f i) we get
1184 -- t1 = truncate at f
1186 -- If we have also have a second occurrence of truncate, we get
1187 -- t3 = truncate at f
1189 -- When simplifying with i,f free, we might still notice that
1190 -- t1=t3; but alas, the binding for t2 (which mentions t1)
1191 -- will continue to float out!
1192 -- (split n i a) returns: n rhss
1193 -- auxiliary bindings
1194 -- 1 or 0 insts to add to irreds
1197 split :: Int -> TcId -> TcId -> Inst
1198 -> TcM (TcDictBinds, [TcExpr])
1199 -- (split n split_id root_id wanted) returns
1200 -- * a list of 'n' expressions, all of which witness 'avail'
1201 -- * a bunch of auxiliary bindings to support these expressions
1202 -- * one or zero insts needed to witness the whole lot
1203 -- (maybe be zero if the initial Inst is a Given)
1205 -- NB: 'wanted' is just a template
1207 split n split_id root_id wanted
1210 ty = linearInstType wanted
1211 pair_ty = mkTyConApp pairTyCon [ty,ty]
1212 id = instToId wanted
1216 go 1 = returnM (EmptyMonoBinds, [HsVar root_id])
1218 go n = go ((n+1) `div` 2) `thenM` \ (binds1, rhss) ->
1219 expand n rhss `thenM` \ (binds2, rhss') ->
1220 returnM (binds1 `AndMonoBinds` binds2, rhss')
1223 -- Given ((n+1)/2) rhss, make n rhss, using auxiliary bindings
1224 -- e.g. expand 3 [rhs1, rhs2]
1225 -- = ( { x = split rhs1 },
1226 -- [fst x, snd x, rhs2] )
1228 | n `rem` 2 == 0 = go rhss -- n is even
1229 | otherwise = go (tail rhss) `thenM` \ (binds', rhss') ->
1230 returnM (binds', head rhss : rhss')
1232 go rhss = mapAndUnzipM do_one rhss `thenM` \ (binds', rhss') ->
1233 returnM (andMonoBindList binds', concat rhss')
1235 do_one rhs = newUnique `thenM` \ uniq ->
1236 tcLookupId fstName `thenM` \ fst_id ->
1237 tcLookupId sndName `thenM` \ snd_id ->
1239 x = mkUserLocal occ uniq pair_ty loc
1241 returnM (VarMonoBind x (mk_app split_id rhs),
1242 [mk_fs_app fst_id ty x, mk_fs_app snd_id ty x])
1244 mk_fs_app id ty var = HsVar id `TyApp` [ty,ty] `HsApp` HsVar var
1246 mk_app id rhs = HsApp (HsVar id) rhs
1248 addBind binds inst rhs = binds `AndMonoBinds` VarMonoBind (instToId inst) rhs
1252 %************************************************************************
1254 \subsection[reduce]{@reduce@}
1256 %************************************************************************
1258 When the "what to do" predicate doesn't depend on the quantified type variables,
1259 matters are easier. We don't need to do any zonking, unless the improvement step
1260 does something, in which case we zonk before iterating.
1262 The "given" set is always empty.
1265 simpleReduceLoop :: SDoc
1266 -> (Inst -> WhatToDo) -- What to do, *not* based on the quantified type variables
1268 -> TcM ([Inst], -- Free
1270 [Inst]) -- Irreducible
1272 simpleReduceLoop doc try_me wanteds
1273 = mappM zonkInst wanteds `thenM` \ wanteds' ->
1274 reduceContext doc try_me [] wanteds' `thenM` \ (no_improvement, frees, binds, irreds) ->
1275 if no_improvement then
1276 returnM (frees, binds, irreds)
1278 simpleReduceLoop doc try_me (irreds ++ frees) `thenM` \ (frees1, binds1, irreds1) ->
1279 returnM (frees1, binds `AndMonoBinds` binds1, irreds1)
1285 reduceContext :: SDoc
1286 -> (Inst -> WhatToDo)
1289 -> TcM (Bool, -- True <=> improve step did no unification
1291 TcDictBinds, -- Dictionary bindings
1292 [Inst]) -- Irreducible
1294 reduceContext doc try_me givens wanteds
1296 traceTc (text "reduceContext" <+> (vcat [
1297 text "----------------------",
1299 text "given" <+> ppr givens,
1300 text "wanted" <+> ppr wanteds,
1301 text "----------------------"
1304 -- Build the Avail mapping from "givens"
1305 foldlM addGiven emptyFM givens `thenM` \ init_state ->
1308 reduceList (0,[]) try_me wanteds init_state `thenM` \ avails ->
1310 -- Do improvement, using everything in avails
1311 -- In particular, avails includes all superclasses of everything
1312 tcImprove avails `thenM` \ no_improvement ->
1314 extractResults avails wanteds `thenM` \ (binds, irreds, frees) ->
1316 traceTc (text "reduceContext end" <+> (vcat [
1317 text "----------------------",
1319 text "given" <+> ppr givens,
1320 text "wanted" <+> ppr wanteds,
1322 text "avails" <+> pprAvails avails,
1323 text "frees" <+> ppr frees,
1324 text "no_improvement =" <+> ppr no_improvement,
1325 text "----------------------"
1328 returnM (no_improvement, frees, binds, irreds)
1331 = tcGetInstEnv `thenM` \ inst_env ->
1333 preds = [ (pred, pp_loc)
1334 | inst <- keysFM avails,
1335 let pp_loc = pprInstLoc (instLoc inst),
1336 pred <- fdPredsOfInst inst
1338 -- Avails has all the superclasses etc (good)
1339 -- It also has all the intermediates of the deduction (good)
1340 -- It does not have duplicates (good)
1341 -- NB that (?x::t1) and (?x::t2) will be held separately in avails
1342 -- so that improve will see them separate
1343 eqns = improve (classInstEnv inst_env) preds
1348 traceTc (ptext SLIT("Improve:") <+> vcat (map pprEquationDoc eqns)) `thenM_`
1349 mappM_ unify eqns `thenM_`
1352 unify ((qtvs, t1, t2), doc)
1354 tcInstTyVars VanillaTv (varSetElems qtvs) `thenM` \ (_, _, tenv) ->
1355 unifyTauTy (substTy tenv t1) (substTy tenv t2)
1358 The main context-reduction function is @reduce@. Here's its game plan.
1361 reduceList :: (Int,[Inst]) -- Stack (for err msgs)
1362 -- along with its depth
1363 -> (Inst -> WhatToDo)
1370 try_me: given an inst, this function returns
1372 DontReduce return this in "irreds"
1373 Free return this in "frees"
1375 wanteds: The list of insts to reduce
1376 state: An accumulating parameter of type Avails
1377 that contains the state of the algorithm
1379 It returns a Avails.
1381 The (n,stack) pair is just used for error reporting.
1382 n is always the depth of the stack.
1383 The stack is the stack of Insts being reduced: to produce X
1384 I had to produce Y, to produce Y I had to produce Z, and so on.
1387 reduceList (n,stack) try_me wanteds state
1388 | n > opt_MaxContextReductionDepth
1389 = failWithTc (reduceDepthErr n stack)
1395 pprTrace "Jeepers! ReduceContext:" (reduceDepthMsg n stack)
1400 go [] state = returnM state
1401 go (w:ws) state = reduce (n+1, w:stack) try_me w state `thenM` \ state' ->
1404 -- Base case: we're done!
1405 reduce stack try_me wanted state
1406 -- It's the same as an existing inst, or a superclass thereof
1407 | Just avail <- isAvailable state wanted
1408 = if isLinearInst wanted then
1409 addLinearAvailable state avail wanted `thenM` \ (state', wanteds') ->
1410 reduceList stack try_me wanteds' state'
1412 returnM state -- No op for non-linear things
1415 = case try_me wanted of {
1417 DontReduce want_scs -> addIrred want_scs state wanted
1419 ; DontReduceUnlessConstant -> -- It's irreducible (or at least should not be reduced)
1420 -- First, see if the inst can be reduced to a constant in one step
1421 try_simple (addIrred AddSCs) -- Assume want superclasses
1423 ; Free -> -- It's free so just chuck it upstairs
1424 -- First, see if the inst can be reduced to a constant in one step
1427 ; ReduceMe -> -- It should be reduced
1428 lookupInst wanted `thenM` \ lookup_result ->
1429 case lookup_result of
1430 GenInst wanteds' rhs -> reduceList stack try_me wanteds' state `thenM` \ state' ->
1431 addWanted state' wanted rhs wanteds'
1432 SimpleInst rhs -> addWanted state wanted rhs []
1434 NoInstance -> -- No such instance!
1435 -- Add it and its superclasses
1436 addIrred AddSCs state wanted
1440 try_simple do_this_otherwise
1441 = lookupInst wanted `thenM` \ lookup_result ->
1442 case lookup_result of
1443 SimpleInst rhs -> addWanted state wanted rhs []
1444 other -> do_this_otherwise state wanted
1449 -------------------------
1450 isAvailable :: Avails -> Inst -> Maybe Avail
1451 isAvailable avails wanted = lookupFM avails wanted
1452 -- NB 1: the Ord instance of Inst compares by the class/type info
1453 -- *not* by unique. So
1454 -- d1::C Int == d2::C Int
1456 addLinearAvailable :: Avails -> Avail -> Inst -> TcM (Avails, [Inst])
1457 addLinearAvailable avails avail wanted
1458 -- avails currently maps [wanted -> avail]
1459 -- Extend avails to reflect a neeed for an extra copy of avail
1461 | Just avail' <- split_avail avail
1462 = returnM (addToFM avails wanted avail', [])
1465 = tcLookupId splitName `thenM` \ split_id ->
1466 tcInstClassOp (instLoc wanted) split_id
1467 [linearInstType wanted] `thenM` \ split_inst ->
1468 returnM (addToFM avails wanted (Linear 2 split_inst avail), [split_inst])
1471 split_avail :: Avail -> Maybe Avail
1472 -- (Just av) if there's a modified version of avail that
1473 -- we can use to replace avail in avails
1474 -- Nothing if there isn't, so we need to create a Linear
1475 split_avail (Linear n i a) = Just (Linear (n+1) i a)
1476 split_avail (Given id used) | not used = Just (Given id True)
1477 | otherwise = Nothing
1478 split_avail Irred = Nothing
1479 split_avail IsFree = Nothing
1480 split_avail other = pprPanic "addLinearAvailable" (ppr avail $$ ppr wanted $$ ppr avails)
1482 -------------------------
1483 addFree :: Avails -> Inst -> TcM Avails
1484 -- When an Inst is tossed upstairs as 'free' we nevertheless add it
1485 -- to avails, so that any other equal Insts will be commoned up right
1486 -- here rather than also being tossed upstairs. This is really just
1487 -- an optimisation, and perhaps it is more trouble that it is worth,
1488 -- as the following comments show!
1490 -- NB: do *not* add superclasses. If we have
1493 -- but a is not bound here, then we *don't* want to derive
1494 -- dn from df here lest we lose sharing.
1496 addFree avails free = returnM (addToFM avails free IsFree)
1498 addWanted :: Avails -> Inst -> TcExpr -> [Inst] -> TcM Avails
1499 addWanted avails wanted rhs_expr wanteds
1500 = ASSERT2( not (wanted `elemFM` avails), ppr wanted $$ ppr avails )
1501 addAvailAndSCs avails wanted avail
1503 avail | instBindingRequired wanted = Rhs rhs_expr wanteds
1504 | otherwise = ASSERT( null wanteds ) NoRhs
1506 addGiven :: Avails -> Inst -> TcM Avails
1507 addGiven state given = addAvailAndSCs state given (Given (instToId given) False)
1508 -- No ASSERT( not (given `elemFM` avails) ) because in an instance
1509 -- decl for Ord t we can add both Ord t and Eq t as 'givens',
1510 -- so the assert isn't true
1512 addIrred :: WantSCs -> Avails -> Inst -> TcM Avails
1513 addIrred NoSCs avails irred = returnM (addToFM avails irred Irred)
1514 addIrred AddSCs avails irred = ASSERT2( not (irred `elemFM` avails), ppr irred $$ ppr avails )
1515 addAvailAndSCs avails irred Irred
1517 addAvailAndSCs :: Avails -> Inst -> Avail -> TcM Avails
1518 addAvailAndSCs avails inst avail
1519 | not (isClassDict inst) = returnM avails1
1520 | otherwise = addSCs is_loop avails1 inst
1522 avails1 = addToFM avails inst avail
1523 is_loop inst = inst `elem` deps -- Note: this compares by *type*, not by Unique
1524 deps = findAllDeps avails avail
1526 findAllDeps :: Avails -> Avail -> [Inst]
1527 -- Find all the Insts that this one depends on
1528 -- See Note [SUPERCLASS-LOOP]
1529 findAllDeps avails (Rhs _ kids) = kids ++ concat (map (find_all_deps_help avails) kids)
1530 findAllDeps avails other = []
1532 find_all_deps_help :: Avails -> Inst -> [Inst]
1533 find_all_deps_help avails inst
1534 = case lookupFM avails inst of
1535 Just avail -> findAllDeps avails avail
1538 addSCs :: (Inst -> Bool) -> Avails -> Inst -> TcM Avails
1539 -- Add all the superclasses of the Inst to Avails
1540 -- The first param says "dont do this because the original thing
1541 -- depends on this one, so you'd build a loop"
1542 -- Invariant: the Inst is already in Avails.
1544 addSCs is_loop avails dict
1545 = newDictsFromOld dict sc_theta' `thenM` \ sc_dicts ->
1546 foldlM add_sc avails (zipEqual "add_scs" sc_dicts sc_sels)
1548 (clas, tys) = getDictClassTys dict
1549 (tyvars, sc_theta, sc_sels, _) = classBigSig clas
1550 sc_theta' = substTheta (mkTopTyVarSubst tyvars tys) sc_theta
1552 add_sc avails (sc_dict, sc_sel) -- Add it, and its superclasses
1553 = case lookupFM avails sc_dict of
1554 Just (Given _ _) -> returnM avails -- Given is cheaper than
1555 -- a superclass selection
1556 Just other | is_loop sc_dict -> returnM avails -- See Note [SUPERCLASS-LOOP]
1557 | otherwise -> returnM avails' -- SCs already added
1559 Nothing -> addSCs is_loop avails' sc_dict
1561 sc_sel_rhs = DictApp (TyApp (HsVar sc_sel) tys) [instToId dict]
1562 avail = Rhs sc_sel_rhs [dict]
1563 avails' = addToFM avails sc_dict avail
1566 Note [SUPERCLASS-LOOP]: Checking for loops
1567 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1568 We have to be careful here. If we are *given* d1:Ord a,
1569 and want to deduce (d2:C [a]) where
1571 class Ord a => C a where
1572 instance Ord a => C [a] where ...
1574 Then we'll use the instance decl to deduce C [a] and then add the
1575 superclasses of C [a] to avails. But we must not overwrite the binding
1576 for d1:Ord a (which is given) with a superclass selection or we'll just
1579 Here's another example
1580 class Eq b => Foo a b
1581 instance Eq a => Foo [a] a
1585 we'll first deduce that it holds (via the instance decl). We must not
1586 then overwrite the Eq t constraint with a superclass selection!
1588 At first I had a gross hack, whereby I simply did not add superclass constraints
1589 in addWanted, though I did for addGiven and addIrred. This was sub-optimal,
1590 becuase it lost legitimate superclass sharing, and it still didn't do the job:
1591 I found a very obscure program (now tcrun021) in which improvement meant the
1592 simplifier got two bites a the cherry... so something seemed to be an Irred
1593 first time, but reducible next time.
1595 Now we implement the Right Solution, which is to check for loops directly
1596 when adding superclasses. It's a bit like the occurs check in unification.
1600 %************************************************************************
1602 \section{tcSimplifyTop: defaulting}
1604 %************************************************************************
1607 @tcSimplifyTop@ is called once per module to simplify all the constant
1608 and ambiguous Insts.
1610 We need to be careful of one case. Suppose we have
1612 instance Num a => Num (Foo a b) where ...
1614 and @tcSimplifyTop@ is given a constraint (Num (Foo x y)). Then it'll simplify
1615 to (Num x), and default x to Int. But what about y??
1617 It's OK: the final zonking stage should zap y to (), which is fine.
1621 tcSimplifyTop :: [Inst] -> TcM TcDictBinds
1622 -- The TcLclEnv should be valid here, solely to improve
1623 -- error message generation for the monomorphism restriction
1624 tcSimplifyTop wanteds
1625 = getLclEnv `thenM` \ lcl_env ->
1626 traceTc (text "tcSimplifyTop" <+> ppr (lclEnvElts lcl_env)) `thenM_`
1627 simpleReduceLoop (text "tcSimplTop") reduceMe wanteds `thenM` \ (frees, binds, irreds) ->
1628 ASSERT( null frees )
1631 -- All the non-std ones are definite errors
1632 (stds, non_stds) = partition isStdClassTyVarDict irreds
1634 -- Group by type variable
1635 std_groups = equivClasses cmp_by_tyvar stds
1637 -- Pick the ones which its worth trying to disambiguate
1638 -- namely, the onese whose type variable isn't bound
1639 -- up with one of the non-standard classes
1640 (std_oks, std_bads) = partition worth_a_try std_groups
1641 worth_a_try group@(d:_) = not (non_std_tyvars `intersectsVarSet` tyVarsOfInst d)
1642 non_std_tyvars = unionVarSets (map tyVarsOfInst non_stds)
1644 -- Collect together all the bad guys
1645 bad_guys = non_stds ++ concat std_bads
1646 (tidy_env, tidy_dicts) = tidyInsts bad_guys
1647 (bad_ips, non_ips) = partition isIPDict tidy_dicts
1648 (no_insts, ambigs) = partition no_inst non_ips
1649 no_inst d = not (isTyVarDict d) || tyVarsOfInst d `subVarSet` fixed_tvs
1650 fixed_tvs = oclose (fdPredsOfInsts tidy_dicts) emptyVarSet
1653 -- Report definite errors
1654 addTopInstanceErrs tidy_env no_insts `thenM_`
1655 addTopIPErrs tidy_env bad_ips `thenM_`
1657 -- Deal with ambiguity errors, but only if
1658 -- if there has not been an error so far; errors often
1659 -- give rise to spurious ambiguous Insts
1660 ifErrsM (returnM []) (
1662 -- Complain about the ones that don't fall under
1663 -- the Haskell rules for disambiguation
1664 -- This group includes both non-existent instances
1665 -- e.g. Num (IO a) and Eq (Int -> Int)
1666 -- and ambiguous dictionaries
1668 addTopAmbigErrs (tidy_env, ambigs) `thenM_`
1670 -- Disambiguate the ones that look feasible
1671 mappM disambigGroup std_oks
1672 ) `thenM` \ binds_ambig ->
1674 returnM (binds `andMonoBinds` andMonoBindList binds_ambig)
1676 ----------------------------------
1677 d1 `cmp_by_tyvar` d2 = get_tv d1 `compare` get_tv d2
1679 get_tv d = case getDictClassTys d of
1680 (clas, [ty]) -> tcGetTyVar "tcSimplify" ty
1681 get_clas d = case getDictClassTys d of
1682 (clas, [ty]) -> clas
1685 If a dictionary constrains a type variable which is
1686 * not mentioned in the environment
1687 * and not mentioned in the type of the expression
1688 then it is ambiguous. No further information will arise to instantiate
1689 the type variable; nor will it be generalised and turned into an extra
1690 parameter to a function.
1692 It is an error for this to occur, except that Haskell provided for
1693 certain rules to be applied in the special case of numeric types.
1695 * at least one of its classes is a numeric class, and
1696 * all of its classes are numeric or standard
1697 then the type variable can be defaulted to the first type in the
1698 default-type list which is an instance of all the offending classes.
1700 So here is the function which does the work. It takes the ambiguous
1701 dictionaries and either resolves them (producing bindings) or
1702 complains. It works by splitting the dictionary list by type
1703 variable, and using @disambigOne@ to do the real business.
1705 @disambigOne@ assumes that its arguments dictionaries constrain all
1706 the same type variable.
1708 ADR Comment 20/6/94: I've changed the @CReturnable@ case to default to
1709 @()@ instead of @Int@. I reckon this is the Right Thing to do since
1710 the most common use of defaulting is code like:
1712 _ccall_ foo `seqPrimIO` bar
1714 Since we're not using the result of @foo@, the result if (presumably)
1718 disambigGroup :: [Inst] -- All standard classes of form (C a)
1722 | any isNumericClass classes -- Guaranteed all standard classes
1723 -- see comment at the end of function for reasons as to
1724 -- why the defaulting mechanism doesn't apply to groups that
1725 -- include CCallable or CReturnable dicts.
1726 && not (any isCcallishClass classes)
1727 = -- THE DICTS OBEY THE DEFAULTABLE CONSTRAINT
1728 -- SO, TRY DEFAULT TYPES IN ORDER
1730 -- Failure here is caused by there being no type in the
1731 -- default list which can satisfy all the ambiguous classes.
1732 -- For example, if Real a is reqd, but the only type in the
1733 -- default list is Int.
1734 getDefaultTys `thenM` \ default_tys ->
1736 try_default [] -- No defaults work, so fail
1739 try_default (default_ty : default_tys)
1740 = tryTcLIE_ (try_default default_tys) $ -- If default_ty fails, we try
1741 -- default_tys instead
1742 tcSimplifyDefault theta `thenM` \ _ ->
1745 theta = [mkClassPred clas [default_ty] | clas <- classes]
1747 -- See if any default works
1748 tryM (try_default default_tys) `thenM` \ mb_ty ->
1750 Left _ -> -- If not, add an AmbigErr
1751 addTopAmbigErrs (tidyInsts dicts) `thenM_`
1752 returnM EmptyMonoBinds ;
1754 Right chosen_default_ty ->
1756 -- If so, bind the type variable
1757 -- and reduce the context, for real this time
1758 unifyTauTy chosen_default_ty (mkTyVarTy tyvar) `thenM_`
1759 simpleReduceLoop (text "disambig" <+> ppr dicts)
1760 reduceMe dicts `thenM` \ (frees, binds, ambigs) ->
1761 WARN( not (null frees && null ambigs), ppr frees $$ ppr ambigs )
1762 warnDefault dicts chosen_default_ty `thenM_`
1765 | all isCreturnableClass classes
1766 = -- Default CCall stuff to (); we don't even both to check that () is an
1767 -- instance of CReturnable, because we know it is.
1768 unifyTauTy (mkTyVarTy tyvar) unitTy `thenM_`
1769 returnM EmptyMonoBinds
1771 | otherwise -- No defaults
1772 = addTopAmbigErrs (tidyInsts dicts) `thenM_`
1773 returnM EmptyMonoBinds
1776 tyvar = get_tv (head dicts) -- Should be non-empty
1777 classes = map get_clas dicts
1780 [Aside - why the defaulting mechanism is turned off when
1781 dealing with arguments and results to ccalls.
1783 When typechecking _ccall_s, TcExpr ensures that the external
1784 function is only passed arguments (and in the other direction,
1785 results) of a restricted set of 'native' types. This is
1786 implemented via the help of the pseudo-type classes,
1787 @CReturnable@ (CR) and @CCallable@ (CC.)
1789 The interaction between the defaulting mechanism for numeric
1790 values and CC & CR can be a bit puzzling to the user at times.
1799 What type has 'x' got here? That depends on the default list
1800 in operation, if it is equal to Haskell 98's default-default
1801 of (Integer, Double), 'x' has type Double, since Integer
1802 is not an instance of CR. If the default list is equal to
1803 Haskell 1.4's default-default of (Int, Double), 'x' has type
1806 To try to minimise the potential for surprises here, the
1807 defaulting mechanism is turned off in the presence of
1808 CCallable and CReturnable.
1813 %************************************************************************
1815 \subsection[simple]{@Simple@ versions}
1817 %************************************************************************
1819 Much simpler versions when there are no bindings to make!
1821 @tcSimplifyThetas@ simplifies class-type constraints formed by
1822 @deriving@ declarations and when specialising instances. We are
1823 only interested in the simplified bunch of class/type constraints.
1825 It simplifies to constraints of the form (C a b c) where
1826 a,b,c are type variables. This is required for the context of
1827 instance declarations.
1830 tcSimplifyDeriv :: [TyVar]
1831 -> ThetaType -- Wanted
1832 -> TcM ThetaType -- Needed
1834 tcSimplifyDeriv tyvars theta
1835 = tcInstTyVars VanillaTv tyvars `thenM` \ (tvs, _, tenv) ->
1836 -- The main loop may do unification, and that may crash if
1837 -- it doesn't see a TcTyVar, so we have to instantiate. Sigh
1838 -- ToDo: what if two of them do get unified?
1839 newDicts DataDeclOrigin (substTheta tenv theta) `thenM` \ wanteds ->
1840 simpleReduceLoop doc reduceMe wanteds `thenM` \ (frees, _, irreds) ->
1841 ASSERT( null frees ) -- reduceMe never returns Free
1843 doptM Opt_AllowUndecidableInstances `thenM` \ undecidable_ok ->
1845 tv_set = mkVarSet tvs
1846 simpl_theta = map dictPred irreds -- reduceMe squashes all non-dicts
1849 | isEmptyVarSet pred_tyvars -- Things like (Eq T) should be rejected
1850 = addErrTc (noInstErr pred)
1852 | not undecidable_ok && not (isTyVarClassPred pred)
1853 -- Check that the returned dictionaries are all of form (C a b)
1854 -- (where a, b are type variables).
1855 -- We allow this if we had -fallow-undecidable-instances,
1856 -- but note that risks non-termination in the 'deriving' context-inference
1857 -- fixpoint loop. It is useful for situations like
1858 -- data Min h a = E | M a (h a)
1859 -- which gives the instance decl
1860 -- instance (Eq a, Eq (h a)) => Eq (Min h a)
1861 = addErrTc (noInstErr pred)
1863 | not (pred_tyvars `subVarSet` tv_set)
1864 -- Check for a bizarre corner case, when the derived instance decl should
1865 -- have form instance C a b => D (T a) where ...
1866 -- Note that 'b' isn't a parameter of T. This gives rise to all sorts
1867 -- of problems; in particular, it's hard to compare solutions for
1868 -- equality when finding the fixpoint. So I just rule it out for now.
1869 = addErrTc (badDerivedPred pred)
1874 pred_tyvars = tyVarsOfPred pred
1876 rev_env = mkTopTyVarSubst tvs (mkTyVarTys tyvars)
1877 -- This reverse-mapping is a Royal Pain,
1878 -- but the result should mention TyVars not TcTyVars
1881 mappM check_pred simpl_theta `thenM_`
1882 checkAmbiguity tvs simpl_theta tv_set `thenM_`
1883 returnM (substTheta rev_env simpl_theta)
1885 doc = ptext SLIT("deriving classes for a data type")
1888 @tcSimplifyDefault@ just checks class-type constraints, essentially;
1889 used with \tr{default} declarations. We are only interested in
1890 whether it worked or not.
1893 tcSimplifyDefault :: ThetaType -- Wanted; has no type variables in it
1896 tcSimplifyDefault theta
1897 = newDicts DataDeclOrigin theta `thenM` \ wanteds ->
1898 simpleReduceLoop doc reduceMe wanteds `thenM` \ (frees, _, irreds) ->
1899 ASSERT( null frees ) -- try_me never returns Free
1900 mappM (addErrTc . noInstErr) irreds `thenM_`
1906 doc = ptext SLIT("default declaration")
1910 %************************************************************************
1912 \section{Errors and contexts}
1914 %************************************************************************
1916 ToDo: for these error messages, should we note the location as coming
1917 from the insts, or just whatever seems to be around in the monad just
1921 groupErrs :: ([Inst] -> TcM ()) -- Deal with one group
1922 -> [Inst] -- The offending Insts
1924 -- Group together insts with the same origin
1925 -- We want to report them together in error messages
1927 groupErrs report_err []
1929 groupErrs report_err (inst:insts)
1930 = do_one (inst:friends) `thenM_`
1931 groupErrs report_err others
1934 -- (It may seem a bit crude to compare the error messages,
1935 -- but it makes sure that we combine just what the user sees,
1936 -- and it avoids need equality on InstLocs.)
1937 (friends, others) = partition is_friend insts
1938 loc_msg = showSDoc (pprInstLoc (instLoc inst))
1939 is_friend friend = showSDoc (pprInstLoc (instLoc friend)) == loc_msg
1940 do_one insts = addInstCtxt (instLoc (head insts)) (report_err insts)
1941 -- Add location and context information derived from the Insts
1943 -- Add the "arising from..." part to a message about bunch of dicts
1944 addInstLoc :: [Inst] -> Message -> Message
1945 addInstLoc insts msg = msg $$ nest 2 (pprInstLoc (instLoc (head insts)))
1948 plural xs = char 's'
1951 addTopIPErrs tidy_env tidy_dicts
1952 = groupErrs report tidy_dicts
1954 report dicts = addErrTcM (tidy_env, mk_msg dicts)
1955 mk_msg dicts = addInstLoc dicts (ptext SLIT("Unbound implicit parameter") <>
1956 plural tidy_dicts <+> pprInsts tidy_dicts)
1958 -- Used for top-level irreducibles
1959 addTopInstanceErrs tidy_env tidy_dicts
1960 = groupErrs report tidy_dicts
1962 report dicts = mkMonomorphismMsg tidy_env dicts `thenM` \ (tidy_env, mono_msg) ->
1963 addErrTcM (tidy_env, mk_msg dicts $$ mono_msg)
1964 mk_msg dicts = addInstLoc dicts (ptext SLIT("No instance") <> plural tidy_dicts <+>
1965 ptext SLIT("for") <+> pprInsts tidy_dicts)
1968 addTopAmbigErrs (tidy_env, tidy_dicts)
1969 -- Divide into groups that share a common set of ambiguous tyvars
1970 = mapM report (equivClasses cmp [(d, tvs_of d) | d <- tidy_dicts])
1972 tvs_of :: Inst -> [TcTyVar]
1973 tvs_of d = varSetElems (tyVarsOfInst d)
1974 cmp (_,tvs1) (_,tvs2) = tvs1 `compare` tvs2
1976 report :: [(Inst,[TcTyVar])] -> TcM ()
1977 report pairs@((_,tvs) : _) -- The pairs share a common set of ambiguous tyvars
1978 = mkMonomorphismMsg tidy_env dicts `thenM` \ (tidy_env, mono_msg) ->
1979 addErrTcM (tidy_env, msg $$ mono_msg)
1981 dicts = map fst pairs
1982 msg = sep [text "Ambiguous type variable" <> plural tvs <+>
1983 pprQuotedList tvs <+> in_msg,
1984 nest 2 (pprInstsInFull dicts)]
1985 in_msg | isSingleton dicts = text "in the top-level constraint:"
1986 | otherwise = text "in these top-level constraints:"
1989 mkMonomorphismMsg :: TidyEnv -> [Inst] -> TcM (TidyEnv, Message)
1990 -- There's an error with these Insts; if they have free type variables
1991 -- it's probably caused by the monomorphism restriction.
1992 -- Try to identify the offending variable
1993 -- ASSUMPTION: the Insts are fully zonked
1994 mkMonomorphismMsg tidy_env insts
1995 | isEmptyVarSet inst_tvs
1996 = returnM (tidy_env, empty)
1998 = findGlobals inst_tvs tidy_env `thenM` \ (tidy_env, docs) ->
1999 returnM (tidy_env, mk_msg docs)
2002 inst_tvs = tyVarsOfInsts insts
2004 mk_msg [] = empty -- This happens in things like
2005 -- f x = show (read "foo")
2006 -- whre monomorphism doesn't play any role
2007 mk_msg docs = vcat [ptext SLIT("Possible cause: the monomorphism restriction applied to the following:"),
2009 ptext SLIT("Probable fix: give these definition(s) an explicit type signature")]
2011 warnDefault dicts default_ty
2012 = doptM Opt_WarnTypeDefaults `thenM` \ warn_flag ->
2013 addInstCtxt (instLoc (head dicts)) (warnTc warn_flag warn_msg)
2016 (_, tidy_dicts) = tidyInsts dicts
2017 warn_msg = vcat [ptext SLIT("Defaulting the following constraint(s) to type") <+>
2018 quotes (ppr default_ty),
2019 pprInstsInFull tidy_dicts]
2021 complainCheck doc givens irreds
2022 = mappM zonkInst given_dicts_and_ips `thenM` \ givens' ->
2023 groupErrs (addNoInstanceErrs doc givens') irreds `thenM_`
2026 given_dicts_and_ips = filter (not . isMethod) givens
2027 -- Filter out methods, which are only added to
2028 -- the given set as an optimisation
2030 addNoInstanceErrs what_doc givens dicts
2031 = getDOpts `thenM` \ dflags ->
2032 tcGetInstEnv `thenM` \ inst_env ->
2034 (tidy_env1, tidy_givens) = tidyInsts givens
2035 (tidy_env2, tidy_dicts) = tidyMoreInsts tidy_env1 dicts
2037 doc = vcat [addInstLoc dicts $
2038 sep [herald <+> pprInsts tidy_dicts,
2039 nest 4 $ ptext SLIT("from the context") <+> pprInsts tidy_givens],
2041 ptext SLIT("Probable fix:"),
2045 herald = ptext SLIT("Could not") <+> unambig_doc <+> ptext SLIT("deduce")
2046 unambig_doc | ambig_overlap = ptext SLIT("unambiguously")
2049 -- The error message when we don't find a suitable instance
2050 -- is complicated by the fact that sometimes this is because
2051 -- there is no instance, and sometimes it's because there are
2052 -- too many instances (overlap). See the comments in TcEnv.lhs
2053 -- with the InstEnv stuff.
2056 | not ambig_overlap = empty
2058 = vcat [ptext SLIT("The choice of (overlapping) instance declaration"),
2059 nest 4 (ptext SLIT("depends on the instantiation of") <+>
2060 quotes (pprWithCommas ppr (varSetElems (tyVarsOfInsts tidy_dicts))))]
2062 fix1 = sep [ptext SLIT("Add") <+> pprInsts tidy_dicts,
2063 ptext SLIT("to the") <+> what_doc]
2065 fix2 | null instance_dicts
2068 = ptext SLIT("Or add an instance declaration for") <+> pprInsts instance_dicts
2070 instance_dicts = [d | d <- tidy_dicts, isClassDict d, not (isTyVarDict d)]
2071 -- Insts for which it is worth suggesting an adding an instance declaration
2072 -- Exclude implicit parameters, and tyvar dicts
2074 -- Checks for the ambiguous case when we have overlapping instances
2075 ambig_overlap = any ambig_overlap1 dicts
2078 = case lookupInstEnv dflags inst_env clas tys of
2079 NoMatch ambig -> ambig
2083 (clas,tys) = getDictClassTys dict
2085 addErrTcM (tidy_env2, doc)
2087 -- Used for the ...Thetas variants; all top level
2088 noInstErr pred = ptext SLIT("No instance for") <+> quotes (ppr pred)
2091 = vcat [ptext SLIT("Can't derive instances where the instance context mentions"),
2092 ptext SLIT("type variables that are not data type parameters"),
2093 nest 2 (ptext SLIT("Offending constraint:") <+> ppr pred)]
2095 reduceDepthErr n stack
2096 = vcat [ptext SLIT("Context reduction stack overflow; size =") <+> int n,
2097 ptext SLIT("Use -fcontext-stack20 to increase stack size to (e.g.) 20"),
2098 nest 4 (pprInstsInFull stack)]
2100 reduceDepthMsg n stack = nest 4 (pprInstsInFull stack)
2102 -----------------------------------------------
2104 = addErrTc (sep [ptext SLIT("Cannot generalise these overloadings (in a _ccall_):"),
2105 nest 4 (ppr inst <+> pprInstLoc (instLoc inst))])