2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[TcSimplify]{TcSimplify}
10 tcSimplifyInfer, tcSimplifyInferCheck, tcSimplifyCheck,
11 tcSimplifyToDicts, tcSimplifyIPs, tcSimplifyTop,
12 tcSimplifyThetas, tcSimplifyCheckThetas,
16 #include "HsVersions.h"
18 import HsSyn ( MonoBinds(..), HsExpr(..), andMonoBinds, andMonoBindList )
19 import TcHsSyn ( TcExpr, TcId,
20 TcMonoBinds, TcDictBinds
24 import Inst ( lookupInst, lookupSimpleInst, LookupInstResult(..),
25 tyVarsOfInst, predsOfInsts,
27 isStdClassTyVarDict, isMethodFor,
28 instToId, tyVarsOfInsts,
29 instBindingRequired, instCanBeGeneralised,
30 newDictsFromOld, instMentionsIPs,
31 getDictClassTys, getIPs, isTyVarDict,
32 instLoc, pprInst, zonkInst, tidyInst, tidyInsts,
33 Inst, LIE, pprInsts, pprInstsInFull,
34 mkLIE, plusLIE, isEmptyLIE,
37 import TcEnv ( tcGetGlobalTyVars, tcGetInstEnv )
38 import InstEnv ( lookupInstEnv, classInstEnv, InstLookupResult(..) )
40 import TcType ( zonkTcTyVarsAndFV, tcInstTyVars )
41 import TcUnify ( unifyTauTy )
44 import NameSet ( mkNameSet )
45 import Class ( Class, classBigSig )
46 import FunDeps ( oclose, grow, improve )
47 import PrelInfo ( isNumericClass, isCreturnableClass, isCcallishClass )
49 import Type ( Type, ClassContext,
51 isTyVarTy, splitSigmaTy, tyVarsOfTypes
53 import Subst ( mkTopTyVarSubst, substClasses, substTy )
54 import PprType ( pprClassPred )
55 import TysWiredIn ( unitTy )
59 import ListSetOps ( equivClasses )
60 import Util ( zipEqual, mapAccumL )
61 import List ( partition )
66 %************************************************************************
70 %************************************************************************
72 --------------------------------------
73 Notes on quantification
74 --------------------------------------
76 Suppose we are about to do a generalisation step.
81 C the constraints from that RHS
83 The game is to figure out
85 Q the set of type variables over which to quantify
86 Ct the constraints we will *not* quantify over
87 Cq the constraints we will quantify over
89 So we're going to infer the type
93 and float the constraints Ct further outwards.
95 Here are the things that *must* be true:
97 (A) Q intersect fv(G) = EMPTY limits how big Q can be
98 (B) Q superset fv(Cq union T) \ oclose(fv(G),C) limits how small Q can be
100 (A) says we can't quantify over a variable that's free in the
101 environment. (B) says we must quantify over all the truly free
102 variables in T, else we won't get a sufficiently general type. We do
103 not *need* to quantify over any variable that is fixed by the free
104 vars of the environment G.
106 BETWEEN THESE TWO BOUNDS, ANY Q WILL DO!
108 Example: class H x y | x->y where ...
110 fv(G) = {a} C = {H a b, H c d}
113 (A) Q intersect {a} is empty
114 (B) Q superset {a,b,c,d} \ oclose({a}, C) = {a,b,c,d} \ {a,b} = {c,d}
116 So Q can be {c,d}, {b,c,d}
118 Other things being equal, however, we'd like to quantify over as few
119 variables as possible: smaller types, fewer type applications, more
120 constraints can get into Ct instead of Cq.
123 -----------------------------------------
126 fv(T) the free type vars of T
128 oclose(vs,C) The result of extending the set of tyvars vs
129 using the functional dependencies from C
131 grow(vs,C) The result of extend the set of tyvars vs
132 using all conceivable links from C.
134 E.g. vs = {a}, C = {H [a] b, K (b,Int) c, Eq e}
135 Then grow(vs,C) = {a,b,c}
137 Note that grow(vs,C) `superset` grow(vs,simplify(C))
138 That is, simplfication can only shrink the result of grow.
141 oclose is conservative one way: v `elem` oclose(vs,C) => v is definitely fixed by vs
142 grow is conservative the other way: if v might be fixed by vs => v `elem` grow(vs,C)
145 -----------------------------------------
149 Here's a good way to choose Q:
151 Q = grow( fv(T), C ) \ oclose( fv(G), C )
153 That is, quantify over all variable that that MIGHT be fixed by the
154 call site (which influences T), but which aren't DEFINITELY fixed by
155 G. This choice definitely quantifies over enough type variables,
156 albeit perhaps too many.
158 Why grow( fv(T), C ) rather than fv(T)? Consider
160 class H x y | x->y where ...
165 If we used fv(T) = {c} we'd get the type
167 forall c. H c d => c -> b
169 And then if the fn was called at several different c's, each of
170 which fixed d differently, we'd get a unification error, because
171 d isn't quantified. Solution: quantify d. So we must quantify
172 everything that might be influenced by c.
174 Why not oclose( fv(T), C )? Because we might not be able to see
175 all the functional dependencies yet:
177 class H x y | x->y where ...
178 instance H x y => Eq (T x y) where ...
183 Now oclose(fv(T),C) = {c}, because the functional dependency isn't
184 apparent yet, and that's wrong. We must really quantify over d too.
187 There really isn't any point in quantifying over any more than
188 grow( fv(T), C ), because the call sites can't possibly influence
189 any other type variables.
193 --------------------------------------
195 --------------------------------------
197 It's very hard to be certain when a type is ambiguous. Consider
201 instance H x y => K (x,y)
203 Is this type ambiguous?
204 forall a b. (K (a,b), Eq b) => a -> a
206 Looks like it! But if we simplify (K (a,b)) we get (H a b) and
207 now we see that a fixes b. So we can't tell about ambiguity for sure
208 without doing a full simplification. And even that isn't possible if
209 the context has some free vars that may get unified. Urgle!
211 Here's another example: is this ambiguous?
212 forall a b. Eq (T b) => a -> a
213 Not if there's an insance decl (with no context)
214 instance Eq (T b) where ...
216 You may say of this example that we should use the instance decl right
217 away, but you can't always do that:
219 class J a b where ...
220 instance J Int b where ...
222 f :: forall a b. J a b => a -> a
224 (Notice: no functional dependency in J's class decl.)
225 Here f's type is perfectly fine, provided f is only called at Int.
226 It's premature to complain when meeting f's signature, or even
227 when inferring a type for f.
231 However, we don't *need* to report ambiguity right away. It'll always
232 show up at the call site.... and eventually at main, which needs special
233 treatment. Nevertheless, reporting ambiguity promptly is an excellent thing.
235 So heres the plan. We WARN about probable ambiguity if
237 fv(Cq) is not a subset of oclose(fv(T) union fv(G), C)
239 (all tested before quantification).
240 That is, all the type variables in Cq must be fixed by the the variables
241 in the environment, or by the variables in the type.
243 Notice that we union before calling oclose. Here's an example:
245 class J a b c | a b -> c
249 forall b c. (J a b c) => b -> b
251 Only if we union {a} from G with {b} from T before using oclose,
252 do we see that c is fixed.
254 It's a bit vague exactly which C we should use for this oclose call. If we
255 don't fix enough variables we might complain when we shouldn't (see
256 the above nasty example). Nothing will be perfect. That's why we can
257 only issue a warning.
260 Can we ever be *certain* about ambiguity? Yes: if there's a constraint
262 c in C such that fv(c) intersect (fv(G) union fv(T)) = EMPTY
264 then c is a "bubble"; there's no way it can ever improve, and it's
265 certainly ambiguous. UNLESS it is a constant (sigh). And what about
270 instance H x y => K (x,y)
272 Is this type ambiguous?
273 forall a b. (K (a,b), Eq b) => a -> a
275 Urk. The (Eq b) looks "definitely ambiguous" but it isn't. What we are after
276 is a "bubble" that's a set of constraints
278 Cq = Ca union Cq' st fv(Ca) intersect (fv(Cq') union fv(T) union fv(G)) = EMPTY
280 Hence another idea. To decide Q start with fv(T) and grow it
281 by transitive closure in Cq (no functional dependencies involved).
282 Now partition Cq using Q, leaving the definitely-ambiguous and probably-ok.
283 The definitely-ambigous can then float out, and get smashed at top level
284 (which squashes out the constants, like Eq (T a) above)
287 --------------------------------------
288 Notes on implicit parameters
289 --------------------------------------
295 Then we get an LIE like (?y::Int). Doesn't constrain a type variable,
296 but we must nevertheless infer a type like
298 f :: (?y::Int) => Int -> Int
300 so that f is passed the value of y at the call site. Is this legal?
305 Should f be overloaded on "?y" ? Or does the type signature say that it
306 shouldn't be? Our position is that it should be illegal. Otherwise
307 you can change the *dynamic* semantics by adding a type signature:
309 (let f x = x + ?y -- f :: (?y::Int) => Int -> Int
310 in (f 3, f 3 with ?y=5)) with ?y = 6
316 in (f 3, f 3 with ?y=5)) with ?y = 6
320 URK! Let's not do this. So this is illegal:
325 BOTTOM LINE: you *must* quantify over implicit parameters.
328 --------------------------------------
329 Notes on principal types
330 --------------------------------------
335 f x = let g y = op (y::Int) in True
337 Here the principal type of f is (forall a. a->a)
338 but we'll produce the non-principal type
339 f :: forall a. C Int => a -> a
342 %************************************************************************
344 \subsection{tcSimplifyInfer}
346 %************************************************************************
348 tcSimplify is called when we *inferring* a type. Here's the overall game plan:
350 1. Compute Q = grow( fvs(T), C )
352 2. Partition C based on Q into Ct and Cq. Notice that ambiguous
353 predicates will end up in Ct; we deal with them at the top level
355 3. Try improvement, using functional dependencies
357 4. If Step 3 did any unification, repeat from step 1
358 (Unification can change the result of 'grow'.)
360 Note: we don't reduce dictionaries in step 2. For example, if we have
361 Eq (a,b), we don't simplify to (Eq a, Eq b). So Q won't be different
362 after step 2. However note that we may therefore quantify over more
363 type variables than we absolutely have to.
365 For the guts, we need a loop, that alternates context reduction and
366 improvement with unification. E.g. Suppose we have
368 class C x y | x->y where ...
370 and tcSimplify is called with:
372 Then improvement unifies a with b, giving
375 If we need to unify anything, we rattle round the whole thing all over
382 -> [TcTyVar] -- fv(T); type vars
384 -> TcM ([TcTyVar], -- Tyvars to quantify (zonked)
386 TcDictBinds, -- Bindings
387 [TcId]) -- Dict Ids that must be bound here (zonked)
392 tcSimplifyInfer doc tau_tvs wanted_lie
393 = inferLoop doc tau_tvs (lieToList wanted_lie) `thenTc` \ (qtvs, frees, binds, irreds) ->
395 -- Check for non-generalisable insts
396 mapTc_ addCantGenErr (filter (not . instCanBeGeneralised) irreds) `thenTc_`
398 returnTc (qtvs, frees, binds, map instToId irreds)
400 inferLoop doc tau_tvs wanteds
402 zonkTcTyVarsAndFV tau_tvs `thenNF_Tc` \ tau_tvs' ->
403 mapNF_Tc zonkInst wanteds `thenNF_Tc` \ wanteds' ->
404 tcGetGlobalTyVars `thenNF_Tc` \ gbl_tvs ->
406 preds = predsOfInsts wanteds'
407 qtvs = grow preds tau_tvs' `minusVarSet` oclose preds gbl_tvs
410 | isFree qtvs inst = Free
411 | isClassDict inst = DontReduceUnlessConstant -- Dicts
412 | otherwise = ReduceMe AddToIrreds -- Lits and Methods
415 reduceContext doc try_me [] wanteds' `thenTc` \ (no_improvement, frees, binds, irreds) ->
418 if no_improvement then
419 returnTc (varSetElems qtvs, frees, binds, irreds)
421 -- We start again with irreds, not wanteds
422 -- Using an instance decl might have introduced a fresh type variable
423 -- which might have been unified, so we'd get an infinite loop
424 -- if we started again with wanteds! See example [LOOP]
425 inferLoop doc tau_tvs irreds `thenTc` \ (qtvs1, frees1, binds1, irreds1) ->
426 returnTc (qtvs1, frees1 `plusLIE` frees, binds `AndMonoBinds` binds1, irreds1)
431 class If b t e r | b t e -> r
434 class Lte a b c | a b -> c where lte :: a -> b -> c
436 instance (Lte a b l,If l b a c) => Max a b c
438 Wanted: Max Z (S x) y
440 Then we'll reduce using the Max instance to:
441 (Lte Z (S x) l, If l (S x) Z y)
442 and improve by binding l->T, after which we can do some reduction
443 on both the Lte and If constraints. What we *can't* do is start again
444 with (Max Z (S x) y)!
448 = not (tyVarsOfInst inst `intersectsVarSet` qtvs) -- Constrains no quantified vars
449 && null (getIPs inst) -- And no implicit parameter involved
450 -- (see "Notes on implicit parameters")
454 %************************************************************************
456 \subsection{tcSimplifyCheck}
458 %************************************************************************
460 @tcSimplifyCheck@ is used when we know exactly the set of variables
461 we are going to quantify over.
466 -> [TcTyVar] -- Quantify over these
470 TcDictBinds) -- Bindings
472 tcSimplifyCheck doc qtvs givens wanted_lie
473 = checkLoop doc qtvs givens (lieToList wanted_lie) `thenTc` \ (frees, binds, irreds) ->
475 -- Complain about any irreducible ones
476 complainCheck doc givens irreds `thenNF_Tc_`
479 returnTc (frees, binds)
481 checkLoop doc qtvs givens wanteds
483 zonkTcTyVarsAndFV qtvs `thenNF_Tc` \ qtvs' ->
484 mapNF_Tc zonkInst givens `thenNF_Tc` \ givens' ->
485 mapNF_Tc zonkInst wanteds `thenNF_Tc` \ wanteds' ->
487 -- When checking against a given signature we always reduce
488 -- until we find a match against something given, or can't reduce
489 try_me inst | isFree qtvs' inst = Free
490 | otherwise = ReduceMe AddToIrreds
493 reduceContext doc try_me givens' wanteds' `thenTc` \ (no_improvement, frees, binds, irreds) ->
496 if no_improvement then
497 returnTc (frees, binds, irreds)
499 checkLoop doc qtvs givens irreds `thenTc` \ (frees1, binds1, irreds1) ->
500 returnTc (frees `plusLIE` frees1, binds `AndMonoBinds` binds1, irreds1)
502 complainCheck doc givens irreds
503 = mapNF_Tc zonkInst given_dicts `thenNF_Tc` \ givens' ->
504 mapNF_Tc (addNoInstanceErr doc given_dicts) irreds `thenNF_Tc_`
507 given_dicts = filter isDict givens
508 -- Filter out methods, which are only added to
509 -- the given set as an optimisation
514 %************************************************************************
516 \subsection{tcSimplifyAndCheck}
518 %************************************************************************
520 @tcSimplifyInferCheck@ is used when we know the consraints we are to simplify
521 against, but we don't know the type variables over which we are going to quantify.
526 -> [TcTyVar] -- fv(T)
529 -> TcM ([TcTyVar], -- Variables over which to quantify
531 TcDictBinds) -- Bindings
533 tcSimplifyInferCheck doc tau_tvs givens wanted
534 = inferCheckLoop doc tau_tvs givens (lieToList wanted) `thenTc` \ (qtvs, frees, binds, irreds) ->
536 -- Complain about any irreducible ones
537 complainCheck doc givens irreds `thenNF_Tc_`
540 returnTc (qtvs, frees, binds)
542 inferCheckLoop doc tau_tvs givens wanteds
544 zonkTcTyVarsAndFV tau_tvs `thenNF_Tc` \ tau_tvs' ->
545 mapNF_Tc zonkInst givens `thenNF_Tc` \ givens' ->
546 mapNF_Tc zonkInst wanteds `thenNF_Tc` \ wanteds' ->
547 tcGetGlobalTyVars `thenNF_Tc` \ gbl_tvs ->
550 -- Figure out what we are going to generalise over
551 -- You might think it should just be the signature tyvars,
552 -- but in bizarre cases you can get extra ones
553 -- f :: forall a. Num a => a -> a
554 -- f x = fst (g (x, head [])) + 1
556 -- Here we infer g :: forall a b. a -> b -> (b,a)
557 -- We don't want g to be monomorphic in b just because
558 -- f isn't quantified over b.
559 qtvs = (tau_tvs' `unionVarSet` tyVarsOfInsts givens') `minusVarSet` gbl_tvs
560 -- We could close gbl_tvs, but its not necessary for
561 -- soundness, and it'll only affect which tyvars, not which
562 -- dictionaries, we quantify over
564 -- When checking against a given signature we always reduce
565 -- until we find a match against something given, or can't reduce
566 try_me inst | isFree qtvs inst = Free
567 | otherwise = ReduceMe AddToIrreds
570 reduceContext doc try_me givens' wanteds' `thenTc` \ (no_improvement, frees, binds, irreds) ->
573 if no_improvement then
574 returnTc (varSetElems qtvs, frees, binds, irreds)
576 inferCheckLoop doc tau_tvs givens wanteds `thenTc` \ (qtvs1, frees1, binds1, irreds1) ->
577 returnTc (qtvs1, frees1 `plusLIE` frees, binds `AndMonoBinds` binds1, irreds1)
582 %************************************************************************
584 \subsection{tcSimplifyToDicts}
586 %************************************************************************
588 On the LHS of transformation rules we only simplify methods and constants,
589 getting dictionaries. We want to keep all of them unsimplified, to serve
590 as the available stuff for the RHS of the rule.
592 The same thing is used for specialise pragmas. Consider
595 {-# SPECIALISE f :: Int -> Int #-}
598 The type checker generates a binding like:
600 f_spec = (f :: Int -> Int)
602 and we want to end up with
604 f_spec = _inline_me_ (f Int dNumInt)
606 But that means that we must simplify the Method for f to (f Int dNumInt)!
607 So tcSimplifyToDicts squeezes out all Methods.
610 tcSimplifyToDicts :: LIE -> TcM ([Inst], TcDictBinds)
611 tcSimplifyToDicts wanted_lie
612 = simpleReduceLoop doc try_me wanteds `thenTc` \ (frees, binds, irreds) ->
613 -- Since try_me doesn't look at types, we don't need to
614 -- do any zonking, so it's safe to call reduceContext directly
615 ASSERT( isEmptyLIE frees )
616 returnTc (irreds, binds)
619 doc = text "tcSimplifyToDicts"
620 wanteds = lieToList wanted_lie
622 -- Reduce methods and lits only; stop as soon as we get a dictionary
623 try_me inst | isDict inst = DontReduce
624 | otherwise = ReduceMe AddToIrreds
628 %************************************************************************
630 \subsection{Filtering at a dynamic binding}
632 %************************************************************************
637 we must discharge all the ?x constraints from B. We also do an improvement
638 step; if we have ?x::t1 and ?x::t2 we must unify t1, t2. No need to iterate, though.
641 tcSimplifyIPs :: [Name] -- The implicit parameters bound here
643 -> TcM (LIE, TcDictBinds)
644 tcSimplifyIPs ip_names wanted_lie
645 = simpleReduceLoop doc try_me wanteds `thenTc` \ (frees, binds, irreds) ->
646 -- The irreducible ones should be a subset of the implicit
647 -- parameters we provided
648 ASSERT( all here_ip irreds )
649 returnTc (frees, binds)
652 doc = text "tcSimplifyIPs" <+> ppr ip_names
653 wanteds = lieToList wanted_lie
654 ip_set = mkNameSet ip_names
655 here_ip ip = isDict ip && ip `instMentionsIPs` ip_set
657 -- Simplify any methods that mention the implicit parameter
658 try_me inst | inst `instMentionsIPs` ip_set = ReduceMe AddToIrreds
663 %************************************************************************
665 \subsection[binds-for-local-funs]{@bindInstsOfLocalFuns@}
667 %************************************************************************
669 When doing a binding group, we may have @Insts@ of local functions.
670 For example, we might have...
672 let f x = x + 1 -- orig local function (overloaded)
673 f.1 = f Int -- two instances of f
678 The point is: we must drop the bindings for @f.1@ and @f.2@ here,
679 where @f@ is in scope; those @Insts@ must certainly not be passed
680 upwards towards the top-level. If the @Insts@ were binding-ified up
681 there, they would have unresolvable references to @f@.
683 We pass in an @init_lie@ of @Insts@ and a list of locally-bound @Ids@.
684 For each method @Inst@ in the @init_lie@ that mentions one of the
685 @Ids@, we create a binding. We return the remaining @Insts@ (in an
686 @LIE@), as well as the @HsBinds@ generated.
689 bindInstsOfLocalFuns :: LIE -> [TcId] -> TcM (LIE, TcMonoBinds)
691 bindInstsOfLocalFuns init_lie local_ids
692 | null overloaded_ids
694 = returnTc (init_lie, EmptyMonoBinds)
697 = simpleReduceLoop doc try_me wanteds `thenTc` \ (frees, binds, irreds) ->
698 ASSERT( null irreds )
699 returnTc (frees, binds)
701 doc = text "bindInsts" <+> ppr local_ids
702 wanteds = lieToList init_lie
703 overloaded_ids = filter is_overloaded local_ids
704 is_overloaded id = case splitSigmaTy (idType id) of
705 (_, theta, _) -> not (null theta)
707 overloaded_set = mkVarSet overloaded_ids -- There can occasionally be a lot of them
708 -- so it's worth building a set, so that
709 -- lookup (in isMethodFor) is faster
711 try_me inst | isMethodFor overloaded_set inst = ReduceMe AddToIrreds
716 %************************************************************************
718 \subsection{Data types for the reduction mechanism}
720 %************************************************************************
722 The main control over context reduction is here
726 = ReduceMe -- Try to reduce this
727 NoInstanceAction -- What to do if there's no such instance
729 | DontReduce -- Return as irreducible
731 | DontReduceUnlessConstant -- Return as irreducible unless it can
732 -- be reduced to a constant in one step
734 | Free -- Return as free
736 data NoInstanceAction
737 = Stop -- Fail; no error message
738 -- (Only used when tautology checking.)
740 | AddToIrreds -- Just add the inst to the irreductible ones; don't
741 -- produce an error message of any kind.
742 -- It might be quite legitimate such as (Eq a)!
748 type RedState = (Avails, -- What's available
749 [Inst]) -- Insts for which try_me returned Free
751 type Avails = FiniteMap Inst Avail
754 = Irred -- Used for irreducible dictionaries,
755 -- which are going to be lambda bound
757 | BoundTo TcId -- Used for dictionaries for which we have a binding
758 -- e.g. those "given" in a signature
760 | NoRhs -- Used for Insts like (CCallable f)
761 -- where no witness is required.
763 | Rhs -- Used when there is a RHS
765 [Inst] -- Insts free in the RHS; we need these too
767 pprAvails avails = vcat [ppr inst <+> equals <+> pprAvail avail
768 | (inst,avail) <- fmToList avails ]
770 instance Outputable Avail where
773 pprAvail NoRhs = text "<no rhs>"
774 pprAvail Irred = text "Irred"
775 pprAvail (BoundTo x) = text "Bound to" <+> ppr x
776 pprAvail (Rhs rhs bs) = ppr rhs <+> braces (ppr bs)
779 Extracting the bindings from a bunch of Avails.
780 The bindings do *not* come back sorted in dependency order.
781 We assume that they'll be wrapped in a big Rec, so that the
782 dependency analyser can sort them out later
786 bindsAndIrreds :: Avails
788 -> (TcDictBinds, -- Bindings
789 [Inst]) -- Irreducible ones
791 bindsAndIrreds avails wanteds
792 = go avails EmptyMonoBinds [] wanteds
794 go avails binds irreds [] = (binds, irreds)
796 go avails binds irreds (w:ws)
797 = case lookupFM avails w of
798 Nothing -> -- Free guys come out here
799 -- (If we didn't do addFree we could use this as the
800 -- criterion for free-ness, and pick up the free ones here too)
801 go avails binds irreds ws
803 Just NoRhs -> go avails binds irreds ws
805 Just Irred -> go (addToFM avails w (BoundTo (instToId w))) binds (w:irreds) ws
807 Just (BoundTo id) -> go avails new_binds irreds ws
809 -- For implicit parameters, all occurrences share the same
810 -- Id, so there is no need for synonym bindings
811 new_binds | new_id == id = binds
812 | otherwise = binds `AndMonoBinds` new_bind
813 new_bind = VarMonoBind new_id (HsVar id)
816 Just (Rhs rhs ws') -> go avails' (binds `AndMonoBinds` new_bind) irreds (ws' ++ ws)
819 avails' = addToFM avails w (BoundTo id)
820 new_bind = VarMonoBind id rhs
824 %************************************************************************
826 \subsection[reduce]{@reduce@}
828 %************************************************************************
830 When the "what to do" predicate doesn't depend on the quantified type variables,
831 matters are easier. We don't need to do any zonking, unless the improvement step
832 does something, in which case we zonk before iterating.
834 The "given" set is always empty.
837 simpleReduceLoop :: SDoc
838 -> (Inst -> WhatToDo) -- What to do, *not* based on the quantified type variables
842 [Inst]) -- Irreducible
844 simpleReduceLoop doc try_me wanteds
845 = mapNF_Tc zonkInst wanteds `thenNF_Tc` \ wanteds' ->
846 reduceContext doc try_me [] wanteds' `thenTc` \ (no_improvement, frees, binds, irreds) ->
847 if no_improvement then
848 returnTc (frees, binds, irreds)
850 simpleReduceLoop doc try_me irreds `thenTc` \ (frees1, binds1, irreds1) ->
851 returnTc (frees `plusLIE` frees1, binds `AndMonoBinds` binds1, irreds1)
857 reduceContext :: SDoc
858 -> (Inst -> WhatToDo)
861 -> NF_TcM (Bool, -- True <=> improve step did no unification
863 TcDictBinds, -- Dictionary bindings
864 [Inst]) -- Irreducible
866 reduceContext doc try_me givens wanteds
868 traceTc (text "reduceContext" <+> (vcat [
869 text "----------------------",
871 text "given" <+> ppr givens,
872 text "wanted" <+> ppr wanteds,
873 text "----------------------"
876 -- Build the Avail mapping from "givens"
877 foldlNF_Tc addGiven (emptyFM, []) givens `thenNF_Tc` \ init_state ->
880 reduceList (0,[]) try_me wanteds init_state `thenNF_Tc` \ state@(avails, frees) ->
882 -- Do improvement, using everything in avails
883 -- In particular, avails includes all superclasses of everything
884 tcImprove avails `thenTc` \ no_improvement ->
886 traceTc (text "reduceContext end" <+> (vcat [
887 text "----------------------",
889 text "given" <+> ppr givens,
890 text "wanted" <+> ppr wanteds,
892 text "avails" <+> pprAvails avails,
893 text "frees" <+> ppr frees,
894 text "no_improvement =" <+> ppr no_improvement,
895 text "----------------------"
898 (binds, irreds) = bindsAndIrreds avails wanteds
900 returnTc (no_improvement, mkLIE frees, binds, irreds)
903 = tcGetInstEnv `thenTc` \ inst_env ->
905 preds = predsOfInsts (keysFM avails)
906 -- Avails has all the superclasses etc (good)
907 -- It also has all the intermediates of the deduction (good)
908 -- It does not have duplicates (good)
909 -- NB that (?x::t1) and (?x::t2) will be held separately in avails
910 -- so that improve will see them separate
911 eqns = improve (classInstEnv inst_env) preds
916 traceTc (ptext SLIT("Improve:") <+> vcat (map ppr_eqn eqns)) `thenNF_Tc_`
917 mapTc_ unify eqns `thenTc_`
920 unify (qtvs, t1, t2) = tcInstTyVars (varSetElems qtvs) `thenNF_Tc` \ (_, _, tenv) ->
921 unifyTauTy (substTy tenv t1) (substTy tenv t2)
922 ppr_eqn (qtvs, t1, t2) = ptext SLIT("forall") <+> braces (pprWithCommas ppr (varSetElems qtvs)) <+>
923 ppr t1 <+> equals <+> ppr t2
926 The main context-reduction function is @reduce@. Here's its game plan.
929 reduceList :: (Int,[Inst]) -- Stack (for err msgs)
930 -- along with its depth
931 -> (Inst -> WhatToDo)
938 try_me: given an inst, this function returns
940 DontReduce return this in "irreds"
941 Free return this in "frees"
943 wanteds: The list of insts to reduce
944 state: An accumulating parameter of type RedState
945 that contains the state of the algorithm
947 It returns a RedState.
949 The (n,stack) pair is just used for error reporting.
950 n is always the depth of the stack.
951 The stack is the stack of Insts being reduced: to produce X
952 I had to produce Y, to produce Y I had to produce Z, and so on.
955 reduceList (n,stack) try_me wanteds state
956 | n > opt_MaxContextReductionDepth
957 = failWithTc (reduceDepthErr n stack)
963 pprTrace "Jeepers! ReduceContext:" (reduceDepthMsg n stack)
968 go [] state = returnTc state
969 go (w:ws) state = reduce (n+1, w:stack) try_me w state `thenTc` \ state' ->
972 -- Base case: we're done!
973 reduce stack try_me wanted state
974 -- It's the same as an existing inst, or a superclass thereof
975 | isAvailable state wanted
979 = case try_me wanted of {
981 DontReduce -> addIrred state wanted
983 ; DontReduceUnlessConstant -> -- It's irreducible (or at least should not be reduced)
984 -- First, see if the inst can be reduced to a constant in one step
987 ; Free -> -- It's free so just chuck it upstairs
988 -- First, see if the inst can be reduced to a constant in one step
991 ; ReduceMe no_instance_action -> -- It should be reduced
992 lookupInst wanted `thenNF_Tc` \ lookup_result ->
993 case lookup_result of
994 GenInst wanteds' rhs -> reduceList stack try_me wanteds' state `thenTc` \ state' ->
995 addWanted state' wanted rhs wanteds'
996 SimpleInst rhs -> addWanted state wanted rhs []
998 NoInstance -> -- No such instance!
999 case no_instance_action of
1001 AddToIrreds -> addIrred state wanted
1005 try_simple do_this_otherwise
1006 = lookupInst wanted `thenNF_Tc` \ lookup_result ->
1007 case lookup_result of
1008 SimpleInst rhs -> addWanted state wanted rhs []
1009 other -> do_this_otherwise state wanted
1014 isAvailable :: RedState -> Inst -> Bool
1015 isAvailable (avails, _) wanted = wanted `elemFM` avails
1016 -- NB: the Ord instance of Inst compares by the class/type info
1017 -- *not* by unique. So
1018 -- d1::C Int == d2::C Int
1020 -------------------------
1021 addFree :: RedState -> Inst -> NF_TcM RedState
1022 -- When an Inst is tossed upstairs as 'free' we nevertheless add it
1023 -- to avails, so that any other equal Insts will be commoned up right
1024 -- here rather than also being tossed upstairs. This is really just
1025 -- an optimisation, and perhaps it is more trouble that it is worth,
1026 -- as the following comments show!
1028 -- NB1: do *not* add superclasses. If we have
1031 -- but a is not bound here, then we *don't* want to derive
1032 -- dn from df here lest we lose sharing.
1034 -- NB2: do *not* add the Inst to avails at all if it's a method.
1035 -- The following situation shows why this is bad:
1036 -- truncate :: forall a. RealFrac a => forall b. Integral b => a -> b
1037 -- From an application (truncate f i) we get
1038 -- t1 = truncate at f
1040 -- If we have also have a second occurrence of truncate, we get
1041 -- t3 = truncate at f
1043 -- When simplifying with i,f free, we might still notice that
1044 -- t1=t3; but alas, the binding for t2 (which mentions t1)
1045 -- will continue to float out!
1046 -- Solution: never put methods in avail till they are captured
1047 -- in which case addFree isn't used
1049 -- NB3: make sure that CCallable/CReturnable use NoRhs rather
1050 -- than BoundTo, else we end up with bogus bindings.
1051 -- c.f. instBindingRequired in addWanted
1052 addFree (avails, frees) free
1053 | isDict free = returnNF_Tc (addToFM avails free avail, free:frees)
1054 | otherwise = returnNF_Tc (avails, free:frees)
1056 avail | instBindingRequired free = BoundTo (instToId free)
1059 addWanted :: RedState -> Inst -> TcExpr -> [Inst] -> NF_TcM RedState
1060 addWanted state@(avails, frees) wanted rhs_expr wanteds
1061 -- Do *not* add superclasses as well. Here's an example of why not
1062 -- class Eq a => Foo a b
1063 -- instance Eq a => Foo [a] a
1064 -- If we are reducing
1066 -- we'll first deduce that it holds (via the instance decl). We
1067 -- must not then overwrite the Eq t constraint with a superclass selection!
1068 -- ToDo: this isn't entirely unsatisfactory, because
1069 -- we may also lose some entirely-legitimate sharing this way
1071 = ASSERT( not (isAvailable state wanted) )
1072 returnNF_Tc (addToFM avails wanted avail, frees)
1074 avail | instBindingRequired wanted = Rhs rhs_expr wanteds
1075 | otherwise = ASSERT( null wanteds ) NoRhs
1077 addGiven :: RedState -> Inst -> NF_TcM RedState
1078 addGiven state given = add_avail state given (BoundTo (instToId given))
1080 addIrred :: RedState -> Inst -> NF_TcM RedState
1081 addIrred state irred = add_avail state irred Irred
1083 add_avail :: RedState -> Inst -> Avail -> NF_TcM RedState
1084 add_avail (avails, frees) wanted avail
1085 = addAvail avails wanted avail `thenNF_Tc` \ avails' ->
1086 returnNF_Tc (avails', frees)
1088 ---------------------
1089 addAvail :: Avails -> Inst -> Avail -> NF_TcM Avails
1090 addAvail avails wanted avail
1091 = addSuperClasses (addToFM avails wanted avail) wanted
1093 addSuperClasses :: Avails -> Inst -> NF_TcM Avails
1094 -- Add all the superclasses of the Inst to Avails
1095 -- Invariant: the Inst is already in Avails.
1097 addSuperClasses avails dict
1098 | not (isClassDict dict)
1099 = returnNF_Tc avails
1101 | otherwise -- It is a dictionary
1102 = newDictsFromOld dict sc_theta' `thenNF_Tc` \ sc_dicts ->
1103 foldlNF_Tc add_sc avails (zipEqual "addSuperClasses" sc_dicts sc_sels)
1105 (clas, tys) = getDictClassTys dict
1106 (tyvars, sc_theta, sc_sels, _) = classBigSig clas
1107 sc_theta' = substClasses (mkTopTyVarSubst tyvars tys) sc_theta
1109 add_sc avails (sc_dict, sc_sel) -- Add it, and its superclasses
1110 = case lookupFM avails sc_dict of
1111 Just (BoundTo _) -> returnNF_Tc avails -- See Note [SUPER] below
1112 other -> addAvail avails sc_dict avail
1114 sc_sel_rhs = DictApp (TyApp (HsVar sc_sel) tys) [instToId dict]
1115 avail = Rhs sc_sel_rhs [dict]
1118 Note [SUPER]. We have to be careful here. If we are *given* d1:Ord a,
1119 and want to deduce (d2:C [a]) where
1121 class Ord a => C a where
1122 instance Ord a => C [a] where ...
1124 Then we'll use the instance decl to deduce C [a] and then add the
1125 superclasses of C [a] to avails. But we must not overwrite the binding
1126 for d1:Ord a (which is given) with a superclass selection or we'll just
1127 build a loop! Hence looking for BoundTo. Crudely, BoundTo is cheaper
1131 %************************************************************************
1133 \section{tcSimplifyTop: defaulting}
1135 %************************************************************************
1138 If a dictionary constrains a type variable which is
1139 * not mentioned in the environment
1140 * and not mentioned in the type of the expression
1141 then it is ambiguous. No further information will arise to instantiate
1142 the type variable; nor will it be generalised and turned into an extra
1143 parameter to a function.
1145 It is an error for this to occur, except that Haskell provided for
1146 certain rules to be applied in the special case of numeric types.
1148 * at least one of its classes is a numeric class, and
1149 * all of its classes are numeric or standard
1150 then the type variable can be defaulted to the first type in the
1151 default-type list which is an instance of all the offending classes.
1153 So here is the function which does the work. It takes the ambiguous
1154 dictionaries and either resolves them (producing bindings) or
1155 complains. It works by splitting the dictionary list by type
1156 variable, and using @disambigOne@ to do the real business.
1158 @tcSimplifyTop@ is called once per module to simplify all the constant
1159 and ambiguous Insts.
1161 We need to be careful of one case. Suppose we have
1163 instance Num a => Num (Foo a b) where ...
1165 and @tcSimplifyTop@ is given a constraint (Num (Foo x y)). Then it'll simplify
1166 to (Num x), and default x to Int. But what about y??
1168 It's OK: the final zonking stage should zap y to (), which is fine.
1172 tcSimplifyTop :: LIE -> TcM TcDictBinds
1173 tcSimplifyTop wanted_lie
1174 = simpleReduceLoop (text "tcSimplTop") try_me wanteds `thenTc` \ (frees, binds, irreds) ->
1175 ASSERT( isEmptyLIE frees )
1178 -- All the non-std ones are definite errors
1179 (stds, non_stds) = partition isStdClassTyVarDict irreds
1181 -- Group by type variable
1182 std_groups = equivClasses cmp_by_tyvar stds
1184 -- Pick the ones which its worth trying to disambiguate
1185 (std_oks, std_bads) = partition worth_a_try std_groups
1187 -- Have a try at disambiguation
1188 -- if the type variable isn't bound
1189 -- up with one of the non-standard classes
1190 worth_a_try group@(d:_) = not (non_std_tyvars `intersectsVarSet` tyVarsOfInst d)
1191 non_std_tyvars = unionVarSets (map tyVarsOfInst non_stds)
1193 -- Collect together all the bad guys
1194 bad_guys = non_stds ++ concat std_bads
1196 -- Disambiguate the ones that look feasible
1197 mapTc disambigGroup std_oks `thenTc` \ binds_ambig ->
1199 -- And complain about the ones that don't
1200 addTopAmbigErrs bad_guys `thenNF_Tc_`
1202 returnTc (binds `andMonoBinds` andMonoBindList binds_ambig)
1204 wanteds = lieToList wanted_lie
1205 try_me inst = ReduceMe AddToIrreds
1207 d1 `cmp_by_tyvar` d2 = get_tv d1 `compare` get_tv d2
1209 get_tv d = case getDictClassTys d of
1210 (clas, [ty]) -> getTyVar "tcSimplifyTop" ty
1211 get_clas d = case getDictClassTys d of
1212 (clas, [ty]) -> clas
1215 @disambigOne@ assumes that its arguments dictionaries constrain all
1216 the same type variable.
1218 ADR Comment 20/6/94: I've changed the @CReturnable@ case to default to
1219 @()@ instead of @Int@. I reckon this is the Right Thing to do since
1220 the most common use of defaulting is code like:
1222 _ccall_ foo `seqPrimIO` bar
1224 Since we're not using the result of @foo@, the result if (presumably)
1228 disambigGroup :: [Inst] -- All standard classes of form (C a)
1232 | any isNumericClass classes -- Guaranteed all standard classes
1233 -- see comment at the end of function for reasons as to
1234 -- why the defaulting mechanism doesn't apply to groups that
1235 -- include CCallable or CReturnable dicts.
1236 && not (any isCcallishClass classes)
1237 = -- THE DICTS OBEY THE DEFAULTABLE CONSTRAINT
1238 -- SO, TRY DEFAULT TYPES IN ORDER
1240 -- Failure here is caused by there being no type in the
1241 -- default list which can satisfy all the ambiguous classes.
1242 -- For example, if Real a is reqd, but the only type in the
1243 -- default list is Int.
1244 tcGetDefaultTys `thenNF_Tc` \ default_tys ->
1246 try_default [] -- No defaults work, so fail
1249 try_default (default_ty : default_tys)
1250 = tryTc_ (try_default default_tys) $ -- If default_ty fails, we try
1251 -- default_tys instead
1252 tcSimplifyCheckThetas [] thetas `thenTc` \ _ ->
1255 thetas = classes `zip` repeat [default_ty]
1257 -- See if any default works, and if so bind the type variable to it
1258 -- If not, add an AmbigErr
1259 recoverTc (addAmbigErrs dicts `thenNF_Tc_` returnTc EmptyMonoBinds) $
1261 try_default default_tys `thenTc` \ chosen_default_ty ->
1263 -- Bind the type variable and reduce the context, for real this time
1264 unifyTauTy chosen_default_ty (mkTyVarTy tyvar) `thenTc_`
1265 simpleReduceLoop (text "disambig" <+> ppr dicts)
1266 try_me dicts `thenTc` \ (frees, binds, ambigs) ->
1267 WARN( not (isEmptyLIE frees && null ambigs), ppr frees $$ ppr ambigs )
1268 warnDefault dicts chosen_default_ty `thenTc_`
1271 | all isCreturnableClass classes
1272 = -- Default CCall stuff to (); we don't even both to check that () is an
1273 -- instance of CReturnable, because we know it is.
1274 unifyTauTy (mkTyVarTy tyvar) unitTy `thenTc_`
1275 returnTc EmptyMonoBinds
1277 | otherwise -- No defaults
1278 = addAmbigErrs dicts `thenNF_Tc_`
1279 returnTc EmptyMonoBinds
1282 try_me inst = ReduceMe AddToIrreds -- This reduce should not fail
1283 tyvar = get_tv (head dicts) -- Should be non-empty
1284 classes = map get_clas dicts
1287 [Aside - why the defaulting mechanism is turned off when
1288 dealing with arguments and results to ccalls.
1290 When typechecking _ccall_s, TcExpr ensures that the external
1291 function is only passed arguments (and in the other direction,
1292 results) of a restricted set of 'native' types. This is
1293 implemented via the help of the pseudo-type classes,
1294 @CReturnable@ (CR) and @CCallable@ (CC.)
1296 The interaction between the defaulting mechanism for numeric
1297 values and CC & CR can be a bit puzzling to the user at times.
1306 What type has 'x' got here? That depends on the default list
1307 in operation, if it is equal to Haskell 98's default-default
1308 of (Integer, Double), 'x' has type Double, since Integer
1309 is not an instance of CR. If the default list is equal to
1310 Haskell 1.4's default-default of (Int, Double), 'x' has type
1313 To try to minimise the potential for surprises here, the
1314 defaulting mechanism is turned off in the presence of
1315 CCallable and CReturnable.
1320 %************************************************************************
1322 \subsection[simple]{@Simple@ versions}
1324 %************************************************************************
1326 Much simpler versions when there are no bindings to make!
1328 @tcSimplifyThetas@ simplifies class-type constraints formed by
1329 @deriving@ declarations and when specialising instances. We are
1330 only interested in the simplified bunch of class/type constraints.
1332 It simplifies to constraints of the form (C a b c) where
1333 a,b,c are type variables. This is required for the context of
1334 instance declarations.
1337 tcSimplifyThetas :: ClassContext -- Wanted
1338 -> TcM ClassContext -- Needed
1340 tcSimplifyThetas wanteds
1341 = doptsTc Opt_GlasgowExts `thenNF_Tc` \ glaExts ->
1342 reduceSimple [] wanteds `thenNF_Tc` \ irreds ->
1344 -- For multi-param Haskell, check that the returned dictionaries
1345 -- don't have any of the form (C Int Bool) for which
1346 -- we expect an instance here
1347 -- For Haskell 98, check that all the constraints are of the form C a,
1348 -- where a is a type variable
1349 bad_guys | glaExts = [ct | ct@(clas,tys) <- irreds,
1350 isEmptyVarSet (tyVarsOfTypes tys)]
1351 | otherwise = [ct | ct@(clas,tys) <- irreds,
1352 not (all isTyVarTy tys)]
1354 if null bad_guys then
1357 mapNF_Tc addNoInstErr bad_guys `thenNF_Tc_`
1361 @tcSimplifyCheckThetas@ just checks class-type constraints, essentially;
1362 used with \tr{default} declarations. We are only interested in
1363 whether it worked or not.
1366 tcSimplifyCheckThetas :: ClassContext -- Given
1367 -> ClassContext -- Wanted
1370 tcSimplifyCheckThetas givens wanteds
1371 = reduceSimple givens wanteds `thenNF_Tc` \ irreds ->
1375 mapNF_Tc addNoInstErr irreds `thenNF_Tc_`
1381 type AvailsSimple = FiniteMap (Class,[Type]) Bool
1382 -- True => irreducible
1383 -- False => given, or can be derived from a given or from an irreducible
1385 reduceSimple :: ClassContext -- Given
1386 -> ClassContext -- Wanted
1387 -> NF_TcM ClassContext -- Irreducible
1389 reduceSimple givens wanteds
1390 = reduce_simple (0,[]) givens_fm wanteds `thenNF_Tc` \ givens_fm' ->
1391 returnNF_Tc [ct | (ct,True) <- fmToList givens_fm']
1393 givens_fm = foldl addNonIrred emptyFM givens
1395 reduce_simple :: (Int,ClassContext) -- Stack
1398 -> NF_TcM AvailsSimple
1400 reduce_simple (n,stack) avails wanteds
1403 go avails [] = returnNF_Tc avails
1404 go avails (w:ws) = reduce_simple_help (n+1,w:stack) avails w `thenNF_Tc` \ avails' ->
1407 reduce_simple_help stack givens wanted@(clas,tys)
1408 | wanted `elemFM` givens
1409 = returnNF_Tc givens
1412 = lookupSimpleInst clas tys `thenNF_Tc` \ maybe_theta ->
1415 Nothing -> returnNF_Tc (addSimpleIrred givens wanted)
1416 Just theta -> reduce_simple stack (addNonIrred givens wanted) theta
1418 addSimpleIrred :: AvailsSimple -> (Class,[Type]) -> AvailsSimple
1419 addSimpleIrred givens ct@(clas,tys)
1420 = addSCs (addToFM givens ct True) ct
1422 addNonIrred :: AvailsSimple -> (Class,[Type]) -> AvailsSimple
1423 addNonIrred givens ct@(clas,tys)
1424 = addSCs (addToFM givens ct False) ct
1426 addSCs givens ct@(clas,tys)
1427 = foldl add givens sc_theta
1429 (tyvars, sc_theta_tmpl, _, _) = classBigSig clas
1430 sc_theta = substClasses (mkTopTyVarSubst tyvars tys) sc_theta_tmpl
1432 add givens ct@(clas, tys)
1433 = case lookupFM givens ct of
1434 Nothing -> -- Add it and its superclasses
1435 addSCs (addToFM givens ct False) ct
1437 Just True -> -- Set its flag to False; superclasses already done
1438 addToFM givens ct False
1440 Just False -> -- Already done
1446 %************************************************************************
1448 \section{Errors and contexts}
1450 %************************************************************************
1452 ToDo: for these error messages, should we note the location as coming
1453 from the insts, or just whatever seems to be around in the monad just
1457 addTopAmbigErrs dicts
1458 = mapNF_Tc complain tidy_dicts
1460 fixed_tvs = oclose (predsOfInsts tidy_dicts) emptyVarSet
1461 (tidy_env, tidy_dicts) = tidyInsts emptyTidyEnv dicts
1462 complain d | not (null (getIPs d)) = addTopIPErr tidy_env d
1463 | tyVarsOfInst d `subVarSet` fixed_tvs = addTopInstanceErr tidy_env d
1464 | otherwise = addAmbigErr tidy_env d
1466 addTopIPErr tidy_env tidy_dict
1467 = addInstErrTcM (instLoc tidy_dict)
1469 ptext SLIT("Unbound implicit parameter") <+> quotes (pprInst tidy_dict))
1471 -- Used for top-level irreducibles
1472 addTopInstanceErr tidy_env tidy_dict
1473 = addInstErrTcM (instLoc tidy_dict)
1475 ptext SLIT("No instance for") <+> quotes (pprInst tidy_dict))
1478 = mapNF_Tc (addAmbigErr tidy_env) tidy_dicts
1480 (tidy_env, tidy_dicts) = tidyInsts emptyTidyEnv dicts
1482 addAmbigErr tidy_env tidy_dict
1483 = addInstErrTcM (instLoc tidy_dict)
1485 sep [text "Ambiguous type variable(s)" <+> pprQuotedList ambig_tvs,
1486 nest 4 (text "in the constraint" <+> quotes (pprInst tidy_dict))])
1488 ambig_tvs = varSetElems (tyVarsOfInst tidy_dict)
1490 warnDefault dicts default_ty
1491 = doptsTc Opt_WarnTypeDefaults `thenTc` \ warn_flag ->
1493 then mapNF_Tc warn groups `thenNF_Tc_` returnNF_Tc ()
1498 (_, tidy_dicts) = mapAccumL tidyInst emptyTidyEnv dicts
1500 -- Group the dictionaries by source location
1501 groups = equivClasses cmp tidy_dicts
1502 i1 `cmp` i2 = get_loc i1 `compare` get_loc i2
1503 get_loc i = case instLoc i of { (_,loc,_) -> loc }
1505 warn [dict] = tcAddSrcLoc (get_loc dict) $
1506 warnTc True (ptext SLIT("Defaulting") <+> quotes (pprInst dict) <+>
1507 ptext SLIT("to type") <+> quotes (ppr default_ty))
1509 warn dicts = tcAddSrcLoc (get_loc (head dicts)) $
1510 warnTc True (vcat [ptext SLIT("Defaulting the following constraint(s) to type") <+> quotes (ppr default_ty),
1511 pprInstsInFull dicts])
1513 -- The error message when we don't find a suitable instance
1514 -- is complicated by the fact that sometimes this is because
1515 -- there is no instance, and sometimes it's because there are
1516 -- too many instances (overlap). See the comments in TcEnv.lhs
1517 -- with the InstEnv stuff.
1518 addNoInstanceErr what_doc givens dict
1519 = tcGetInstEnv `thenNF_Tc` \ inst_env ->
1521 doc = vcat [sep [herald <+> quotes (pprInst tidy_dict),
1522 nest 4 $ ptext SLIT("from the context") <+> pprInsts tidy_givens],
1524 ptext SLIT("Probable fix:"),
1528 herald = ptext SLIT("Could not") <+> unambig_doc <+> ptext SLIT("deduce")
1529 unambig_doc | ambig_overlap = ptext SLIT("unambiguously")
1533 | not ambig_overlap = empty
1535 = vcat [ptext SLIT("The choice of (overlapping) instance declaration"),
1536 nest 4 (ptext SLIT("depends on the instantiation of") <+>
1537 quotes (pprWithCommas ppr (varSetElems (tyVarsOfInst tidy_dict))))]
1539 fix1 = sep [ptext SLIT("Add") <+> quotes (pprInst tidy_dict),
1540 ptext SLIT("to the") <+> what_doc]
1542 fix2 | isTyVarDict dict || ambig_overlap
1545 = ptext SLIT("Or add an instance declaration for") <+> quotes (pprInst tidy_dict)
1547 (tidy_env, tidy_dict:tidy_givens) = tidyInsts emptyTidyEnv (dict:givens)
1549 -- Checks for the ambiguous case when we have overlapping instances
1550 ambig_overlap | isClassDict dict
1551 = case lookupInstEnv inst_env clas tys of
1552 NoMatch ambig -> ambig
1556 (clas,tys) = getDictClassTys dict
1558 addInstErrTcM (instLoc dict) (tidy_env, doc)
1560 -- Used for the ...Thetas variants; all top level
1562 = addErrTc (ptext SLIT("No instance for") <+> quotes (pprClassPred c ts))
1564 reduceDepthErr n stack
1565 = vcat [ptext SLIT("Context reduction stack overflow; size =") <+> int n,
1566 ptext SLIT("Use -fcontext-stack20 to increase stack size to (e.g.) 20"),
1567 nest 4 (pprInstsInFull stack)]
1569 reduceDepthMsg n stack = nest 4 (pprInstsInFull stack)
1571 -----------------------------------------------
1573 = addErrTc (sep [ptext SLIT("Cannot generalise these overloadings (in a _ccall_):"),
1574 nest 4 (ppr inst <+> pprInstLoc (instLoc inst))])