c1535f8733e162663e3f2ea7b2baa9be8a4943ce
[ghc.git] / compiler / typecheck / TcSimplify.hs
1 {-# LANGUAGE CPP #-}
2
3 module TcSimplify(
4 simplifyInfer,
5 pickQuantifiablePreds, growThetaTyVars,
6 simplifyAmbiguityCheck,
7 simplifyDefault,
8 simplifyTop, simplifyInteractive,
9 solveWantedsTcM,
10
11 -- For Rules we need these twoo
12 solveWanteds, runTcS
13 ) where
14
15 #include "HsVersions.h"
16
17 import TcRnTypes
18 import TcRnMonad
19 import TcErrors
20 import TcMType as TcM
21 import TcType
22 import TcSMonad as TcS
23 import TcInteract
24 import Kind ( isKind, defaultKind_maybe )
25 import Inst
26 import Unify ( tcMatchTy )
27 import Type ( classifyPredType, isIPClass, PredTree(..)
28 , getClassPredTys_maybe, EqRel(..) )
29 import TyCon ( isTypeFamilyTyCon )
30 import Class ( Class )
31 import Id ( idType )
32 import Var
33 import Unique
34 import VarSet
35 import TcEvidence
36 import Name
37 import Bag
38 import ListSetOps
39 import Util
40 import PrelInfo
41 import PrelNames
42 import Control.Monad ( unless )
43 import DynFlags ( ExtensionFlag( Opt_AllowAmbiguousTypes, Opt_FlexibleContexts ) )
44 import Class ( classKey )
45 import Maybes ( isNothing )
46 import Outputable
47 import FastString
48 import TrieMap () -- DV: for now
49 import Data.List( partition )
50
51 {-
52 *********************************************************************************
53 * *
54 * External interface *
55 * *
56 *********************************************************************************
57 -}
58
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
64 simplifyTop wanteds
65 = do { traceTc "simplifyTop {" $ text "wanted = " <+> ppr wanteds
66 ; (final_wc, binds1) <- runTcS (simpl_top wanteds)
67 ; traceTc "End simplifyTop }" empty
68
69 ; traceTc "reportUnsolved {" empty
70 ; binds2 <- reportUnsolved final_wc
71 ; traceTc "reportUnsolved }" empty
72
73 ; return (binds1 `unionBags` binds2) }
74
75 simpl_top :: WantedConstraints -> TcS WantedConstraints
76 -- See Note [Top-level Defaulting Plan]
77 simpl_top wanteds
78 = do { wc_first_go <- nestTcS (solveWantedsAndDrop wanteds)
79 -- This is where the main work happens
80 ; try_tyvar_defaulting wc_first_go }
81 where
82 try_tyvar_defaulting :: WantedConstraints -> TcS WantedConstraints
83 try_tyvar_defaulting wc
84 | isEmptyWC wc
85 = return wc
86 | otherwise
87 = do { free_tvs <- TcS.zonkTyVarsAndFV (tyVarsOfWC wc)
88 ; let meta_tvs = varSetElems (filterVarSet isMetaTyVar free_tvs)
89 -- zonkTyVarsAndFV: the wc_first_go is not yet zonked
90 -- filter isMetaTyVar: we might have runtime-skolems in GHCi,
91 -- and we definitely don't want to try to assign to those!
92
93 ; meta_tvs' <- mapM defaultTyVar meta_tvs -- Has unification side effects
94 ; if meta_tvs' == meta_tvs -- No defaulting took place;
95 -- (defaulting returns fresh vars)
96 then try_class_defaulting wc
97 else do { wc_residual <- nestTcS (solveWantedsAndDrop wc)
98 -- See Note [Must simplify after defaulting]
99 ; try_class_defaulting wc_residual } }
100
101 try_class_defaulting :: WantedConstraints -> TcS WantedConstraints
102 try_class_defaulting wc
103 | isEmptyWC wc
104 = return wc
105 | otherwise -- See Note [When to do type-class defaulting]
106 = do { something_happened <- applyDefaultingRules wc
107 -- See Note [Top-level Defaulting Plan]
108 ; if something_happened
109 then do { wc_residual <- nestTcS (solveWantedsAndDrop wc)
110 ; try_class_defaulting wc_residual }
111 else return wc }
112
113 {-
114 Note [When to do type-class defaulting]
115 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
116 In GHC 7.6 and 7.8.2, we did type-class defaulting only if insolubleWC
117 was false, on the grounds that defaulting can't help solve insoluble
118 constraints. But if we *don't* do defaulting we may report a whole
119 lot of errors that would be solved by defaulting; these errors are
120 quite spurious because fixing the single insoluble error means that
121 defaulting happens again, which makes all the other errors go away.
122 This is jolly confusing: Trac #9033.
123
124 So it seems better to always do type-class defaulting.
125
126 However, always doing defaulting does mean that we'll do it in
127 situations like this (Trac #5934):
128 run :: (forall s. GenST s) -> Int
129 run = fromInteger 0
130 We don't unify the return type of fromInteger with the given function
131 type, because the latter involves foralls. So we're left with
132 (Num alpha, alpha ~ (forall s. GenST s) -> Int)
133 Now we do defaulting, get alpha := Integer, and report that we can't
134 match Integer with (forall s. GenST s) -> Int. That's not totally
135 stupid, but perhaps a little strange.
136
137 Another potential alternative would be to suppress *all* non-insoluble
138 errors if there are *any* insoluble errors, anywhere, but that seems
139 too drastic.
140
141 Note [Must simplify after defaulting]
142 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
143 We may have a deeply buried constraint
144 (t:*) ~ (a:Open)
145 which we couldn't solve because of the kind incompatibility, and 'a' is free.
146 Then when we default 'a' we can solve the constraint. And we want to do
147 that before starting in on type classes. We MUST do it before reporting
148 errors, because it isn't an error! Trac #7967 was due to this.
149
150 Note [Top-level Defaulting Plan]
151 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
152 We have considered two design choices for where/when to apply defaulting.
153 (i) Do it in SimplCheck mode only /whenever/ you try to solve some
154 simple constraints, maybe deep inside the context of implications.
155 This used to be the case in GHC 7.4.1.
156 (ii) Do it in a tight loop at simplifyTop, once all other constraint has
157 finished. This is the current story.
158
159 Option (i) had many disadvantages:
160 a) First it was deep inside the actual solver,
161 b) Second it was dependent on the context (Infer a type signature,
162 or Check a type signature, or Interactive) since we did not want
163 to always start defaulting when inferring (though there is an exception to
164 this see Note [Default while Inferring])
165 c) It plainly did not work. Consider typecheck/should_compile/DfltProb2.hs:
166 f :: Int -> Bool
167 f x = const True (\y -> let w :: a -> a
168 w a = const a (y+1)
169 in w y)
170 We will get an implication constraint (for beta the type of y):
171 [untch=beta] forall a. 0 => Num beta
172 which we really cannot default /while solving/ the implication, since beta is
173 untouchable.
174
175 Instead our new defaulting story is to pull defaulting out of the solver loop and
176 go with option (i), implemented at SimplifyTop. Namely:
177 - First have a go at solving the residual constraint of the whole program
178 - Try to approximate it with a simple constraint
179 - Figure out derived defaulting equations for that simple constraint
180 - Go round the loop again if you did manage to get some equations
181
182 Now, that has to do with class defaulting. However there exists type variable /kind/
183 defaulting. Again this is done at the top-level and the plan is:
184 - At the top-level, once you had a go at solving the constraint, do
185 figure out /all/ the touchable unification variables of the wanted constraints.
186 - Apply defaulting to their kinds
187
188 More details in Note [DefaultTyVar].
189 -}
190
191 ------------------
192 simplifyAmbiguityCheck :: Type -> WantedConstraints -> TcM ()
193 simplifyAmbiguityCheck ty wanteds
194 = do { traceTc "simplifyAmbiguityCheck {" (text "type = " <+> ppr ty $$ text "wanted = " <+> ppr wanteds)
195 ; (final_wc, _binds) <- runTcS (simpl_top wanteds)
196 ; traceTc "End simplifyAmbiguityCheck }" empty
197
198 -- Normally report all errors; but with -XAllowAmbiguousTypes
199 -- report only insoluble ones, since they represent genuinely
200 -- inaccessible code
201 ; allow_ambiguous <- xoptM Opt_AllowAmbiguousTypes
202 ; traceTc "reportUnsolved(ambig) {" empty
203 ; unless (allow_ambiguous && not (insolubleWC final_wc))
204 (discardResult (reportUnsolved final_wc))
205 ; traceTc "reportUnsolved(ambig) }" empty
206
207 ; return () }
208
209 ------------------
210 simplifyInteractive :: WantedConstraints -> TcM (Bag EvBind)
211 simplifyInteractive wanteds
212 = traceTc "simplifyInteractive" empty >>
213 simplifyTop wanteds
214
215 ------------------
216 simplifyDefault :: ThetaType -- Wanted; has no type variables in it
217 -> TcM () -- Succeeds iff the constraint is soluble
218 simplifyDefault theta
219 = do { traceTc "simplifyInteractive" empty
220 ; wanted <- newWanteds DefaultOrigin theta
221 ; unsolved <- solveWantedsTcM wanted
222
223 ; traceTc "reportUnsolved {" empty
224 -- See Note [Deferring coercion errors to runtime]
225 ; reportAllUnsolved unsolved
226 ; traceTc "reportUnsolved }" empty
227
228 ; return () }
229
230 {-
231 *********************************************************************************
232 * *
233 * Inference
234 * *
235 ***********************************************************************************
236
237 Note [Inferring the type of a let-bound variable]
238 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
239 Consider
240 f x = rhs
241
242 To infer f's type we do the following:
243 * Gather the constraints for the RHS with ambient level *one more than*
244 the current one. This is done by the call
245 pushLevelAndCaptureConstraints (tcMonoBinds...)
246 in TcBinds.tcPolyInfer
247
248 * Call simplifyInfer to simplify the constraints and decide what to
249 quantify over. We pass in the level used for the RHS constraints,
250 here called rhs_tclvl.
251
252 This ensures that the implication constraint we generate, if any,
253 has a strictly-increased level compared to the ambient level outside
254 the let binding.
255 -}
256
257 simplifyInfer :: TcLevel -- Used when generating the constraints
258 -> Bool -- Apply monomorphism restriction
259 -> [(Name, TcTauType)] -- Variables to be generalised,
260 -- and their tau-types
261 -> WantedConstraints
262 -> TcM ([TcTyVar], -- Quantify over these type variables
263 [EvVar], -- ... and these constraints (fully zonked)
264 Bool, -- The monomorphism restriction did something
265 -- so the results type is not as general as
266 -- it could be
267 TcEvBinds) -- ... binding these evidence variables
268 simplifyInfer rhs_tclvl apply_mr name_taus wanteds
269 | isEmptyWC wanteds
270 = do { gbl_tvs <- tcGetGlobalTyVars
271 ; qtkvs <- quantifyTyVars gbl_tvs (tyVarsOfTypes (map snd name_taus))
272 ; traceTc "simplifyInfer: empty WC" (ppr name_taus $$ ppr qtkvs)
273 ; return (qtkvs, [], False, emptyTcEvBinds) }
274
275 | otherwise
276 = do { traceTc "simplifyInfer {" $ vcat
277 [ ptext (sLit "binds =") <+> ppr name_taus
278 , ptext (sLit "rhs_tclvl =") <+> ppr rhs_tclvl
279 , ptext (sLit "apply_mr =") <+> ppr apply_mr
280 , ptext (sLit "(unzonked) wanted =") <+> ppr wanteds
281 ]
282
283 -- Historical note: Before step 2 we used to have a
284 -- HORRIBLE HACK described in Note [Avoid unecessary
285 -- constraint simplification] but, as described in Trac
286 -- #4361, we have taken in out now. That's why we start
287 -- with step 2!
288
289 -- Step 2) First try full-blown solving
290
291 -- NB: we must gather up all the bindings from doing
292 -- this solving; hence (runTcSWithEvBinds ev_binds_var).
293 -- And note that since there are nested implications,
294 -- calling solveWanteds will side-effect their evidence
295 -- bindings, so we can't just revert to the input
296 -- constraint.
297
298 ; ev_binds_var <- TcM.newTcEvBinds
299 ; wanted_transformed_incl_derivs <- setTcLevel rhs_tclvl $
300 runTcSWithEvBinds ev_binds_var (solveWanteds wanteds)
301 ; wanted_transformed_incl_derivs <- TcM.zonkWC wanted_transformed_incl_derivs
302
303 -- Step 4) Candidates for quantification are an approximation of wanted_transformed
304 -- NB: Already the fixpoint of any unifications that may have happened
305 -- NB: We do not do any defaulting when inferring a type, this can lead
306 -- to less polymorphic types, see Note [Default while Inferring]
307
308 ; tc_lcl_env <- TcRnMonad.getLclEnv
309 ; null_ev_binds_var <- TcM.newTcEvBinds
310 ; let wanted_transformed = dropDerivedWC wanted_transformed_incl_derivs
311 ; quant_pred_candidates -- Fully zonked
312 <- if insolubleWC wanted_transformed_incl_derivs
313 then return [] -- See Note [Quantification with errors]
314 -- NB: must include derived errors in this test,
315 -- hence "incl_derivs"
316
317 else do { let quant_cand = approximateWC wanted_transformed
318 meta_tvs = filter isMetaTyVar (varSetElems (tyVarsOfCts quant_cand))
319 ; gbl_tvs <- tcGetGlobalTyVars
320 -- Miminise quant_cand. We are not interested in any evidence
321 -- produced, because we are going to simplify wanted_transformed
322 -- again later. All we want here is the predicates over which to
323 -- quantify.
324 --
325 -- If any meta-tyvar unifications take place (unlikely), we'll
326 -- pick that up later.
327
328 ; WC { wc_simple = simples }
329 <- setTcLevel rhs_tclvl $
330 runTcSWithEvBinds null_ev_binds_var $
331 do { mapM_ (promoteAndDefaultTyVar rhs_tclvl gbl_tvs) meta_tvs
332 -- See Note [Promote _and_ default when inferring]
333 ; solveSimpleWanteds quant_cand }
334
335 ; return [ ctEvPred ev | ct <- bagToList simples
336 , let ev = ctEvidence ct
337 , isWanted ev ] }
338
339 -- NB: quant_pred_candidates is already fully zonked
340
341 -- Decide what type variables and constraints to quantify
342 ; zonked_taus <- mapM (TcM.zonkTcType . snd) name_taus
343 ; let zonked_tau_tvs = tyVarsOfTypes zonked_taus
344 ; (qtvs, bound_theta, mr_bites)
345 <- decideQuantification apply_mr quant_pred_candidates zonked_tau_tvs
346
347 -- Emit an implication constraint for the
348 -- remaining constraints from the RHS
349 ; bound_ev_vars <- mapM TcM.newEvVar bound_theta
350 ; let skol_info = InferSkol [ (name, mkSigmaTy [] bound_theta ty)
351 | (name, ty) <- name_taus ]
352 -- Don't add the quantified variables here, because
353 -- they are also bound in ic_skols and we want them
354 -- to be tidied uniformly
355
356 implic = Implic { ic_tclvl = rhs_tclvl
357 , ic_skols = qtvs
358 , ic_no_eqs = False
359 , ic_given = bound_ev_vars
360 , ic_wanted = wanted_transformed
361 , ic_status = IC_Unsolved
362 , ic_binds = ev_binds_var
363 , ic_info = skol_info
364 , ic_env = tc_lcl_env }
365 ; emitImplication implic
366
367 -- Promote any type variables that are free in the inferred type
368 -- of the function:
369 -- f :: forall qtvs. bound_theta => zonked_tau
370 -- These variables now become free in the envt, and hence will show
371 -- up whenever 'f' is called. They may currently at rhs_tclvl, but
372 -- they had better be unifiable at the outer_tclvl!
373 -- Example: envt mentions alpha[1]
374 -- tau_ty = beta[2] -> beta[2]
375 -- consraints = alpha ~ [beta]
376 -- we don't quantify over beta (since it is fixed by envt)
377 -- so we must promote it! The inferred type is just
378 -- f :: beta -> beta
379 ; outer_tclvl <- TcRnMonad.getTcLevel
380 ; zonked_tau_tvs <- TcM.zonkTyVarsAndFV zonked_tau_tvs
381 -- decideQuantification turned some meta tyvars into
382 -- quantified skolems, so we have to zonk again
383 ; let phi_tvs = tyVarsOfTypes bound_theta `unionVarSet` zonked_tau_tvs
384 promote_tvs = varSetElems (closeOverKinds phi_tvs `delVarSetList` qtvs)
385 ; runTcSWithEvBinds null_ev_binds_var $ -- runTcS just to get the types right :-(
386 mapM_ (promoteTyVar outer_tclvl) promote_tvs
387
388 -- All done!
389 ; traceTc "} simplifyInfer/produced residual implication for quantification" $
390 vcat [ ptext (sLit "quant_pred_candidates =") <+> ppr quant_pred_candidates
391 , ptext (sLit "zonked_taus") <+> ppr zonked_taus
392 , ptext (sLit "zonked_tau_tvs=") <+> ppr zonked_tau_tvs
393 , ptext (sLit "promote_tvs=") <+> ppr promote_tvs
394 , ptext (sLit "bound_theta =") <+> vcat [ ppr v <+> dcolon <+> ppr (idType v)
395 | v <- bound_ev_vars]
396 , ptext (sLit "mr_bites =") <+> ppr mr_bites
397 , ptext (sLit "qtvs =") <+> ppr qtvs
398 , ptext (sLit "implic =") <+> ppr implic ]
399
400 ; return ( qtvs, bound_ev_vars, mr_bites, TcEvBinds ev_binds_var) }
401
402 {-
403 ************************************************************************
404 * *
405 Quantification
406 * *
407 ************************************************************************
408
409 Note [Deciding quantification]
410 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
411 If the monomorphism restriction does not apply, then we quantify as follows:
412 * Take the global tyvars, and "grow" them using the equality constraints
413 E.g. if x:alpha is in the environment, and alpha ~ [beta] (which can
414 happen because alpha is untouchable here) then do not quantify over
415 beta, because alpha fixes beta, and beta is effectively free in
416 the environment too
417 These are the mono_tvs
418
419 * Take the free vars of the tau-type (zonked_tau_tvs) and "grow" them
420 using all the constraints. These are tau_tvs_plus
421
422 * Use quantifyTyVars to quantify over (tau_tvs_plus - mono_tvs), being
423 careful to close over kinds, and to skolemise the quantified tyvars.
424 (This actually unifies each quantifies meta-tyvar with a fresh skolem.)
425 Result is qtvs.
426
427 * Filter the constraints using pickQuantifyablePreds and the qtvs.
428 We have to zonk the constraints first, so they "see" the freshly
429 created skolems.
430
431 If the MR does apply, mono_tvs includes all the constrained tyvars,
432 and the quantified constraints are empty.
433 -}
434
435 decideQuantification
436 :: Bool -- Apply monomorphism restriction
437 -> [PredType] -> TcTyVarSet -- Constraints and type variables from RHS
438 -> TcM ( [TcTyVar] -- Quantify over these tyvars (skolems)
439 , [PredType] -- and this context (fully zonked)
440 , Bool ) -- Did the MR bite?
441 -- See Note [Deciding quantification]
442 decideQuantification apply_mr constraints zonked_tau_tvs
443 | apply_mr -- Apply the Monomorphism restriction
444 = do { gbl_tvs <- tcGetGlobalTyVars
445 ; let constrained_tvs = tyVarsOfTypes constraints
446 mono_tvs = gbl_tvs `unionVarSet` constrained_tvs
447 mr_bites = constrained_tvs `intersectsVarSet` zonked_tau_tvs
448 ; qtvs <- quantifyTyVars mono_tvs zonked_tau_tvs
449 ; traceTc "decideQuantification 1" (vcat [ppr constraints, ppr gbl_tvs, ppr mono_tvs, ppr qtvs])
450 ; return (qtvs, [], mr_bites) }
451
452 | otherwise
453 = do { gbl_tvs <- tcGetGlobalTyVars
454 ; let mono_tvs = growThetaTyVars (filter isEqPred constraints) gbl_tvs
455 tau_tvs_plus = growThetaTyVars constraints zonked_tau_tvs
456 ; qtvs <- quantifyTyVars mono_tvs tau_tvs_plus
457 ; constraints <- zonkTcThetaType constraints
458 -- quantifyTyVars turned some meta tyvars into
459 -- quantified skolems, so we have to zonk again
460
461 ; theta <- pickQuantifiablePreds (mkVarSet qtvs) constraints
462 ; let min_theta = mkMinimalBySCs theta -- See Note [Minimize by Superclasses]
463
464 ; traceTc "decideQuantification 2" (vcat [ppr constraints, ppr gbl_tvs, ppr mono_tvs
465 , ppr tau_tvs_plus, ppr qtvs, ppr min_theta])
466 ; return (qtvs, min_theta, False) }
467
468 ------------------
469 pickQuantifiablePreds :: TyVarSet -- Quantifying over these
470 -> TcThetaType -- Proposed constraints to quantify
471 -> TcM TcThetaType -- A subset that we can actually quantify
472 -- This function decides whether a particular constraint shoudl be
473 -- quantified over, given the type variables that are being quantified
474 pickQuantifiablePreds qtvs theta
475 = do { flex_ctxt <- xoptM Opt_FlexibleContexts
476 ; return (filter (pick_me flex_ctxt) theta) }
477 where
478 pick_me flex_ctxt pred
479 = case classifyPredType pred of
480 ClassPred cls tys
481 | isIPClass cls -> True -- See note [Inheriting implicit parameters]
482 | otherwise -> pick_cls_pred flex_ctxt tys
483
484 EqPred ReprEq ty1 ty2 -> pick_cls_pred flex_ctxt [ty1, ty2]
485 -- Representational equality is like a class constraint
486
487 EqPred NomEq ty1 ty2 -> quant_fun ty1 || quant_fun ty2
488 IrredPred ty -> tyVarsOfType ty `intersectsVarSet` qtvs
489 TuplePred {} -> False
490
491 pick_cls_pred flex_ctxt tys
492 = tyVarsOfTypes tys `intersectsVarSet` qtvs
493 && (checkValidClsArgs flex_ctxt tys)
494 -- Only quantify over predicates that checkValidType
495 -- will pass! See Trac #10351.
496
497 -- See Note [Quantifying over equality constraints]
498 quant_fun ty
499 = case tcSplitTyConApp_maybe ty of
500 Just (tc, tys) | isTypeFamilyTyCon tc
501 -> tyVarsOfTypes tys `intersectsVarSet` qtvs
502 _ -> False
503
504 ------------------
505 growThetaTyVars :: ThetaType -> TyVarSet -> TyVarSet
506 -- See Note [Growing the tau-tvs using constraints]
507 growThetaTyVars theta tvs
508 | null theta = tvs
509 | otherwise = transCloVarSet mk_next seed_tvs
510 where
511 seed_tvs = tvs `unionVarSet` tyVarsOfTypes ips
512 (ips, non_ips) = partition isIPPred theta
513 -- See note [Inheriting implicit parameters]
514
515 mk_next :: VarSet -> VarSet -- Maps current set to newly-grown ones
516 mk_next so_far = foldr (grow_one so_far) emptyVarSet non_ips
517 grow_one so_far pred tvs
518 | pred_tvs `intersectsVarSet` so_far = tvs `unionVarSet` pred_tvs
519 | otherwise = tvs
520 where
521 pred_tvs = tyVarsOfType pred
522
523 {-
524 Note [Quantifying over equality constraints]
525 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
526 Should we quantify over an equality constraint (s ~ t)? In general, we don't.
527 Doing so may simply postpone a type error from the function definition site to
528 its call site. (At worst, imagine (Int ~ Bool)).
529
530 However, consider this
531 forall a. (F [a] ~ Int) => blah
532 Should we quantify over the (F [a] ~ Int). Perhaps yes, because at the call
533 site we will know 'a', and perhaps we have instance F [Bool] = Int.
534 So we *do* quantify over a type-family equality where the arguments mention
535 the quantified variables.
536
537 Note [Growing the tau-tvs using constraints]
538 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
539 (growThetaTyVars insts tvs) is the result of extending the set
540 of tyvars tvs using all conceivable links from pred
541
542 E.g. tvs = {a}, preds = {H [a] b, K (b,Int) c, Eq e}
543 Then growThetaTyVars preds tvs = {a,b,c}
544
545 Notice that
546 growThetaTyVars is conservative if v might be fixed by vs
547 => v `elem` grow(vs,C)
548
549 Note [Inheriting implicit parameters]
550 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
551 Consider this:
552
553 f x = (x::Int) + ?y
554
555 where f is *not* a top-level binding.
556 From the RHS of f we'll get the constraint (?y::Int).
557 There are two types we might infer for f:
558
559 f :: Int -> Int
560
561 (so we get ?y from the context of f's definition), or
562
563 f :: (?y::Int) => Int -> Int
564
565 At first you might think the first was better, because then
566 ?y behaves like a free variable of the definition, rather than
567 having to be passed at each call site. But of course, the WHOLE
568 IDEA is that ?y should be passed at each call site (that's what
569 dynamic binding means) so we'd better infer the second.
570
571 BOTTOM LINE: when *inferring types* you must quantify over implicit
572 parameters, *even if* they don't mention the bound type variables.
573 Reason: because implicit parameters, uniquely, have local instance
574 declarations. See the pickQuantifiablePreds.
575
576 Note [Quantification with errors]
577 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
578 If we find that the RHS of the definition has some absolutely-insoluble
579 constraints, we abandon all attempts to find a context to quantify
580 over, and instead make the function fully-polymorphic in whatever
581 type we have found. For two reasons
582 a) Minimise downstream errors
583 b) Avoid spurious errors from this function
584
585 But NB that we must include *derived* errors in the check. Example:
586 (a::*) ~ Int#
587 We get an insoluble derived error *~#, and we don't want to discard
588 it before doing the isInsolubleWC test! (Trac #8262)
589
590 Note [Default while Inferring]
591 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
592 Our current plan is that defaulting only happens at simplifyTop and
593 not simplifyInfer. This may lead to some insoluble deferred constraints
594 Example:
595
596 instance D g => C g Int b
597
598 constraint inferred = (forall b. 0 => C gamma alpha b) /\ Num alpha
599 type inferred = gamma -> gamma
600
601 Now, if we try to default (alpha := Int) we will be able to refine the implication to
602 (forall b. 0 => C gamma Int b)
603 which can then be simplified further to
604 (forall b. 0 => D gamma)
605 Finally we /can/ approximate this implication with (D gamma) and infer the quantified
606 type: forall g. D g => g -> g
607
608 Instead what will currently happen is that we will get a quantified type
609 (forall g. g -> g) and an implication:
610 forall g. 0 => (forall b. 0 => C g alpha b) /\ Num alpha
611
612 which, even if the simplifyTop defaults (alpha := Int) we will still be left with an
613 unsolvable implication:
614 forall g. 0 => (forall b. 0 => D g)
615
616 The concrete example would be:
617 h :: C g a s => g -> a -> ST s a
618 f (x::gamma) = (\_ -> x) (runST (h x (undefined::alpha)) + 1)
619
620 But it is quite tedious to do defaulting and resolve the implication constraints and
621 we have not observed code breaking because of the lack of defaulting in inference so
622 we don't do it for now.
623
624
625
626 Note [Minimize by Superclasses]
627 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
628 When we quantify over a constraint, in simplifyInfer we need to
629 quantify over a constraint that is minimal in some sense: For
630 instance, if the final wanted constraint is (Eq alpha, Ord alpha),
631 we'd like to quantify over Ord alpha, because we can just get Eq alpha
632 from superclass selection from Ord alpha. This minimization is what
633 mkMinimalBySCs does. Then, simplifyInfer uses the minimal constraint
634 to check the original wanted.
635
636
637 Note [Avoid unecessary constraint simplification]
638 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
639 -------- NB NB NB (Jun 12) -------------
640 This note not longer applies; see the notes with Trac #4361.
641 But I'm leaving it in here so we remember the issue.)
642 ----------------------------------------
643 When inferring the type of a let-binding, with simplifyInfer,
644 try to avoid unnecessarily simplifying class constraints.
645 Doing so aids sharing, but it also helps with delicate
646 situations like
647
648 instance C t => C [t] where ..
649
650 f :: C [t] => ....
651 f x = let g y = ...(constraint C [t])...
652 in ...
653 When inferring a type for 'g', we don't want to apply the
654 instance decl, because then we can't satisfy (C t). So we
655 just notice that g isn't quantified over 't' and partition
656 the constraints before simplifying.
657
658 This only half-works, but then let-generalisation only half-works.
659
660
661 *********************************************************************************
662 * *
663 * Main Simplifier *
664 * *
665 ***********************************************************************************
666
667 Note [Deferring coercion errors to runtime]
668 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
669 While developing, sometimes it is desirable to allow compilation to succeed even
670 if there are type errors in the code. Consider the following case:
671
672 module Main where
673
674 a :: Int
675 a = 'a'
676
677 main = print "b"
678
679 Even though `a` is ill-typed, it is not used in the end, so if all that we're
680 interested in is `main` it is handy to be able to ignore the problems in `a`.
681
682 Since we treat type equalities as evidence, this is relatively simple. Whenever
683 we run into a type mismatch in TcUnify, we normally just emit an error. But it
684 is always safe to defer the mismatch to the main constraint solver. If we do
685 that, `a` will get transformed into
686
687 co :: Int ~ Char
688 co = ...
689
690 a :: Int
691 a = 'a' `cast` co
692
693 The constraint solver would realize that `co` is an insoluble constraint, and
694 emit an error with `reportUnsolved`. But we can also replace the right-hand side
695 of `co` with `error "Deferred type error: Int ~ Char"`. This allows the program
696 to compile, and it will run fine unless we evaluate `a`. This is what
697 `deferErrorsToRuntime` does.
698
699 It does this by keeping track of which errors correspond to which coercion
700 in TcErrors (with ErrEnv). TcErrors.reportTidyWanteds does not print the errors
701 and does not fail if -fdefer-type-errors is on, so that we can continue
702 compilation. The errors are turned into warnings in `reportUnsolved`.
703 -}
704
705 solveWantedsTcM :: [CtEvidence] -> TcM WantedConstraints
706 -- Simplify the input constraints
707 -- Discard the evidence binds
708 -- Discards all Derived stuff in result
709 -- Result is /not/ guaranteed zonked
710 solveWantedsTcM wanted
711 = do { (wanted1, _binds) <- runTcS (solveWantedsAndDrop (mkSimpleWC wanted))
712 ; return wanted1 }
713
714 solveWantedsAndDrop :: WantedConstraints -> TcS WantedConstraints
715 -- Since solveWanteds returns the residual WantedConstraints,
716 -- it should always be called within a runTcS or something similar,
717 -- Result is not zonked
718 solveWantedsAndDrop wanted
719 = do { wc <- solveWanteds wanted
720 ; return (dropDerivedWC wc) }
721
722 solveWanteds :: WantedConstraints -> TcS WantedConstraints
723 -- so that the inert set doesn't mindlessly propagate.
724 -- NB: wc_simples may be wanted /or/ derived now
725 solveWanteds wc@(WC { wc_simple = simples, wc_insol = insols, wc_impl = implics })
726 = do { traceTcS "solveWanteds {" (ppr wc)
727
728 -- Try the simple bit, including insolubles. Solving insolubles a
729 -- second time round is a bit of a waste; but the code is simple
730 -- and the program is wrong anyway, and we don't run the danger
731 -- of adding Derived insolubles twice; see
732 -- TcSMonad Note [Do not add duplicate derived insolubles]
733 ; wc1 <- solveSimpleWanteds simples
734 ; let WC { wc_simple = simples1, wc_insol = insols1, wc_impl = implics1 } = wc1
735
736 ; (floated_eqs, implics2) <- solveNestedImplications (implics `unionBags` implics1)
737
738 ; final_wc <- simpl_loop 0 floated_eqs
739 (WC { wc_simple = simples1, wc_impl = implics2
740 , wc_insol = insols `unionBags` insols1 })
741
742 ; bb <- getTcEvBindsMap
743 ; traceTcS "solveWanteds }" $
744 vcat [ text "final wc =" <+> ppr final_wc
745 , text "current evbinds =" <+> ppr (evBindMapBinds bb) ]
746
747 ; return final_wc }
748
749 simpl_loop :: Int -> Cts
750 -> WantedConstraints
751 -> TcS WantedConstraints
752 simpl_loop n floated_eqs
753 wc@(WC { wc_simple = simples, wc_insol = insols, wc_impl = implics })
754 | n > 10
755 = do { traceTcS "solveWanteds: loop!" (ppr wc); return wc }
756
757 | no_floated_eqs
758 = return wc -- Done!
759
760 | otherwise
761 = do { traceTcS "simpl_loop, iteration" (int n)
762
763 -- solveSimples may make progress if either float_eqs hold
764 ; (unifs_happened1, wc1) <- if no_floated_eqs
765 then return (False, emptyWC)
766 else reportUnifications $
767 solveSimpleWanteds (floated_eqs `unionBags` simples)
768 -- Put floated_eqs first so they get solved first
769 -- NB: the floated_eqs may include /derived/ equalities
770 -- arising from fundeps inside an implication
771
772 ; let WC { wc_simple = simples1, wc_insol = insols1, wc_impl = implics1 } = wc1
773
774 -- solveImplications may make progress only if unifs2 holds
775 ; (floated_eqs2, implics2) <- if not unifs_happened1 && isEmptyBag implics1
776 then return (emptyBag, implics)
777 else solveNestedImplications (implics `unionBags` implics1)
778
779 ; simpl_loop (n+1) floated_eqs2
780 (WC { wc_simple = simples1, wc_impl = implics2
781 , wc_insol = insols `unionBags` insols1 }) }
782
783 where
784 no_floated_eqs = isEmptyBag floated_eqs
785
786 solveNestedImplications :: Bag Implication
787 -> TcS (Cts, Bag Implication)
788 -- Precondition: the TcS inerts may contain unsolved simples which have
789 -- to be converted to givens before we go inside a nested implication.
790 solveNestedImplications implics
791 | isEmptyBag implics
792 = return (emptyBag, emptyBag)
793 | otherwise
794 = do { traceTcS "solveNestedImplications starting {" empty
795 ; (floated_eqs_s, unsolved_implics) <- mapAndUnzipBagM solveImplication implics
796 ; let floated_eqs = concatBag floated_eqs_s
797
798 -- ... and we are back in the original TcS inerts
799 -- Notice that the original includes the _insoluble_simples so it was safe to ignore
800 -- them in the beginning of this function.
801 ; traceTcS "solveNestedImplications end }" $
802 vcat [ text "all floated_eqs =" <+> ppr floated_eqs
803 , text "unsolved_implics =" <+> ppr unsolved_implics ]
804
805 ; return (floated_eqs, catBagMaybes unsolved_implics) }
806
807 solveImplication :: Implication -- Wanted
808 -> TcS (Cts, -- All wanted or derived floated equalities: var = type
809 Maybe Implication) -- Simplified implication (empty or singleton)
810 -- Precondition: The TcS monad contains an empty worklist and given-only inerts
811 -- which after trying to solve this implication we must restore to their original value
812 solveImplication imp@(Implic { ic_tclvl = tclvl
813 , ic_binds = ev_binds
814 , ic_skols = skols
815 , ic_given = givens
816 , ic_wanted = wanteds
817 , ic_info = info
818 , ic_status = status
819 , ic_env = env })
820 | IC_Solved {} <- status
821 = return (emptyCts, Just imp) -- Do nothing
822
823 | otherwise -- Even for IC_Insoluble it is worth doing more work
824 -- The insoluble stuff might be in one sub-implication
825 -- and other unsolved goals in another; and we want to
826 -- solve the latter as much as possible
827 = do { inerts <- getTcSInerts
828 ; traceTcS "solveImplication {" (ppr imp $$ text "Inerts" <+> ppr inerts)
829
830 -- Solve the nested constraints
831 ; (no_given_eqs, given_insols, residual_wanted)
832 <- nestImplicTcS ev_binds tclvl $
833 do { given_insols <- solveSimpleGivens (mkGivenLoc tclvl info env) givens
834 ; no_eqs <- getNoGivenEqs tclvl skols
835
836 ; residual_wanted <- solveWanteds wanteds
837 -- solveWanteds, *not* solveWantedsAndDrop, because
838 -- we want to retain derived equalities so we can float
839 -- them out in floatEqualities
840
841 ; return (no_eqs, given_insols, residual_wanted) }
842
843 ; (floated_eqs, residual_wanted)
844 <- floatEqualities skols no_given_eqs residual_wanted
845
846 ; let final_wanted = residual_wanted `addInsols` given_insols
847
848 ; res_implic <- setImplicationStatus (imp { ic_no_eqs = no_given_eqs
849 , ic_wanted = final_wanted })
850
851 ; evbinds <- getTcEvBindsMap
852 ; traceTcS "solveImplication end }" $ vcat
853 [ text "no_given_eqs =" <+> ppr no_given_eqs
854 , text "floated_eqs =" <+> ppr floated_eqs
855 , text "res_implic =" <+> ppr res_implic
856 , text "implication evbinds = " <+> ppr (evBindMapBinds evbinds) ]
857
858 ; return (floated_eqs, res_implic) }
859
860 ----------------------
861 setImplicationStatus :: Implication -> TcS (Maybe Implication)
862 -- Finalise the implication returned from solveImplication:
863 -- * Set the ic_status field
864 -- * Trim the ic_wanted field to remove Derived constraints
865 -- Return Nothing if we can discard the implication altogether
866 setImplicationStatus implic@(Implic { ic_binds = EvBindsVar ev_binds_var _
867 , ic_info = info
868 , ic_wanted = wc
869 , ic_given = givens })
870 | some_insoluble
871 = return $ Just $
872 implic { ic_status = IC_Insoluble
873 , ic_wanted = wc { wc_simple = pruned_simples
874 , wc_insol = pruned_insols } }
875
876 | some_unsolved
877 = return $ Just $
878 implic { ic_status = IC_Unsolved
879 , ic_wanted = wc { wc_simple = pruned_simples
880 , wc_insol = pruned_insols } }
881
882 | otherwise -- Everything is solved; look at the implications
883 -- See Note [Tracking redundant constraints]
884 = do { ev_binds <- TcS.readTcRef ev_binds_var
885 ; let all_needs = neededEvVars ev_binds implic_needs
886
887 dead_givens | warnRedundantGivens info
888 = filterOut (`elemVarSet` all_needs) givens
889 | otherwise = [] -- None to report
890
891 final_needs = all_needs `delVarSetList` givens
892
893 discard_entire_implication -- Can we discard the entire implication?
894 = null dead_givens -- No warning from this implication
895 && isEmptyBag pruned_implics -- No live children
896 && isEmptyVarSet final_needs -- No needed vars to pass up to parent
897
898 final_status = IC_Solved { ics_need = final_needs
899 , ics_dead = dead_givens }
900 final_implic = implic { ic_status = final_status
901 , ic_wanted = wc { wc_simple = pruned_simples
902 , wc_insol = pruned_insols
903 , wc_impl = pruned_implics } }
904 -- We can only prune the child implications (pruned_implics)
905 -- in the IC_Solved status case, because only then we can
906 -- accumulate their needed evidence variales into the
907 -- IC_Solved final_status field of the parent implication.
908
909 ; return $ if discard_entire_implication
910 then Nothing
911 else Just final_implic }
912 where
913 WC { wc_simple = simples, wc_impl = implics, wc_insol = insols } = wc
914
915 some_insoluble = insolubleWC wc
916 some_unsolved = not (isEmptyBag simples && isEmptyBag insols)
917 || isNothing mb_implic_needs
918
919 pruned_simples = dropDerivedSimples simples
920 pruned_insols = dropDerivedInsols insols
921 pruned_implics = filterBag need_to_keep_implic implics
922
923 mb_implic_needs :: Maybe VarSet
924 -- Just vs => all implics are IC_Solved, with 'vs' needed
925 -- Nothing => at least one implic is not IC_Solved
926 mb_implic_needs = foldrBag add_implic (Just emptyVarSet) implics
927 Just implic_needs = mb_implic_needs
928
929 add_implic implic acc
930 | Just vs_acc <- acc
931 , IC_Solved { ics_need = vs } <- ic_status implic
932 = Just (vs `unionVarSet` vs_acc)
933 | otherwise = Nothing
934
935 need_to_keep_implic ic
936 | IC_Solved { ics_dead = [] } <- ic_status ic
937 -- Fully solved, and no redundant givens to report
938 , isEmptyBag (wc_impl (ic_wanted ic))
939 -- And no children that might have things to report
940 = False
941 | otherwise
942 = True
943
944 warnRedundantGivens :: SkolemInfo -> Bool
945 warnRedundantGivens (SigSkol ctxt _)
946 = case ctxt of
947 FunSigCtxt _ warn_redundant -> warn_redundant
948 ExprSigCtxt -> True
949 _ -> False
950 warnRedundantGivens InstSkol = True
951 warnRedundantGivens _ = False
952
953 neededEvVars :: EvBindMap -> VarSet -> VarSet
954 -- Find all the evidence variables that are "needed",
955 -- and then delete all those bound by the evidence bindings
956 -- A variable is "needed" if
957 -- a) it is free in the RHS of a Wanted EvBind (add_wanted)
958 -- b) it is free in the RHS of an EvBind whose LHS is needed (transClo)
959 -- c) it is in the ic_need_evs of a nested implication (initial_seeds)
960 -- (after removing the givens)
961 neededEvVars ev_binds initial_seeds
962 = needed `minusVarSet` bndrs
963 where
964 seeds = foldEvBindMap add_wanted initial_seeds ev_binds
965 needed = transCloVarSet also_needs seeds
966 bndrs = foldEvBindMap add_bndr emptyVarSet ev_binds
967
968 add_wanted :: EvBind -> VarSet -> VarSet
969 add_wanted (EvBind { eb_is_given = is_given, eb_rhs = rhs }) needs
970 | is_given = needs -- Add the rhs vars of the Wanted bindings only
971 | otherwise = evVarsOfTerm rhs `unionVarSet` needs
972
973 also_needs :: VarSet -> VarSet
974 also_needs needs
975 = foldVarSet add emptyVarSet needs
976 where
977 add v needs
978 | Just ev_bind <- lookupEvBind ev_binds v
979 , EvBind { eb_is_given = is_given, eb_rhs = rhs } <- ev_bind
980 , is_given
981 = evVarsOfTerm rhs `unionVarSet` needs
982 | otherwise
983 = needs
984
985 add_bndr :: EvBind -> VarSet -> VarSet
986 add_bndr (EvBind { eb_lhs = v }) vs = extendVarSet vs v
987
988
989 {-
990 Note [Tracking redundant constraints]
991 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
992 With Opt_WarnRedundantConstraints, GHC can report which
993 constraints of a type signature (or instance declaration) are
994 redundant, and can be omitted. Here is an overview of how it
995 works:
996
997 ----- What is a redudant constraint?
998
999 * The things that can be redundant are precisely the Given
1000 constraints of an implication.
1001
1002 * A constraint can be redundant in two different ways:
1003 a) It is implied by other givens. E.g.
1004 f :: (Eq a, Ord a) => blah -- Eq a unnecessary
1005 g :: (Eq a, a~b, Eq b) => blah -- Either Eq a or Eq b unnecessary
1006 b) It is not needed by the Wanted constraints covered by the
1007 implication E.g.
1008 f :: Eq a => a -> Bool
1009 f x = True -- Equality not uesd
1010
1011 * To find (a), when we have two Given constraints,
1012 we must be careful to drop the one that is a naked variable (if poss).
1013 So if we have
1014 f :: (Eq a, Ord a) => blah
1015 then we may find [G] sc_sel (d1::Ord a) :: Eq a
1016 [G] d2 :: Eq a
1017 We want to discard d2 in favour of the superclass selection from
1018 the Ord dictionary. This is done by TcInteract.solveOneFromTheOther
1019 See Note [Replacement vs keeping].
1020
1021 * To find (b) we need to know which evidence bindings are 'wanted';
1022 hence the eb_is_given field on an EvBind.
1023
1024 ----- How tracking works
1025
1026 * When the constraint solver finishes solving all the wanteds in
1027 an implication, it sets its status to IC_Solved
1028
1029 - The ics_dead field of IC_Solved records the subset of the ic_given
1030 of this implication that are redundant (not needed).
1031
1032 - The ics_need field of IC_Solved then records all the
1033 in-scope (given) evidence variables, bound by the context, that
1034 were needed to solve this implication, including all its nested
1035 implications. (We remove the ic_given of this implication from
1036 the set, of course.)
1037
1038 * We compute which evidence variables are needed by an implication
1039 in setImplicationStatus. A variable is needed if
1040 a) it is free in the RHS of a Wanted EvBind
1041 b) it is free in the RHS of an EvBind whose LHS is needed
1042 c) it is in the ics_need of a nested implication
1043
1044 * We need to be careful not to discard an implication
1045 prematurely, even one that is fully solved, because we might
1046 thereby forget which variables it needs, and hence wrongly
1047 report a constraint as redundant. But we can discard it once
1048 its free vars have been incorporated into its parent; or if it
1049 simply has no free vars. This careful discarding is also
1050 handled in setImplicationStatus
1051
1052 ----- Reporting redundant constraints
1053
1054 * TcErrors does the actual warning, in warnRedundantConstraints.
1055
1056 * We don't report redundant givens for *every* implication; only
1057 for those which reply True to TcSimplify.warnRedundantGivens:
1058
1059 - For example, in a class declaration, the default method *can*
1060 use the class constraint, but it certainly doesn't *have* to,
1061 and we don't want to report an error there.
1062
1063 - More subtly, in a function definition
1064 f :: (Ord a, Ord a, Ix a) => a -> a
1065 f x = rhs
1066 we do an ambiguity check on the type (which would find that one
1067 of the Ord a constraints was redundant), and then we check that
1068 the definition has that type (which might find that both are
1069 redundant). We don't want to report the same error twice, so
1070 we disable it for the ambiguity check. Hence the flag in
1071 TcType.FunSigCtxt.
1072
1073 This decision is taken in setImplicationStatus, rather than TcErrors
1074 so that we can discard implication constraints that we don't need.
1075 So ics_dead consists only of the *reportable* redundant givens.
1076
1077 ----- Shortcomings
1078
1079 Consider (see Trac #9939)
1080 f2 :: (Eq a, Ord a) => a -> a -> Bool
1081 -- Ord a redundant, but Eq a is reported
1082 f2 x y = (x == y)
1083
1084 We report (Eq a) as redundant, whereas actually (Ord a) is. But it's
1085 really not easy to detect that!
1086
1087
1088 Note [Cutting off simpl_loop]
1089 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1090 It is very important not to iterate in simpl_loop unless there is a chance
1091 of progress. Trac #8474 is a classic example:
1092
1093 * There's a deeply-nested chain of implication constraints.
1094 ?x:alpha => ?y1:beta1 => ... ?yn:betan => [W] ?x:Int
1095
1096 * From the innermost one we get a [D] alpha ~ Int,
1097 but alpha is untouchable until we get out to the outermost one
1098
1099 * We float [D] alpha~Int out (it is in floated_eqs), but since alpha
1100 is untouchable, the solveInteract in simpl_loop makes no progress
1101
1102 * So there is no point in attempting to re-solve
1103 ?yn:betan => [W] ?x:Int
1104 because we'll just get the same [D] again
1105
1106 * If we *do* re-solve, we'll get an ininite loop. It is cut off by
1107 the fixed bound of 10, but solving the next takes 10*10*...*10 (ie
1108 exponentially many) iterations!
1109
1110 Conclusion: we should iterate simpl_loop iff we will get more 'givens'
1111 in the inert set when solving the nested implications. That is the
1112 result of prepareInertsForImplications is larger. How can we tell
1113 this?
1114
1115 Consider floated_eqs (all wanted or derived):
1116
1117 (a) [W/D] CTyEqCan (a ~ ty). This can give rise to a new given only by causing
1118 a unification. So we count those unifications.
1119
1120 (b) [W] CFunEqCan (F tys ~ xi). Even though these are wanted, they
1121 are pushed in as givens by prepareInertsForImplications. See Note
1122 [Preparing inert set for implications] in TcSMonad. But because
1123 of that very fact, we won't generate another copy if we iterate
1124 simpl_loop. So we iterate if there any of these
1125 -}
1126
1127 promoteTyVar :: TcLevel -> TcTyVar -> TcS TcTyVar
1128 -- When we float a constraint out of an implication we must restore
1129 -- invariant (MetaTvInv) in Note [TcLevel and untouchable type variables] in TcType
1130 -- See Note [Promoting unification variables]
1131 promoteTyVar tclvl tv
1132 | isFloatedTouchableMetaTyVar tclvl tv
1133 = do { cloned_tv <- TcS.cloneMetaTyVar tv
1134 ; let rhs_tv = setMetaTyVarTcLevel cloned_tv tclvl
1135 ; unifyTyVar tv (mkTyVarTy rhs_tv)
1136 ; return rhs_tv }
1137 | otherwise
1138 = return tv
1139
1140 promoteAndDefaultTyVar :: TcLevel -> TcTyVarSet -> TcTyVar -> TcS TcTyVar
1141 -- See Note [Promote _and_ default when inferring]
1142 promoteAndDefaultTyVar tclvl gbl_tvs tv
1143 = do { tv1 <- if tv `elemVarSet` gbl_tvs
1144 then return tv
1145 else defaultTyVar tv
1146 ; promoteTyVar tclvl tv1 }
1147
1148 defaultTyVar :: TcTyVar -> TcS TcTyVar
1149 -- Precondition: MetaTyVars only
1150 -- See Note [DefaultTyVar]
1151 defaultTyVar the_tv
1152 | Just default_k <- defaultKind_maybe (tyVarKind the_tv)
1153 = do { tv' <- TcS.cloneMetaTyVar the_tv
1154 ; let new_tv = setTyVarKind tv' default_k
1155 ; traceTcS "defaultTyVar" (ppr the_tv <+> ppr new_tv)
1156 ; unifyTyVar the_tv (mkTyVarTy new_tv)
1157 ; return new_tv }
1158 -- Why not directly derived_pred = mkTcEqPred k default_k?
1159 -- See Note [DefaultTyVar]
1160 -- We keep the same TcLevel on tv'
1161
1162 | otherwise = return the_tv -- The common case
1163
1164 approximateWC :: WantedConstraints -> Cts
1165 -- Postcondition: Wanted or Derived Cts
1166 -- See Note [ApproximateWC]
1167 approximateWC wc
1168 = float_wc emptyVarSet wc
1169 where
1170 float_wc :: TcTyVarSet -> WantedConstraints -> Cts
1171 float_wc trapping_tvs (WC { wc_simple = simples, wc_impl = implics })
1172 = filterBag is_floatable simples `unionBags`
1173 do_bag (float_implic new_trapping_tvs) implics
1174 where
1175 is_floatable ct = tyVarsOfCt ct `disjointVarSet` new_trapping_tvs
1176 new_trapping_tvs = transCloVarSet grow trapping_tvs
1177
1178 grow :: VarSet -> VarSet -- Maps current trapped tyvars to newly-trapped ones
1179 grow so_far = foldrBag (grow_one so_far) emptyVarSet simples
1180 grow_one so_far ct tvs
1181 | ct_tvs `intersectsVarSet` so_far = tvs `unionVarSet` ct_tvs
1182 | otherwise = tvs
1183 where
1184 ct_tvs = tyVarsOfCt ct
1185
1186 float_implic :: TcTyVarSet -> Implication -> Cts
1187 float_implic trapping_tvs imp
1188 | ic_no_eqs imp -- No equalities, so float
1189 = float_wc new_trapping_tvs (ic_wanted imp)
1190 | otherwise -- Don't float out of equalities
1191 = emptyCts -- See Note [ApproximateWC]
1192 where
1193 new_trapping_tvs = trapping_tvs `extendVarSetList` ic_skols imp
1194 do_bag :: (a -> Bag c) -> Bag a -> Bag c
1195 do_bag f = foldrBag (unionBags.f) emptyBag
1196
1197 {-
1198 Note [ApproximateWC]
1199 ~~~~~~~~~~~~~~~~~~~~
1200 approximateWC takes a constraint, typically arising from the RHS of a
1201 let-binding whose type we are *inferring*, and extracts from it some
1202 *simple* constraints that we might plausibly abstract over. Of course
1203 the top-level simple constraints are plausible, but we also float constraints
1204 out from inside, if they are not captured by skolems.
1205
1206 The same function is used when doing type-class defaulting (see the call
1207 to applyDefaultingRules) to extract constraints that that might be defaulted.
1208
1209 There are two caveats:
1210
1211 1. We do *not* float anything out if the implication binds equality
1212 constraints, because that defeats the OutsideIn story. Consider
1213 data T a where
1214 TInt :: T Int
1215 MkT :: T a
1216
1217 f TInt = 3::Int
1218
1219 We get the implication (a ~ Int => res ~ Int), where so far we've decided
1220 f :: T a -> res
1221 We don't want to float (res~Int) out because then we'll infer
1222 f :: T a -> Int
1223 which is only on of the possible types. (GHC 7.6 accidentally *did*
1224 float out of such implications, which meant it would happily infer
1225 non-principal types.)
1226
1227 2. We do not float out an inner constraint that shares a type variable
1228 (transitively) with one that is trapped by a skolem. Eg
1229 forall a. F a ~ beta, Integral beta
1230 We don't want to float out (Integral beta). Doing so would be bad
1231 when defaulting, because then we'll default beta:=Integer, and that
1232 makes the error message much worse; we'd get
1233 Can't solve F a ~ Integer
1234 rather than
1235 Can't solve Integral (F a)
1236
1237 Moreover, floating out these "contaminated" constraints doesn't help
1238 when generalising either. If we generalise over (Integral b), we still
1239 can't solve the retained implication (forall a. F a ~ b). Indeed,
1240 arguably that too would be a harder error to understand.
1241
1242 Note [DefaultTyVar]
1243 ~~~~~~~~~~~~~~~~~~~
1244 defaultTyVar is used on any un-instantiated meta type variables to
1245 default the kind of OpenKind and ArgKind etc to *. This is important
1246 to ensure that instance declarations match. For example consider
1247
1248 instance Show (a->b)
1249 foo x = show (\_ -> True)
1250
1251 Then we'll get a constraint (Show (p ->q)) where p has kind ArgKind,
1252 and that won't match the typeKind (*) in the instance decl. See tests
1253 tc217 and tc175.
1254
1255 We look only at touchable type variables. No further constraints
1256 are going to affect these type variables, so it's time to do it by
1257 hand. However we aren't ready to default them fully to () or
1258 whatever, because the type-class defaulting rules have yet to run.
1259
1260 An important point is that if the type variable tv has kind k and the
1261 default is default_k we do not simply generate [D] (k ~ default_k) because:
1262
1263 (1) k may be ArgKind and default_k may be * so we will fail
1264
1265 (2) We need to rewrite all occurrences of the tv to be a type
1266 variable with the right kind and we choose to do this by rewriting
1267 the type variable /itself/ by a new variable which does have the
1268 right kind.
1269
1270 Note [Promote _and_ default when inferring]
1271 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1272 When we are inferring a type, we simplify the constraint, and then use
1273 approximateWC to produce a list of candidate constraints. Then we MUST
1274
1275 a) Promote any meta-tyvars that have been floated out by
1276 approximateWC, to restore invariant (MetaTvInv) described in
1277 Note [TcLevel and untouchable type variables] in TcType.
1278
1279 b) Default the kind of any meta-tyyvars that are not mentioned in
1280 in the environment.
1281
1282 To see (b), suppose the constraint is (C ((a :: OpenKind) -> Int)), and we
1283 have an instance (C ((x:*) -> Int)). The instance doesn't match -- but it
1284 should! If we don't solve the constraint, we'll stupidly quantify over
1285 (C (a->Int)) and, worse, in doing so zonkQuantifiedTyVar will quantify over
1286 (b:*) instead of (a:OpenKind), which can lead to disaster; see Trac #7332.
1287 Trac #7641 is a simpler example.
1288
1289 Note [Promoting unification variables]
1290 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1291 When we float an equality out of an implication we must "promote" free
1292 unification variables of the equality, in order to maintain Invariant
1293 (MetaTvInv) from Note [TcLevel and untouchable type variables] in TcType. for the
1294 leftover implication.
1295
1296 This is absolutely necessary. Consider the following example. We start
1297 with two implications and a class with a functional dependency.
1298
1299 class C x y | x -> y
1300 instance C [a] [a]
1301
1302 (I1) [untch=beta]forall b. 0 => F Int ~ [beta]
1303 (I2) [untch=beta]forall c. 0 => F Int ~ [[alpha]] /\ C beta [c]
1304
1305 We float (F Int ~ [beta]) out of I1, and we float (F Int ~ [[alpha]]) out of I2.
1306 They may react to yield that (beta := [alpha]) which can then be pushed inwards
1307 the leftover of I2 to get (C [alpha] [a]) which, using the FunDep, will mean that
1308 (alpha := a). In the end we will have the skolem 'b' escaping in the untouchable
1309 beta! Concrete example is in indexed_types/should_fail/ExtraTcsUntch.hs:
1310
1311 class C x y | x -> y where
1312 op :: x -> y -> ()
1313
1314 instance C [a] [a]
1315
1316 type family F a :: *
1317
1318 h :: F Int -> ()
1319 h = undefined
1320
1321 data TEx where
1322 TEx :: a -> TEx
1323
1324 f (x::beta) =
1325 let g1 :: forall b. b -> ()
1326 g1 _ = h [x]
1327 g2 z = case z of TEx y -> (h [[undefined]], op x [y])
1328 in (g1 '3', g2 undefined)
1329
1330
1331 Note [Solving Family Equations]
1332 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1333 After we are done with simplification we may be left with constraints of the form:
1334 [Wanted] F xis ~ beta
1335 If 'beta' is a touchable unification variable not already bound in the TyBinds
1336 then we'd like to create a binding for it, effectively "defaulting" it to be 'F xis'.
1337
1338 When is it ok to do so?
1339 1) 'beta' must not already be defaulted to something. Example:
1340
1341 [Wanted] F Int ~ beta <~ Will default [beta := F Int]
1342 [Wanted] F Char ~ beta <~ Already defaulted, can't default again. We
1343 have to report this as unsolved.
1344
1345 2) However, we must still do an occurs check when defaulting (F xis ~ beta), to
1346 set [beta := F xis] only if beta is not among the free variables of xis.
1347
1348 3) Notice that 'beta' can't be bound in ty binds already because we rewrite RHS
1349 of type family equations. See Inert Set invariants in TcInteract.
1350
1351 This solving is now happening during zonking, see Note [Unflattening while zonking]
1352 in TcMType.
1353
1354
1355 *********************************************************************************
1356 * *
1357 * Floating equalities *
1358 * *
1359 *********************************************************************************
1360
1361 Note [Float Equalities out of Implications]
1362 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1363 For ordinary pattern matches (including existentials) we float
1364 equalities out of implications, for instance:
1365 data T where
1366 MkT :: Eq a => a -> T
1367 f x y = case x of MkT _ -> (y::Int)
1368 We get the implication constraint (x::T) (y::alpha):
1369 forall a. [untouchable=alpha] Eq a => alpha ~ Int
1370 We want to float out the equality into a scope where alpha is no
1371 longer untouchable, to solve the implication!
1372
1373 But we cannot float equalities out of implications whose givens may
1374 yield or contain equalities:
1375
1376 data T a where
1377 T1 :: T Int
1378 T2 :: T Bool
1379 T3 :: T a
1380
1381 h :: T a -> a -> Int
1382
1383 f x y = case x of
1384 T1 -> y::Int
1385 T2 -> y::Bool
1386 T3 -> h x y
1387
1388 We generate constraint, for (x::T alpha) and (y :: beta):
1389 [untouchables = beta] (alpha ~ Int => beta ~ Int) -- From 1st branch
1390 [untouchables = beta] (alpha ~ Bool => beta ~ Bool) -- From 2nd branch
1391 (alpha ~ beta) -- From 3rd branch
1392
1393 If we float the equality (beta ~ Int) outside of the first implication and
1394 the equality (beta ~ Bool) out of the second we get an insoluble constraint.
1395 But if we just leave them inside the implications we unify alpha := beta and
1396 solve everything.
1397
1398 Principle:
1399 We do not want to float equalities out which may
1400 need the given *evidence* to become soluble.
1401
1402 Consequence: classes with functional dependencies don't matter (since there is
1403 no evidence for a fundep equality), but equality superclasses do matter (since
1404 they carry evidence).
1405 -}
1406
1407 floatEqualities :: [TcTyVar] -> Bool
1408 -> WantedConstraints
1409 -> TcS (Cts, WantedConstraints)
1410 -- Main idea: see Note [Float Equalities out of Implications]
1411 --
1412 -- Precondition: the wc_simple of the incoming WantedConstraints are
1413 -- fully zonked, so that we can see their free variables
1414 --
1415 -- Postcondition: The returned floated constraints (Cts) are only
1416 -- Wanted or Derived and come from the input wanted
1417 -- ev vars or deriveds
1418 --
1419 -- Also performs some unifications (via promoteTyVar), adding to
1420 -- monadically-carried ty_binds. These will be used when processing
1421 -- floated_eqs later
1422 --
1423 -- Subtleties: Note [Float equalities from under a skolem binding]
1424 -- Note [Skolem escape]
1425 floatEqualities skols no_given_eqs wanteds@(WC { wc_simple = simples })
1426 | not no_given_eqs -- There are some given equalities, so don't float
1427 = return (emptyBag, wanteds) -- Note [Float Equalities out of Implications]
1428 | otherwise
1429 = do { outer_tclvl <- TcS.getTcLevel
1430 ; mapM_ (promoteTyVar outer_tclvl) (varSetElems (tyVarsOfCts float_eqs))
1431 -- See Note [Promoting unification variables]
1432 ; traceTcS "floatEqualities" (vcat [ text "Skols =" <+> ppr skols
1433 , text "Simples =" <+> ppr simples
1434 , text "Floated eqs =" <+> ppr float_eqs ])
1435 ; return (float_eqs, wanteds { wc_simple = remaining_simples }) }
1436 where
1437 skol_set = mkVarSet skols
1438 (float_eqs, remaining_simples) = partitionBag (usefulToFloat is_useful) simples
1439 is_useful pred = tyVarsOfType pred `disjointVarSet` skol_set
1440
1441 {- Note [Float equalities from under a skolem binding]
1442 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1443 Which of the simple equalities can we float out? Obviously, only
1444 ones that don't mention the skolem-bound variables. But that is
1445 over-eager. Consider
1446 [2] forall a. F a beta[1] ~ gamma[2], G beta[1] gamma[2] ~ Int
1447 The second constraint doesn't mention 'a'. But if we float it
1448 we'll promote gamma[2] to gamma'[1]. Now suppose that we learn that
1449 beta := Bool, and F a Bool = a, and G Bool _ = Int. Then we'll
1450 we left with the constraint
1451 [2] forall a. a ~ gamma'[1]
1452 which is insoluble because gamma became untouchable.
1453
1454 Solution: float only constraints that stand a jolly good chance of
1455 being soluble simply by being floated, namely ones of form
1456 a ~ ty
1457 where 'a' is a currently-untouchable unification variable, but may
1458 become touchable by being floated (perhaps by more than one level).
1459
1460 We had a very complicated rule previously, but this is nice and
1461 simple. (To see the notes, look at this Note in a version of
1462 TcSimplify prior to Oct 2014).
1463
1464 Note [Skolem escape]
1465 ~~~~~~~~~~~~~~~~~~~~
1466 You might worry about skolem escape with all this floating.
1467 For example, consider
1468 [2] forall a. (a ~ F beta[2] delta,
1469 Maybe beta[2] ~ gamma[1])
1470
1471 The (Maybe beta ~ gamma) doesn't mention 'a', so we float it, and
1472 solve with gamma := beta. But what if later delta:=Int, and
1473 F b Int = b.
1474 Then we'd get a ~ beta[2], and solve to get beta:=a, and now the
1475 skolem has escaped!
1476
1477 But it's ok: when we float (Maybe beta[2] ~ gamma[1]), we promote beta[2]
1478 to beta[1], and that means the (a ~ beta[1]) will be stuck, as it should be.
1479
1480
1481 *********************************************************************************
1482 * *
1483 * Defaulting and disamgiguation *
1484 * *
1485 *********************************************************************************
1486 -}
1487
1488 applyDefaultingRules :: WantedConstraints -> TcS Bool
1489 -- True <=> I did some defaulting, by unifying a meta-tyvar
1490 -- Imput WantedConstraints are not necessarily zonked
1491
1492 applyDefaultingRules wanteds
1493 | isEmptyWC wanteds
1494 = return False
1495 | otherwise
1496 = do { info@(default_tys, _) <- getDefaultInfo
1497 ; wanteds <- TcS.zonkWC wanteds
1498
1499 ; let groups = findDefaultableGroups info wanteds
1500
1501 ; traceTcS "applyDefaultingRules {" $
1502 vcat [ text "wanteds =" <+> ppr wanteds
1503 , text "groups =" <+> ppr groups
1504 , text "info =" <+> ppr info ]
1505
1506 ; something_happeneds <- mapM (disambigGroup default_tys) groups
1507
1508 ; traceTcS "applyDefaultingRules }" (ppr something_happeneds)
1509
1510 ; return (or something_happeneds) }
1511
1512 findDefaultableGroups
1513 :: ( [Type]
1514 , (Bool,Bool) ) -- (Overloaded strings, extended default rules)
1515 -> WantedConstraints -- Unsolved (wanted or derived)
1516 -> [(TyVar, [Ct])]
1517 findDefaultableGroups (default_tys, (ovl_strings, extended_defaults)) wanteds
1518 | null default_tys
1519 = []
1520 | otherwise
1521 = [ (tv, map fstOf3 group)
1522 | group@((_,_,tv):_) <- unary_groups
1523 , defaultable_tyvar tv
1524 , defaultable_classes (map sndOf3 group) ]
1525 where
1526 simples = approximateWC wanteds
1527 (unaries, non_unaries) = partitionWith find_unary (bagToList simples)
1528 unary_groups = equivClasses cmp_tv unaries
1529
1530 unary_groups :: [[(Ct, Class, TcTyVar)]] -- (C tv) constraints
1531 unaries :: [(Ct, Class, TcTyVar)] -- (C tv) constraints
1532 non_unaries :: [Ct] -- and *other* constraints
1533
1534 -- Finds unary type-class constraints
1535 -- But take account of polykinded classes like Typeable,
1536 -- which may look like (Typeable * (a:*)) (Trac #8931)
1537 find_unary cc
1538 | Just (cls,tys) <- getClassPredTys_maybe (ctPred cc)
1539 , Just (kinds, ty) <- snocView tys -- Ignore kind arguments
1540 , all isKind kinds -- for this purpose
1541 , Just tv <- tcGetTyVar_maybe ty
1542 , isMetaTyVar tv -- We might have runtime-skolems in GHCi, and
1543 -- we definitely don't want to try to assign to those!
1544 = Left (cc, cls, tv)
1545 find_unary cc = Right cc -- Non unary or non dictionary
1546
1547 bad_tvs :: TcTyVarSet -- TyVars mentioned by non-unaries
1548 bad_tvs = mapUnionVarSet tyVarsOfCt non_unaries
1549
1550 cmp_tv (_,_,tv1) (_,_,tv2) = tv1 `compare` tv2
1551
1552 defaultable_tyvar tv
1553 = let b1 = isTyConableTyVar tv -- Note [Avoiding spurious errors]
1554 b2 = not (tv `elemVarSet` bad_tvs)
1555 in b1 && b2
1556
1557 defaultable_classes clss
1558 | extended_defaults = any isInteractiveClass clss
1559 | otherwise = all is_std_class clss && (any is_num_class clss)
1560
1561 -- In interactive mode, or with -XExtendedDefaultRules,
1562 -- we default Show a to Show () to avoid graututious errors on "show []"
1563 isInteractiveClass cls
1564 = is_num_class cls || (classKey cls `elem` [showClassKey, eqClassKey, ordClassKey])
1565
1566 is_num_class cls = isNumericClass cls || (ovl_strings && (cls `hasKey` isStringClassKey))
1567 -- is_num_class adds IsString to the standard numeric classes,
1568 -- when -foverloaded-strings is enabled
1569
1570 is_std_class cls = isStandardClass cls || (ovl_strings && (cls `hasKey` isStringClassKey))
1571 -- Similarly is_std_class
1572
1573 ------------------------------
1574 disambigGroup :: [Type] -- The default types
1575 -> (TcTyVar, [Ct]) -- All classes of the form (C a)
1576 -- sharing same type variable
1577 -> TcS Bool -- True <=> something happened, reflected in ty_binds
1578
1579 disambigGroup [] _
1580 = return False
1581 disambigGroup (default_ty:default_tys) group@(the_tv, wanteds)
1582 = do { traceTcS "disambigGroup {" (vcat [ ppr default_ty, ppr the_tv, ppr wanteds ])
1583 ; fake_ev_binds_var <- TcS.newTcEvBinds
1584 ; tclvl <- TcS.getTcLevel
1585 ; success <- nestImplicTcS fake_ev_binds_var (pushTcLevel tclvl)
1586 try_group
1587
1588 ; if success then
1589 -- Success: record the type variable binding, and return
1590 do { unifyTyVar the_tv default_ty
1591 ; wrapWarnTcS $ warnDefaulting wanteds default_ty
1592 ; traceTcS "disambigGroup succeeded }" (ppr default_ty)
1593 ; return True }
1594 else
1595 -- Failure: try with the next type
1596 do { traceTcS "disambigGroup failed, will try other default types }"
1597 (ppr default_ty)
1598 ; disambigGroup default_tys group } }
1599 where
1600 try_group
1601 | Just subst <- mb_subst
1602 = do { wanted_evs <- mapM (newWantedEvVarNC loc . substTy subst . ctPred)
1603 wanteds
1604 ; residual_wanted <- solveSimpleWanteds $ listToBag $
1605 map mkNonCanonical wanted_evs
1606 ; return (isEmptyWC residual_wanted) }
1607 | otherwise
1608 = return False
1609
1610 tmpl_tvs = extendVarSet (tyVarsOfType (tyVarKind the_tv)) the_tv
1611 mb_subst = tcMatchTy tmpl_tvs (mkTyVarTy the_tv) default_ty
1612 -- Make sure the kinds match too; hence this call to tcMatchTy
1613 -- E.g. suppose the only constraint was (Typeable k (a::k))
1614
1615 loc = CtLoc { ctl_origin = GivenOrigin UnkSkol
1616 , ctl_env = panic "disambigGroup:env"
1617 , ctl_depth = initialSubGoalDepth }
1618
1619 {-
1620 Note [Avoiding spurious errors]
1621 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1622 When doing the unification for defaulting, we check for skolem
1623 type variables, and simply don't default them. For example:
1624 f = (*) -- Monomorphic
1625 g :: Num a => a -> a
1626 g x = f x x
1627 Here, we get a complaint when checking the type signature for g,
1628 that g isn't polymorphic enough; but then we get another one when
1629 dealing with the (Num a) context arising from f's definition;
1630 we try to unify a with Int (to default it), but find that it's
1631 already been unified with the rigid variable from g's type sig
1632 -}