Improve error messages for recursive superclasses
[ghc.git] / compiler / typecheck / TcSimplify.hs
1 {-# LANGUAGE CPP #-}
2
3 module TcSimplify(
4 simplifyInfer,
5 growThetaTyVars,
6 simplifyAmbiguityCheck,
7 simplifyDefault,
8 simplifyTop, simplifyInteractive, solveEqualities,
9 simplifyWantedsTcM,
10 tcCheckSatisfiability,
11
12 -- For Rules we need these
13 solveWanteds, runTcSDeriveds
14 ) where
15
16 #include "HsVersions.h"
17
18 import Bag
19 import Class ( Class, classKey, classTyCon )
20 import DynFlags ( WarningFlag ( Opt_WarnMonomorphism )
21 , DynFlags( solverIterations ) )
22 import Inst
23 import ListSetOps
24 import Maybes
25 import Name
26 import Outputable
27 import Pair
28 import PrelInfo
29 import PrelNames
30 import TcErrors
31 import TcEvidence
32 import TcInteract
33 import TcCanonical ( makeSuperClasses, mkGivensWithSuperClasses )
34 import TcMType as TcM
35 import TcRnMonad as TcM
36 import TcSMonad as TcS
37 import TcType
38 import TrieMap () -- DV: for now
39 import Type
40 import TysWiredIn ( liftedDataConTy )
41 import Unify ( tcMatchTy )
42 import Util
43 import Var
44 import VarSet
45 import BasicTypes ( IntWithInf, intGtLimit )
46 import ErrUtils ( emptyMessages )
47 import qualified GHC.LanguageExtensions as LangExt
48
49 import Control.Monad ( when, unless )
50 import Data.List ( partition )
51 import Data.Foldable ( fold )
52
53 {-
54 *********************************************************************************
55 * *
56 * External interface *
57 * *
58 *********************************************************************************
59 -}
60
61 simplifyTop :: WantedConstraints -> TcM (Bag EvBind)
62 -- Simplify top-level constraints
63 -- Usually these will be implications,
64 -- but when there is nothing to quantify we don't wrap
65 -- in a degenerate implication, so we do that here instead
66 simplifyTop wanteds
67 = do { traceTc "simplifyTop {" $ text "wanted = " <+> ppr wanteds
68 ; ((final_wc, unsafe_ol), binds1) <- runTcS $
69 do { final_wc <- simpl_top wanteds
70 ; unsafe_ol <- getSafeOverlapFailures
71 ; return (final_wc, unsafe_ol) }
72 ; traceTc "End simplifyTop }" empty
73
74 ; traceTc "reportUnsolved {" empty
75 ; binds2 <- reportUnsolved final_wc
76 ; traceTc "reportUnsolved }" empty
77
78 ; traceTc "reportUnsolved (unsafe overlapping) {" empty
79 ; unless (isEmptyCts unsafe_ol) $ do {
80 -- grab current error messages and clear, warnAllUnsolved will
81 -- update error messages which we'll grab and then restore saved
82 -- messages.
83 ; errs_var <- getErrsVar
84 ; saved_msg <- TcM.readTcRef errs_var
85 ; TcM.writeTcRef errs_var emptyMessages
86
87 ; warnAllUnsolved $ WC { wc_simple = unsafe_ol
88 , wc_insol = emptyCts
89 , wc_impl = emptyBag }
90
91 ; whyUnsafe <- fst <$> TcM.readTcRef errs_var
92 ; TcM.writeTcRef errs_var saved_msg
93 ; recordUnsafeInfer whyUnsafe
94 }
95 ; traceTc "reportUnsolved (unsafe overlapping) }" empty
96
97 ; return (evBindMapBinds binds1 `unionBags` binds2) }
98
99 -- | Type-check a thing that emits only equality constraints, then
100 -- solve those constraints. Emits errors -- but does not fail --
101 -- if there is trouble.
102 solveEqualities :: TcM a -> TcM a
103 solveEqualities thing_inside
104 = do { (result, wanted) <- captureConstraints thing_inside
105 ; traceTc "solveEqualities {" $ text "wanted = " <+> ppr wanted
106 ; final_wc <- runTcSEqualities $ simpl_top wanted
107 ; traceTc "End solveEqualities }" empty
108
109 ; traceTc "reportAllUnsolved {" empty
110 ; reportAllUnsolved final_wc
111 ; traceTc "reportAllUnsolved }" empty
112 ; return result }
113
114 simpl_top :: WantedConstraints -> TcS WantedConstraints
115 -- See Note [Top-level Defaulting Plan]
116 simpl_top wanteds
117 = do { wc_first_go <- nestTcS (solveWantedsAndDrop wanteds)
118 -- This is where the main work happens
119 ; try_tyvar_defaulting wc_first_go }
120 where
121 try_tyvar_defaulting :: WantedConstraints -> TcS WantedConstraints
122 try_tyvar_defaulting wc
123 | isEmptyWC wc
124 = return wc
125 | otherwise
126 = do { free_tvs <- TcS.zonkTyCoVarsAndFV (tyCoVarsOfWC wc)
127 ; let meta_tvs = varSetElems (filterVarSet isMetaTyVar free_tvs)
128 -- zonkTyCoVarsAndFV: the wc_first_go is not yet zonked
129 -- filter isMetaTyVar: we might have runtime-skolems in GHCi,
130 -- and we definitely don't want to try to assign to those!
131
132 ; defaulted <- mapM defaultTyVarTcS meta_tvs -- Has unification side effects
133 ; if or defaulted
134 then do { wc_residual <- nestTcS (solveWanteds wc)
135 -- See Note [Must simplify after defaulting]
136 ; try_class_defaulting wc_residual }
137 else try_class_defaulting wc } -- No defaulting took place
138
139 try_class_defaulting :: WantedConstraints -> TcS WantedConstraints
140 try_class_defaulting wc
141 | isEmptyWC wc
142 = return wc
143 | otherwise -- See Note [When to do type-class defaulting]
144 = do { something_happened <- applyDefaultingRules wc
145 -- See Note [Top-level Defaulting Plan]
146 ; if something_happened
147 then do { wc_residual <- nestTcS (solveWantedsAndDrop wc)
148 ; try_class_defaulting wc_residual }
149 -- See Note [Overview of implicit CallStacks] in TcEvidence
150 else try_callstack_defaulting wc }
151
152 try_callstack_defaulting :: WantedConstraints -> TcS WantedConstraints
153 try_callstack_defaulting wc
154 | isEmptyWC wc
155 = return wc
156 | otherwise
157 = defaultCallStacks wc
158
159 -- | Default any remaining @CallStack@ constraints to empty @CallStack@s.
160 defaultCallStacks :: WantedConstraints -> TcS WantedConstraints
161 -- See Note [Overview of implicit CallStacks] in TcEvidence
162 defaultCallStacks wanteds
163 = do simples <- handle_simples (wc_simple wanteds)
164 implics <- mapBagM handle_implic (wc_impl wanteds)
165 return (wanteds { wc_simple = simples, wc_impl = implics })
166
167 where
168
169 handle_simples simples
170 = catBagMaybes <$> mapBagM defaultCallStack simples
171
172 handle_implic implic = do
173 wanteds <- defaultCallStacks (ic_wanted implic)
174 return (implic { ic_wanted = wanteds })
175
176 defaultCallStack ct
177 | Just (cls, tys) <- getClassPredTys_maybe (ctPred ct)
178 , Just _ <- isCallStackDict cls tys
179 = do { solveCallStack (cc_ev ct) EvCsEmpty
180 ; return Nothing }
181
182 defaultCallStack ct
183 = return (Just ct)
184
185
186 {-
187 Note [When to do type-class defaulting]
188 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
189 In GHC 7.6 and 7.8.2, we did type-class defaulting only if insolubleWC
190 was false, on the grounds that defaulting can't help solve insoluble
191 constraints. But if we *don't* do defaulting we may report a whole
192 lot of errors that would be solved by defaulting; these errors are
193 quite spurious because fixing the single insoluble error means that
194 defaulting happens again, which makes all the other errors go away.
195 This is jolly confusing: Trac #9033.
196
197 So it seems better to always do type-class defaulting.
198
199 However, always doing defaulting does mean that we'll do it in
200 situations like this (Trac #5934):
201 run :: (forall s. GenST s) -> Int
202 run = fromInteger 0
203 We don't unify the return type of fromInteger with the given function
204 type, because the latter involves foralls. So we're left with
205 (Num alpha, alpha ~ (forall s. GenST s) -> Int)
206 Now we do defaulting, get alpha := Integer, and report that we can't
207 match Integer with (forall s. GenST s) -> Int. That's not totally
208 stupid, but perhaps a little strange.
209
210 Another potential alternative would be to suppress *all* non-insoluble
211 errors if there are *any* insoluble errors, anywhere, but that seems
212 too drastic.
213
214 Note [Must simplify after defaulting]
215 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
216 We may have a deeply buried constraint
217 (t:*) ~ (a:Open)
218 which we couldn't solve because of the kind incompatibility, and 'a' is free.
219 Then when we default 'a' we can solve the constraint. And we want to do
220 that before starting in on type classes. We MUST do it before reporting
221 errors, because it isn't an error! Trac #7967 was due to this.
222
223 Note [Top-level Defaulting Plan]
224 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
225 We have considered two design choices for where/when to apply defaulting.
226 (i) Do it in SimplCheck mode only /whenever/ you try to solve some
227 simple constraints, maybe deep inside the context of implications.
228 This used to be the case in GHC 7.4.1.
229 (ii) Do it in a tight loop at simplifyTop, once all other constraints have
230 finished. This is the current story.
231
232 Option (i) had many disadvantages:
233 a) Firstly, it was deep inside the actual solver.
234 b) Secondly, it was dependent on the context (Infer a type signature,
235 or Check a type signature, or Interactive) since we did not want
236 to always start defaulting when inferring (though there is an exception to
237 this, see Note [Default while Inferring]).
238 c) It plainly did not work. Consider typecheck/should_compile/DfltProb2.hs:
239 f :: Int -> Bool
240 f x = const True (\y -> let w :: a -> a
241 w a = const a (y+1)
242 in w y)
243 We will get an implication constraint (for beta the type of y):
244 [untch=beta] forall a. 0 => Num beta
245 which we really cannot default /while solving/ the implication, since beta is
246 untouchable.
247
248 Instead our new defaulting story is to pull defaulting out of the solver loop and
249 go with option (ii), implemented at SimplifyTop. Namely:
250 - First, have a go at solving the residual constraint of the whole
251 program
252 - Try to approximate it with a simple constraint
253 - Figure out derived defaulting equations for that simple constraint
254 - Go round the loop again if you did manage to get some equations
255
256 Now, that has to do with class defaulting. However there exists type variable /kind/
257 defaulting. Again this is done at the top-level and the plan is:
258 - At the top-level, once you had a go at solving the constraint, do
259 figure out /all/ the touchable unification variables of the wanted constraints.
260 - Apply defaulting to their kinds
261
262 More details in Note [DefaultTyVar].
263
264 Note [Safe Haskell Overlapping Instances]
265 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
266 In Safe Haskell, we apply an extra restriction to overlapping instances. The
267 motive is to prevent untrusted code provided by a third-party, changing the
268 behavior of trusted code through type-classes. This is due to the global and
269 implicit nature of type-classes that can hide the source of the dictionary.
270
271 Another way to state this is: if a module M compiles without importing another
272 module N, changing M to import N shouldn't change the behavior of M.
273
274 Overlapping instances with type-classes can violate this principle. However,
275 overlapping instances aren't always unsafe. They are just unsafe when the most
276 selected dictionary comes from untrusted code (code compiled with -XSafe) and
277 overlaps instances provided by other modules.
278
279 In particular, in Safe Haskell at a call site with overlapping instances, we
280 apply the following rule to determine if it is a 'unsafe' overlap:
281
282 1) Most specific instance, I1, defined in an `-XSafe` compiled module.
283 2) I1 is an orphan instance or a MPTC.
284 3) At least one overlapped instance, Ix, is both:
285 A) from a different module than I1
286 B) Ix is not marked `OVERLAPPABLE`
287
288 This is a slightly involved heuristic, but captures the situation of an
289 imported module N changing the behavior of existing code. For example, if
290 condition (2) isn't violated, then the module author M must depend either on a
291 type-class or type defined in N.
292
293 Secondly, when should these heuristics be enforced? We enforced them when the
294 type-class method call site is in a module marked `-XSafe` or `-XTrustworthy`.
295 This allows `-XUnsafe` modules to operate without restriction, and for Safe
296 Haskell inferrence to infer modules with unsafe overlaps as unsafe.
297
298 One alternative design would be to also consider if an instance was imported as
299 a `safe` import or not and only apply the restriction to instances imported
300 safely. However, since instances are global and can be imported through more
301 than one path, this alternative doesn't work.
302
303 Note [Safe Haskell Overlapping Instances Implementation]
304 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
305
306 How is this implemented? It's complicated! So we'll step through it all:
307
308 1) `InstEnv.lookupInstEnv` -- Performs instance resolution, so this is where
309 we check if a particular type-class method call is safe or unsafe. We do this
310 through the return type, `ClsInstLookupResult`, where the last parameter is a
311 list of instances that are unsafe to overlap. When the method call is safe,
312 the list is null.
313
314 2) `TcInteract.matchClassInst` -- This module drives the instance resolution
315 / dictionary generation. The return type is `LookupInstResult`, which either
316 says no instance matched, or one found, and if it was a safe or unsafe
317 overlap.
318
319 3) `TcInteract.doTopReactDict` -- Takes a dictionary / class constraint and
320 tries to resolve it by calling (in part) `matchClassInst`. The resolving
321 mechanism has a work list (of constraints) that it process one at a time. If
322 the constraint can't be resolved, it's added to an inert set. When compiling
323 an `-XSafe` or `-XTrustworthy` module, we follow this approach as we know
324 compilation should fail. These are handled as normal constraint resolution
325 failures from here-on (see step 6).
326
327 Otherwise, we may be inferring safety (or using `-Wunsafe`), and
328 compilation should succeed, but print warnings and/or mark the compiled module
329 as `-XUnsafe`. In this case, we call `insertSafeOverlapFailureTcS` which adds
330 the unsafe (but resolved!) constraint to the `inert_safehask` field of
331 `InertCans`.
332
333 4) `TcSimplify.simplifyTop`:
334 * Call simpl_top, the top-level function for driving the simplifier for
335 constraint resolution.
336
337 * Once finished, call `getSafeOverlapFailures` to retrieve the
338 list of overlapping instances that were successfully resolved,
339 but unsafe. Remember, this is only applicable for generating warnings
340 (`-Wunsafe`) or inferring a module unsafe. `-XSafe` and `-XTrustworthy`
341 cause compilation failure by not resolving the unsafe constraint at all.
342
343 * For unresolved constraints (all types), call `TcErrors.reportUnsolved`,
344 while for resolved but unsafe overlapping dictionary constraints, call
345 `TcErrors.warnAllUnsolved`. Both functions convert constraints into a
346 warning message for the user.
347
348 * In the case of `warnAllUnsolved` for resolved, but unsafe
349 dictionary constraints, we collect the generated warning
350 message (pop it) and call `TcRnMonad.recordUnsafeInfer` to
351 mark the module we are compiling as unsafe, passing the
352 warning message along as the reason.
353
354 5) `TcErrors.*Unsolved` -- Generates error messages for constraints by
355 actually calling `InstEnv.lookupInstEnv` again! Yes, confusing, but all we
356 know is the constraint that is unresolved or unsafe. For dictionary, all we
357 know is that we need a dictionary of type C, but not what instances are
358 available and how they overlap. So we once again call `lookupInstEnv` to
359 figure that out so we can generate a helpful error message.
360
361 6) `TcRnMonad.recordUnsafeInfer` -- Save the unsafe result and reason in an
362 IORef called `tcg_safeInfer`.
363
364 7) `HscMain.tcRnModule'` -- Reads `tcg_safeInfer` after type-checking, calling
365 `HscMain.markUnsafeInfer` (passing the reason along) when safe-inferrence
366 failed.
367 -}
368
369 ------------------
370 simplifyAmbiguityCheck :: Type -> WantedConstraints -> TcM ()
371 simplifyAmbiguityCheck ty wanteds
372 = do { traceTc "simplifyAmbiguityCheck {" (text "type = " <+> ppr ty $$ text "wanted = " <+> ppr wanteds)
373 ; (final_wc, _) <- runTcS $ simpl_top wanteds
374 ; traceTc "End simplifyAmbiguityCheck }" empty
375
376 -- Normally report all errors; but with -XAllowAmbiguousTypes
377 -- report only insoluble ones, since they represent genuinely
378 -- inaccessible code
379 ; allow_ambiguous <- xoptM LangExt.AllowAmbiguousTypes
380 ; traceTc "reportUnsolved(ambig) {" empty
381 ; tc_lvl <- TcM.getTcLevel
382 ; unless (allow_ambiguous && not (insolubleWC tc_lvl final_wc))
383 (discardResult (reportUnsolved final_wc))
384 ; traceTc "reportUnsolved(ambig) }" empty
385
386 ; return () }
387
388 ------------------
389 simplifyInteractive :: WantedConstraints -> TcM (Bag EvBind)
390 simplifyInteractive wanteds
391 = traceTc "simplifyInteractive" empty >>
392 simplifyTop wanteds
393
394 ------------------
395 simplifyDefault :: ThetaType -- Wanted; has no type variables in it
396 -> TcM () -- Succeeds if the constraint is soluble
397 simplifyDefault theta
398 = do { traceTc "simplifyInteractive" empty
399 ; wanted <- newWanteds DefaultOrigin theta
400 ; unsolved <- simplifyWantedsTcM wanted
401
402 ; traceTc "reportUnsolved {" empty
403 ; reportAllUnsolved unsolved
404 ; traceTc "reportUnsolved }" empty
405
406 ; return () }
407
408 ------------------
409 tcCheckSatisfiability :: Bag EvVar -> TcM Bool
410 -- Return True if satisfiable, False if definitely contradictory
411 tcCheckSatisfiability given_ids
412 = do { lcl_env <- TcM.getLclEnv
413 ; let given_loc = mkGivenLoc topTcLevel UnkSkol lcl_env
414 ; (res, _ev_binds) <- runTcS $
415 do { traceTcS "checkSatisfiability {" (ppr given_ids)
416 ; given_cts <- mkGivensWithSuperClasses given_loc (bagToList given_ids)
417 -- See Note [Superclases and satisfiability]
418 ; insols <- solveSimpleGivens given_cts
419 ; insols <- try_harder insols
420 ; traceTcS "checkSatisfiability }" (ppr insols)
421 ; return (isEmptyBag insols) }
422 ; return res }
423 where
424 try_harder :: Cts -> TcS Cts
425 -- Maybe we have to search up the superclass chain to find
426 -- an unsatisfiable constraint. Example: pmcheck/T3927b.
427 -- At the moment we try just once
428 try_harder insols
429 | not (isEmptyBag insols) -- We've found that it's definitely unsatisfiable
430 = return insols -- Hurrah -- stop now.
431 | otherwise
432 = do { pending_given <- getPendingScDicts
433 ; new_given <- makeSuperClasses pending_given
434 ; solveSimpleGivens new_given }
435
436 {- Note [Superclases and satisfiability]
437 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
438 Expand superclasses before starting, because (Int ~ Bool), has
439 (Int ~~ Bool) as a superclass, which in turn has (Int ~N# Bool)
440 as a superclass, and it's the latter that is insoluble. See
441 Note [The equality types story] in TysPrim.
442
443 If we fail to prove unsatisfiability we (arbitrarily) try just once to
444 find superclasses, using try_harder. Reason: we might have a type
445 signature
446 f :: F op (Implements push) => ..
447 where F is a type function. This happened in Trac #3972.
448
449 We could do more than once but we'd have to have /some/ limit: in the
450 the recurisve case, we would go on forever in the common case where
451 the constraints /are/ satisfiable (Trac #10592 comment:12!).
452
453 For stratightforard situations without type functions the try_harder
454 step does nothing.
455
456
457 ***********************************************************************************
458 * *
459 * Inference
460 * *
461 ***********************************************************************************
462
463 Note [Inferring the type of a let-bound variable]
464 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
465 Consider
466 f x = rhs
467
468 To infer f's type we do the following:
469 * Gather the constraints for the RHS with ambient level *one more than*
470 the current one. This is done by the call
471 pushLevelAndCaptureConstraints (tcMonoBinds...)
472 in TcBinds.tcPolyInfer
473
474 * Call simplifyInfer to simplify the constraints and decide what to
475 quantify over. We pass in the level used for the RHS constraints,
476 here called rhs_tclvl.
477
478 This ensures that the implication constraint we generate, if any,
479 has a strictly-increased level compared to the ambient level outside
480 the let binding.
481
482 -}
483
484 simplifyInfer :: TcLevel -- Used when generating the constraints
485 -> Bool -- Apply monomorphism restriction
486 -> [TcIdSigInfo] -- Any signatures (possibly partial)
487 -> [(Name, TcTauType)] -- Variables to be generalised,
488 -- and their tau-types
489 -> WantedConstraints
490 -> TcM ([TcTyVar], -- Quantify over these type variables
491 [EvVar], -- ... and these constraints (fully zonked)
492 TcEvBinds) -- ... binding these evidence variables
493 simplifyInfer rhs_tclvl apply_mr sigs name_taus wanteds
494 | isEmptyWC wanteds
495 = do { gbl_tvs <- tcGetGlobalTyCoVars
496 ; qtkvs <- quantify_tvs sigs gbl_tvs $
497 splitDepVarsOfTypes (map snd name_taus)
498 ; traceTc "simplifyInfer: empty WC" (ppr name_taus $$ ppr qtkvs)
499 ; return (qtkvs, [], emptyTcEvBinds) }
500
501 | otherwise
502 = do { traceTc "simplifyInfer {" $ vcat
503 [ text "sigs =" <+> ppr sigs
504 , text "binds =" <+> ppr name_taus
505 , text "rhs_tclvl =" <+> ppr rhs_tclvl
506 , text "apply_mr =" <+> ppr apply_mr
507 , text "(unzonked) wanted =" <+> ppr wanteds
508 ]
509
510 -- First do full-blown solving
511 -- NB: we must gather up all the bindings from doing
512 -- this solving; hence (runTcSWithEvBinds ev_binds_var).
513 -- And note that since there are nested implications,
514 -- calling solveWanteds will side-effect their evidence
515 -- bindings, so we can't just revert to the input
516 -- constraint.
517
518 ; ev_binds_var <- TcM.newTcEvBinds
519 ; wanted_transformed_incl_derivs <- setTcLevel rhs_tclvl $
520 do { sig_derived <- concatMapM mkSigDerivedWanteds sigs
521 -- the False says we don't really need to solve all Deriveds
522 ; runTcSWithEvBinds False (Just ev_binds_var) $
523 solveWanteds (wanteds `addSimples` listToBag sig_derived) }
524 ; wanted_transformed_incl_derivs <- TcM.zonkWC wanted_transformed_incl_derivs
525
526 -- Find quant_pred_candidates, the predicates that
527 -- we'll consider quantifying over
528 -- NB: We do not do any defaulting when inferring a type, this can lead
529 -- to less polymorphic types, see Note [Default while Inferring]
530
531 ; tc_lcl_env <- TcM.getLclEnv
532 ; let wanted_transformed = dropDerivedWC wanted_transformed_incl_derivs
533 ; quant_pred_candidates -- Fully zonked
534 <- if insolubleWC rhs_tclvl wanted_transformed_incl_derivs
535 then return [] -- See Note [Quantification with errors]
536 -- NB: must include derived errors in this test,
537 -- hence "incl_derivs"
538
539 else do { let quant_cand = approximateWC wanted_transformed
540 meta_tvs = filter isMetaTyVar (varSetElems (tyCoVarsOfCts quant_cand))
541
542 ; gbl_tvs <- tcGetGlobalTyCoVars
543 -- Miminise quant_cand. We are not interested in any evidence
544 -- produced, because we are going to simplify wanted_transformed
545 -- again later. All we want here are the predicates over which to
546 -- quantify.
547 --
548 -- If any meta-tyvar unifications take place (unlikely),
549 -- we'll pick that up later.
550
551 -- See Note [Promote _and_ default when inferring]
552 ; let def_tyvar tv
553 = when (not $ tv `elemVarSet` gbl_tvs) $
554 defaultTyVar tv
555 ; mapM_ def_tyvar meta_tvs
556 ; mapM_ (promoteTyVar rhs_tclvl) meta_tvs
557
558 ; WC { wc_simple = simples }
559 <- setTcLevel rhs_tclvl $
560 runTcSDeriveds $
561 solveSimpleWanteds $
562 mapBag toDerivedCt quant_cand
563 -- NB: we don't want evidence,
564 -- so use Derived constraints
565
566 ; simples <- TcM.zonkSimples simples
567
568 ; return [ ctEvPred ev | ct <- bagToList simples
569 , let ev = ctEvidence ct ] }
570
571 -- NB: quant_pred_candidates is already fully zonked
572
573 -- Decide what type variables and constraints to quantify
574 ; zonked_taus <- mapM (TcM.zonkTcType . snd) name_taus
575 ; let zonked_tau_tkvs = splitDepVarsOfTypes zonked_taus
576 ; (qtvs, bound_theta)
577 <- decideQuantification apply_mr sigs name_taus
578 quant_pred_candidates zonked_tau_tkvs
579
580 -- Promote any type variables that are free in the inferred type
581 -- of the function:
582 -- f :: forall qtvs. bound_theta => zonked_tau
583 -- These variables now become free in the envt, and hence will show
584 -- up whenever 'f' is called. They may currently at rhs_tclvl, but
585 -- they had better be unifiable at the outer_tclvl!
586 -- Example: envt mentions alpha[1]
587 -- tau_ty = beta[2] -> beta[2]
588 -- consraints = alpha ~ [beta]
589 -- we don't quantify over beta (since it is fixed by envt)
590 -- so we must promote it! The inferred type is just
591 -- f :: beta -> beta
592 ; outer_tclvl <- TcM.getTcLevel
593 ; zonked_tau_tvs <- fold <$>
594 traverse TcM.zonkTyCoVarsAndFV zonked_tau_tkvs
595 -- decideQuantification turned some meta tyvars into
596 -- quantified skolems, so we have to zonk again
597
598 ; let phi_tvs = tyCoVarsOfTypes bound_theta
599 `unionVarSet` zonked_tau_tvs
600
601 promote_tvs = closeOverKinds phi_tvs `delVarSetList` qtvs
602 ; MASSERT2( closeOverKinds promote_tvs `subVarSet` promote_tvs
603 , ppr phi_tvs $$
604 ppr (closeOverKinds phi_tvs) $$
605 ppr promote_tvs $$
606 ppr (closeOverKinds promote_tvs) )
607 -- we really don't want a type to be promoted when its kind isn't!
608
609 -- promoteTyVar ignores coercion variables
610 ; mapM_ (promoteTyVar outer_tclvl) (varSetElems promote_tvs)
611
612 -- Emit an implication constraint for the
613 -- remaining constraints from the RHS
614 ; bound_theta_vars <- mapM TcM.newEvVar bound_theta
615 ; let skol_info = InferSkol [ (name, mkSigmaTy [] bound_theta ty)
616 | (name, ty) <- name_taus ]
617 -- Don't add the quantified variables here, because
618 -- they are also bound in ic_skols and we want them
619 -- to be tidied uniformly
620
621 implic = Implic { ic_tclvl = rhs_tclvl
622 , ic_skols = qtvs
623 , ic_no_eqs = False
624 , ic_given = bound_theta_vars
625 , ic_wanted = wanted_transformed
626 , ic_status = IC_Unsolved
627 , ic_binds = Just ev_binds_var
628 , ic_info = skol_info
629 , ic_env = tc_lcl_env }
630 ; emitImplication implic
631
632 -- All done!
633 ; traceTc "} simplifyInfer/produced residual implication for quantification" $
634 vcat [ text "quant_pred_candidates =" <+> ppr quant_pred_candidates
635 , text "zonked_taus" <+> ppr zonked_taus
636 , text "zonked_tau_tvs=" <+> ppr zonked_tau_tvs
637 , text "promote_tvs=" <+> ppr promote_tvs
638 , text "bound_theta =" <+> ppr bound_theta
639 , text "qtvs =" <+> ppr qtvs
640 , text "implic =" <+> ppr implic ]
641
642 ; return ( qtvs, bound_theta_vars, TcEvBinds ev_binds_var ) }
643
644 mkSigDerivedWanteds :: TcIdSigInfo -> TcM [Ct]
645 -- See Note [Add deriveds for signature contexts]
646 mkSigDerivedWanteds (TISI { sig_bndr = PartialSig { sig_name = name }
647 , sig_theta = theta, sig_tau = tau })
648 = do { let skol_info = InferSkol [(name, mkSigmaTy [] theta tau)]
649 ; loc <- getCtLocM (GivenOrigin skol_info) (Just TypeLevel)
650 ; return [ mkNonCanonical (CtDerived { ctev_pred = pred
651 , ctev_loc = loc })
652 | pred <- theta ] }
653 mkSigDerivedWanteds _ = return []
654
655 {- Note [Add deriveds for signature contexts]
656 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
657 Consider this (Trac #11016):
658 f2 :: (?x :: Int) => _
659 f2 = ?x
660 We'll use plan InferGen because there are holes in the type. But we want
661 to have the (?x :: Int) constraint floating around so that the functional
662 dependencies kick in. Otherwise the occurrence of ?x on the RHS produces
663 constraint (?x :: alpha), and we wont unify alpha:=Int.
664
665 Solution: in simplifyInfer, just before simplifying the constraints
666 gathered from the RHS, add Derived constraints for the context of any
667 type signatures. This is rare; if there is a type signature we'll usually
668 be doing CheckGen. But it happens for signatures with holes.
669
670 ************************************************************************
671 * *
672 Quantification
673 * *
674 ************************************************************************
675
676 Note [Deciding quantification]
677 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
678 If the monomorphism restriction does not apply, then we quantify as follows:
679 * Take the global tyvars, and "grow" them using the equality constraints
680 E.g. if x:alpha is in the environment, and alpha ~ [beta] (which can
681 happen because alpha is untouchable here) then do not quantify over
682 beta, because alpha fixes beta, and beta is effectively free in
683 the environment too
684 These are the mono_tvs
685
686 * Take the free vars of the tau-type (zonked_tau_tvs) and "grow" them
687 using all the constraints. These are tau_tvs_plus
688
689 * Use quantifyTyVars to quantify over (tau_tvs_plus - mono_tvs), being
690 careful to close over kinds, and to skolemise the quantified tyvars.
691 (This actually unifies each quantifies meta-tyvar with a fresh skolem.)
692 Result is qtvs.
693
694 * Filter the constraints using pickQuantifiablePreds and the qtvs.
695 We have to zonk the constraints first, so they "see" the freshly
696 created skolems.
697
698 If the MR does apply, mono_tvs includes all the constrained tyvars --
699 including all covars -- and the quantified constraints are empty/insoluble.
700
701 -}
702
703 decideQuantification
704 :: Bool -- try the MR restriction?
705 -> [TcIdSigInfo]
706 -> [(Name, TcTauType)] -- variables to be generalised (for errors only)
707 -> [PredType] -- candidate theta
708 -> Pair TcTyCoVarSet -- dependent (kind) variables & type variables
709 -> TcM ( [TcTyVar] -- Quantify over these (skolems)
710 , [PredType] ) -- and this context (fully zonked)
711 -- See Note [Deciding quantification]
712 decideQuantification apply_mr sigs name_taus constraints
713 zonked_pair@(Pair zonked_tau_kvs zonked_tau_tvs)
714 | apply_mr -- Apply the Monomorphism restriction
715 = do { gbl_tvs <- tcGetGlobalTyCoVars
716 ; let constrained_tvs = tyCoVarsOfTypes constraints `unionVarSet`
717 filterVarSet isCoVar zonked_tkvs
718 mono_tvs = gbl_tvs `unionVarSet` constrained_tvs
719 ; qtvs <- quantify_tvs sigs mono_tvs zonked_pair
720
721 -- Warn about the monomorphism restriction
722 ; warn_mono <- woptM Opt_WarnMonomorphism
723 ; let mr_bites = constrained_tvs `intersectsVarSet` zonked_tkvs
724 ; warnTc (warn_mono && mr_bites) $
725 hang (text "The Monomorphism Restriction applies to the binding"
726 <> plural bndrs <+> text "for" <+> pp_bndrs)
727 2 (text "Consider giving a type signature for"
728 <+> if isSingleton bndrs then pp_bndrs
729 else text "these binders")
730
731 -- All done
732 ; traceTc "decideQuantification 1" (vcat [ppr constraints, ppr gbl_tvs, ppr mono_tvs
733 , ppr qtvs, ppr mr_bites])
734 ; return (qtvs, []) }
735
736 | otherwise
737 = do { gbl_tvs <- tcGetGlobalTyCoVars
738 ; let mono_tvs = growThetaTyVars equality_constraints gbl_tvs
739 tau_tvs_plus = growThetaTyVars constraints zonked_tau_tvs
740 ; qtvs <- quantify_tvs sigs mono_tvs (Pair zonked_tau_kvs tau_tvs_plus)
741 -- We don't grow the kvs, as there's no real need to. Recall
742 -- that quantifyTyVars uses the separation between kvs and tvs
743 -- only for defaulting, and we don't want (ever) to default a tv
744 -- to *. So, don't grow the kvs.
745
746 ; constraints <- TcM.zonkTcTypes constraints
747 -- quantiyTyVars turned some meta tyvars into
748 -- quantified skolems, so we have to zonk again
749
750 ; let theta = pickQuantifiablePreds (mkVarSet qtvs) constraints
751 min_theta = mkMinimalBySCs theta
752 -- See Note [Minimize by Superclasses]
753
754 ; traceTc "decideQuantification 2"
755 (vcat [ text "constraints:" <+> ppr constraints
756 , text "gbl_tvs:" <+> ppr gbl_tvs
757 , text "mono_tvs:" <+> ppr mono_tvs
758 , text "zonked_kvs:" <+> ppr zonked_tau_kvs
759 , text "tau_tvs_plus:" <+> ppr tau_tvs_plus
760 , text "qtvs:" <+> ppr qtvs
761 , text "min_theta:" <+> ppr min_theta ])
762 ; return (qtvs, min_theta) }
763 where
764 zonked_tkvs = zonked_tau_kvs `unionVarSet` zonked_tau_tvs
765 bndrs = map fst name_taus
766 pp_bndrs = pprWithCommas (quotes . ppr) bndrs
767 equality_constraints = filter isEqPred constraints
768
769 quantify_tvs :: [TcIdSigInfo]
770 -> TcTyVarSet -- the monomorphic tvs
771 -> Pair TcTyVarSet -- kvs, tvs to quantify
772 -> TcM [TcTyVar]
773 -- See Note [Which type variables to quantify]
774 quantify_tvs sigs mono_tvs (Pair tau_kvs tau_tvs)
775 = quantifyTyVars (mono_tvs `delVarSetList` sig_qtvs)
776 (Pair tau_kvs
777 (tau_tvs `extendVarSetList` sig_qtvs
778 `extendVarSetList` sig_wcs))
779 -- NB: quantifyTyVars zonks its arguments
780 where
781 sig_qtvs = [ skol | sig <- sigs, (_, skol) <- sig_skols sig ]
782 sig_wcs = [ wc | TISI { sig_bndr = PartialSig { sig_wcs = wcs } } <- sigs
783 , (_, wc) <- wcs ]
784
785
786 ------------------
787 growThetaTyVars :: ThetaType -> TyCoVarSet -> TyVarSet
788 -- See Note [Growing the tau-tvs using constraints]
789 -- NB: only returns tyvars, never covars
790 growThetaTyVars theta tvs
791 | null theta = tvs_only
792 | otherwise = filterVarSet isTyVar $
793 transCloVarSet mk_next seed_tvs
794 where
795 tvs_only = filterVarSet isTyVar tvs
796 seed_tvs = tvs `unionVarSet` tyCoVarsOfTypes ips
797 (ips, non_ips) = partition isIPPred theta
798 -- See Note [Inheriting implicit parameters] in TcType
799
800 mk_next :: VarSet -> VarSet -- Maps current set to newly-grown ones
801 mk_next so_far = foldr (grow_one so_far) emptyVarSet non_ips
802 grow_one so_far pred tvs
803 | pred_tvs `intersectsVarSet` so_far = tvs `unionVarSet` pred_tvs
804 | otherwise = tvs
805 where
806 pred_tvs = tyCoVarsOfType pred
807
808 {- Note [Which type variables to quantify]
809 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
810 When choosing type variables to quantify, the basic plan is to
811 quantify over all type variables that are
812 * free in the tau_tvs, and
813 * not forced to be monomorphic (mono_tvs),
814 for example by being free in the environment.
815
816 However, for a pattern binding, or with wildcards, we might
817 be doing inference *in the presence of a type signature*.
818 Mostly, if there is a signature we use CheckGen, not InferGen,
819 but with pattern bindings or wildcards we might do InferGen
820 and still have a type signature. For example:
821 f :: _ -> a
822 f x = ...
823 or
824 g :: (Eq _a) => _b -> _b
825 or
826 p :: a -> a
827 (p,q) = e
828 In all these cases we use plan InferGen, and hence call simplifyInfer.
829 But those 'a' variables are skolems, and we should be sure to quantify
830 over them, regardless of the monomorphism restriction etc. If we
831 don't, when reporting a type error we panic when we find that a
832 skolem isn't bound by any enclosing implication.
833
834 Moreover we must quantify over all wildcards that are not free in
835 the environment. In the case of 'g' for example, silly though it is,
836 we want to get the inferred type
837 g :: forall t. Eq t => Int -> Int
838 and then report ambiguity, rather than *not* quantifying over 't'
839 and getting some much more mysterious error later. A similar case
840 is
841 h :: F _a -> Int
842
843 That's why we pass sigs to simplifyInfer, and make sure (in
844 quantify_tvs) that we do quantify over them. Trac #10615 is
845 a case in point.
846
847 Note [Quantifying over equality constraints]
848 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
849 Should we quantify over an equality constraint (s ~ t)? In general, we don't.
850 Doing so may simply postpone a type error from the function definition site to
851 its call site. (At worst, imagine (Int ~ Bool)).
852
853 However, consider this
854 forall a. (F [a] ~ Int) => blah
855 Should we quantify over the (F [a] ~ Int)? Perhaps yes, because at the call
856 site we will know 'a', and perhaps we have instance F [Bool] = Int.
857 So we *do* quantify over a type-family equality where the arguments mention
858 the quantified variables.
859
860 Note [Growing the tau-tvs using constraints]
861 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
862 (growThetaTyVars insts tvs) is the result of extending the set
863 of tyvars, tvs, using all conceivable links from pred
864
865 E.g. tvs = {a}, preds = {H [a] b, K (b,Int) c, Eq e}
866 Then growThetaTyVars preds tvs = {a,b,c}
867
868 Notice that
869 growThetaTyVars is conservative if v might be fixed by vs
870 => v `elem` grow(vs,C)
871
872 Note [Quantification with errors]
873 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
874 If we find that the RHS of the definition has some absolutely-insoluble
875 constraints, we abandon all attempts to find a context to quantify
876 over, and instead make the function fully-polymorphic in whatever
877 type we have found. For two reasons
878 a) Minimise downstream errors
879 b) Avoid spurious errors from this function
880
881 But NB that we must include *derived* errors in the check. Example:
882 (a::*) ~ Int#
883 We get an insoluble derived error *~#, and we don't want to discard
884 it before doing the isInsolubleWC test! (Trac #8262)
885
886 Note [Default while Inferring]
887 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
888 Our current plan is that defaulting only happens at simplifyTop and
889 not simplifyInfer. This may lead to some insoluble deferred constraints.
890 Example:
891
892 instance D g => C g Int b
893
894 constraint inferred = (forall b. 0 => C gamma alpha b) /\ Num alpha
895 type inferred = gamma -> gamma
896
897 Now, if we try to default (alpha := Int) we will be able to refine the implication to
898 (forall b. 0 => C gamma Int b)
899 which can then be simplified further to
900 (forall b. 0 => D gamma)
901 Finally, we /can/ approximate this implication with (D gamma) and infer the quantified
902 type: forall g. D g => g -> g
903
904 Instead what will currently happen is that we will get a quantified type
905 (forall g. g -> g) and an implication:
906 forall g. 0 => (forall b. 0 => C g alpha b) /\ Num alpha
907
908 Which, even if the simplifyTop defaults (alpha := Int) we will still be left with an
909 unsolvable implication:
910 forall g. 0 => (forall b. 0 => D g)
911
912 The concrete example would be:
913 h :: C g a s => g -> a -> ST s a
914 f (x::gamma) = (\_ -> x) (runST (h x (undefined::alpha)) + 1)
915
916 But it is quite tedious to do defaulting and resolve the implication constraints, and
917 we have not observed code breaking because of the lack of defaulting in inference, so
918 we don't do it for now.
919
920
921
922 Note [Minimize by Superclasses]
923 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
924 When we quantify over a constraint, in simplifyInfer we need to
925 quantify over a constraint that is minimal in some sense: For
926 instance, if the final wanted constraint is (Eq alpha, Ord alpha),
927 we'd like to quantify over Ord alpha, because we can just get Eq alpha
928 from superclass selection from Ord alpha. This minimization is what
929 mkMinimalBySCs does. Then, simplifyInfer uses the minimal constraint
930 to check the original wanted.
931
932
933 Note [Avoid unnecessary constraint simplification]
934 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
935 -------- NB NB NB (Jun 12) -------------
936 This note not longer applies; see the notes with Trac #4361.
937 But I'm leaving it in here so we remember the issue.)
938 ----------------------------------------
939 When inferring the type of a let-binding, with simplifyInfer,
940 try to avoid unnecessarily simplifying class constraints.
941 Doing so aids sharing, but it also helps with delicate
942 situations like
943
944 instance C t => C [t] where ..
945
946 f :: C [t] => ....
947 f x = let g y = ...(constraint C [t])...
948 in ...
949 When inferring a type for 'g', we don't want to apply the
950 instance decl, because then we can't satisfy (C t). So we
951 just notice that g isn't quantified over 't' and partition
952 the constraints before simplifying.
953
954 This only half-works, but then let-generalisation only half-works.
955
956 *********************************************************************************
957 * *
958 * Main Simplifier *
959 * *
960 ***********************************************************************************
961
962 -}
963
964 simplifyWantedsTcM :: [CtEvidence] -> TcM WantedConstraints
965 -- Solve the specified Wanted constraints
966 -- Discard the evidence binds
967 -- Discards all Derived stuff in result
968 -- Postcondition: fully zonked and unflattened constraints
969 simplifyWantedsTcM wanted
970 = do { traceTc "simplifyWantedsTcM {" (ppr wanted)
971 ; (result, _) <- runTcS (solveWantedsAndDrop $ mkSimpleWC wanted)
972 ; result <- TcM.zonkWC result
973 ; traceTc "simplifyWantedsTcM }" (ppr result)
974 ; return result }
975
976 solveWantedsAndDrop :: WantedConstraints -> TcS WantedConstraints
977 -- Since solveWanteds returns the residual WantedConstraints,
978 -- it should always be called within a runTcS or something similar,
979 -- Result is not zonked
980 solveWantedsAndDrop wanted
981 = do { wc <- solveWanteds wanted
982 ; return (dropDerivedWC wc) }
983
984 solveWanteds :: WantedConstraints -> TcS WantedConstraints
985 -- so that the inert set doesn't mindlessly propagate.
986 -- NB: wc_simples may be wanted /or/ derived now
987 solveWanteds wc@(WC { wc_simple = simples, wc_insol = insols, wc_impl = implics })
988 = do { traceTcS "solveWanteds {" (ppr wc)
989
990 -- Try the simple bit, including insolubles. Solving insolubles a
991 -- second time round is a bit of a waste; but the code is simple
992 -- and the program is wrong anyway, and we don't run the danger
993 -- of adding Derived insolubles twice; see
994 -- TcSMonad Note [Do not add duplicate derived insolubles]
995 ; wc1 <- solveSimpleWanteds simples
996 ; (no_new_scs, wc1) <- expandSuperClasses wc1
997 ; let WC { wc_simple = simples1, wc_insol = insols1, wc_impl = implics1 } = wc1
998
999 ; (floated_eqs, implics2) <- solveNestedImplications (implics `unionBags` implics1)
1000
1001 ; dflags <- getDynFlags
1002 ; final_wc <- simpl_loop 0 (solverIterations dflags) floated_eqs no_new_scs
1003 (WC { wc_simple = simples1, wc_impl = implics2
1004 , wc_insol = insols `unionBags` insols1 })
1005
1006 ; bb <- TcS.getTcEvBindsMap
1007 ; traceTcS "solveWanteds }" $
1008 vcat [ text "final wc =" <+> ppr final_wc
1009 , text "current evbinds =" <+> ppr (evBindMapBinds bb) ]
1010
1011 ; return final_wc }
1012
1013 simpl_loop :: Int -> IntWithInf -> Cts -> Bool
1014 -> WantedConstraints
1015 -> TcS WantedConstraints
1016 simpl_loop n limit floated_eqs no_new_scs
1017 wc@(WC { wc_simple = simples, wc_insol = insols, wc_impl = implics })
1018 | isEmptyBag floated_eqs && no_new_scs
1019 = return wc -- Done!
1020
1021 | n `intGtLimit` limit
1022 = do { -- Add an error (not a warning) if we blow the limit,
1023 -- Typically if we blow the limit we are going to report some other error
1024 -- (an unsolved constraint), and we don't want that error to suppress
1025 -- the iteration limit warning!
1026 addErrTcS (hang (text "solveWanteds: too many iterations"
1027 <+> parens (text "limit =" <+> ppr limit))
1028 2 (vcat [ text "Unsolved:" <+> ppr wc
1029 , ppUnless (isEmptyBag floated_eqs) $
1030 text "Floated equalities:" <+> ppr floated_eqs
1031 , ppUnless no_new_scs $
1032 text "New superclasses found"
1033 , text "Set limit with -fconstraint-solver-iterations=n; n=0 for no limit"
1034 ]))
1035 ; return wc }
1036
1037 | otherwise
1038 = do { let n_floated = lengthBag floated_eqs
1039 ; csTraceTcS $
1040 text "simpl_loop iteration=" <> int n
1041 <+> (parens $ hsep [ text "no new scs =" <+> ppr no_new_scs <> comma
1042 , int n_floated <+> text "floated eqs" <> comma
1043 , int (lengthBag simples) <+> text "simples to solve" ])
1044
1045 -- solveSimples may make progress if either float_eqs hold
1046 ; (unifs1, wc1) <- reportUnifications $
1047 solveSimpleWanteds (floated_eqs `unionBags` simples)
1048 -- Put floated_eqs first so they get solved first
1049 -- NB: the floated_eqs may include /derived/ equalities
1050 -- arising from fundeps inside an implication
1051
1052 ; (no_new_scs, wc1) <- expandSuperClasses wc1
1053 ; let WC { wc_simple = simples1, wc_insol = insols1, wc_impl = implics1 } = wc1
1054
1055 -- We have already tried to solve the nested implications once
1056 -- Try again only if we have unified some meta-variables
1057 -- (which is a bit like adding more givens
1058 -- See Note [Cutting off simpl_loop]
1059 ; (floated_eqs2, implics2) <- if unifs1 == 0 && isEmptyBag implics1
1060 then return (emptyBag, implics)
1061 else solveNestedImplications (implics `unionBags` implics1)
1062
1063 ; simpl_loop (n+1) limit floated_eqs2 no_new_scs
1064 (WC { wc_simple = simples1, wc_impl = implics2
1065 , wc_insol = insols `unionBags` insols1 }) }
1066
1067 expandSuperClasses :: WantedConstraints -> TcS (Bool, WantedConstraints)
1068 -- If there are any unsolved wanteds, expand one step of superclasses for
1069 -- unsolved wanteds or givens
1070 -- See Note [The superclass story] in TcCanonical
1071 expandSuperClasses wc@(WC { wc_simple = unsolved, wc_insol = insols })
1072 | not (anyBag superClassesMightHelp unsolved)
1073 = return (True, wc)
1074 | otherwise
1075 = do { traceTcS "expandSuperClasses {" empty
1076 ; let (pending_wanted, unsolved') = mapAccumBagL get [] unsolved
1077 get acc ct = case isPendingScDict ct of
1078 Just ct' -> (ct':acc, ct')
1079 Nothing -> (acc, ct)
1080 ; pending_given <- getPendingScDicts
1081 ; if null pending_given && null pending_wanted
1082 then do { traceTcS "End expandSuperClasses no-op }" empty
1083 ; return (True, wc) }
1084 else
1085 do { new_given <- makeSuperClasses pending_given
1086 ; new_insols <- solveSimpleGivens new_given
1087 ; new_wanted <- makeSuperClasses pending_wanted
1088 ; traceTcS "End expandSuperClasses }"
1089 (vcat [ text "Given:" <+> ppr pending_given
1090 , text "Insols from given:" <+> ppr new_insols
1091 , text "Wanted:" <+> ppr new_wanted ])
1092 ; return (False, wc { wc_simple = unsolved' `unionBags` listToBag new_wanted
1093 , wc_insol = insols `unionBags` new_insols }) } }
1094
1095 solveNestedImplications :: Bag Implication
1096 -> TcS (Cts, Bag Implication)
1097 -- Precondition: the TcS inerts may contain unsolved simples which have
1098 -- to be converted to givens before we go inside a nested implication.
1099 solveNestedImplications implics
1100 | isEmptyBag implics
1101 = return (emptyBag, emptyBag)
1102 | otherwise
1103 = do { traceTcS "solveNestedImplications starting {" empty
1104 ; (floated_eqs_s, unsolved_implics) <- mapAndUnzipBagM solveImplication implics
1105 ; let floated_eqs = concatBag floated_eqs_s
1106
1107 -- ... and we are back in the original TcS inerts
1108 -- Notice that the original includes the _insoluble_simples so it was safe to ignore
1109 -- them in the beginning of this function.
1110 ; traceTcS "solveNestedImplications end }" $
1111 vcat [ text "all floated_eqs =" <+> ppr floated_eqs
1112 , text "unsolved_implics =" <+> ppr unsolved_implics ]
1113
1114 ; return (floated_eqs, catBagMaybes unsolved_implics) }
1115
1116 solveImplication :: Implication -- Wanted
1117 -> TcS (Cts, -- All wanted or derived floated equalities: var = type
1118 Maybe Implication) -- Simplified implication (empty or singleton)
1119 -- Precondition: The TcS monad contains an empty worklist and given-only inerts
1120 -- which after trying to solve this implication we must restore to their original value
1121 solveImplication imp@(Implic { ic_tclvl = tclvl
1122 , ic_binds = m_ev_binds
1123 , ic_skols = skols
1124 , ic_given = given_ids
1125 , ic_wanted = wanteds
1126 , ic_info = info
1127 , ic_status = status
1128 , ic_env = env })
1129 | IC_Solved {} <- status
1130 = return (emptyCts, Just imp) -- Do nothing
1131
1132 | otherwise -- Even for IC_Insoluble it is worth doing more work
1133 -- The insoluble stuff might be in one sub-implication
1134 -- and other unsolved goals in another; and we want to
1135 -- solve the latter as much as possible
1136 = do { inerts <- getTcSInerts
1137 ; traceTcS "solveImplication {" (ppr imp $$ text "Inerts" <+> ppr inerts)
1138
1139 -- Solve the nested constraints
1140 ; ((no_given_eqs, given_insols, residual_wanted), used_tcvs)
1141 <- nestImplicTcS m_ev_binds (mkVarSet (skols ++ given_ids)) tclvl $
1142 do { let loc = mkGivenLoc tclvl info env
1143 ; givens_w_scs <- mkGivensWithSuperClasses loc given_ids
1144 ; given_insols <- solveSimpleGivens givens_w_scs
1145
1146 ; residual_wanted <- solveWanteds wanteds
1147 -- solveWanteds, *not* solveWantedsAndDrop, because
1148 -- we want to retain derived equalities so we can float
1149 -- them out in floatEqualities
1150
1151 ; no_eqs <- getNoGivenEqs tclvl skols
1152 -- Call getNoGivenEqs /after/ solveWanteds, because
1153 -- solveWanteds can augment the givens, via expandSuperClasses,
1154 -- to reveal given superclass equalities
1155
1156 ; return (no_eqs, given_insols, residual_wanted) }
1157
1158 ; (floated_eqs, residual_wanted)
1159 <- floatEqualities skols no_given_eqs residual_wanted
1160
1161 ; traceTcS "solveImplication 2"
1162 (ppr given_insols $$ ppr residual_wanted $$ ppr used_tcvs)
1163 ; let final_wanted = residual_wanted `addInsols` given_insols
1164
1165 ; res_implic <- setImplicationStatus (imp { ic_no_eqs = no_given_eqs
1166 , ic_wanted = final_wanted })
1167 used_tcvs
1168
1169 ; evbinds <- TcS.getTcEvBindsMap
1170 ; traceTcS "solveImplication end }" $ vcat
1171 [ text "no_given_eqs =" <+> ppr no_given_eqs
1172 , text "floated_eqs =" <+> ppr floated_eqs
1173 , text "res_implic =" <+> ppr res_implic
1174 , text "implication evbinds = " <+> ppr (evBindMapBinds evbinds) ]
1175
1176 ; return (floated_eqs, res_implic) }
1177
1178 ----------------------
1179 setImplicationStatus :: Implication -> TyCoVarSet -- needed variables
1180 -> TcS (Maybe Implication)
1181 -- Finalise the implication returned from solveImplication:
1182 -- * Set the ic_status field
1183 -- * Trim the ic_wanted field to remove Derived constraints
1184 -- Return Nothing if we can discard the implication altogether
1185 setImplicationStatus implic@(Implic { ic_binds = m_ev_binds_var
1186 , ic_info = info
1187 , ic_tclvl = tc_lvl
1188 , ic_wanted = wc
1189 , ic_given = givens })
1190 used_tcvs
1191 | some_insoluble
1192 = return $ Just $
1193 implic { ic_status = IC_Insoluble
1194 , ic_wanted = wc { wc_simple = pruned_simples
1195 , wc_insol = pruned_insols } }
1196
1197 | some_unsolved
1198 = return $ Just $
1199 implic { ic_status = IC_Unsolved
1200 , ic_wanted = wc { wc_simple = pruned_simples
1201 , wc_insol = pruned_insols } }
1202
1203 | otherwise -- Everything is solved; look at the implications
1204 -- See Note [Tracking redundant constraints]
1205 = do { ev_binds <- case m_ev_binds_var of
1206 Just (EvBindsVar ref _) -> TcS.readTcRef ref
1207 Nothing -> return emptyEvBindMap
1208 ; let all_needs = neededEvVars ev_binds
1209 (used_tcvs `unionVarSet` implic_needs)
1210
1211 dead_givens | warnRedundantGivens info
1212 = filterOut (`elemVarSet` all_needs) givens
1213 | otherwise = [] -- None to report
1214
1215 final_needs = all_needs `delVarSetList` givens
1216
1217 discard_entire_implication -- Can we discard the entire implication?
1218 = null dead_givens -- No warning from this implication
1219 && isEmptyBag pruned_implics -- No live children
1220 && isEmptyVarSet final_needs -- No needed vars to pass up to parent
1221
1222 final_status = IC_Solved { ics_need = final_needs
1223 , ics_dead = dead_givens }
1224 final_implic = implic { ic_status = final_status
1225 , ic_wanted = wc { wc_simple = pruned_simples
1226 , wc_insol = pruned_insols
1227 , wc_impl = pruned_implics } }
1228 -- We can only prune the child implications (pruned_implics)
1229 -- in the IC_Solved status case, because only then we can
1230 -- accumulate their needed evidence variales into the
1231 -- IC_Solved final_status field of the parent implication.
1232
1233 ; return $ if discard_entire_implication
1234 then Nothing
1235 else Just final_implic }
1236 where
1237 WC { wc_simple = simples, wc_impl = implics, wc_insol = insols } = wc
1238
1239 some_insoluble = insolubleWC tc_lvl wc
1240 some_unsolved = not (isEmptyBag simples && isEmptyBag insols)
1241 || isNothing mb_implic_needs
1242
1243 pruned_simples = dropDerivedSimples simples
1244 pruned_insols = dropDerivedInsols insols
1245 pruned_implics = filterBag need_to_keep_implic implics
1246
1247 mb_implic_needs :: Maybe VarSet
1248 -- Just vs => all implics are IC_Solved, with 'vs' needed
1249 -- Nothing => at least one implic is not IC_Solved
1250 mb_implic_needs = foldrBag add_implic (Just emptyVarSet) implics
1251 Just implic_needs = mb_implic_needs
1252
1253 add_implic implic acc
1254 | Just vs_acc <- acc
1255 , IC_Solved { ics_need = vs } <- ic_status implic
1256 = Just (vs `unionVarSet` vs_acc)
1257 | otherwise = Nothing
1258
1259 need_to_keep_implic ic
1260 | IC_Solved { ics_dead = [] } <- ic_status ic
1261 -- Fully solved, and no redundant givens to report
1262 , isEmptyBag (wc_impl (ic_wanted ic))
1263 -- And no children that might have things to report
1264 = False
1265 | otherwise
1266 = True
1267
1268 warnRedundantGivens :: SkolemInfo -> Bool
1269 warnRedundantGivens (SigSkol ctxt _)
1270 = case ctxt of
1271 FunSigCtxt _ warn_redundant -> warn_redundant
1272 ExprSigCtxt -> True
1273 _ -> False
1274 -- To think about: do we want to report redundant givens for
1275 -- pattern synonyms, PatSynCtxt? c.f Trac #9953, comment:21.
1276
1277 warnRedundantGivens (InstSkol {}) = True
1278 warnRedundantGivens _ = False
1279
1280 neededEvVars :: EvBindMap -> VarSet -> VarSet
1281 -- Find all the evidence variables that are "needed",
1282 -- and then delete all those bound by the evidence bindings
1283 -- See note [Tracking redundant constraints]
1284 neededEvVars ev_binds initial_seeds
1285 = needed `minusVarSet` bndrs
1286 where
1287 seeds = foldEvBindMap add_wanted initial_seeds ev_binds
1288 needed = transCloVarSet also_needs seeds
1289 bndrs = foldEvBindMap add_bndr emptyVarSet ev_binds
1290
1291 add_wanted :: EvBind -> VarSet -> VarSet
1292 add_wanted (EvBind { eb_is_given = is_given, eb_rhs = rhs }) needs
1293 | is_given = needs -- Add the rhs vars of the Wanted bindings only
1294 | otherwise = evVarsOfTerm rhs `unionVarSet` needs
1295
1296 also_needs :: VarSet -> VarSet
1297 also_needs needs
1298 = foldVarSet add emptyVarSet needs
1299 where
1300 add v needs
1301 | Just ev_bind <- lookupEvBind ev_binds v
1302 , EvBind { eb_is_given = is_given, eb_rhs = rhs } <- ev_bind
1303 , is_given
1304 = evVarsOfTerm rhs `unionVarSet` needs
1305 | otherwise
1306 = needs
1307
1308 add_bndr :: EvBind -> VarSet -> VarSet
1309 add_bndr (EvBind { eb_lhs = v }) vs = extendVarSet vs v
1310
1311
1312 {-
1313 Note [Tracking redundant constraints]
1314 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1315 With Opt_WarnRedundantConstraints, GHC can report which
1316 constraints of a type signature (or instance declaration) are
1317 redundant, and can be omitted. Here is an overview of how it
1318 works:
1319
1320 ----- What is a redundant constraint?
1321
1322 * The things that can be redundant are precisely the Given
1323 constraints of an implication.
1324
1325 * A constraint can be redundant in two different ways:
1326 a) It is implied by other givens. E.g.
1327 f :: (Eq a, Ord a) => blah -- Eq a unnecessary
1328 g :: (Eq a, a~b, Eq b) => blah -- Either Eq a or Eq b unnecessary
1329 b) It is not needed by the Wanted constraints covered by the
1330 implication E.g.
1331 f :: Eq a => a -> Bool
1332 f x = True -- Equality not used
1333
1334 * To find (a), when we have two Given constraints,
1335 we must be careful to drop the one that is a naked variable (if poss).
1336 So if we have
1337 f :: (Eq a, Ord a) => blah
1338 then we may find [G] sc_sel (d1::Ord a) :: Eq a
1339 [G] d2 :: Eq a
1340 We want to discard d2 in favour of the superclass selection from
1341 the Ord dictionary. This is done by TcInteract.solveOneFromTheOther
1342 See Note [Replacement vs keeping].
1343
1344 * To find (b) we need to know which evidence bindings are 'wanted';
1345 hence the eb_is_given field on an EvBind.
1346
1347 ----- How tracking works
1348
1349 * When the constraint solver finishes solving all the wanteds in
1350 an implication, it sets its status to IC_Solved
1351
1352 - The ics_dead field, of IC_Solved, records the subset of this implication's
1353 ic_given that are redundant (not needed).
1354
1355 - The ics_need field of IC_Solved then records all the
1356 in-scope (given) evidence variables bound by the context, that
1357 were needed to solve this implication, including all its nested
1358 implications. (We remove the ic_given of this implication from
1359 the set, of course.)
1360
1361 * We compute which evidence variables are needed by an implication
1362 in setImplicationStatus. A variable is needed if
1363 a) it is free in the RHS of a Wanted EvBind,
1364 b) it is free in the RHS of an EvBind whose LHS is needed,
1365 c) it is in the ics_need of a nested implication.
1366 d) it is listed in the tcs_used_tcvs field of the nested TcSEnv
1367
1368 * We need to be careful not to discard an implication
1369 prematurely, even one that is fully solved, because we might
1370 thereby forget which variables it needs, and hence wrongly
1371 report a constraint as redundant. But we can discard it once
1372 its free vars have been incorporated into its parent; or if it
1373 simply has no free vars. This careful discarding is also
1374 handled in setImplicationStatus.
1375
1376 ----- Reporting redundant constraints
1377
1378 * TcErrors does the actual warning, in warnRedundantConstraints.
1379
1380 * We don't report redundant givens for *every* implication; only
1381 for those which reply True to TcSimplify.warnRedundantGivens:
1382
1383 - For example, in a class declaration, the default method *can*
1384 use the class constraint, but it certainly doesn't *have* to,
1385 and we don't want to report an error there.
1386
1387 - More subtly, in a function definition
1388 f :: (Ord a, Ord a, Ix a) => a -> a
1389 f x = rhs
1390 we do an ambiguity check on the type (which would find that one
1391 of the Ord a constraints was redundant), and then we check that
1392 the definition has that type (which might find that both are
1393 redundant). We don't want to report the same error twice, so we
1394 disable it for the ambiguity check. Hence using two different
1395 FunSigCtxts, one with the warn-redundant field set True, and the
1396 other set False in
1397 - TcBinds.tcSpecPrag
1398 - TcBinds.tcTySig
1399
1400 This decision is taken in setImplicationStatus, rather than TcErrors
1401 so that we can discard implication constraints that we don't need.
1402 So ics_dead consists only of the *reportable* redundant givens.
1403
1404 ----- Shortcomings
1405
1406 Consider (see Trac #9939)
1407 f2 :: (Eq a, Ord a) => a -> a -> Bool
1408 -- Ord a redundant, but Eq a is reported
1409 f2 x y = (x == y)
1410
1411 We report (Eq a) as redundant, whereas actually (Ord a) is. But it's
1412 really not easy to detect that!
1413
1414
1415 Note [Cutting off simpl_loop]
1416 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1417 It is very important not to iterate in simpl_loop unless there is a chance
1418 of progress. Trac #8474 is a classic example:
1419
1420 * There's a deeply-nested chain of implication constraints.
1421 ?x:alpha => ?y1:beta1 => ... ?yn:betan => [W] ?x:Int
1422
1423 * From the innermost one we get a [D] alpha ~ Int,
1424 but alpha is untouchable until we get out to the outermost one
1425
1426 * We float [D] alpha~Int out (it is in floated_eqs), but since alpha
1427 is untouchable, the solveInteract in simpl_loop makes no progress
1428
1429 * So there is no point in attempting to re-solve
1430 ?yn:betan => [W] ?x:Int
1431 via solveNestedImplications, because we'll just get the
1432 same [D] again
1433
1434 * If we *do* re-solve, we'll get an ininite loop. It is cut off by
1435 the fixed bound of 10, but solving the next takes 10*10*...*10 (ie
1436 exponentially many) iterations!
1437
1438 Conclusion: we should call solveNestedImplications only if we did
1439 some unifiction in solveSimpleWanteds; because that's the only way
1440 we'll get more Givens (a unificaiton is like adding a Given) to
1441 allow the implication to make progress.
1442 -}
1443
1444 promoteTyVar :: TcLevel -> TcTyVar -> TcM ()
1445 -- When we float a constraint out of an implication we must restore
1446 -- invariant (MetaTvInv) in Note [TcLevel and untouchable type variables] in TcType
1447 -- See Note [Promoting unification variables]
1448 promoteTyVar tclvl tv
1449 | isFloatedTouchableMetaTyVar tclvl tv
1450 = do { cloned_tv <- TcM.cloneMetaTyVar tv
1451 ; let rhs_tv = setMetaTyVarTcLevel cloned_tv tclvl
1452 ; TcM.writeMetaTyVar tv (mkTyVarTy rhs_tv) }
1453 | otherwise
1454 = return ()
1455
1456 promoteTyVarTcS :: TcLevel -> TcTyVar -> TcS ()
1457 -- When we float a constraint out of an implication we must restore
1458 -- invariant (MetaTvInv) in Note [TcLevel and untouchable type variables] in TcType
1459 -- See Note [Promoting unification variables]
1460 -- We don't just call promoteTyVar because we want to use unifyTyVar,
1461 -- not writeMetaTyVar
1462 promoteTyVarTcS tclvl tv
1463 | isFloatedTouchableMetaTyVar tclvl tv
1464 = do { cloned_tv <- TcS.cloneMetaTyVar tv
1465 ; let rhs_tv = setMetaTyVarTcLevel cloned_tv tclvl
1466 ; unifyTyVar tv (mkTyVarTy rhs_tv) }
1467 | otherwise
1468 = return ()
1469
1470 -- | If the tyvar is a levity var, set it to Lifted. Returns whether or
1471 -- not this happened.
1472 defaultTyVar :: TcTyVar -> TcM ()
1473 -- Precondition: MetaTyVars only
1474 -- See Note [DefaultTyVar]
1475 defaultTyVar the_tv
1476 | isLevityVar the_tv
1477 = do { traceTc "defaultTyVar levity" (ppr the_tv)
1478 ; writeMetaTyVar the_tv liftedDataConTy }
1479
1480 | otherwise = return () -- The common case
1481
1482 -- | Like 'defaultTyVar', but in the TcS monad.
1483 defaultTyVarTcS :: TcTyVar -> TcS Bool
1484 defaultTyVarTcS the_tv
1485 | isLevityVar the_tv
1486 = do { traceTcS "defaultTyVarTcS levity" (ppr the_tv)
1487 ; unifyTyVar the_tv liftedDataConTy
1488 ; return True }
1489 | otherwise
1490 = return False -- the common case
1491
1492 approximateWC :: WantedConstraints -> Cts
1493 -- Postcondition: Wanted or Derived Cts
1494 -- See Note [ApproximateWC]
1495 approximateWC wc
1496 = float_wc emptyVarSet wc
1497 where
1498 float_wc :: TcTyCoVarSet -> WantedConstraints -> Cts
1499 float_wc trapping_tvs (WC { wc_simple = simples, wc_impl = implics })
1500 = filterBag is_floatable simples `unionBags`
1501 do_bag (float_implic new_trapping_tvs) implics
1502 where
1503 is_floatable ct = tyCoVarsOfCt ct `disjointVarSet` new_trapping_tvs
1504 new_trapping_tvs = transCloVarSet grow trapping_tvs
1505
1506 grow :: VarSet -> VarSet -- Maps current trapped tyvars to newly-trapped ones
1507 grow so_far = foldrBag (grow_one so_far) emptyVarSet simples
1508 grow_one so_far ct tvs
1509 | ct_tvs `intersectsVarSet` so_far = tvs `unionVarSet` ct_tvs
1510 | otherwise = tvs
1511 where
1512 ct_tvs = tyCoVarsOfCt ct
1513
1514 float_implic :: TcTyCoVarSet -> Implication -> Cts
1515 float_implic trapping_tvs imp
1516 | ic_no_eqs imp -- No equalities, so float
1517 = float_wc new_trapping_tvs (ic_wanted imp)
1518 | otherwise -- Don't float out of equalities
1519 = emptyCts -- See Note [ApproximateWC]
1520 where
1521 new_trapping_tvs = trapping_tvs `extendVarSetList` ic_skols imp
1522 do_bag :: (a -> Bag c) -> Bag a -> Bag c
1523 do_bag f = foldrBag (unionBags.f) emptyBag
1524
1525 {-
1526 Note [ApproximateWC]
1527 ~~~~~~~~~~~~~~~~~~~~
1528 approximateWC takes a constraint, typically arising from the RHS of a
1529 let-binding whose type we are *inferring*, and extracts from it some
1530 *simple* constraints that we might plausibly abstract over. Of course
1531 the top-level simple constraints are plausible, but we also float constraints
1532 out from inside, if they are not captured by skolems.
1533
1534 The same function is used when doing type-class defaulting (see the call
1535 to applyDefaultingRules) to extract constraints that that might be defaulted.
1536
1537 There are two caveats:
1538
1539 1. We do *not* float anything out if the implication binds equality
1540 constraints, because that defeats the OutsideIn story. Consider
1541 data T a where
1542 TInt :: T Int
1543 MkT :: T a
1544
1545 f TInt = 3::Int
1546
1547 We get the implication (a ~ Int => res ~ Int), where so far we've decided
1548 f :: T a -> res
1549 We don't want to float (res~Int) out because then we'll infer
1550 f :: T a -> Int
1551 which is only on of the possible types. (GHC 7.6 accidentally *did*
1552 float out of such implications, which meant it would happily infer
1553 non-principal types.)
1554
1555 2. We do not float out an inner constraint that shares a type variable
1556 (transitively) with one that is trapped by a skolem. Eg
1557 forall a. F a ~ beta, Integral beta
1558 We don't want to float out (Integral beta). Doing so would be bad
1559 when defaulting, because then we'll default beta:=Integer, and that
1560 makes the error message much worse; we'd get
1561 Can't solve F a ~ Integer
1562 rather than
1563 Can't solve Integral (F a)
1564
1565 Moreover, floating out these "contaminated" constraints doesn't help
1566 when generalising either. If we generalise over (Integral b), we still
1567 can't solve the retained implication (forall a. F a ~ b). Indeed,
1568 arguably that too would be a harder error to understand.
1569
1570 Note [DefaultTyVar]
1571 ~~~~~~~~~~~~~~~~~~~
1572 defaultTyVar is used on any un-instantiated meta type variables to
1573 default any levity variables to Lifted. This is important
1574 to ensure that instance declarations match. For example consider
1575
1576 instance Show (a->b)
1577 foo x = show (\_ -> True)
1578
1579 Then we'll get a constraint (Show (p ->q)) where p has kind ArgKind,
1580 and that won't match the typeKind (*) in the instance decl. See tests
1581 tc217 and tc175.
1582
1583 We look only at touchable type variables. No further constraints
1584 are going to affect these type variables, so it's time to do it by
1585 hand. However we aren't ready to default them fully to () or
1586 whatever, because the type-class defaulting rules have yet to run.
1587
1588 An alternate implementation would be to emit a derived constraint setting
1589 the levity variable to Lifted, but this seems unnecessarily indirect.
1590
1591 Note [Promote _and_ default when inferring]
1592 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1593 When we are inferring a type, we simplify the constraint, and then use
1594 approximateWC to produce a list of candidate constraints. Then we MUST
1595
1596 a) Promote any meta-tyvars that have been floated out by
1597 approximateWC, to restore invariant (MetaTvInv) described in
1598 Note [TcLevel and untouchable type variables] in TcType.
1599
1600 b) Default the kind of any meta-tyyvars that are not mentioned in
1601 in the environment.
1602
1603 To see (b), suppose the constraint is (C ((a :: OpenKind) -> Int)), and we
1604 have an instance (C ((x:*) -> Int)). The instance doesn't match -- but it
1605 should! If we don't solve the constraint, we'll stupidly quantify over
1606 (C (a->Int)) and, worse, in doing so zonkQuantifiedTyVar will quantify over
1607 (b:*) instead of (a:OpenKind), which can lead to disaster; see Trac #7332.
1608 Trac #7641 is a simpler example.
1609
1610 Note [Promoting unification variables]
1611 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1612 When we float an equality out of an implication we must "promote" free
1613 unification variables of the equality, in order to maintain Invariant
1614 (MetaTvInv) from Note [TcLevel and untouchable type variables] in TcType. for the
1615 leftover implication.
1616
1617 This is absolutely necessary. Consider the following example. We start
1618 with two implications and a class with a functional dependency.
1619
1620 class C x y | x -> y
1621 instance C [a] [a]
1622
1623 (I1) [untch=beta]forall b. 0 => F Int ~ [beta]
1624 (I2) [untch=beta]forall c. 0 => F Int ~ [[alpha]] /\ C beta [c]
1625
1626 We float (F Int ~ [beta]) out of I1, and we float (F Int ~ [[alpha]]) out of I2.
1627 They may react to yield that (beta := [alpha]) which can then be pushed inwards
1628 the leftover of I2 to get (C [alpha] [a]) which, using the FunDep, will mean that
1629 (alpha := a). In the end we will have the skolem 'b' escaping in the untouchable
1630 beta! Concrete example is in indexed_types/should_fail/ExtraTcsUntch.hs:
1631
1632 class C x y | x -> y where
1633 op :: x -> y -> ()
1634
1635 instance C [a] [a]
1636
1637 type family F a :: *
1638
1639 h :: F Int -> ()
1640 h = undefined
1641
1642 data TEx where
1643 TEx :: a -> TEx
1644
1645 f (x::beta) =
1646 let g1 :: forall b. b -> ()
1647 g1 _ = h [x]
1648 g2 z = case z of TEx y -> (h [[undefined]], op x [y])
1649 in (g1 '3', g2 undefined)
1650
1651
1652 Note [Solving Family Equations]
1653 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1654 After we are done with simplification we may be left with constraints of the form:
1655 [Wanted] F xis ~ beta
1656 If 'beta' is a touchable unification variable not already bound in the TyBinds
1657 then we'd like to create a binding for it, effectively "defaulting" it to be 'F xis'.
1658
1659 When is it ok to do so?
1660 1) 'beta' must not already be defaulted to something. Example:
1661
1662 [Wanted] F Int ~ beta <~ Will default [beta := F Int]
1663 [Wanted] F Char ~ beta <~ Already defaulted, can't default again. We
1664 have to report this as unsolved.
1665
1666 2) However, we must still do an occurs check when defaulting (F xis ~ beta), to
1667 set [beta := F xis] only if beta is not among the free variables of xis.
1668
1669 3) Notice that 'beta' can't be bound in ty binds already because we rewrite RHS
1670 of type family equations. See Inert Set invariants in TcInteract.
1671
1672 This solving is now happening during zonking, see Note [Unflattening while zonking]
1673 in TcMType.
1674
1675
1676 *********************************************************************************
1677 * *
1678 * Floating equalities *
1679 * *
1680 *********************************************************************************
1681
1682 Note [Float Equalities out of Implications]
1683 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1684 For ordinary pattern matches (including existentials) we float
1685 equalities out of implications, for instance:
1686 data T where
1687 MkT :: Eq a => a -> T
1688 f x y = case x of MkT _ -> (y::Int)
1689 We get the implication constraint (x::T) (y::alpha):
1690 forall a. [untouchable=alpha] Eq a => alpha ~ Int
1691 We want to float out the equality into a scope where alpha is no
1692 longer untouchable, to solve the implication!
1693
1694 But we cannot float equalities out of implications whose givens may
1695 yield or contain equalities:
1696
1697 data T a where
1698 T1 :: T Int
1699 T2 :: T Bool
1700 T3 :: T a
1701
1702 h :: T a -> a -> Int
1703
1704 f x y = case x of
1705 T1 -> y::Int
1706 T2 -> y::Bool
1707 T3 -> h x y
1708
1709 We generate constraint, for (x::T alpha) and (y :: beta):
1710 [untouchables = beta] (alpha ~ Int => beta ~ Int) -- From 1st branch
1711 [untouchables = beta] (alpha ~ Bool => beta ~ Bool) -- From 2nd branch
1712 (alpha ~ beta) -- From 3rd branch
1713
1714 If we float the equality (beta ~ Int) outside of the first implication and
1715 the equality (beta ~ Bool) out of the second we get an insoluble constraint.
1716 But if we just leave them inside the implications, we unify alpha := beta and
1717 solve everything.
1718
1719 Principle:
1720 We do not want to float equalities out which may
1721 need the given *evidence* to become soluble.
1722
1723 Consequence: classes with functional dependencies don't matter (since there is
1724 no evidence for a fundep equality), but equality superclasses do matter (since
1725 they carry evidence).
1726 -}
1727
1728 floatEqualities :: [TcTyVar] -> Bool
1729 -> WantedConstraints
1730 -> TcS (Cts, WantedConstraints)
1731 -- Main idea: see Note [Float Equalities out of Implications]
1732 --
1733 -- Precondition: the wc_simple of the incoming WantedConstraints are
1734 -- fully zonked, so that we can see their free variables
1735 --
1736 -- Postcondition: The returned floated constraints (Cts) are only
1737 -- Wanted or Derived
1738 --
1739 -- Also performs some unifications (via promoteTyVar), adding to
1740 -- monadically-carried ty_binds. These will be used when processing
1741 -- floated_eqs later
1742 --
1743 -- Subtleties: Note [Float equalities from under a skolem binding]
1744 -- Note [Skolem escape]
1745 floatEqualities skols no_given_eqs
1746 wanteds@(WC { wc_simple = simples })
1747 | not no_given_eqs -- There are some given equalities, so don't float
1748 = return (emptyBag, wanteds) -- Note [Float Equalities out of Implications]
1749 | otherwise
1750 = do { outer_tclvl <- TcS.getTcLevel
1751 ; mapM_ (promoteTyVarTcS outer_tclvl)
1752 (varSetElems (tyCoVarsOfCts float_eqs))
1753 -- See Note [Promoting unification variables]
1754
1755 ; traceTcS "floatEqualities" (vcat [ text "Skols =" <+> ppr skols
1756 , text "Simples =" <+> ppr simples
1757 , text "Floated eqs =" <+> ppr float_eqs])
1758 ; return ( float_eqs
1759 , wanteds { wc_simple = remaining_simples } ) }
1760 where
1761 skol_set = mkVarSet skols
1762 (float_eqs, remaining_simples) = partitionBag (usefulToFloat is_useful) simples
1763 is_useful pred = tyCoVarsOfType pred `disjointVarSet` skol_set
1764
1765 usefulToFloat :: (TcPredType -> Bool) -> Ct -> Bool
1766 usefulToFloat is_useful_pred ct -- The constraint is un-flattened and de-canonicalised
1767 = is_meta_var_eq pred && is_useful_pred pred
1768 where
1769 pred = ctPred ct
1770
1771 -- Float out alpha ~ ty, or ty ~ alpha
1772 -- which might be unified outside
1773 -- See Note [Which equalities to float]
1774 is_meta_var_eq pred
1775 | EqPred NomEq ty1 ty2 <- classifyPredType pred
1776 = case (tcGetTyVar_maybe ty1, tcGetTyVar_maybe ty2) of
1777 (Just tv1, _) -> float_tv_eq tv1 ty2
1778 (_, Just tv2) -> float_tv_eq tv2 ty1
1779 _ -> False
1780 | otherwise
1781 = False
1782
1783 float_tv_eq tv1 ty2 -- See Note [Which equalities to float]
1784 = isMetaTyVar tv1
1785 && (not (isSigTyVar tv1) || isTyVarTy ty2)
1786
1787 {- Note [Float equalities from under a skolem binding]
1788 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1789 Which of the simple equalities can we float out? Obviously, only
1790 ones that don't mention the skolem-bound variables. But that is
1791 over-eager. Consider
1792 [2] forall a. F a beta[1] ~ gamma[2], G beta[1] gamma[2] ~ Int
1793 The second constraint doesn't mention 'a'. But if we float it,
1794 we'll promote gamma[2] to gamma'[1]. Now suppose that we learn that
1795 beta := Bool, and F a Bool = a, and G Bool _ = Int. Then we'll
1796 we left with the constraint
1797 [2] forall a. a ~ gamma'[1]
1798 which is insoluble because gamma became untouchable.
1799
1800 Solution: float only constraints that stand a jolly good chance of
1801 being soluble simply by being floated, namely ones of form
1802 a ~ ty
1803 where 'a' is a currently-untouchable unification variable, but may
1804 become touchable by being floated (perhaps by more than one level).
1805
1806 We had a very complicated rule previously, but this is nice and
1807 simple. (To see the notes, look at this Note in a version of
1808 TcSimplify prior to Oct 2014).
1809
1810 Note [Which equalities to float]
1811 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1812 Which equalities should we float? We want to float ones where there
1813 is a decent chance that floating outwards will allow unification to
1814 happen. In particular:
1815
1816 Float out equalities of form (alpaha ~ ty) or (ty ~ alpha), where
1817
1818 * alpha is a meta-tyvar.
1819
1820 * And 'alpha' is not a SigTv with 'ty' being a non-tyvar. In that
1821 case, floating out won't help either, and it may affect grouping
1822 of error messages.
1823
1824 Note [Skolem escape]
1825 ~~~~~~~~~~~~~~~~~~~~
1826 You might worry about skolem escape with all this floating.
1827 For example, consider
1828 [2] forall a. (a ~ F beta[2] delta,
1829 Maybe beta[2] ~ gamma[1])
1830
1831 The (Maybe beta ~ gamma) doesn't mention 'a', so we float it, and
1832 solve with gamma := beta. But what if later delta:=Int, and
1833 F b Int = b.
1834 Then we'd get a ~ beta[2], and solve to get beta:=a, and now the
1835 skolem has escaped!
1836
1837 But it's ok: when we float (Maybe beta[2] ~ gamma[1]), we promote beta[2]
1838 to beta[1], and that means the (a ~ beta[1]) will be stuck, as it should be.
1839
1840
1841 *********************************************************************************
1842 * *
1843 * Defaulting and disamgiguation *
1844 * *
1845 *********************************************************************************
1846 -}
1847
1848 applyDefaultingRules :: WantedConstraints -> TcS Bool
1849 -- True <=> I did some defaulting, by unifying a meta-tyvar
1850 -- Imput WantedConstraints are not necessarily zonked
1851
1852 applyDefaultingRules wanteds
1853 | isEmptyWC wanteds
1854 = return False
1855 | otherwise
1856 = do { info@(default_tys, _) <- getDefaultInfo
1857 ; wanteds <- TcS.zonkWC wanteds
1858
1859 ; let groups = findDefaultableGroups info wanteds
1860
1861 ; traceTcS "applyDefaultingRules {" $
1862 vcat [ text "wanteds =" <+> ppr wanteds
1863 , text "groups =" <+> ppr groups
1864 , text "info =" <+> ppr info ]
1865
1866 ; something_happeneds <- mapM (disambigGroup default_tys) groups
1867
1868 ; traceTcS "applyDefaultingRules }" (ppr something_happeneds)
1869
1870 ; return (or something_happeneds) }
1871
1872 findDefaultableGroups
1873 :: ( [Type]
1874 , (Bool,Bool) ) -- (Overloaded strings, extended default rules)
1875 -> WantedConstraints -- Unsolved (wanted or derived)
1876 -> [(TyVar, [Ct])]
1877 findDefaultableGroups (default_tys, (ovl_strings, extended_defaults)) wanteds
1878 | null default_tys
1879 = []
1880 | otherwise
1881 = [ (tv, map fstOf3 group)
1882 | group@((_,_,tv):_) <- unary_groups
1883 , defaultable_tyvar tv
1884 , defaultable_classes (map sndOf3 group) ]
1885 where
1886 simples = approximateWC wanteds
1887 (unaries, non_unaries) = partitionWith find_unary (bagToList simples)
1888 unary_groups = equivClasses cmp_tv unaries
1889
1890 unary_groups :: [[(Ct, Class, TcTyVar)]] -- (C tv) constraints
1891 unaries :: [(Ct, Class, TcTyVar)] -- (C tv) constraints
1892 non_unaries :: [Ct] -- and *other* constraints
1893
1894 -- Finds unary type-class constraints
1895 -- But take account of polykinded classes like Typeable,
1896 -- which may look like (Typeable * (a:*)) (Trac #8931)
1897 find_unary cc
1898 | Just (cls,tys) <- getClassPredTys_maybe (ctPred cc)
1899 , [ty] <- filterOutInvisibleTypes (classTyCon cls) tys
1900 -- Ignore invisible arguments for this purpose
1901 , Just tv <- tcGetTyVar_maybe ty
1902 , isMetaTyVar tv -- We might have runtime-skolems in GHCi, and
1903 -- we definitely don't want to try to assign to those!
1904 = Left (cc, cls, tv)
1905 find_unary cc = Right cc -- Non unary or non dictionary
1906
1907 bad_tvs :: TcTyCoVarSet -- TyVars mentioned by non-unaries
1908 bad_tvs = mapUnionVarSet tyCoVarsOfCt non_unaries
1909
1910 cmp_tv (_,_,tv1) (_,_,tv2) = tv1 `compare` tv2
1911
1912 defaultable_tyvar tv
1913 = let b1 = isTyConableTyVar tv -- Note [Avoiding spurious errors]
1914 b2 = not (tv `elemVarSet` bad_tvs)
1915 in b1 && b2
1916
1917 defaultable_classes clss
1918 | extended_defaults = any isInteractiveClass clss
1919 | otherwise = all is_std_class clss && (any is_num_class clss)
1920
1921 -- In interactive mode, or with -XExtendedDefaultRules,
1922 -- we default Show a to Show () to avoid graututious errors on "show []"
1923 isInteractiveClass cls
1924 = is_num_class cls || (classKey cls `elem` [showClassKey, eqClassKey
1925 , ordClassKey, foldableClassKey
1926 , traversableClassKey])
1927
1928 is_num_class cls = isNumericClass cls || (ovl_strings && (cls `hasKey` isStringClassKey))
1929 -- is_num_class adds IsString to the standard numeric classes,
1930 -- when -foverloaded-strings is enabled
1931
1932 is_std_class cls = isStandardClass cls || (ovl_strings && (cls `hasKey` isStringClassKey))
1933 -- Similarly is_std_class
1934
1935 ------------------------------
1936 disambigGroup :: [Type] -- The default types
1937 -> (TcTyVar, [Ct]) -- All classes of the form (C a)
1938 -- sharing same type variable
1939 -> TcS Bool -- True <=> something happened, reflected in ty_binds
1940
1941 disambigGroup [] _
1942 = return False
1943 disambigGroup (default_ty:default_tys) group@(the_tv, wanteds)
1944 = do { traceTcS "disambigGroup {" (vcat [ ppr default_ty, ppr the_tv, ppr wanteds ])
1945 ; fake_ev_binds_var <- TcS.newTcEvBinds
1946 ; tclvl <- TcS.getTcLevel
1947 ; (success, _) <- nestImplicTcS (Just fake_ev_binds_var) emptyVarSet
1948 (pushTcLevel tclvl) try_group
1949
1950 ; if success then
1951 -- Success: record the type variable binding, and return
1952 do { unifyTyVar the_tv default_ty
1953 ; wrapWarnTcS $ warnDefaulting wanteds default_ty
1954 ; traceTcS "disambigGroup succeeded }" (ppr default_ty)
1955 ; return True }
1956 else
1957 -- Failure: try with the next type
1958 do { traceTcS "disambigGroup failed, will try other default types }"
1959 (ppr default_ty)
1960 ; disambigGroup default_tys group } }
1961 where
1962 try_group
1963 | Just subst <- mb_subst
1964 = do { lcl_env <- TcS.getLclEnv
1965 ; let loc = CtLoc { ctl_origin = GivenOrigin UnkSkol
1966 , ctl_env = lcl_env
1967 , ctl_t_or_k = Nothing
1968 , ctl_depth = initialSubGoalDepth }
1969 ; wanted_evs <- mapM (newWantedEvVarNC loc . substTy subst . ctPred)
1970 wanteds
1971 ; fmap isEmptyWC $
1972 solveSimpleWanteds $ listToBag $
1973 map mkNonCanonical wanted_evs }
1974
1975 | otherwise
1976 = return False
1977
1978 the_ty = mkTyVarTy the_tv
1979 mb_subst = tcMatchTy the_ty default_ty
1980 -- Make sure the kinds match too; hence this call to tcMatchTy
1981 -- E.g. suppose the only constraint was (Typeable k (a::k))
1982 -- With the addition of polykinded defaulting we also want to reject
1983 -- ill-kinded defaulting attempts like (Eq []) or (Foldable Int) here.
1984
1985
1986 {-
1987 Note [Avoiding spurious errors]
1988 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1989 When doing the unification for defaulting, we check for skolem
1990 type variables, and simply don't default them. For example:
1991 f = (*) -- Monomorphic
1992 g :: Num a => a -> a
1993 g x = f x x
1994 Here, we get a complaint when checking the type signature for g,
1995 that g isn't polymorphic enough; but then we get another one when
1996 dealing with the (Num a) context arising from f's definition;
1997 we try to unify a with Int (to default it), but find that it's
1998 already been unified with the rigid variable from g's type sig.
1999 -}