e6c00aea4a5d392631522febb3dd70d49b3fa34d
[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 (cc_ev 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 <- getPendingScDicts
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 pickQuantifieablePreds 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 ; let WC { wc_simple = simples1, wc_impl = implics1 } = wc1
1378
1379 ; (floated_eqs, implics2) <- solveNestedImplications (implics `unionBags` implics1)
1380 ; (no_new_scs, simples2) <- expandSuperClasses simples1
1381
1382 ; traceTcS "solveWanteds middle" $ vcat [ text "simples1 =" <+> ppr simples1
1383 , text "simples2 =" <+> ppr simples2 ]
1384
1385 ; dflags <- getDynFlags
1386 ; final_wc <- simpl_loop 0 (solverIterations dflags) floated_eqs
1387 no_new_scs
1388 (WC { wc_simple = simples2
1389 , wc_impl = implics2 })
1390
1391 ; ev_binds_var <- getTcEvBindsVar
1392 ; bb <- TcS.getTcEvBindsMap ev_binds_var
1393 ; traceTcS "solveWanteds }" $
1394 vcat [ text "final wc =" <+> ppr final_wc
1395 , text "current evbinds =" <+> ppr (evBindMapBinds bb) ]
1396
1397 ; return final_wc }
1398
1399 simpl_loop :: Int -> IntWithInf -> Cts -> Bool
1400 -> WantedConstraints
1401 -> TcS WantedConstraints
1402 simpl_loop n limit floated_eqs no_new_deriveds
1403 wc@(WC { wc_simple = simples, wc_impl = implics })
1404 | isEmptyBag floated_eqs && no_new_deriveds
1405 = return wc -- Done!
1406
1407 | n `intGtLimit` limit
1408 = do { -- Add an error (not a warning) if we blow the limit,
1409 -- Typically if we blow the limit we are going to report some other error
1410 -- (an unsolved constraint), and we don't want that error to suppress
1411 -- the iteration limit warning!
1412 addErrTcS (hang (text "solveWanteds: too many iterations"
1413 <+> parens (text "limit =" <+> ppr limit))
1414 2 (vcat [ text "Unsolved:" <+> ppr wc
1415 , ppUnless (isEmptyBag floated_eqs) $
1416 text "Floated equalities:" <+> ppr floated_eqs
1417 , ppUnless no_new_deriveds $
1418 text "New deriveds found"
1419 , text "Set limit with -fconstraint-solver-iterations=n; n=0 for no limit"
1420 ]))
1421 ; return wc }
1422
1423 | otherwise
1424 = do { let n_floated = lengthBag floated_eqs
1425 ; csTraceTcS $
1426 text "simpl_loop iteration=" <> int n
1427 <+> (parens $ hsep [ text "no new deriveds =" <+> ppr no_new_deriveds <> comma
1428 , int n_floated <+> text "floated eqs" <> comma
1429 , int (lengthBag simples) <+> text "simples to solve" ])
1430
1431 -- solveSimples may make progress if either float_eqs hold
1432 ; (unifs1, wc1) <- reportUnifications $
1433 solveSimpleWanteds $
1434 floated_eqs `unionBags` simples
1435 -- Notes:
1436 -- - Put floated_eqs first so they get solved first
1437 -- NB: the floated_eqs may include /derived/ equalities
1438 -- arising from fundeps inside an implication
1439
1440 ; let WC { wc_simple = simples1, wc_impl = implics1 } = wc1
1441 ; (no_new_scs, simples2) <- expandSuperClasses simples1
1442
1443 -- We have already tried to solve the nested implications once
1444 -- Try again only if we have unified some meta-variables
1445 -- (which is a bit like adding more givens)
1446 -- See Note [Cutting off simpl_loop]
1447 ; (floated_eqs2, implics2) <- if unifs1 == 0 && isEmptyBag implics1
1448 then return (emptyBag, implics)
1449 else solveNestedImplications (implics `unionBags` implics1)
1450
1451 ; simpl_loop (n+1) limit floated_eqs2 no_new_scs
1452 (WC { wc_simple = simples2
1453 , wc_impl = implics2 }) }
1454
1455
1456 expandSuperClasses :: Cts -> TcS (Bool, Cts)
1457 -- If there are any unsolved wanteds, expand one step of
1458 -- superclasses for deriveds
1459 -- Returned Bool is True <=> no new superclass constraints added
1460 -- See Note [The superclass story] in TcCanonical
1461 expandSuperClasses unsolved
1462 | not (anyBag superClassesMightHelp unsolved)
1463 = return (True, unsolved)
1464 | otherwise
1465 = do { traceTcS "expandSuperClasses {" (ppr unsolved)
1466 ; let (pending_wanted, unsolved') = mapAccumBagL get [] unsolved
1467 get acc ct | Just ct' <- isPendingScDict ct
1468 = (ct':acc, ct')
1469 | otherwise
1470 = (acc, ct)
1471 ; pending_given <- getPendingScDicts
1472 ; if null pending_given && null pending_wanted
1473 then do { traceTcS "End expandSuperClasses no-op }" empty
1474 ; return (True, unsolved) }
1475 else
1476 do { traceTcS "expandSuperClasses mid"
1477 (vcat [ text "pending_given:" <+> ppr pending_given
1478 , text "pending_wanted:" <+> ppr pending_wanted ])
1479 ; new_given <- makeSuperClasses pending_given
1480 ; solveSimpleGivens new_given
1481 ; new_wanted <- makeSuperClasses pending_wanted
1482 ; traceTcS "End expandSuperClasses }"
1483 (vcat [ text "Given:" <+> ppr pending_given
1484 , text "Wanted:" <+> ppr new_wanted ])
1485 ; return (False, unsolved' `unionBags` listToBag new_wanted) } }
1486
1487 solveNestedImplications :: Bag Implication
1488 -> TcS (Cts, Bag Implication)
1489 -- Precondition: the TcS inerts may contain unsolved simples which have
1490 -- to be converted to givens before we go inside a nested implication.
1491 solveNestedImplications implics
1492 | isEmptyBag implics
1493 = return (emptyBag, emptyBag)
1494 | otherwise
1495 = do { traceTcS "solveNestedImplications starting {" empty
1496 ; (floated_eqs_s, unsolved_implics) <- mapAndUnzipBagM solveImplication implics
1497 ; let floated_eqs = concatBag floated_eqs_s
1498
1499 -- ... and we are back in the original TcS inerts
1500 -- Notice that the original includes the _insoluble_simples so it was safe to ignore
1501 -- them in the beginning of this function.
1502 ; traceTcS "solveNestedImplications end }" $
1503 vcat [ text "all floated_eqs =" <+> ppr floated_eqs
1504 , text "unsolved_implics =" <+> ppr unsolved_implics ]
1505
1506 ; return (floated_eqs, catBagMaybes unsolved_implics) }
1507
1508 solveImplication :: Implication -- Wanted
1509 -> TcS (Cts, -- All wanted or derived floated equalities: var = type
1510 Maybe Implication) -- Simplified implication (empty or singleton)
1511 -- Precondition: The TcS monad contains an empty worklist and given-only inerts
1512 -- which after trying to solve this implication we must restore to their original value
1513 solveImplication imp@(Implic { ic_tclvl = tclvl
1514 , ic_binds = ev_binds_var
1515 , ic_skols = skols
1516 , ic_given = given_ids
1517 , ic_wanted = wanteds
1518 , ic_info = info
1519 , ic_status = status
1520 , ic_env = env })
1521 | isSolvedStatus status
1522 = return (emptyCts, Just imp) -- Do nothing
1523
1524 | otherwise -- Even for IC_Insoluble it is worth doing more work
1525 -- The insoluble stuff might be in one sub-implication
1526 -- and other unsolved goals in another; and we want to
1527 -- solve the latter as much as possible
1528 = do { inerts <- getTcSInerts
1529 ; traceTcS "solveImplication {" (ppr imp $$ text "Inerts" <+> ppr inerts)
1530
1531 -- Solve the nested constraints
1532 ; (no_given_eqs, given_insols, residual_wanted)
1533 <- nestImplicTcS ev_binds_var tclvl $
1534 do { let loc = mkGivenLoc tclvl info env
1535 givens = mkGivens loc given_ids
1536 ; solveSimpleGivens givens
1537
1538 ; residual_wanted <- solveWanteds wanteds
1539 -- solveWanteds, *not* solveWantedsAndDrop, because
1540 -- we want to retain derived equalities so we can float
1541 -- them out in floatEqualities
1542
1543 ; (no_eqs, given_insols) <- getNoGivenEqs tclvl skols
1544 -- Call getNoGivenEqs /after/ solveWanteds, because
1545 -- solveWanteds can augment the givens, via expandSuperClasses,
1546 -- to reveal given superclass equalities
1547
1548 ; return (no_eqs, given_insols, residual_wanted) }
1549
1550 ; (floated_eqs, residual_wanted)
1551 <- floatEqualities skols given_ids ev_binds_var
1552 no_given_eqs residual_wanted
1553
1554 ; traceTcS "solveImplication 2"
1555 (ppr given_insols $$ ppr residual_wanted)
1556 ; let final_wanted = residual_wanted `addInsols` given_insols
1557 -- Don't lose track of the insoluble givens,
1558 -- which signal unreachable code; put them in ic_wanted
1559
1560 ; res_implic <- setImplicationStatus (imp { ic_no_eqs = no_given_eqs
1561 , ic_wanted = final_wanted })
1562
1563 ; evbinds <- TcS.getTcEvBindsMap ev_binds_var
1564 ; tcvs <- TcS.getTcEvTyCoVars ev_binds_var
1565 ; traceTcS "solveImplication end }" $ vcat
1566 [ text "no_given_eqs =" <+> ppr no_given_eqs
1567 , text "floated_eqs =" <+> ppr floated_eqs
1568 , text "res_implic =" <+> ppr res_implic
1569 , text "implication evbinds =" <+> ppr (evBindMapBinds evbinds)
1570 , text "implication tvcs =" <+> ppr tcvs ]
1571
1572 ; return (floated_eqs, res_implic) }
1573
1574 ----------------------
1575 setImplicationStatus :: Implication -> TcS (Maybe Implication)
1576 -- Finalise the implication returned from solveImplication:
1577 -- * Set the ic_status field
1578 -- * Trim the ic_wanted field to remove Derived constraints
1579 -- Precondition: the ic_status field is not already IC_Solved
1580 -- Return Nothing if we can discard the implication altogether
1581 setImplicationStatus implic@(Implic { ic_status = status
1582 , ic_info = info
1583 , ic_skols = skols
1584 , ic_telescope = m_telescope
1585 , ic_wanted = wc
1586 , ic_given = givens })
1587 | ASSERT2( not (isSolvedStatus status ), ppr info )
1588 -- Precondition: we only set the status if it is not already solved
1589 not (isSolvedWC pruned_wc)
1590 = do { traceTcS "setImplicationStatus(not-all-solved) {" (ppr implic)
1591
1592 ; implic <- neededEvVars implic
1593
1594 ; let new_status | insolubleWC pruned_wc = IC_Insoluble
1595 | otherwise = IC_Unsolved
1596 new_implic = implic { ic_status = new_status
1597 , ic_wanted = pruned_wc }
1598
1599 ; traceTcS "setImplicationStatus(not-all-solved) }" (ppr new_implic)
1600
1601 ; return $ Just new_implic }
1602
1603 | otherwise -- Everything is solved
1604 -- Set status to IC_Solved,
1605 -- and compute the dead givens and outer needs
1606 -- See Note [Tracking redundant constraints]
1607 = do { traceTcS "setImplicationStatus(all-solved) {" (ppr implic)
1608
1609 ; implic <- neededEvVars implic
1610 ; skols <- mapM TcS.zonkTcTyCoVarBndr skols
1611
1612 ; let dead_givens | warnRedundantGivens info
1613 = filterOut (`elemVarSet` ic_need_inner implic) givens
1614 | otherwise = [] -- None to report
1615
1616 bad_telescope = check_telescope skols
1617
1618 discard_entire_implication -- Can we discard the entire implication?
1619 = null dead_givens -- No warning from this implication
1620 && not bad_telescope
1621 && isEmptyBag pruned_implics -- No live children
1622 && isEmptyVarSet (ic_need_outer implic) -- No needed vars to pass up to parent
1623
1624 final_status
1625 | bad_telescope = IC_BadTelescope
1626 | otherwise = IC_Solved { ics_dead = dead_givens }
1627 final_implic = implic { ic_status = final_status
1628 , ic_wanted = pruned_wc }
1629
1630 ; traceTcS "setImplicationStatus(all-solved) }" $
1631 vcat [ text "discard:" <+> ppr discard_entire_implication
1632 , text "new_implic:" <+> ppr final_implic ]
1633
1634 ; return $ if discard_entire_implication
1635 then Nothing
1636 else Just final_implic }
1637 where
1638 WC { wc_simple = simples, wc_impl = implics } = wc
1639
1640 pruned_simples = dropDerivedSimples simples
1641 pruned_implics = filterBag keep_me implics
1642 pruned_wc = WC { wc_simple = pruned_simples
1643 , wc_impl = pruned_implics }
1644
1645 keep_me :: Implication -> Bool
1646 keep_me ic
1647 | IC_Solved { ics_dead = dead_givens } <- ic_status ic
1648 -- Fully solved
1649 , null dead_givens -- No redundant givens to report
1650 , isEmptyBag (wc_impl (ic_wanted ic))
1651 -- And no children that might have things to report
1652 = False -- Tnen we don't need to keep it
1653 | otherwise
1654 = True -- Otherwise, keep it
1655
1656 -- See Note [Keeping scoped variables in order: Explicit] in TcHsType
1657 check_telescope sks = isJust m_telescope && go emptyVarSet (reverse sks)
1658 where
1659 go :: TyVarSet -- skolems that appear *later* than the current ones
1660 -> [TcTyVar] -- ordered skolems, in reverse order
1661 -> Bool -- True <=> there is an out-of-order skolem
1662 go _ [] = False
1663 go later_skols (one_skol : earlier_skols)
1664 | tyCoVarsOfType (tyVarKind one_skol) `intersectsVarSet` later_skols
1665 = True
1666 | otherwise
1667 = go (later_skols `extendVarSet` one_skol) earlier_skols
1668
1669 warnRedundantGivens :: SkolemInfo -> Bool
1670 warnRedundantGivens (SigSkol ctxt _ _)
1671 = case ctxt of
1672 FunSigCtxt _ warn_redundant -> warn_redundant
1673 ExprSigCtxt -> True
1674 _ -> False
1675
1676 -- To think about: do we want to report redundant givens for
1677 -- pattern synonyms, PatSynSigSkol? c.f Trac #9953, comment:21.
1678 warnRedundantGivens (InstSkol {}) = True
1679 warnRedundantGivens _ = False
1680
1681 neededEvVars :: Implication -> TcS Implication
1682 -- Find all the evidence variables that are "needed",
1683 -- and delete dead evidence bindings
1684 -- See Note [Tracking redundant constraints]
1685 -- See Note [Delete dead Given evidence bindings]
1686 --
1687 -- - Start from initial_seeds (from nested implications)
1688 --
1689 -- - Add free vars of RHS of all Wanted evidence bindings
1690 -- and coercion variables accumulated in tcvs (all Wanted)
1691 --
1692 -- - Generate 'needed', the needed set of EvVars, by doing transitive
1693 -- closure through Given bindings
1694 -- e.g. Needed {a,b}
1695 -- Given a = sc_sel a2
1696 -- Then a2 is needed too
1697 --
1698 -- - Prune out all Given bindings that are not needed
1699 --
1700 -- - From the 'needed' set, delete ev_bndrs, the binders of the
1701 -- evidence bindings, to give the final needed variables
1702 --
1703 neededEvVars implic@(Implic { ic_given = givens
1704 , ic_binds = ev_binds_var
1705 , ic_wanted = WC { wc_impl = implics }
1706 , ic_need_inner = old_needs })
1707 = do { ev_binds <- TcS.getTcEvBindsMap ev_binds_var
1708 ; tcvs <- TcS.getTcEvTyCoVars ev_binds_var
1709
1710 ; let seeds1 = foldrBag add_implic_seeds old_needs implics
1711 seeds2 = foldEvBindMap add_wanted seeds1 ev_binds
1712 seeds3 = seeds2 `unionVarSet` tcvs
1713 need_inner = findNeededEvVars ev_binds seeds3
1714 live_ev_binds = filterEvBindMap (needed_ev_bind need_inner) ev_binds
1715 need_outer = foldEvBindMap del_ev_bndr need_inner live_ev_binds
1716 `delVarSetList` givens
1717
1718 ; TcS.setTcEvBindsMap ev_binds_var live_ev_binds
1719 -- See Note [Delete dead Given evidence bindings]
1720
1721 ; traceTcS "neededEvVars" $
1722 vcat [ text "old_needs:" <+> ppr old_needs
1723 , text "seeds3:" <+> ppr seeds3
1724 , text "ev_binds:" <+> ppr ev_binds
1725 , text "live_ev_binds:" <+> ppr live_ev_binds ]
1726
1727 ; return (implic { ic_need_inner = need_inner
1728 , ic_need_outer = need_outer }) }
1729 where
1730 add_implic_seeds (Implic { ic_need_outer = needs, ic_given = givens }) acc
1731 = (needs `delVarSetList` givens) `unionVarSet` acc
1732
1733 needed_ev_bind needed (EvBind { eb_lhs = ev_var
1734 , eb_is_given = is_given })
1735 | is_given = ev_var `elemVarSet` needed
1736 | otherwise = True -- Keep all wanted bindings
1737
1738 del_ev_bndr :: EvBind -> VarSet -> VarSet
1739 del_ev_bndr (EvBind { eb_lhs = v }) needs = delVarSet needs v
1740
1741 add_wanted :: EvBind -> VarSet -> VarSet
1742 add_wanted (EvBind { eb_is_given = is_given, eb_rhs = rhs }) needs
1743 | is_given = needs -- Add the rhs vars of the Wanted bindings only
1744 | otherwise = evVarsOfTerm rhs `unionVarSet` needs
1745
1746
1747 {- Note [Delete dead Given evidence bindings]
1748 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1749 As a result of superclass expansion, we speculatively
1750 generate evidence bindings for Givens. E.g.
1751 f :: (a ~ b) => a -> b -> Bool
1752 f x y = ...
1753 We'll have
1754 [G] d1 :: (a~b)
1755 and we'll specuatively generate the evidence binding
1756 [G] d2 :: (a ~# b) = sc_sel d
1757
1758 Now d2 is available for solving. But it may not be needed! Usually
1759 such dead superclass selections will eventually be dropped as dead
1760 code, but:
1761
1762 * It won't always be dropped (Trac #13032). In the case of an
1763 unlifted-equality superclass like d2 above, we generate
1764 case heq_sc d1 of d2 -> ...
1765 and we can't (in general) drop that case exrpession in case
1766 d1 is bottom. So it's technically unsound to have added it
1767 in the first place.
1768
1769 * Simply generating all those extra superclasses can generate lots of
1770 code that has to be zonked, only to be discarded later. Better not
1771 to generate it in the first place.
1772
1773 Moreover, if we simplify this implication more than once
1774 (e.g. because we can't solve it completely on the first iteration
1775 of simpl_looop), we'll generate all the same bindings AGAIN!
1776
1777 Easy solution: take advantage of the work we are doing to track dead
1778 (unused) Givens, and use it to prune the Given bindings too. This is
1779 all done by neededEvVars.
1780
1781 This led to a remarkable 25% overall compiler allocation decrease in
1782 test T12227.
1783
1784 Note [Tracking redundant constraints]
1785 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1786 With Opt_WarnRedundantConstraints, GHC can report which
1787 constraints of a type signature (or instance declaration) are
1788 redundant, and can be omitted. Here is an overview of how it
1789 works:
1790
1791 ----- What is a redundant constraint?
1792
1793 * The things that can be redundant are precisely the Given
1794 constraints of an implication.
1795
1796 * A constraint can be redundant in two different ways:
1797 a) It is implied by other givens. E.g.
1798 f :: (Eq a, Ord a) => blah -- Eq a unnecessary
1799 g :: (Eq a, a~b, Eq b) => blah -- Either Eq a or Eq b unnecessary
1800 b) It is not needed by the Wanted constraints covered by the
1801 implication E.g.
1802 f :: Eq a => a -> Bool
1803 f x = True -- Equality not used
1804
1805 * To find (a), when we have two Given constraints,
1806 we must be careful to drop the one that is a naked variable (if poss).
1807 So if we have
1808 f :: (Eq a, Ord a) => blah
1809 then we may find [G] sc_sel (d1::Ord a) :: Eq a
1810 [G] d2 :: Eq a
1811 We want to discard d2 in favour of the superclass selection from
1812 the Ord dictionary. This is done by TcInteract.solveOneFromTheOther
1813 See Note [Replacement vs keeping].
1814
1815 * To find (b) we need to know which evidence bindings are 'wanted';
1816 hence the eb_is_given field on an EvBind.
1817
1818 ----- How tracking works
1819
1820 * The ic_need fields of an Implic records in-scope (given) evidence
1821 variables bound by the context, that were needed to solve this
1822 implication (so far). See the declaration of Implication.
1823
1824 * When the constraint solver finishes solving all the wanteds in
1825 an implication, it sets its status to IC_Solved
1826
1827 - The ics_dead field, of IC_Solved, records the subset of this
1828 implication's ic_given that are redundant (not needed).
1829
1830 * We compute which evidence variables are needed by an implication
1831 in setImplicationStatus. A variable is needed if
1832 a) it is free in the RHS of a Wanted EvBind,
1833 b) it is free in the RHS of an EvBind whose LHS is needed,
1834 c) it is in the ics_need of a nested implication.
1835
1836 * We need to be careful not to discard an implication
1837 prematurely, even one that is fully solved, because we might
1838 thereby forget which variables it needs, and hence wrongly
1839 report a constraint as redundant. But we can discard it once
1840 its free vars have been incorporated into its parent; or if it
1841 simply has no free vars. This careful discarding is also
1842 handled in setImplicationStatus.
1843
1844 ----- Reporting redundant constraints
1845
1846 * TcErrors does the actual warning, in warnRedundantConstraints.
1847
1848 * We don't report redundant givens for *every* implication; only
1849 for those which reply True to TcSimplify.warnRedundantGivens:
1850
1851 - For example, in a class declaration, the default method *can*
1852 use the class constraint, but it certainly doesn't *have* to,
1853 and we don't want to report an error there.
1854
1855 - More subtly, in a function definition
1856 f :: (Ord a, Ord a, Ix a) => a -> a
1857 f x = rhs
1858 we do an ambiguity check on the type (which would find that one
1859 of the Ord a constraints was redundant), and then we check that
1860 the definition has that type (which might find that both are
1861 redundant). We don't want to report the same error twice, so we
1862 disable it for the ambiguity check. Hence using two different
1863 FunSigCtxts, one with the warn-redundant field set True, and the
1864 other set False in
1865 - TcBinds.tcSpecPrag
1866 - TcBinds.tcTySig
1867
1868 This decision is taken in setImplicationStatus, rather than TcErrors
1869 so that we can discard implication constraints that we don't need.
1870 So ics_dead consists only of the *reportable* redundant givens.
1871
1872 ----- Shortcomings
1873
1874 Consider (see Trac #9939)
1875 f2 :: (Eq a, Ord a) => a -> a -> Bool
1876 -- Ord a redundant, but Eq a is reported
1877 f2 x y = (x == y)
1878
1879 We report (Eq a) as redundant, whereas actually (Ord a) is. But it's
1880 really not easy to detect that!
1881
1882
1883 Note [Cutting off simpl_loop]
1884 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1885 It is very important not to iterate in simpl_loop unless there is a chance
1886 of progress. Trac #8474 is a classic example:
1887
1888 * There's a deeply-nested chain of implication constraints.
1889 ?x:alpha => ?y1:beta1 => ... ?yn:betan => [W] ?x:Int
1890
1891 * From the innermost one we get a [D] alpha ~ Int,
1892 but alpha is untouchable until we get out to the outermost one
1893
1894 * We float [D] alpha~Int out (it is in floated_eqs), but since alpha
1895 is untouchable, the solveInteract in simpl_loop makes no progress
1896
1897 * So there is no point in attempting to re-solve
1898 ?yn:betan => [W] ?x:Int
1899 via solveNestedImplications, because we'll just get the
1900 same [D] again
1901
1902 * If we *do* re-solve, we'll get an ininite loop. It is cut off by
1903 the fixed bound of 10, but solving the next takes 10*10*...*10 (ie
1904 exponentially many) iterations!
1905
1906 Conclusion: we should call solveNestedImplications only if we did
1907 some unification in solveSimpleWanteds; because that's the only way
1908 we'll get more Givens (a unification is like adding a Given) to
1909 allow the implication to make progress.
1910 -}
1911
1912 promoteTyVar :: TcTyVar -> TcM Bool
1913 -- When we float a constraint out of an implication we must restore
1914 -- invariant (WantedInv) in Note [TcLevel and untouchable type variables] in TcType
1915 -- Return True <=> we did some promotion
1916 -- See Note [Promoting unification variables]
1917 promoteTyVar tv
1918 = do { tclvl <- TcM.getTcLevel
1919 ; if (isFloatedTouchableMetaTyVar tclvl tv)
1920 then do { cloned_tv <- TcM.cloneMetaTyVar tv
1921 ; let rhs_tv = setMetaTyVarTcLevel cloned_tv tclvl
1922 ; TcM.writeMetaTyVar tv (mkTyVarTy rhs_tv)
1923 ; return True }
1924 else return False }
1925
1926 -- Returns whether or not *any* tyvar is defaulted
1927 promoteTyVarSet :: TcTyVarSet -> TcM Bool
1928 promoteTyVarSet tvs
1929 = or <$> mapM promoteTyVar (nonDetEltsUniqSet tvs)
1930 -- non-determinism is OK because order of promotion doesn't matter
1931
1932 promoteTyVarTcS :: TcTyVar -> TcS ()
1933 -- When we float a constraint out of an implication we must restore
1934 -- invariant (WantedInv) in Note [TcLevel and untouchable type variables] in TcType
1935 -- See Note [Promoting unification variables]
1936 -- We don't just call promoteTyVar because we want to use unifyTyVar,
1937 -- not writeMetaTyVar
1938 promoteTyVarTcS tv
1939 = do { tclvl <- TcS.getTcLevel
1940 ; when (isFloatedTouchableMetaTyVar tclvl tv) $
1941 do { cloned_tv <- TcS.cloneMetaTyVar tv
1942 ; let rhs_tv = setMetaTyVarTcLevel cloned_tv tclvl
1943 ; unifyTyVar tv (mkTyVarTy rhs_tv) } }
1944
1945 -- | Like 'defaultTyVar', but in the TcS monad.
1946 defaultTyVarTcS :: TcTyVar -> TcS Bool
1947 defaultTyVarTcS the_tv
1948 | isRuntimeRepVar the_tv
1949 , not (isSigTyVar the_tv) -- SigTvs should only be unified with a tyvar
1950 -- never with a type; c.f. TcMType.defaultTyVar
1951 -- See Note [Kind generalisation and SigTvs]
1952 = do { traceTcS "defaultTyVarTcS RuntimeRep" (ppr the_tv)
1953 ; unifyTyVar the_tv liftedRepTy
1954 ; return True }
1955 | otherwise
1956 = return False -- the common case
1957
1958 approximateWC :: Bool -> WantedConstraints -> Cts
1959 -- Postcondition: Wanted or Derived Cts
1960 -- See Note [ApproximateWC]
1961 approximateWC float_past_equalities wc
1962 = float_wc emptyVarSet wc
1963 where
1964 float_wc :: TcTyCoVarSet -> WantedConstraints -> Cts
1965 float_wc trapping_tvs (WC { wc_simple = simples, wc_impl = implics })
1966 = filterBag (is_floatable trapping_tvs) simples `unionBags`
1967 do_bag (float_implic trapping_tvs) implics
1968 where
1969
1970 float_implic :: TcTyCoVarSet -> Implication -> Cts
1971 float_implic trapping_tvs imp
1972 | float_past_equalities || ic_no_eqs imp
1973 = float_wc new_trapping_tvs (ic_wanted imp)
1974 | otherwise -- Take care with equalities
1975 = emptyCts -- See (1) under Note [ApproximateWC]
1976 where
1977 new_trapping_tvs = trapping_tvs `extendVarSetList` ic_skols imp
1978
1979 do_bag :: (a -> Bag c) -> Bag a -> Bag c
1980 do_bag f = foldrBag (unionBags.f) emptyBag
1981
1982 is_floatable skol_tvs ct
1983 | isGivenCt ct = False
1984 | isHoleCt ct = False
1985 | insolubleEqCt ct = False
1986 | otherwise = tyCoVarsOfCt ct `disjointVarSet` skol_tvs
1987
1988 {- Note [ApproximateWC]
1989 ~~~~~~~~~~~~~~~~~~~~~~~
1990 approximateWC takes a constraint, typically arising from the RHS of a
1991 let-binding whose type we are *inferring*, and extracts from it some
1992 *simple* constraints that we might plausibly abstract over. Of course
1993 the top-level simple constraints are plausible, but we also float constraints
1994 out from inside, if they are not captured by skolems.
1995
1996 The same function is used when doing type-class defaulting (see the call
1997 to applyDefaultingRules) to extract constraints that that might be defaulted.
1998
1999 There is one caveat:
2000
2001 1. When infering most-general types (in simplifyInfer), we do *not*
2002 float anything out if the implication binds equality constraints,
2003 because that defeats the OutsideIn story. Consider
2004 data T a where
2005 TInt :: T Int
2006 MkT :: T a
2007
2008 f TInt = 3::Int
2009
2010 We get the implication (a ~ Int => res ~ Int), where so far we've decided
2011 f :: T a -> res
2012 We don't want to float (res~Int) out because then we'll infer
2013 f :: T a -> Int
2014 which is only on of the possible types. (GHC 7.6 accidentally *did*
2015 float out of such implications, which meant it would happily infer
2016 non-principal types.)
2017
2018 HOWEVER (Trac #12797) in findDefaultableGroups we are not worried about
2019 the most-general type; and we /do/ want to float out of equalities.
2020 Hence the boolean flag to approximateWC.
2021
2022 ------ Historical note -----------
2023 There used to be a second caveat, driven by Trac #8155
2024
2025 2. We do not float out an inner constraint that shares a type variable
2026 (transitively) with one that is trapped by a skolem. Eg
2027 forall a. F a ~ beta, Integral beta
2028 We don't want to float out (Integral beta). Doing so would be bad
2029 when defaulting, because then we'll default beta:=Integer, and that
2030 makes the error message much worse; we'd get
2031 Can't solve F a ~ Integer
2032 rather than
2033 Can't solve Integral (F a)
2034
2035 Moreover, floating out these "contaminated" constraints doesn't help
2036 when generalising either. If we generalise over (Integral b), we still
2037 can't solve the retained implication (forall a. F a ~ b). Indeed,
2038 arguably that too would be a harder error to understand.
2039
2040 But this transitive closure stuff gives rise to a complex rule for
2041 when defaulting actually happens, and one that was never documented.
2042 Moreover (Trac #12923), the more complex rule is sometimes NOT what
2043 you want. So I simply removed the extra code to implement the
2044 contamination stuff. There was zero effect on the testsuite (not even
2045 #8155).
2046 ------ End of historical note -----------
2047
2048
2049 Note [DefaultTyVar]
2050 ~~~~~~~~~~~~~~~~~~~
2051 defaultTyVar is used on any un-instantiated meta type variables to
2052 default any RuntimeRep variables to LiftedRep. This is important
2053 to ensure that instance declarations match. For example consider
2054
2055 instance Show (a->b)
2056 foo x = show (\_ -> True)
2057
2058 Then we'll get a constraint (Show (p ->q)) where p has kind (TYPE r),
2059 and that won't match the typeKind (*) in the instance decl. See tests
2060 tc217 and tc175.
2061
2062 We look only at touchable type variables. No further constraints
2063 are going to affect these type variables, so it's time to do it by
2064 hand. However we aren't ready to default them fully to () or
2065 whatever, because the type-class defaulting rules have yet to run.
2066
2067 An alternate implementation would be to emit a derived constraint setting
2068 the RuntimeRep variable to LiftedRep, but this seems unnecessarily indirect.
2069
2070 Note [Promote _and_ default when inferring]
2071 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2072 When we are inferring a type, we simplify the constraint, and then use
2073 approximateWC to produce a list of candidate constraints. Then we MUST
2074
2075 a) Promote any meta-tyvars that have been floated out by
2076 approximateWC, to restore invariant (WantedInv) described in
2077 Note [TcLevel and untouchable type variables] in TcType.
2078
2079 b) Default the kind of any meta-tyvars that are not mentioned in
2080 in the environment.
2081
2082 To see (b), suppose the constraint is (C ((a :: OpenKind) -> Int)), and we
2083 have an instance (C ((x:*) -> Int)). The instance doesn't match -- but it
2084 should! If we don't solve the constraint, we'll stupidly quantify over
2085 (C (a->Int)) and, worse, in doing so zonkQuantifiedTyVar will quantify over
2086 (b:*) instead of (a:OpenKind), which can lead to disaster; see Trac #7332.
2087 Trac #7641 is a simpler example.
2088
2089 Note [Promoting unification variables]
2090 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2091 When we float an equality out of an implication we must "promote" free
2092 unification variables of the equality, in order to maintain Invariant
2093 (WantedInv) from Note [TcLevel and untouchable type variables] in
2094 TcType. for the leftover implication.
2095
2096 This is absolutely necessary. Consider the following example. We start
2097 with two implications and a class with a functional dependency.
2098
2099 class C x y | x -> y
2100 instance C [a] [a]
2101
2102 (I1) [untch=beta]forall b. 0 => F Int ~ [beta]
2103 (I2) [untch=beta]forall c. 0 => F Int ~ [[alpha]] /\ C beta [c]
2104
2105 We float (F Int ~ [beta]) out of I1, and we float (F Int ~ [[alpha]]) out of I2.
2106 They may react to yield that (beta := [alpha]) which can then be pushed inwards
2107 the leftover of I2 to get (C [alpha] [a]) which, using the FunDep, will mean that
2108 (alpha := a). In the end we will have the skolem 'b' escaping in the untouchable
2109 beta! Concrete example is in indexed_types/should_fail/ExtraTcsUntch.hs:
2110
2111 class C x y | x -> y where
2112 op :: x -> y -> ()
2113
2114 instance C [a] [a]
2115
2116 type family F a :: *
2117
2118 h :: F Int -> ()
2119 h = undefined
2120
2121 data TEx where
2122 TEx :: a -> TEx
2123
2124 f (x::beta) =
2125 let g1 :: forall b. b -> ()
2126 g1 _ = h [x]
2127 g2 z = case z of TEx y -> (h [[undefined]], op x [y])
2128 in (g1 '3', g2 undefined)
2129
2130
2131
2132 *********************************************************************************
2133 * *
2134 * Floating equalities *
2135 * *
2136 *********************************************************************************
2137
2138 Note [Float Equalities out of Implications]
2139 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2140 For ordinary pattern matches (including existentials) we float
2141 equalities out of implications, for instance:
2142 data T where
2143 MkT :: Eq a => a -> T
2144 f x y = case x of MkT _ -> (y::Int)
2145 We get the implication constraint (x::T) (y::alpha):
2146 forall a. [untouchable=alpha] Eq a => alpha ~ Int
2147 We want to float out the equality into a scope where alpha is no
2148 longer untouchable, to solve the implication!
2149
2150 But we cannot float equalities out of implications whose givens may
2151 yield or contain equalities:
2152
2153 data T a where
2154 T1 :: T Int
2155 T2 :: T Bool
2156 T3 :: T a
2157
2158 h :: T a -> a -> Int
2159
2160 f x y = case x of
2161 T1 -> y::Int
2162 T2 -> y::Bool
2163 T3 -> h x y
2164
2165 We generate constraint, for (x::T alpha) and (y :: beta):
2166 [untouchables = beta] (alpha ~ Int => beta ~ Int) -- From 1st branch
2167 [untouchables = beta] (alpha ~ Bool => beta ~ Bool) -- From 2nd branch
2168 (alpha ~ beta) -- From 3rd branch
2169
2170 If we float the equality (beta ~ Int) outside of the first implication and
2171 the equality (beta ~ Bool) out of the second we get an insoluble constraint.
2172 But if we just leave them inside the implications, we unify alpha := beta and
2173 solve everything.
2174
2175 Principle:
2176 We do not want to float equalities out which may
2177 need the given *evidence* to become soluble.
2178
2179 Consequence: classes with functional dependencies don't matter (since there is
2180 no evidence for a fundep equality), but equality superclasses do matter (since
2181 they carry evidence).
2182 -}
2183
2184 floatEqualities :: [TcTyVar] -> [EvId] -> EvBindsVar -> Bool
2185 -> WantedConstraints
2186 -> TcS (Cts, WantedConstraints)
2187 -- Main idea: see Note [Float Equalities out of Implications]
2188 --
2189 -- Precondition: the wc_simple of the incoming WantedConstraints are
2190 -- fully zonked, so that we can see their free variables
2191 --
2192 -- Postcondition: The returned floated constraints (Cts) are only
2193 -- Wanted or Derived
2194 --
2195 -- Also performs some unifications (via promoteTyVar), adding to
2196 -- monadically-carried ty_binds. These will be used when processing
2197 -- floated_eqs later
2198 --
2199 -- Subtleties: Note [Float equalities from under a skolem binding]
2200 -- Note [Skolem escape]
2201 -- Note [What prevents a constraint from floating]
2202 floatEqualities skols given_ids ev_binds_var no_given_eqs
2203 wanteds@(WC { wc_simple = simples })
2204 | not no_given_eqs -- There are some given equalities, so don't float
2205 = return (emptyBag, wanteds) -- Note [Float Equalities out of Implications]
2206
2207 | otherwise
2208 = do { -- First zonk: the inert set (from whence they came) is fully
2209 -- zonked, but unflattening may have filled in unification
2210 -- variables, and we /must/ see them. Otherwise we may float
2211 -- constraints that mention the skolems!
2212 simples <- TcS.zonkSimples simples
2213 ; binds <- TcS.getTcEvBindsMap ev_binds_var
2214
2215 -- Now we can pick the ones to float
2216 -- The constraints are un-flattened and de-canonicalised
2217 ; let seed_skols = mkVarSet skols `unionVarSet`
2218 mkVarSet given_ids `unionVarSet`
2219 foldEvBindMap add_one emptyVarSet binds
2220 add_one bind acc = extendVarSet acc (evBindVar bind)
2221 -- seed_skols: See Note [What prevents a constraint from floating] (1,2,3)
2222
2223 (eqs, non_eqs) = partitionBag is_eq_ct simples
2224 extended_skols = transCloVarSet (extra_skols eqs) seed_skols
2225 (flt_eqs, no_flt_eqs) = partitionBag (is_floatable extended_skols) eqs
2226 remaining_simples = non_eqs `andCts` no_flt_eqs
2227 -- extended_skols: See Note [What prevents a constraint from floating] (3)
2228
2229 -- Promote any unification variables mentioned in the floated equalities
2230 -- See Note [Promoting unification variables]
2231 ; mapM_ promoteTyVarTcS (tyCoVarsOfCtsList flt_eqs)
2232
2233 ; traceTcS "floatEqualities" (vcat [ text "Skols =" <+> ppr skols
2234 , text "Extended skols =" <+> ppr extended_skols
2235 , text "Simples =" <+> ppr simples
2236 , text "Eqs =" <+> ppr eqs
2237 , text "Floated eqs =" <+> ppr flt_eqs])
2238 ; return ( flt_eqs, wanteds { wc_simple = remaining_simples } ) }
2239
2240 where
2241 is_floatable :: VarSet -> Ct -> Bool
2242 is_floatable skols ct
2243 | isDerivedCt ct = not (tyCoVarsOfCt ct `intersectsVarSet` skols)
2244 | otherwise = not (ctEvId ct `elemVarSet` skols)
2245
2246 is_eq_ct ct | CTyEqCan {} <- ct = True
2247 | is_homo_eq (ctPred ct) = True
2248 | otherwise = False
2249
2250 extra_skols :: Cts -> VarSet -> VarSet
2251 extra_skols eqs skols = foldrBag extra_skol emptyVarSet eqs
2252 where
2253 extra_skol ct acc
2254 | isDerivedCt ct = acc
2255 | tyCoVarsOfCt ct `intersectsVarSet` skols = extendVarSet acc (ctEvId ct)
2256 | otherwise = acc
2257
2258 -- Float out alpha ~ ty, or ty ~ alpha
2259 -- which might be unified outside
2260 -- See Note [Which equalities to float]
2261 is_homo_eq pred
2262 | EqPred NomEq ty1 ty2 <- classifyPredType pred
2263 , typeKind ty1 `tcEqType` typeKind ty2
2264 = case (tcGetTyVar_maybe ty1, tcGetTyVar_maybe ty2) of
2265 (Just tv1, _) -> float_tv_eq tv1 ty2
2266 (_, Just tv2) -> float_tv_eq tv2 ty1
2267 _ -> False
2268 | otherwise
2269 = False
2270
2271 float_tv_eq tv1 ty2 -- See Note [Which equalities to float]
2272 = isMetaTyVar tv1
2273 && (not (isSigTyVar tv1) || isTyVarTy ty2)
2274
2275
2276 {- Note [Float equalities from under a skolem binding]
2277 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2278 Which of the simple equalities can we float out? Obviously, only
2279 ones that don't mention the skolem-bound variables. But that is
2280 over-eager. Consider
2281 [2] forall a. F a beta[1] ~ gamma[2], G beta[1] gamma[2] ~ Int
2282 The second constraint doesn't mention 'a'. But if we float it,
2283 we'll promote gamma[2] to gamma'[1]. Now suppose that we learn that
2284 beta := Bool, and F a Bool = a, and G Bool _ = Int. Then we'll
2285 we left with the constraint
2286 [2] forall a. a ~ gamma'[1]
2287 which is insoluble because gamma became untouchable.
2288
2289 Solution: float only constraints that stand a jolly good chance of
2290 being soluble simply by being floated, namely ones of form
2291 a ~ ty
2292 where 'a' is a currently-untouchable unification variable, but may
2293 become touchable by being floated (perhaps by more than one level).
2294
2295 We had a very complicated rule previously, but this is nice and
2296 simple. (To see the notes, look at this Note in a version of
2297 TcSimplify prior to Oct 2014).
2298
2299 Note [Which equalities to float]
2300 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2301 Which equalities should we float? We want to float ones where there
2302 is a decent chance that floating outwards will allow unification to
2303 happen. In particular:
2304
2305 Float out homogeneous equalities of form (alpha ~ ty) or (ty ~ alpha), where
2306
2307 * alpha is a meta-tyvar.
2308
2309 * And 'alpha' is not a SigTv with 'ty' being a non-tyvar. In that
2310 case, floating out won't help either, and it may affect grouping
2311 of error messages.
2312
2313 Why homogeneous (i.e., the kinds of the types are the same)? Because heterogeneous
2314 equalities have derived kind equalities. See Note [Equalities with incompatible kinds]
2315 in TcCanonical. If we float out a hetero equality, then it will spit out the
2316 same derived kind equality again, which might create duplicate error messages.
2317 Instead, we do float out the kind equality (if it's worth floating out, as
2318 above). If/when we solve it, we'll be able to rewrite the original hetero equality
2319 to be homogeneous, and then perhaps make progress / float it out. The duplicate
2320 error message was spotted in typecheck/should_fail/T7368.
2321
2322 Note [Skolem escape]
2323 ~~~~~~~~~~~~~~~~~~~~
2324 You might worry about skolem escape with all this floating.
2325 For example, consider
2326 [2] forall a. (a ~ F beta[2] delta,
2327 Maybe beta[2] ~ gamma[1])
2328
2329 The (Maybe beta ~ gamma) doesn't mention 'a', so we float it, and
2330 solve with gamma := beta. But what if later delta:=Int, and
2331 F b Int = b.
2332 Then we'd get a ~ beta[2], and solve to get beta:=a, and now the
2333 skolem has escaped!
2334
2335 But it's ok: when we float (Maybe beta[2] ~ gamma[1]), we promote beta[2]
2336 to beta[1], and that means the (a ~ beta[1]) will be stuck, as it should be.
2337
2338 Note [What prevents a constraint from floating]
2339 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2340 What /prevents/ a constraint from floating? If it mentions one of the
2341 "bound variables of the implication". What are they?
2342
2343 The "bound variables of the implication" are
2344
2345 1. The skolem type variables `ic_skols`
2346
2347 2. The "given" evidence variables `ic_given`. Example:
2348 forall a. (co :: t1 ~# t2) => [W] co : (a ~# b |> co)
2349
2350 3. The binders of all evidence bindings in `ic_binds`. Example
2351 forall a. (d :: t1 ~ t2)
2352 EvBinds { (co :: t1 ~# t2) = superclass-sel d }
2353 => [W] co2 : (a ~# b |> co)
2354 Here `co` is gotten by superclass selection from `d`, and the
2355 wanted constraint co2 must not float.
2356
2357 4. And the evidence variable of any equality constraint (incl
2358 Wanted ones) whose type mentions a bound variable. Example:
2359 forall k. [W] co1 :: t1 ~# t2 |> co2
2360 [W] co2 :: k ~# *
2361 Here, since `k` is bound, so is `co2` and hence so is `co1`.
2362
2363 Here (1,2,3) are handled by the "seed_skols" calculation, and
2364 (4) is done by the transCloVarSet call.
2365
2366 The possible dependence on givens, and evidence bindings, is more
2367 subtle than we'd realised at first. See Trac #14584.
2368
2369
2370 *********************************************************************************
2371 * *
2372 * Defaulting and disambiguation *
2373 * *
2374 *********************************************************************************
2375 -}
2376
2377 applyDefaultingRules :: WantedConstraints -> TcS Bool
2378 -- True <=> I did some defaulting, by unifying a meta-tyvar
2379 -- Input WantedConstraints are not necessarily zonked
2380
2381 applyDefaultingRules wanteds
2382 | isEmptyWC wanteds
2383 = return False
2384 | otherwise
2385 = do { info@(default_tys, _) <- getDefaultInfo
2386 ; wanteds <- TcS.zonkWC wanteds
2387
2388 ; let groups = findDefaultableGroups info wanteds
2389
2390 ; traceTcS "applyDefaultingRules {" $
2391 vcat [ text "wanteds =" <+> ppr wanteds
2392 , text "groups =" <+> ppr groups
2393 , text "info =" <+> ppr info ]
2394
2395 ; something_happeneds <- mapM (disambigGroup default_tys) groups
2396
2397 ; traceTcS "applyDefaultingRules }" (ppr something_happeneds)
2398
2399 ; return (or something_happeneds) }
2400
2401 findDefaultableGroups
2402 :: ( [Type]
2403 , (Bool,Bool) ) -- (Overloaded strings, extended default rules)
2404 -> WantedConstraints -- Unsolved (wanted or derived)
2405 -> [(TyVar, [Ct])]
2406 findDefaultableGroups (default_tys, (ovl_strings, extended_defaults)) wanteds
2407 | null default_tys
2408 = []
2409 | otherwise
2410 = [ (tv, map fstOf3 group)
2411 | group'@((_,_,tv) :| _) <- unary_groups
2412 , let group = toList group'
2413 , defaultable_tyvar tv
2414 , defaultable_classes (map sndOf3 group) ]
2415 where
2416 simples = approximateWC True wanteds
2417 (unaries, non_unaries) = partitionWith find_unary (bagToList simples)
2418 unary_groups = equivClasses cmp_tv unaries
2419
2420 unary_groups :: [NonEmpty (Ct, Class, TcTyVar)] -- (C tv) constraints
2421 unaries :: [(Ct, Class, TcTyVar)] -- (C tv) constraints
2422 non_unaries :: [Ct] -- and *other* constraints
2423
2424 -- Finds unary type-class constraints
2425 -- But take account of polykinded classes like Typeable,
2426 -- which may look like (Typeable * (a:*)) (Trac #8931)
2427 find_unary :: Ct -> Either (Ct, Class, TyVar) Ct
2428 find_unary cc
2429 | Just (cls,tys) <- getClassPredTys_maybe (ctPred cc)
2430 , [ty] <- filterOutInvisibleTypes (classTyCon cls) tys
2431 -- Ignore invisible arguments for this purpose
2432 , Just tv <- tcGetTyVar_maybe ty
2433 , isMetaTyVar tv -- We might have runtime-skolems in GHCi, and
2434 -- we definitely don't want to try to assign to those!
2435 = Left (cc, cls, tv)
2436 find_unary cc = Right cc -- Non unary or non dictionary
2437
2438 bad_tvs :: TcTyCoVarSet -- TyVars mentioned by non-unaries
2439 bad_tvs = mapUnionVarSet tyCoVarsOfCt non_unaries
2440
2441 cmp_tv (_,_,tv1) (_,_,tv2) = tv1 `compare` tv2
2442
2443 defaultable_tyvar :: TcTyVar -> Bool
2444 defaultable_tyvar tv
2445 = let b1 = isTyConableTyVar tv -- Note [Avoiding spurious errors]
2446 b2 = not (tv `elemVarSet` bad_tvs)
2447 in b1 && (b2 || extended_defaults) -- Note [Multi-parameter defaults]
2448
2449 defaultable_classes :: [Class] -> Bool
2450 defaultable_classes clss
2451 | extended_defaults = any (isInteractiveClass ovl_strings) clss
2452 | otherwise = all is_std_class clss && (any (isNumClass ovl_strings) clss)
2453
2454 -- is_std_class adds IsString to the standard numeric classes,
2455 -- when -foverloaded-strings is enabled
2456 is_std_class cls = isStandardClass cls ||
2457 (ovl_strings && (cls `hasKey` isStringClassKey))
2458
2459 ------------------------------
2460 disambigGroup :: [Type] -- The default types
2461 -> (TcTyVar, [Ct]) -- All classes of the form (C a)
2462 -- sharing same type variable
2463 -> TcS Bool -- True <=> something happened, reflected in ty_binds
2464
2465 disambigGroup [] _
2466 = return False
2467 disambigGroup (default_ty:default_tys) group@(the_tv, wanteds)
2468 = do { traceTcS "disambigGroup {" (vcat [ ppr default_ty, ppr the_tv, ppr wanteds ])
2469 ; fake_ev_binds_var <- TcS.newTcEvBinds
2470 ; tclvl <- TcS.getTcLevel
2471 ; success <- nestImplicTcS fake_ev_binds_var (pushTcLevel tclvl) try_group
2472
2473 ; if success then
2474 -- Success: record the type variable binding, and return
2475 do { unifyTyVar the_tv default_ty
2476 ; wrapWarnTcS $ warnDefaulting wanteds default_ty
2477 ; traceTcS "disambigGroup succeeded }" (ppr default_ty)
2478 ; return True }
2479 else
2480 -- Failure: try with the next type
2481 do { traceTcS "disambigGroup failed, will try other default types }"
2482 (ppr default_ty)
2483 ; disambigGroup default_tys group } }
2484 where
2485 try_group
2486 | Just subst <- mb_subst
2487 = do { lcl_env <- TcS.getLclEnv
2488 ; tc_lvl <- TcS.getTcLevel
2489 ; let loc = mkGivenLoc tc_lvl UnkSkol lcl_env
2490 ; wanted_evs <- mapM (newWantedEvVarNC loc . substTy subst . ctPred)
2491 wanteds
2492 ; fmap isEmptyWC $
2493 solveSimpleWanteds $ listToBag $
2494 map mkNonCanonical wanted_evs }
2495
2496 | otherwise
2497 = return False
2498
2499 the_ty = mkTyVarTy the_tv
2500 mb_subst = tcMatchTyKi the_ty default_ty
2501 -- Make sure the kinds match too; hence this call to tcMatchTyKi
2502 -- E.g. suppose the only constraint was (Typeable k (a::k))
2503 -- With the addition of polykinded defaulting we also want to reject
2504 -- ill-kinded defaulting attempts like (Eq []) or (Foldable Int) here.
2505
2506 -- In interactive mode, or with -XExtendedDefaultRules,
2507 -- we default Show a to Show () to avoid graututious errors on "show []"
2508 isInteractiveClass :: Bool -- -XOverloadedStrings?
2509 -> Class -> Bool
2510 isInteractiveClass ovl_strings cls
2511 = isNumClass ovl_strings cls || (classKey cls `elem` interactiveClassKeys)
2512
2513 -- isNumClass adds IsString to the standard numeric classes,
2514 -- when -foverloaded-strings is enabled
2515 isNumClass :: Bool -- -XOverloadedStrings?
2516 -> Class -> Bool
2517 isNumClass ovl_strings cls
2518 = isNumericClass cls || (ovl_strings && (cls `hasKey` isStringClassKey))
2519
2520
2521 {-
2522 Note [Avoiding spurious errors]
2523 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2524 When doing the unification for defaulting, we check for skolem
2525 type variables, and simply don't default them. For example:
2526 f = (*) -- Monomorphic
2527 g :: Num a => a -> a
2528 g x = f x x
2529 Here, we get a complaint when checking the type signature for g,
2530 that g isn't polymorphic enough; but then we get another one when
2531 dealing with the (Num a) context arising from f's definition;
2532 we try to unify a with Int (to default it), but find that it's
2533 already been unified with the rigid variable from g's type sig.
2534
2535 Note [Multi-parameter defaults]
2536 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2537 With -XExtendedDefaultRules, we default only based on single-variable
2538 constraints, but do not exclude from defaulting any type variables which also
2539 appear in multi-variable constraints. This means that the following will
2540 default properly:
2541
2542 default (Integer, Double)
2543
2544 class A b (c :: Symbol) where
2545 a :: b -> Proxy c
2546
2547 instance A Integer c where a _ = Proxy
2548
2549 main = print (a 5 :: Proxy "5")
2550
2551 Note that if we change the above instance ("instance A Integer") to
2552 "instance A Double", we get an error:
2553
2554 No instance for (A Integer "5")
2555
2556 This is because the first defaulted type (Integer) has successfully satisfied
2557 its single-parameter constraints (in this case Num).
2558 -}