2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
10 tcSimplifyInfer, tcSimplifyInferCheck,
11 tcSimplifyCheck, tcSimplifyRestricted,
12 tcSimplifyRuleLhs, tcSimplifyIPs,
13 tcSimplifySuperClasses,
14 tcSimplifyTop, tcSimplifyInteractive,
15 tcSimplifyBracket, tcSimplifyCheckPat,
17 tcSimplifyDeriv, tcSimplifyDefault,
21 #include "HsVersions.h"
23 import {-# SOURCE #-} TcUnify( unifyType )
60 %************************************************************************
64 %************************************************************************
66 --------------------------------------
67 Notes on functional dependencies (a bug)
68 --------------------------------------
75 instance D a b => C a b -- Undecidable
76 -- (Not sure if it's crucial to this eg)
77 f :: C a b => a -> Bool
80 g :: C a b => a -> Bool
83 Here f typechecks, but g does not!! Reason: before doing improvement,
84 we reduce the (C a b1) constraint from the call of f to (D a b1).
86 Here is a more complicated example:
88 | > class Foo a b | a->b
90 | > class Bar a b | a->b
94 | > instance Bar Obj Obj
96 | > instance (Bar a b) => Foo a b
98 | > foo:: (Foo a b) => a -> String
101 | > runFoo:: (forall a b. (Foo a b) => a -> w) -> w
107 | Could not deduce (Bar a b) from the context (Foo a b)
108 | arising from use of `foo' at <interactive>:1
110 | Add (Bar a b) to the expected type of an expression
111 | In the first argument of `runFoo', namely `foo'
112 | In the definition of `it': it = runFoo foo
114 | Why all of the sudden does GHC need the constraint Bar a b? The
115 | function foo didn't ask for that...
117 The trouble is that to type (runFoo foo), GHC has to solve the problem:
119 Given constraint Foo a b
120 Solve constraint Foo a b'
122 Notice that b and b' aren't the same. To solve this, just do
123 improvement and then they are the same. But GHC currently does
128 That is usually fine, but it isn't here, because it sees that Foo a b is
129 not the same as Foo a b', and so instead applies the instance decl for
130 instance Bar a b => Foo a b. And that's where the Bar constraint comes
133 The Right Thing is to improve whenever the constraint set changes at
134 all. Not hard in principle, but it'll take a bit of fiddling to do.
138 --------------------------------------
139 Notes on quantification
140 --------------------------------------
142 Suppose we are about to do a generalisation step.
146 T the type of the RHS
147 C the constraints from that RHS
149 The game is to figure out
151 Q the set of type variables over which to quantify
152 Ct the constraints we will *not* quantify over
153 Cq the constraints we will quantify over
155 So we're going to infer the type
159 and float the constraints Ct further outwards.
161 Here are the things that *must* be true:
163 (A) Q intersect fv(G) = EMPTY limits how big Q can be
164 (B) Q superset fv(Cq union T) \ oclose(fv(G),C) limits how small Q can be
166 (A) says we can't quantify over a variable that's free in the
167 environment. (B) says we must quantify over all the truly free
168 variables in T, else we won't get a sufficiently general type. We do
169 not *need* to quantify over any variable that is fixed by the free
170 vars of the environment G.
172 BETWEEN THESE TWO BOUNDS, ANY Q WILL DO!
174 Example: class H x y | x->y where ...
176 fv(G) = {a} C = {H a b, H c d}
179 (A) Q intersect {a} is empty
180 (B) Q superset {a,b,c,d} \ oclose({a}, C) = {a,b,c,d} \ {a,b} = {c,d}
182 So Q can be {c,d}, {b,c,d}
184 Other things being equal, however, we'd like to quantify over as few
185 variables as possible: smaller types, fewer type applications, more
186 constraints can get into Ct instead of Cq.
189 -----------------------------------------
192 fv(T) the free type vars of T
194 oclose(vs,C) The result of extending the set of tyvars vs
195 using the functional dependencies from C
197 grow(vs,C) The result of extend the set of tyvars vs
198 using all conceivable links from C.
200 E.g. vs = {a}, C = {H [a] b, K (b,Int) c, Eq e}
201 Then grow(vs,C) = {a,b,c}
203 Note that grow(vs,C) `superset` grow(vs,simplify(C))
204 That is, simplfication can only shrink the result of grow.
207 oclose is conservative one way: v `elem` oclose(vs,C) => v is definitely fixed by vs
208 grow is conservative the other way: if v might be fixed by vs => v `elem` grow(vs,C)
211 -----------------------------------------
215 Here's a good way to choose Q:
217 Q = grow( fv(T), C ) \ oclose( fv(G), C )
219 That is, quantify over all variable that that MIGHT be fixed by the
220 call site (which influences T), but which aren't DEFINITELY fixed by
221 G. This choice definitely quantifies over enough type variables,
222 albeit perhaps too many.
224 Why grow( fv(T), C ) rather than fv(T)? Consider
226 class H x y | x->y where ...
231 If we used fv(T) = {c} we'd get the type
233 forall c. H c d => c -> b
235 And then if the fn was called at several different c's, each of
236 which fixed d differently, we'd get a unification error, because
237 d isn't quantified. Solution: quantify d. So we must quantify
238 everything that might be influenced by c.
240 Why not oclose( fv(T), C )? Because we might not be able to see
241 all the functional dependencies yet:
243 class H x y | x->y where ...
244 instance H x y => Eq (T x y) where ...
249 Now oclose(fv(T),C) = {c}, because the functional dependency isn't
250 apparent yet, and that's wrong. We must really quantify over d too.
253 There really isn't any point in quantifying over any more than
254 grow( fv(T), C ), because the call sites can't possibly influence
255 any other type variables.
259 -------------------------------------
261 -------------------------------------
263 It's very hard to be certain when a type is ambiguous. Consider
267 instance H x y => K (x,y)
269 Is this type ambiguous?
270 forall a b. (K (a,b), Eq b) => a -> a
272 Looks like it! But if we simplify (K (a,b)) we get (H a b) and
273 now we see that a fixes b. So we can't tell about ambiguity for sure
274 without doing a full simplification. And even that isn't possible if
275 the context has some free vars that may get unified. Urgle!
277 Here's another example: is this ambiguous?
278 forall a b. Eq (T b) => a -> a
279 Not if there's an insance decl (with no context)
280 instance Eq (T b) where ...
282 You may say of this example that we should use the instance decl right
283 away, but you can't always do that:
285 class J a b where ...
286 instance J Int b where ...
288 f :: forall a b. J a b => a -> a
290 (Notice: no functional dependency in J's class decl.)
291 Here f's type is perfectly fine, provided f is only called at Int.
292 It's premature to complain when meeting f's signature, or even
293 when inferring a type for f.
297 However, we don't *need* to report ambiguity right away. It'll always
298 show up at the call site.... and eventually at main, which needs special
299 treatment. Nevertheless, reporting ambiguity promptly is an excellent thing.
301 So here's the plan. We WARN about probable ambiguity if
303 fv(Cq) is not a subset of oclose(fv(T) union fv(G), C)
305 (all tested before quantification).
306 That is, all the type variables in Cq must be fixed by the the variables
307 in the environment, or by the variables in the type.
309 Notice that we union before calling oclose. Here's an example:
311 class J a b c | a b -> c
315 forall b c. (J a b c) => b -> b
317 Only if we union {a} from G with {b} from T before using oclose,
318 do we see that c is fixed.
320 It's a bit vague exactly which C we should use for this oclose call. If we
321 don't fix enough variables we might complain when we shouldn't (see
322 the above nasty example). Nothing will be perfect. That's why we can
323 only issue a warning.
326 Can we ever be *certain* about ambiguity? Yes: if there's a constraint
328 c in C such that fv(c) intersect (fv(G) union fv(T)) = EMPTY
330 then c is a "bubble"; there's no way it can ever improve, and it's
331 certainly ambiguous. UNLESS it is a constant (sigh). And what about
336 instance H x y => K (x,y)
338 Is this type ambiguous?
339 forall a b. (K (a,b), Eq b) => a -> a
341 Urk. The (Eq b) looks "definitely ambiguous" but it isn't. What we are after
342 is a "bubble" that's a set of constraints
344 Cq = Ca union Cq' st fv(Ca) intersect (fv(Cq') union fv(T) union fv(G)) = EMPTY
346 Hence another idea. To decide Q start with fv(T) and grow it
347 by transitive closure in Cq (no functional dependencies involved).
348 Now partition Cq using Q, leaving the definitely-ambiguous and probably-ok.
349 The definitely-ambiguous can then float out, and get smashed at top level
350 (which squashes out the constants, like Eq (T a) above)
353 --------------------------------------
354 Notes on principal types
355 --------------------------------------
360 f x = let g y = op (y::Int) in True
362 Here the principal type of f is (forall a. a->a)
363 but we'll produce the non-principal type
364 f :: forall a. C Int => a -> a
367 --------------------------------------
368 The need for forall's in constraints
369 --------------------------------------
371 [Exchange on Haskell Cafe 5/6 Dec 2000]
373 class C t where op :: t -> Bool
374 instance C [t] where op x = True
376 p y = (let f :: c -> Bool; f x = op (y >> return x) in f, y ++ [])
377 q y = (y ++ [], let f :: c -> Bool; f x = op (y >> return x) in f)
379 The definitions of p and q differ only in the order of the components in
380 the pair on their right-hand sides. And yet:
382 ghc and "Typing Haskell in Haskell" reject p, but accept q;
383 Hugs rejects q, but accepts p;
384 hbc rejects both p and q;
385 nhc98 ... (Malcolm, can you fill in the blank for us!).
387 The type signature for f forces context reduction to take place, and
388 the results of this depend on whether or not the type of y is known,
389 which in turn depends on which component of the pair the type checker
392 Solution: if y::m a, float out the constraints
393 Monad m, forall c. C (m c)
394 When m is later unified with [], we can solve both constraints.
397 --------------------------------------
398 Notes on implicit parameters
399 --------------------------------------
401 Question 1: can we "inherit" implicit parameters
402 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
407 where f is *not* a top-level binding.
408 From the RHS of f we'll get the constraint (?y::Int).
409 There are two types we might infer for f:
413 (so we get ?y from the context of f's definition), or
415 f :: (?y::Int) => Int -> Int
417 At first you might think the first was better, becuase then
418 ?y behaves like a free variable of the definition, rather than
419 having to be passed at each call site. But of course, the WHOLE
420 IDEA is that ?y should be passed at each call site (that's what
421 dynamic binding means) so we'd better infer the second.
423 BOTTOM LINE: when *inferring types* you *must* quantify
424 over implicit parameters. See the predicate isFreeWhenInferring.
427 Question 2: type signatures
428 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
429 BUT WATCH OUT: When you supply a type signature, we can't force you
430 to quantify over implicit parameters. For example:
434 This is perfectly reasonable. We do not want to insist on
436 (?x + 1) :: (?x::Int => Int)
438 That would be silly. Here, the definition site *is* the occurrence site,
439 so the above strictures don't apply. Hence the difference between
440 tcSimplifyCheck (which *does* allow implicit paramters to be inherited)
441 and tcSimplifyCheckBind (which does not).
443 What about when you supply a type signature for a binding?
444 Is it legal to give the following explicit, user type
445 signature to f, thus:
450 At first sight this seems reasonable, but it has the nasty property
451 that adding a type signature changes the dynamic semantics.
454 (let f x = (x::Int) + ?y
455 in (f 3, f 3 with ?y=5)) with ?y = 6
461 in (f 3, f 3 with ?y=5)) with ?y = 6
465 Indeed, simply inlining f (at the Haskell source level) would change the
468 Nevertheless, as Launchbury says (email Oct 01) we can't really give the
469 semantics for a Haskell program without knowing its typing, so if you
470 change the typing you may change the semantics.
472 To make things consistent in all cases where we are *checking* against
473 a supplied signature (as opposed to inferring a type), we adopt the
476 a signature does not need to quantify over implicit params.
478 [This represents a (rather marginal) change of policy since GHC 5.02,
479 which *required* an explicit signature to quantify over all implicit
480 params for the reasons mentioned above.]
482 But that raises a new question. Consider
484 Given (signature) ?x::Int
485 Wanted (inferred) ?x::Int, ?y::Bool
487 Clearly we want to discharge the ?x and float the ?y out. But
488 what is the criterion that distinguishes them? Clearly it isn't
489 what free type variables they have. The Right Thing seems to be
490 to float a constraint that
491 neither mentions any of the quantified type variables
492 nor any of the quantified implicit parameters
494 See the predicate isFreeWhenChecking.
497 Question 3: monomorphism
498 ~~~~~~~~~~~~~~~~~~~~~~~~
499 There's a nasty corner case when the monomorphism restriction bites:
503 The argument above suggests that we *must* generalise
504 over the ?y parameter, to get
505 z :: (?y::Int) => Int,
506 but the monomorphism restriction says that we *must not*, giving
508 Why does the momomorphism restriction say this? Because if you have
510 let z = x + ?y in z+z
512 you might not expect the addition to be done twice --- but it will if
513 we follow the argument of Question 2 and generalise over ?y.
516 Question 4: top level
517 ~~~~~~~~~~~~~~~~~~~~~
518 At the top level, monomorhism makes no sense at all.
521 main = let ?x = 5 in print foo
525 woggle :: (?x :: Int) => Int -> Int
528 We definitely don't want (foo :: Int) with a top-level implicit parameter
529 (?x::Int) becuase there is no way to bind it.
534 (A) Always generalise over implicit parameters
535 Bindings that fall under the monomorphism restriction can't
539 * Inlining remains valid
540 * No unexpected loss of sharing
541 * But simple bindings like
543 will be rejected, unless you add an explicit type signature
544 (to avoid the monomorphism restriction)
545 z :: (?y::Int) => Int
547 This seems unacceptable
549 (B) Monomorphism restriction "wins"
550 Bindings that fall under the monomorphism restriction can't
552 Always generalise over implicit parameters *except* for bindings
553 that fall under the monomorphism restriction
556 * Inlining isn't valid in general
557 * No unexpected loss of sharing
558 * Simple bindings like
560 accepted (get value of ?y from binding site)
562 (C) Always generalise over implicit parameters
563 Bindings that fall under the monomorphism restriction can't
564 be generalised, EXCEPT for implicit parameters
566 * Inlining remains valid
567 * Unexpected loss of sharing (from the extra generalisation)
568 * Simple bindings like
570 accepted (get value of ?y from occurrence sites)
575 None of these choices seems very satisfactory. But at least we should
576 decide which we want to do.
578 It's really not clear what is the Right Thing To Do. If you see
582 would you expect the value of ?y to be got from the *occurrence sites*
583 of 'z', or from the valuue of ?y at the *definition* of 'z'? In the
584 case of function definitions, the answer is clearly the former, but
585 less so in the case of non-fucntion definitions. On the other hand,
586 if we say that we get the value of ?y from the definition site of 'z',
587 then inlining 'z' might change the semantics of the program.
589 Choice (C) really says "the monomorphism restriction doesn't apply
590 to implicit parameters". Which is fine, but remember that every
591 innocent binding 'x = ...' that mentions an implicit parameter in
592 the RHS becomes a *function* of that parameter, called at each
593 use of 'x'. Now, the chances are that there are no intervening 'with'
594 clauses that bind ?y, so a decent compiler should common up all
595 those function calls. So I think I strongly favour (C). Indeed,
596 one could make a similar argument for abolishing the monomorphism
597 restriction altogether.
599 BOTTOM LINE: we choose (B) at present. See tcSimplifyRestricted
603 %************************************************************************
605 \subsection{tcSimplifyInfer}
607 %************************************************************************
609 tcSimplify is called when we *inferring* a type. Here's the overall game plan:
611 1. Compute Q = grow( fvs(T), C )
613 2. Partition C based on Q into Ct and Cq. Notice that ambiguous
614 predicates will end up in Ct; we deal with them at the top level
616 3. Try improvement, using functional dependencies
618 4. If Step 3 did any unification, repeat from step 1
619 (Unification can change the result of 'grow'.)
621 Note: we don't reduce dictionaries in step 2. For example, if we have
622 Eq (a,b), we don't simplify to (Eq a, Eq b). So Q won't be different
623 after step 2. However note that we may therefore quantify over more
624 type variables than we absolutely have to.
626 For the guts, we need a loop, that alternates context reduction and
627 improvement with unification. E.g. Suppose we have
629 class C x y | x->y where ...
631 and tcSimplify is called with:
633 Then improvement unifies a with b, giving
636 If we need to unify anything, we rattle round the whole thing all over
643 -> TcTyVarSet -- fv(T); type vars
645 -> TcM ([TcTyVar], -- Tyvars to quantify (zonked)
646 TcDictBinds, -- Bindings
647 [TcId]) -- Dict Ids that must be bound here (zonked)
648 -- Any free (escaping) Insts are tossed into the environment
653 tcSimplifyInfer doc tau_tvs wanted_lie
654 = inferLoop doc (varSetElems tau_tvs)
655 wanted_lie `thenM` \ (qtvs, frees, binds, irreds) ->
657 extendLIEs frees `thenM_`
658 returnM (qtvs, binds, map instToId irreds)
660 inferLoop doc tau_tvs wanteds
662 zonkTcTyVarsAndFV tau_tvs `thenM` \ tau_tvs' ->
663 mappM zonkInst wanteds `thenM` \ wanteds' ->
664 tcGetGlobalTyVars `thenM` \ gbl_tvs ->
666 preds = fdPredsOfInsts wanteds'
667 qtvs = grow preds tau_tvs' `minusVarSet` oclose preds gbl_tvs
670 | isFreeWhenInferring qtvs inst = Free
671 | isClassDict inst = Irred -- Dicts
672 | otherwise = ReduceMe NoSCs -- Lits and Methods
673 env = mkRedEnv doc try_me []
675 traceTc (text "infloop" <+> vcat [ppr tau_tvs', ppr wanteds', ppr preds,
676 ppr (grow preds tau_tvs'), ppr qtvs]) `thenM_`
678 reduceContext env wanteds' `thenM` \ (improved, frees, binds, irreds) ->
682 returnM (varSetElems qtvs, frees, binds, irreds)
684 -- If improvement did some unification, we go round again. There
685 -- are two subtleties:
686 -- a) We start again with irreds, not wanteds
687 -- Using an instance decl might have introduced a fresh type variable
688 -- which might have been unified, so we'd get an infinite loop
689 -- if we started again with wanteds! See example [LOOP]
691 -- b) It's also essential to re-process frees, because unification
692 -- might mean that a type variable that looked free isn't now.
694 -- Hence the (irreds ++ frees)
696 -- However, NOTICE that when we are done, we might have some bindings, but
697 -- the final qtvs might be empty. See [NO TYVARS] below.
699 inferLoop doc tau_tvs (irreds ++ frees) `thenM` \ (qtvs1, frees1, binds1, irreds1) ->
700 returnM (qtvs1, frees1, binds `unionBags` binds1, irreds1)
705 class If b t e r | b t e -> r
708 class Lte a b c | a b -> c where lte :: a -> b -> c
710 instance (Lte a b l,If l b a c) => Max a b c
712 Wanted: Max Z (S x) y
714 Then we'll reduce using the Max instance to:
715 (Lte Z (S x) l, If l (S x) Z y)
716 and improve by binding l->T, after which we can do some reduction
717 on both the Lte and If constraints. What we *can't* do is start again
718 with (Max Z (S x) y)!
722 class Y a b | a -> b where
725 instance Y [[a]] a where
728 k :: X a -> X a -> X a
730 g :: Num a => [X a] -> [X a]
733 h ys = ys ++ map (k (y [[0]])) xs
735 The excitement comes when simplifying the bindings for h. Initially
736 try to simplify {y @ [[t1]] t2, 0 @ t1}, with initial qtvs = {t2}.
737 From this we get t1:=:t2, but also various bindings. We can't forget
738 the bindings (because of [LOOP]), but in fact t1 is what g is
741 The net effect of [NO TYVARS]
744 isFreeWhenInferring :: TyVarSet -> Inst -> Bool
745 isFreeWhenInferring qtvs inst
746 = isFreeWrtTyVars qtvs inst -- Constrains no quantified vars
747 && isInheritableInst inst -- And no implicit parameter involved
748 -- (see "Notes on implicit parameters")
750 {- No longer used (with implication constraints)
751 isFreeWhenChecking :: TyVarSet -- Quantified tyvars
752 -> NameSet -- Quantified implicit parameters
754 isFreeWhenChecking qtvs ips inst
755 = isFreeWrtTyVars qtvs inst
756 && isFreeWrtIPs ips inst
759 isFreeWrtTyVars qtvs inst = tyVarsOfInst inst `disjointVarSet` qtvs
760 isFreeWrtIPs ips inst = not (any (`elemNameSet` ips) (ipNamesOfInst inst))
764 %************************************************************************
766 \subsection{tcSimplifyCheck}
768 %************************************************************************
770 @tcSimplifyCheck@ is used when we know exactly the set of variables
771 we are going to quantify over. For example, a class or instance declaration.
774 -----------------------------------------------------------
775 -- tcSimplifyCheck is used when checking expression type signatures,
776 -- class decls, instance decls etc.
777 tcSimplifyCheck :: InstLoc
778 -> [TcTyVar] -- Quantify over these
781 -> TcM TcDictBinds -- Bindings
782 tcSimplifyCheck loc qtvs givens wanteds
783 = ASSERT( all isSkolemTyVar qtvs )
784 do { (binds, irreds) <- innerCheckLoop loc AddSCs givens wanteds
785 ; implic_bind <- makeImplicationBind loc [] emptyRefinement
787 ; return (binds `unionBags` implic_bind) }
789 -----------------------------------------------------------
790 -- tcSimplifyCheckPat is used for existential pattern match
791 tcSimplifyCheckPat :: InstLoc
792 -> [CoVar] -> Refinement
793 -> [TcTyVar] -- Quantify over these
796 -> TcM TcDictBinds -- Bindings
797 tcSimplifyCheckPat loc co_vars reft qtvs givens wanteds
798 = ASSERT( all isSkolemTyVar qtvs )
799 do { (binds, irreds) <- innerCheckLoop loc AddSCs givens wanteds
800 ; implic_bind <- makeImplicationBind loc co_vars reft
802 ; return (binds `unionBags` implic_bind) }
804 -----------------------------------------------------------
805 makeImplicationBind :: InstLoc -> [CoVar] -> Refinement
806 -> [TcTyVar] -> [Inst] -> [Inst]
808 -- Make a binding that binds 'irreds', by generating an implication
809 -- constraint for them, *and* throwing the constraint into the LIE
810 makeImplicationBind loc co_vars reft qtvs givens irreds
811 = do { let givens' = filter isDict givens
812 -- The givens can include methods
814 -- If there are no 'givens', then it's safe to
815 -- partition the 'wanteds' by their qtvs, thereby trimming irreds
816 -- See Note [Freeness and implications]
817 ; irreds <- if null givens'
819 { let qtv_set = mkVarSet qtvs
820 (frees, real_irreds) = partition (isFreeWrtTyVars qtv_set) irreds
822 ; return real_irreds }
826 -- If there are no irreds, we are done!
827 ; if null irreds then
831 -- Otherwise we must generate a binding
832 -- The binding looks like
833 -- (ir1, .., irn) = f qtvs givens
834 -- where f is (evidence for) the new implication constraint
836 -- This binding must line up the 'rhs' in reduceImplication
839 ; span <- getSrcSpanM
840 ; let all_tvs = qtvs ++ co_vars -- Abstract over all these
841 name = mkInternalName uniq (mkVarOcc "ic") (srcSpanStart span)
842 implic_inst = ImplicInst { tci_name = name, tci_reft = reft,
843 tci_tyvars = all_tvs,
845 tci_wanted = irreds, tci_loc = loc }
847 ; let n_irreds = length irreds
848 irred_ids = map instToId irreds
849 tup_ty = mkTupleTy Boxed n_irreds (map idType irred_ids)
850 pat = TuplePat (map nlVarPat irred_ids) Boxed tup_ty
851 rhs = L span (mkHsWrap co (HsVar (instToId implic_inst)))
852 co = mkWpApps (map instToId givens') <.> mkWpTyApps (mkTyVarTys all_tvs)
853 bind | n_irreds==1 = VarBind (head irred_ids) rhs
854 | otherwise = PatBind { pat_lhs = L span pat,
855 pat_rhs = unguardedGRHSs rhs,
857 bind_fvs = placeHolderNames }
858 ; -- pprTrace "Make implic inst" (ppr implic_inst) $
859 extendLIE implic_inst
860 ; return (unitBag (L span bind)) }}
863 -----------------------------------------------------------
867 [Inst]) -- Irreducible
869 topCheckLoop doc wanteds
870 = checkLoop (mkRedEnv doc try_me []) wanteds
872 try_me inst = ReduceMe AddSCs
874 -----------------------------------------------------------
875 innerCheckLoop :: InstLoc -> WantSCs
879 [Inst]) -- Irreducible
881 innerCheckLoop inst_loc want_scs givens wanteds
882 = checkLoop env wanteds
884 env = mkRedEnv (pprInstLoc inst_loc) try_me givens
886 try_me inst | isMethodOrLit inst = ReduceMe want_scs
888 -- When checking against a given signature
889 -- we MUST be very gentle: Note [Check gently]
894 We have to very careful about not simplifying too vigorously
899 f :: Show b => T b -> b
902 Inside the pattern match, which binds (a:*, x:a), we know that
904 Hence we have a dictionary for Show [a] available; and indeed we
905 need it. We are going to build an implication contraint
906 forall a. (b~[a]) => Show [a]
907 Later, we will solve this constraint using the knowledge (Show b)
909 But we MUST NOT reduce (Show [a]) to (Show a), else the whole
910 thing becomes insoluble. So we simplify gently (get rid of literals
911 and methods only, plus common up equal things), deferring the real
912 work until top level, when we solve the implication constraint
917 -----------------------------------------------------------
921 [Inst]) -- Irreducible
922 -- Precondition: the try_me never returns Free
923 -- givens are completely rigid
925 checkLoop env wanteds
926 = do { -- Givens are skolems, so no need to zonk them
927 wanteds' <- mappM zonkInst wanteds
929 ; (improved, _frees, binds, irreds) <- reduceContext env wanteds'
931 ; ASSERT( null _frees )
934 return (binds, irreds)
937 { (binds1, irreds1) <- checkLoop env irreds
938 ; return (binds `unionBags` binds1, irreds1) } }
943 -----------------------------------------------------------
944 -- tcSimplifyInferCheck is used when we know the constraints we are to simplify
945 -- against, but we don't know the type variables over which we are going to quantify.
946 -- This happens when we have a type signature for a mutually recursive group
949 -> TcTyVarSet -- fv(T)
952 -> TcM ([TcTyVar], -- Variables over which to quantify
953 TcDictBinds) -- Bindings
955 tcSimplifyInferCheck loc tau_tvs givens wanteds
956 = do { (binds, irreds) <- innerCheckLoop loc AddSCs givens wanteds
958 -- Figure out which type variables to quantify over
959 -- You might think it should just be the signature tyvars,
960 -- but in bizarre cases you can get extra ones
961 -- f :: forall a. Num a => a -> a
962 -- f x = fst (g (x, head [])) + 1
964 -- Here we infer g :: forall a b. a -> b -> (b,a)
965 -- We don't want g to be monomorphic in b just because
966 -- f isn't quantified over b.
967 ; let all_tvs = varSetElems (tau_tvs `unionVarSet` tyVarsOfInsts givens)
968 ; all_tvs <- zonkTcTyVarsAndFV all_tvs
969 ; gbl_tvs <- tcGetGlobalTyVars
970 ; let qtvs = varSetElems (all_tvs `minusVarSet` gbl_tvs)
971 -- We could close gbl_tvs, but its not necessary for
972 -- soundness, and it'll only affect which tyvars, not which
973 -- dictionaries, we quantify over
975 -- Now we are back to normal (c.f. tcSimplCheck)
976 ; implic_bind <- makeImplicationBind loc [] emptyRefinement
978 ; return (qtvs, binds `unionBags` implic_bind) }
982 %************************************************************************
984 tcSimplifySuperClasses
986 %************************************************************************
988 Note [SUPERCLASS-LOOP 1]
989 ~~~~~~~~~~~~~~~~~~~~~~~~
990 We have to be very, very careful when generating superclasses, lest we
991 accidentally build a loop. Here's an example:
995 class S a => C a where { opc :: a -> a }
996 class S b => D b where { opd :: b -> b }
1001 instance D Int where
1004 From (instance C Int) we get the constraint set {ds1:S Int, dd:D Int}
1005 Simplifying, we may well get:
1006 $dfCInt = :C ds1 (opd dd)
1009 Notice that we spot that we can extract ds1 from dd.
1011 Alas! Alack! We can do the same for (instance D Int):
1013 $dfDInt = :D ds2 (opc dc)
1017 And now we've defined the superclass in terms of itself.
1019 Solution: never generate a superclass selectors at all when
1020 satisfying the superclass context of an instance declaration.
1022 Two more nasty cases are in
1027 tcSimplifySuperClasses
1032 tcSimplifySuperClasses loc givens sc_wanteds
1033 = do { (binds1, irreds) <- checkLoop env sc_wanteds
1034 ; let (tidy_env, tidy_irreds) = tidyInsts irreds
1035 ; reportNoInstances tidy_env (Just (loc, givens)) tidy_irreds
1038 env = mkRedEnv (pprInstLoc loc) try_me givens
1039 try_me inst = ReduceMe NoSCs
1040 -- Like topCheckLoop, but with NoSCs
1044 %************************************************************************
1046 \subsection{tcSimplifyRestricted}
1048 %************************************************************************
1050 tcSimplifyRestricted infers which type variables to quantify for a
1051 group of restricted bindings. This isn't trivial.
1054 We want to quantify over a to get id :: forall a. a->a
1057 We do not want to quantify over a, because there's an Eq a
1058 constraint, so we get eq :: a->a->Bool (notice no forall)
1061 RHS has type 'tau', whose free tyvars are tau_tvs
1062 RHS has constraints 'wanteds'
1065 Quantify over (tau_tvs \ ftvs(wanteds))
1066 This is bad. The constraints may contain (Monad (ST s))
1067 where we have instance Monad (ST s) where...
1068 so there's no need to be monomorphic in s!
1070 Also the constraint might be a method constraint,
1071 whose type mentions a perfectly innocent tyvar:
1072 op :: Num a => a -> b -> a
1073 Here, b is unconstrained. A good example would be
1075 We want to infer the polymorphic type
1076 foo :: forall b. b -> b
1079 Plan B (cunning, used for a long time up to and including GHC 6.2)
1080 Step 1: Simplify the constraints as much as possible (to deal
1081 with Plan A's problem). Then set
1082 qtvs = tau_tvs \ ftvs( simplify( wanteds ) )
1084 Step 2: Now simplify again, treating the constraint as 'free' if
1085 it does not mention qtvs, and trying to reduce it otherwise.
1086 The reasons for this is to maximise sharing.
1088 This fails for a very subtle reason. Suppose that in the Step 2
1089 a constraint (Foo (Succ Zero) (Succ Zero) b) gets thrown upstairs as 'free'.
1090 In the Step 1 this constraint might have been simplified, perhaps to
1091 (Foo Zero Zero b), AND THEN THAT MIGHT BE IMPROVED, to bind 'b' to 'T'.
1092 This won't happen in Step 2... but that in turn might prevent some other
1093 constraint (Baz [a] b) being simplified (e.g. via instance Baz [a] T where {..})
1094 and that in turn breaks the invariant that no constraints are quantified over.
1096 Test typecheck/should_compile/tc177 (which failed in GHC 6.2) demonstrates
1101 Step 1: Simplify the constraints as much as possible (to deal
1102 with Plan A's problem). Then set
1103 qtvs = tau_tvs \ ftvs( simplify( wanteds ) )
1104 Return the bindings from Step 1.
1107 A note about Plan C (arising from "bug" reported by George Russel March 2004)
1110 instance (HasBinary ty IO) => HasCodedValue ty
1112 foo :: HasCodedValue a => String -> IO a
1114 doDecodeIO :: HasCodedValue a => () -> () -> IO a
1115 doDecodeIO codedValue view
1116 = let { act = foo "foo" } in act
1118 You might think this should work becuase the call to foo gives rise to a constraint
1119 (HasCodedValue t), which can be satisfied by the type sig for doDecodeIO. But the
1120 restricted binding act = ... calls tcSimplifyRestricted, and PlanC simplifies the
1121 constraint using the (rather bogus) instance declaration, and now we are stuffed.
1123 I claim this is not really a bug -- but it bit Sergey as well as George. So here's
1127 Plan D (a variant of plan B)
1128 Step 1: Simplify the constraints as much as possible (to deal
1129 with Plan A's problem), BUT DO NO IMPROVEMENT. Then set
1130 qtvs = tau_tvs \ ftvs( simplify( wanteds ) )
1132 Step 2: Now simplify again, treating the constraint as 'free' if
1133 it does not mention qtvs, and trying to reduce it otherwise.
1135 The point here is that it's generally OK to have too few qtvs; that is,
1136 to make the thing more monomorphic than it could be. We don't want to
1137 do that in the common cases, but in wierd cases it's ok: the programmer
1138 can always add a signature.
1140 Too few qtvs => too many wanteds, which is what happens if you do less
1145 tcSimplifyRestricted -- Used for restricted binding groups
1146 -- i.e. ones subject to the monomorphism restriction
1149 -> [Name] -- Things bound in this group
1150 -> TcTyVarSet -- Free in the type of the RHSs
1151 -> [Inst] -- Free in the RHSs
1152 -> TcM ([TcTyVar], -- Tyvars to quantify (zonked)
1153 TcDictBinds) -- Bindings
1154 -- tcSimpifyRestricted returns no constraints to
1155 -- quantify over; by definition there are none.
1156 -- They are all thrown back in the LIE
1158 tcSimplifyRestricted doc top_lvl bndrs tau_tvs wanteds
1159 -- Zonk everything in sight
1160 = mappM zonkInst wanteds `thenM` \ wanteds' ->
1162 -- 'reduceMe': Reduce as far as we can. Don't stop at
1163 -- dicts; the idea is to get rid of as many type
1164 -- variables as possible, and we don't want to stop
1165 -- at (say) Monad (ST s), because that reduces
1166 -- immediately, with no constraint on s.
1168 -- BUT do no improvement! See Plan D above
1169 -- HOWEVER, some unification may take place, if we instantiate
1170 -- a method Inst with an equality constraint
1171 let env = mkNoImproveRedEnv doc reduceMe
1173 reduceContext env wanteds' `thenM` \ (_imp, _frees, _binds, constrained_dicts) ->
1175 -- Next, figure out the tyvars we will quantify over
1176 zonkTcTyVarsAndFV (varSetElems tau_tvs) `thenM` \ tau_tvs' ->
1177 tcGetGlobalTyVars `thenM` \ gbl_tvs' ->
1178 mappM zonkInst constrained_dicts `thenM` \ constrained_dicts' ->
1180 constrained_tvs' = tyVarsOfInsts constrained_dicts'
1181 qtvs' = (tau_tvs' `minusVarSet` oclose (fdPredsOfInsts constrained_dicts) gbl_tvs')
1182 `minusVarSet` constrained_tvs'
1184 traceTc (text "tcSimplifyRestricted" <+> vcat [
1185 pprInsts wanteds, pprInsts _frees, pprInsts constrained_dicts',
1187 ppr constrained_tvs', ppr tau_tvs', ppr qtvs' ]) `thenM_`
1189 -- The first step may have squashed more methods than
1190 -- necessary, so try again, this time more gently, knowing the exact
1191 -- set of type variables to quantify over.
1193 -- We quantify only over constraints that are captured by qtvs';
1194 -- these will just be a subset of non-dicts. This in contrast
1195 -- to normal inference (using isFreeWhenInferring) in which we quantify over
1196 -- all *non-inheritable* constraints too. This implements choice
1197 -- (B) under "implicit parameter and monomorphism" above.
1199 -- Remember that we may need to do *some* simplification, to
1200 -- (for example) squash {Monad (ST s)} into {}. It's not enough
1201 -- just to float all constraints
1203 -- At top level, we *do* squash methods becuase we want to
1204 -- expose implicit parameters to the test that follows
1206 is_nested_group = isNotTopLevel top_lvl
1207 try_me inst | isFreeWrtTyVars qtvs' inst,
1208 (is_nested_group || isDict inst) = Free
1209 | otherwise = ReduceMe AddSCs
1210 env = mkNoImproveRedEnv doc try_me
1212 reduceContext env wanteds' `thenM` \ (_imp, frees, binds, irreds) ->
1213 ASSERT( null irreds )
1215 -- See "Notes on implicit parameters, Question 4: top level"
1216 if is_nested_group then
1217 extendLIEs frees `thenM_`
1218 returnM (varSetElems qtvs', binds)
1221 (non_ips, bad_ips) = partition isClassDict frees
1223 addTopIPErrs bndrs bad_ips `thenM_`
1224 extendLIEs non_ips `thenM_`
1225 returnM (varSetElems qtvs', binds)
1229 %************************************************************************
1233 %************************************************************************
1235 On the LHS of transformation rules we only simplify methods and constants,
1236 getting dictionaries. We want to keep all of them unsimplified, to serve
1237 as the available stuff for the RHS of the rule.
1239 Example. Consider the following left-hand side of a rule
1241 f (x == y) (y > z) = ...
1243 If we typecheck this expression we get constraints
1245 d1 :: Ord a, d2 :: Eq a
1247 We do NOT want to "simplify" to the LHS
1249 forall x::a, y::a, z::a, d1::Ord a.
1250 f ((==) (eqFromOrd d1) x y) ((>) d1 y z) = ...
1254 forall x::a, y::a, z::a, d1::Ord a, d2::Eq a.
1255 f ((==) d2 x y) ((>) d1 y z) = ...
1257 Here is another example:
1259 fromIntegral :: (Integral a, Num b) => a -> b
1260 {-# RULES "foo" fromIntegral = id :: Int -> Int #-}
1262 In the rule, a=b=Int, and Num Int is a superclass of Integral Int. But
1263 we *dont* want to get
1265 forall dIntegralInt.
1266 fromIntegral Int Int dIntegralInt (scsel dIntegralInt) = id Int
1268 because the scsel will mess up RULE matching. Instead we want
1270 forall dIntegralInt, dNumInt.
1271 fromIntegral Int Int dIntegralInt dNumInt = id Int
1275 g (x == y) (y == z) = ..
1277 where the two dictionaries are *identical*, we do NOT WANT
1279 forall x::a, y::a, z::a, d1::Eq a
1280 f ((==) d1 x y) ((>) d1 y z) = ...
1282 because that will only match if the dict args are (visibly) equal.
1283 Instead we want to quantify over the dictionaries separately.
1285 In short, tcSimplifyRuleLhs must *only* squash LitInst and MethInts, leaving
1286 all dicts unchanged, with absolutely no sharing. It's simpler to do this
1287 from scratch, rather than further parameterise simpleReduceLoop etc
1290 tcSimplifyRuleLhs :: [Inst] -> TcM ([Inst], TcDictBinds)
1291 tcSimplifyRuleLhs wanteds
1292 = go [] emptyBag wanteds
1295 = return (dicts, binds)
1296 go dicts binds (w:ws)
1298 = go (w:dicts) binds ws
1300 = do { w' <- zonkInst w -- So that (3::Int) does not generate a call
1301 -- to fromInteger; this looks fragile to me
1302 ; lookup_result <- lookupSimpleInst w'
1303 ; case lookup_result of
1304 GenInst ws' rhs -> go dicts (addBind binds w rhs) (ws' ++ ws)
1305 NoInstance -> pprPanic "tcSimplifyRuleLhs" (ppr w)
1309 tcSimplifyBracket is used when simplifying the constraints arising from
1310 a Template Haskell bracket [| ... |]. We want to check that there aren't
1311 any constraints that can't be satisfied (e.g. Show Foo, where Foo has no
1312 Show instance), but we aren't otherwise interested in the results.
1313 Nor do we care about ambiguous dictionaries etc. We will type check
1314 this bracket again at its usage site.
1317 tcSimplifyBracket :: [Inst] -> TcM ()
1318 tcSimplifyBracket wanteds
1319 = do { topCheckLoop doc wanteds
1322 doc = text "tcSimplifyBracket"
1326 %************************************************************************
1328 \subsection{Filtering at a dynamic binding}
1330 %************************************************************************
1335 we must discharge all the ?x constraints from B. We also do an improvement
1336 step; if we have ?x::t1 and ?x::t2 we must unify t1, t2.
1338 Actually, the constraints from B might improve the types in ?x. For example
1340 f :: (?x::Int) => Char -> Char
1343 then the constraint (?x::Int) arising from the call to f will
1344 force the binding for ?x to be of type Int.
1347 tcSimplifyIPs :: [Inst] -- The implicit parameters bound here
1350 -- We need a loop so that we do improvement, and then
1351 -- (next time round) generate a binding to connect the two
1353 -- Here the two ?x's have different types, and improvement
1354 -- makes them the same.
1356 tcSimplifyIPs given_ips wanteds
1357 = do { wanteds' <- mappM zonkInst wanteds
1358 ; given_ips' <- mappM zonkInst given_ips
1359 -- Unusually for checking, we *must* zonk the given_ips
1361 ; let env = mkRedEnv doc try_me given_ips'
1362 ; (improved, _frees, binds, irreds) <- reduceContext env wanteds'
1364 ; if not improved then
1365 ASSERT( all is_free irreds )
1366 do { extendLIEs irreds
1369 tcSimplifyIPs given_ips wanteds }
1371 doc = text "tcSimplifyIPs" <+> ppr given_ips
1372 ip_set = mkNameSet (ipNamesOfInsts given_ips)
1373 is_free inst = isFreeWrtIPs ip_set inst
1375 -- Simplify any methods that mention the implicit parameter
1376 try_me inst | is_free inst = Irred
1377 | otherwise = ReduceMe NoSCs
1381 %************************************************************************
1383 \subsection[binds-for-local-funs]{@bindInstsOfLocalFuns@}
1385 %************************************************************************
1387 When doing a binding group, we may have @Insts@ of local functions.
1388 For example, we might have...
1390 let f x = x + 1 -- orig local function (overloaded)
1391 f.1 = f Int -- two instances of f
1396 The point is: we must drop the bindings for @f.1@ and @f.2@ here,
1397 where @f@ is in scope; those @Insts@ must certainly not be passed
1398 upwards towards the top-level. If the @Insts@ were binding-ified up
1399 there, they would have unresolvable references to @f@.
1401 We pass in an @init_lie@ of @Insts@ and a list of locally-bound @Ids@.
1402 For each method @Inst@ in the @init_lie@ that mentions one of the
1403 @Ids@, we create a binding. We return the remaining @Insts@ (in an
1404 @LIE@), as well as the @HsBinds@ generated.
1407 bindInstsOfLocalFuns :: [Inst] -> [TcId] -> TcM TcDictBinds
1408 -- Simlifies only MethodInsts, and generate only bindings of form
1410 -- We're careful not to even generate bindings of the form
1412 -- You'd think that'd be fine, but it interacts with what is
1413 -- arguably a bug in Match.tidyEqnInfo (see notes there)
1415 bindInstsOfLocalFuns wanteds local_ids
1416 | null overloaded_ids
1418 = extendLIEs wanteds `thenM_`
1419 returnM emptyLHsBinds
1422 = do { (binds, irreds) <- checkLoop env for_me
1423 ; extendLIEs not_for_me
1427 env = mkRedEnv doc try_me []
1428 doc = text "bindInsts" <+> ppr local_ids
1429 overloaded_ids = filter is_overloaded local_ids
1430 is_overloaded id = isOverloadedTy (idType id)
1431 (for_me, not_for_me) = partition (isMethodFor overloaded_set) wanteds
1433 overloaded_set = mkVarSet overloaded_ids -- There can occasionally be a lot of them
1434 -- so it's worth building a set, so that
1435 -- lookup (in isMethodFor) is faster
1436 try_me inst | isMethod inst = ReduceMe NoSCs
1441 %************************************************************************
1443 \subsection{Data types for the reduction mechanism}
1445 %************************************************************************
1447 The main control over context reduction is here
1451 = RedEnv { red_doc :: SDoc -- The context
1452 , red_try_me :: Inst -> WhatToDo
1453 , red_improve :: Bool -- True <=> do improvement
1454 , red_givens :: [Inst] -- All guaranteed rigid
1456 -- but see Note [Rigidity]
1457 , red_stack :: (Int, [Inst]) -- Recursion stack (for err msg)
1458 -- See Note [RedStack]
1462 -- The red_givens are rigid so far as cmpInst is concerned.
1463 -- There is one case where they are not totally rigid, namely in tcSimplifyIPs
1464 -- let ?x = e in ...
1465 -- Here, the given is (?x::a), where 'a' is not necy a rigid type
1466 -- But that doesn't affect the comparison, which is based only on mame.
1469 -- The red_stack pair (n,insts) pair is just used for error reporting.
1470 -- 'n' is always the depth of the stack.
1471 -- The 'insts' is the stack of Insts being reduced: to produce X
1472 -- I had to produce Y, to produce Y I had to produce Z, and so on.
1475 mkRedEnv :: SDoc -> (Inst -> WhatToDo) -> [Inst] -> RedEnv
1476 mkRedEnv doc try_me givens
1477 = RedEnv { red_doc = doc, red_try_me = try_me,
1478 red_givens = givens, red_stack = (0,[]),
1479 red_improve = True }
1481 mkNoImproveRedEnv :: SDoc -> (Inst -> WhatToDo) -> RedEnv
1482 -- Do not do improvement; no givens
1483 mkNoImproveRedEnv doc try_me
1484 = RedEnv { red_doc = doc, red_try_me = try_me,
1485 red_givens = [], red_stack = (0,[]),
1486 red_improve = True }
1489 = ReduceMe WantSCs -- Try to reduce this
1490 -- If there's no instance, add the inst to the
1491 -- irreductible ones, but don't produce an error
1492 -- message of any kind.
1493 -- It might be quite legitimate such as (Eq a)!
1495 | Irred -- Return as irreducible unless it can
1496 -- be reduced to a constant in one step
1498 | Free -- Return as free
1500 reduceMe :: Inst -> WhatToDo
1501 reduceMe inst = ReduceMe AddSCs
1503 data WantSCs = NoSCs | AddSCs -- Tells whether we should add the superclasses
1504 -- of a predicate when adding it to the avails
1505 -- The reason for this flag is entirely the super-class loop problem
1506 -- Note [SUPER-CLASS LOOP 1]
1509 %************************************************************************
1511 \subsection[reduce]{@reduce@}
1513 %************************************************************************
1517 reduceContext :: RedEnv
1519 -> TcM (ImprovementDone,
1521 TcDictBinds, -- Dictionary bindings
1522 [Inst]) -- Irreducible
1524 reduceContext env wanteds
1525 = do { traceTc (text "reduceContext" <+> (vcat [
1526 text "----------------------",
1528 text "given" <+> ppr (red_givens env),
1529 text "wanted" <+> ppr wanteds,
1530 text "----------------------"
1533 -- Build the Avail mapping from "givens"
1534 ; init_state <- foldlM addGiven emptyAvails (red_givens env)
1537 ; avails <- reduceList env wanteds init_state
1539 ; let improved = availsImproved avails
1540 ; (binds, irreds, frees) <- extractResults avails wanteds
1542 ; traceTc (text "reduceContext end" <+> (vcat [
1543 text "----------------------",
1545 text "given" <+> ppr (red_givens env),
1546 text "wanted" <+> ppr wanteds,
1548 text "avails" <+> pprAvails avails,
1549 text "frees" <+> ppr frees,
1550 text "improved =" <+> ppr improved,
1551 text "----------------------"
1554 ; return (improved, frees, binds, irreds) }
1556 tcImproveOne :: Avails -> Inst -> TcM ImprovementDone
1557 tcImproveOne avails inst
1558 | not (isDict inst) = return False
1560 = do { inst_envs <- tcGetInstEnvs
1561 ; let eqns = improveOne (classInstances inst_envs)
1562 (dictPred inst, pprInstArising inst)
1563 [ (dictPred p, pprInstArising p)
1564 | p <- availsInsts avails, isDict p ]
1565 -- Avails has all the superclasses etc (good)
1566 -- It also has all the intermediates of the deduction (good)
1567 -- It does not have duplicates (good)
1568 -- NB that (?x::t1) and (?x::t2) will be held separately in avails
1569 -- so that improve will see them separate
1570 ; traceTc (text "improveOne" <+> ppr inst)
1573 unifyEqns :: [(Equation,(PredType,SDoc),(PredType,SDoc))]
1574 -> TcM ImprovementDone
1575 unifyEqns [] = return False
1577 = do { traceTc (ptext SLIT("Improve:") <+> vcat (map pprEquationDoc eqns))
1581 unify ((qtvs, pairs), what1, what2)
1582 = addErrCtxtM (mkEqnMsg what1 what2) $
1583 tcInstTyVars (varSetElems qtvs) `thenM` \ (_, _, tenv) ->
1584 mapM_ (unif_pr tenv) pairs
1585 unif_pr tenv (ty1,ty2) = unifyType (substTy tenv ty1) (substTy tenv ty2)
1587 pprEquationDoc (eqn, (p1,w1), (p2,w2)) = vcat [pprEquation eqn, nest 2 (ppr p1), nest 2 (ppr p2)]
1589 mkEqnMsg (pred1,from1) (pred2,from2) tidy_env
1590 = do { pred1' <- zonkTcPredType pred1; pred2' <- zonkTcPredType pred2
1591 ; let { pred1'' = tidyPred tidy_env pred1'; pred2'' = tidyPred tidy_env pred2' }
1592 ; let msg = vcat [ptext SLIT("When using functional dependencies to combine"),
1593 nest 2 (sep [ppr pred1'' <> comma, nest 2 from1]),
1594 nest 2 (sep [ppr pred2'' <> comma, nest 2 from2])]
1595 ; return (tidy_env, msg) }
1598 The main context-reduction function is @reduce@. Here's its game plan.
1601 reduceList :: RedEnv -> [Inst] -> Avails -> TcM Avails
1602 reduceList env@(RedEnv {red_stack = (n,stk)}) wanteds state
1603 = do { dopts <- getDOpts
1606 dumpTcRn (hang (ptext SLIT("Interesting! Context reduction stack depth") <+> int n)
1607 2 (ifPprDebug (nest 2 (pprStack stk))))
1610 ; if n >= ctxtStkDepth dopts then
1611 failWithTc (reduceDepthErr n stk)
1615 go [] state = return state
1616 go (w:ws) state = do { state' <- reduce (env {red_stack = (n+1, w:stk)}) w state
1619 -- Base case: we're done!
1620 reduce env wanted avails
1621 -- It's the same as an existing inst, or a superclass thereof
1622 | Just avail <- findAvail avails wanted
1626 = case red_try_me env wanted of {
1627 Free -> try_simple addFree -- It's free so just chuck it upstairs
1628 ; Irred -> try_simple (addIrred AddSCs) -- Assume want superclasses
1630 ; ReduceMe want_scs -> -- It should be reduced
1631 reduceInst env avails wanted `thenM` \ (avails, lookup_result) ->
1632 case lookup_result of
1633 NoInstance -> -- No such instance!
1634 -- Add it and its superclasses
1635 addIrred want_scs avails wanted
1637 GenInst [] rhs -> addWanted want_scs avails wanted rhs []
1639 GenInst wanteds' rhs -> do { avails1 <- addIrred NoSCs avails wanted
1640 ; avails2 <- reduceList env wanteds' avails1
1641 ; addWanted want_scs avails2 wanted rhs wanteds' }
1642 -- Temporarily do addIrred *before* the reduceList,
1643 -- which has the effect of adding the thing we are trying
1644 -- to prove to the database before trying to prove the things it
1645 -- needs. See note [RECURSIVE DICTIONARIES]
1646 -- NB: we must not do an addWanted before, because that adds the
1647 -- superclasses too, and thaat can lead to a spurious loop; see
1648 -- the examples in [SUPERCLASS-LOOP]
1649 -- So we do an addIrred before, and then overwrite it afterwards with addWanted
1653 -- First, see if the inst can be reduced to a constant in one step
1654 -- Works well for literals (1::Int) and constant dictionaries (d::Num Int)
1655 -- Don't bother for implication constraints, which take real work
1656 try_simple do_this_otherwise
1657 = do { res <- lookupSimpleInst wanted
1659 GenInst [] rhs -> addWanted AddSCs avails wanted rhs []
1660 other -> do_this_otherwise avails wanted }
1664 Note [SUPERCLASS-LOOP 2]
1665 ~~~~~~~~~~~~~~~~~~~~~~~~
1666 But the above isn't enough. Suppose we are *given* d1:Ord a,
1667 and want to deduce (d2:C [a]) where
1669 class Ord a => C a where
1670 instance Ord [a] => C [a] where ...
1672 Then we'll use the instance decl to deduce C [a] from Ord [a], and then add the
1673 superclasses of C [a] to avails. But we must not overwrite the binding
1674 for Ord [a] (which is obtained from Ord a) with a superclass selection or we'll just
1677 Here's another variant, immortalised in tcrun020
1678 class Monad m => C1 m
1679 class C1 m => C2 m x
1680 instance C2 Maybe Bool
1681 For the instance decl we need to build (C1 Maybe), and it's no good if
1682 we run around and add (C2 Maybe Bool) and its superclasses to the avails
1683 before we search for C1 Maybe.
1685 Here's another example
1686 class Eq b => Foo a b
1687 instance Eq a => Foo [a] a
1691 we'll first deduce that it holds (via the instance decl). We must not
1692 then overwrite the Eq t constraint with a superclass selection!
1694 At first I had a gross hack, whereby I simply did not add superclass constraints
1695 in addWanted, though I did for addGiven and addIrred. This was sub-optimal,
1696 becuase it lost legitimate superclass sharing, and it still didn't do the job:
1697 I found a very obscure program (now tcrun021) in which improvement meant the
1698 simplifier got two bites a the cherry... so something seemed to be an Irred
1699 first time, but reducible next time.
1701 Now we implement the Right Solution, which is to check for loops directly
1702 when adding superclasses. It's a bit like the occurs check in unification.
1705 Note [RECURSIVE DICTIONARIES]
1706 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1708 data D r = ZeroD | SuccD (r (D r));
1710 instance (Eq (r (D r))) => Eq (D r) where
1711 ZeroD == ZeroD = True
1712 (SuccD a) == (SuccD b) = a == b
1715 equalDC :: D [] -> D [] -> Bool;
1718 We need to prove (Eq (D [])). Here's how we go:
1722 by instance decl, holds if
1726 by instance decl of Eq, holds if
1728 where d2 = dfEqList d3
1731 But now we can "tie the knot" to give
1737 and it'll even run! The trick is to put the thing we are trying to prove
1738 (in this case Eq (D []) into the database before trying to prove its
1739 contributing clauses.
1742 %************************************************************************
1744 Reducing a single constraint
1746 %************************************************************************
1749 ---------------------------------------------
1750 reduceInst :: RedEnv -> Avails -> Inst -> TcM (Avails, LookupInstResult)
1751 reduceInst env avails (ImplicInst { tci_tyvars = tvs, tci_reft = reft, tci_loc = loc,
1752 tci_given = extra_givens, tci_wanted = wanteds })
1753 = reduceImplication env avails reft tvs extra_givens wanteds loc
1755 reduceInst env avails other_inst
1756 = do { result <- lookupSimpleInst other_inst
1757 ; return (avails, result) }
1761 ---------------------------------------------
1762 reduceImplication :: RedEnv
1764 -> Refinement -- May refine the givens; often empty
1765 -> [TcTyVar] -- Quantified type variables; all skolems
1766 -> [Inst] -- Extra givens; all rigid
1769 -> TcM (Avails, LookupInstResult)
1772 Suppose we are simplifying the constraint
1773 forall bs. extras => wanted
1774 in the context of an overall simplification problem with givens 'givens',
1775 and refinment 'reft'.
1778 * The refinement is often empty
1780 * The 'extra givens' need not mention any of the quantified type variables
1781 e.g. forall {}. Eq a => Eq [a]
1782 forall {}. C Int => D (Tree Int)
1784 This happens when you have something like
1786 T1 :: Eq a => a -> T a
1789 f x = ...(case x of { T1 v -> v==v })...
1792 -- ToDo: should we instantiate tvs? I think it's not necessary
1794 -- ToDo: what about improvement? There may be some improvement
1795 -- exposed as a result of the simplifications done by reduceList
1796 -- which are discarded if we back off.
1797 -- This is almost certainly Wrong, but we'll fix it when dealing
1798 -- better with equality constraints
1799 reduceImplication env orig_avails reft tvs extra_givens wanteds inst_loc
1800 = do { -- Add refined givens, and the extra givens
1801 (refined_red_givens, avails)
1802 <- if isEmptyRefinement reft then return (red_givens env, orig_avails)
1803 else foldlM (addRefinedGiven reft) ([], orig_avails) (red_givens env)
1804 ; avails <- foldlM addGiven avails extra_givens
1806 -- Solve the sub-problem
1807 ; let try_me inst = ReduceMe AddSCs -- Note [Freeness and implications]
1808 env' = env { red_givens = refined_red_givens ++ extra_givens
1809 , red_try_me = try_me }
1811 ; traceTc (text "reduceImplication" <+> vcat
1812 [ ppr (red_givens env), ppr extra_givens, ppr reft, ppr wanteds ])
1813 ; avails <- reduceList env' wanteds avails
1815 -- Extract the binding
1816 ; (binds, irreds, _frees) <- extractResults avails wanteds
1817 -- No frees, because try_me never says Free
1819 ; let dict_ids = map instToId extra_givens
1820 co = mkWpTyLams tvs <.> mkWpLams dict_ids <.> WpLet binds
1821 rhs = mkHsWrap co payload
1822 loc = instLocSpan inst_loc
1823 payload | isSingleton wanteds = HsVar (instToId (head wanteds))
1824 | otherwise = ExplicitTuple (map (L loc . HsVar . instToId) wanteds) Boxed
1826 -- If there are any irreds, we back off and return NoInstance
1827 -- Either way, we discard the extra avails we've generated;
1828 -- but we remember if we have done any (global) improvement
1829 ; let ret_avails = updateImprovement orig_avails avails
1831 [] -> return (ret_avails, GenInst [] (L loc rhs))
1832 other -> return (ret_avails, NoInstance)
1836 Note [Freeness and implications]
1837 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1838 It's hard to say when an implication constraint can be floated out. Consider
1839 forall {} Eq a => Foo [a]
1840 The (Foo [a]) doesn't mention any of the quantified variables, but it
1841 still might be partially satisfied by the (Eq a).
1843 There is a useful special case when it *is* easy to partition the
1844 constraints, namely when there are no 'givens'. Consider
1845 forall {a}. () => Bar b
1846 There are no 'givens', and so there is no reason to capture (Bar b).
1847 We can let it float out. But if there is even one constraint we
1848 must be much more careful:
1849 forall {a}. C a b => Bar (m b)
1850 because (C a b) might have a superclass (D b), from which we might
1851 deduce (Bar [b]) when m later gets instantiated to []. Ha!
1853 Here is an even more exotic example
1855 Now consider the constraint
1856 forall b. D Int b => C Int
1857 We can satisfy the (C Int) from the superclass of D, so we don't want
1858 to float the (C Int) out, even though it mentions no type variable in
1861 %************************************************************************
1863 Avails and AvailHow: the pool of evidence
1865 %************************************************************************
1869 data Avails = Avails !ImprovementDone !AvailEnv
1871 type ImprovementDone = Bool -- True <=> some unification has happened
1872 -- so some Irreds might now be reducible
1873 -- keys that are now
1875 type AvailEnv = FiniteMap Inst AvailHow
1877 = IsFree -- Used for free Insts
1878 | IsIrred -- Used for irreducible dictionaries,
1879 -- which are going to be lambda bound
1881 | Given TcId -- Used for dictionaries for which we have a binding
1882 -- e.g. those "given" in a signature
1884 | Rhs -- Used when there is a RHS
1885 (LHsExpr TcId) -- The RHS
1886 [Inst] -- Insts free in the RHS; we need these too
1888 instance Outputable Avails where
1891 pprAvails (Avails imp avails)
1892 = vcat [ ptext SLIT("Avails") <> (if imp then ptext SLIT("[improved]") else empty)
1893 , nest 2 (vcat [sep [ppr inst, nest 2 (equals <+> ppr avail)]
1894 | (inst,avail) <- fmToList avails ])]
1896 instance Outputable AvailHow where
1899 -------------------------
1900 pprAvail :: AvailHow -> SDoc
1901 pprAvail IsFree = text "Free"
1902 pprAvail IsIrred = text "Irred"
1903 pprAvail (Given x) = text "Given" <+> ppr x
1904 pprAvail (Rhs rhs bs) = text "Rhs" <+> ppr rhs <+> braces (ppr bs)
1906 -------------------------
1907 extendAvailEnv :: AvailEnv -> Inst -> AvailHow -> AvailEnv
1908 extendAvailEnv env inst avail = addToFM env inst avail
1910 findAvailEnv :: AvailEnv -> Inst -> Maybe AvailHow
1911 findAvailEnv env wanted = lookupFM env wanted
1912 -- NB 1: the Ord instance of Inst compares by the class/type info
1913 -- *not* by unique. So
1914 -- d1::C Int == d2::C Int
1916 emptyAvails :: Avails
1917 emptyAvails = Avails False emptyFM
1919 findAvail :: Avails -> Inst -> Maybe AvailHow
1920 findAvail (Avails _ avails) wanted = findAvailEnv avails wanted
1922 elemAvails :: Inst -> Avails -> Bool
1923 elemAvails wanted (Avails _ avails) = wanted `elemFM` avails
1925 extendAvails :: Avails -> Inst -> AvailHow -> TcM Avails
1927 extendAvails avails@(Avails imp env) inst avail
1928 = do { imp1 <- tcImproveOne avails inst -- Do any improvement
1929 ; return (Avails (imp || imp1) (extendAvailEnv env inst avail)) }
1931 availsInsts :: Avails -> [Inst]
1932 availsInsts (Avails _ avails) = keysFM avails
1934 availsImproved (Avails imp _) = imp
1936 updateImprovement :: Avails -> Avails -> Avails
1937 -- (updateImprovement a1 a2) sets a1's improvement flag from a2
1938 updateImprovement (Avails _ avails1) (Avails imp2 _) = Avails imp2 avails1
1941 Extracting the bindings from a bunch of Avails.
1942 The bindings do *not* come back sorted in dependency order.
1943 We assume that they'll be wrapped in a big Rec, so that the
1944 dependency analyser can sort them out later
1947 extractResults :: Avails
1949 -> TcM ( TcDictBinds, -- Bindings
1950 [Inst], -- Irreducible ones
1951 [Inst]) -- Free ones
1953 extractResults (Avails _ avails) wanteds
1954 = go avails emptyBag [] [] wanteds
1956 go :: AvailEnv -> TcDictBinds -> [Inst] -> [Inst] -> [Inst]
1957 -> TcM (TcDictBinds, [Inst], [Inst])
1958 go avails binds irreds frees []
1959 = returnM (binds, irreds, frees)
1961 go avails binds irreds frees (w:ws)
1962 = case findAvailEnv avails w of
1963 Nothing -> pprTrace "Urk: extractResults" (ppr w) $
1964 go avails binds irreds frees ws
1966 Just IsFree -> go (add_free avails w) binds irreds (w:frees) ws
1967 Just IsIrred -> go (add_given avails w) binds (w:irreds) frees ws
1969 Just (Given id) -> go avails new_binds irreds frees ws
1971 new_binds | id == instToId w = binds
1972 | otherwise = addBind binds w (L (instSpan w) (HsVar id))
1973 -- The sought Id can be one of the givens, via a superclass chain
1974 -- and then we definitely don't want to generate an x=x binding!
1976 Just (Rhs rhs ws') -> go (add_given avails w) new_binds irreds frees (ws' ++ ws)
1978 new_binds = addBind binds w rhs
1980 add_given avails w = extendAvailEnv avails w (Given (instToId w))
1982 add_free avails w | isMethod w = avails
1983 | otherwise = add_given avails w
1985 -- Do *not* replace Free by Given if it's a method.
1986 -- The following situation shows why this is bad:
1987 -- truncate :: forall a. RealFrac a => forall b. Integral b => a -> b
1988 -- From an application (truncate f i) we get
1989 -- t1 = truncate at f
1991 -- If we have also have a second occurrence of truncate, we get
1992 -- t3 = truncate at f
1994 -- When simplifying with i,f free, we might still notice that
1995 -- t1=t3; but alas, the binding for t2 (which mentions t1)
1996 -- will continue to float out!
1998 addBind binds inst rhs = binds `unionBags` unitBag (L (instSpan inst)
1999 (VarBind (instToId inst) rhs))
2000 instSpan wanted = instLocSpan (instLoc wanted)
2005 -------------------------
2006 addFree :: Avails -> Inst -> TcM Avails
2007 -- When an Inst is tossed upstairs as 'free' we nevertheless add it
2008 -- to avails, so that any other equal Insts will be commoned up right
2009 -- here rather than also being tossed upstairs. This is really just
2010 -- an optimisation, and perhaps it is more trouble that it is worth,
2011 -- as the following comments show!
2013 -- NB: do *not* add superclasses. If we have
2016 -- but a is not bound here, then we *don't* want to derive
2017 -- dn from df here lest we lose sharing.
2019 addFree avails free = extendAvails avails free IsFree
2021 addWanted :: WantSCs -> Avails -> Inst -> LHsExpr TcId -> [Inst] -> TcM Avails
2022 addWanted want_scs avails wanted rhs_expr wanteds
2023 = addAvailAndSCs want_scs avails wanted avail
2025 avail = Rhs rhs_expr wanteds
2027 addGiven :: Avails -> Inst -> TcM Avails
2028 addGiven avails given = addAvailAndSCs AddSCs avails given (Given (instToId given))
2029 -- Always add superclasses for 'givens'
2031 -- No ASSERT( not (given `elemAvails` avails) ) because in an instance
2032 -- decl for Ord t we can add both Ord t and Eq t as 'givens',
2033 -- so the assert isn't true
2035 addRefinedGiven :: Refinement -> ([Inst], Avails) -> Inst -> TcM ([Inst], Avails)
2036 addRefinedGiven reft (refined_givens, avails) given
2037 | isDict given -- We sometimes have 'given' methods, but they
2038 -- are always optional, so we can drop them
2039 , Just (co, pred) <- refinePred reft (dictPred given)
2040 = do { new_given <- newDictBndr (instLoc given) pred
2041 ; let rhs = L (instSpan given) $
2042 HsWrap (WpCo co) (HsVar (instToId given))
2043 ; avails <- addAvailAndSCs AddSCs avails new_given (Rhs rhs [given])
2044 ; return (new_given:refined_givens, avails) }
2045 -- ToDo: the superclasses of the original given all exist in Avails
2046 -- so we could really just cast them, but it's more awkward to do,
2047 -- and hopefully the optimiser will spot the duplicated work
2049 = return (refined_givens, avails)
2051 addIrred :: WantSCs -> Avails -> Inst -> TcM Avails
2052 addIrred want_scs avails irred = ASSERT2( not (irred `elemAvails` avails), ppr irred $$ ppr avails )
2053 addAvailAndSCs want_scs avails irred IsIrred
2055 addAvailAndSCs :: WantSCs -> Avails -> Inst -> AvailHow -> TcM Avails
2056 addAvailAndSCs want_scs avails inst avail
2057 | not (isClassDict inst) = extendAvails avails inst avail
2058 | NoSCs <- want_scs = extendAvails avails inst avail
2059 | otherwise = do { traceTc (text "addAvailAndSCs" <+> vcat [ppr inst, ppr deps])
2060 ; avails' <- extendAvails avails inst avail
2061 ; addSCs is_loop avails' inst }
2063 is_loop pred = any (`tcEqType` mkPredTy pred) dep_tys
2064 -- Note: this compares by *type*, not by Unique
2065 deps = findAllDeps (unitVarSet (instToId inst)) avail
2066 dep_tys = map idType (varSetElems deps)
2068 findAllDeps :: IdSet -> AvailHow -> IdSet
2069 -- Find all the Insts that this one depends on
2070 -- See Note [SUPERCLASS-LOOP 2]
2071 -- Watch out, though. Since the avails may contain loops
2072 -- (see Note [RECURSIVE DICTIONARIES]), so we need to track the ones we've seen so far
2073 findAllDeps so_far (Rhs _ kids) = foldl find_all so_far kids
2074 findAllDeps so_far other = so_far
2076 find_all :: IdSet -> Inst -> IdSet
2078 | kid_id `elemVarSet` so_far = so_far
2079 | Just avail <- findAvail avails kid = findAllDeps so_far' avail
2080 | otherwise = so_far'
2082 so_far' = extendVarSet so_far kid_id -- Add the new kid to so_far
2083 kid_id = instToId kid
2085 addSCs :: (TcPredType -> Bool) -> Avails -> Inst -> TcM Avails
2086 -- Add all the superclasses of the Inst to Avails
2087 -- The first param says "dont do this because the original thing
2088 -- depends on this one, so you'd build a loop"
2089 -- Invariant: the Inst is already in Avails.
2091 addSCs is_loop avails dict
2092 = ASSERT( isDict dict )
2093 do { sc_dicts <- newDictBndrs (instLoc dict) sc_theta'
2094 ; foldlM add_sc avails (zipEqual "add_scs" sc_dicts sc_sels) }
2096 (clas, tys) = getDictClassTys dict
2097 (tyvars, sc_theta, sc_sels, _) = classBigSig clas
2098 sc_theta' = substTheta (zipTopTvSubst tyvars tys) sc_theta
2100 add_sc avails (sc_dict, sc_sel)
2101 | is_loop (dictPred sc_dict) = return avails -- See Note [SUPERCLASS-LOOP 2]
2102 | is_given sc_dict = return avails
2103 | otherwise = do { avails' <- extendAvails avails sc_dict (Rhs sc_sel_rhs [dict])
2104 ; addSCs is_loop avails' sc_dict }
2106 sc_sel_rhs = L (instSpan dict) (HsWrap co_fn (HsVar sc_sel))
2107 co_fn = WpApp (instToId dict) <.> mkWpTyApps tys
2109 is_given :: Inst -> Bool
2110 is_given sc_dict = case findAvail avails sc_dict of
2111 Just (Given _) -> True -- Given is cheaper than superclass selection
2115 %************************************************************************
2117 \section{tcSimplifyTop: defaulting}
2119 %************************************************************************
2122 @tcSimplifyTop@ is called once per module to simplify all the constant
2123 and ambiguous Insts.
2125 We need to be careful of one case. Suppose we have
2127 instance Num a => Num (Foo a b) where ...
2129 and @tcSimplifyTop@ is given a constraint (Num (Foo x y)). Then it'll simplify
2130 to (Num x), and default x to Int. But what about y??
2132 It's OK: the final zonking stage should zap y to (), which is fine.
2136 tcSimplifyTop, tcSimplifyInteractive :: [Inst] -> TcM TcDictBinds
2137 tcSimplifyTop wanteds
2138 = tc_simplify_top doc False wanteds
2140 doc = text "tcSimplifyTop"
2142 tcSimplifyInteractive wanteds
2143 = tc_simplify_top doc True wanteds
2145 doc = text "tcSimplifyInteractive"
2147 -- The TcLclEnv should be valid here, solely to improve
2148 -- error message generation for the monomorphism restriction
2149 tc_simplify_top doc interactive wanteds
2150 = do { wanteds <- mapM zonkInst wanteds
2151 ; mapM_ zonkTopTyVar (varSetElems (tyVarsOfInsts wanteds))
2153 ; (binds1, irreds1) <- topCheckLoop doc wanteds
2155 ; if null irreds1 then
2158 -- OK, so there are some errors
2159 { -- Use the defaulting rules to do extra unification
2160 -- NB: irreds are already zonked
2161 ; extended_default <- if interactive then return True
2162 else doptM Opt_ExtendedDefaultRules
2163 ; disambiguate extended_default irreds1 -- Does unification
2164 ; (binds2, irreds2) <- topCheckLoop doc irreds1
2166 -- Deal with implicit parameter
2167 ; let (bad_ips, non_ips) = partition isIPDict irreds2
2168 (ambigs, others) = partition isTyVarDict non_ips
2170 ; topIPErrs bad_ips -- Can arise from f :: Int -> Int
2172 ; addNoInstanceErrs others
2173 ; addTopAmbigErrs ambigs
2175 ; return (binds1 `unionBags` binds2) }}
2178 If a dictionary constrains a type variable which is
2179 * not mentioned in the environment
2180 * and not mentioned in the type of the expression
2181 then it is ambiguous. No further information will arise to instantiate
2182 the type variable; nor will it be generalised and turned into an extra
2183 parameter to a function.
2185 It is an error for this to occur, except that Haskell provided for
2186 certain rules to be applied in the special case of numeric types.
2188 * at least one of its classes is a numeric class, and
2189 * all of its classes are numeric or standard
2190 then the type variable can be defaulted to the first type in the
2191 default-type list which is an instance of all the offending classes.
2193 So here is the function which does the work. It takes the ambiguous
2194 dictionaries and either resolves them (producing bindings) or
2195 complains. It works by splitting the dictionary list by type
2196 variable, and using @disambigOne@ to do the real business.
2198 @disambigOne@ assumes that its arguments dictionaries constrain all
2199 the same type variable.
2201 ADR Comment 20/6/94: I've changed the @CReturnable@ case to default to
2202 @()@ instead of @Int@. I reckon this is the Right Thing to do since
2203 the most common use of defaulting is code like:
2205 _ccall_ foo `seqPrimIO` bar
2207 Since we're not using the result of @foo@, the result if (presumably)
2211 disambiguate :: Bool -> [Inst] -> TcM ()
2212 -- Just does unification to fix the default types
2213 -- The Insts are assumed to be pre-zonked
2214 disambiguate extended_defaulting insts
2215 | null defaultable_groups
2218 = do { -- Figure out what default types to use
2219 mb_defaults <- getDefaultTys
2220 ; default_tys <- case mb_defaults of
2221 Just tys -> return tys
2222 Nothing -> -- No use-supplied default;
2223 -- use [Integer, Double]
2224 do { integer_ty <- tcMetaTy integerTyConName
2225 ; checkWiredInTyCon doubleTyCon
2226 ; return [integer_ty, doubleTy] }
2227 ; mapM_ (disambigGroup default_tys) defaultable_groups }
2229 unaries :: [(Inst,Class, TcTyVar)] -- (C tv) constraints
2230 bad_tvs :: TcTyVarSet -- Tyvars mentioned by *other* constraints
2231 (unaries, bad_tvs) = getDefaultableDicts insts
2233 -- Group by type variable
2234 defaultable_groups :: [[(Inst,Class,TcTyVar)]]
2235 defaultable_groups = filter defaultable_group (equivClasses cmp_tv unaries)
2236 cmp_tv (_,_,tv1) (_,_,tv2) = tv1 `compare` tv2
2238 defaultable_group :: [(Inst,Class,TcTyVar)] -> Bool
2239 defaultable_group ds@((_,_,tv):_)
2240 = not (isSkolemTyVar tv) -- Note [Avoiding spurious errors]
2241 && not (tv `elemVarSet` bad_tvs)
2242 && defaultable_classes [c | (_,c,_) <- ds]
2243 defaultable_group [] = panic "defaultable_group"
2245 defaultable_classes clss
2246 | extended_defaulting = any isInteractiveClass clss
2247 | otherwise = all isStandardClass clss && any isNumericClass clss
2249 -- In interactive mode, or with -fextended-default-rules,
2250 -- we default Show a to Show () to avoid graututious errors on "show []"
2251 isInteractiveClass cls
2252 = isNumericClass cls
2253 || (classKey cls `elem` [showClassKey, eqClassKey, ordClassKey])
2256 disambigGroup :: [Type] -- The default types
2257 -> [(Inst,Class,TcTyVar)] -- All standard classes of form (C a)
2258 -> TcM () -- Just does unification, to fix the default types
2260 disambigGroup default_tys dicts
2261 = try_default default_tys
2263 (_,_,tyvar) = head dicts -- Should be non-empty
2264 classes = [c | (_,c,_) <- dicts]
2266 try_default [] = return ()
2267 try_default (default_ty : default_tys)
2268 = tryTcLIE_ (try_default default_tys) $
2269 do { tcSimplifyDefault [mkClassPred clas [default_ty] | clas <- classes]
2270 -- This may fail; then the tryTcLIE_ kicks in
2271 -- Failure here is caused by there being no type in the
2272 -- default list which can satisfy all the ambiguous classes.
2273 -- For example, if Real a is reqd, but the only type in the
2274 -- default list is Int.
2276 -- After this we can't fail
2277 ; warnDefault dicts default_ty
2278 ; unifyType default_ty (mkTyVarTy tyvar) }
2281 Note [Avoiding spurious errors]
2282 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2283 When doing the unification for defaulting, we check for skolem
2284 type variables, and simply don't default them. For example:
2285 f = (*) -- Monomorphic
2286 g :: Num a => a -> a
2288 Here, we get a complaint when checking the type signature for g,
2289 that g isn't polymorphic enough; but then we get another one when
2290 dealing with the (Num a) context arising from f's definition;
2291 we try to unify a with Int (to default it), but find that it's
2292 already been unified with the rigid variable from g's type sig
2295 %************************************************************************
2297 \subsection[simple]{@Simple@ versions}
2299 %************************************************************************
2301 Much simpler versions when there are no bindings to make!
2303 @tcSimplifyThetas@ simplifies class-type constraints formed by
2304 @deriving@ declarations and when specialising instances. We are
2305 only interested in the simplified bunch of class/type constraints.
2307 It simplifies to constraints of the form (C a b c) where
2308 a,b,c are type variables. This is required for the context of
2309 instance declarations.
2312 tcSimplifyDeriv :: InstOrigin
2315 -> ThetaType -- Wanted
2316 -> TcM ThetaType -- Needed
2318 tcSimplifyDeriv orig tc tyvars theta
2319 = tcInstTyVars tyvars `thenM` \ (tvs, _, tenv) ->
2320 -- The main loop may do unification, and that may crash if
2321 -- it doesn't see a TcTyVar, so we have to instantiate. Sigh
2322 -- ToDo: what if two of them do get unified?
2323 newDictBndrsO orig (substTheta tenv theta) `thenM` \ wanteds ->
2324 topCheckLoop doc wanteds `thenM` \ (_, irreds) ->
2326 doptM Opt_GlasgowExts `thenM` \ gla_exts ->
2327 doptM Opt_AllowUndecidableInstances `thenM` \ undecidable_ok ->
2329 inst_ty = mkTyConApp tc (mkTyVarTys tvs)
2330 (ok_insts, bad_insts) = partition is_ok_inst irreds
2332 = isDict inst -- Exclude implication consraints
2333 && (isTyVarClassPred pred || (gla_exts && ok_gla_pred pred))
2335 pred = dictPred inst
2337 ok_gla_pred pred = null (checkInstTermination [inst_ty] [pred])
2338 -- See Note [Deriving context]
2340 tv_set = mkVarSet tvs
2341 simpl_theta = map dictPred ok_insts
2342 weird_preds = [pred | pred <- simpl_theta
2343 , not (tyVarsOfPred pred `subVarSet` tv_set)]
2345 -- Check for a bizarre corner case, when the derived instance decl should
2346 -- have form instance C a b => D (T a) where ...
2347 -- Note that 'b' isn't a parameter of T. This gives rise to all sorts
2348 -- of problems; in particular, it's hard to compare solutions for
2349 -- equality when finding the fixpoint. So I just rule it out for now.
2351 rev_env = zipTopTvSubst tvs (mkTyVarTys tyvars)
2352 -- This reverse-mapping is a Royal Pain,
2353 -- but the result should mention TyVars not TcTyVars
2355 -- In effect, the bad and wierd insts cover all of the cases that
2356 -- would make checkValidInstance fail; if it were called right after tcSimplifyDeriv
2357 -- * wierd_preds ensures unambiguous instances (checkAmbiguity in checkValidInstance)
2358 -- * ok_gla_pred ensures termination (checkInstTermination in checkValidInstance)
2359 addNoInstanceErrs bad_insts `thenM_`
2360 mapM_ (addErrTc . badDerivedPred) weird_preds `thenM_`
2361 returnM (substTheta rev_env simpl_theta)
2363 doc = ptext SLIT("deriving classes for a data type")
2366 Note [Deriving context]
2367 ~~~~~~~~~~~~~~~~~~~~~~~
2368 With -fglasgow-exts, we allow things like (C Int a) in the simplified
2369 context for a derived instance declaration, because at a use of this
2370 instance, we might know that a=Bool, and have an instance for (C Int
2373 We nevertheless insist that each predicate meets the termination
2374 conditions. If not, the deriving mechanism generates larger and larger
2375 constraints. Example:
2377 data Seq a = Cons a (Seq (Succ a)) | Nil deriving Show
2379 Note the lack of a Show instance for Succ. First we'll generate
2380 instance (Show (Succ a), Show a) => Show (Seq a)
2382 instance (Show (Succ (Succ a)), Show (Succ a), Show a) => Show (Seq a)
2383 and so on. Instead we want to complain of no instance for (Show (Succ a)).
2387 @tcSimplifyDefault@ just checks class-type constraints, essentially;
2388 used with \tr{default} declarations. We are only interested in
2389 whether it worked or not.
2392 tcSimplifyDefault :: ThetaType -- Wanted; has no type variables in it
2395 tcSimplifyDefault theta
2396 = newDictBndrsO DefaultOrigin theta `thenM` \ wanteds ->
2397 topCheckLoop doc wanteds `thenM` \ (_, irreds) ->
2398 addNoInstanceErrs irreds `thenM_`
2404 doc = ptext SLIT("default declaration")
2408 %************************************************************************
2410 \section{Errors and contexts}
2412 %************************************************************************
2414 ToDo: for these error messages, should we note the location as coming
2415 from the insts, or just whatever seems to be around in the monad just
2419 groupErrs :: ([Inst] -> TcM ()) -- Deal with one group
2420 -> [Inst] -- The offending Insts
2422 -- Group together insts with the same origin
2423 -- We want to report them together in error messages
2425 groupErrs report_err []
2427 groupErrs report_err (inst:insts)
2428 = do_one (inst:friends) `thenM_`
2429 groupErrs report_err others
2432 -- (It may seem a bit crude to compare the error messages,
2433 -- but it makes sure that we combine just what the user sees,
2434 -- and it avoids need equality on InstLocs.)
2435 (friends, others) = partition is_friend insts
2436 loc_msg = showSDoc (pprInstLoc (instLoc inst))
2437 is_friend friend = showSDoc (pprInstLoc (instLoc friend)) == loc_msg
2438 do_one insts = addInstCtxt (instLoc (head insts)) (report_err insts)
2439 -- Add location and context information derived from the Insts
2441 -- Add the "arising from..." part to a message about bunch of dicts
2442 addInstLoc :: [Inst] -> Message -> Message
2443 addInstLoc insts msg = msg $$ nest 2 (pprInstArising (head insts))
2445 addTopIPErrs :: [Name] -> [Inst] -> TcM ()
2446 addTopIPErrs bndrs []
2448 addTopIPErrs bndrs ips
2449 = addErrTcM (tidy_env, mk_msg tidy_ips)
2451 (tidy_env, tidy_ips) = tidyInsts ips
2452 mk_msg ips = vcat [sep [ptext SLIT("Implicit parameters escape from"),
2453 nest 2 (ptext SLIT("the monomorphic top-level binding(s) of")
2454 <+> pprBinders bndrs <> colon)],
2455 nest 2 (vcat (map ppr_ip ips)),
2457 ppr_ip ip = pprPred (dictPred ip) <+> pprInstArising ip
2459 topIPErrs :: [Inst] -> TcM ()
2461 = groupErrs report tidy_dicts
2463 (tidy_env, tidy_dicts) = tidyInsts dicts
2464 report dicts = addErrTcM (tidy_env, mk_msg dicts)
2465 mk_msg dicts = addInstLoc dicts (ptext SLIT("Unbound implicit parameter") <>
2466 plural tidy_dicts <+> pprDictsTheta tidy_dicts)
2468 addNoInstanceErrs :: [Inst] -- Wanted (can include implications)
2470 addNoInstanceErrs insts
2471 = do { let (tidy_env, tidy_insts) = tidyInsts insts
2472 ; reportNoInstances tidy_env Nothing tidy_insts }
2476 -> Maybe (InstLoc, [Inst]) -- Context
2477 -- Nothing => top level
2478 -- Just (d,g) => d describes the construct
2480 -> [Inst] -- What is wanted (can include implications)
2483 reportNoInstances tidy_env mb_what insts
2484 = groupErrs (report_no_instances tidy_env mb_what) insts
2486 report_no_instances tidy_env mb_what insts
2487 = do { inst_envs <- tcGetInstEnvs
2488 ; let (implics, insts1) = partition isImplicInst insts
2489 (insts2, overlaps) = partitionWith (check_overlap inst_envs) insts1
2490 ; traceTc (text "reportNoInstnces" <+> vcat
2491 [ppr implics, ppr insts1, ppr insts2])
2492 ; mapM_ complain_implic implics
2493 ; mapM_ (\doc -> addErrTcM (tidy_env, doc)) overlaps
2494 ; groupErrs complain_no_inst insts2 }
2496 complain_no_inst insts = addErrTcM (tidy_env, mk_no_inst_err insts)
2498 complain_implic inst -- Recurse!
2499 = reportNoInstances tidy_env
2500 (Just (tci_loc inst, tci_given inst))
2503 check_overlap :: (InstEnv,InstEnv) -> Inst -> Either Inst SDoc
2504 -- Right msg => overlap message
2505 -- Left inst => no instance
2506 check_overlap inst_envs wanted
2507 | not (isClassDict wanted) = Left wanted
2509 = case lookupInstEnv inst_envs clas tys of
2510 -- The case of exactly one match and no unifiers means
2511 -- a successful lookup. That can't happen here, becuase
2512 -- dicts only end up here if they didn't match in Inst.lookupInst
2514 ([m],[]) -> pprPanic "reportNoInstance" (ppr wanted)
2516 ([], _) -> Left wanted -- No match
2517 res -> Right (mk_overlap_msg wanted res)
2519 (clas,tys) = getDictClassTys wanted
2521 mk_overlap_msg dict (matches, unifiers)
2522 = vcat [ addInstLoc [dict] ((ptext SLIT("Overlapping instances for")
2523 <+> pprPred (dictPred dict))),
2524 sep [ptext SLIT("Matching instances") <> colon,
2525 nest 2 (vcat [pprInstances ispecs, pprInstances unifiers])],
2526 ASSERT( not (null matches) )
2527 if not (isSingleton matches)
2528 then -- Two or more matches
2530 else -- One match, plus some unifiers
2531 ASSERT( not (null unifiers) )
2532 parens (vcat [ptext SLIT("The choice depends on the instantiation of") <+>
2533 quotes (pprWithCommas ppr (varSetElems (tyVarsOfInst dict))),
2534 ptext SLIT("Use -fallow-incoherent-instances to use the first choice above")])]
2536 ispecs = [ispec | (_, ispec) <- matches]
2538 mk_no_inst_err insts
2539 | null insts = empty
2541 | Just (loc, givens) <- mb_what, -- Nested (type signatures, instance decls)
2542 not (isEmptyVarSet (tyVarsOfInsts insts))
2543 = vcat [ addInstLoc insts $
2544 sep [ ptext SLIT("Could not deduce") <+> pprDictsTheta insts
2545 , nest 2 $ ptext SLIT("from the context") <+> pprDictsTheta givens]
2546 , show_fixes (fix1 loc : fixes2) ]
2548 | otherwise -- Top level
2549 = vcat [ addInstLoc insts $
2550 ptext SLIT("No instance") <> plural insts
2551 <+> ptext SLIT("for") <+> pprDictsTheta insts
2552 , show_fixes fixes2 ]
2555 fix1 loc = sep [ ptext SLIT("add") <+> pprDictsTheta insts
2556 <+> ptext SLIT("to the context of"),
2557 nest 2 (ppr (instLocOrigin loc)) ]
2558 -- I'm not sure it helps to add the location
2559 -- nest 2 (ptext SLIT("at") <+> ppr (instLocSpan loc)) ]
2561 fixes2 | null instance_dicts = []
2562 | otherwise = [sep [ptext SLIT("add an instance declaration for"),
2563 pprDictsTheta instance_dicts]]
2564 instance_dicts = [d | d <- insts, isClassDict d, not (isTyVarDict d)]
2565 -- Insts for which it is worth suggesting an adding an instance declaration
2566 -- Exclude implicit parameters, and tyvar dicts
2568 show_fixes :: [SDoc] -> SDoc
2569 show_fixes [] = empty
2570 show_fixes (f:fs) = sep [ptext SLIT("Possible fix:"),
2571 nest 2 (vcat (f : map (ptext SLIT("or") <+>) fs))]
2573 addTopAmbigErrs dicts
2574 -- Divide into groups that share a common set of ambiguous tyvars
2575 = ifErrsM (return ()) $ -- Only report ambiguity if no other errors happened
2576 -- See Note [Avoiding spurious errors]
2577 mapM_ report (equivClasses cmp [(d, tvs_of d) | d <- tidy_dicts])
2579 (tidy_env, tidy_dicts) = tidyInsts dicts
2581 tvs_of :: Inst -> [TcTyVar]
2582 tvs_of d = varSetElems (tyVarsOfInst d)
2583 cmp (_,tvs1) (_,tvs2) = tvs1 `compare` tvs2
2585 report :: [(Inst,[TcTyVar])] -> TcM ()
2586 report pairs@((inst,tvs) : _) -- The pairs share a common set of ambiguous tyvars
2587 = mkMonomorphismMsg tidy_env tvs `thenM` \ (tidy_env, mono_msg) ->
2588 setSrcSpan (instSpan inst) $
2589 -- the location of the first one will do for the err message
2590 addErrTcM (tidy_env, msg $$ mono_msg)
2592 dicts = map fst pairs
2593 msg = sep [text "Ambiguous type variable" <> plural tvs <+>
2594 pprQuotedList tvs <+> in_msg,
2595 nest 2 (pprDictsInFull dicts)]
2596 in_msg = text "in the constraint" <> plural dicts <> colon
2597 report [] = panic "addTopAmbigErrs"
2600 mkMonomorphismMsg :: TidyEnv -> [TcTyVar] -> TcM (TidyEnv, Message)
2601 -- There's an error with these Insts; if they have free type variables
2602 -- it's probably caused by the monomorphism restriction.
2603 -- Try to identify the offending variable
2604 -- ASSUMPTION: the Insts are fully zonked
2605 mkMonomorphismMsg tidy_env inst_tvs
2606 = findGlobals (mkVarSet inst_tvs) tidy_env `thenM` \ (tidy_env, docs) ->
2607 returnM (tidy_env, mk_msg docs)
2609 mk_msg [] = ptext SLIT("Probable fix: add a type signature that fixes these type variable(s)")
2610 -- This happens in things like
2611 -- f x = show (read "foo")
2612 -- where monomorphism doesn't play any role
2613 mk_msg docs = vcat [ptext SLIT("Possible cause: the monomorphism restriction applied to the following:"),
2617 monomorphism_fix :: SDoc
2618 monomorphism_fix = ptext SLIT("Probable fix:") <+>
2619 (ptext SLIT("give these definition(s) an explicit type signature")
2620 $$ ptext SLIT("or use -fno-monomorphism-restriction"))
2622 warnDefault ups default_ty
2623 = doptM Opt_WarnTypeDefaults `thenM` \ warn_flag ->
2624 addInstCtxt (instLoc (head (dicts))) (warnTc warn_flag warn_msg)
2626 dicts = [d | (d,_,_) <- ups]
2629 (_, tidy_dicts) = tidyInsts dicts
2630 warn_msg = vcat [ptext SLIT("Defaulting the following constraint(s) to type") <+>
2631 quotes (ppr default_ty),
2632 pprDictsInFull tidy_dicts]
2634 -- Used for the ...Thetas variants; all top level
2636 = vcat [ptext SLIT("Can't derive instances where the instance context mentions"),
2637 ptext SLIT("type variables that are not data type parameters"),
2638 nest 2 (ptext SLIT("Offending constraint:") <+> ppr pred)]
2640 reduceDepthErr n stack
2641 = vcat [ptext SLIT("Context reduction stack overflow; size =") <+> int n,
2642 ptext SLIT("Use -fcontext-stack=N to increase stack size to N"),
2643 nest 4 (pprStack stack)]
2645 pprStack stack = vcat (map pprInstInFull stack)