Fix floating of equalities
[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
14 -- For Rules we need these
15 solveWanteds, solveWantedsAndDrop,
16 approximateWC, runTcSDeriveds
17 ) where
18
19 #include "HsVersions.h"
20
21 import GhcPrelude
22
23 import Bag
24 import Class ( Class, classKey, classTyCon )
25 import DynFlags ( WarningFlag ( Opt_WarnMonomorphism )
26 , WarnReason ( Reason )
27 , DynFlags( solverIterations ) )
28 import Id ( idType )
29 import Inst
30 import ListSetOps
31 import Maybes
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 ty_a ty_b | ty_a `eqType` ty_b = return True
493 tcSubsumes ty_a ty_b = discardErrs $
494 do { (_, wanted, _) <- pushLevelAndCaptureConstraints $
495 tcSubType_NC ExprSigCtxt ty_b ty_a
496 ; (rem, _) <- runTcS (simpl_top wanted)
497 -- We don't want any insoluble or simple constraints left,
498 -- but solved implications are ok (and neccessary for e.g. undefined)
499 ; return (isEmptyBag (wc_simple rem)
500 && allBag (isSolvedStatus . ic_status) (wc_impl rem))
501 }
502
503 ------------------
504 tcCheckSatisfiability :: Bag EvVar -> TcM Bool
505 -- Return True if satisfiable, False if definitely contradictory
506 tcCheckSatisfiability given_ids
507 = do { lcl_env <- TcM.getLclEnv
508 ; let given_loc = mkGivenLoc topTcLevel UnkSkol lcl_env
509 ; (res, _ev_binds) <- runTcS $
510 do { traceTcS "checkSatisfiability {" (ppr given_ids)
511 ; let given_cts = mkGivens given_loc (bagToList given_ids)
512 -- See Note [Superclasses and satisfiability]
513 ; solveSimpleGivens given_cts
514 ; insols <- getInertInsols
515 ; insols <- try_harder insols
516 ; traceTcS "checkSatisfiability }" (ppr insols)
517 ; return (isEmptyBag insols) }
518 ; return res }
519 where
520 try_harder :: Cts -> TcS Cts
521 -- Maybe we have to search up the superclass chain to find
522 -- an unsatisfiable constraint. Example: pmcheck/T3927b.
523 -- At the moment we try just once
524 try_harder insols
525 | not (isEmptyBag insols) -- We've found that it's definitely unsatisfiable
526 = return insols -- Hurrah -- stop now.
527 | otherwise
528 = do { pending_given <- getPendingScDicts
529 ; new_given <- makeSuperClasses pending_given
530 ; solveSimpleGivens new_given
531 ; getInertInsols }
532
533 {- Note [Superclasses and satisfiability]
534 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
535 Expand superclasses before starting, because (Int ~ Bool), has
536 (Int ~~ Bool) as a superclass, which in turn has (Int ~N# Bool)
537 as a superclass, and it's the latter that is insoluble. See
538 Note [The equality types story] in TysPrim.
539
540 If we fail to prove unsatisfiability we (arbitrarily) try just once to
541 find superclasses, using try_harder. Reason: we might have a type
542 signature
543 f :: F op (Implements push) => ..
544 where F is a type function. This happened in Trac #3972.
545
546 We could do more than once but we'd have to have /some/ limit: in the
547 the recursive case, we would go on forever in the common case where
548 the constraints /are/ satisfiable (Trac #10592 comment:12!).
549
550 For stratightforard situations without type functions the try_harder
551 step does nothing.
552
553
554 ***********************************************************************************
555 * *
556 * Inference
557 * *
558 ***********************************************************************************
559
560 Note [Inferring the type of a let-bound variable]
561 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
562 Consider
563 f x = rhs
564
565 To infer f's type we do the following:
566 * Gather the constraints for the RHS with ambient level *one more than*
567 the current one. This is done by the call
568 pushLevelAndCaptureConstraints (tcMonoBinds...)
569 in TcBinds.tcPolyInfer
570
571 * Call simplifyInfer to simplify the constraints and decide what to
572 quantify over. We pass in the level used for the RHS constraints,
573 here called rhs_tclvl.
574
575 This ensures that the implication constraint we generate, if any,
576 has a strictly-increased level compared to the ambient level outside
577 the let binding.
578
579 -}
580
581 -- | How should we choose which constraints to quantify over?
582 data InferMode = ApplyMR -- ^ Apply the monomorphism restriction,
583 -- never quantifying over any constraints
584 | EagerDefaulting -- ^ See Note [TcRnExprMode] in TcRnDriver,
585 -- the :type +d case; this mode refuses
586 -- to quantify over any defaultable constraint
587 | NoRestrictions -- ^ Quantify over any constraint that
588 -- satisfies TcType.pickQuantifiablePreds
589
590 instance Outputable InferMode where
591 ppr ApplyMR = text "ApplyMR"
592 ppr EagerDefaulting = text "EagerDefaulting"
593 ppr NoRestrictions = text "NoRestrictions"
594
595 simplifyInfer :: TcLevel -- Used when generating the constraints
596 -> InferMode
597 -> [TcIdSigInst] -- Any signatures (possibly partial)
598 -> [(Name, TcTauType)] -- Variables to be generalised,
599 -- and their tau-types
600 -> WantedConstraints
601 -> TcM ([TcTyVar], -- Quantify over these type variables
602 [EvVar], -- ... and these constraints (fully zonked)
603 TcEvBinds, -- ... binding these evidence variables
604 Bool) -- True <=> there was an insoluble type error
605 -- in these bindings
606 simplifyInfer rhs_tclvl infer_mode sigs name_taus wanteds
607 | isEmptyWC wanteds
608 = do { gbl_tvs <- tcGetGlobalTyCoVars
609 ; dep_vars <- zonkTcTypesAndSplitDepVars (map snd name_taus)
610 ; qtkvs <- quantifyTyVars gbl_tvs dep_vars
611 ; traceTc "simplifyInfer: empty WC" (ppr name_taus $$ ppr qtkvs)
612 ; return (qtkvs, [], emptyTcEvBinds, False) }
613
614 | otherwise
615 = do { traceTc "simplifyInfer {" $ vcat
616 [ text "sigs =" <+> ppr sigs
617 , text "binds =" <+> ppr name_taus
618 , text "rhs_tclvl =" <+> ppr rhs_tclvl
619 , text "infer_mode =" <+> ppr infer_mode
620 , text "(unzonked) wanted =" <+> ppr wanteds
621 ]
622
623 ; let partial_sigs = filter isPartialSig sigs
624 psig_theta = concatMap sig_inst_theta partial_sigs
625
626 -- First do full-blown solving
627 -- NB: we must gather up all the bindings from doing
628 -- this solving; hence (runTcSWithEvBinds ev_binds_var).
629 -- And note that since there are nested implications,
630 -- calling solveWanteds will side-effect their evidence
631 -- bindings, so we can't just revert to the input
632 -- constraint.
633
634 ; tc_lcl_env <- TcM.getLclEnv
635 ; ev_binds_var <- TcM.newTcEvBinds
636 ; psig_theta_vars <- mapM TcM.newEvVar psig_theta
637 ; wanted_transformed_incl_derivs
638 <- setTcLevel rhs_tclvl $
639 runTcSWithEvBinds ev_binds_var $
640 do { let loc = mkGivenLoc rhs_tclvl UnkSkol tc_lcl_env
641 psig_givens = mkGivens loc psig_theta_vars
642 ; _ <- solveSimpleGivens psig_givens
643 -- See Note [Add signature contexts as givens]
644 ; wanteds' <- solveWanteds wanteds
645 ; TcS.zonkWC wanteds' }
646
647
648 -- Find quant_pred_candidates, the predicates that
649 -- we'll consider quantifying over
650 -- NB1: wanted_transformed does not include anything provable from
651 -- the psig_theta; it's just the extra bit
652 -- NB2: We do not do any defaulting when inferring a type, this can lead
653 -- to less polymorphic types, see Note [Default while Inferring]
654 ; let definite_error = insolubleWC wanted_transformed_incl_derivs
655 -- See Note [Quantification with errors]
656 -- NB: must include derived errors in this test,
657 -- hence "incl_derivs"
658 wanted_transformed = dropDerivedWC wanted_transformed_incl_derivs
659 quant_pred_candidates
660 | definite_error = []
661 | otherwise = ctsPreds (approximateWC False wanted_transformed)
662
663 -- Decide what type variables and constraints to quantify
664 -- NB: quant_pred_candidates is already fully zonked
665 -- NB: bound_theta are constraints we want to quantify over,
666 -- /apart from/ the psig_theta, which we always quantify over
667 ; (qtvs, bound_theta, co_vars) <- decideQuantification infer_mode rhs_tclvl
668 name_taus partial_sigs
669 quant_pred_candidates
670
671 -- We must retain the psig_theta_vars, because we've used them in
672 -- evidence bindings constructed by solveWanteds earlier
673 ; psig_theta_vars <- mapM zonkId psig_theta_vars
674 ; bound_theta_vars <- mapM TcM.newEvVar bound_theta
675 ; let full_theta_vars = psig_theta_vars ++ bound_theta_vars
676
677 ; emitResidualConstraints rhs_tclvl tc_lcl_env ev_binds_var
678 name_taus co_vars qtvs
679 full_theta_vars wanted_transformed
680
681 -- All done!
682 ; traceTc "} simplifyInfer/produced residual implication for quantification" $
683 vcat [ text "quant_pred_candidates =" <+> ppr quant_pred_candidates
684 , text "psig_theta =" <+> ppr psig_theta
685 , text "bound_theta =" <+> ppr bound_theta
686 , text "full_theta =" <+> ppr (map idType full_theta_vars)
687 , text "qtvs =" <+> ppr qtvs
688 , text "definite_error =" <+> ppr definite_error ]
689
690 ; return ( qtvs, full_theta_vars, TcEvBinds ev_binds_var, definite_error ) }
691 -- NB: full_theta_vars must be fully zonked
692
693
694 --------------------
695 emitResidualConstraints :: TcLevel -> TcLclEnv -> EvBindsVar
696 -> [(Name, TcTauType)]
697 -> VarSet -> [TcTyVar] -> [EvVar]
698 -> WantedConstraints -> TcM ()
699 -- Emit the remaining constraints from the RHS.
700 -- See Note [Emitting the residual implication in simplifyInfer]
701 emitResidualConstraints rhs_tclvl tc_lcl_env ev_binds_var
702 name_taus co_vars qtvs full_theta_vars wanteds
703 | isEmptyWC wanteds
704 = return ()
705 | otherwise
706 = do { wanted_simple <- TcM.zonkSimples (wc_simple wanteds)
707 ; let (outer_simple, inner_simple) = partitionBag is_mono wanted_simple
708 is_mono ct = isWantedCt ct && ctEvId ct `elemVarSet` co_vars
709
710 ; tc_lvl <- TcM.getTcLevel
711 ; mapM_ (promoteTyVar tc_lvl) (tyCoVarsOfCtsList outer_simple)
712
713 ; unless (isEmptyCts outer_simple) $
714 do { traceTc "emitResidualConstrants:simple" (ppr outer_simple)
715 ; emitSimples outer_simple }
716
717 ; let inner_wanted = wanteds { wc_simple = inner_simple }
718 implic = mk_implic inner_wanted
719 ; unless (isEmptyWC inner_wanted) $
720 do { traceTc "emitResidualConstraints:implic" (ppr implic)
721 ; emitImplication implic }
722 }
723 where
724 mk_implic inner_wanted
725 = Implic { ic_tclvl = rhs_tclvl
726 , ic_skols = qtvs
727 , ic_no_eqs = False
728 , ic_given = full_theta_vars
729 , ic_wanted = inner_wanted
730 , ic_status = IC_Unsolved
731 , ic_binds = ev_binds_var
732 , ic_info = skol_info
733 , ic_needed = emptyVarSet
734 , ic_env = tc_lcl_env }
735
736 full_theta = map idType full_theta_vars
737 skol_info = InferSkol [ (name, mkSigmaTy [] full_theta ty)
738 | (name, ty) <- name_taus ]
739 -- Don't add the quantified variables here, because
740 -- they are also bound in ic_skols and we want them
741 -- to be tidied uniformly
742
743 --------------------
744 ctsPreds :: Cts -> [PredType]
745 ctsPreds cts = [ ctEvPred ev | ct <- bagToList cts
746 , let ev = ctEvidence ct ]
747
748 {- Note [Emitting the residual implication in simplifyInfer]
749 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
750 Consider
751 f = e
752 where f's type is infeered to be something like (a, Proxy k (Int |> co))
753 and we have an as-yet-unsolved, or perhaps insoluble, constraint
754 [W] co :: Type ~ k
755 We can't form types like (forall co. blah), so we can't generalise over
756 the coercion variable, and hence we can't generalise over things free in
757 its kind, in the case 'k'. But we can still generalise over 'a'. So
758 we'll generalise to
759 f :: forall a. (a, Proxy k (Int |> co))
760 Now we do NOT want to form the residual implication constraint
761 forall a. [W] co :: Type ~ k
762 because then co's eventual binding (which will be a value binding if we
763 use -fdefer-type-errors) won't scope over the entire binding for 'f' (whose
764 type mentions 'co'). Instead, just as we don't generalise over 'co', we
765 should not bury its constraint inside the implication. Instead, we must
766 put it outside.
767
768 That is the reason for the partitionBag in emitResidualConstraints,
769 which takes the CoVars free in the inferred type, and pulls their
770 constraints out. (NB: this set of CoVars should be
771 closed-over-kinds.)
772
773 All rather subtle; see Trac #14584.
774
775 Note [Add signature contexts as givens]
776 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
777 Consider this (Trac #11016):
778 f2 :: (?x :: Int) => _
779 f2 = ?x
780 or this
781 f3 :: a ~ Bool => (a, _)
782 f3 = (True, False)
783 or theis
784 f4 :: (Ord a, _) => a -> Bool
785 f4 x = x==x
786
787 We'll use plan InferGen because there are holes in the type. But:
788 * For f2 we want to have the (?x :: Int) constraint floating around
789 so that the functional dependencies kick in. Otherwise the
790 occurrence of ?x on the RHS produces constraint (?x :: alpha), and
791 we won't unify alpha:=Int.
792 * For f3 we want the (a ~ Bool) available to solve the wanted (a ~ Bool)
793 in the RHS
794 * For f4 we want to use the (Ord a) in the signature to solve the Eq a
795 constraint.
796
797 Solution: in simplifyInfer, just before simplifying the constraints
798 gathered from the RHS, add Given constraints for the context of any
799 type signatures.
800
801 ************************************************************************
802 * *
803 Quantification
804 * *
805 ************************************************************************
806
807 Note [Deciding quantification]
808 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
809 If the monomorphism restriction does not apply, then we quantify as follows:
810
811 * Step 1. Take the global tyvars, and "grow" them using the equality
812 constraints
813 E.g. if x:alpha is in the environment, and alpha ~ [beta] (which can
814 happen because alpha is untouchable here) then do not quantify over
815 beta, because alpha fixes beta, and beta is effectively free in
816 the environment too
817
818 We also account for the monomorphism restriction; if it applies,
819 add the free vars of all the constraints.
820
821 Result is mono_tvs; we will not quantify over these.
822
823 * Step 2. Default any non-mono tyvars (i.e ones that are definitely
824 not going to become further constrained), and re-simplify the
825 candidate constraints.
826
827 Motivation for re-simplification (Trac #7857): imagine we have a
828 constraint (C (a->b)), where 'a :: TYPE l1' and 'b :: TYPE l2' are
829 not free in the envt, and instance forall (a::*) (b::*). (C a) => C
830 (a -> b) The instance doesn't match while l1,l2 are polymorphic, but
831 it will match when we default them to LiftedRep.
832
833 This is all very tiresome.
834
835 * Step 3: decide which variables to quantify over, as follows:
836
837 - Take the free vars of the tau-type (zonked_tau_tvs) and "grow"
838 them using all the constraints. These are tau_tvs_plus
839
840 - Use quantifyTyVars to quantify over (tau_tvs_plus - mono_tvs), being
841 careful to close over kinds, and to skolemise the quantified tyvars.
842 (This actually unifies each quantifies meta-tyvar with a fresh skolem.)
843
844 Result is qtvs.
845
846 * Step 4: Filter the constraints using pickQuantifiablePreds and the
847 qtvs. We have to zonk the constraints first, so they "see" the
848 freshly created skolems.
849
850 -}
851
852 decideQuantification
853 :: InferMode
854 -> TcLevel
855 -> [(Name, TcTauType)] -- Variables to be generalised
856 -> [TcIdSigInst] -- Partial type signatures (if any)
857 -> [PredType] -- Candidate theta; already zonked
858 -> TcM ( [TcTyVar] -- Quantify over these (skolems)
859 , [PredType] -- and this context (fully zonked)
860 , VarSet)
861 -- See Note [Deciding quantification]
862 decideQuantification infer_mode rhs_tclvl name_taus psigs candidates
863 = do { -- Step 1: find the mono_tvs
864 ; (mono_tvs, candidates) <- decideMonoTyVars infer_mode
865 name_taus psigs candidates
866
867 -- Step 2: default any non-mono tyvars, and re-simplify
868 -- This step may do some unification, but result candidates is zonked
869 ; candidates <- defaultTyVarsAndSimplify rhs_tclvl mono_tvs candidates
870
871 -- Step 3: decide which kind/type variables to quantify over
872 ; (qtvs, co_vars) <- decideQuantifiedTyVars mono_tvs name_taus psigs candidates
873
874 -- Step 4: choose which of the remaining candidate
875 -- predicates to actually quantify over
876 -- NB: decideQuantifiedTyVars turned some meta tyvars
877 -- into quantified skolems, so we have to zonk again
878 ; candidates <- TcM.zonkTcTypes candidates
879 ; let theta = pickQuantifiablePreds (mkVarSet qtvs) $
880 mkMinimalBySCs id $ -- See Note [Minimize by Superclasses]
881 candidates
882
883 ; traceTc "decideQuantification"
884 (vcat [ text "infer_mode:" <+> ppr infer_mode
885 , text "candidates:" <+> ppr candidates
886 , text "mono_tvs:" <+> ppr mono_tvs
887 , text "co_vars:" <+> ppr co_vars
888 , text "qtvs:" <+> ppr qtvs
889 , text "theta:" <+> ppr theta ])
890 ; return (qtvs, theta, co_vars) }
891
892 ------------------
893 decideMonoTyVars :: InferMode
894 -> [(Name,TcType)]
895 -> [TcIdSigInst]
896 -> [PredType]
897 -> TcM (TcTyCoVarSet, [PredType])
898 -- Decide which tyvars and covars cannot be generalised:
899 -- (a) Free in the environment
900 -- (b) Mentioned in a constraint we can't generalise
901 -- (c) Connected by an equality to (a) or (b)
902 -- Also return the reduced set of constraint we can generalise
903 decideMonoTyVars infer_mode name_taus psigs candidates
904 = do { (no_quant, maybe_quant) <- pick infer_mode candidates
905
906 -- If possible, we quantify over partial-sig qtvs, so they are
907 -- not mono. Need to zonk them because they are meta-tyvar SigTvs
908 ; psig_qtvs <- mapM zonkTcTyVarToTyVar $
909 concatMap (map snd . sig_inst_skols) psigs
910
911 ; mono_tvs0 <- tcGetGlobalTyCoVars
912 ; let eq_constraints = filter isEqPred candidates
913 mono_tvs1 = growThetaTyVars eq_constraints mono_tvs0
914
915 constrained_tvs = (growThetaTyVars eq_constraints
916 (tyCoVarsOfTypes no_quant)
917 `minusVarSet` mono_tvs1)
918 `delVarSetList` psig_qtvs
919 -- constrained_tvs: the tyvars that we are not going to
920 -- quantify solely because of the moonomorphism restriction
921 --
922 -- (`minusVarSet` mono_tvs1`): a type variable is only
923 -- "constrained" (so that the MR bites) if it is not
924 -- free in the environment (Trac #13785)
925 --
926 -- (`delVarSetList` psig_qtvs): if the user has explicitly
927 -- asked for quantification, then that request "wins"
928 -- over the MR. Note: do /not/ delete psig_qtvs from
929 -- mono_tvs1, because mono_tvs1 cannot under any circumstances
930 -- be quantified (Trac #14479); see
931 -- Note [Quantification and partial signatures], Wrinkle 3, 4
932
933 mono_tvs = mono_tvs1 `unionVarSet` constrained_tvs
934
935 -- Warn about the monomorphism restriction
936 ; warn_mono <- woptM Opt_WarnMonomorphism
937 ; when (case infer_mode of { ApplyMR -> warn_mono; _ -> False}) $
938 do { taus <- mapM (TcM.zonkTcType . snd) name_taus
939 ; warnTc (Reason Opt_WarnMonomorphism)
940 (constrained_tvs `intersectsVarSet` tyCoVarsOfTypes taus)
941 mr_msg }
942
943 ; traceTc "decideMonoTyVars" $ vcat
944 [ text "mono_tvs0 =" <+> ppr mono_tvs0
945 , text "mono_tvs1 =" <+> ppr mono_tvs1
946 , text "no_quant =" <+> ppr no_quant
947 , text "maybe_quant =" <+> ppr maybe_quant
948 , text "eq_constraints =" <+> ppr eq_constraints
949 , text "mono_tvs =" <+> ppr mono_tvs ]
950
951 ; return (mono_tvs, maybe_quant) }
952 where
953 pick :: InferMode -> [PredType] -> TcM ([PredType], [PredType])
954 -- Split the candidates into ones we definitely
955 -- won't quantify, and ones that we might
956 pick NoRestrictions cand = return ([], cand)
957 pick ApplyMR cand = return (cand, [])
958 pick EagerDefaulting cand = do { os <- xoptM LangExt.OverloadedStrings
959 ; return (partition (is_int_ct os) cand) }
960
961 -- For EagerDefaulting, do not quantify over
962 -- over any interactive class constraint
963 is_int_ct ovl_strings pred
964 | Just (cls, _) <- getClassPredTys_maybe pred
965 = isInteractiveClass ovl_strings cls
966 | otherwise
967 = False
968
969 pp_bndrs = pprWithCommas (quotes . ppr . fst) name_taus
970 mr_msg =
971 hang (sep [ text "The Monomorphism Restriction applies to the binding"
972 <> plural name_taus
973 , text "for" <+> pp_bndrs ])
974 2 (hsep [ text "Consider giving"
975 , text (if isSingleton name_taus then "it" else "them")
976 , text "a type signature"])
977
978 -------------------
979 defaultTyVarsAndSimplify :: TcLevel
980 -> TyCoVarSet
981 -> [PredType] -- Assumed zonked
982 -> TcM [PredType] -- Guaranteed zonked
983 -- Default any tyvar free in the constraints,
984 -- and re-simplify in case the defaulting allows further simplification
985 defaultTyVarsAndSimplify rhs_tclvl mono_tvs candidates
986 = do { -- Promote any tyvars that we cannot generalise
987 -- See Note [Promote momomorphic tyvars]
988 ; outer_tclvl <- TcM.getTcLevel
989 ; let prom_tvs = nonDetEltsUniqSet mono_tvs
990 -- It's OK to use nonDetEltsUniqSet here
991 -- because promoteTyVar is commutative
992 ; traceTc "decideMonoTyVars: promotion:" (ppr prom_tvs)
993 ; proms <- mapM (promoteTyVar outer_tclvl) prom_tvs
994
995 -- Default any kind/levity vars
996 ; let DV {dv_kvs = cand_kvs, dv_tvs = cand_tvs}
997 = candidateQTyVarsOfTypes candidates
998 ; poly_kinds <- xoptM LangExt.PolyKinds
999 ; default_kvs <- mapM (default_one poly_kinds True)
1000 (dVarSetElems cand_kvs)
1001 ; default_tvs <- mapM (default_one poly_kinds False)
1002 (dVarSetElems (cand_tvs `minusDVarSet` cand_kvs))
1003 ; let some_default = or default_kvs || or default_tvs
1004
1005 ; case () of
1006 _ | some_default -> simplify_cand candidates
1007 | or proms -> mapM TcM.zonkTcType candidates
1008 | otherwise -> return candidates
1009 }
1010 where
1011 default_one poly_kinds is_kind_var tv
1012 | not (isMetaTyVar tv)
1013 = return False
1014 | tv `elemVarSet` mono_tvs
1015 = return False
1016 | otherwise
1017 = defaultTyVar (not poly_kinds && is_kind_var) tv
1018
1019 simplify_cand candidates
1020 = do { clone_wanteds <- newWanteds DefaultOrigin candidates
1021 ; WC { wc_simple = simples } <- setTcLevel rhs_tclvl $
1022 simplifyWantedsTcM clone_wanteds
1023 -- Discard evidence; simples is fully zonked
1024
1025 ; let new_candidates = ctsPreds simples
1026 ; traceTc "Simplified after defaulting" $
1027 vcat [ text "Before:" <+> ppr candidates
1028 , text "After:" <+> ppr new_candidates ]
1029 ; return new_candidates }
1030
1031 ------------------
1032 decideQuantifiedTyVars
1033 :: TyCoVarSet -- Monomorphic tyvars
1034 -> [(Name,TcType)] -- Annotated theta and (name,tau) pairs
1035 -> [TcIdSigInst] -- Partial signatures
1036 -> [PredType] -- Candidates, zonked
1037 -> TcM ([TyVar], CoVarSet)
1038 -- Fix what tyvars we are going to quantify over, and quantify them
1039 -- Also return CoVars that appear free in the final quatified types
1040 -- we can't quantify over these, and we must make sure they are in scope
1041 decideQuantifiedTyVars mono_tvs name_taus psigs candidates
1042 = do { -- Why psig_tys? We try to quantify over everything free in here
1043 -- See Note [Quantification and partial signatures]
1044 -- Wrinkles 2 and 3
1045 ; psig_tv_tys <- mapM TcM.zonkTcTyVar [ tv | sig <- psigs
1046 , (_,tv) <- sig_inst_skols sig ]
1047 ; psig_theta <- mapM TcM.zonkTcType [ pred | sig <- psigs
1048 , pred <- sig_inst_theta sig ]
1049 ; tau_tys <- mapM (TcM.zonkTcType . snd) name_taus
1050 ; mono_tvs <- TcM.zonkTyCoVarsAndFV mono_tvs
1051
1052 ; let -- Try to quantify over variables free in these types
1053 psig_tys = psig_tv_tys ++ psig_theta
1054 seed_tys = psig_tys ++ tau_tys
1055
1056 -- Now "grow" those seeds to find ones reachable via 'candidates'
1057 grown_tcvs = growThetaTyVars candidates (tyCoVarsOfTypes seed_tys)
1058
1059 -- We cannot quantify a type over a coercion (term-level) variable
1060 -- So, if any CoVars appear in grow_tcvs (they might for example
1061 -- appear in a cast in a type) we must remove them from the quantified
1062 -- variables, along with any type variables free in their kinds
1063 -- E.g. If we can't quantify over co :: k~Type, then we can't
1064 -- quantify over k either! Hence closeOverKinds
1065 ; let co_vars = filterVarSet isCoVar grown_tcvs
1066 proto_qtvs = grown_tcvs `minusVarSet` closeOverKinds co_vars
1067
1068 -- Now we have to classify them into kind variables and type variables
1069 -- (sigh) just for the benefit of -XNoPolyKinds; see quantifyTyVars
1070 --
1071 -- Keep the psig_tys first, so that candidateQTyVarsOfTypes produces
1072 -- them in that order, so that the final qtvs quantifies in the same
1073 -- order as the partial signatures do (Trac #13524)
1074 ; let DV {dv_kvs = cand_kvs, dv_tvs = cand_tvs}
1075 = candidateQTyVarsOfTypes $
1076 psig_tys ++ candidates ++ tau_tys
1077 pick = (`dVarSetIntersectVarSet` proto_qtvs)
1078 dvs_plus = DV { dv_kvs = pick cand_kvs, dv_tvs = pick cand_tvs }
1079
1080 ; traceTc "decideQuantifiedTyVars" (vcat
1081 [ text "seed_tys =" <+> ppr seed_tys
1082 , text "seed_tcvs =" <+> ppr (tyCoVarsOfTypes seed_tys)
1083 , text "grown_tcvs =" <+> ppr grown_tcvs
1084 , text "co_vars =" <+> ppr co_vars
1085 , text "proto_qtvs =" <+> ppr proto_qtvs])
1086
1087 ; qtvs <- quantifyTyVars mono_tvs dvs_plus
1088 ; return (qtvs, co_vars) }
1089
1090 ------------------
1091 growThetaTyVars :: ThetaType -> TyCoVarSet -> TyCoVarSet
1092 -- See Note [Growing the tau-tvs using constraints]
1093 growThetaTyVars theta tcvs
1094 | null theta = tcvs
1095 | otherwise = transCloVarSet mk_next seed_tcvs
1096 where
1097 seed_tcvs = tcvs `unionVarSet` tyCoVarsOfTypes ips
1098 (ips, non_ips) = partition isIPPred theta
1099 -- See Note [Inheriting implicit parameters] in TcType
1100
1101 mk_next :: VarSet -> VarSet -- Maps current set to newly-grown ones
1102 mk_next so_far = foldr (grow_one so_far) emptyVarSet non_ips
1103 grow_one so_far pred tcvs
1104 | pred_tcvs `intersectsVarSet` so_far = tcvs `unionVarSet` pred_tcvs
1105 | otherwise = tcvs
1106 where
1107 pred_tcvs = tyCoVarsOfType pred
1108
1109 {- Note [Promote momomorphic tyvars]
1110 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1111 Promote any type variables that are free in the environment. Eg
1112 f :: forall qtvs. bound_theta => zonked_tau
1113 The free vars of f's type become free in the envt, and hence will show
1114 up whenever 'f' is called. They may currently at rhs_tclvl, but they
1115 had better be unifiable at the outer_tclvl! Example: envt mentions
1116 alpha[1]
1117 tau_ty = beta[2] -> beta[2]
1118 constraints = alpha ~ [beta]
1119 we don't quantify over beta (since it is fixed by envt)
1120 so we must promote it! The inferred type is just
1121 f :: beta -> beta
1122
1123 NB: promoteTyVar ignores coercion variables
1124
1125 Note [Quantification and partial signatures]
1126 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1127 When choosing type variables to quantify, the basic plan is to
1128 quantify over all type variables that are
1129 * free in the tau_tvs, and
1130 * not forced to be monomorphic (mono_tvs),
1131 for example by being free in the environment.
1132
1133 However, in the case of a partial type signature, be doing inference
1134 *in the presence of a type signature*. For example:
1135 f :: _ -> a
1136 f x = ...
1137 or
1138 g :: (Eq _a) => _b -> _b
1139 In both cases we use plan InferGen, and hence call simplifyInfer. But
1140 those 'a' variables are skolems (actually SigTvs), and we should be
1141 sure to quantify over them. This leads to several wrinkles:
1142
1143 * Wrinkle 1. In the case of a type error
1144 f :: _ -> Maybe a
1145 f x = True && x
1146 The inferred type of 'f' is f :: Bool -> Bool, but there's a
1147 left-over error of form (HoleCan (Maybe a ~ Bool)). The error-reporting
1148 machine expects to find a binding site for the skolem 'a', so we
1149 add it to the quantified tyvars.
1150
1151 * Wrinkle 2. Consider the partial type signature
1152 f :: (Eq _) => Int -> Int
1153 f x = x
1154 In normal cases that makes sense; e.g.
1155 g :: Eq _a => _a -> _a
1156 g x = x
1157 where the signature makes the type less general than it could
1158 be. But for 'f' we must therefore quantify over the user-annotated
1159 constraints, to get
1160 f :: forall a. Eq a => Int -> Int
1161 (thereby correctly triggering an ambiguity error later). If we don't
1162 we'll end up with a strange open type
1163 f :: Eq alpha => Int -> Int
1164 which isn't ambiguous but is still very wrong.
1165
1166 Bottom line: Try to quantify over any variable free in psig_theta,
1167 just like the tau-part of the type.
1168
1169 * Wrinkle 3 (Trac #13482). Also consider
1170 f :: forall a. _ => Int -> Int
1171 f x = if (undefined :: a) == undefined then x else 0
1172 Here we get an (Eq a) constraint, but it's not mentioned in the
1173 psig_theta nor the type of 'f'. But we still want to quantify
1174 over 'a' even if the monomorphism restriction is on.
1175
1176 * Wrinkle 4 (Trac #14479)
1177 foo :: Num a => a -> a
1178 foo xxx = g xxx
1179 where
1180 g :: forall b. Num b => _ -> b
1181 g y = xxx + y
1182
1183 In the signature for 'g', we cannot quantify over 'b' because it turns out to
1184 get unified with 'a', which is free in g's environment. So we carefully
1185 refrain from bogusly quantifying, in TcSimplify.decideMonoTyVars. We
1186 report the error later, in TcBinds.chooseInferredQuantifiers.
1187
1188 Note [Quantifying over equality constraints]
1189 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1190 Should we quantify over an equality constraint (s ~ t)? In general, we don't.
1191 Doing so may simply postpone a type error from the function definition site to
1192 its call site. (At worst, imagine (Int ~ Bool)).
1193
1194 However, consider this
1195 forall a. (F [a] ~ Int) => blah
1196 Should we quantify over the (F [a] ~ Int)? Perhaps yes, because at the call
1197 site we will know 'a', and perhaps we have instance F [Bool] = Int.
1198 So we *do* quantify over a type-family equality where the arguments mention
1199 the quantified variables.
1200
1201 Note [Growing the tau-tvs using constraints]
1202 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1203 (growThetaTyVars insts tvs) is the result of extending the set
1204 of tyvars, tvs, using all conceivable links from pred
1205
1206 E.g. tvs = {a}, preds = {H [a] b, K (b,Int) c, Eq e}
1207 Then growThetaTyVars preds tvs = {a,b,c}
1208
1209 Notice that
1210 growThetaTyVars is conservative if v might be fixed by vs
1211 => v `elem` grow(vs,C)
1212
1213 Note [Quantification with errors]
1214 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1215 If we find that the RHS of the definition has some absolutely-insoluble
1216 constraints (including especially "variable not in scope"), we
1217
1218 * Abandon all attempts to find a context to quantify over,
1219 and instead make the function fully-polymorphic in whatever
1220 type we have found
1221
1222 * Return a flag from simplifyInfer, indicating that we found an
1223 insoluble constraint. This flag is used to suppress the ambiguity
1224 check for the inferred type, which may well be bogus, and which
1225 tends to obscure the real error. This fix feels a bit clunky,
1226 but I failed to come up with anything better.
1227
1228 Reasons:
1229 - Avoid downstream errors
1230 - Do not perform an ambiguity test on a bogus type, which might well
1231 fail spuriously, thereby obfuscating the original insoluble error.
1232 Trac #14000 is an example
1233
1234 I tried an alterantive approach: simply failM, after emitting the
1235 residual implication constraint; the exception will be caught in
1236 TcBinds.tcPolyBinds, which gives all the binders in the group the type
1237 (forall a. a). But that didn't work with -fdefer-type-errors, because
1238 the recovery from failM emits no code at all, so there is no function
1239 to run! But -fdefer-type-errors aspires to produce a runnable program.
1240
1241 NB that we must include *derived* errors in the check for insolubles.
1242 Example:
1243 (a::*) ~ Int#
1244 We get an insoluble derived error *~#, and we don't want to discard
1245 it before doing the isInsolubleWC test! (Trac #8262)
1246
1247 Note [Default while Inferring]
1248 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1249 Our current plan is that defaulting only happens at simplifyTop and
1250 not simplifyInfer. This may lead to some insoluble deferred constraints.
1251 Example:
1252
1253 instance D g => C g Int b
1254
1255 constraint inferred = (forall b. 0 => C gamma alpha b) /\ Num alpha
1256 type inferred = gamma -> gamma
1257
1258 Now, if we try to default (alpha := Int) we will be able to refine the implication to
1259 (forall b. 0 => C gamma Int b)
1260 which can then be simplified further to
1261 (forall b. 0 => D gamma)
1262 Finally, we /can/ approximate this implication with (D gamma) and infer the quantified
1263 type: forall g. D g => g -> g
1264
1265 Instead what will currently happen is that we will get a quantified type
1266 (forall g. g -> g) and an implication:
1267 forall g. 0 => (forall b. 0 => C g alpha b) /\ Num alpha
1268
1269 Which, even if the simplifyTop defaults (alpha := Int) we will still be left with an
1270 unsolvable implication:
1271 forall g. 0 => (forall b. 0 => D g)
1272
1273 The concrete example would be:
1274 h :: C g a s => g -> a -> ST s a
1275 f (x::gamma) = (\_ -> x) (runST (h x (undefined::alpha)) + 1)
1276
1277 But it is quite tedious to do defaulting and resolve the implication constraints, and
1278 we have not observed code breaking because of the lack of defaulting in inference, so
1279 we don't do it for now.
1280
1281
1282
1283 Note [Minimize by Superclasses]
1284 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1285 When we quantify over a constraint, in simplifyInfer we need to
1286 quantify over a constraint that is minimal in some sense: For
1287 instance, if the final wanted constraint is (Eq alpha, Ord alpha),
1288 we'd like to quantify over Ord alpha, because we can just get Eq alpha
1289 from superclass selection from Ord alpha. This minimization is what
1290 mkMinimalBySCs does. Then, simplifyInfer uses the minimal constraint
1291 to check the original wanted.
1292
1293
1294 Note [Avoid unnecessary constraint simplification]
1295 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1296 -------- NB NB NB (Jun 12) -------------
1297 This note not longer applies; see the notes with Trac #4361.
1298 But I'm leaving it in here so we remember the issue.)
1299 ----------------------------------------
1300 When inferring the type of a let-binding, with simplifyInfer,
1301 try to avoid unnecessarily simplifying class constraints.
1302 Doing so aids sharing, but it also helps with delicate
1303 situations like
1304
1305 instance C t => C [t] where ..
1306
1307 f :: C [t] => ....
1308 f x = let g y = ...(constraint C [t])...
1309 in ...
1310 When inferring a type for 'g', we don't want to apply the
1311 instance decl, because then we can't satisfy (C t). So we
1312 just notice that g isn't quantified over 't' and partition
1313 the constraints before simplifying.
1314
1315 This only half-works, but then let-generalisation only half-works.
1316
1317 *********************************************************************************
1318 * *
1319 * Main Simplifier *
1320 * *
1321 ***********************************************************************************
1322
1323 -}
1324
1325 simplifyWantedsTcM :: [CtEvidence] -> TcM WantedConstraints
1326 -- Solve the specified Wanted constraints
1327 -- Discard the evidence binds
1328 -- Discards all Derived stuff in result
1329 -- Postcondition: fully zonked and unflattened constraints
1330 simplifyWantedsTcM wanted
1331 = do { traceTc "simplifyWantedsTcM {" (ppr wanted)
1332 ; (result, _) <- runTcS (solveWantedsAndDrop (mkSimpleWC wanted))
1333 ; result <- TcM.zonkWC result
1334 ; traceTc "simplifyWantedsTcM }" (ppr result)
1335 ; return result }
1336
1337 solveWantedsAndDrop :: WantedConstraints -> TcS WantedConstraints
1338 -- Since solveWanteds returns the residual WantedConstraints,
1339 -- it should always be called within a runTcS or something similar,
1340 -- Result is not zonked
1341 solveWantedsAndDrop wanted
1342 = do { wc <- solveWanteds wanted
1343 ; return (dropDerivedWC wc) }
1344
1345 solveWanteds :: WantedConstraints -> TcS WantedConstraints
1346 -- so that the inert set doesn't mindlessly propagate.
1347 -- NB: wc_simples may be wanted /or/ derived now
1348 solveWanteds wc@(WC { wc_simple = simples, wc_impl = implics })
1349 = do { traceTcS "solveWanteds {" (ppr wc)
1350
1351 ; wc1 <- solveSimpleWanteds simples
1352 -- Any insoluble constraints are in 'simples' and so get rewritten
1353 -- See Note [Rewrite insolubles] in TcSMonad
1354
1355 ; let WC { wc_simple = simples1, wc_impl = implics1 } = wc1
1356
1357 ; (floated_eqs, implics2) <- solveNestedImplications (implics `unionBags` implics1)
1358 ; (no_new_scs, simples2) <- expandSuperClasses simples1
1359
1360 ; traceTcS "solveWanteds middle" $ vcat [ text "simples1 =" <+> ppr simples1
1361 , text "simples2 =" <+> ppr simples2 ]
1362
1363 ; dflags <- getDynFlags
1364 ; final_wc <- simpl_loop 0 (solverIterations dflags) floated_eqs
1365 no_new_scs
1366 (WC { wc_simple = simples2
1367 , wc_impl = implics2 })
1368
1369 ; ev_binds_var <- getTcEvBindsVar
1370 ; bb <- TcS.getTcEvBindsMap ev_binds_var
1371 ; traceTcS "solveWanteds }" $
1372 vcat [ text "final wc =" <+> ppr final_wc
1373 , text "current evbinds =" <+> ppr (evBindMapBinds bb) ]
1374
1375 ; return final_wc }
1376
1377 simpl_loop :: Int -> IntWithInf -> Cts -> Bool
1378 -> WantedConstraints
1379 -> TcS WantedConstraints
1380 simpl_loop n limit floated_eqs no_new_deriveds
1381 wc@(WC { wc_simple = simples, wc_impl = implics })
1382 | isEmptyBag floated_eqs && no_new_deriveds
1383 = return wc -- Done!
1384
1385 | n `intGtLimit` limit
1386 = do { -- Add an error (not a warning) if we blow the limit,
1387 -- Typically if we blow the limit we are going to report some other error
1388 -- (an unsolved constraint), and we don't want that error to suppress
1389 -- the iteration limit warning!
1390 addErrTcS (hang (text "solveWanteds: too many iterations"
1391 <+> parens (text "limit =" <+> ppr limit))
1392 2 (vcat [ text "Unsolved:" <+> ppr wc
1393 , ppUnless (isEmptyBag floated_eqs) $
1394 text "Floated equalities:" <+> ppr floated_eqs
1395 , ppUnless no_new_deriveds $
1396 text "New deriveds found"
1397 , text "Set limit with -fconstraint-solver-iterations=n; n=0 for no limit"
1398 ]))
1399 ; return wc }
1400
1401 | otherwise
1402 = do { let n_floated = lengthBag floated_eqs
1403 ; csTraceTcS $
1404 text "simpl_loop iteration=" <> int n
1405 <+> (parens $ hsep [ text "no new deriveds =" <+> ppr no_new_deriveds <> comma
1406 , int n_floated <+> text "floated eqs" <> comma
1407 , int (lengthBag simples) <+> text "simples to solve" ])
1408
1409 -- solveSimples may make progress if either float_eqs hold
1410 ; (unifs1, wc1) <- reportUnifications $
1411 solveSimpleWanteds $
1412 floated_eqs `unionBags` simples
1413 -- Notes:
1414 -- - Put floated_eqs first so they get solved first
1415 -- NB: the floated_eqs may include /derived/ equalities
1416 -- arising from fundeps inside an implication
1417
1418 ; let WC { wc_simple = simples1, wc_impl = implics1 } = wc1
1419 ; (no_new_scs, simples2) <- expandSuperClasses simples1
1420
1421 -- We have already tried to solve the nested implications once
1422 -- Try again only if we have unified some meta-variables
1423 -- (which is a bit like adding more givens)
1424 -- See Note [Cutting off simpl_loop]
1425 ; (floated_eqs2, implics2) <- if unifs1 == 0 && isEmptyBag implics1
1426 then return (emptyBag, implics)
1427 else solveNestedImplications (implics `unionBags` implics1)
1428
1429 ; simpl_loop (n+1) limit floated_eqs2 no_new_scs
1430 (WC { wc_simple = simples2
1431 , wc_impl = implics2 }) }
1432
1433
1434 expandSuperClasses :: Cts -> TcS (Bool, Cts)
1435 -- If there are any unsolved wanteds, expand one step of
1436 -- superclasses for deriveds
1437 -- Returned Bool is True <=> no new superclass constraints added
1438 -- See Note [The superclass story] in TcCanonical
1439 expandSuperClasses unsolved
1440 | not (anyBag superClassesMightHelp unsolved)
1441 = return (True, unsolved)
1442 | otherwise
1443 = do { traceTcS "expandSuperClasses {" empty
1444 ; let (pending_wanted, unsolved') = mapAccumBagL get [] unsolved
1445 get acc ct | Just ct' <- isPendingScDict ct
1446 = (ct':acc, ct')
1447 | otherwise
1448 = (acc, ct)
1449 ; pending_given <- getPendingScDicts
1450 ; if null pending_given && null pending_wanted
1451 then do { traceTcS "End expandSuperClasses no-op }" empty
1452 ; return (True, unsolved) }
1453 else
1454 do { new_given <- makeSuperClasses pending_given
1455 ; solveSimpleGivens new_given
1456 ; new_wanted <- makeSuperClasses pending_wanted
1457 ; traceTcS "End expandSuperClasses }"
1458 (vcat [ text "Given:" <+> ppr pending_given
1459 , text "Wanted:" <+> ppr new_wanted ])
1460 ; return (False, unsolved' `unionBags` listToBag new_wanted) } }
1461
1462 solveNestedImplications :: Bag Implication
1463 -> TcS (Cts, Bag Implication)
1464 -- Precondition: the TcS inerts may contain unsolved simples which have
1465 -- to be converted to givens before we go inside a nested implication.
1466 solveNestedImplications implics
1467 | isEmptyBag implics
1468 = return (emptyBag, emptyBag)
1469 | otherwise
1470 = do { traceTcS "solveNestedImplications starting {" empty
1471 ; (floated_eqs_s, unsolved_implics) <- mapAndUnzipBagM solveImplication implics
1472 ; let floated_eqs = concatBag floated_eqs_s
1473
1474 -- ... and we are back in the original TcS inerts
1475 -- Notice that the original includes the _insoluble_simples so it was safe to ignore
1476 -- them in the beginning of this function.
1477 ; traceTcS "solveNestedImplications end }" $
1478 vcat [ text "all floated_eqs =" <+> ppr floated_eqs
1479 , text "unsolved_implics =" <+> ppr unsolved_implics ]
1480
1481 ; return (floated_eqs, catBagMaybes unsolved_implics) }
1482
1483 solveImplication :: Implication -- Wanted
1484 -> TcS (Cts, -- All wanted or derived floated equalities: var = type
1485 Maybe Implication) -- Simplified implication (empty or singleton)
1486 -- Precondition: The TcS monad contains an empty worklist and given-only inerts
1487 -- which after trying to solve this implication we must restore to their original value
1488 solveImplication imp@(Implic { ic_tclvl = tclvl
1489 , ic_binds = ev_binds_var
1490 , ic_skols = skols
1491 , ic_given = given_ids
1492 , ic_wanted = wanteds
1493 , ic_info = info
1494 , ic_status = status
1495 , ic_env = env })
1496 | isSolvedStatus status
1497 = return (emptyCts, Just imp) -- Do nothing
1498
1499 | otherwise -- Even for IC_Insoluble it is worth doing more work
1500 -- The insoluble stuff might be in one sub-implication
1501 -- and other unsolved goals in another; and we want to
1502 -- solve the latter as much as possible
1503 = do { inerts <- getTcSInerts
1504 ; traceTcS "solveImplication {" (ppr imp $$ text "Inerts" <+> ppr inerts)
1505
1506 -- Solve the nested constraints
1507 ; (no_given_eqs, given_insols, residual_wanted)
1508 <- nestImplicTcS ev_binds_var tclvl $
1509 do { let loc = mkGivenLoc tclvl info env
1510 givens = mkGivens loc given_ids
1511 ; solveSimpleGivens givens
1512
1513 ; residual_wanted <- solveWanteds wanteds
1514 -- solveWanteds, *not* solveWantedsAndDrop, because
1515 -- we want to retain derived equalities so we can float
1516 -- them out in floatEqualities
1517
1518 ; (no_eqs, given_insols) <- getNoGivenEqs tclvl skols
1519 -- Call getNoGivenEqs /after/ solveWanteds, because
1520 -- solveWanteds can augment the givens, via expandSuperClasses,
1521 -- to reveal given superclass equalities
1522
1523 ; return (no_eqs, given_insols, residual_wanted) }
1524
1525 ; (floated_eqs, residual_wanted)
1526 <- floatEqualities skols given_ids ev_binds_var
1527 no_given_eqs residual_wanted
1528
1529 ; traceTcS "solveImplication 2"
1530 (ppr given_insols $$ ppr residual_wanted)
1531 ; let final_wanted = residual_wanted `addInsols` given_insols
1532 -- Don't lose track of the insoluble givens,
1533 -- which signal unreachable code; put them in ic_wanted
1534
1535 ; res_implic <- setImplicationStatus (imp { ic_no_eqs = no_given_eqs
1536 , ic_wanted = final_wanted })
1537
1538 ; (evbinds, tcvs) <- TcS.getTcEvBindsAndTCVs ev_binds_var
1539 ; traceTcS "solveImplication end }" $ vcat
1540 [ text "no_given_eqs =" <+> ppr no_given_eqs
1541 , text "floated_eqs =" <+> ppr floated_eqs
1542 , text "res_implic =" <+> ppr res_implic
1543 , text "implication evbinds =" <+> ppr (evBindMapBinds evbinds)
1544 , text "implication tvcs =" <+> ppr tcvs ]
1545
1546 ; return (floated_eqs, res_implic) }
1547
1548 ----------------------
1549 setImplicationStatus :: Implication -> TcS (Maybe Implication)
1550 -- Finalise the implication returned from solveImplication:
1551 -- * Set the ic_status field
1552 -- * Trim the ic_wanted field to remove Derived constraints
1553 -- Precondition: the ic_status field is not already IC_Solved
1554 -- Return Nothing if we can discard the implication altogether
1555 setImplicationStatus implic@(Implic { ic_binds = ev_binds_var
1556 , ic_status = status
1557 , ic_info = info
1558 , ic_wanted = wc
1559 , ic_needed = old_discarded_needs
1560 , ic_given = givens })
1561 | ASSERT2( not (isSolvedStatus status ), ppr info )
1562 -- Precondition: we only set the status if it is not already solved
1563 some_insoluble
1564 = return $ Just $
1565 implic { ic_status = IC_Insoluble
1566 , ic_needed = new_discarded_needs
1567 , ic_wanted = pruned_wc }
1568
1569 | some_unsolved
1570 = do { traceTcS "setImplicationStatus" $
1571 vcat [ppr givens $$ ppr simples $$ ppr mb_implic_needs]
1572 ; return $ Just $
1573 implic { ic_status = IC_Unsolved
1574 , ic_needed = new_discarded_needs
1575 , ic_wanted = pruned_wc }
1576 }
1577
1578 | otherwise -- Everything is solved; look at the implications
1579 -- See Note [Tracking redundant constraints]
1580 = do { ev_binds <- TcS.getTcEvBindsAndTCVs ev_binds_var
1581 ; let all_needs = neededEvVars ev_binds $
1582 solved_implic_needs `unionVarSet` new_discarded_needs
1583
1584 dead_givens | warnRedundantGivens info
1585 = filterOut (`elemVarSet` all_needs) givens
1586 | otherwise = [] -- None to report
1587
1588 final_needs = all_needs `delVarSetList` givens
1589
1590 discard_entire_implication -- Can we discard the entire implication?
1591 = null dead_givens -- No warning from this implication
1592 && isEmptyBag pruned_implics -- No live children
1593 && isEmptyVarSet final_needs -- No needed vars to pass up to parent
1594
1595 final_status = IC_Solved { ics_need = final_needs
1596 , ics_dead = dead_givens }
1597 final_implic = implic { ic_status = final_status
1598 , ic_needed = emptyVarSet -- Irrelevant for IC_Solved
1599 , ic_wanted = pruned_wc }
1600
1601 -- Check that there are no term-level evidence bindings
1602 -- in the cases where we have no place to put them
1603 ; MASSERT2( termEvidenceAllowed info || isEmptyEvBindMap (fst ev_binds)
1604 , ppr info $$ ppr ev_binds )
1605
1606 ; traceTcS "setImplicationStatus 2" $
1607 vcat [ppr givens $$ ppr ev_binds $$ ppr all_needs]
1608 ; return $ if discard_entire_implication
1609 then Nothing
1610 else Just final_implic }
1611 where
1612 WC { wc_simple = simples, wc_impl = implics } = wc
1613
1614 some_insoluble = insolubleWC wc
1615 some_unsolved = not (isEmptyBag simples)
1616 || isNothing mb_implic_needs
1617
1618 pruned_simples = dropDerivedSimples simples
1619 (pruned_implics, discarded_needs) = partitionBagWith discard_me implics
1620 pruned_wc = wc { wc_simple = pruned_simples
1621 , wc_impl = pruned_implics }
1622 new_discarded_needs = foldrBag unionVarSet old_discarded_needs discarded_needs
1623
1624 mb_implic_needs :: Maybe VarSet
1625 -- Just vs => all implics are IC_Solved, with 'vs' needed
1626 -- Nothing => at least one implic is not IC_Solved
1627 mb_implic_needs = foldrBag add_implic (Just emptyVarSet) pruned_implics
1628 Just solved_implic_needs = mb_implic_needs
1629
1630 add_implic implic acc
1631 | Just vs_acc <- acc
1632 , IC_Solved { ics_need = vs } <- ic_status implic
1633 = Just (vs `unionVarSet` vs_acc)
1634 | otherwise = Nothing
1635
1636 discard_me :: Implication -> Either Implication VarSet
1637 discard_me ic
1638 | IC_Solved { ics_dead = dead_givens, ics_need = needed } <- ic_status ic
1639 -- Fully solved
1640 , null dead_givens -- No redundant givens to report
1641 , isEmptyBag (wc_impl (ic_wanted ic))
1642 -- And no children that might have things to report
1643 = Right needed
1644 | otherwise
1645 = Left ic
1646
1647 warnRedundantGivens :: SkolemInfo -> Bool
1648 warnRedundantGivens (SigSkol ctxt _ _)
1649 = case ctxt of
1650 FunSigCtxt _ warn_redundant -> warn_redundant
1651 ExprSigCtxt -> True
1652 _ -> False
1653
1654 -- To think about: do we want to report redundant givens for
1655 -- pattern synonyms, PatSynSigSkol? c.f Trac #9953, comment:21.
1656 warnRedundantGivens (InstSkol {}) = True
1657 warnRedundantGivens _ = False
1658
1659 neededEvVars :: (EvBindMap, TcTyVarSet) -> VarSet -> VarSet
1660 -- Find all the evidence variables that are "needed",
1661 -- and then delete all those bound by the evidence bindings
1662 -- See Note [Tracking redundant constraints]
1663 --
1664 -- - Start from initial_seeds (from nested implications)
1665 -- - Add free vars of RHS of all Wanted evidence bindings
1666 -- and coercion variables accumulated in tcvs (all Wanted)
1667 -- - Do transitive closure through Given bindings
1668 -- e.g. Neede {a,b}
1669 -- Given a = sc_sel a2
1670 -- Then a2 is needed too
1671 -- - Finally delete all the binders of the evidence bindings
1672 --
1673 neededEvVars (ev_binds, tcvs) initial_seeds
1674 = needed `minusVarSet` bndrs
1675 where
1676 needed = transCloVarSet also_needs seeds
1677 seeds = foldEvBindMap add_wanted initial_seeds ev_binds
1678 `unionVarSet` tcvs
1679 bndrs = foldEvBindMap add_bndr emptyVarSet ev_binds
1680
1681 add_wanted :: EvBind -> VarSet -> VarSet
1682 add_wanted (EvBind { eb_is_given = is_given, eb_rhs = rhs }) needs
1683 | is_given = needs -- Add the rhs vars of the Wanted bindings only
1684 | otherwise = evVarsOfTerm rhs `unionVarSet` needs
1685
1686 also_needs :: VarSet -> VarSet
1687 also_needs needs
1688 = nonDetFoldUniqSet add emptyVarSet needs
1689 -- It's OK to use nonDetFoldUFM here because we immediately forget
1690 -- about the ordering by creating a set
1691 where
1692 add v needs
1693 | Just ev_bind <- lookupEvBind ev_binds v
1694 , EvBind { eb_is_given = is_given, eb_rhs = rhs } <- ev_bind
1695 , is_given
1696 = evVarsOfTerm rhs `unionVarSet` needs
1697 | otherwise
1698 = needs
1699
1700 add_bndr :: EvBind -> VarSet -> VarSet
1701 add_bndr (EvBind { eb_lhs = v }) vs = extendVarSet vs v
1702
1703
1704 {-
1705 Note [Tracking redundant constraints]
1706 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1707 With Opt_WarnRedundantConstraints, GHC can report which
1708 constraints of a type signature (or instance declaration) are
1709 redundant, and can be omitted. Here is an overview of how it
1710 works:
1711
1712 ----- What is a redundant constraint?
1713
1714 * The things that can be redundant are precisely the Given
1715 constraints of an implication.
1716
1717 * A constraint can be redundant in two different ways:
1718 a) It is implied by other givens. E.g.
1719 f :: (Eq a, Ord a) => blah -- Eq a unnecessary
1720 g :: (Eq a, a~b, Eq b) => blah -- Either Eq a or Eq b unnecessary
1721 b) It is not needed by the Wanted constraints covered by the
1722 implication E.g.
1723 f :: Eq a => a -> Bool
1724 f x = True -- Equality not used
1725
1726 * To find (a), when we have two Given constraints,
1727 we must be careful to drop the one that is a naked variable (if poss).
1728 So if we have
1729 f :: (Eq a, Ord a) => blah
1730 then we may find [G] sc_sel (d1::Ord a) :: Eq a
1731 [G] d2 :: Eq a
1732 We want to discard d2 in favour of the superclass selection from
1733 the Ord dictionary. This is done by TcInteract.solveOneFromTheOther
1734 See Note [Replacement vs keeping].
1735
1736 * To find (b) we need to know which evidence bindings are 'wanted';
1737 hence the eb_is_given field on an EvBind.
1738
1739 ----- How tracking works
1740
1741 * When the constraint solver finishes solving all the wanteds in
1742 an implication, it sets its status to IC_Solved
1743
1744 - The ics_dead field, of IC_Solved, records the subset of this
1745 implication's ic_given that are redundant (not needed).
1746
1747 - The ics_need field of IC_Solved then records all the
1748 in-scope (given) evidence variables bound by the context, that
1749 were needed to solve this implication, including all its nested
1750 implications. (We remove the ic_given of this implication from
1751 the set, of course.)
1752
1753 * We compute which evidence variables are needed by an implication
1754 in setImplicationStatus. A variable is needed if
1755 a) it is free in the RHS of a Wanted EvBind,
1756 b) it is free in the RHS of an EvBind whose LHS is needed,
1757 c) it is in the ics_need of a nested implication.
1758
1759 * We need to be careful not to discard an implication
1760 prematurely, even one that is fully solved, because we might
1761 thereby forget which variables it needs, and hence wrongly
1762 report a constraint as redundant. But we can discard it once
1763 its free vars have been incorporated into its parent; or if it
1764 simply has no free vars. This careful discarding is also
1765 handled in setImplicationStatus.
1766
1767 ----- Reporting redundant constraints
1768
1769 * TcErrors does the actual warning, in warnRedundantConstraints.
1770
1771 * We don't report redundant givens for *every* implication; only
1772 for those which reply True to TcSimplify.warnRedundantGivens:
1773
1774 - For example, in a class declaration, the default method *can*
1775 use the class constraint, but it certainly doesn't *have* to,
1776 and we don't want to report an error there.
1777
1778 - More subtly, in a function definition
1779 f :: (Ord a, Ord a, Ix a) => a -> a
1780 f x = rhs
1781 we do an ambiguity check on the type (which would find that one
1782 of the Ord a constraints was redundant), and then we check that
1783 the definition has that type (which might find that both are
1784 redundant). We don't want to report the same error twice, so we
1785 disable it for the ambiguity check. Hence using two different
1786 FunSigCtxts, one with the warn-redundant field set True, and the
1787 other set False in
1788 - TcBinds.tcSpecPrag
1789 - TcBinds.tcTySig
1790
1791 This decision is taken in setImplicationStatus, rather than TcErrors
1792 so that we can discard implication constraints that we don't need.
1793 So ics_dead consists only of the *reportable* redundant givens.
1794
1795 ----- Shortcomings
1796
1797 Consider (see Trac #9939)
1798 f2 :: (Eq a, Ord a) => a -> a -> Bool
1799 -- Ord a redundant, but Eq a is reported
1800 f2 x y = (x == y)
1801
1802 We report (Eq a) as redundant, whereas actually (Ord a) is. But it's
1803 really not easy to detect that!
1804
1805
1806 Note [Cutting off simpl_loop]
1807 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1808 It is very important not to iterate in simpl_loop unless there is a chance
1809 of progress. Trac #8474 is a classic example:
1810
1811 * There's a deeply-nested chain of implication constraints.
1812 ?x:alpha => ?y1:beta1 => ... ?yn:betan => [W] ?x:Int
1813
1814 * From the innermost one we get a [D] alpha ~ Int,
1815 but alpha is untouchable until we get out to the outermost one
1816
1817 * We float [D] alpha~Int out (it is in floated_eqs), but since alpha
1818 is untouchable, the solveInteract in simpl_loop makes no progress
1819
1820 * So there is no point in attempting to re-solve
1821 ?yn:betan => [W] ?x:Int
1822 via solveNestedImplications, because we'll just get the
1823 same [D] again
1824
1825 * If we *do* re-solve, we'll get an ininite loop. It is cut off by
1826 the fixed bound of 10, but solving the next takes 10*10*...*10 (ie
1827 exponentially many) iterations!
1828
1829 Conclusion: we should call solveNestedImplications only if we did
1830 some unification in solveSimpleWanteds; because that's the only way
1831 we'll get more Givens (a unification is like adding a Given) to
1832 allow the implication to make progress.
1833 -}
1834
1835 promoteTyVar :: TcLevel -> TcTyVar -> TcM Bool
1836 -- When we float a constraint out of an implication we must restore
1837 -- invariant (MetaTvInv) in Note [TcLevel and untouchable type variables] in TcType
1838 -- Return True <=> we did some promotion
1839 -- See Note [Promoting unification variables]
1840 promoteTyVar tclvl tv
1841 | isFloatedTouchableMetaTyVar tclvl tv
1842 = do { cloned_tv <- TcM.cloneMetaTyVar tv
1843 ; let rhs_tv = setMetaTyVarTcLevel cloned_tv tclvl
1844 ; TcM.writeMetaTyVar tv (mkTyVarTy rhs_tv)
1845 ; return True }
1846 | otherwise
1847 = return False
1848
1849 promoteTyVarTcS :: TcLevel -> TcTyVar -> TcS ()
1850 -- When we float a constraint out of an implication we must restore
1851 -- invariant (MetaTvInv) in Note [TcLevel and untouchable type variables] in TcType
1852 -- See Note [Promoting unification variables]
1853 -- We don't just call promoteTyVar because we want to use unifyTyVar,
1854 -- not writeMetaTyVar
1855 promoteTyVarTcS tclvl tv
1856 | isFloatedTouchableMetaTyVar tclvl tv
1857 = do { cloned_tv <- TcS.cloneMetaTyVar tv
1858 ; let rhs_tv = setMetaTyVarTcLevel cloned_tv tclvl
1859 ; unifyTyVar tv (mkTyVarTy rhs_tv) }
1860 | otherwise
1861 = return ()
1862
1863 -- | Like 'defaultTyVar', but in the TcS monad.
1864 defaultTyVarTcS :: TcTyVar -> TcS Bool
1865 defaultTyVarTcS the_tv
1866 | isRuntimeRepVar the_tv
1867 , not (isSigTyVar the_tv) -- SigTvs should only be unified with a tyvar
1868 -- never with a type; c.f. TcMType.defaultTyVar
1869 -- See Note [Kind generalisation and SigTvs]
1870 = do { traceTcS "defaultTyVarTcS RuntimeRep" (ppr the_tv)
1871 ; unifyTyVar the_tv liftedRepTy
1872 ; return True }
1873 | otherwise
1874 = return False -- the common case
1875
1876 approximateWC :: Bool -> WantedConstraints -> Cts
1877 -- Postcondition: Wanted or Derived Cts
1878 -- See Note [ApproximateWC]
1879 approximateWC float_past_equalities wc
1880 = float_wc emptyVarSet wc
1881 where
1882 float_wc :: TcTyCoVarSet -> WantedConstraints -> Cts
1883 float_wc trapping_tvs (WC { wc_simple = simples, wc_impl = implics })
1884 = filterBag (is_floatable trapping_tvs) simples `unionBags`
1885 do_bag (float_implic trapping_tvs) implics
1886 where
1887
1888 float_implic :: TcTyCoVarSet -> Implication -> Cts
1889 float_implic trapping_tvs imp
1890 | float_past_equalities || ic_no_eqs imp
1891 = float_wc new_trapping_tvs (ic_wanted imp)
1892 | otherwise -- Take care with equalities
1893 = emptyCts -- See (1) under Note [ApproximateWC]
1894 where
1895 new_trapping_tvs = trapping_tvs `extendVarSetList` ic_skols imp
1896
1897 do_bag :: (a -> Bag c) -> Bag a -> Bag c
1898 do_bag f = foldrBag (unionBags.f) emptyBag
1899
1900 is_floatable skol_tvs ct
1901 | isGivenCt ct = False
1902 | isHoleCt ct = False
1903 | insolubleEqCt ct = False
1904 | otherwise = tyCoVarsOfCt ct `disjointVarSet` skol_tvs
1905
1906 {- Note [ApproximateWC]
1907 ~~~~~~~~~~~~~~~~~~~~~~~
1908 approximateWC takes a constraint, typically arising from the RHS of a
1909 let-binding whose type we are *inferring*, and extracts from it some
1910 *simple* constraints that we might plausibly abstract over. Of course
1911 the top-level simple constraints are plausible, but we also float constraints
1912 out from inside, if they are not captured by skolems.
1913
1914 The same function is used when doing type-class defaulting (see the call
1915 to applyDefaultingRules) to extract constraints that that might be defaulted.
1916
1917 There is one caveat:
1918
1919 1. When infering most-general types (in simplifyInfer), we do *not*
1920 float anything out if the implication binds equality constraints,
1921 because that defeats the OutsideIn story. Consider
1922 data T a where
1923 TInt :: T Int
1924 MkT :: T a
1925
1926 f TInt = 3::Int
1927
1928 We get the implication (a ~ Int => res ~ Int), where so far we've decided
1929 f :: T a -> res
1930 We don't want to float (res~Int) out because then we'll infer
1931 f :: T a -> Int
1932 which is only on of the possible types. (GHC 7.6 accidentally *did*
1933 float out of such implications, which meant it would happily infer
1934 non-principal types.)
1935
1936 HOWEVER (Trac #12797) in findDefaultableGroups we are not worried about
1937 the most-general type; and we /do/ want to float out of equalities.
1938 Hence the boolean flag to approximateWC.
1939
1940 ------ Historical note -----------
1941 There used to be a second caveat, driven by Trac #8155
1942
1943 2. We do not float out an inner constraint that shares a type variable
1944 (transitively) with one that is trapped by a skolem. Eg
1945 forall a. F a ~ beta, Integral beta
1946 We don't want to float out (Integral beta). Doing so would be bad
1947 when defaulting, because then we'll default beta:=Integer, and that
1948 makes the error message much worse; we'd get
1949 Can't solve F a ~ Integer
1950 rather than
1951 Can't solve Integral (F a)
1952
1953 Moreover, floating out these "contaminated" constraints doesn't help
1954 when generalising either. If we generalise over (Integral b), we still
1955 can't solve the retained implication (forall a. F a ~ b). Indeed,
1956 arguably that too would be a harder error to understand.
1957
1958 But this transitive closure stuff gives rise to a complex rule for
1959 when defaulting actually happens, and one that was never documented.
1960 Moreover (Trac #12923), the more complex rule is sometimes NOT what
1961 you want. So I simply removed the extra code to implement the
1962 contamination stuff. There was zero effect on the testsuite (not even
1963 #8155).
1964 ------ End of historical note -----------
1965
1966
1967 Note [DefaultTyVar]
1968 ~~~~~~~~~~~~~~~~~~~
1969 defaultTyVar is used on any un-instantiated meta type variables to
1970 default any RuntimeRep variables to LiftedRep. This is important
1971 to ensure that instance declarations match. For example consider
1972
1973 instance Show (a->b)
1974 foo x = show (\_ -> True)
1975
1976 Then we'll get a constraint (Show (p ->q)) where p has kind (TYPE r),
1977 and that won't match the typeKind (*) in the instance decl. See tests
1978 tc217 and tc175.
1979
1980 We look only at touchable type variables. No further constraints
1981 are going to affect these type variables, so it's time to do it by
1982 hand. However we aren't ready to default them fully to () or
1983 whatever, because the type-class defaulting rules have yet to run.
1984
1985 An alternate implementation would be to emit a derived constraint setting
1986 the RuntimeRep variable to LiftedRep, but this seems unnecessarily indirect.
1987
1988 Note [Promote _and_ default when inferring]
1989 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1990 When we are inferring a type, we simplify the constraint, and then use
1991 approximateWC to produce a list of candidate constraints. Then we MUST
1992
1993 a) Promote any meta-tyvars that have been floated out by
1994 approximateWC, to restore invariant (MetaTvInv) described in
1995 Note [TcLevel and untouchable type variables] in TcType.
1996
1997 b) Default the kind of any meta-tyvars that are not mentioned in
1998 in the environment.
1999
2000 To see (b), suppose the constraint is (C ((a :: OpenKind) -> Int)), and we
2001 have an instance (C ((x:*) -> Int)). The instance doesn't match -- but it
2002 should! If we don't solve the constraint, we'll stupidly quantify over
2003 (C (a->Int)) and, worse, in doing so zonkQuantifiedTyVar will quantify over
2004 (b:*) instead of (a:OpenKind), which can lead to disaster; see Trac #7332.
2005 Trac #7641 is a simpler example.
2006
2007 Note [Promoting unification variables]
2008 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2009 When we float an equality out of an implication we must "promote" free
2010 unification variables of the equality, in order to maintain Invariant
2011 (MetaTvInv) from Note [TcLevel and untouchable type variables] in TcType. for the
2012 leftover implication.
2013
2014 This is absolutely necessary. Consider the following example. We start
2015 with two implications and a class with a functional dependency.
2016
2017 class C x y | x -> y
2018 instance C [a] [a]
2019
2020 (I1) [untch=beta]forall b. 0 => F Int ~ [beta]
2021 (I2) [untch=beta]forall c. 0 => F Int ~ [[alpha]] /\ C beta [c]
2022
2023 We float (F Int ~ [beta]) out of I1, and we float (F Int ~ [[alpha]]) out of I2.
2024 They may react to yield that (beta := [alpha]) which can then be pushed inwards
2025 the leftover of I2 to get (C [alpha] [a]) which, using the FunDep, will mean that
2026 (alpha := a). In the end we will have the skolem 'b' escaping in the untouchable
2027 beta! Concrete example is in indexed_types/should_fail/ExtraTcsUntch.hs:
2028
2029 class C x y | x -> y where
2030 op :: x -> y -> ()
2031
2032 instance C [a] [a]
2033
2034 type family F a :: *
2035
2036 h :: F Int -> ()
2037 h = undefined
2038
2039 data TEx where
2040 TEx :: a -> TEx
2041
2042 f (x::beta) =
2043 let g1 :: forall b. b -> ()
2044 g1 _ = h [x]
2045 g2 z = case z of TEx y -> (h [[undefined]], op x [y])
2046 in (g1 '3', g2 undefined)
2047
2048
2049
2050 *********************************************************************************
2051 * *
2052 * Floating equalities *
2053 * *
2054 *********************************************************************************
2055
2056 Note [Float Equalities out of Implications]
2057 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2058 For ordinary pattern matches (including existentials) we float
2059 equalities out of implications, for instance:
2060 data T where
2061 MkT :: Eq a => a -> T
2062 f x y = case x of MkT _ -> (y::Int)
2063 We get the implication constraint (x::T) (y::alpha):
2064 forall a. [untouchable=alpha] Eq a => alpha ~ Int
2065 We want to float out the equality into a scope where alpha is no
2066 longer untouchable, to solve the implication!
2067
2068 But we cannot float equalities out of implications whose givens may
2069 yield or contain equalities:
2070
2071 data T a where
2072 T1 :: T Int
2073 T2 :: T Bool
2074 T3 :: T a
2075
2076 h :: T a -> a -> Int
2077
2078 f x y = case x of
2079 T1 -> y::Int
2080 T2 -> y::Bool
2081 T3 -> h x y
2082
2083 We generate constraint, for (x::T alpha) and (y :: beta):
2084 [untouchables = beta] (alpha ~ Int => beta ~ Int) -- From 1st branch
2085 [untouchables = beta] (alpha ~ Bool => beta ~ Bool) -- From 2nd branch
2086 (alpha ~ beta) -- From 3rd branch
2087
2088 If we float the equality (beta ~ Int) outside of the first implication and
2089 the equality (beta ~ Bool) out of the second we get an insoluble constraint.
2090 But if we just leave them inside the implications, we unify alpha := beta and
2091 solve everything.
2092
2093 Principle:
2094 We do not want to float equalities out which may
2095 need the given *evidence* to become soluble.
2096
2097 Consequence: classes with functional dependencies don't matter (since there is
2098 no evidence for a fundep equality), but equality superclasses do matter (since
2099 they carry evidence).
2100 -}
2101
2102 floatEqualities :: [TcTyVar] -> [EvId] -> EvBindsVar -> Bool
2103 -> WantedConstraints
2104 -> TcS (Cts, WantedConstraints)
2105 -- Main idea: see Note [Float Equalities out of Implications]
2106 --
2107 -- Precondition: the wc_simple of the incoming WantedConstraints are
2108 -- fully zonked, so that we can see their free variables
2109 --
2110 -- Postcondition: The returned floated constraints (Cts) are only
2111 -- Wanted or Derived
2112 --
2113 -- Also performs some unifications (via promoteTyVar), adding to
2114 -- monadically-carried ty_binds. These will be used when processing
2115 -- floated_eqs later
2116 --
2117 -- Subtleties: Note [Float equalities from under a skolem binding]
2118 -- Note [Skolem escape]
2119 -- Note [What prevents a constraint from floating]
2120 floatEqualities skols given_ids ev_binds_var no_given_eqs
2121 wanteds@(WC { wc_simple = simples })
2122 | not no_given_eqs -- There are some given equalities, so don't float
2123 = return (emptyBag, wanteds) -- Note [Float Equalities out of Implications]
2124
2125 | otherwise
2126 = do { -- First zonk: the inert set (from whence they came) is fully
2127 -- zonked, but unflattening may have filled in unification
2128 -- variables, and we /must/ see them. Otherwise we may float
2129 -- constraints that mention the skolems!
2130 simples <- TcS.zonkSimples simples
2131 ; binds <- TcS.getTcEvBindsMap ev_binds_var
2132
2133 -- Now we can pick the ones to float
2134 -- The constraints are un-flattened and de-canonicalised
2135 ; let seed_skols = mkVarSet skols `unionVarSet`
2136 mkVarSet given_ids `unionVarSet`
2137 foldEvBindMap add_one emptyVarSet binds
2138 add_one bind acc = extendVarSet acc (evBindVar bind)
2139 -- seed_skols: See Note [What prevents a constraint from floating] (1,2,3)
2140
2141 (eqs, non_eqs) = partitionBag is_eq_ct simples
2142 extended_skols = transCloVarSet (extra_skols eqs) seed_skols
2143 (flt_eqs, no_flt_eqs) = partitionBag (is_floatable extended_skols) eqs
2144 remaining_simples = non_eqs `andCts` no_flt_eqs
2145 -- extended_skols: See Note [What prevents a constraint from floating] (3)
2146
2147 -- Promote any unification variables mentioned in the floated equalities
2148 -- See Note [Promoting unification variables]
2149 ; outer_tclvl <- TcS.getTcLevel
2150 ; mapM_ (promoteTyVarTcS outer_tclvl)
2151 (tyCoVarsOfCtsList flt_eqs)
2152
2153 ; traceTcS "floatEqualities" (vcat [ text "Skols =" <+> ppr skols
2154 , text "Extended skols =" <+> ppr extended_skols
2155 , text "Simples =" <+> ppr simples
2156 , text "Eqs =" <+> ppr eqs
2157 , text "Floated eqs =" <+> ppr flt_eqs])
2158 ; return ( flt_eqs, wanteds { wc_simple = remaining_simples } ) }
2159
2160 where
2161 is_floatable :: VarSet -> Ct -> Bool
2162 is_floatable skols ct
2163 | isDerivedCt ct = not (tyCoVarsOfCt ct `intersectsVarSet` skols)
2164 | otherwise = not (ctEvId ct `elemVarSet` skols)
2165
2166 is_eq_ct ct | CTyEqCan {} <- ct = True
2167 | is_homo_eq (ctPred ct) = True
2168 | otherwise = False
2169
2170 extra_skols :: Cts -> VarSet -> VarSet
2171 extra_skols eqs skols = foldrBag extra_skol emptyVarSet eqs
2172 where
2173 extra_skol ct acc
2174 | isDerivedCt ct = acc
2175 | tyCoVarsOfCt ct `intersectsVarSet` skols = extendVarSet acc (ctEvId ct)
2176 | otherwise = acc
2177
2178 -- Float out alpha ~ ty, or ty ~ alpha
2179 -- which might be unified outside
2180 -- See Note [Which equalities to float]
2181 is_homo_eq pred
2182 | EqPred NomEq ty1 ty2 <- classifyPredType pred
2183 , typeKind ty1 `tcEqType` typeKind ty2
2184 = case (tcGetTyVar_maybe ty1, tcGetTyVar_maybe ty2) of
2185 (Just tv1, _) -> float_tv_eq tv1 ty2
2186 (_, Just tv2) -> float_tv_eq tv2 ty1
2187 _ -> False
2188 | otherwise
2189 = False
2190
2191 float_tv_eq tv1 ty2 -- See Note [Which equalities to float]
2192 = isMetaTyVar tv1
2193 && (not (isSigTyVar tv1) || isTyVarTy ty2)
2194
2195
2196 {- Note [Float equalities from under a skolem binding]
2197 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2198 Which of the simple equalities can we float out? Obviously, only
2199 ones that don't mention the skolem-bound variables. But that is
2200 over-eager. Consider
2201 [2] forall a. F a beta[1] ~ gamma[2], G beta[1] gamma[2] ~ Int
2202 The second constraint doesn't mention 'a'. But if we float it,
2203 we'll promote gamma[2] to gamma'[1]. Now suppose that we learn that
2204 beta := Bool, and F a Bool = a, and G Bool _ = Int. Then we'll
2205 we left with the constraint
2206 [2] forall a. a ~ gamma'[1]
2207 which is insoluble because gamma became untouchable.
2208
2209 Solution: float only constraints that stand a jolly good chance of
2210 being soluble simply by being floated, namely ones of form
2211 a ~ ty
2212 where 'a' is a currently-untouchable unification variable, but may
2213 become touchable by being floated (perhaps by more than one level).
2214
2215 We had a very complicated rule previously, but this is nice and
2216 simple. (To see the notes, look at this Note in a version of
2217 TcSimplify prior to Oct 2014).
2218
2219 Note [Which equalities to float]
2220 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2221 Which equalities should we float? We want to float ones where there
2222 is a decent chance that floating outwards will allow unification to
2223 happen. In particular:
2224
2225 Float out homogeneous equalities of form (alpha ~ ty) or (ty ~ alpha), where
2226
2227 * alpha is a meta-tyvar.
2228
2229 * And 'alpha' is not a SigTv with 'ty' being a non-tyvar. In that
2230 case, floating out won't help either, and it may affect grouping
2231 of error messages.
2232
2233 Why homogeneous (i.e., the kinds of the types are the same)? Because heterogeneous
2234 equalities have derived kind equalities. See Note [Equalities with incompatible kinds]
2235 in TcCanonical. If we float out a hetero equality, then it will spit out the
2236 same derived kind equality again, which might create duplicate error messages.
2237 Instead, we do float out the kind equality (if it's worth floating out, as
2238 above). If/when we solve it, we'll be able to rewrite the original hetero equality
2239 to be homogeneous, and then perhaps make progress / float it out. The duplicate
2240 error message was spotted in typecheck/should_fail/T7368.
2241
2242 Note [Skolem escape]
2243 ~~~~~~~~~~~~~~~~~~~~
2244 You might worry about skolem escape with all this floating.
2245 For example, consider
2246 [2] forall a. (a ~ F beta[2] delta,
2247 Maybe beta[2] ~ gamma[1])
2248
2249 The (Maybe beta ~ gamma) doesn't mention 'a', so we float it, and
2250 solve with gamma := beta. But what if later delta:=Int, and
2251 F b Int = b.
2252 Then we'd get a ~ beta[2], and solve to get beta:=a, and now the
2253 skolem has escaped!
2254
2255 But it's ok: when we float (Maybe beta[2] ~ gamma[1]), we promote beta[2]
2256 to beta[1], and that means the (a ~ beta[1]) will be stuck, as it should be.
2257
2258 Note [What prevents a constraint from floating]
2259 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2260 What /prevents/ a constraint from floating? If it mentions one of the
2261 "bound variables of the implication". What are they?
2262
2263 The "bound variables of the implication" are
2264
2265 1. The skolem type variables `ic_skols`
2266
2267 2. The "given" evidence variables `ic_given`. Example:
2268 forall a. (co :: t1 ~# t2) => [W] co : (a ~# b |> co)
2269
2270 3. The binders of all evidence bindings in `ic_binds`. Example
2271 forall a. (d :: t1 ~ t2)
2272 EvBinds { (co :: t1 ~# t2) = superclass-sel d }
2273 => [W] co : (a ~# b |> co)
2274 Here `co` is gotten by superclass selection from `d`.
2275
2276 4. And the evidence variable of any equality constraint whose type
2277 mentions a bound variable. Example:
2278 forall k. [W] co1 :: t1 ~# t2 |> co2
2279 [W] co2 :: k ~# *
2280 Here, since `k` is bound, so is `co2` and hence so is `co1`.
2281
2282 Here (1,2,3) are handled by the "seed_skols" calculation, and
2283 (4) is done by the transCloVarSet call.
2284
2285 The possible dependence on givens, and evidence bindings, is more
2286 subtle than we'd realised at first. See Trac #14584.
2287
2288
2289 *********************************************************************************
2290 * *
2291 * Defaulting and disambiguation *
2292 * *
2293 *********************************************************************************
2294 -}
2295
2296 applyDefaultingRules :: WantedConstraints -> TcS Bool
2297 -- True <=> I did some defaulting, by unifying a meta-tyvar
2298 -- Input WantedConstraints are not necessarily zonked
2299
2300 applyDefaultingRules wanteds
2301 | isEmptyWC wanteds
2302 = return False
2303 | otherwise
2304 = do { info@(default_tys, _) <- getDefaultInfo
2305 ; wanteds <- TcS.zonkWC wanteds
2306
2307 ; let groups = findDefaultableGroups info wanteds
2308
2309 ; traceTcS "applyDefaultingRules {" $
2310 vcat [ text "wanteds =" <+> ppr wanteds
2311 , text "groups =" <+> ppr groups
2312 , text "info =" <+> ppr info ]
2313
2314 ; something_happeneds <- mapM (disambigGroup default_tys) groups
2315
2316 ; traceTcS "applyDefaultingRules }" (ppr something_happeneds)
2317
2318 ; return (or something_happeneds) }
2319
2320 findDefaultableGroups
2321 :: ( [Type]
2322 , (Bool,Bool) ) -- (Overloaded strings, extended default rules)
2323 -> WantedConstraints -- Unsolved (wanted or derived)
2324 -> [(TyVar, [Ct])]
2325 findDefaultableGroups (default_tys, (ovl_strings, extended_defaults)) wanteds
2326 | null default_tys
2327 = []
2328 | otherwise
2329 = [ (tv, map fstOf3 group)
2330 | group'@((_,_,tv) :| _) <- unary_groups
2331 , let group = toList group'
2332 , defaultable_tyvar tv
2333 , defaultable_classes (map sndOf3 group) ]
2334 where
2335 simples = approximateWC True wanteds
2336 (unaries, non_unaries) = partitionWith find_unary (bagToList simples)
2337 unary_groups = equivClasses cmp_tv unaries
2338
2339 unary_groups :: [NonEmpty (Ct, Class, TcTyVar)] -- (C tv) constraints
2340 unaries :: [(Ct, Class, TcTyVar)] -- (C tv) constraints
2341 non_unaries :: [Ct] -- and *other* constraints
2342
2343 -- Finds unary type-class constraints
2344 -- But take account of polykinded classes like Typeable,
2345 -- which may look like (Typeable * (a:*)) (Trac #8931)
2346 find_unary :: Ct -> Either (Ct, Class, TyVar) Ct
2347 find_unary cc
2348 | Just (cls,tys) <- getClassPredTys_maybe (ctPred cc)
2349 , [ty] <- filterOutInvisibleTypes (classTyCon cls) tys
2350 -- Ignore invisible arguments for this purpose
2351 , Just tv <- tcGetTyVar_maybe ty
2352 , isMetaTyVar tv -- We might have runtime-skolems in GHCi, and
2353 -- we definitely don't want to try to assign to those!
2354 = Left (cc, cls, tv)
2355 find_unary cc = Right cc -- Non unary or non dictionary
2356
2357 bad_tvs :: TcTyCoVarSet -- TyVars mentioned by non-unaries
2358 bad_tvs = mapUnionVarSet tyCoVarsOfCt non_unaries
2359
2360 cmp_tv (_,_,tv1) (_,_,tv2) = tv1 `compare` tv2
2361
2362 defaultable_tyvar :: TcTyVar -> Bool
2363 defaultable_tyvar tv
2364 = let b1 = isTyConableTyVar tv -- Note [Avoiding spurious errors]
2365 b2 = not (tv `elemVarSet` bad_tvs)
2366 in b1 && (b2 || extended_defaults) -- Note [Multi-parameter defaults]
2367
2368 defaultable_classes :: [Class] -> Bool
2369 defaultable_classes clss
2370 | extended_defaults = any (isInteractiveClass ovl_strings) clss
2371 | otherwise = all is_std_class clss && (any (isNumClass ovl_strings) clss)
2372
2373 -- is_std_class adds IsString to the standard numeric classes,
2374 -- when -foverloaded-strings is enabled
2375 is_std_class cls = isStandardClass cls ||
2376 (ovl_strings && (cls `hasKey` isStringClassKey))
2377
2378 ------------------------------
2379 disambigGroup :: [Type] -- The default types
2380 -> (TcTyVar, [Ct]) -- All classes of the form (C a)
2381 -- sharing same type variable
2382 -> TcS Bool -- True <=> something happened, reflected in ty_binds
2383
2384 disambigGroup [] _
2385 = return False
2386 disambigGroup (default_ty:default_tys) group@(the_tv, wanteds)
2387 = do { traceTcS "disambigGroup {" (vcat [ ppr default_ty, ppr the_tv, ppr wanteds ])
2388 ; fake_ev_binds_var <- TcS.newTcEvBinds
2389 ; tclvl <- TcS.getTcLevel
2390 ; success <- nestImplicTcS fake_ev_binds_var (pushTcLevel tclvl) try_group
2391
2392 ; if success then
2393 -- Success: record the type variable binding, and return
2394 do { unifyTyVar the_tv default_ty
2395 ; wrapWarnTcS $ warnDefaulting wanteds default_ty
2396 ; traceTcS "disambigGroup succeeded }" (ppr default_ty)
2397 ; return True }
2398 else
2399 -- Failure: try with the next type
2400 do { traceTcS "disambigGroup failed, will try other default types }"
2401 (ppr default_ty)
2402 ; disambigGroup default_tys group } }
2403 where
2404 try_group
2405 | Just subst <- mb_subst
2406 = do { lcl_env <- TcS.getLclEnv
2407 ; tc_lvl <- TcS.getTcLevel
2408 ; let loc = mkGivenLoc tc_lvl UnkSkol lcl_env
2409 ; wanted_evs <- mapM (newWantedEvVarNC loc . substTy subst . ctPred)
2410 wanteds
2411 ; fmap isEmptyWC $
2412 solveSimpleWanteds $ listToBag $
2413 map mkNonCanonical wanted_evs }
2414
2415 | otherwise
2416 = return False
2417
2418 the_ty = mkTyVarTy the_tv
2419 mb_subst = tcMatchTyKi the_ty default_ty
2420 -- Make sure the kinds match too; hence this call to tcMatchTyKi
2421 -- E.g. suppose the only constraint was (Typeable k (a::k))
2422 -- With the addition of polykinded defaulting we also want to reject
2423 -- ill-kinded defaulting attempts like (Eq []) or (Foldable Int) here.
2424
2425 -- In interactive mode, or with -XExtendedDefaultRules,
2426 -- we default Show a to Show () to avoid graututious errors on "show []"
2427 isInteractiveClass :: Bool -- -XOverloadedStrings?
2428 -> Class -> Bool
2429 isInteractiveClass ovl_strings cls
2430 = isNumClass ovl_strings cls || (classKey cls `elem` interactiveClassKeys)
2431
2432 -- isNumClass adds IsString to the standard numeric classes,
2433 -- when -foverloaded-strings is enabled
2434 isNumClass :: Bool -- -XOverloadedStrings?
2435 -> Class -> Bool
2436 isNumClass ovl_strings cls
2437 = isNumericClass cls || (ovl_strings && (cls `hasKey` isStringClassKey))
2438
2439
2440 {-
2441 Note [Avoiding spurious errors]
2442 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2443 When doing the unification for defaulting, we check for skolem
2444 type variables, and simply don't default them. For example:
2445 f = (*) -- Monomorphic
2446 g :: Num a => a -> a
2447 g x = f x x
2448 Here, we get a complaint when checking the type signature for g,
2449 that g isn't polymorphic enough; but then we get another one when
2450 dealing with the (Num a) context arising from f's definition;
2451 we try to unify a with Int (to default it), but find that it's
2452 already been unified with the rigid variable from g's type sig.
2453
2454 Note [Multi-parameter defaults]
2455 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2456 With -XExtendedDefaultRules, we default only based on single-variable
2457 constraints, but do not exclude from defaulting any type variables which also
2458 appear in multi-variable constraints. This means that the following will
2459 default properly:
2460
2461 default (Integer, Double)
2462
2463 class A b (c :: Symbol) where
2464 a :: b -> Proxy c
2465
2466 instance A Integer c where a _ = Proxy
2467
2468 main = print (a 5 :: Proxy "5")
2469
2470 Note that if we change the above instance ("instance A Integer") to
2471 "instance A Double", we get an error:
2472
2473 No instance for (A Integer "5")
2474
2475 This is because the first defaulted type (Integer) has successfully satisfied
2476 its single-parameter constraints (in this case Num).
2477 -}