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