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