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