2 {-# OPTIONS -fno-warn-tabs #-}
3 -- The above warning supression flag is a temporary kludge.
4 -- While working on this module you are encouraged to remove it and
5 -- detab the module (please do the detabbing in a separate patch). See
6 -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#TabsvsSpaces
10 simplifyInfer, simplifyAmbiguityCheck,
11 simplifyDefault, simplifyDeriv,
12 simplifyRule, simplifyTop, simplifyInteractive
15 #include "HsVersions.h"
24 import Unify ( niFixTvSubst, niSubstTvSet )
25 import Type ( classifyPredType, PredTree(..), isIPPred_maybe )
38 import Class ( classKey )
39 import BasicTypes ( RuleName )
40 import Control.Monad ( when )
43 import TrieMap () -- DV: for now
45 import Data.Maybe ( mapMaybe )
49 *********************************************************************************
51 * External interface *
53 *********************************************************************************
59 simplifyTop :: WantedConstraints -> TcM (Bag EvBind)
60 -- Simplify top-level constraints
61 -- Usually these will be implications,
62 -- but when there is nothing to quantify we don't wrap
63 -- in a degenerate implication, so we do that here instead
65 = do { ev_binds_var <- newTcEvBinds
67 ; zonked_wanteds <- zonkWC wanteds
68 ; wc_first_go <- solveWantedsWithEvBinds ev_binds_var zonked_wanteds
69 ; cts <- applyTyVarDefaulting wc_first_go
70 -- See Note [Top-level Defaulting Plan]
72 ; let wc_for_loop = wc_first_go { wc_flat = wc_flat wc_first_go `unionBags` cts }
74 ; traceTc "simpl_top_loop {" $ text "zonked_wc =" <+> ppr zonked_wanteds
75 ; simpl_top_loop ev_binds_var wc_for_loop }
77 where simpl_top_loop ev_binds_var wc
79 = do { traceTc "simpl_top_loop }" empty
80 ; TcRnMonad.getTcEvBinds ev_binds_var }
82 = do { wc_residual <- solveWantedsWithEvBinds ev_binds_var wc
83 ; let wc_flat_approximate = approximateWC wc_residual
84 ; (dflt_eqs,_unused_bind) <- runTcS $
85 applyDefaultingRules wc_flat_approximate
86 -- See Note [Top-level Defaulting Plan]
87 ; if isEmptyBag dflt_eqs then
88 do { traceTc "simpl_top_loop }" empty
89 ; report_and_finish ev_binds_var wc_residual }
91 simpl_top_loop ev_binds_var $
92 wc_residual { wc_flat = wc_flat wc_residual `unionBags` dflt_eqs } }
94 report_and_finish ev_binds_var wc_residual
95 = do { eb1 <- TcRnMonad.getTcEvBinds ev_binds_var
96 ; traceTc "reportUnsolved {" empty
97 -- See Note [Deferring coercion errors to runtime]
98 ; runtimeCoercionErrors <- doptM Opt_DeferTypeErrors
99 ; eb2 <- reportUnsolved runtimeCoercionErrors wc_residual
100 ; traceTc "reportUnsolved }" empty
101 ; return (eb1 `unionBags` eb2) }
104 Note [Top-level Defaulting Plan]
105 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
107 We have considered two design choices for where/when to apply defaulting.
108 (i) Do it in SimplCheck mode only /whenever/ you try to solve some
109 flat constraints, maybe deep inside the context of implications.
110 This used to be the case in GHC 7.4.1.
111 (ii) Do it in a tight loop at simplifyTop, once all other constraint has
112 finished. This is the current story.
114 Option (i) had many disadvantages:
115 a) First it was deep inside the actual solver,
116 b) Second it was dependent on the context (Infer a type signature,
117 or Check a type signature, or Interactive) since we did not want
118 to always start defaulting when inferring (though there is an exception to
119 this see Note [Default while Inferring])
120 c) It plainly did not work. Consider typecheck/should_compile/DfltProb2.hs:
122 f x = const True (\y -> let w :: a -> a
125 We will get an implication constraint (for beta the type of y):
126 [untch=beta] forall a. 0 => Num beta
127 which we really cannot default /while solving/ the implication, since beta is
130 Instead our new defaulting story is to pull defaulting out of the solver loop and
131 go with option (i), implemented at SimplifyTop. Namely:
132 - First have a go at solving the residual constraint of the whole program
133 - Try to approximate it with a flat constraint
134 - Figure out derived defaulting equations for that flat constraint
135 - Go round the loop again if you did manage to get some equations
137 Now, that has to do with class defaulting. However there exists type variable /kind/
138 defaulting. Again this is done at the top-level and the plan is:
139 - At the top-level, once you had a go at solving the constraint, do
140 figure out /all/ the touchable unification variables of the wanted contraints.
141 - Apply defaulting to their kinds
143 More details in Note [DefaultTyVar].
148 simplifyAmbiguityCheck :: Name -> WantedConstraints -> TcM (Bag EvBind)
149 simplifyAmbiguityCheck name wanteds
150 = traceTc "simplifyAmbiguityCheck" (text "name =" <+> ppr name) >>
151 simplifyCheck wanteds
154 simplifyInteractive :: WantedConstraints -> TcM (Bag EvBind)
155 simplifyInteractive wanteds
156 = traceTc "simplifyInteractive" empty >>
160 simplifyDefault :: ThetaType -- Wanted; has no type variables in it
161 -> TcM () -- Succeeds iff the constraint is soluble
162 simplifyDefault theta
163 = do { traceTc "simplifyInteractive" empty
164 ; wanted <- newFlatWanteds DefaultOrigin theta
165 ; _ignored_ev_binds <- simplifyCheck (mkFlatWC wanted)
170 ***********************************************************************************
174 ***********************************************************************************
177 simplifyDeriv :: CtOrigin
180 -> ThetaType -- Wanted
181 -> TcM ThetaType -- Needed
182 -- Given instance (wanted) => C inst_ty
183 -- Simplify 'wanted' as much as possibles
184 -- Fail if not possible
185 simplifyDeriv orig pred tvs theta
186 = do { (skol_subst, tvs_skols) <- tcInstSkolTyVars tvs -- Skolemize
187 -- The constraint solving machinery
188 -- expects *TcTyVars* not TyVars.
189 -- We use *non-overlappable* (vanilla) skolems
190 -- See Note [Overlap and deriving]
192 ; let subst_skol = zipTopTvSubst tvs_skols $ map mkTyVarTy tvs
193 skol_set = mkVarSet tvs_skols
194 doc = ptext (sLit "deriving") <+> parens (ppr pred)
196 ; wanted <- newFlatWanteds orig (substTheta skol_subst theta)
198 ; traceTc "simplifyDeriv" $
199 vcat [ pprTvBndrs tvs $$ ppr theta $$ ppr wanted, doc ]
200 ; (residual_wanted, _ev_binds1)
201 <- solveWanteds (mkFlatWC wanted)
203 ; let (good, bad) = partitionBagWith get_good (wc_flat residual_wanted)
204 -- See Note [Exotic derived instance contexts]
205 get_good :: Ct -> Either PredType Ct
206 get_good ct | validDerivPred skol_set p
207 , isWantedCt ct = Left p
208 -- NB: residual_wanted may contain unsolved
209 -- Derived and we stick them into the bad set
210 -- so that reportUnsolved may decide what to do with them
211 | otherwise = Right ct
214 -- We never want to defer these errors because they are errors in the
215 -- compiler! Hence the `False` below
216 ; _ev_binds2 <- reportUnsolved False (residual_wanted { wc_flat = bad })
218 ; let min_theta = mkMinimalBySCs (bagToList good)
219 ; return (substTheta subst_skol min_theta) }
222 Note [Overlap and deriving]
223 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
224 Consider some overlapping instances:
225 data Show a => Show [a] where ..
226 data Show [Char] where ...
228 Now a data type with deriving:
229 data T a = MkT [a] deriving( Show )
231 We want to get the derived instance
232 instance Show [a] => Show (T a) where...
234 instance Show a => Show (T a) where...
235 so that the (Show (T Char)) instance does the Right Thing
237 It's very like the situation when we're inferring the type
241 f :: Show [a] => a -> String
243 BOTTOM LINE: use vanilla, non-overlappable skolems when inferring
244 the context for the derived instance.
245 Hence tcInstSkolTyVars not tcInstSuperSkolTyVars
247 Note [Exotic derived instance contexts]
248 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
249 In a 'derived' instance declaration, we *infer* the context. It's a
250 bit unclear what rules we should apply for this; the Haskell report is
251 silent. Obviously, constraints like (Eq a) are fine, but what about
252 data T f a = MkT (f a) deriving( Eq )
253 where we'd get an Eq (f a) constraint. That's probably fine too.
255 One could go further: consider
256 data T a b c = MkT (Foo a b c) deriving( Eq )
257 instance (C Int a, Eq b, Eq c) => Eq (Foo a b c)
259 Notice that this instance (just) satisfies the Paterson termination
260 conditions. Then we *could* derive an instance decl like this:
262 instance (C Int a, Eq b, Eq c) => Eq (T a b c)
263 even though there is no instance for (C Int a), because there just
264 *might* be an instance for, say, (C Int Bool) at a site where we
265 need the equality instance for T's.
267 However, this seems pretty exotic, and it's quite tricky to allow
268 this, and yet give sensible error messages in the (much more common)
269 case where we really want that instance decl for C.
271 So for now we simply require that the derived instance context
272 should have only type-variable constraints.
274 Here is another example:
275 data Fix f = In (f (Fix f)) deriving( Eq )
276 Here, if we are prepared to allow -XUndecidableInstances we
277 could derive the instance
278 instance Eq (f (Fix f)) => Eq (Fix f)
279 but this is so delicate that I don't think it should happen inside
280 'deriving'. If you want this, write it yourself!
282 NB: if you want to lift this condition, make sure you still meet the
283 termination conditions! If not, the deriving mechanism generates
284 larger and larger constraints. Example:
286 data Seq a = Cons a (Seq (Succ a)) | Nil deriving Show
288 Note the lack of a Show instance for Succ. First we'll generate
289 instance (Show (Succ a), Show a) => Show (Seq a)
291 instance (Show (Succ (Succ a)), Show (Succ a), Show a) => Show (Seq a)
292 and so on. Instead we want to complain of no instance for (Show (Succ a)).
296 Allow constraints which consist only of type variables, with no repeats.
298 *********************************************************************************
302 ***********************************************************************************
304 Note [Which variables to quantify]
305 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
306 Suppose the inferred type of a function is
307 T kappa (alpha:kappa) -> Int
308 where alpha is a type unification variable and
309 kappa is a kind unification variable
310 Then we want to quantify over *both* alpha and kappa. But notice that
311 kappa appears "at top level" of the type, as well as inside the kind
312 of alpha. So it should be fine to just look for the "top level"
313 kind/type variables of the type, without looking transitively into the
314 kinds of those type variables.
317 simplifyInfer :: Bool
318 -> Bool -- Apply monomorphism restriction
319 -> [(Name, TcTauType)] -- Variables to be generalised,
320 -- and their tau-types
321 -> (Untouchables, WantedConstraints)
322 -> TcM ([TcTyVar], -- Quantify over these type variables
323 [EvVar], -- ... and these constraints
324 Bool, -- The monomorphism restriction did something
325 -- so the results type is not as general as
327 TcEvBinds) -- ... binding these evidence variables
328 simplifyInfer _top_lvl apply_mr name_taus (untch,wanteds)
330 = do { gbl_tvs <- tcGetGlobalTyVars -- Already zonked
331 ; zonked_taus <- zonkTcTypes (map snd name_taus)
332 ; let tvs_to_quantify = varSetElems (tyVarsOfTypes zonked_taus `minusVarSet` gbl_tvs)
333 -- tvs_to_quantify can contain both kind and type vars
334 -- See Note [Which variables to quantify]
335 ; qtvs <- zonkQuantifiedTyVars tvs_to_quantify
336 ; return (qtvs, [], False, emptyTcEvBinds) }
339 = do { runtimeCoercionErrors <- doptM Opt_DeferTypeErrors
340 ; gbl_tvs <- tcGetGlobalTyVars
341 ; zonked_tau_tvs <- zonkTyVarsAndFV (tyVarsOfTypes (map snd name_taus))
342 ; zonked_wanteds <- zonkWC wanteds
344 ; traceTc "simplifyInfer {" $ vcat
345 [ ptext (sLit "names =") <+> ppr (map fst name_taus)
346 , ptext (sLit "taus =") <+> ppr (map snd name_taus)
347 , ptext (sLit "tau_tvs (zonked) =") <+> ppr zonked_tau_tvs
348 , ptext (sLit "gbl_tvs =") <+> ppr gbl_tvs
349 , ptext (sLit "closed =") <+> ppr _top_lvl
350 , ptext (sLit "apply_mr =") <+> ppr apply_mr
351 , ptext (sLit "untch =") <+> ppr untch
352 , ptext (sLit "wanted =") <+> ppr zonked_wanteds
355 -- Historical note: Before step 2 we used to have a
356 -- HORRIBLE HACK described in Note [Avoid unecessary
357 -- constraint simplification] but, as described in Trac
358 -- #4361, we have taken in out now. That's why we start
361 -- Step 2) First try full-blown solving
363 -- NB: we must gather up all the bindings from doing
364 -- this solving; hence (runTcSWithEvBinds ev_binds_var).
365 -- And note that since there are nested implications,
366 -- calling solveWanteds will side-effect their evidence
367 -- bindings, so we can't just revert to the input
369 ; ev_binds_var <- newTcEvBinds
370 ; wanted_transformed <- solveWantedsWithEvBinds ev_binds_var zonked_wanteds
372 -- Step 3) Fail fast if there is an insoluble constraint,
373 -- unless we are deferring errors to runtime
374 ; when (not runtimeCoercionErrors && insolubleWC wanted_transformed) $
375 do { _ev_binds <- reportUnsolved False wanted_transformed; failM }
377 -- Step 4) Candidates for quantification are an approximation of wanted_transformed
378 ; let quant_candidates = approximateWC wanted_transformed
379 -- NB: Already the fixpoint of any unifications that may have happened
380 -- NB: We do not do any defaulting when inferring a type, this can lead
381 -- to less polymorphic types, see Note [Default while Inferring]
382 -- NB: quant_candidates here are wanted or derived, we filter the wanteds later, anyway
384 -- Step 5) Minimize the quantification candidates
385 ; (quant_candidates_transformed, _extra_binds)
386 <- solveWanteds $ WC { wc_flat = quant_candidates
388 , wc_insol = emptyBag }
390 -- Step 6) Final candidates for quantification
391 ; let final_quant_candidates :: Bag PredType
392 final_quant_candidates = mapBag ctPred $
393 keepWanted (wc_flat quant_candidates_transformed)
394 -- NB: Already the fixpoint of any unifications that may have happened
396 ; gbl_tvs <- tcGetGlobalTyVars -- TODO: can we just use untch instead of gbl_tvs?
397 ; zonked_tau_tvs <- zonkTyVarsAndFV zonked_tau_tvs
399 ; traceTc "simplifyWithApprox" $
400 vcat [ ptext (sLit "final_quant_candidates =") <+> ppr final_quant_candidates
401 , ptext (sLit "gbl_tvs=") <+> ppr gbl_tvs
402 , ptext (sLit "zonked_tau_tvs=") <+> ppr zonked_tau_tvs ]
404 ; let init_tvs = zonked_tau_tvs `minusVarSet` gbl_tvs
405 poly_qtvs = growPreds gbl_tvs id final_quant_candidates init_tvs
407 pbound = filterBag (quantifyMe poly_qtvs id) final_quant_candidates
409 ; traceTc "simplifyWithApprox" $
410 vcat [ ptext (sLit "pbound =") <+> ppr pbound ]
412 -- Monomorphism restriction
413 ; let mr_qtvs = init_tvs `minusVarSet` constrained_tvs
414 constrained_tvs = tyVarsOfBag tyVarsOfType final_quant_candidates
415 mr_bites = apply_mr && not (isEmptyBag pbound)
418 | mr_bites = (mr_qtvs, emptyBag)
419 | otherwise = (poly_qtvs, pbound)
422 ; if isEmptyVarSet qtvs && isEmptyBag bound
423 then do { traceTc "} simplifyInfer/no quantification" empty
424 ; emitConstraints wanted_transformed
425 -- Includes insolubles (if -fdefer-type-errors)
426 -- as well as flats and implications
427 ; return ([], [], mr_bites, TcEvBinds ev_binds_var) }
430 { traceTc "simplifyApprox" $
431 ptext (sLit "bound are =") <+> ppr bound
433 -- Step 4, zonk quantified variables
434 ; let minimal_flat_preds = mkMinimalBySCs $ bagToList bound
435 skol_info = InferSkol [ (name, mkSigmaTy [] minimal_flat_preds ty)
436 | (name, ty) <- name_taus ]
437 -- Don't add the quantified variables here, because
438 -- they are also bound in ic_skols and we want them to be
441 ; qtvs_to_return <- zonkQuantifiedTyVars (varSetElems qtvs)
443 -- Step 7) Emit an implication
444 ; minimal_bound_ev_vars <- mapM TcMType.newEvVar minimal_flat_preds
445 ; lcl_env <- getLclTypeEnv
446 ; gloc <- getCtLoc skol_info
447 ; let implic = Implic { ic_untch = untch
449 , ic_skols = qtvs_to_return
450 , ic_given = minimal_bound_ev_vars
451 , ic_wanted = wanted_transformed
453 , ic_binds = ev_binds_var
455 ; emitImplication implic
457 ; traceTc "} simplifyInfer/produced residual implication for quantification" $
458 vcat [ ptext (sLit "implic =") <+> ppr implic
459 -- ic_skols, ic_given give rest of result
460 , ptext (sLit "qtvs =") <+> ppr qtvs_to_return
461 , ptext (sLit "spb =") <+> ppr final_quant_candidates
462 , ptext (sLit "bound =") <+> ppr bound ]
464 ; return ( qtvs_to_return, minimal_bound_ev_vars
465 , mr_bites, TcEvBinds ev_binds_var) } }
470 Note [Note [Default while Inferring]
471 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
472 Our current plan is that defaulting only happens at simplifyTop and
473 not simplifyInfer. This may lead to some insoluble deferred constraints
476 instance D g => C g Int b
478 constraint inferred = (forall b. 0 => C gamma alpha b) /\ Num alpha
479 type inferred = gamma -> gamma
481 Now, if we try to default (alpha := Int) we will be able to refine the implication to
482 (forall b. 0 => C gamma Int b)
483 which can then be simplified further to
484 (forall b. 0 => D gamma)
485 Finally we /can/ approximate this implication with (D gamma) and infer the quantified
486 type: forall g. D g => g -> g
488 Instead what will currently happen is that we will get a quantified type
489 (forall g. g -> g) and an implication:
490 forall g. 0 => (forall b. 0 => C g alpha b) /\ Num alpha
492 which, even if the simplifyTop defaults (alpha := Int) we will still be left with an
493 unsolvable implication:
494 forall g. 0 => (forall b. 0 => D g)
496 The concrete example would be:
497 h :: C g a s => g -> a -> ST s a
498 f (x::gamma) = (\_ -> x) (runST (h x (undefined::alpha)) + 1)
500 But it is quite tedious to do defaulting and resolve the implication constraints and
501 we have not observed code breaking because of the lack of defaulting in inference so
502 we don't do it for now.
506 Note [Minimize by Superclasses]
507 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
509 When we quantify over a constraint, in simplifyInfer we need to
510 quantify over a constraint that is minimal in some sense: For
511 instance, if the final wanted constraint is (Eq alpha, Ord alpha),
512 we'd like to quantify over Ord alpha, because we can just get Eq alpha
513 from superclass selection from Ord alpha. This minimization is what
514 mkMinimalBySCs does. Then, simplifyInfer uses the minimal constraint
515 to check the original wanted.
521 approximateWC :: WantedConstraints -> Cts
522 -- Postcondition: Wanted or Derived Cts
523 approximateWC wc = float_wc emptyVarSet wc
525 float_wc :: TcTyVarSet -> WantedConstraints -> Cts
526 float_wc skols (WC { wc_flat = flat, wc_impl = implic }) = floats1 `unionBags` floats2
527 where floats1 = do_bag (float_flat skols) flat
528 floats2 = do_bag (float_implic skols) implic
530 float_implic :: TcTyVarSet -> Implication -> Cts
531 float_implic skols imp
532 = float_wc (skols `extendVarSetList` ic_skols imp) (ic_wanted imp)
534 float_flat :: TcTyVarSet -> Ct -> Cts
536 | tyVarsOfCt ct `disjointVarSet` skols
538 | otherwise = emptyCts
540 do_bag :: (a -> Bag c) -> Bag a -> Bag c
541 do_bag f = foldrBag (unionBags.f) emptyBag
547 growPreds :: TyVarSet -> (a -> PredType) -> Bag a -> TyVarSet -> TyVarSet
548 growPreds gbl_tvs get_pred items tvs
549 = foldrBag extend tvs items
551 extend item tvs = tvs `unionVarSet`
552 (growPredTyVars (get_pred item) tvs `minusVarSet` gbl_tvs)
555 quantifyMe :: TyVarSet -- Quantifying over these
557 -> a -> Bool -- True <=> quantify over this wanted
558 quantifyMe qtvs toPred ct
559 | isIPPred pred = True -- Note [Inheriting implicit parameters]
560 | otherwise = tyVarsOfType pred `intersectsVarSet` qtvs
565 Note [Avoid unecessary constraint simplification]
566 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
567 -------- NB NB NB (Jun 12) -------------
568 This note not longer applies; see the notes with Trac #4361.
569 But I'm leaving it in here so we remember the issue.)
570 ----------------------------------------
571 When inferring the type of a let-binding, with simplifyInfer,
572 try to avoid unnecessarily simplifying class constraints.
573 Doing so aids sharing, but it also helps with delicate
576 instance C t => C [t] where ..
579 f x = let g y = ...(constraint C [t])...
581 When inferring a type for 'g', we don't want to apply the
582 instance decl, because then we can't satisfy (C t). So we
583 just notice that g isn't quantified over 't' and partition
584 the contraints before simplifying.
586 This only half-works, but then let-generalisation only half-works.
589 Note [Inheriting implicit parameters]
590 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
595 where f is *not* a top-level binding.
596 From the RHS of f we'll get the constraint (?y::Int).
597 There are two types we might infer for f:
601 (so we get ?y from the context of f's definition), or
603 f :: (?y::Int) => Int -> Int
605 At first you might think the first was better, becuase then
606 ?y behaves like a free variable of the definition, rather than
607 having to be passed at each call site. But of course, the WHOLE
608 IDEA is that ?y should be passed at each call site (that's what
609 dynamic binding means) so we'd better infer the second.
611 BOTTOM LINE: when *inferring types* you *must* quantify
612 over implicit parameters. See the predicate isFreeWhenInferring.
615 *********************************************************************************
619 ***********************************************************************************
621 See note [Simplifying RULE consraints] in TcRule
623 Note [RULE quanfification over equalities]
624 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
625 Decideing which equalities to quantify over is tricky:
626 * We do not want to quantify over insoluble equalities (Int ~ Bool)
627 (a) because we prefer to report a LHS type error
628 (b) because if such things end up in 'givens' we get a bogus
629 "inaccessible code" error
631 * But we do want to quantify over things like (a ~ F b), where
632 F is a type function.
634 The difficulty is that it's hard to tell what is insoluble!
635 So we see whether the simplificaiotn step yielded any type errors,
636 and if so refrain from quantifying over *any* equalites.
639 simplifyRule :: RuleName
640 -> WantedConstraints -- Constraints from LHS
641 -> WantedConstraints -- Constraints from RHS
642 -> TcM ([EvVar], WantedConstraints) -- LHS evidence varaibles
643 -- See Note [Simplifying RULE constraints] in TcRule
644 simplifyRule name lhs_wanted rhs_wanted
645 = do { zonked_all <- zonkWC (lhs_wanted `andWC` rhs_wanted)
646 ; let doc = ptext (sLit "LHS of rule") <+> doubleQuotes (ftext name)
648 -- We allow ourselves to unify environment
649 -- variables: runTcS runs with NoUntouchables
650 ; (resid_wanted, _) <- solveWanteds zonked_all
652 ; zonked_lhs <- zonkWC lhs_wanted
654 ; let (q_cts, non_q_cts) = partitionBag quantify_me (wc_flat zonked_lhs)
655 quantify_me -- Note [RULE quantification over equalities]
656 | insolubleWC resid_wanted = quantify_insol
657 | otherwise = quantify_normal
659 quantify_insol ct = not (isEqPred (ctPred ct))
662 | EqPred t1 t2 <- classifyPredType (ctPred ct)
663 = not (t1 `eqType` t2)
667 ; traceTc "simplifyRule" $
669 , text "zonked_lhs" <+> ppr zonked_lhs
670 , text "q_cts" <+> ppr q_cts ]
672 ; return ( map (ctEvId . ctEvidence) (bagToList q_cts)
673 , zonked_lhs { wc_flat = non_q_cts }) }
677 *********************************************************************************
681 ***********************************************************************************
684 simplifyCheck :: WantedConstraints -- Wanted
686 -- Solve a single, top-level implication constraint
687 -- e.g. typically one created from a top-level type signature
688 -- f :: forall a. [a] -> [a]
690 -- We do this even if the function has no polymorphism:
694 -- (whereas for *nested* bindings we would not create
695 -- an implication constraint for g at all.)
697 -- Fails if can't solve something in the input wanteds
698 simplifyCheck wanteds
699 = do { wanteds <- zonkWC wanteds
701 ; traceTc "simplifyCheck {" (vcat
702 [ ptext (sLit "wanted =") <+> ppr wanteds ])
704 ; (unsolved, eb1) <- solveWanteds wanteds
706 ; traceTc "simplifyCheck }" $ ptext (sLit "unsolved =") <+> ppr unsolved
708 ; traceTc "reportUnsolved {" empty
709 -- See Note [Deferring coercion errors to runtime]
710 ; runtimeCoercionErrors <- doptM Opt_DeferTypeErrors
711 ; eb2 <- reportUnsolved runtimeCoercionErrors unsolved
712 ; traceTc "reportUnsolved }" empty
714 ; return (eb1 `unionBags` eb2) }
717 Note [Deferring coercion errors to runtime]
718 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
720 While developing, sometimes it is desirable to allow compilation to succeed even
721 if there are type errors in the code. Consider the following case:
730 Even though `a` is ill-typed, it is not used in the end, so if all that we're
731 interested in is `main` it is handy to be able to ignore the problems in `a`.
733 Since we treat type equalities as evidence, this is relatively simple. Whenever
734 we run into a type mismatch in TcUnify, we normally just emit an error. But it
735 is always safe to defer the mismatch to the main constraint solver. If we do
736 that, `a` will get transformed into
744 The constraint solver would realize that `co` is an insoluble constraint, and
745 emit an error with `reportUnsolved`. But we can also replace the right-hand side
746 of `co` with `error "Deferred type error: Int ~ Char"`. This allows the program
747 to compile, and it will run fine unless we evaluate `a`. This is what
748 `deferErrorsToRuntime` does.
750 It does this by keeping track of which errors correspond to which coercion
751 in TcErrors (with ErrEnv). TcErrors.reportTidyWanteds does not print the errors
752 and does not fail if -fwarn-type-errors is on, so that we can continue
753 compilation. The errors are turned into warnings in `reportUnsolved`.
757 solveWanteds :: WantedConstraints -> TcM (WantedConstraints, Bag EvBind)
758 -- Return the evidence binds in the BagEvBinds result
759 solveWanteds wanted = runTcS $ solve_wanteds wanted
761 solveWantedsWithEvBinds :: EvBindsVar -> WantedConstraints -> TcM WantedConstraints
762 -- Side-effect the EvBindsVar argument to add new bindings from solving
763 solveWantedsWithEvBinds ev_binds_var wanted
764 = runTcSWithEvBinds ev_binds_var $ solve_wanteds wanted
767 solve_wanteds :: WantedConstraints -> TcS WantedConstraints
768 -- NB: wc_flats may be wanted /or/ derived now
769 solve_wanteds wanted@(WC { wc_flat = flats, wc_impl = implics, wc_insol = insols })
770 = do { traceTcS "solveWanteds {" (ppr wanted)
772 -- Try the flat bit, including insolubles. Solving insolubles a
773 -- second time round is a bit of a waste but the code is simple
774 -- and the program is wrong anyway.
775 -- Why keepWanted insols? See Note [KeepWanted in SolveWanteds]
776 ; let all_flats = flats `unionBags` keepWanted insols
777 -- DV: Used to be 'keepWanted insols' but just insols is
779 ; impls_from_flats <- solveInteractCts $ bagToList all_flats
781 -- solve_wanteds iterates when it is able to float equalities
782 -- out of one or more of the implications.
783 ; unsolved_implics <- simpl_loop 1 (implics `unionBags` impls_from_flats)
786 ; let insoluble_flats = getInertInsols is
787 unsolved_flats = getInertUnsolved is
789 ; bb <- getTcEvBindsMap
790 ; tb <- getTcSTyBindsMap
792 ; traceTcS "solveWanteds }" $
793 vcat [ text "unsolved_flats =" <+> ppr unsolved_flats
794 , text "unsolved_implics =" <+> ppr unsolved_implics
795 , text "current evbinds =" <+> ppr (evBindMapBinds bb)
796 , text "current tybinds =" <+> vcat (map ppr (varEnvElts tb))
799 ; let wc = WC { wc_flat = unsolved_flats
800 , wc_impl = unsolved_implics
801 , wc_insol = insoluble_flats }
804 ; traceTcS "solveWanteds finished with" $
805 vcat [ text "wc (unflattened) =" <+> ppr wc ]
813 -> TcS (Bag Implication)
816 = traceTcS "solveWanteds: loop!" empty >> return implics
818 = do { (implic_eqs, unsolved_implics) <- solveNestedImplications implics
820 ; let improve_eqs = implic_eqs
821 -- NB: improve_eqs used to contain defaulting equations HERE but
822 -- defaulting now happens only at simplifyTop and not deep inside
823 -- simpl_loop! See Note [Top-level Defaulting Plan]
825 ; unsolved_flats <- getTcSInerts >>= (return . getInertUnsolved)
826 ; traceTcS "solveWanteds: simpl_loop end" $
827 vcat [ text "improve_eqs =" <+> ppr improve_eqs
828 , text "unsolved_flats =" <+> ppr unsolved_flats
829 , text "unsolved_implics =" <+> ppr unsolved_implics ]
832 ; if isEmptyBag improve_eqs then return unsolved_implics
833 else do { impls_from_eqs <- solveInteractCts $ bagToList improve_eqs
834 ; simpl_loop (n+1) (unsolved_implics `unionBags`
838 solveNestedImplications :: Bag Implication
839 -> TcS (Cts, Bag Implication)
840 -- Precondition: the TcS inerts may contain unsolved flats which have
841 -- to be converted to givens before we go inside a nested implication.
842 solveNestedImplications implics
844 = return (emptyBag, emptyBag)
846 = do { inerts <- getTcSInerts
847 ; traceTcS "solveNestedImplications starting, inerts are:" $ ppr inerts
848 ; let (pushed_givens, thinner_inerts) = splitInertsForImplications inerts
850 ; traceTcS "solveNestedImplications starting, more info:" $
851 vcat [ text "original inerts = " <+> ppr inerts
852 , text "pushed_givens = " <+> ppr pushed_givens
853 , text "thinner_inerts = " <+> ppr thinner_inerts ]
855 ; (implic_eqs, unsolved_implics)
856 <- doWithInert thinner_inerts $
857 do { let tcs_untouchables
858 = foldr (unionVarSet . tyVarsOfCt) emptyVarSet pushed_givens
859 -- Typically pushed_givens is very small, consists
860 -- only of unsolved equalities, so no inefficiency
864 -- See Note [Preparing inert set for implications]
865 -- Push the unsolved wanteds inwards, but as givens
866 ; traceTcS "solveWanteds: preparing inerts for implications {" $
867 vcat [ppr tcs_untouchables, ppr pushed_givens]
868 ; impls_from_givens <- solveInteractCts pushed_givens
870 ; MASSERT (isEmptyBag impls_from_givens)
871 -- impls_from_givens must be empty, since we are reacting givens
872 -- with givens, and they can never generate extra implications
873 -- from decomposition of ForAll types. (Whereas wanteds can, see
874 -- TcCanonical, canEq ForAll-ForAll case)
876 ; traceTcS "solveWanteds: } now doing nested implications {" empty
877 ; flatMapBagPairM (solveImplication tcs_untouchables) implics }
879 -- ... and we are back in the original TcS inerts
880 -- Notice that the original includes the _insoluble_flats so it was safe to ignore
881 -- them in the beginning of this function.
882 ; traceTcS "solveWanteds: done nested implications }" $
883 vcat [ text "implic_eqs =" <+> ppr implic_eqs
884 , text "unsolved_implics =" <+> ppr unsolved_implics ]
886 ; return (implic_eqs, unsolved_implics) }
888 solveImplication :: TcTyVarSet -- Untouchable TcS unification variables
889 -> Implication -- Wanted
890 -> TcS (Cts, -- All wanted or derived floated equalities: var = type
891 Bag Implication) -- Unsolved rest (always empty or singleton)
892 -- Precondition: The TcS monad contains an empty worklist and given-only inerts
893 -- which after trying to solve this implication we must restore to their original value
894 solveImplication tcs_untouchables
895 imp@(Implic { ic_untch = untch
896 , ic_binds = ev_binds
899 , ic_wanted = wanteds
901 = shadowIPs givens $ -- See Note [Shadowing of Implicit Parameters]
902 nestImplicTcS ev_binds (untch, tcs_untouchables) $
903 recoverTcS (return (emptyBag, emptyBag)) $
904 -- Recover from nested failures. Even the top level is
905 -- just a bunch of implications, so failing at the first one is bad
906 do { traceTcS "solveImplication {" (ppr imp)
909 ; impls_from_givens <- solveInteractGiven loc givens
910 ; MASSERT (isEmptyBag impls_from_givens)
912 -- Simplify the wanteds
913 ; WC { wc_flat = unsolved_flats
914 , wc_impl = unsolved_implics
915 , wc_insol = insols } <- solve_wanteds wanteds
917 ; let (res_flat_free, res_flat_bound)
918 = floatEqualities skols givens unsolved_flats
920 ; let res_wanted = WC { wc_flat = keepWanted $ res_flat_bound
921 -- I think this keepWanted must eventually go away, but it is
922 -- a real code-breaking change.
923 -- See Note [KeepWanted in SolveImplication]
924 , wc_impl = unsolved_implics
925 , wc_insol = insols }
927 res_implic = unitImplication $
928 imp { ic_wanted = res_wanted
929 , ic_insol = insolubleWC res_wanted }
931 ; evbinds <- getTcEvBindsMap
933 ; traceTcS "solveImplication end }" $ vcat
934 [ text "res_flat_free =" <+> ppr res_flat_free
935 , text "implication evbinds = " <+> ppr (evBindMapBinds evbinds)
936 , text "res_implic =" <+> ppr res_implic ]
938 ; return (res_flat_free, res_implic) }
939 -- and we are back to the original inerts
943 Note [KeepWanted in SolveWanteds]
944 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
946 let all_flats = flats `unionBags` keepWanted insols
947 instead of the simpler:
948 let all_flats = flats `unionBags` insols
951 Assume a top-level class and instance declaration:
956 Assume we have started with an implication:
958 forall c. Eq c => { wc_flat = D [c] c [W] }
960 which we have simplified to:
962 forall c. Eq c => { wc_flat = D [c] c [W]
963 , wc_insols = (c ~ [c]) [D] }
965 For some reason, e.g. because we floated an equality somewhere else,
966 we might try to re-solve this implication. If we do not do a
967 keepWanted, then we will end up trying to solve the following
968 constraints the second time:
973 which will result in two Deriveds to end up in the insoluble set:
975 wc_flat = D [c] c [W]
976 wc_insols = (c ~ [c]) [D], (c ~ [c]) [D]
978 which can result in reporting the same error twice.
980 So, do we /lose/ some potentially useful information by doing this?
982 No, because the insoluble Derived/Given are going to be equalities,
983 which are going to be derivable anyway from the rest of the flat
987 Note [KeepWanted in SolveImplication]
988 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
990 Here is a real example,
991 stripped off from libraries/utf8-string/Codec/Binary/UTF8/Generic.hs
994 g :: C a b => a -> b -> ()
995 f :: C a b => a -> b -> ()
1000 We will first try to infer a type for loop, and we will succeed:
1002 Subsequently, we will type check (loop xb) and all is good. But,
1003 recall that we have to solve a final implication constraint:
1004 C a b => (C a b' => .... cts from body of loop .... ))
1005 And now we have a problem as we will generate an equality b ~ b' and fail to
1008 I actually think this is a legitimate behaviour (to fail). After all, if we had
1009 given the inferred signature to foo we would have failed as well, but we have to
1010 find a workaround because library code breaks.
1012 For now I keep the 'keepWanted' though it seems problematic e.g. we might discard
1018 floatEqualities :: [TcTyVar] -> [EvVar] -> Cts -> (Cts, Cts)
1019 -- Post: The returned FlavoredEvVar's are only Wanted or Derived
1020 -- and come from the input wanted ev vars or deriveds
1021 floatEqualities skols can_given wantders
1022 | hasEqualities can_given = (emptyBag, wantders)
1023 -- Note [Float Equalities out of Implications]
1024 | otherwise = partitionBag is_floatable wantders
1025 where skol_set = mkVarSet skols
1026 is_floatable :: Ct -> Bool
1028 | ct_predty <- ctPred ct
1029 , isEqPred ct_predty
1030 = skol_set `disjointVarSet` tvs_under_fsks ct_predty
1031 is_floatable _ct = False
1033 tvs_under_fsks :: Type -> TyVarSet
1034 -- ^ NB: for type synonyms tvs_under_fsks does /not/ expand the synonym
1035 tvs_under_fsks (TyVarTy tv)
1036 | not (isTcTyVar tv) = unitVarSet tv
1037 | FlatSkol ty <- tcTyVarDetails tv = tvs_under_fsks ty
1038 | otherwise = unitVarSet tv
1039 tvs_under_fsks (TyConApp _ tys) = unionVarSets (map tvs_under_fsks tys)
1040 tvs_under_fsks (LitTy {}) = emptyVarSet
1041 tvs_under_fsks (FunTy arg res) = tvs_under_fsks arg `unionVarSet` tvs_under_fsks res
1042 tvs_under_fsks (AppTy fun arg) = tvs_under_fsks fun `unionVarSet` tvs_under_fsks arg
1043 tvs_under_fsks (ForAllTy tv ty) -- The kind of a coercion binder
1044 -- can mention type variables!
1045 | isTyVar tv = inner_tvs `delVarSet` tv
1046 | otherwise {- Coercion -} = -- ASSERT( not (tv `elemVarSet` inner_tvs) )
1047 inner_tvs `unionVarSet` tvs_under_fsks (tyVarKind tv)
1049 inner_tvs = tvs_under_fsks ty
1051 shadowIPs :: [EvVar] -> TcS a -> TcS a
1054 | otherwise = do is <- getTcSInerts
1055 doWithInert (purgeShadowed is) m
1057 shadowed = mapMaybe isIP gs
1059 isIP g = do p <- evVarPred_maybe g
1060 (x,_) <- isIPPred_maybe p
1063 isShadowedCt ct = isShadowedEv (ctEvidence ct)
1064 isShadowedEv ev = case isIPPred_maybe (ctEvPred ev) of
1065 Just (x,_) -> x `elem` shadowed
1068 purgeShadowed is = is { inert_cans = purgeCans (inert_cans is)
1069 , inert_solved = purgeSolved (inert_solved is)
1072 purgeDicts = snd . partitionCCanMap isShadowedCt
1073 purgeCans ics = ics { inert_dicts = purgeDicts (inert_dicts ics) }
1074 purgeSolved = filterSolved (not . isShadowedEv)
1077 Note [Preparing inert set for implications]
1078 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1079 Before solving the nested implications, we convert any unsolved flat wanteds
1080 to givens, and add them to the inert set. Reasons:
1082 a) In checking mode, suppresses unnecessary errors. We already have
1083 on unsolved-wanted error; adding it to the givens prevents any
1084 consequential errors from showing up
1086 b) More importantly, in inference mode, we are going to quantify over this
1087 constraint, and we *don't* want to quantify over any constraints that
1088 are deducible from it.
1090 c) Flattened type-family equalities must be exposed to the nested
1091 constraints. Consider
1092 F b ~ alpha, (forall c. F b ~ alpha)
1093 Obviously this is soluble with [alpha := F b]. But the
1094 unification is only done by solveCTyFunEqs, right at the end of
1095 solveWanteds, and if we aren't careful we'll end up with an
1096 unsolved goal inside the implication. We need to "push" the
1097 as-yes-unsolved (F b ~ alpha) inwards, as a *given*, so that it
1098 can be used to solve the inner (F b
1099 ~ alpha). See Trac #4935.
1101 d) There are other cases where interactions between wanteds that can help
1102 to solve a constraint. For example
1104 class C a b | a -> b
1106 (C Int alpha), (forall d. C d blah => C Int a)
1108 If we push the (C Int alpha) inwards, as a given, it can produce
1109 a fundep (alpha~a) and this can float out again and be used to
1110 fix alpha. (In general we can't float class constraints out just
1111 in case (C d blah) might help to solve (C Int a).)
1113 The unsolved wanteds are *canonical* but they may not be *inert*,
1114 because when made into a given they might interact with other givens.
1115 Hence the call to solveInteract. Example:
1117 Original inert set = (d :_g D a) /\ (co :_w a ~ [beta])
1119 We were not able to solve (a ~w [beta]) but we can't just assume it as
1120 given because the resulting set is not inert. Hence we have to do a
1121 'solveInteract' step first.
1123 Finally, note that we convert them to [Given] and NOT [Given/Solved].
1124 The reason is that Given/Solved are weaker than Givens and may be discarded.
1125 As an example consider the inference case, where we may have, the following
1126 original constraints:
1127 [Wanted] F Int ~ Int
1128 (F Int ~ a => F Int ~ a)
1129 If we convert F Int ~ Int to [Given/Solved] instead of Given, then the next
1130 given (F Int ~ a) is going to cause the Given/Solved to be ignored, casting
1131 the (F Int ~ a) insoluble. Hence we should really convert the residual
1132 wanteds to plain old Given.
1134 We need only push in unsolved equalities both in checking mode and inference mode:
1136 (1) In checking mode we should not push given dictionaries in because of
1137 example LongWayOverlapping.hs, where we might get strange overlap
1138 errors between far-away constraints in the program. But even in
1139 checking mode, we must still push type family equations. Consider:
1141 type instance F True a b = a
1142 type instance F False a b = b
1145 (c ~ True) => a ~ gamma
1146 (c ~ False) => b ~ gamma
1148 Since solveCTyFunEqs happens at the very end of solving, the only way to solve
1149 the two implications is temporarily consider (F c a b ~ gamma) as Given (NB: not
1150 merely Given/Solved because it has to interact with the top-level instance
1151 environment) and push it inside the implications. Now, when we come out again at
1152 the end, having solved the implications solveCTyFunEqs will solve this equality.
1154 (2) In inference mode, we recheck the final constraint in checking mode and
1155 hence we will be able to solve inner implications from top-level quantified
1156 constraints nonetheless.
1159 Note [Extra TcsTv untouchables]
1160 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1162 Whenever we are solving a bunch of flat constraints, they may contain
1163 the following sorts of 'touchable' unification variables:
1165 (i) Born-touchables in that scope
1167 (ii) Simplifier-generated unification variables, such as unification
1170 (iii) Touchables that have been floated out from some nested
1171 implications, see Note [Float Equalities out of Implications].
1173 Now, once we are done with solving these flats and have to move inwards to
1174 the nested implications (perhaps for a second time), we must consider all the
1175 extra variables (categories (ii) and (iii) above) as untouchables for the
1176 implication. Otherwise we have the danger or double unifications, as well
1177 as the danger of not ``seing'' some unification. Example (from Trac #4494):
1179 (F Int ~ uf) /\ [untch=beta](forall a. C a => F Int ~ beta)
1181 In this example, beta is touchable inside the implication. The
1182 first solveInteract step leaves 'uf' ununified. Then we move inside
1183 the implication where a new constraint
1185 emerges. We may spontaneously solve it to get uf := beta, so the whole
1186 implication disappears but when we pop out again we are left with (F
1187 Int ~ uf) which will be unified by our final solveCTyFunEqs stage and
1188 uf will get unified *once more* to (F Int).
1190 The solution is to record the unification variables of the flats,
1191 and make them untouchables for the nested implication. In the
1192 example above uf would become untouchable, so beta would be forced
1193 to be unified as beta := uf.
1195 Note [Float Equalities out of Implications]
1196 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1197 For ordinary pattern matches (including existentials) we float
1198 equalities out of implications, for instance:
1200 MkT :: Eq a => a -> T
1201 f x y = case x of MkT _ -> (y::Int)
1202 We get the implication constraint (x::T) (y::alpha):
1203 forall a. [untouchable=alpha] Eq a => alpha ~ Int
1204 We want to float out the equality into a scope where alpha is no
1205 longer untouchable, to solve the implication!
1207 But we cannot float equalities out of implications whose givens may
1208 yield or contain equalities:
1215 h :: T a -> a -> Int
1222 We generate constraint, for (x::T alpha) and (y :: beta):
1223 [untouchables = beta] (alpha ~ Int => beta ~ Int) -- From 1st branch
1224 [untouchables = beta] (alpha ~ Bool => beta ~ Bool) -- From 2nd branch
1225 (alpha ~ beta) -- From 3rd branch
1227 If we float the equality (beta ~ Int) outside of the first implication and
1228 the equality (beta ~ Bool) out of the second we get an insoluble constraint.
1229 But if we just leave them inside the implications we unify alpha := beta and
1233 We do not want to float equalities out which may need the given *evidence*
1236 Consequence: classes with functional dependencies don't matter (since there is
1237 no evidence for a fundep equality), but equality superclasses do matter (since
1238 they carry evidence).
1240 Notice that, due to Note [Extra TcSTv Untouchables], the free unification variables
1241 of an equality that is floated out of an implication become effectively untouchables
1242 for the leftover implication. This is absolutely necessary. Consider the following
1243 example. We start with two implications and a class with a functional dependency.
1245 class C x y | x -> y
1248 (I1) [untch=beta]forall b. 0 => F Int ~ [beta]
1249 (I2) [untch=beta]forall b. 0 => F Int ~ [[alpha]] /\ C beta [b]
1251 We float (F Int ~ [beta]) out of I1, and we float (F Int ~ [[alpha]]) out of I2.
1252 They may react to yield that (beta := [alpha]) which can then be pushed inwards
1253 the leftover of I2 to get (C [alpha] [a]) which, using the FunDep, will mean that
1254 (alpha := a). In the end we will have the skolem 'b' escaping in the untouchable
1255 beta! Concrete example is in indexed_types/should_fail/ExtraTcsUntch.hs:
1257 class C x y | x -> y where
1262 type family F a :: *
1272 let g1 :: forall b. b -> ()
1274 g2 z = case z of TEx y -> (h [[undefined]], op x [y])
1275 in (g1 '3', g2 undefined)
1277 Note [Shadowing of Implicit Parameters]
1278 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1279 Consider the following example:
1281 f :: (?x :: Char) => Char
1282 f = let ?x = 'a' in ?x
1284 The "let ?x = ..." generates an implication constraint of the form:
1286 ?x :: Char => ?x :: Char
1289 Furthermore, the signature for `f` also generates an implication
1290 constraint, so we end up with the following nested implication:
1292 ?x :: Char => (?x :: Char => ?x :: Char)
1294 Note that the wanted (?x :: Char) constraint may be solved in
1295 two incompatible ways: either by using the parameter from the
1296 signature, or by using the local definition. Our intention is
1297 that the local definition should "shadow" the parameter of the
1298 signature, and we implement this as follows: when we nest implications,
1299 we remove any implicit parameters in the outer implication, that
1300 have the same name as givens of the inner implication.
1302 Here is another variation of the example:
1304 f :: (?x :: Int) => Char
1305 f = let ?x = 'x' in ?x
1307 This program should also be accepted: the two constraints `?x :: Int`
1308 and `?x :: Char` never exist in the same context, so they don't get to
1309 interact to cause failure.
1314 unFlattenWC :: WantedConstraints -> TcS WantedConstraints
1316 = do { (subst, remaining_unsolved_flats) <- solveCTyFunEqs (wc_flat wc)
1317 -- See Note [Solving Family Equations]
1318 -- NB: remaining_flats has already had subst applied
1320 WC { wc_flat = mapBag (substCt subst) remaining_unsolved_flats
1321 , wc_impl = mapBag (substImplication subst) (wc_impl wc)
1322 , wc_insol = mapBag (substCt subst) (wc_insol wc) }
1325 solveCTyFunEqs :: Cts -> TcS (TvSubst, Cts)
1326 -- Default equalities (F xi ~ alpha) by setting (alpha := F xi), whenever possible
1327 -- See Note [Solving Family Equations]
1328 -- Returns: a bunch of unsolved constraints from the original Cts and implications
1329 -- where the newly generated equalities (alpha := F xi) have been substituted through.
1331 = do { untch <- getUntouchables
1332 ; let (unsolved_can_cts, (ni_subst, cv_binds))
1333 = getSolvableCTyFunEqs untch cts
1334 ; traceTcS "defaultCTyFunEqs" (vcat [text "Trying to default family equations:"
1335 , ppr ni_subst, ppr cv_binds
1337 ; mapM_ solve_one cv_binds
1339 ; return (niFixTvSubst ni_subst, unsolved_can_cts) }
1341 solve_one (Wanted { ctev_evar = cv }, tv, ty)
1342 = setWantedTyBind tv ty >> setEvBind cv (EvCoercion (mkTcReflCo ty))
1343 solve_one (Derived {}, tv, ty)
1344 = setWantedTyBind tv ty
1346 = pprPanic "solveCTyFunEqs: can't solve a /given/ family equation!" $ ppr arg
1349 type FunEqBinds = (TvSubstEnv, [(CtEvidence, TcTyVar, TcType)])
1350 -- The TvSubstEnv is not idempotent, but is loop-free
1351 -- See Note [Non-idempotent substitution] in Unify
1352 emptyFunEqBinds :: FunEqBinds
1353 emptyFunEqBinds = (emptyVarEnv, [])
1355 extendFunEqBinds :: FunEqBinds -> CtEvidence -> TcTyVar -> TcType -> FunEqBinds
1356 extendFunEqBinds (tv_subst, cv_binds) fl tv ty
1357 = (extendVarEnv tv_subst tv ty, (fl, tv, ty):cv_binds)
1360 getSolvableCTyFunEqs :: TcsUntouchables
1361 -> Cts -- Precondition: all Wanteds or Derived!
1362 -> (Cts, FunEqBinds) -- Postcondition: returns the unsolvables
1363 getSolvableCTyFunEqs untch cts
1364 = Bag.foldlBag dflt_funeq (emptyCts, emptyFunEqBinds) cts
1366 dflt_funeq :: (Cts, FunEqBinds) -> Ct
1367 -> (Cts, FunEqBinds)
1368 dflt_funeq (cts_in, feb@(tv_subst, _))
1369 (CFunEqCan { cc_ev = fl
1373 | Just tv <- tcGetTyVar_maybe xi -- RHS is a type variable
1375 , isTouchableMetaTyVar_InRange untch tv
1376 -- And it's a *touchable* unification variable
1378 , typeKind xi `tcIsSubKind` tyVarKind tv
1379 -- Must do a small kind check since TcCanonical invariants
1380 -- on family equations only impose compatibility, not subkinding
1382 , not (tv `elemVarEnv` tv_subst)
1383 -- Check not in extra_binds
1384 -- See Note [Solving Family Equations], Point 1
1386 , not (tv `elemVarSet` niSubstTvSet tv_subst (tyVarsOfTypes xis))
1387 -- Occurs check: see Note [Solving Family Equations], Point 2
1388 = ASSERT ( not (isGiven fl) )
1389 (cts_in, extendFunEqBinds feb fl tv (mkTyConApp tc xis))
1391 dflt_funeq (cts_in, fun_eq_binds) ct
1392 = (cts_in `extendCts` ct, fun_eq_binds)
1395 Note [Solving Family Equations]
1396 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1397 After we are done with simplification we may be left with constraints of the form:
1398 [Wanted] F xis ~ beta
1399 If 'beta' is a touchable unification variable not already bound in the TyBinds
1400 then we'd like to create a binding for it, effectively "defaulting" it to be 'F xis'.
1402 When is it ok to do so?
1403 1) 'beta' must not already be defaulted to something. Example:
1405 [Wanted] F Int ~ beta <~ Will default [beta := F Int]
1406 [Wanted] F Char ~ beta <~ Already defaulted, can't default again. We
1407 have to report this as unsolved.
1409 2) However, we must still do an occurs check when defaulting (F xis ~ beta), to
1410 set [beta := F xis] only if beta is not among the free variables of xis.
1412 3) Notice that 'beta' can't be bound in ty binds already because we rewrite RHS
1413 of type family equations. See Inert Set invariants in TcInteract.
1416 *********************************************************************************
1418 * Defaulting and disamgiguation *
1420 *********************************************************************************
1422 applyDefaultingRules :: Cts -- Wanteds or Deriveds
1423 -> TcS Cts -- Derived equalities
1424 -- Return some extra derived equalities, which express the
1425 -- type-class default choice.
1426 applyDefaultingRules wanteds
1427 | isEmptyBag wanteds
1430 = do { traceTcS "applyDefaultingRules { " $
1431 text "wanteds =" <+> ppr wanteds
1433 ; info@(default_tys, _) <- getDefaultInfo
1434 ; let groups = findDefaultableGroups info wanteds
1435 ; traceTcS "findDefaultableGroups" $ vcat [ text "groups=" <+> ppr groups
1436 , text "info=" <+> ppr info ]
1437 ; deflt_cts <- mapM (disambigGroup default_tys) groups
1439 ; traceTcS "applyDefaultingRules }" $
1440 vcat [ text "Type defaults =" <+> ppr deflt_cts]
1442 ; return (unionManyBags deflt_cts) }
1445 Note [tryTcS in defaulting]
1446 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
1448 defaultTyVar and disambigGroup create new evidence variables for
1449 default equations, and hence update the EvVar cache. However, after
1450 applyDefaultingRules we will try to solve these default equations
1451 using solveInteractCts, which will consult the cache and solve those
1452 EvVars from themselves! That's wrong.
1454 To avoid this problem we guard defaulting under a @tryTcS@ which leaves
1455 the original cache unmodified.
1457 There is a second reason for @tryTcS@ in defaulting: disambGroup does
1458 some constraint solving to determine if a default equation is
1459 ``useful'' in solving some wanted constraints, but we want to
1460 discharge all evidence and unifications that may have happened during
1461 this constraint solving.
1463 Finally, @tryTcS@ importantly does not inherit the original cache from
1464 the higher level but makes up a new cache, the reason is that disambigGroup
1465 will call solveInteractCts so the new derived and the wanteds must not be
1471 touchablesOfWC :: WantedConstraints -> TcTyVarSet
1472 -- See Note [Extra Tcs Untouchables] to see why we carry a TcsUntouchables
1473 -- instead of just using the Untouchable range have in our hands.
1474 touchablesOfWC = go (NoUntouchables, emptyVarSet)
1475 where go :: TcsUntouchables -> WantedConstraints -> TcTyVarSet
1476 go untch (WC { wc_flat = flats, wc_impl = impls })
1477 = filterVarSet is_touchable flat_tvs `unionVarSet`
1478 foldrBag (unionVarSet . (go_impl $ untch_for_impls untch)) emptyVarSet impls
1479 where is_touchable = isTouchableMetaTyVar_InRange untch
1480 flat_tvs = tyVarsOfCts flats
1481 untch_for_impls (r,uset) = (r, uset `unionVarSet` flat_tvs)
1482 go_impl (_rng,set) implic = go (ic_untch implic,set) (ic_wanted implic)
1484 applyTyVarDefaulting :: WantedConstraints -> TcM Cts
1485 applyTyVarDefaulting wc = runTcS do_dflt >>= (return . fst)
1486 where do_dflt = do { tv_cts <- mapM defaultTyVar $
1487 varSetElems (touchablesOfWC wc)
1488 ; return (unionManyBags tv_cts) }
1490 defaultTyVar :: TcTyVar -> TcS Cts
1491 -- Precondition: a touchable meta-variable
1493 | not (k `eqKind` default_k)
1494 -- Why tryTcS? See Note [tryTcS in defaulting]
1496 do { let loc = CtLoc DefaultOrigin (getSrcSpan the_tv) [] -- Yuk
1497 ; ty_k <- instFlexiTcSHelperTcS (tyVarName the_tv) default_k
1498 ; md <- newDerived loc (mkTcEqPred (mkTyVarTy the_tv) ty_k)
1499 -- Why not directly newDerived loc (mkTcEqPred k default_k)?
1500 -- See Note [DefaultTyVar]
1502 | Just der_ev <- md = [mkNonCanonical der_ev]
1505 ; implics_from_defaulting <- solveInteractCts cts
1506 ; MASSERT (isEmptyBag implics_from_defaulting)
1508 ; unsolved <- getTcSInerts >>= (return . getInertUnsolved)
1509 ; if isEmptyBag (keepWanted unsolved) then return (listToBag cts)
1510 else return emptyBag }
1511 | otherwise = return emptyBag -- The common case
1513 k = tyVarKind the_tv
1514 default_k = defaultKind k
1519 defaultTyVar is used on any un-instantiated meta type variables to
1520 default the kind of OpenKind and ArgKind etc to *. This is important
1521 to ensure that instance declarations match. For example consider
1523 instance Show (a->b)
1524 foo x = show (\_ -> True)
1526 Then we'll get a constraint (Show (p ->q)) where p has kind ArgKind,
1527 and that won't match the typeKind (*) in the instance decl. See tests
1530 We look only at touchable type variables. No further constraints
1531 are going to affect these type variables, so it's time to do it by
1532 hand. However we aren't ready to default them fully to () or
1533 whatever, because the type-class defaulting rules have yet to run.
1535 An important point is that if the type variable tv has kind k and the
1536 default is default_k we do not simply generate [D] (k ~ default_k) because:
1538 (1) k may be ArgKind and default_k may be * so we will fail
1540 (2) We need to rewrite all occurrences of the tv to be a type
1541 variable with the right kind and we choose to do this by rewriting
1542 the type variable /itself/ by a new variable which does have the
1549 findDefaultableGroups
1551 , (Bool,Bool) ) -- (Overloaded strings, extended default rules)
1552 -> Cts -- Unsolved (wanted or derived)
1554 findDefaultableGroups (default_tys, (ovl_strings, extended_defaults)) wanteds
1555 | null default_tys = []
1556 | otherwise = filter is_defaultable_group (equivClasses cmp_tv unaries)
1558 unaries :: [(Ct, TcTyVar)] -- (C tv) constraints
1559 non_unaries :: [Ct] -- and *other* constraints
1561 (unaries, non_unaries) = partitionWith find_unary (bagToList wanteds)
1562 -- Finds unary type-class constraints
1563 find_unary cc@(CDictCan { cc_tyargs = [ty] })
1564 | Just tv <- tcGetTyVar_maybe ty
1566 find_unary cc = Right cc -- Non unary or non dictionary
1568 bad_tvs :: TcTyVarSet -- TyVars mentioned by non-unaries
1569 bad_tvs = foldr (unionVarSet . tyVarsOfCt) emptyVarSet non_unaries
1571 cmp_tv (_,tv1) (_,tv2) = tv1 `compare` tv2
1573 is_defaultable_group ds@((_,tv):_)
1574 = let b1 = isTyConableTyVar tv -- Note [Avoiding spurious errors]
1575 b2 = not (tv `elemVarSet` bad_tvs)
1576 b4 = defaultable_classes [cc_class cc | (cc,_) <- ds]
1578 is_defaultable_group [] = panic "defaultable_group"
1580 defaultable_classes clss
1581 | extended_defaults = any isInteractiveClass clss
1582 | otherwise = all is_std_class clss && (any is_num_class clss)
1584 -- In interactive mode, or with -XExtendedDefaultRules,
1585 -- we default Show a to Show () to avoid graututious errors on "show []"
1586 isInteractiveClass cls
1587 = is_num_class cls || (classKey cls `elem` [showClassKey, eqClassKey, ordClassKey])
1589 is_num_class cls = isNumericClass cls || (ovl_strings && (cls `hasKey` isStringClassKey))
1590 -- is_num_class adds IsString to the standard numeric classes,
1591 -- when -foverloaded-strings is enabled
1593 is_std_class cls = isStandardClass cls || (ovl_strings && (cls `hasKey` isStringClassKey))
1594 -- Similarly is_std_class
1596 ------------------------------
1597 disambigGroup :: [Type] -- The default types
1598 -> [(Ct, TcTyVar)] -- All classes of the form (C a)
1599 -- sharing same type variable
1602 disambigGroup [] _grp
1604 disambigGroup (default_ty:default_tys) group
1605 = do { traceTcS "disambigGroup" (ppr group $$ ppr default_ty)
1606 ; success <- tryTcS $ -- Why tryTcS? See Note [tryTcS in defaulting]
1607 do { derived_eq <- tryTcS $
1608 -- I need a new tryTcS because we will call solveInteractCts below!
1609 do { md <- newDerived (ctev_wloc the_fl)
1610 (mkTcEqPred (mkTyVarTy the_tv) default_ty)
1611 -- ctev_wloc because constraint is not Given!
1613 Nothing -> return []
1614 Just ctev -> return [ mkNonCanonical ctev ] }
1616 ; traceTcS "disambigGroup (solving) {" $
1617 text "trying to solve constraints along with default equations ..."
1618 ; implics_from_defaulting <-
1619 solveInteractCts (derived_eq ++ wanteds)
1620 ; MASSERT (isEmptyBag implics_from_defaulting)
1621 -- I am not certain if any implications can be generated
1622 -- but I am letting this fail aggressively if this ever happens.
1624 ; unsolved <- getTcSInerts >>= (return . getInertUnsolved)
1625 ; traceTcS "disambigGroup (solving) }" $
1626 text "disambigGroup unsolved =" <+> ppr (keepWanted unsolved)
1627 ; if isEmptyBag (keepWanted unsolved) then -- Don't care about Derived's
1628 return (Just $ listToBag derived_eq)
1633 Just cts -> -- Success: record the type variable binding, and return
1634 do { wrapWarnTcS $ warnDefaulting wanteds default_ty
1635 ; traceTcS "disambigGroup succeeded" (ppr default_ty)
1637 Nothing -> -- Failure: try with the next type
1638 do { traceTcS "disambigGroup failed, will try other default types"
1640 ; disambigGroup default_tys group } }
1642 ((the_ct,the_tv):_) = group
1643 the_fl = cc_ev the_ct
1644 wanteds = map fst group
1647 Note [Avoiding spurious errors]
1648 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1649 When doing the unification for defaulting, we check for skolem
1650 type variables, and simply don't default them. For example:
1651 f = (*) -- Monomorphic
1652 g :: Num a => a -> a
1654 Here, we get a complaint when checking the type signature for g,
1655 that g isn't polymorphic enough; but then we get another one when
1656 dealing with the (Num a) context arising from f's definition;
1657 we try to unify a with Int (to default it), but find that it's
1658 already been unified with the rigid variable from g's type sig
1662 *********************************************************************************
1666 *********************************************************************************
1669 newFlatWanteds :: CtOrigin -> ThetaType -> TcM [Ct]
1670 newFlatWanteds orig theta
1671 = do { loc <- getCtLoc orig
1672 ; mapM (inst_to_wanted loc) theta }
1674 inst_to_wanted loc pty
1675 = do { v <- TcMType.newWantedEvVar pty
1677 CNonCanonical { cc_ev = Wanted { ctev_evar = v