4 simplifyDefault, simplifyDeriv,
5 simplifyRule, simplifyTop, simplifyInteractive
8 #include "HsVersions.h"
18 import Id ( evVarPred )
19 import Unify ( niFixTvSubst, niSubstTvSet )
27 import NameEnv ( emptyNameEnv )
33 import Class ( classKey )
34 import BasicTypes ( RuleName, TopLevelFlag, isTopLevel )
35 import Control.Monad ( when )
41 *********************************************************************************
43 * External interface *
45 *********************************************************************************
48 simplifyTop :: WantedConstraints -> TcM (Bag EvBind)
49 -- Simplify top-level constraints
50 -- Usually these will be implications,
51 -- but when there is nothing to quantify we don't wrap
52 -- in a degenerate implication, so we do that here instead
54 = simplifyCheck (SimplCheck (ptext (sLit "top level"))) wanteds
57 simplifyInteractive :: WantedConstraints -> TcM (Bag EvBind)
58 simplifyInteractive wanteds
59 = simplifyCheck SimplInteractive wanteds
62 simplifyDefault :: ThetaType -- Wanted; has no type variables in it
63 -> TcM () -- Succeeds iff the constraint is soluble
65 = do { wanted <- newFlatWanteds DefaultOrigin theta
66 ; _ignored_ev_binds <- simplifyCheck (SimplCheck (ptext (sLit "defaults")))
73 *********************************************************************************
77 ***********************************************************************************
80 simplifyDeriv :: CtOrigin
83 -> ThetaType -- Wanted
84 -> TcM ThetaType -- Needed
85 -- Given instance (wanted) => C inst_ty
86 -- Simplify 'wanted' as much as possibles
87 -- Fail if not possible
88 simplifyDeriv orig pred tvs theta
89 = do { tvs_skols <- tcInstSkolTyVars tvs -- Skolemize
90 -- The constraint solving machinery
91 -- expects *TcTyVars* not TyVars.
92 -- We use *non-overlappable* (vanilla) skolems
93 -- See Note [Overlap and deriving]
95 ; let skol_subst = zipTopTvSubst tvs $ map mkTyVarTy tvs_skols
96 subst_skol = zipTopTvSubst tvs_skols $ map mkTyVarTy tvs
97 doc = parens $ ptext (sLit "deriving") <+> parens (ppr pred)
99 ; wanted <- newFlatWanteds orig (substTheta skol_subst theta)
101 ; traceTc "simplifyDeriv" (ppr tvs $$ ppr theta $$ ppr wanted)
102 ; (residual_wanted, _binds)
103 <- runTcS (SimplInfer doc) NoUntouchables $
104 solveWanteds emptyInert (mkFlatWC wanted)
106 ; let (good, bad) = partitionBagWith get_good (wc_flat residual_wanted)
107 -- See Note [Exotic derived instance contexts]
108 get_good :: WantedEvVar -> Either PredType WantedEvVar
109 get_good wev | validDerivPred p = Left p
110 | otherwise = Right wev
111 where p = evVarOfPred wev
113 ; reportUnsolved (residual_wanted { wc_flat = bad })
115 ; let min_theta = mkMinimalBySCs (bagToList good)
116 ; return (substTheta subst_skol min_theta) }
119 Note [Overlap and deriving]
120 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
121 Consider some overlapping instances:
122 data Show a => Show [a] where ..
123 data Show [Char] where ...
125 Now a data type with deriving:
126 data T a = MkT [a] deriving( Show )
128 We want to get the derived instance
129 instance Show [a] => Show (T a) where...
131 instance Show a => Show (T a) where...
132 so that the (Show (T Char)) instance does the Right Thing
134 It's very like the situation when we're inferring the type
138 f :: Show [a] => a -> String
140 BOTTOM LINE: use vanilla, non-overlappable skolems when inferring
141 the context for the derived instance.
142 Hence tcInstSkolTyVars not tcInstSuperSkolTyVars
144 Note [Exotic derived instance contexts]
145 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
146 In a 'derived' instance declaration, we *infer* the context. It's a
147 bit unclear what rules we should apply for this; the Haskell report is
148 silent. Obviously, constraints like (Eq a) are fine, but what about
149 data T f a = MkT (f a) deriving( Eq )
150 where we'd get an Eq (f a) constraint. That's probably fine too.
152 One could go further: consider
153 data T a b c = MkT (Foo a b c) deriving( Eq )
154 instance (C Int a, Eq b, Eq c) => Eq (Foo a b c)
156 Notice that this instance (just) satisfies the Paterson termination
157 conditions. Then we *could* derive an instance decl like this:
159 instance (C Int a, Eq b, Eq c) => Eq (T a b c)
160 even though there is no instance for (C Int a), because there just
161 *might* be an instance for, say, (C Int Bool) at a site where we
162 need the equality instance for T's.
164 However, this seems pretty exotic, and it's quite tricky to allow
165 this, and yet give sensible error messages in the (much more common)
166 case where we really want that instance decl for C.
168 So for now we simply require that the derived instance context
169 should have only type-variable constraints.
171 Here is another example:
172 data Fix f = In (f (Fix f)) deriving( Eq )
173 Here, if we are prepared to allow -XUndecidableInstances we
174 could derive the instance
175 instance Eq (f (Fix f)) => Eq (Fix f)
176 but this is so delicate that I don't think it should happen inside
177 'deriving'. If you want this, write it yourself!
179 NB: if you want to lift this condition, make sure you still meet the
180 termination conditions! If not, the deriving mechanism generates
181 larger and larger constraints. Example:
183 data Seq a = Cons a (Seq (Succ a)) | Nil deriving Show
185 Note the lack of a Show instance for Succ. First we'll generate
186 instance (Show (Succ a), Show a) => Show (Seq a)
188 instance (Show (Succ (Succ a)), Show (Succ a), Show a) => Show (Seq a)
189 and so on. Instead we want to complain of no instance for (Show (Succ a)).
193 Allow constraints which consist only of type variables, with no repeats.
195 *********************************************************************************
199 ***********************************************************************************
202 simplifyInfer :: TopLevelFlag
203 -> Bool -- Apply monomorphism restriction
204 -> [(Name, TcTauType)] -- Variables to be generalised,
205 -- and their tau-types
207 -> TcM ([TcTyVar], -- Quantify over these type variables
208 [EvVar], -- ... and these constraints
209 TcEvBinds) -- ... binding these evidence variables
210 simplifyInfer top_lvl apply_mr name_taus wanteds
212 = do { gbl_tvs <- tcGetGlobalTyVars -- Already zonked
213 ; zonked_taus <- zonkTcTypes (map snd name_taus)
214 ; let tvs_to_quantify = get_tau_tvs zonked_taus `minusVarSet` gbl_tvs
215 ; qtvs <- zonkQuantifiedTyVars (varSetElems tvs_to_quantify)
216 ; return (qtvs, [], emptyTcEvBinds) }
219 = do { zonked_wanteds <- zonkWC wanteds
220 ; zonked_taus <- zonkTcTypes (map snd name_taus)
221 ; gbl_tvs <- tcGetGlobalTyVars
223 ; traceTc "simplifyInfer {" $ vcat
224 [ ptext (sLit "apply_mr =") <+> ppr apply_mr
225 , ptext (sLit "zonked_taus =") <+> ppr zonked_taus
226 , ptext (sLit "wanted =") <+> ppr zonked_wanteds
230 -- Make a guess at the quantified type variables
231 -- Then split the constraints on the baisis of those tyvars
232 -- to avoid unnecessarily simplifying a class constraint
233 -- See Note [Avoid unecessary constraint simplification]
234 ; let zonked_tau_tvs = get_tau_tvs zonked_taus
235 proto_qtvs = growWanteds gbl_tvs zonked_wanteds $
236 zonked_tau_tvs `minusVarSet` gbl_tvs
237 (perhaps_bound, surely_free)
238 = partitionBag (quantifyMe proto_qtvs) (wc_flat zonked_wanteds)
240 ; traceTc "simplifyInfer proto" $ vcat
241 [ ptext (sLit "zonked_tau_tvs =") <+> ppr zonked_tau_tvs
242 , ptext (sLit "proto_qtvs =") <+> ppr proto_qtvs
243 , ptext (sLit "surely_fref =") <+> ppr surely_free
246 ; emitFlats surely_free
247 ; traceTc "sinf" $ vcat
248 [ ptext (sLit "perhaps_bound =") <+> ppr perhaps_bound
249 , ptext (sLit "surely_free =") <+> ppr surely_free
253 -- Now simplify the possibly-bound constraints
254 ; (simpl_results, tc_binds0)
255 <- runTcS (SimplInfer (ppr (map fst name_taus))) NoUntouchables $
256 simplifyWithApprox (zonked_wanteds { wc_flat = perhaps_bound })
258 ; when (insolubleWC simpl_results) -- Fail fast if there is an insoluble constraint
259 (do { reportUnsolved simpl_results; failM })
262 -- Split again simplified_perhaps_bound, because some unifications
263 -- may have happened, and emit the free constraints.
264 ; gbl_tvs <- tcGetGlobalTyVars
265 ; zonked_tau_tvs <- zonkTcTyVarsAndFV zonked_tau_tvs
266 ; zonked_simples <- zonkWantedEvVars (wc_flat simpl_results)
267 ; let init_tvs = zonked_tau_tvs `minusVarSet` gbl_tvs
268 mr_qtvs = init_tvs `minusVarSet` constrained_tvs
269 constrained_tvs = tyVarsOfEvVarXs zonked_simples
270 qtvs = growWantedEVs gbl_tvs zonked_simples init_tvs
271 (final_qtvs, (bound, free))
272 | apply_mr = (mr_qtvs, (emptyBag, zonked_simples))
273 | otherwise = (qtvs, partitionBag (quantifyMe qtvs) zonked_simples)
276 ; if isEmptyVarSet final_qtvs && isEmptyBag bound
277 then ASSERT( isEmptyBag (wc_insol simpl_results) )
278 do { traceTc "} simplifyInfer/no quantification" empty
279 ; emitImplications (wc_impl simpl_results)
280 ; return ([], [], EvBinds tc_binds0) }
283 -- Step 4, zonk quantified variables
284 { let minimal_flat_preds = mkMinimalBySCs $ map evVarOfPred $ bagToList bound
285 ; let poly_ids = [ (name, mkSigmaTy [] minimal_flat_preds ty)
286 | (name, ty) <- name_taus ]
287 -- Don't add the quantified variables here, because
288 -- they are also bound in ic_skols and we want them to be
290 skol_info = InferSkol poly_ids
292 ; gloc <- getCtLoc skol_info
293 ; qtvs_to_return <- zonkQuantifiedTyVars (varSetElems final_qtvs)
296 -- Minimize `bound' and emit an implication
297 ; minimal_bound_ev_vars <- mapM TcMType.newEvVar minimal_flat_preds
298 ; ev_binds_var <- newTcEvBinds
299 ; mapBagM_ (\(EvBind evar etrm) -> addTcEvBind ev_binds_var evar etrm) tc_binds0
300 ; lcl_env <- getLclTypeEnv
301 ; let implic = Implic { ic_untch = NoUntouchables
303 , ic_skols = mkVarSet qtvs_to_return
304 , ic_given = minimal_bound_ev_vars
305 , ic_wanted = simpl_results { wc_flat = bound }
307 , ic_binds = ev_binds_var
309 ; emitImplication implic
310 ; traceTc "} simplifyInfer/produced residual implication for quantification" $
311 vcat [ ptext (sLit "implic =") <+> ppr implic
312 -- ic_skols, ic_given give rest of result
313 , ptext (sLit "qtvs =") <+> ppr final_qtvs
314 , ptext (sLit "spb =") <+> ppr zonked_simples
315 , ptext (sLit "bound =") <+> ppr bound ]
319 ; return (qtvs_to_return, minimal_bound_ev_vars, TcEvBinds ev_binds_var) } }
321 get_tau_tvs | isTopLevel top_lvl = tyVarsOfTypes
322 | otherwise = exactTyVarsOfTypes
323 -- See Note [Silly type synonym] in TcType
327 Note [Minimize by Superclasses]
328 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
330 When we quantify over a constraint, in simplifyInfer we need to
331 quantify over a constraint that is minimal in some sense: For
332 instance, if the final wanted constraint is (Eq alpha, Ord alpha),
333 we'd like to quantify over Ord alpha, because we can just get Eq alpha
334 from superclass selection from Ord alpha. This minimization is what
335 mkMinimalBySCs does. Then, simplifyInfer uses the minimal constraint
336 to check the original wanted.
339 simplifyWithApprox :: WantedConstraints -> TcS WantedConstraints
340 simplifyWithApprox wanted
341 = do { traceTcS "simplifyApproxLoop" (ppr wanted)
343 ; results <- solveWanteds emptyInert wanted
345 ; let (residual_implics, floats) = approximateImplications (wc_impl results)
347 -- If no new work was produced then we are done with simplifyApproxLoop
348 ; if insolubleWC results || isEmptyBag floats
351 else solveWanteds emptyInert
352 (WC { wc_flat = floats `unionBags` wc_flat results
353 , wc_impl = residual_implics
354 , wc_insol = emptyBag }) }
356 approximateImplications :: Bag Implication -> (Bag Implication, Bag WantedEvVar)
357 -- Extracts any nested constraints that don't mention the skolems
358 approximateImplications impls
359 = do_bag (float_implic emptyVarSet) impls
361 do_bag :: forall a b c. (a -> (Bag b, Bag c)) -> Bag a -> (Bag b, Bag c)
362 do_bag f = foldrBag (plus . f) (emptyBag, emptyBag)
363 plus :: forall b c. (Bag b, Bag c) -> (Bag b, Bag c) -> (Bag b, Bag c)
364 plus (a1,b1) (a2,b2) = (a1 `unionBags` a2, b1 `unionBags` b2)
366 float_implic :: TyVarSet -> Implication -> (Bag Implication, Bag WantedEvVar)
367 float_implic skols imp
368 = (unitBag (imp { ic_wanted = wanted' }), floats)
370 (wanted', floats) = float_wc (skols `unionVarSet` ic_skols imp) (ic_wanted imp)
372 float_wc skols wc@(WC { wc_flat = flat, wc_impl = implic })
373 = (wc { wc_flat = flat', wc_impl = implic' }, floats1 `unionBags` floats2)
375 (flat', floats1) = do_bag (float_flat skols) flat
376 (implic', floats2) = do_bag (float_implic skols) implic
378 float_flat :: TcTyVarSet -> WantedEvVar -> (Bag WantedEvVar, Bag WantedEvVar)
380 | tyVarsOfEvVarX wev `disjointVarSet` skols = (emptyBag, unitBag wev)
381 | otherwise = (unitBag wev, emptyBag)
385 -- (growX gbls wanted tvs) grows a seed 'tvs' against the
386 -- X-constraint 'wanted', nuking the 'gbls' at each stage
387 -- It's conservative in that if the seed could *possibly*
388 -- grow to include a type variable, then it does
390 growWanteds :: TyVarSet -> WantedConstraints -> TyVarSet -> TyVarSet
391 growWanteds gbl_tvs wc = fixVarSet (growWC gbl_tvs wc)
393 growWantedEVs :: TyVarSet -> Bag WantedEvVar -> TyVarSet -> TyVarSet
394 growWantedEVs gbl_tvs ws tvs
395 | isEmptyBag ws = tvs
396 | otherwise = fixVarSet (growPreds gbl_tvs evVarOfPred ws) tvs
398 -------- Helper functions, do not do fixpoint ------------------------
399 growWC :: TyVarSet -> WantedConstraints -> TyVarSet -> TyVarSet
400 growWC gbl_tvs wc = growImplics gbl_tvs (wc_impl wc) .
401 growPreds gbl_tvs evVarOfPred (wc_flat wc) .
402 growPreds gbl_tvs evVarOfPred (wc_insol wc)
404 growImplics :: TyVarSet -> Bag Implication -> TyVarSet -> TyVarSet
405 growImplics gbl_tvs implics tvs
406 = foldrBag grow_implic tvs implics
408 grow_implic implic tvs
409 = grow tvs `minusVarSet` ic_skols implic
411 grow = growWC gbl_tvs (ic_wanted implic) .
412 growPreds gbl_tvs evVarPred (listToBag (ic_given implic))
413 -- We must grow from givens too; see test IPRun
415 growPreds :: TyVarSet -> (a -> PredType) -> Bag a -> TyVarSet -> TyVarSet
416 growPreds gbl_tvs get_pred items tvs
417 = foldrBag extend tvs items
419 extend item tvs = tvs `unionVarSet`
420 (growPredTyVars (get_pred item) tvs `minusVarSet` gbl_tvs)
423 quantifyMe :: TyVarSet -- Quantifying over these
425 -> Bool -- True <=> quantify over this wanted
427 | isIPPred pred = True -- Note [Inheriting implicit parameters]
428 | otherwise = tyVarsOfPred pred `intersectsVarSet` qtvs
430 pred = evVarOfPred wev
433 Note [Avoid unecessary constraint simplification]
434 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
435 When inferring the type of a let-binding, with simplifyInfer,
436 try to avoid unnecessariliy simplifying class constraints.
437 Doing so aids sharing, but it also helps with delicate
439 instance C t => C [t] where ..
441 f x = let g y = ...(constraint C [t])...
443 When inferring a type for 'g', we don't want to apply the
444 instance decl, because then we can't satisfy (C t). So we
445 just notice that g isn't quantified over 't' and partition
446 the contraints before simplifying.
448 This only half-works, but then let-generalisation only half-works.
451 Note [Inheriting implicit parameters]
452 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
457 where f is *not* a top-level binding.
458 From the RHS of f we'll get the constraint (?y::Int).
459 There are two types we might infer for f:
463 (so we get ?y from the context of f's definition), or
465 f :: (?y::Int) => Int -> Int
467 At first you might think the first was better, becuase then
468 ?y behaves like a free variable of the definition, rather than
469 having to be passed at each call site. But of course, the WHOLE
470 IDEA is that ?y should be passed at each call site (that's what
471 dynamic binding means) so we'd better infer the second.
473 BOTTOM LINE: when *inferring types* you *must* quantify
474 over implicit parameters. See the predicate isFreeWhenInferring.
477 *********************************************************************************
481 ***********************************************************************************
483 Note [Simplifying RULE lhs constraints]
484 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
485 On the LHS of transformation rules we only simplify only equalities,
486 but not dictionaries. We want to keep dictionaries unsimplified, to
487 serve as the available stuff for the RHS of the rule. We *do* want to
488 simplify equalities, however, to detect ill-typed rules that cannot be
491 Implementation: the TcSFlags carried by the TcSMonad controls the
492 amount of simplification, so simplifyRuleLhs just sets the flag
495 Example. Consider the following left-hand side of a rule
496 f (x == y) (y > z) = ...
497 If we typecheck this expression we get constraints
498 d1 :: Ord a, d2 :: Eq a
499 We do NOT want to "simplify" to the LHS
500 forall x::a, y::a, z::a, d1::Ord a.
501 f ((==) (eqFromOrd d1) x y) ((>) d1 y z) = ...
503 forall x::a, y::a, z::a, d1::Ord a, d2::Eq a.
504 f ((==) d2 x y) ((>) d1 y z) = ...
506 Here is another example:
507 fromIntegral :: (Integral a, Num b) => a -> b
508 {-# RULES "foo" fromIntegral = id :: Int -> Int #-}
509 In the rule, a=b=Int, and Num Int is a superclass of Integral Int. But
510 we *dont* want to get
512 fromIntegral Int Int dIntegralInt (scsel dIntegralInt) = id Int
513 because the scsel will mess up RULE matching. Instead we want
514 forall dIntegralInt, dNumInt.
515 fromIntegral Int Int dIntegralInt dNumInt = id Int
518 g (x == y) (y == z) = ..
519 where the two dictionaries are *identical*, we do NOT WANT
520 forall x::a, y::a, z::a, d1::Eq a
521 f ((==) d1 x y) ((>) d1 y z) = ...
522 because that will only match if the dict args are (visibly) equal.
523 Instead we want to quantify over the dictionaries separately.
525 In short, simplifyRuleLhs must *only* squash equalities, leaving
526 all dicts unchanged, with absolutely no sharing.
528 HOWEVER, under a nested implication things are different
530 f :: (forall a. Eq a => a->a) -> Bool -> ...
531 {-# RULES "foo" forall (v::forall b. Eq b => b->b).
534 Here we *must* solve the wanted (Eq a) from the given (Eq a)
535 resulting from skolemising the agument type of g. So we
536 revert to SimplCheck when going under an implication.
539 simplifyRule :: RuleName
540 -> [TcTyVar] -- Explicit skolems
541 -> WantedConstraints -- Constraints from LHS
542 -> WantedConstraints -- Constraints from RHS
543 -> TcM ([EvVar], -- LHS dicts
544 TcEvBinds, -- Evidence for LHS
545 TcEvBinds) -- Evidence for RHS
546 -- See Note [Simplifying RULE lhs constraints]
547 simplifyRule name tv_bndrs lhs_wanted rhs_wanted
548 = do { loc <- getCtLoc (RuleSkol name)
549 ; zonked_lhs <- zonkWC lhs_wanted
550 ; let untch = NoUntouchables
551 -- We allow ourselves to unify environment
552 -- variables; hence *no untouchables*
554 ; (lhs_results, lhs_binds)
555 <- runTcS (SimplRuleLhs name) untch $
556 solveWanteds emptyInert zonked_lhs
558 ; traceTc "simplifyRule" $
559 vcat [ text "zonked_lhs" <+> ppr zonked_lhs
560 , text "lhs_results" <+> ppr lhs_results
561 , text "lhs_binds" <+> ppr lhs_binds
562 , text "rhs_wanted" <+> ppr rhs_wanted ]
565 -- Don't quantify over equalities (judgement call here)
566 ; let (eqs, dicts) = partitionBag (isEqPred . evVarOfPred)
567 (wc_flat lhs_results)
568 lhs_dicts = map evVarOf (bagToList dicts)
569 -- Dicts and implicit parameters
571 -- Fail if we have not got down to unsolved flats
572 ; ev_binds_var <- newTcEvBinds
573 ; emitImplication $ Implic { ic_untch = untch
574 , ic_env = emptyNameEnv
575 , ic_skols = mkVarSet tv_bndrs
576 , ic_given = lhs_dicts
577 , ic_wanted = lhs_results { wc_flat = eqs }
578 , ic_insol = insolubleWC lhs_results
579 , ic_binds = ev_binds_var
582 -- Notice that we simplify the RHS with only the explicitly
583 -- introduced skolems, allowing the RHS to constrain any
584 -- unification variables.
585 -- Then, and only then, we call zonkQuantifiedTypeVariables
586 -- Example foo :: Ord a => a -> a
587 -- foo_spec :: Int -> Int
588 -- {-# RULE "foo" foo = foo_spec #-}
589 -- Here, it's the RHS that fixes the type variable
591 -- So we don't want to make untouchable the type
592 -- variables in the envt of the RHS, because they include
593 -- the template variables of the RULE
595 -- Hence the rather painful ad-hoc treatement here
596 ; rhs_binds_var@(EvBindsVar evb_ref _) <- newTcEvBinds
597 ; let doc = ptext (sLit "rhs of rule") <+> doubleQuotes (ftext name)
598 ; rhs_binds1 <- simplifyCheck (SimplCheck doc) $
599 WC { wc_flat = emptyBag
600 , wc_insol = emptyBag
601 , wc_impl = unitBag $
602 Implic { ic_untch = NoUntouchables
603 , ic_env = emptyNameEnv
604 , ic_skols = mkVarSet tv_bndrs
605 , ic_given = lhs_dicts
606 , ic_wanted = rhs_wanted
607 , ic_insol = insolubleWC rhs_wanted
608 , ic_binds = rhs_binds_var
610 ; rhs_binds2 <- readTcRef evb_ref
614 , EvBinds (rhs_binds1 `unionBags` evBindMapBinds rhs_binds2)) }
618 *********************************************************************************
622 ***********************************************************************************
625 simplifyCheck :: SimplContext
626 -> WantedConstraints -- Wanted
628 -- Solve a single, top-level implication constraint
629 -- e.g. typically one created from a top-level type signature
630 -- f :: forall a. [a] -> [a]
632 -- We do this even if the function has no polymorphism:
636 -- (whereas for *nested* bindings we would not create
637 -- an implication constraint for g at all.)
639 -- Fails if can't solve something in the input wanteds
640 simplifyCheck ctxt wanteds
641 = do { wanteds <- zonkWC wanteds
643 ; traceTc "simplifyCheck {" (vcat
644 [ ptext (sLit "wanted =") <+> ppr wanteds ])
646 ; (unsolved, ev_binds) <- runTcS ctxt NoUntouchables $
647 solveWanteds emptyInert wanteds
649 ; traceTc "simplifyCheck }" $
650 ptext (sLit "unsolved =") <+> ppr unsolved
652 ; reportUnsolved unsolved
657 solveWanteds :: InertSet -- Given
659 -> TcS WantedConstraints
660 solveWanteds inert wanted
661 = do { (unsolved_flats, unsolved_implics, insols)
662 <- solve_wanteds inert wanted
663 ; return (WC { wc_flat = keepWanted unsolved_flats -- Discard Derived
664 , wc_impl = unsolved_implics
665 , wc_insol = insols }) }
667 solve_wanteds :: InertSet -- Given
669 -> TcS (Bag FlavoredEvVar, Bag Implication, Bag FlavoredEvVar)
670 -- solve_wanteds iterates when it is able to float equalities
671 -- out of one or more of the implications
672 solve_wanteds inert wanted@(WC { wc_flat = flats, wc_impl = implics, wc_insol = insols })
673 = do { traceTcS "solveWanteds {" (ppr wanted)
676 -- Discard from insols all the derived/given constraints
677 -- because they will show up again when we try to solve
678 -- everything else. Solving them a second time is a bit
679 -- of a waste, but the code is simple, and the program is
681 ; let all_flats = flats `unionBags` keepWanted insols
682 ; inert1 <- solveInteractWanted inert (bagToList all_flats)
684 ; (unsolved_flats, unsolved_implics) <- simpl_loop 1 inert1 implics
686 ; bb <- getTcEvBindsBag
687 ; tb <- getTcSTyBindsMap
688 ; traceTcS "solveWanteds }" $
689 vcat [ text "unsolved_flats =" <+> ppr unsolved_flats
690 , text "unsolved_implics =" <+> ppr unsolved_implics
691 , text "current evbinds =" <+> vcat (map ppr (varEnvElts bb))
692 , text "current tybinds =" <+> vcat (map ppr (varEnvElts tb))
695 ; (subst, remaining_flats) <- solveCTyFunEqs unsolved_flats
696 -- See Note [Solving Family Equations]
697 -- NB: remaining_flats has already had subst applied
699 ; let (insoluble_flats, unsolved_flats) = partitionBag isCFrozenErr remaining_flats
701 ; return ( mapBag (substFlavoredEvVar subst . deCanonicalise) unsolved_flats
702 , mapBag (substImplication subst) unsolved_implics
703 , mapBag (substFlavoredEvVar subst . deCanonicalise) insoluble_flats ) }
709 -> TcS (CanonicalCts, Bag Implication) -- CanonicalCts are Wanted or Derived
710 simpl_loop n inert implics
712 = trace "solveWanteds: loop" $ -- Always bleat
713 do { traceTcS "solveWanteds: loop" (ppr inert) -- Bleat more informatively
714 ; let (_, unsolved_cans) = extractUnsolved inert
715 ; return (unsolved_cans, implics) }
718 = do { traceTcS "solveWanteds: simpl_loop start {" $
719 vcat [ text "n =" <+> ppr n
720 , text "implics =" <+> ppr implics
721 , text "inert =" <+> ppr inert ]
723 ; let (just_given_inert, unsolved_cans) = extractUnsolved inert
724 -- unsolved_cans contains either Wanted or Derived!
726 ; (implic_eqs, unsolved_implics)
727 <- solveNestedImplications just_given_inert unsolved_cans implics
729 -- Apply defaulting rules if and only if there
730 -- no floated equalities. If there are, they may
731 -- solve the remaining wanteds, so don't do defaulting.
732 ; improve_eqs <- if not (isEmptyBag implic_eqs)
733 then return implic_eqs
734 else applyDefaultingRules just_given_inert unsolved_cans
736 ; traceTcS "solveWanteds: simpl_loop end }" $
737 vcat [ text "improve_eqs =" <+> ppr improve_eqs
738 , text "unsolved_flats =" <+> ppr unsolved_cans
739 , text "unsolved_implics =" <+> ppr unsolved_implics ]
741 ; (improve_eqs_already_in_inert, inert_with_improvement)
742 <- solveInteract inert improve_eqs
744 ; if improve_eqs_already_in_inert then
745 return (unsolved_cans, unsolved_implics)
747 simpl_loop (n+1) inert_with_improvement
748 -- Contain unsolved_cans and the improve_eqs
752 givensFromWanteds :: SimplContext -> CanonicalCts -> Bag FlavoredEvVar
753 -- Extract the Wanted ones from CanonicalCts and conver to
754 -- Givens; not Given/Solved, see Note [Preparing inert set for implications]
755 givensFromWanteds _ctxt = foldrBag getWanted emptyBag
757 getWanted :: CanonicalCt -> Bag FlavoredEvVar -> Bag FlavoredEvVar
760 = let given = mkEvVarX (cc_id cc) (mkGivenFlavor (cc_flavor cc) UnkSkol)
761 in given `consBag` givens -- and not mkSolvedFlavor,
762 -- see Note [Preparing inert set for implications]
765 pushable_wanted :: CanonicalCt -> Bool
767 | not (isCFrozenErr cc)
769 = isEqPred (evVarPred (cc_id cc)) -- see Note [Preparing inert set for implications]
772 solveNestedImplications :: InertSet -> CanonicalCts
774 -> TcS (Bag FlavoredEvVar, Bag Implication)
775 solveNestedImplications just_given_inert unsolved_cans implics
777 = return (emptyBag, emptyBag)
779 = do { -- See Note [Preparing inert set for implications]
780 -- Push the unsolved wanteds inwards, but as givens
782 ; simpl_ctx <- getTcSContext
784 ; let pushed_givens = givensFromWanteds simpl_ctx unsolved_cans
785 tcs_untouchables = filterVarSet isFlexiTcsTv $
786 tyVarsOfEvVarXs pushed_givens
787 -- See Note [Extra TcsTv untouchables]
789 ; traceTcS "solveWanteds: preparing inerts for implications {"
790 (vcat [ppr tcs_untouchables, ppr pushed_givens])
792 ; (_, inert_for_implics) <- solveInteract just_given_inert pushed_givens
794 ; traceTcS "solveWanteds: } now doing nested implications {" $
795 vcat [ text "inerts_for_implics =" <+> ppr inert_for_implics
796 , text "implics =" <+> ppr implics ]
798 ; (implic_eqs, unsolved_implics)
799 <- flatMapBagPairM (solveImplication tcs_untouchables inert_for_implics) implics
801 ; traceTcS "solveWanteds: done nested implications }" $
802 vcat [ text "implic_eqs =" <+> ppr implic_eqs
803 , text "unsolved_implics =" <+> ppr unsolved_implics ]
805 ; return (implic_eqs, unsolved_implics) }
807 solveImplication :: TcTyVarSet -- Untouchable TcS unification variables
809 -> Implication -- Wanted
810 -> TcS (Bag FlavoredEvVar, -- All wanted or derived unifications: var = type
811 Bag Implication) -- Unsolved rest (always empty or singleton)
813 -- 1. A bag of floatable wanted constraints, not mentioning any skolems,
814 -- that are of the form unification var = type
816 -- 2. Maybe a unsolved implication, empty if entirely solved!
818 -- Precondition: everything is zonked by now
819 solveImplication tcs_untouchables inert
820 imp@(Implic { ic_untch = untch
821 , ic_binds = ev_binds
824 , ic_wanted = wanteds
826 = nestImplicTcS ev_binds (untch, tcs_untouchables) $
827 recoverTcS (return (emptyBag, emptyBag)) $
828 -- Recover from nested failures. Even the top level is
829 -- just a bunch of implications, so failing at the first
831 do { traceTcS "solveImplication {" (ppr imp)
834 ; given_inert <- solveInteractGiven inert loc givens
836 -- Simplify the wanteds
837 ; (unsolved_flats, unsolved_implics, insols)
838 <- solve_wanteds given_inert wanteds
840 ; let (res_flat_free, res_flat_bound)
841 = floatEqualities skols givens unsolved_flats
842 final_flat = keepWanted res_flat_bound
844 ; let res_wanted = WC { wc_flat = final_flat
845 , wc_impl = unsolved_implics
846 , wc_insol = insols }
847 res_implic = unitImplication $
848 imp { ic_wanted = res_wanted
849 , ic_insol = insolubleWC res_wanted }
851 ; traceTcS "solveImplication end }" $ vcat
852 [ text "res_flat_free =" <+> ppr res_flat_free
853 , text "res_implic =" <+> ppr res_implic ]
855 ; return (res_flat_free, res_implic) }
858 floatEqualities :: TcTyVarSet -> [EvVar]
859 -> Bag FlavoredEvVar -> (Bag FlavoredEvVar, Bag FlavoredEvVar)
860 -- Post: The returned FlavoredEvVar's are only Wanted or Derived
861 -- and come from the input wanted ev vars or deriveds
862 floatEqualities skols can_given wantders
863 | hasEqualities can_given = (emptyBag, wantders)
864 -- Note [Float Equalities out of Implications]
865 | otherwise = partitionBag is_floatable wantders
868 where is_floatable :: FlavoredEvVar -> Bool
869 is_floatable (EvVarX cv _fl)
870 | isCoVar cv = skols `disjointVarSet` predTvs_under_fsks (coVarPred cv)
871 is_floatable _flev = False
873 tvs_under_fsks :: Type -> TyVarSet
874 -- ^ NB: for type synonyms tvs_under_fsks does /not/ expand the synonym
875 tvs_under_fsks (TyVarTy tv)
876 | not (isTcTyVar tv) = unitVarSet tv
877 | FlatSkol ty <- tcTyVarDetails tv = tvs_under_fsks ty
878 | otherwise = unitVarSet tv
879 tvs_under_fsks (TyConApp _ tys) = unionVarSets (map tvs_under_fsks tys)
880 tvs_under_fsks (PredTy sty) = predTvs_under_fsks sty
881 tvs_under_fsks (FunTy arg res) = tvs_under_fsks arg `unionVarSet` tvs_under_fsks res
882 tvs_under_fsks (AppTy fun arg) = tvs_under_fsks fun `unionVarSet` tvs_under_fsks arg
883 tvs_under_fsks (ForAllTy tv ty) -- The kind of a coercion binder
884 -- can mention type variables!
885 | isTyVar tv = inner_tvs `delVarSet` tv
886 | otherwise {- Coercion -} = -- ASSERT( not (tv `elemVarSet` inner_tvs) )
887 inner_tvs `unionVarSet` tvs_under_fsks (tyVarKind tv)
889 inner_tvs = tvs_under_fsks ty
891 predTvs_under_fsks :: PredType -> TyVarSet
892 predTvs_under_fsks (IParam _ ty) = tvs_under_fsks ty
893 predTvs_under_fsks (ClassP _ tys) = unionVarSets (map tvs_under_fsks tys)
894 predTvs_under_fsks (EqPred ty1 ty2) = tvs_under_fsks ty1 `unionVarSet` tvs_under_fsks ty2
897 Note [Preparing inert set for implications]
898 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
899 Before solving the nested implications, we convert any unsolved flat wanteds
900 to givens, and add them to the inert set. Reasons:
902 a) In checking mode, suppresses unnecessary errors. We already have
903 on unsolved-wanted error; adding it to the givens prevents any
904 consequential errors from showing up
906 b) More importantly, in inference mode, we are going to quantify over this
907 constraint, and we *don't* want to quantify over any constraints that
908 are deducible from it.
910 c) Flattened type-family equalities must be exposed to the nested
911 constraints. Consider
912 F b ~ alpha, (forall c. F b ~ alpha)
913 Obviously this is soluble with [alpha := F b]. But the
914 unification is only done by solveCTyFunEqs, right at the end of
915 solveWanteds, and if we aren't careful we'll end up with an
916 unsolved goal inside the implication. We need to "push" the
917 as-yes-unsolved (F b ~ alpha) inwards, as a *given*, so that it
918 can be used to solve the inner (F b
919 ~ alpha). See Trac #4935.
921 d) There are other cases where interactions between wanteds that can help
922 to solve a constraint. For example
926 (C Int alpha), (forall d. C d blah => C Int a)
928 If we push the (C Int alpha) inwards, as a given, it can produce
929 a fundep (alpha~a) and this can float out again and be used to
930 fix alpha. (In general we can't float class constraints out just
931 in case (C d blah) might help to solve (C Int a).)
933 The unsolved wanteds are *canonical* but they may not be *inert*,
934 because when made into a given they might interact with other givens.
935 Hence the call to solveInteract. Example:
937 Original inert set = (d :_g D a) /\ (co :_w a ~ [beta])
939 We were not able to solve (a ~w [beta]) but we can't just assume it as
940 given because the resulting set is not inert. Hence we have to do a
941 'solveInteract' step first.
943 Finally, note that we convert them to [Given] and NOT [Given/Solved].
944 The reason is that Given/Solved are weaker than Givens and may be discarded.
945 As an example consider the inference case, where we may have, the following
946 original constraints:
948 (F Int ~ a => F Int ~ a)
949 If we convert F Int ~ Int to [Given/Solved] instead of Given, then the next
950 given (F Int ~ a) is going to cause the Given/Solved to be ignored, casting
951 the (F Int ~ a) insoluble. Hence we should really convert the residual
952 wanteds to plain old Given.
954 We need only push in unsolved equalities both in checking mode and inference mode:
956 (1) In checking mode we should not push given dictionaries in because of
957 example LongWayOverlapping.hs, where we might get strange overlap
958 errors between far-away constraints in the program. But even in
959 checking mode, we must still push type family equations. Consider:
961 type instance F True a b = a
962 type instance F False a b = b
965 (c ~ True) => a ~ gamma
966 (c ~ False) => b ~ gamma
968 Since solveCTyFunEqs happens at the very end of solving, the only way to solve
969 the two implications is temporarily consider (F c a b ~ gamma) as Given (NB: not
970 merely Given/Solved because it has to interact with the top-level instance
971 environment) and push it inside the implications. Now, when we come out again at
972 the end, having solved the implications solveCTyFunEqs will solve this equality.
974 (2) In inference mode, we recheck the final constraint in checking mode and
975 hence we will be able to solve inner implications from top-level quantified
976 constraints nonetheless.
979 Note [Extra TcsTv untouchables]
980 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
981 Furthemore, we record the inert set simplifier-generated unification
982 variables of the TcsTv kind (such as variables from instance that have
983 been applied, or unification flattens). These variables must be passed
984 to the implications as extra untouchable variables. Otherwise we have
985 the danger of double unifications. Example (from trac ticket #4494):
987 (F Int ~ uf) /\ (forall a. C a => F Int ~ beta)
989 In this example, beta is touchable inside the implication. The first
990 solveInteract step leaves 'uf' ununified. Then we move inside the
991 implication where a new constraint
993 emerges. We may spontaneously solve it to get uf := beta, so the whole
994 implication disappears but when we pop out again we are left with (F
995 Int ~ uf) which will be unified by our final solveCTyFunEqs stage and
996 uf will get unified *once more* to (F Int).
998 The solution is to record the TcsTvs (i.e. the simplifier-generated
999 unification variables) that are generated when solving the flats, and
1000 make them untouchables for the nested implication. In the example
1001 above uf would become untouchable, so beta would be forced to be
1002 unified as beta := uf.
1004 NB: A consequence is that every simplifier-generated TcsTv variable
1005 that gets floated out of an implication becomes now untouchable
1006 next time we go inside that implication to solve any residual
1007 constraints. In effect, by floating an equality out of the
1008 implication we are committing to have it solved in the outside.
1010 Note [Float Equalities out of Implications]
1011 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1012 We want to float equalities out of vanilla existentials, but *not* out
1013 of GADT pattern matches.
1018 solveCTyFunEqs :: CanonicalCts -> TcS (TvSubst, CanonicalCts)
1019 -- Default equalities (F xi ~ alpha) by setting (alpha := F xi), whenever possible
1020 -- See Note [Solving Family Equations]
1021 -- Returns: a bunch of unsolved constraints from the original CanonicalCts and implications
1022 -- where the newly generated equalities (alpha := F xi) have been substituted through.
1024 = do { untch <- getUntouchables
1025 ; let (unsolved_can_cts, (ni_subst, cv_binds))
1026 = getSolvableCTyFunEqs untch cts
1027 ; traceTcS "defaultCTyFunEqs" (vcat [text "Trying to default family equations:"
1028 , ppr ni_subst, ppr cv_binds
1030 ; mapM_ solve_one cv_binds
1032 ; return (niFixTvSubst ni_subst, unsolved_can_cts) }
1034 solve_one (cv,tv,ty) = do { setWantedTyBind tv ty
1035 ; setCoBind cv (mkReflCo ty) }
1038 type FunEqBinds = (TvSubstEnv, [(CoVar, TcTyVar, TcType)])
1039 -- The TvSubstEnv is not idempotent, but is loop-free
1040 -- See Note [Non-idempotent substitution] in Unify
1041 emptyFunEqBinds :: FunEqBinds
1042 emptyFunEqBinds = (emptyVarEnv, [])
1044 extendFunEqBinds :: FunEqBinds -> CoVar -> TcTyVar -> TcType -> FunEqBinds
1045 extendFunEqBinds (tv_subst, cv_binds) cv tv ty
1046 = (extendVarEnv tv_subst tv ty, (cv, tv, ty):cv_binds)
1049 getSolvableCTyFunEqs :: TcsUntouchables
1050 -> CanonicalCts -- Precondition: all Wanteds or Derived!
1051 -> (CanonicalCts, FunEqBinds) -- Postcondition: returns the unsolvables
1052 getSolvableCTyFunEqs untch cts
1053 = Bag.foldlBag dflt_funeq (emptyCCan, emptyFunEqBinds) cts
1055 dflt_funeq :: (CanonicalCts, FunEqBinds) -> CanonicalCt
1056 -> (CanonicalCts, FunEqBinds)
1057 dflt_funeq (cts_in, feb@(tv_subst, _))
1058 (CFunEqCan { cc_id = cv
1063 | Just tv <- tcGetTyVar_maybe xi -- RHS is a type variable
1065 , isTouchableMetaTyVar_InRange untch tv
1066 -- And it's a *touchable* unification variable
1068 , typeKind xi `isSubKind` tyVarKind tv
1069 -- Must do a small kind check since TcCanonical invariants
1070 -- on family equations only impose compatibility, not subkinding
1072 , not (tv `elemVarEnv` tv_subst)
1073 -- Check not in extra_binds
1074 -- See Note [Solving Family Equations], Point 1
1076 , not (tv `elemVarSet` niSubstTvSet tv_subst (tyVarsOfTypes xis))
1077 -- Occurs check: see Note [Solving Family Equations], Point 2
1078 = ASSERT ( not (isGivenOrSolved fl) )
1079 (cts_in, extendFunEqBinds feb cv tv (mkTyConApp tc xis))
1081 dflt_funeq (cts_in, fun_eq_binds) ct
1082 = (cts_in `extendCCans` ct, fun_eq_binds)
1085 Note [Solving Family Equations]
1086 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1087 After we are done with simplification we may be left with constraints of the form:
1088 [Wanted] F xis ~ beta
1089 If 'beta' is a touchable unification variable not already bound in the TyBinds
1090 then we'd like to create a binding for it, effectively "defaulting" it to be 'F xis'.
1092 When is it ok to do so?
1093 1) 'beta' must not already be defaulted to something. Example:
1095 [Wanted] F Int ~ beta <~ Will default [beta := F Int]
1096 [Wanted] F Char ~ beta <~ Already defaulted, can't default again. We
1097 have to report this as unsolved.
1099 2) However, we must still do an occurs check when defaulting (F xis ~ beta), to
1100 set [beta := F xis] only if beta is not among the free variables of xis.
1102 3) Notice that 'beta' can't be bound in ty binds already because we rewrite RHS
1103 of type family equations. See Inert Set invariants in TcInteract.
1106 *********************************************************************************
1108 * Defaulting and disamgiguation *
1110 *********************************************************************************
1112 Basic plan behind applyDefaulting rules:
1115 Split wanteds into defaultable groups, `groups' and the rest `rest_wanted'
1116 For each defaultable group, do:
1117 For each possible substitution for [alpha |-> tau] where `alpha' is the
1118 group's variable, do:
1119 1) Make up new TcEvBinds
1120 2) Extend TcS with (groupVariable
1121 3) given_inert <- solveOne inert (given : a ~ tau)
1122 4) (final_inert,unsolved) <- solveWanted (given_inert) (group_constraints)
1123 5) if unsolved == empty then
1124 sneakyUnify a |-> tau
1125 write the evidence bins
1126 return (final_inert ++ group_constraints,[])
1127 -- will contain the info (alpha |-> tau)!!
1128 goto next defaultable group
1129 if unsolved <> empty then
1130 throw away evidence binds
1131 try next substitution
1132 If you've run out of substitutions for this group, too bad, you failed
1133 return (inert,group)
1134 goto next defaultable group
1137 Collect all the (canonical-cts, wanteds) gathered this way.
1138 - Do a solveGiven over the canonical-cts to make sure they are inert
1139 ------------------------------------------------------------------------------------------
1143 applyDefaultingRules :: InertSet
1144 -> CanonicalCts -- All wanteds
1145 -> TcS (Bag FlavoredEvVar) -- All wanteds again!
1146 -- Return some *extra* givens, which express the
1147 -- type-class-default choice
1149 applyDefaultingRules inert wanteds
1150 | isEmptyBag wanteds
1153 = do { untch <- getUntouchables
1154 ; tv_cts <- mapM (defaultTyVar untch) $
1155 varSetElems (tyVarsOfCDicts wanteds)
1157 ; info@(_, default_tys, _) <- getDefaultInfo
1158 ; let groups = findDefaultableGroups info untch wanteds
1159 ; deflt_cts <- mapM (disambigGroup default_tys inert) groups
1161 ; traceTcS "deflt2" (vcat [ text "Tyvar defaults =" <+> ppr tv_cts
1162 , text "Type defaults =" <+> ppr deflt_cts])
1164 ; return (unionManyBags deflt_cts `unionBags` unionManyBags tv_cts) }
1167 defaultTyVar :: TcsUntouchables -> TcTyVar -> TcS (Bag FlavoredEvVar)
1168 -- defaultTyVar is used on any un-instantiated meta type variables to
1169 -- default the kind of ? and ?? etc to *. This is important to ensure
1170 -- that instance declarations match. For example consider
1171 -- instance Show (a->b)
1172 -- foo x = show (\_ -> True)
1173 -- Then we'll get a constraint (Show (p ->q)) where p has argTypeKind (printed ??),
1174 -- and that won't match the typeKind (*) in the instance decl.
1177 -- We look only at touchable type variables. No further constraints
1178 -- are going to affect these type variables, so it's time to do it by
1179 -- hand. However we aren't ready to default them fully to () or
1180 -- whatever, because the type-class defaulting rules have yet to run.
1182 defaultTyVar untch the_tv
1183 | isTouchableMetaTyVar_InRange untch the_tv
1184 , not (k `eqKind` default_k)
1185 = do { ev <- TcSMonad.newKindConstraint the_tv default_k
1186 ; let loc = CtLoc DefaultOrigin (getSrcSpan the_tv) [] -- Yuk
1187 ; return (unitBag (mkEvVarX ev (Wanted loc))) }
1189 = return emptyBag -- The common case
1191 k = tyVarKind the_tv
1192 default_k = defaultKind k
1196 findDefaultableGroups
1199 , (Bool,Bool) ) -- (Overloaded strings, extended default rules)
1200 -> TcsUntouchables -- Untouchable
1201 -> CanonicalCts -- Unsolved
1202 -> [[(CanonicalCt,TcTyVar)]]
1203 findDefaultableGroups (ctxt, default_tys, (ovl_strings, extended_defaults))
1205 | not (performDefaulting ctxt) = []
1206 | null default_tys = []
1207 | otherwise = filter is_defaultable_group (equivClasses cmp_tv unaries)
1209 unaries :: [(CanonicalCt, TcTyVar)] -- (C tv) constraints
1210 non_unaries :: [CanonicalCt] -- and *other* constraints
1212 (unaries, non_unaries) = partitionWith find_unary (bagToList wanteds)
1213 -- Finds unary type-class constraints
1214 find_unary cc@(CDictCan { cc_tyargs = [ty] })
1215 | Just tv <- tcGetTyVar_maybe ty
1217 find_unary cc = Right cc -- Non unary or non dictionary
1219 bad_tvs :: TcTyVarSet -- TyVars mentioned by non-unaries
1220 bad_tvs = foldr (unionVarSet . tyVarsOfCanonical) emptyVarSet non_unaries
1222 cmp_tv (_,tv1) (_,tv2) = tv1 `compare` tv2
1224 is_defaultable_group ds@((_,tv):_)
1225 = isTyConableTyVar tv -- Note [Avoiding spurious errors]
1226 && not (tv `elemVarSet` bad_tvs)
1227 && isTouchableMetaTyVar_InRange untch tv
1228 && defaultable_classes [cc_class cc | (cc,_) <- ds]
1229 is_defaultable_group [] = panic "defaultable_group"
1231 defaultable_classes clss
1232 | extended_defaults = any isInteractiveClass clss
1233 | otherwise = all is_std_class clss && (any is_num_class clss)
1235 -- In interactive mode, or with -XExtendedDefaultRules,
1236 -- we default Show a to Show () to avoid graututious errors on "show []"
1237 isInteractiveClass cls
1238 = is_num_class cls || (classKey cls `elem` [showClassKey, eqClassKey, ordClassKey])
1240 is_num_class cls = isNumericClass cls || (ovl_strings && (cls `hasKey` isStringClassKey))
1241 -- is_num_class adds IsString to the standard numeric classes,
1242 -- when -foverloaded-strings is enabled
1244 is_std_class cls = isStandardClass cls || (ovl_strings && (cls `hasKey` isStringClassKey))
1245 -- Similarly is_std_class
1247 ------------------------------
1248 disambigGroup :: [Type] -- The default types
1249 -> InertSet -- Given inert
1250 -> [(CanonicalCt, TcTyVar)] -- All classes of the form (C a)
1251 -- sharing same type variable
1252 -> TcS (Bag FlavoredEvVar)
1254 disambigGroup [] _inert _grp
1256 disambigGroup (default_ty:default_tys) inert group
1257 = do { traceTcS "disambigGroup" (ppr group $$ ppr default_ty)
1258 ; ev <- TcSMonad.newCoVar (mkTyVarTy the_tv) default_ty
1259 ; let der_flav = mk_derived_flavor (cc_flavor the_ct)
1260 derived_eq = mkEvVarX ev der_flav
1262 ; success <- tryTcS $
1263 do { (_,final_inert) <- solveInteract inert $ listToBag $
1264 derived_eq : wanted_ev_vars
1265 ; let (_, unsolved) = extractUnsolved final_inert
1266 ; let wanted_unsolved = filterBag isWantedCt unsolved
1267 -- Don't care about Derived's
1268 ; return (isEmptyBag wanted_unsolved) }
1270 True -> -- Success: record the type variable binding, and return
1271 do { wrapWarnTcS $ warnDefaulting wanted_ev_vars default_ty
1272 ; traceTcS "disambigGroup succeeded" (ppr default_ty)
1273 ; return (unitBag derived_eq) }
1274 False -> -- Failure: try with the next type
1275 do { traceTcS "disambigGroup failed, will try other default types"
1277 ; disambigGroup default_tys inert group } }
1279 ((the_ct,the_tv):_) = group
1280 wanteds = map fst group
1281 wanted_ev_vars :: [FlavoredEvVar]
1282 wanted_ev_vars = map deCanonicalise wanteds
1284 mk_derived_flavor :: CtFlavor -> CtFlavor
1285 mk_derived_flavor (Wanted loc) = Derived loc
1286 mk_derived_flavor _ = panic "Asked to disambiguate given or derived!"
1289 Note [Avoiding spurious errors]
1290 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1291 When doing the unification for defaulting, we check for skolem
1292 type variables, and simply don't default them. For example:
1293 f = (*) -- Monomorphic
1294 g :: Num a => a -> a
1296 Here, we get a complaint when checking the type signature for g,
1297 that g isn't polymorphic enough; but then we get another one when
1298 dealing with the (Num a) context arising from f's definition;
1299 we try to unify a with Int (to default it), but find that it's
1300 already been unified with the rigid variable from g's type sig
1304 *********************************************************************************
1308 *********************************************************************************
1311 newFlatWanteds :: CtOrigin -> ThetaType -> TcM (Bag WantedEvVar)
1312 newFlatWanteds orig theta
1313 = do { loc <- getCtLoc orig
1314 ; evs <- newWantedEvVars theta
1315 ; return (listToBag [EvVarX w loc | w <- evs]) }