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