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