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