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