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