2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[TcSimplify]{TcSimplify}
10 tcSimplifyInfer, tcSimplifyInferCheck,
11 tcSimplifyCheck, tcSimplifyRestricted,
12 tcSimplifyToDicts, tcSimplifyIPs,
13 tcSimplifyTop, tcSimplifyInteractive,
16 tcSimplifyDeriv, tcSimplifyDefault,
20 #include "HsVersions.h"
22 import {-# SOURCE #-} TcUnify( unifyTauTy )
24 import HsSyn ( HsBind(..), LHsBinds, HsExpr(..), LHsExpr )
25 import TcHsSyn ( TcId, TcDictBinds, mkHsApp, mkHsTyApp, mkHsDictApp )
28 import Inst ( lookupInst, LookupInstResult(..),
29 tyVarsOfInst, fdPredsOfInsts, fdPredsOfInst, newDicts,
30 isDict, isClassDict, isLinearInst, linearInstType,
31 isStdClassTyVarDict, isMethodFor, isMethod,
32 instToId, tyVarsOfInsts, cloneDict,
33 ipNamesOfInsts, ipNamesOfInst, dictPred,
35 newDictsFromOld, tcInstClassOp,
36 getDictClassTys, isTyVarDict,
37 instLoc, zonkInst, tidyInsts, tidyMoreInsts,
38 Inst, pprInsts, pprInstsInFull, tcGetInstEnvs,
39 isIPDict, isInheritableInst, pprDFuns
41 import TcEnv ( tcGetGlobalTyVars, tcLookupId, findGlobals )
42 import InstEnv ( lookupInstEnv, classInstEnv )
43 import TcMType ( zonkTcTyVarsAndFV, tcInstTyVars, checkAmbiguity )
44 import TcType ( TcTyVar, TcTyVarSet, ThetaType, TyVarDetails(VanillaTv),
45 mkClassPred, isOverloadedTy, mkTyConApp,
46 mkTyVarTy, tcGetTyVar, isTyVarClassPred, mkTyVarTys,
47 tyVarsOfPred, tcEqType )
48 import Id ( idType, mkUserLocal )
50 import Name ( getOccName, getSrcLoc )
51 import NameSet ( NameSet, mkNameSet, elemNameSet )
52 import Class ( classBigSig, classKey )
53 import FunDeps ( oclose, grow, improve, pprEquationDoc )
54 import PrelInfo ( isNumericClass )
55 import PrelNames ( splitName, fstName, sndName, integerTyConName,
56 showClassKey, eqClassKey, ordClassKey )
57 import Subst ( mkTopTyVarSubst, substTheta, substTy )
58 import TysWiredIn ( pairTyCon, doubleTy )
59 import ErrUtils ( Message )
61 import VarEnv ( TidyEnv )
65 import ListSetOps ( equivClasses )
66 import Util ( zipEqual, isSingleton )
67 import List ( partition )
68 import SrcLoc ( Located(..) )
73 %************************************************************************
77 %************************************************************************
79 --------------------------------------
80 Notes on functional dependencies (a bug)
81 --------------------------------------
83 | > class Foo a b | a->b
85 | > class Bar a b | a->b
89 | > instance Bar Obj Obj
91 | > instance (Bar a b) => Foo a b
93 | > foo:: (Foo a b) => a -> String
96 | > runFoo:: (forall a b. (Foo a b) => a -> w) -> w
102 | Could not deduce (Bar a b) from the context (Foo a b)
103 | arising from use of `foo' at <interactive>:1
105 | Add (Bar a b) to the expected type of an expression
106 | In the first argument of `runFoo', namely `foo'
107 | In the definition of `it': it = runFoo foo
109 | Why all of the sudden does GHC need the constraint Bar a b? The
110 | function foo didn't ask for that...
112 The trouble is that to type (runFoo foo), GHC has to solve the problem:
114 Given constraint Foo a b
115 Solve constraint Foo a b'
117 Notice that b and b' aren't the same. To solve this, just do
118 improvement and then they are the same. But GHC currently does
123 That is usually fine, but it isn't here, because it sees that Foo a b is
124 not the same as Foo a b', and so instead applies the instance decl for
125 instance Bar a b => Foo a b. And that's where the Bar constraint comes
128 The Right Thing is to improve whenever the constraint set changes at
129 all. Not hard in principle, but it'll take a bit of fiddling to do.
133 --------------------------------------
134 Notes on quantification
135 --------------------------------------
137 Suppose we are about to do a generalisation step.
141 T the type of the RHS
142 C the constraints from that RHS
144 The game is to figure out
146 Q the set of type variables over which to quantify
147 Ct the constraints we will *not* quantify over
148 Cq the constraints we will quantify over
150 So we're going to infer the type
154 and float the constraints Ct further outwards.
156 Here are the things that *must* be true:
158 (A) Q intersect fv(G) = EMPTY limits how big Q can be
159 (B) Q superset fv(Cq union T) \ oclose(fv(G),C) limits how small Q can be
161 (A) says we can't quantify over a variable that's free in the
162 environment. (B) says we must quantify over all the truly free
163 variables in T, else we won't get a sufficiently general type. We do
164 not *need* to quantify over any variable that is fixed by the free
165 vars of the environment G.
167 BETWEEN THESE TWO BOUNDS, ANY Q WILL DO!
169 Example: class H x y | x->y where ...
171 fv(G) = {a} C = {H a b, H c d}
174 (A) Q intersect {a} is empty
175 (B) Q superset {a,b,c,d} \ oclose({a}, C) = {a,b,c,d} \ {a,b} = {c,d}
177 So Q can be {c,d}, {b,c,d}
179 Other things being equal, however, we'd like to quantify over as few
180 variables as possible: smaller types, fewer type applications, more
181 constraints can get into Ct instead of Cq.
184 -----------------------------------------
187 fv(T) the free type vars of T
189 oclose(vs,C) The result of extending the set of tyvars vs
190 using the functional dependencies from C
192 grow(vs,C) The result of extend the set of tyvars vs
193 using all conceivable links from C.
195 E.g. vs = {a}, C = {H [a] b, K (b,Int) c, Eq e}
196 Then grow(vs,C) = {a,b,c}
198 Note that grow(vs,C) `superset` grow(vs,simplify(C))
199 That is, simplfication can only shrink the result of grow.
202 oclose is conservative one way: v `elem` oclose(vs,C) => v is definitely fixed by vs
203 grow is conservative the other way: if v might be fixed by vs => v `elem` grow(vs,C)
206 -----------------------------------------
210 Here's a good way to choose Q:
212 Q = grow( fv(T), C ) \ oclose( fv(G), C )
214 That is, quantify over all variable that that MIGHT be fixed by the
215 call site (which influences T), but which aren't DEFINITELY fixed by
216 G. This choice definitely quantifies over enough type variables,
217 albeit perhaps too many.
219 Why grow( fv(T), C ) rather than fv(T)? Consider
221 class H x y | x->y where ...
226 If we used fv(T) = {c} we'd get the type
228 forall c. H c d => c -> b
230 And then if the fn was called at several different c's, each of
231 which fixed d differently, we'd get a unification error, because
232 d isn't quantified. Solution: quantify d. So we must quantify
233 everything that might be influenced by c.
235 Why not oclose( fv(T), C )? Because we might not be able to see
236 all the functional dependencies yet:
238 class H x y | x->y where ...
239 instance H x y => Eq (T x y) where ...
244 Now oclose(fv(T),C) = {c}, because the functional dependency isn't
245 apparent yet, and that's wrong. We must really quantify over d too.
248 There really isn't any point in quantifying over any more than
249 grow( fv(T), C ), because the call sites can't possibly influence
250 any other type variables.
254 --------------------------------------
256 --------------------------------------
258 It's very hard to be certain when a type is ambiguous. Consider
262 instance H x y => K (x,y)
264 Is this type ambiguous?
265 forall a b. (K (a,b), Eq b) => a -> a
267 Looks like it! But if we simplify (K (a,b)) we get (H a b) and
268 now we see that a fixes b. So we can't tell about ambiguity for sure
269 without doing a full simplification. And even that isn't possible if
270 the context has some free vars that may get unified. Urgle!
272 Here's another example: is this ambiguous?
273 forall a b. Eq (T b) => a -> a
274 Not if there's an insance decl (with no context)
275 instance Eq (T b) where ...
277 You may say of this example that we should use the instance decl right
278 away, but you can't always do that:
280 class J a b where ...
281 instance J Int b where ...
283 f :: forall a b. J a b => a -> a
285 (Notice: no functional dependency in J's class decl.)
286 Here f's type is perfectly fine, provided f is only called at Int.
287 It's premature to complain when meeting f's signature, or even
288 when inferring a type for f.
292 However, we don't *need* to report ambiguity right away. It'll always
293 show up at the call site.... and eventually at main, which needs special
294 treatment. Nevertheless, reporting ambiguity promptly is an excellent thing.
296 So here's the plan. We WARN about probable ambiguity if
298 fv(Cq) is not a subset of oclose(fv(T) union fv(G), C)
300 (all tested before quantification).
301 That is, all the type variables in Cq must be fixed by the the variables
302 in the environment, or by the variables in the type.
304 Notice that we union before calling oclose. Here's an example:
306 class J a b c | a b -> c
310 forall b c. (J a b c) => b -> b
312 Only if we union {a} from G with {b} from T before using oclose,
313 do we see that c is fixed.
315 It's a bit vague exactly which C we should use for this oclose call. If we
316 don't fix enough variables we might complain when we shouldn't (see
317 the above nasty example). Nothing will be perfect. That's why we can
318 only issue a warning.
321 Can we ever be *certain* about ambiguity? Yes: if there's a constraint
323 c in C such that fv(c) intersect (fv(G) union fv(T)) = EMPTY
325 then c is a "bubble"; there's no way it can ever improve, and it's
326 certainly ambiguous. UNLESS it is a constant (sigh). And what about
331 instance H x y => K (x,y)
333 Is this type ambiguous?
334 forall a b. (K (a,b), Eq b) => a -> a
336 Urk. The (Eq b) looks "definitely ambiguous" but it isn't. What we are after
337 is a "bubble" that's a set of constraints
339 Cq = Ca union Cq' st fv(Ca) intersect (fv(Cq') union fv(T) union fv(G)) = EMPTY
341 Hence another idea. To decide Q start with fv(T) and grow it
342 by transitive closure in Cq (no functional dependencies involved).
343 Now partition Cq using Q, leaving the definitely-ambiguous and probably-ok.
344 The definitely-ambiguous can then float out, and get smashed at top level
345 (which squashes out the constants, like Eq (T a) above)
348 --------------------------------------
349 Notes on principal types
350 --------------------------------------
355 f x = let g y = op (y::Int) in True
357 Here the principal type of f is (forall a. a->a)
358 but we'll produce the non-principal type
359 f :: forall a. C Int => a -> a
362 --------------------------------------
363 The need for forall's in constraints
364 --------------------------------------
366 [Exchange on Haskell Cafe 5/6 Dec 2000]
368 class C t where op :: t -> Bool
369 instance C [t] where op x = True
371 p y = (let f :: c -> Bool; f x = op (y >> return x) in f, y ++ [])
372 q y = (y ++ [], let f :: c -> Bool; f x = op (y >> return x) in f)
374 The definitions of p and q differ only in the order of the components in
375 the pair on their right-hand sides. And yet:
377 ghc and "Typing Haskell in Haskell" reject p, but accept q;
378 Hugs rejects q, but accepts p;
379 hbc rejects both p and q;
380 nhc98 ... (Malcolm, can you fill in the blank for us!).
382 The type signature for f forces context reduction to take place, and
383 the results of this depend on whether or not the type of y is known,
384 which in turn depends on which component of the pair the type checker
387 Solution: if y::m a, float out the constraints
388 Monad m, forall c. C (m c)
389 When m is later unified with [], we can solve both constraints.
392 --------------------------------------
393 Notes on implicit parameters
394 --------------------------------------
396 Question 1: can we "inherit" implicit parameters
397 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
402 where f is *not* a top-level binding.
403 From the RHS of f we'll get the constraint (?y::Int).
404 There are two types we might infer for f:
408 (so we get ?y from the context of f's definition), or
410 f :: (?y::Int) => Int -> Int
412 At first you might think the first was better, becuase then
413 ?y behaves like a free variable of the definition, rather than
414 having to be passed at each call site. But of course, the WHOLE
415 IDEA is that ?y should be passed at each call site (that's what
416 dynamic binding means) so we'd better infer the second.
418 BOTTOM LINE: when *inferring types* you *must* quantify
419 over implicit parameters. See the predicate isFreeWhenInferring.
422 Question 2: type signatures
423 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
424 BUT WATCH OUT: When you supply a type signature, we can't force you
425 to quantify over implicit parameters. For example:
429 This is perfectly reasonable. We do not want to insist on
431 (?x + 1) :: (?x::Int => Int)
433 That would be silly. Here, the definition site *is* the occurrence site,
434 so the above strictures don't apply. Hence the difference between
435 tcSimplifyCheck (which *does* allow implicit paramters to be inherited)
436 and tcSimplifyCheckBind (which does not).
438 What about when you supply a type signature for a binding?
439 Is it legal to give the following explicit, user type
440 signature to f, thus:
445 At first sight this seems reasonable, but it has the nasty property
446 that adding a type signature changes the dynamic semantics.
449 (let f x = (x::Int) + ?y
450 in (f 3, f 3 with ?y=5)) with ?y = 6
456 in (f 3, f 3 with ?y=5)) with ?y = 6
460 Indeed, simply inlining f (at the Haskell source level) would change the
463 Nevertheless, as Launchbury says (email Oct 01) we can't really give the
464 semantics for a Haskell program without knowing its typing, so if you
465 change the typing you may change the semantics.
467 To make things consistent in all cases where we are *checking* against
468 a supplied signature (as opposed to inferring a type), we adopt the
471 a signature does not need to quantify over implicit params.
473 [This represents a (rather marginal) change of policy since GHC 5.02,
474 which *required* an explicit signature to quantify over all implicit
475 params for the reasons mentioned above.]
477 But that raises a new question. Consider
479 Given (signature) ?x::Int
480 Wanted (inferred) ?x::Int, ?y::Bool
482 Clearly we want to discharge the ?x and float the ?y out. But
483 what is the criterion that distinguishes them? Clearly it isn't
484 what free type variables they have. The Right Thing seems to be
485 to float a constraint that
486 neither mentions any of the quantified type variables
487 nor any of the quantified implicit parameters
489 See the predicate isFreeWhenChecking.
492 Question 3: monomorphism
493 ~~~~~~~~~~~~~~~~~~~~~~~~
494 There's a nasty corner case when the monomorphism restriction bites:
498 The argument above suggests that we *must* generalise
499 over the ?y parameter, to get
500 z :: (?y::Int) => Int,
501 but the monomorphism restriction says that we *must not*, giving
503 Why does the momomorphism restriction say this? Because if you have
505 let z = x + ?y in z+z
507 you might not expect the addition to be done twice --- but it will if
508 we follow the argument of Question 2 and generalise over ?y.
514 (A) Always generalise over implicit parameters
515 Bindings that fall under the monomorphism restriction can't
519 * Inlining remains valid
520 * No unexpected loss of sharing
521 * But simple bindings like
523 will be rejected, unless you add an explicit type signature
524 (to avoid the monomorphism restriction)
525 z :: (?y::Int) => Int
527 This seems unacceptable
529 (B) Monomorphism restriction "wins"
530 Bindings that fall under the monomorphism restriction can't
532 Always generalise over implicit parameters *except* for bindings
533 that fall under the monomorphism restriction
536 * Inlining isn't valid in general
537 * No unexpected loss of sharing
538 * Simple bindings like
540 accepted (get value of ?y from binding site)
542 (C) Always generalise over implicit parameters
543 Bindings that fall under the monomorphism restriction can't
544 be generalised, EXCEPT for implicit parameters
546 * Inlining remains valid
547 * Unexpected loss of sharing (from the extra generalisation)
548 * Simple bindings like
550 accepted (get value of ?y from occurrence sites)
555 None of these choices seems very satisfactory. But at least we should
556 decide which we want to do.
558 It's really not clear what is the Right Thing To Do. If you see
562 would you expect the value of ?y to be got from the *occurrence sites*
563 of 'z', or from the valuue of ?y at the *definition* of 'z'? In the
564 case of function definitions, the answer is clearly the former, but
565 less so in the case of non-fucntion definitions. On the other hand,
566 if we say that we get the value of ?y from the definition site of 'z',
567 then inlining 'z' might change the semantics of the program.
569 Choice (C) really says "the monomorphism restriction doesn't apply
570 to implicit parameters". Which is fine, but remember that every
571 innocent binding 'x = ...' that mentions an implicit parameter in
572 the RHS becomes a *function* of that parameter, called at each
573 use of 'x'. Now, the chances are that there are no intervening 'with'
574 clauses that bind ?y, so a decent compiler should common up all
575 those function calls. So I think I strongly favour (C). Indeed,
576 one could make a similar argument for abolishing the monomorphism
577 restriction altogether.
579 BOTTOM LINE: we choose (B) at present. See tcSimplifyRestricted
583 %************************************************************************
585 \subsection{tcSimplifyInfer}
587 %************************************************************************
589 tcSimplify is called when we *inferring* a type. Here's the overall game plan:
591 1. Compute Q = grow( fvs(T), C )
593 2. Partition C based on Q into Ct and Cq. Notice that ambiguous
594 predicates will end up in Ct; we deal with them at the top level
596 3. Try improvement, using functional dependencies
598 4. If Step 3 did any unification, repeat from step 1
599 (Unification can change the result of 'grow'.)
601 Note: we don't reduce dictionaries in step 2. For example, if we have
602 Eq (a,b), we don't simplify to (Eq a, Eq b). So Q won't be different
603 after step 2. However note that we may therefore quantify over more
604 type variables than we absolutely have to.
606 For the guts, we need a loop, that alternates context reduction and
607 improvement with unification. E.g. Suppose we have
609 class C x y | x->y where ...
611 and tcSimplify is called with:
613 Then improvement unifies a with b, giving
616 If we need to unify anything, we rattle round the whole thing all over
623 -> TcTyVarSet -- fv(T); type vars
625 -> TcM ([TcTyVar], -- Tyvars to quantify (zonked)
626 TcDictBinds, -- Bindings
627 [TcId]) -- Dict Ids that must be bound here (zonked)
628 -- Any free (escaping) Insts are tossed into the environment
633 tcSimplifyInfer doc tau_tvs wanted_lie
634 = inferLoop doc (varSetElems tau_tvs)
635 wanted_lie `thenM` \ (qtvs, frees, binds, irreds) ->
637 extendLIEs frees `thenM_`
638 returnM (qtvs, binds, map instToId irreds)
640 inferLoop doc tau_tvs wanteds
642 zonkTcTyVarsAndFV tau_tvs `thenM` \ tau_tvs' ->
643 mappM zonkInst wanteds `thenM` \ wanteds' ->
644 tcGetGlobalTyVars `thenM` \ gbl_tvs ->
646 preds = fdPredsOfInsts wanteds'
647 qtvs = grow preds tau_tvs' `minusVarSet` oclose preds gbl_tvs
650 | isFreeWhenInferring qtvs inst = Free
651 | isClassDict inst = DontReduceUnlessConstant -- Dicts
652 | otherwise = ReduceMe -- Lits and Methods
654 traceTc (text "infloop" <+> vcat [ppr tau_tvs', ppr wanteds', ppr preds, ppr (grow preds tau_tvs'), ppr qtvs]) `thenM_`
656 reduceContext doc try_me [] wanteds' `thenM` \ (no_improvement, frees, binds, irreds) ->
659 if no_improvement then
660 returnM (varSetElems qtvs, frees, binds, irreds)
662 -- If improvement did some unification, we go round again. There
663 -- are two subtleties:
664 -- a) We start again with irreds, not wanteds
665 -- Using an instance decl might have introduced a fresh type variable
666 -- which might have been unified, so we'd get an infinite loop
667 -- if we started again with wanteds! See example [LOOP]
669 -- b) It's also essential to re-process frees, because unification
670 -- might mean that a type variable that looked free isn't now.
672 -- Hence the (irreds ++ frees)
674 -- However, NOTICE that when we are done, we might have some bindings, but
675 -- the final qtvs might be empty. See [NO TYVARS] below.
677 inferLoop doc tau_tvs (irreds ++ frees) `thenM` \ (qtvs1, frees1, binds1, irreds1) ->
678 returnM (qtvs1, frees1, binds `unionBags` binds1, irreds1)
683 class If b t e r | b t e -> r
686 class Lte a b c | a b -> c where lte :: a -> b -> c
688 instance (Lte a b l,If l b a c) => Max a b c
690 Wanted: Max Z (S x) y
692 Then we'll reduce using the Max instance to:
693 (Lte Z (S x) l, If l (S x) Z y)
694 and improve by binding l->T, after which we can do some reduction
695 on both the Lte and If constraints. What we *can't* do is start again
696 with (Max Z (S x) y)!
700 class Y a b | a -> b where
703 instance Y [[a]] a where
706 k :: X a -> X a -> X a
708 g :: Num a => [X a] -> [X a]
711 h ys = ys ++ map (k (y [[0]])) xs
713 The excitement comes when simplifying the bindings for h. Initially
714 try to simplify {y @ [[t1]] t2, 0 @ t1}, with initial qtvs = {t2}.
715 From this we get t1:=:t2, but also various bindings. We can't forget
716 the bindings (because of [LOOP]), but in fact t1 is what g is
719 The net effect of [NO TYVARS]
722 isFreeWhenInferring :: TyVarSet -> Inst -> Bool
723 isFreeWhenInferring qtvs inst
724 = isFreeWrtTyVars qtvs inst -- Constrains no quantified vars
725 && isInheritableInst inst -- And no implicit parameter involved
726 -- (see "Notes on implicit parameters")
728 isFreeWhenChecking :: TyVarSet -- Quantified tyvars
729 -> NameSet -- Quantified implicit parameters
731 isFreeWhenChecking qtvs ips inst
732 = isFreeWrtTyVars qtvs inst
733 && isFreeWrtIPs ips inst
735 isFreeWrtTyVars qtvs inst = not (tyVarsOfInst inst `intersectsVarSet` qtvs)
736 isFreeWrtIPs ips inst = not (any (`elemNameSet` ips) (ipNamesOfInst inst))
740 %************************************************************************
742 \subsection{tcSimplifyCheck}
744 %************************************************************************
746 @tcSimplifyCheck@ is used when we know exactly the set of variables
747 we are going to quantify over. For example, a class or instance declaration.
752 -> [TcTyVar] -- Quantify over these
755 -> TcM TcDictBinds -- Bindings
757 -- tcSimplifyCheck is used when checking expression type signatures,
758 -- class decls, instance decls etc.
760 -- NB: tcSimplifyCheck does not consult the
761 -- global type variables in the environment; so you don't
762 -- need to worry about setting them before calling tcSimplifyCheck
763 tcSimplifyCheck doc qtvs givens wanted_lie
764 = tcSimplCheck doc get_qtvs
765 givens wanted_lie `thenM` \ (qtvs', binds) ->
768 get_qtvs = zonkTcTyVarsAndFV qtvs
771 -- tcSimplifyInferCheck is used when we know the constraints we are to simplify
772 -- against, but we don't know the type variables over which we are going to quantify.
773 -- This happens when we have a type signature for a mutually recursive group
776 -> TcTyVarSet -- fv(T)
779 -> TcM ([TcTyVar], -- Variables over which to quantify
780 TcDictBinds) -- Bindings
782 tcSimplifyInferCheck doc tau_tvs givens wanted_lie
783 = tcSimplCheck doc get_qtvs givens wanted_lie
785 -- Figure out which type variables to quantify over
786 -- You might think it should just be the signature tyvars,
787 -- but in bizarre cases you can get extra ones
788 -- f :: forall a. Num a => a -> a
789 -- f x = fst (g (x, head [])) + 1
791 -- Here we infer g :: forall a b. a -> b -> (b,a)
792 -- We don't want g to be monomorphic in b just because
793 -- f isn't quantified over b.
794 all_tvs = varSetElems (tau_tvs `unionVarSet` tyVarsOfInsts givens)
796 get_qtvs = zonkTcTyVarsAndFV all_tvs `thenM` \ all_tvs' ->
797 tcGetGlobalTyVars `thenM` \ gbl_tvs ->
799 qtvs = all_tvs' `minusVarSet` gbl_tvs
800 -- We could close gbl_tvs, but its not necessary for
801 -- soundness, and it'll only affect which tyvars, not which
802 -- dictionaries, we quantify over
807 Here is the workhorse function for all three wrappers.
810 tcSimplCheck doc get_qtvs givens wanted_lie
811 = check_loop givens wanted_lie `thenM` \ (qtvs, frees, binds, irreds) ->
813 -- Complain about any irreducible ones
814 mappM zonkInst given_dicts_and_ips `thenM` \ givens' ->
815 groupErrs (addNoInstanceErrs (Just doc) givens') irreds `thenM_`
818 extendLIEs frees `thenM_`
819 returnM (qtvs, binds)
822 given_dicts_and_ips = filter (not . isMethod) givens
823 -- For error reporting, filter out methods, which are
824 -- only added to the given set as an optimisation
826 ip_set = mkNameSet (ipNamesOfInsts givens)
828 check_loop givens wanteds
830 mappM zonkInst givens `thenM` \ givens' ->
831 mappM zonkInst wanteds `thenM` \ wanteds' ->
832 get_qtvs `thenM` \ qtvs' ->
836 -- When checking against a given signature we always reduce
837 -- until we find a match against something given, or can't reduce
838 try_me inst | isFreeWhenChecking qtvs' ip_set inst = Free
839 | otherwise = ReduceMe
841 reduceContext doc try_me givens' wanteds' `thenM` \ (no_improvement, frees, binds, irreds) ->
844 if no_improvement then
845 returnM (varSetElems qtvs', frees, binds, irreds)
847 check_loop givens' (irreds ++ frees) `thenM` \ (qtvs', frees1, binds1, irreds1) ->
848 returnM (qtvs', frees1, binds `unionBags` binds1, irreds1)
852 %************************************************************************
854 \subsection{tcSimplifyRestricted}
856 %************************************************************************
859 tcSimplifyRestricted -- Used for restricted binding groups
860 -- i.e. ones subject to the monomorphism restriction
862 -> TcTyVarSet -- Free in the type of the RHSs
863 -> [Inst] -- Free in the RHSs
864 -> TcM ([TcTyVar], -- Tyvars to quantify (zonked)
865 TcDictBinds) -- Bindings
867 tcSimplifyRestricted doc tau_tvs wanteds
868 = -- First squash out all methods, to find the constrained tyvars
869 -- We can't just take the free vars of wanted_lie because that'll
870 -- have methods that may incidentally mention entirely unconstrained variables
871 -- e.g. a call to f :: Eq a => a -> b -> b
872 -- Here, b is unconstrained. A good example would be
874 -- We want to infer the polymorphic type
875 -- foo :: forall b. b -> b
877 -- 'reduceMe': Reduce as far as we can. Don't stop at
878 -- dicts; the idea is to get rid of as many type
879 -- variables as possible, and we don't want to stop
880 -- at (say) Monad (ST s), because that reduces
881 -- immediately, with no constraint on s.
882 simpleReduceLoop doc reduceMe wanteds `thenM` \ (foo_frees, foo_binds, constrained_dicts) ->
884 -- Next, figure out the tyvars we will quantify over
885 zonkTcTyVarsAndFV (varSetElems tau_tvs) `thenM` \ tau_tvs' ->
886 tcGetGlobalTyVars `thenM` \ gbl_tvs ->
888 constrained_tvs = tyVarsOfInsts constrained_dicts
889 qtvs = (tau_tvs' `minusVarSet` oclose (fdPredsOfInsts constrained_dicts) gbl_tvs)
890 `minusVarSet` constrained_tvs
892 traceTc (text "tcSimplifyRestricted" <+> vcat [
893 pprInsts wanteds, pprInsts foo_frees, pprInsts constrained_dicts,
895 ppr constrained_tvs, ppr tau_tvs', ppr qtvs ]) `thenM_`
897 -- The first step may have squashed more methods than
898 -- necessary, so try again, this time knowing the exact
899 -- set of type variables to quantify over.
901 -- We quantify only over constraints that are captured by qtvs;
902 -- these will just be a subset of non-dicts. This in contrast
903 -- to normal inference (using isFreeWhenInferring) in which we quantify over
904 -- all *non-inheritable* constraints too. This implements choice
905 -- (B) under "implicit parameter and monomorphism" above.
907 -- Remember that we may need to do *some* simplification, to
908 -- (for example) squash {Monad (ST s)} into {}. It's not enough
909 -- just to float all constraints
910 restrict_loop doc qtvs wanteds
911 -- We still need a loop because improvement can take place
912 -- E.g. if we have (C (T a)) and the instance decl
913 -- instance D Int b => C (T a) where ...
914 -- and there's a functional dependency for D. Then we may improve
915 -- the tyep variable 'b'.
917 restrict_loop doc qtvs wanteds
918 = mappM zonkInst wanteds `thenM` \ wanteds' ->
919 zonkTcTyVarsAndFV (varSetElems qtvs) `thenM` \ qtvs' ->
921 try_me inst | isFreeWrtTyVars qtvs' inst = Free
922 | otherwise = ReduceMe
924 reduceContext doc try_me [] wanteds' `thenM` \ (no_improvement, frees, binds, irreds) ->
925 if no_improvement then
926 ASSERT( null irreds )
927 extendLIEs frees `thenM_`
928 returnM (varSetElems qtvs', binds)
930 restrict_loop doc qtvs' (irreds ++ frees) `thenM` \ (qtvs1, binds1) ->
931 returnM (qtvs1, binds `unionBags` binds1)
935 %************************************************************************
937 \subsection{tcSimplifyToDicts}
939 %************************************************************************
941 On the LHS of transformation rules we only simplify methods and constants,
942 getting dictionaries. We want to keep all of them unsimplified, to serve
943 as the available stuff for the RHS of the rule.
945 The same thing is used for specialise pragmas. Consider
948 {-# SPECIALISE f :: Int -> Int #-}
951 The type checker generates a binding like:
953 f_spec = (f :: Int -> Int)
955 and we want to end up with
957 f_spec = _inline_me_ (f Int dNumInt)
959 But that means that we must simplify the Method for f to (f Int dNumInt)!
960 So tcSimplifyToDicts squeezes out all Methods.
962 IMPORTANT NOTE: we *don't* want to do superclass commoning up. Consider
964 fromIntegral :: (Integral a, Num b) => a -> b
965 {-# RULES "foo" fromIntegral = id :: Int -> Int #-}
967 Here, a=b=Int, and Num Int is a superclass of Integral Int. But we *dont*
971 fromIntegral Int Int dIntegralInt (scsel dIntegralInt) = id Int
973 because the scsel will mess up matching. Instead we want
975 forall dIntegralInt, dNumInt.
976 fromIntegral Int Int dIntegralInt dNumInt = id Int
978 Hence "DontReduce NoSCs"
981 tcSimplifyToDicts :: [Inst] -> TcM (TcDictBinds)
982 tcSimplifyToDicts wanteds
983 = simpleReduceLoop doc try_me wanteds `thenM` \ (frees, binds, irreds) ->
984 -- Since try_me doesn't look at types, we don't need to
985 -- do any zonking, so it's safe to call reduceContext directly
987 extendLIEs irreds `thenM_`
991 doc = text "tcSimplifyToDicts"
993 -- Reduce methods and lits only; stop as soon as we get a dictionary
994 try_me inst | isDict inst = DontReduce NoSCs -- See notes above for why NoSCs
995 | otherwise = ReduceMe
1000 tcSimplifyBracket is used when simplifying the constraints arising from
1001 a Template Haskell bracket [| ... |]. We want to check that there aren't
1002 any constraints that can't be satisfied (e.g. Show Foo, where Foo has no
1003 Show instance), but we aren't otherwise interested in the results.
1004 Nor do we care about ambiguous dictionaries etc. We will type check
1005 this bracket again at its usage site.
1008 tcSimplifyBracket :: [Inst] -> TcM ()
1009 tcSimplifyBracket wanteds
1010 = simpleReduceLoop doc reduceMe wanteds `thenM_`
1013 doc = text "tcSimplifyBracket"
1017 %************************************************************************
1019 \subsection{Filtering at a dynamic binding}
1021 %************************************************************************
1026 we must discharge all the ?x constraints from B. We also do an improvement
1027 step; if we have ?x::t1 and ?x::t2 we must unify t1, t2.
1029 Actually, the constraints from B might improve the types in ?x. For example
1031 f :: (?x::Int) => Char -> Char
1034 then the constraint (?x::Int) arising from the call to f will
1035 force the binding for ?x to be of type Int.
1038 tcSimplifyIPs :: [Inst] -- The implicit parameters bound here
1041 tcSimplifyIPs given_ips wanteds
1042 = simpl_loop given_ips wanteds `thenM` \ (frees, binds) ->
1043 extendLIEs frees `thenM_`
1046 doc = text "tcSimplifyIPs" <+> ppr given_ips
1047 ip_set = mkNameSet (ipNamesOfInsts given_ips)
1049 -- Simplify any methods that mention the implicit parameter
1050 try_me inst | isFreeWrtIPs ip_set inst = Free
1051 | otherwise = ReduceMe
1053 simpl_loop givens wanteds
1054 = mappM zonkInst givens `thenM` \ givens' ->
1055 mappM zonkInst wanteds `thenM` \ wanteds' ->
1057 reduceContext doc try_me givens' wanteds' `thenM` \ (no_improvement, frees, binds, irreds) ->
1059 if no_improvement then
1060 ASSERT( null irreds )
1061 returnM (frees, binds)
1063 simpl_loop givens' (irreds ++ frees) `thenM` \ (frees1, binds1) ->
1064 returnM (frees1, binds `unionBags` binds1)
1068 %************************************************************************
1070 \subsection[binds-for-local-funs]{@bindInstsOfLocalFuns@}
1072 %************************************************************************
1074 When doing a binding group, we may have @Insts@ of local functions.
1075 For example, we might have...
1077 let f x = x + 1 -- orig local function (overloaded)
1078 f.1 = f Int -- two instances of f
1083 The point is: we must drop the bindings for @f.1@ and @f.2@ here,
1084 where @f@ is in scope; those @Insts@ must certainly not be passed
1085 upwards towards the top-level. If the @Insts@ were binding-ified up
1086 there, they would have unresolvable references to @f@.
1088 We pass in an @init_lie@ of @Insts@ and a list of locally-bound @Ids@.
1089 For each method @Inst@ in the @init_lie@ that mentions one of the
1090 @Ids@, we create a binding. We return the remaining @Insts@ (in an
1091 @LIE@), as well as the @HsBinds@ generated.
1094 bindInstsOfLocalFuns :: [Inst] -> [TcId] -> TcM (LHsBinds TcId)
1096 bindInstsOfLocalFuns wanteds local_ids
1097 | null overloaded_ids
1099 = extendLIEs wanteds `thenM_`
1103 = simpleReduceLoop doc try_me wanteds `thenM` \ (frees, binds, irreds) ->
1104 ASSERT( null irreds )
1105 extendLIEs frees `thenM_`
1108 doc = text "bindInsts" <+> ppr local_ids
1109 overloaded_ids = filter is_overloaded local_ids
1110 is_overloaded id = isOverloadedTy (idType id)
1112 overloaded_set = mkVarSet overloaded_ids -- There can occasionally be a lot of them
1113 -- so it's worth building a set, so that
1114 -- lookup (in isMethodFor) is faster
1116 try_me inst | isMethodFor overloaded_set inst = ReduceMe
1121 %************************************************************************
1123 \subsection{Data types for the reduction mechanism}
1125 %************************************************************************
1127 The main control over context reduction is here
1131 = ReduceMe -- Try to reduce this
1132 -- If there's no instance, behave exactly like
1133 -- DontReduce: add the inst to
1134 -- the irreductible ones, but don't
1135 -- produce an error message of any kind.
1136 -- It might be quite legitimate such as (Eq a)!
1138 | DontReduce WantSCs -- Return as irreducible
1140 | DontReduceUnlessConstant -- Return as irreducible unless it can
1141 -- be reduced to a constant in one step
1143 | Free -- Return as free
1145 reduceMe :: Inst -> WhatToDo
1146 reduceMe inst = ReduceMe
1148 data WantSCs = NoSCs | AddSCs -- Tells whether we should add the superclasses
1149 -- of a predicate when adding it to the avails
1155 type Avails = FiniteMap Inst Avail
1158 = IsFree -- Used for free Insts
1159 | Irred -- Used for irreducible dictionaries,
1160 -- which are going to be lambda bound
1162 | Given TcId -- Used for dictionaries for which we have a binding
1163 -- e.g. those "given" in a signature
1164 Bool -- True <=> actually consumed (splittable IPs only)
1166 | NoRhs -- Used for Insts like (CCallable f)
1167 -- where no witness is required.
1170 | Rhs -- Used when there is a RHS
1171 (LHsExpr TcId) -- The RHS
1172 [Inst] -- Insts free in the RHS; we need these too
1174 | Linear -- Splittable Insts only.
1175 Int -- The Int is always 2 or more; indicates how
1176 -- many copies are required
1177 Inst -- The splitter
1178 Avail -- Where the "master copy" is
1180 | LinRhss -- Splittable Insts only; this is used only internally
1181 -- by extractResults, where a Linear
1182 -- is turned into an LinRhss
1183 [LHsExpr TcId] -- A supply of suitable RHSs
1185 pprAvails avails = vcat [sep [ppr inst, nest 2 (equals <+> pprAvail avail)]
1186 | (inst,avail) <- fmToList avails ]
1188 instance Outputable Avail where
1191 pprAvail NoRhs = text "<no rhs>"
1192 pprAvail IsFree = text "Free"
1193 pprAvail Irred = text "Irred"
1194 pprAvail (Given x b) = text "Given" <+> ppr x <+>
1195 if b then text "(used)" else empty
1196 pprAvail (Rhs rhs bs) = text "Rhs" <+> ppr rhs <+> braces (ppr bs)
1197 pprAvail (Linear n i a) = text "Linear" <+> ppr n <+> braces (ppr i) <+> ppr a
1198 pprAvail (LinRhss rhss) = text "LinRhss" <+> ppr rhss
1201 Extracting the bindings from a bunch of Avails.
1202 The bindings do *not* come back sorted in dependency order.
1203 We assume that they'll be wrapped in a big Rec, so that the
1204 dependency analyser can sort them out later
1208 extractResults :: Avails
1210 -> TcM (TcDictBinds, -- Bindings
1211 [Inst], -- Irreducible ones
1212 [Inst]) -- Free ones
1214 extractResults avails wanteds
1215 = go avails emptyBag [] [] wanteds
1217 go avails binds irreds frees []
1218 = returnM (binds, irreds, frees)
1220 go avails binds irreds frees (w:ws)
1221 = case lookupFM avails w of
1222 Nothing -> pprTrace "Urk: extractResults" (ppr w) $
1223 go avails binds irreds frees ws
1225 Just NoRhs -> go avails binds irreds frees ws
1226 Just IsFree -> go (add_free avails w) binds irreds (w:frees) ws
1227 Just Irred -> go (add_given avails w) binds (w:irreds) frees ws
1229 Just (Given id _) -> go avails new_binds irreds frees ws
1231 new_binds | id == instToId w = binds
1232 | otherwise = addBind binds w (L (instSpan w) (HsVar id))
1233 -- The sought Id can be one of the givens, via a superclass chain
1234 -- and then we definitely don't want to generate an x=x binding!
1236 Just (Rhs rhs ws') -> go (add_given avails w) new_binds irreds frees (ws' ++ ws)
1238 new_binds = addBind binds w rhs
1240 Just (Linear n split_inst avail) -- Transform Linear --> LinRhss
1241 -> get_root irreds frees avail w `thenM` \ (irreds', frees', root_id) ->
1242 split n (instToId split_inst) root_id w `thenM` \ (binds', rhss) ->
1243 go (addToFM avails w (LinRhss rhss))
1244 (binds `unionBags` binds')
1245 irreds' frees' (split_inst : w : ws)
1247 Just (LinRhss (rhs:rhss)) -- Consume one of the Rhss
1248 -> go new_avails new_binds irreds frees ws
1250 new_binds = addBind binds w rhs
1251 new_avails = addToFM avails w (LinRhss rhss)
1253 get_root irreds frees (Given id _) w = returnM (irreds, frees, id)
1254 get_root irreds frees Irred w = cloneDict w `thenM` \ w' ->
1255 returnM (w':irreds, frees, instToId w')
1256 get_root irreds frees IsFree w = cloneDict w `thenM` \ w' ->
1257 returnM (irreds, w':frees, instToId w')
1260 | instBindingRequired w = addToFM avails w (Given (instToId w) True)
1261 | otherwise = addToFM avails w NoRhs
1262 -- NB: make sure that CCallable/CReturnable use NoRhs rather
1263 -- than Given, else we end up with bogus bindings.
1265 add_free avails w | isMethod w = avails
1266 | otherwise = add_given avails w
1268 -- Do *not* replace Free by Given if it's a method.
1269 -- The following situation shows why this is bad:
1270 -- truncate :: forall a. RealFrac a => forall b. Integral b => a -> b
1271 -- From an application (truncate f i) we get
1272 -- t1 = truncate at f
1274 -- If we have also have a second occurrence of truncate, we get
1275 -- t3 = truncate at f
1277 -- When simplifying with i,f free, we might still notice that
1278 -- t1=t3; but alas, the binding for t2 (which mentions t1)
1279 -- will continue to float out!
1280 -- (split n i a) returns: n rhss
1281 -- auxiliary bindings
1282 -- 1 or 0 insts to add to irreds
1285 split :: Int -> TcId -> TcId -> Inst
1286 -> TcM (TcDictBinds, [LHsExpr TcId])
1287 -- (split n split_id root_id wanted) returns
1288 -- * a list of 'n' expressions, all of which witness 'avail'
1289 -- * a bunch of auxiliary bindings to support these expressions
1290 -- * one or zero insts needed to witness the whole lot
1291 -- (maybe be zero if the initial Inst is a Given)
1293 -- NB: 'wanted' is just a template
1295 split n split_id root_id wanted
1298 ty = linearInstType wanted
1299 pair_ty = mkTyConApp pairTyCon [ty,ty]
1300 id = instToId wanted
1303 span = instSpan wanted
1305 go 1 = returnM (emptyBag, [L span $ HsVar root_id])
1307 go n = go ((n+1) `div` 2) `thenM` \ (binds1, rhss) ->
1308 expand n rhss `thenM` \ (binds2, rhss') ->
1309 returnM (binds1 `unionBags` binds2, rhss')
1312 -- Given ((n+1)/2) rhss, make n rhss, using auxiliary bindings
1313 -- e.g. expand 3 [rhs1, rhs2]
1314 -- = ( { x = split rhs1 },
1315 -- [fst x, snd x, rhs2] )
1317 | n `rem` 2 == 0 = go rhss -- n is even
1318 | otherwise = go (tail rhss) `thenM` \ (binds', rhss') ->
1319 returnM (binds', head rhss : rhss')
1321 go rhss = mapAndUnzipM do_one rhss `thenM` \ (binds', rhss') ->
1322 returnM (listToBag binds', concat rhss')
1324 do_one rhs = newUnique `thenM` \ uniq ->
1325 tcLookupId fstName `thenM` \ fst_id ->
1326 tcLookupId sndName `thenM` \ snd_id ->
1328 x = mkUserLocal occ uniq pair_ty loc
1330 returnM (L span (VarBind x (mk_app span split_id rhs)),
1331 [mk_fs_app span fst_id ty x, mk_fs_app span snd_id ty x])
1333 mk_fs_app span id ty var = L span (HsVar id) `mkHsTyApp` [ty,ty] `mkHsApp` (L span (HsVar var))
1335 mk_app span id rhs = L span (HsApp (L span (HsVar id)) rhs)
1337 addBind binds inst rhs = binds `unionBags` unitBag (L (instLocSrcSpan (instLoc inst))
1338 (VarBind (instToId inst) rhs))
1339 instSpan wanted = instLocSrcSpan (instLoc wanted)
1343 %************************************************************************
1345 \subsection[reduce]{@reduce@}
1347 %************************************************************************
1349 When the "what to do" predicate doesn't depend on the quantified type variables,
1350 matters are easier. We don't need to do any zonking, unless the improvement step
1351 does something, in which case we zonk before iterating.
1353 The "given" set is always empty.
1356 simpleReduceLoop :: SDoc
1357 -> (Inst -> WhatToDo) -- What to do, *not* based on the quantified type variables
1359 -> TcM ([Inst], -- Free
1361 [Inst]) -- Irreducible
1363 simpleReduceLoop doc try_me wanteds
1364 = mappM zonkInst wanteds `thenM` \ wanteds' ->
1365 reduceContext doc try_me [] wanteds' `thenM` \ (no_improvement, frees, binds, irreds) ->
1366 if no_improvement then
1367 returnM (frees, binds, irreds)
1369 simpleReduceLoop doc try_me (irreds ++ frees) `thenM` \ (frees1, binds1, irreds1) ->
1370 returnM (frees1, binds `unionBags` binds1, irreds1)
1376 reduceContext :: SDoc
1377 -> (Inst -> WhatToDo)
1380 -> TcM (Bool, -- True <=> improve step did no unification
1382 TcDictBinds, -- Dictionary bindings
1383 [Inst]) -- Irreducible
1385 reduceContext doc try_me givens wanteds
1387 traceTc (text "reduceContext" <+> (vcat [
1388 text "----------------------",
1390 text "given" <+> ppr givens,
1391 text "wanted" <+> ppr wanteds,
1392 text "----------------------"
1395 -- Build the Avail mapping from "givens"
1396 foldlM addGiven emptyFM givens `thenM` \ init_state ->
1399 reduceList (0,[]) try_me wanteds init_state `thenM` \ avails ->
1401 -- Do improvement, using everything in avails
1402 -- In particular, avails includes all superclasses of everything
1403 tcImprove avails `thenM` \ no_improvement ->
1405 extractResults avails wanteds `thenM` \ (binds, irreds, frees) ->
1407 traceTc (text "reduceContext end" <+> (vcat [
1408 text "----------------------",
1410 text "given" <+> ppr givens,
1411 text "wanted" <+> ppr wanteds,
1413 text "avails" <+> pprAvails avails,
1414 text "frees" <+> ppr frees,
1415 text "no_improvement =" <+> ppr no_improvement,
1416 text "----------------------"
1419 returnM (no_improvement, frees, binds, irreds)
1421 tcImprove :: Avails -> TcM Bool -- False <=> no change
1422 -- Perform improvement using all the predicates in Avails
1424 = tcGetInstEnvs `thenM` \ (home_ie, pkg_ie) ->
1426 preds = [ (pred, pp_loc)
1427 | inst <- keysFM avails,
1428 let pp_loc = pprInstLoc (instLoc inst),
1429 pred <- fdPredsOfInst inst
1431 -- Avails has all the superclasses etc (good)
1432 -- It also has all the intermediates of the deduction (good)
1433 -- It does not have duplicates (good)
1434 -- NB that (?x::t1) and (?x::t2) will be held separately in avails
1435 -- so that improve will see them separate
1436 eqns = improve get_insts preds
1437 get_insts clas = classInstEnv home_ie clas ++ classInstEnv pkg_ie clas
1442 traceTc (ptext SLIT("Improve:") <+> vcat (map pprEquationDoc eqns)) `thenM_`
1443 mappM_ unify eqns `thenM_`
1446 unify ((qtvs, t1, t2), doc)
1448 tcInstTyVars VanillaTv (varSetElems qtvs) `thenM` \ (_, _, tenv) ->
1449 unifyTauTy (substTy tenv t1) (substTy tenv t2)
1452 The main context-reduction function is @reduce@. Here's its game plan.
1455 reduceList :: (Int,[Inst]) -- Stack (for err msgs)
1456 -- along with its depth
1457 -> (Inst -> WhatToDo)
1464 try_me: given an inst, this function returns
1466 DontReduce return this in "irreds"
1467 Free return this in "frees"
1469 wanteds: The list of insts to reduce
1470 state: An accumulating parameter of type Avails
1471 that contains the state of the algorithm
1473 It returns a Avails.
1475 The (n,stack) pair is just used for error reporting.
1476 n is always the depth of the stack.
1477 The stack is the stack of Insts being reduced: to produce X
1478 I had to produce Y, to produce Y I had to produce Z, and so on.
1481 reduceList (n,stack) try_me wanteds state
1482 | n > opt_MaxContextReductionDepth
1483 = failWithTc (reduceDepthErr n stack)
1489 pprTrace "Jeepers! ReduceContext:" (reduceDepthMsg n stack)
1494 go [] state = returnM state
1495 go (w:ws) state = reduce (n+1, w:stack) try_me w state `thenM` \ state' ->
1498 -- Base case: we're done!
1499 reduce stack try_me wanted avails
1500 -- It's the same as an existing inst, or a superclass thereof
1501 | Just avail <- isAvailable avails wanted
1502 = if isLinearInst wanted then
1503 addLinearAvailable avails avail wanted `thenM` \ (avails', wanteds') ->
1504 reduceList stack try_me wanteds' avails'
1506 returnM avails -- No op for non-linear things
1509 = case try_me wanted of {
1511 DontReduce want_scs -> addIrred want_scs avails wanted
1513 ; DontReduceUnlessConstant -> -- It's irreducible (or at least should not be reduced)
1514 -- First, see if the inst can be reduced to a constant in one step
1515 try_simple (addIrred AddSCs) -- Assume want superclasses
1517 ; Free -> -- It's free so just chuck it upstairs
1518 -- First, see if the inst can be reduced to a constant in one step
1521 ; ReduceMe -> -- It should be reduced
1522 lookupInst wanted `thenM` \ lookup_result ->
1523 case lookup_result of
1524 GenInst wanteds' rhs -> addIrred NoSCs avails wanted `thenM` \ avails1 ->
1525 reduceList stack try_me wanteds' avails1 `thenM` \ avails2 ->
1526 addWanted avails2 wanted rhs wanteds'
1527 -- Experiment with temporarily doing addIrred *before* the reduceList,
1528 -- which has the effect of adding the thing we are trying
1529 -- to prove to the database before trying to prove the things it
1530 -- needs. See note [RECURSIVE DICTIONARIES]
1531 -- NB: we must not do an addWanted before, because that adds the
1532 -- superclasses too, and thaat can lead to a spurious loop; see
1533 -- the examples in [SUPERCLASS-LOOP]
1534 -- So we do an addIrred before, and then overwrite it afterwards with addWanted
1536 SimpleInst rhs -> addWanted avails wanted rhs []
1538 NoInstance -> -- No such instance!
1539 -- Add it and its superclasses
1540 addIrred AddSCs avails wanted
1543 try_simple do_this_otherwise
1544 = lookupInst wanted `thenM` \ lookup_result ->
1545 case lookup_result of
1546 SimpleInst rhs -> addWanted avails wanted rhs []
1547 other -> do_this_otherwise avails wanted
1552 -------------------------
1553 isAvailable :: Avails -> Inst -> Maybe Avail
1554 isAvailable avails wanted = lookupFM avails wanted
1555 -- NB 1: the Ord instance of Inst compares by the class/type info
1556 -- *not* by unique. So
1557 -- d1::C Int == d2::C Int
1559 addLinearAvailable :: Avails -> Avail -> Inst -> TcM (Avails, [Inst])
1560 addLinearAvailable avails avail wanted
1561 -- avails currently maps [wanted -> avail]
1562 -- Extend avails to reflect a neeed for an extra copy of avail
1564 | Just avail' <- split_avail avail
1565 = returnM (addToFM avails wanted avail', [])
1568 = tcLookupId splitName `thenM` \ split_id ->
1569 tcInstClassOp (instLoc wanted) split_id
1570 [linearInstType wanted] `thenM` \ split_inst ->
1571 returnM (addToFM avails wanted (Linear 2 split_inst avail), [split_inst])
1574 split_avail :: Avail -> Maybe Avail
1575 -- (Just av) if there's a modified version of avail that
1576 -- we can use to replace avail in avails
1577 -- Nothing if there isn't, so we need to create a Linear
1578 split_avail (Linear n i a) = Just (Linear (n+1) i a)
1579 split_avail (Given id used) | not used = Just (Given id True)
1580 | otherwise = Nothing
1581 split_avail Irred = Nothing
1582 split_avail IsFree = Nothing
1583 split_avail other = pprPanic "addLinearAvailable" (ppr avail $$ ppr wanted $$ ppr avails)
1585 -------------------------
1586 addFree :: Avails -> Inst -> TcM Avails
1587 -- When an Inst is tossed upstairs as 'free' we nevertheless add it
1588 -- to avails, so that any other equal Insts will be commoned up right
1589 -- here rather than also being tossed upstairs. This is really just
1590 -- an optimisation, and perhaps it is more trouble that it is worth,
1591 -- as the following comments show!
1593 -- NB: do *not* add superclasses. If we have
1596 -- but a is not bound here, then we *don't* want to derive
1597 -- dn from df here lest we lose sharing.
1599 addFree avails free = returnM (addToFM avails free IsFree)
1601 addWanted :: Avails -> Inst -> LHsExpr TcId -> [Inst] -> TcM Avails
1602 addWanted avails wanted rhs_expr wanteds
1603 = addAvailAndSCs avails wanted avail
1605 avail | instBindingRequired wanted = Rhs rhs_expr wanteds
1606 | otherwise = ASSERT( null wanteds ) NoRhs
1608 addGiven :: Avails -> Inst -> TcM Avails
1609 addGiven avails given = addAvailAndSCs avails given (Given (instToId given) False)
1610 -- No ASSERT( not (given `elemFM` avails) ) because in an instance
1611 -- decl for Ord t we can add both Ord t and Eq t as 'givens',
1612 -- so the assert isn't true
1614 addIrred :: WantSCs -> Avails -> Inst -> TcM Avails
1615 addIrred NoSCs avails irred = returnM (addToFM avails irred Irred)
1616 addIrred AddSCs avails irred = ASSERT2( not (irred `elemFM` avails), ppr irred $$ ppr avails )
1617 addAvailAndSCs avails irred Irred
1619 addAvailAndSCs :: Avails -> Inst -> Avail -> TcM Avails
1620 addAvailAndSCs avails inst avail
1621 | not (isClassDict inst) = returnM avails1
1622 | otherwise = traceTc (text "addAvailAndSCs" <+> vcat [ppr inst, ppr deps]) `thenM_`
1623 addSCs is_loop avails1 inst
1625 avails1 = addToFM avails inst avail
1626 is_loop inst = any (`tcEqType` idType (instToId inst)) dep_tys
1627 -- Note: this compares by *type*, not by Unique
1628 deps = findAllDeps emptyVarSet avail
1629 dep_tys = map idType (varSetElems deps)
1631 findAllDeps :: IdSet -> Avail -> IdSet
1632 -- Find all the Insts that this one depends on
1633 -- See Note [SUPERCLASS-LOOP]
1634 -- Watch out, though. Since the avails may contain loops
1635 -- (see Note [RECURSIVE DICTIONARIES]), so we need to track the ones we've seen so far
1636 findAllDeps so_far (Rhs _ kids)
1638 (extendVarSetList so_far (map instToId kids)) -- Add the kids to so_far
1639 [a | Just a <- map (lookupFM avails) kids] -- Find the kids' Avail
1640 findAllDeps so_far other = so_far
1643 addSCs :: (Inst -> Bool) -> Avails -> Inst -> TcM Avails
1644 -- Add all the superclasses of the Inst to Avails
1645 -- The first param says "dont do this because the original thing
1646 -- depends on this one, so you'd build a loop"
1647 -- Invariant: the Inst is already in Avails.
1649 addSCs is_loop avails dict
1650 = newDictsFromOld dict sc_theta' `thenM` \ sc_dicts ->
1651 foldlM add_sc avails (zipEqual "add_scs" sc_dicts sc_sels)
1653 (clas, tys) = getDictClassTys dict
1654 (tyvars, sc_theta, sc_sels, _) = classBigSig clas
1655 sc_theta' = substTheta (mkTopTyVarSubst tyvars tys) sc_theta
1657 add_sc avails (sc_dict, sc_sel) -- Add it, and its superclasses
1658 | add_me sc_dict = addSCs is_loop avails' sc_dict
1659 | otherwise = returnM avails
1661 sc_sel_rhs = mkHsDictApp (mkHsTyApp (L (instSpan dict) (HsVar sc_sel)) tys) [instToId dict]
1662 avails' = addToFM avails sc_dict (Rhs sc_sel_rhs [dict])
1664 add_me :: Inst -> Bool
1666 | is_loop sc_dict = False -- See Note [SUPERCLASS-LOOP]
1667 | otherwise = case lookupFM avails sc_dict of
1668 Just (Given _ _) -> False -- Given is cheaper than superclass selection
1672 Note [SUPERCLASS-LOOP]: Checking for loops
1673 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1674 We have to be careful here. If we are *given* d1:Ord a,
1675 and want to deduce (d2:C [a]) where
1677 class Ord a => C a where
1678 instance Ord a => C [a] where ...
1680 Then we'll use the instance decl to deduce C [a] and then add the
1681 superclasses of C [a] to avails. But we must not overwrite the binding
1682 for d1:Ord a (which is given) with a superclass selection or we'll just
1685 Here's another variant, immortalised in tcrun020
1686 class Monad m => C1 m
1687 class C1 m => C2 m x
1688 instance C2 Maybe Bool
1689 For the instance decl we need to build (C1 Maybe), and it's no good if
1690 we run around and add (C2 Maybe Bool) and its superclasses to the avails
1691 before we search for C1 Maybe.
1693 Here's another example
1694 class Eq b => Foo a b
1695 instance Eq a => Foo [a] a
1699 we'll first deduce that it holds (via the instance decl). We must not
1700 then overwrite the Eq t constraint with a superclass selection!
1702 At first I had a gross hack, whereby I simply did not add superclass constraints
1703 in addWanted, though I did for addGiven and addIrred. This was sub-optimal,
1704 becuase it lost legitimate superclass sharing, and it still didn't do the job:
1705 I found a very obscure program (now tcrun021) in which improvement meant the
1706 simplifier got two bites a the cherry... so something seemed to be an Irred
1707 first time, but reducible next time.
1709 Now we implement the Right Solution, which is to check for loops directly
1710 when adding superclasses. It's a bit like the occurs check in unification.
1713 Note [RECURSIVE DICTIONARIES]
1714 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1716 data D r = ZeroD | SuccD (r (D r));
1718 instance (Eq (r (D r))) => Eq (D r) where
1719 ZeroD == ZeroD = True
1720 (SuccD a) == (SuccD b) = a == b
1723 equalDC :: D [] -> D [] -> Bool;
1726 We need to prove (Eq (D [])). Here's how we go:
1730 by instance decl, holds if
1734 by instance decl of Eq, holds if
1736 where d2 = dfEqList d3
1739 But now we can "tie the knot" to give
1745 and it'll even run! The trick is to put the thing we are trying to prove
1746 (in this case Eq (D []) into the database before trying to prove its
1747 contributing clauses.
1750 %************************************************************************
1752 \section{tcSimplifyTop: defaulting}
1754 %************************************************************************
1757 @tcSimplifyTop@ is called once per module to simplify all the constant
1758 and ambiguous Insts.
1760 We need to be careful of one case. Suppose we have
1762 instance Num a => Num (Foo a b) where ...
1764 and @tcSimplifyTop@ is given a constraint (Num (Foo x y)). Then it'll simplify
1765 to (Num x), and default x to Int. But what about y??
1767 It's OK: the final zonking stage should zap y to (), which is fine.
1771 tcSimplifyTop, tcSimplifyInteractive :: [Inst] -> TcM TcDictBinds
1772 tcSimplifyTop wanteds = tc_simplify_top False {- Not interactive loop -} wanteds
1773 tcSimplifyInteractive wanteds = tc_simplify_top True {- Interactive loop -} wanteds
1776 -- The TcLclEnv should be valid here, solely to improve
1777 -- error message generation for the monomorphism restriction
1778 tc_simplify_top is_interactive wanteds
1779 = getLclEnv `thenM` \ lcl_env ->
1780 traceTc (text "tcSimplifyTop" <+> ppr (lclEnvElts lcl_env)) `thenM_`
1781 simpleReduceLoop (text "tcSimplTop") reduceMe wanteds `thenM` \ (frees, binds, irreds) ->
1782 ASSERT( null frees )
1785 -- All the non-std ones are definite errors
1786 (stds, non_stds) = partition isStdClassTyVarDict irreds
1788 -- Group by type variable
1789 std_groups = equivClasses cmp_by_tyvar stds
1791 -- Pick the ones which its worth trying to disambiguate
1792 -- namely, the onese whose type variable isn't bound
1793 -- up with one of the non-standard classes
1794 (std_oks, std_bads) = partition worth_a_try std_groups
1795 worth_a_try group@(d:_) = not (non_std_tyvars `intersectsVarSet` tyVarsOfInst d)
1796 non_std_tyvars = unionVarSets (map tyVarsOfInst non_stds)
1798 -- Collect together all the bad guys
1799 bad_guys = non_stds ++ concat std_bads
1800 (bad_ips, non_ips) = partition isIPDict bad_guys
1801 (no_insts, ambigs) = partition no_inst non_ips
1802 no_inst d = not (isTyVarDict d)
1803 -- Previously, there was a more elaborate no_inst definition:
1804 -- no_inst d = not (isTyVarDict d) || tyVarsOfInst d `subVarSet` fixed_tvs
1805 -- fixed_tvs = oclose (fdPredsOfInsts tidy_dicts) emptyVarSet
1806 -- But that seems over-elaborate to me; it only bites for class decls with
1807 -- fundeps like this: class C a b | -> b where ...
1810 -- Report definite errors
1811 groupErrs (addNoInstanceErrs Nothing []) no_insts `thenM_`
1812 addTopIPErrs bad_ips `thenM_`
1814 -- Deal with ambiguity errors, but only if
1815 -- if there has not been an error so far; errors often
1816 -- give rise to spurious ambiguous Insts
1817 ifErrsM (returnM []) (
1819 -- Complain about the ones that don't fall under
1820 -- the Haskell rules for disambiguation
1821 -- This group includes both non-existent instances
1822 -- e.g. Num (IO a) and Eq (Int -> Int)
1823 -- and ambiguous dictionaries
1825 addTopAmbigErrs ambigs `thenM_`
1827 -- Disambiguate the ones that look feasible
1828 mappM (disambigGroup is_interactive) std_oks
1829 ) `thenM` \ binds_ambig ->
1831 returnM (binds `unionBags` unionManyBags binds_ambig)
1833 ----------------------------------
1834 d1 `cmp_by_tyvar` d2 = get_tv d1 `compare` get_tv d2
1836 get_tv d = case getDictClassTys d of
1837 (clas, [ty]) -> tcGetTyVar "tcSimplify" ty
1838 get_clas d = case getDictClassTys d of
1839 (clas, [ty]) -> clas
1842 If a dictionary constrains a type variable which is
1843 * not mentioned in the environment
1844 * and not mentioned in the type of the expression
1845 then it is ambiguous. No further information will arise to instantiate
1846 the type variable; nor will it be generalised and turned into an extra
1847 parameter to a function.
1849 It is an error for this to occur, except that Haskell provided for
1850 certain rules to be applied in the special case of numeric types.
1852 * at least one of its classes is a numeric class, and
1853 * all of its classes are numeric or standard
1854 then the type variable can be defaulted to the first type in the
1855 default-type list which is an instance of all the offending classes.
1857 So here is the function which does the work. It takes the ambiguous
1858 dictionaries and either resolves them (producing bindings) or
1859 complains. It works by splitting the dictionary list by type
1860 variable, and using @disambigOne@ to do the real business.
1862 @disambigOne@ assumes that its arguments dictionaries constrain all
1863 the same type variable.
1865 ADR Comment 20/6/94: I've changed the @CReturnable@ case to default to
1866 @()@ instead of @Int@. I reckon this is the Right Thing to do since
1867 the most common use of defaulting is code like:
1869 _ccall_ foo `seqPrimIO` bar
1871 Since we're not using the result of @foo@, the result if (presumably)
1875 disambigGroup :: Bool -- True <=> simplifying at top-level interactive loop
1876 -> [Inst] -- All standard classes of form (C a)
1879 disambigGroup is_interactive dicts
1880 | any std_default_class classes -- Guaranteed all standard classes
1881 = -- THE DICTS OBEY THE DEFAULTABLE CONSTRAINT
1882 -- SO, TRY DEFAULT TYPES IN ORDER
1884 -- Failure here is caused by there being no type in the
1885 -- default list which can satisfy all the ambiguous classes.
1886 -- For example, if Real a is reqd, but the only type in the
1887 -- default list is Int.
1888 get_default_tys `thenM` \ default_tys ->
1890 try_default [] -- No defaults work, so fail
1893 try_default (default_ty : default_tys)
1894 = tryTcLIE_ (try_default default_tys) $ -- If default_ty fails, we try
1895 -- default_tys instead
1896 tcSimplifyDefault theta `thenM` \ _ ->
1899 theta = [mkClassPred clas [default_ty] | clas <- classes]
1901 -- See if any default works
1902 tryM (try_default default_tys) `thenM` \ mb_ty ->
1905 Right chosen_default_ty -> choose_default chosen_default_ty
1907 | otherwise -- No defaults
1911 tyvar = get_tv (head dicts) -- Should be non-empty
1912 classes = map get_clas dicts
1914 std_default_class cls
1915 = isNumericClass cls
1916 || (is_interactive &&
1917 classKey cls `elem` [showClassKey, eqClassKey, ordClassKey])
1918 -- In interactive mode, we default Show a to Show ()
1919 -- to avoid graututious errors on "show []"
1921 choose_default default_ty -- Commit to tyvar = default_ty
1922 = -- Bind the type variable
1923 unifyTauTy default_ty (mkTyVarTy tyvar) `thenM_`
1924 -- and reduce the context, for real this time
1925 simpleReduceLoop (text "disambig" <+> ppr dicts)
1926 reduceMe dicts `thenM` \ (frees, binds, ambigs) ->
1927 WARN( not (null frees && null ambigs), ppr frees $$ ppr ambigs )
1928 warnDefault dicts default_ty `thenM_`
1931 bomb_out = addTopAmbigErrs dicts `thenM_`
1935 = do { mb_defaults <- getDefaultTys
1936 ; case mb_defaults of
1937 Just tys -> return tys
1938 Nothing -> -- No use-supplied default;
1939 -- use [Integer, Double]
1940 do { integer_ty <- tcMetaTy integerTyConName
1941 ; return [integer_ty, doubleTy] } }
1944 [Aside - why the defaulting mechanism is turned off when
1945 dealing with arguments and results to ccalls.
1947 When typechecking _ccall_s, TcExpr ensures that the external
1948 function is only passed arguments (and in the other direction,
1949 results) of a restricted set of 'native' types. This is
1950 implemented via the help of the pseudo-type classes,
1951 @CReturnable@ (CR) and @CCallable@ (CC.)
1953 The interaction between the defaulting mechanism for numeric
1954 values and CC & CR can be a bit puzzling to the user at times.
1963 What type has 'x' got here? That depends on the default list
1964 in operation, if it is equal to Haskell 98's default-default
1965 of (Integer, Double), 'x' has type Double, since Integer
1966 is not an instance of CR. If the default list is equal to
1967 Haskell 1.4's default-default of (Int, Double), 'x' has type
1970 To try to minimise the potential for surprises here, the
1971 defaulting mechanism is turned off in the presence of
1972 CCallable and CReturnable.
1977 %************************************************************************
1979 \subsection[simple]{@Simple@ versions}
1981 %************************************************************************
1983 Much simpler versions when there are no bindings to make!
1985 @tcSimplifyThetas@ simplifies class-type constraints formed by
1986 @deriving@ declarations and when specialising instances. We are
1987 only interested in the simplified bunch of class/type constraints.
1989 It simplifies to constraints of the form (C a b c) where
1990 a,b,c are type variables. This is required for the context of
1991 instance declarations.
1994 tcSimplifyDeriv :: [TyVar]
1995 -> ThetaType -- Wanted
1996 -> TcM ThetaType -- Needed
1998 tcSimplifyDeriv tyvars theta
1999 = tcInstTyVars VanillaTv tyvars `thenM` \ (tvs, _, tenv) ->
2000 -- The main loop may do unification, and that may crash if
2001 -- it doesn't see a TcTyVar, so we have to instantiate. Sigh
2002 -- ToDo: what if two of them do get unified?
2003 newDicts DataDeclOrigin (substTheta tenv theta) `thenM` \ wanteds ->
2004 simpleReduceLoop doc reduceMe wanteds `thenM` \ (frees, _, irreds) ->
2005 ASSERT( null frees ) -- reduceMe never returns Free
2007 doptM Opt_AllowUndecidableInstances `thenM` \ undecidable_ok ->
2009 tv_set = mkVarSet tvs
2010 simpl_theta = map dictPred irreds -- reduceMe squashes all non-dicts
2013 | isEmptyVarSet pred_tyvars -- Things like (Eq T) should be rejected
2014 = addErrTc (noInstErr pred)
2016 | not undecidable_ok && not (isTyVarClassPred pred)
2017 -- Check that the returned dictionaries are all of form (C a b)
2018 -- (where a, b are type variables).
2019 -- We allow this if we had -fallow-undecidable-instances,
2020 -- but note that risks non-termination in the 'deriving' context-inference
2021 -- fixpoint loop. It is useful for situations like
2022 -- data Min h a = E | M a (h a)
2023 -- which gives the instance decl
2024 -- instance (Eq a, Eq (h a)) => Eq (Min h a)
2025 = addErrTc (noInstErr pred)
2027 | not (pred_tyvars `subVarSet` tv_set)
2028 -- Check for a bizarre corner case, when the derived instance decl should
2029 -- have form instance C a b => D (T a) where ...
2030 -- Note that 'b' isn't a parameter of T. This gives rise to all sorts
2031 -- of problems; in particular, it's hard to compare solutions for
2032 -- equality when finding the fixpoint. So I just rule it out for now.
2033 = addErrTc (badDerivedPred pred)
2038 pred_tyvars = tyVarsOfPred pred
2040 rev_env = mkTopTyVarSubst tvs (mkTyVarTys tyvars)
2041 -- This reverse-mapping is a Royal Pain,
2042 -- but the result should mention TyVars not TcTyVars
2045 mappM check_pred simpl_theta `thenM_`
2046 checkAmbiguity tvs simpl_theta tv_set `thenM_`
2047 returnM (substTheta rev_env simpl_theta)
2049 doc = ptext SLIT("deriving classes for a data type")
2052 @tcSimplifyDefault@ just checks class-type constraints, essentially;
2053 used with \tr{default} declarations. We are only interested in
2054 whether it worked or not.
2057 tcSimplifyDefault :: ThetaType -- Wanted; has no type variables in it
2060 tcSimplifyDefault theta
2061 = newDicts DataDeclOrigin theta `thenM` \ wanteds ->
2062 simpleReduceLoop doc reduceMe wanteds `thenM` \ (frees, _, irreds) ->
2063 ASSERT( null frees ) -- try_me never returns Free
2064 mappM (addErrTc . noInstErr) irreds `thenM_`
2070 doc = ptext SLIT("default declaration")
2074 %************************************************************************
2076 \section{Errors and contexts}
2078 %************************************************************************
2080 ToDo: for these error messages, should we note the location as coming
2081 from the insts, or just whatever seems to be around in the monad just
2085 groupErrs :: ([Inst] -> TcM ()) -- Deal with one group
2086 -> [Inst] -- The offending Insts
2088 -- Group together insts with the same origin
2089 -- We want to report them together in error messages
2091 groupErrs report_err []
2093 groupErrs report_err (inst:insts)
2094 = do_one (inst:friends) `thenM_`
2095 groupErrs report_err others
2098 -- (It may seem a bit crude to compare the error messages,
2099 -- but it makes sure that we combine just what the user sees,
2100 -- and it avoids need equality on InstLocs.)
2101 (friends, others) = partition is_friend insts
2102 loc_msg = showSDoc (pprInstLoc (instLoc inst))
2103 is_friend friend = showSDoc (pprInstLoc (instLoc friend)) == loc_msg
2104 do_one insts = addInstCtxt (instLoc (head insts)) (report_err insts)
2105 -- Add location and context information derived from the Insts
2107 -- Add the "arising from..." part to a message about bunch of dicts
2108 addInstLoc :: [Inst] -> Message -> Message
2109 addInstLoc insts msg = msg $$ nest 2 (pprInstLoc (instLoc (head insts)))
2112 plural xs = char 's'
2115 = groupErrs report tidy_dicts
2117 (tidy_env, tidy_dicts) = tidyInsts dicts
2118 report dicts = addErrTcM (tidy_env, mk_msg dicts)
2119 mk_msg dicts = addInstLoc dicts (ptext SLIT("Unbound implicit parameter") <>
2120 plural tidy_dicts <+> pprInsts tidy_dicts)
2122 addNoInstanceErrs :: Maybe SDoc -- Nothing => top level
2123 -- Just d => d describes the construct
2124 -> [Inst] -- What is given by the context or type sig
2125 -> [Inst] -- What is wanted
2127 addNoInstanceErrs mb_what givens []
2129 addNoInstanceErrs mb_what givens dicts
2130 = -- Some of the dicts are here because there is no instances
2131 -- and some because there are too many instances (overlap)
2132 -- The first thing we do is separate them
2133 getDOpts `thenM` \ dflags ->
2134 tcGetInstEnvs `thenM` \ inst_envs ->
2136 (tidy_env1, tidy_givens) = tidyInsts givens
2137 (tidy_env2, tidy_dicts) = tidyMoreInsts tidy_env1 dicts
2139 -- Run through the dicts, generating a message for each
2140 -- overlapping one, but simply accumulating all the
2141 -- no-instance ones so they can be reported as a group
2142 (overlap_doc, no_inst_dicts) = foldl check_overlap (empty, []) tidy_dicts
2143 check_overlap (overlap_doc, no_inst_dicts) dict
2144 | not (isClassDict dict) = (overlap_doc, dict : no_inst_dicts)
2146 = case lookupInstEnv dflags inst_envs clas tys of
2148 | length ms > 1 -> (mk_overlap_msg dict res $$ overlap_doc, no_inst_dicts)
2149 | otherwise -> (overlap_doc, dict : no_inst_dicts) -- No match
2150 -- NB: there can be exactly one match, in the case where we have
2151 -- instance C a where ...
2152 -- (In this case, lookupInst doesn't bother to look up,
2153 -- unless -fallow-undecidable-instances is set.)
2154 -- So we report this as "no instance" rather than "overlap"; the fix is
2155 -- to specify -fallow-undecidable-instances, but we leave that to the programmer!
2157 (clas,tys) = getDictClassTys dict
2159 mk_probable_fix tidy_env2 mb_what no_inst_dicts `thenM` \ (tidy_env3, probable_fix) ->
2161 no_inst_doc | null no_inst_dicts = empty
2162 | otherwise = vcat [addInstLoc no_inst_dicts heading, probable_fix]
2163 heading | null givens = ptext SLIT("No instance") <> plural no_inst_dicts <+>
2164 ptext SLIT("for") <+> pprInsts no_inst_dicts
2165 | otherwise = sep [ptext SLIT("Could not deduce") <+> pprInsts no_inst_dicts,
2166 nest 2 $ ptext SLIT("from the context") <+> pprInsts tidy_givens]
2168 addErrTcM (tidy_env3, no_inst_doc $$ overlap_doc)
2171 mk_overlap_msg dict (matches, unifiers)
2172 = vcat [ addInstLoc [dict] ((ptext SLIT("Overlapping instances for") <+> ppr dict)),
2173 sep [ptext SLIT("Matching instances") <> colon,
2174 nest 2 (pprDFuns (dfuns ++ unifiers))],
2177 else parens (ptext SLIT("The choice depends on the instantiation of") <+>
2178 quotes (pprWithCommas ppr (varSetElems (tyVarsOfInst dict))))]
2180 dfuns = [df | (_, (_,_,df)) <- matches]
2182 mk_probable_fix tidy_env Nothing dicts -- Top level
2183 = mkMonomorphismMsg tidy_env dicts
2184 mk_probable_fix tidy_env (Just what) dicts -- Nested (type signatures, instance decls)
2185 = returnM (tidy_env, sep [ptext SLIT("Probable fix:"), nest 2 fix1, nest 2 fix2])
2187 fix1 = sep [ptext SLIT("Add") <+> pprInsts dicts,
2188 ptext SLIT("to the") <+> what]
2190 fix2 | null instance_dicts = empty
2191 | otherwise = ptext SLIT("Or add an instance declaration for")
2192 <+> pprInsts instance_dicts
2193 instance_dicts = [d | d <- dicts, isClassDict d, not (isTyVarDict d)]
2194 -- Insts for which it is worth suggesting an adding an instance declaration
2195 -- Exclude implicit parameters, and tyvar dicts
2198 addTopAmbigErrs dicts
2199 -- Divide into groups that share a common set of ambiguous tyvars
2200 = mapM report (equivClasses cmp [(d, tvs_of d) | d <- tidy_dicts])
2202 (tidy_env, tidy_dicts) = tidyInsts dicts
2204 tvs_of :: Inst -> [TcTyVar]
2205 tvs_of d = varSetElems (tyVarsOfInst d)
2206 cmp (_,tvs1) (_,tvs2) = tvs1 `compare` tvs2
2208 report :: [(Inst,[TcTyVar])] -> TcM ()
2209 report pairs@((inst,tvs) : _) -- The pairs share a common set of ambiguous tyvars
2210 = mkMonomorphismMsg tidy_env dicts `thenM` \ (tidy_env, mono_msg) ->
2211 addSrcSpan (instLocSrcSpan (instLoc inst)) $
2212 -- the location of the first one will do for the err message
2213 addErrTcM (tidy_env, msg $$ mono_msg)
2215 dicts = map fst pairs
2216 msg = sep [text "Ambiguous type variable" <> plural tvs <+>
2217 pprQuotedList tvs <+> in_msg,
2218 nest 2 (pprInstsInFull dicts)]
2219 in_msg | isSingleton dicts = text "in the top-level constraint:"
2220 | otherwise = text "in these top-level constraints:"
2223 mkMonomorphismMsg :: TidyEnv -> [Inst] -> TcM (TidyEnv, Message)
2224 -- There's an error with these Insts; if they have free type variables
2225 -- it's probably caused by the monomorphism restriction.
2226 -- Try to identify the offending variable
2227 -- ASSUMPTION: the Insts are fully zonked
2228 mkMonomorphismMsg tidy_env insts
2229 | isEmptyVarSet inst_tvs
2230 = returnM (tidy_env, empty)
2232 = findGlobals inst_tvs tidy_env `thenM` \ (tidy_env, docs) ->
2233 returnM (tidy_env, mk_msg docs)
2236 inst_tvs = tyVarsOfInsts insts
2238 mk_msg [] = empty -- This happens in things like
2239 -- f x = show (read "foo")
2240 -- whre monomorphism doesn't play any role
2241 mk_msg docs = vcat [ptext SLIT("Possible cause: the monomorphism restriction applied to the following:"),
2243 ptext SLIT("Probable fix: give these definition(s) an explicit type signature")]
2245 warnDefault dicts default_ty
2246 = doptM Opt_WarnTypeDefaults `thenM` \ warn_flag ->
2247 addInstCtxt (instLoc (head dicts)) (warnTc warn_flag warn_msg)
2250 (_, tidy_dicts) = tidyInsts dicts
2251 warn_msg = vcat [ptext SLIT("Defaulting the following constraint(s) to type") <+>
2252 quotes (ppr default_ty),
2253 pprInstsInFull tidy_dicts]
2255 -- Used for the ...Thetas variants; all top level
2256 noInstErr pred = ptext SLIT("No instance for") <+> quotes (ppr pred)
2259 = vcat [ptext SLIT("Can't derive instances where the instance context mentions"),
2260 ptext SLIT("type variables that are not data type parameters"),
2261 nest 2 (ptext SLIT("Offending constraint:") <+> ppr pred)]
2263 reduceDepthErr n stack
2264 = vcat [ptext SLIT("Context reduction stack overflow; size =") <+> int n,
2265 ptext SLIT("Use -fcontext-stack20 to increase stack size to (e.g.) 20"),
2266 nest 4 (pprInstsInFull stack)]
2268 reduceDepthMsg n stack = nest 4 (pprInstsInFull stack)