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