Remove dead quantifyTyVars
[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 ; solveWanteds wanteds }
619 ; wanted_transformed_incl_derivs <- TcM.zonkWC wanted_transformed_incl_derivs
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 = filterDVarSet (`elemVarSet` 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
1205 ; let WC { wc_simple = simples1, wc_insol = insols1, wc_impl = implics1 } = wc1
1206
1207 ; (floated_eqs, implics2) <- solveNestedImplications (implics `unionBags` implics1)
1208 ; (no_new_scs, simples2) <- expandSuperClasses simples1
1209
1210 ; traceTcS "solveWanteds middle" $ vcat [ text "simples1 =" <+> ppr simples1
1211 , text "simples2 =" <+> ppr simples2 ]
1212
1213 ; dflags <- getDynFlags
1214 ; final_wc <- simpl_loop 0 (solverIterations dflags) floated_eqs
1215 no_new_scs
1216 (WC { wc_simple = simples2, wc_impl = implics2
1217 , wc_insol = insols `unionBags` insols1 })
1218
1219 ; bb <- TcS.getTcEvBindsMap
1220 ; traceTcS "solveWanteds }" $
1221 vcat [ text "final wc =" <+> ppr final_wc
1222 , text "current evbinds =" <+> ppr (evBindMapBinds bb) ]
1223
1224 ; return final_wc }
1225
1226 simpl_loop :: Int -> IntWithInf -> Cts -> Bool
1227 -> WantedConstraints
1228 -> TcS WantedConstraints
1229 simpl_loop n limit floated_eqs no_new_deriveds
1230 wc@(WC { wc_simple = simples, wc_insol = insols, wc_impl = implics })
1231 | isEmptyBag floated_eqs && no_new_deriveds
1232 = return wc -- Done!
1233
1234 | n `intGtLimit` limit
1235 = do { -- Add an error (not a warning) if we blow the limit,
1236 -- Typically if we blow the limit we are going to report some other error
1237 -- (an unsolved constraint), and we don't want that error to suppress
1238 -- the iteration limit warning!
1239 addErrTcS (hang (text "solveWanteds: too many iterations"
1240 <+> parens (text "limit =" <+> ppr limit))
1241 2 (vcat [ text "Unsolved:" <+> ppr wc
1242 , ppUnless (isEmptyBag floated_eqs) $
1243 text "Floated equalities:" <+> ppr floated_eqs
1244 , ppUnless no_new_deriveds $
1245 text "New deriveds found"
1246 , text "Set limit with -fconstraint-solver-iterations=n; n=0 for no limit"
1247 ]))
1248 ; return wc }
1249
1250 | otherwise
1251 = do { let n_floated = lengthBag floated_eqs
1252 ; csTraceTcS $
1253 text "simpl_loop iteration=" <> int n
1254 <+> (parens $ hsep [ text "no new deriveds =" <+> ppr no_new_deriveds <> comma
1255 , int n_floated <+> text "floated eqs" <> comma
1256 , int (lengthBag simples) <+> text "simples to solve" ])
1257
1258 -- solveSimples may make progress if either float_eqs hold
1259 ; (unifs1, wc1) <- reportUnifications $
1260 solveSimpleWanteds (floated_eqs `unionBags` simples)
1261 -- Put floated_eqs first so they get solved first
1262 -- NB: the floated_eqs may include /derived/ equalities
1263 -- arising from fundeps inside an implication
1264
1265 ; let WC { wc_simple = simples1, wc_insol = insols1, wc_impl = implics1 } = wc1
1266 ; (no_new_scs, simples2) <- expandSuperClasses simples1
1267
1268 -- We have already tried to solve the nested implications once
1269 -- Try again only if we have unified some meta-variables
1270 -- (which is a bit like adding more givens
1271 -- See Note [Cutting off simpl_loop]
1272 ; (floated_eqs2, implics2) <- if unifs1 == 0 && isEmptyBag implics1
1273 then return (emptyBag, implics)
1274 else solveNestedImplications (implics `unionBags` implics1)
1275
1276 ; simpl_loop (n+1) limit floated_eqs2 no_new_scs
1277 (WC { wc_simple = simples2, wc_impl = implics2
1278 , wc_insol = insols `unionBags` insols1 }) }
1279
1280 expandSuperClasses :: Cts -> TcS (Bool, Cts)
1281 -- If there are any unsolved wanteds, expand one step of
1282 -- superclasses for deriveds
1283 -- Returned Bool is True <=> no new superclass constraints added
1284 -- See Note [The superclass story] in TcCanonical
1285 expandSuperClasses unsolved
1286 | not (anyBag superClassesMightHelp unsolved)
1287 = return (True, unsolved)
1288 | otherwise
1289 = do { traceTcS "expandSuperClasses {" empty
1290 ; let (pending_wanted, unsolved') = mapAccumBagL get [] unsolved
1291 get acc ct | Just ct' <- isPendingScDict ct
1292 = (ct':acc, ct')
1293 | otherwise
1294 = (acc, ct)
1295 ; pending_given <- getPendingScDicts
1296 ; if null pending_given && null pending_wanted
1297 then do { traceTcS "End expandSuperClasses no-op }" empty
1298 ; return (True, unsolved) }
1299 else
1300 do { new_given <- makeSuperClasses pending_given
1301 ; solveSimpleGivens new_given
1302 ; new_wanted <- makeSuperClasses pending_wanted
1303 ; traceTcS "End expandSuperClasses }"
1304 (vcat [ text "Given:" <+> ppr pending_given
1305 , text "Wanted:" <+> ppr new_wanted ])
1306 ; return (False, unsolved' `unionBags` listToBag new_wanted) } }
1307
1308 solveNestedImplications :: Bag Implication
1309 -> TcS (Cts, Bag Implication)
1310 -- Precondition: the TcS inerts may contain unsolved simples which have
1311 -- to be converted to givens before we go inside a nested implication.
1312 solveNestedImplications implics
1313 | isEmptyBag implics
1314 = return (emptyBag, emptyBag)
1315 | otherwise
1316 = do { traceTcS "solveNestedImplications starting {" empty
1317 ; (floated_eqs_s, unsolved_implics) <- mapAndUnzipBagM solveImplication implics
1318 ; let floated_eqs = concatBag floated_eqs_s
1319
1320 -- ... and we are back in the original TcS inerts
1321 -- Notice that the original includes the _insoluble_simples so it was safe to ignore
1322 -- them in the beginning of this function.
1323 ; traceTcS "solveNestedImplications end }" $
1324 vcat [ text "all floated_eqs =" <+> ppr floated_eqs
1325 , text "unsolved_implics =" <+> ppr unsolved_implics ]
1326
1327 ; return (floated_eqs, catBagMaybes unsolved_implics) }
1328
1329 solveImplication :: Implication -- Wanted
1330 -> TcS (Cts, -- All wanted or derived floated equalities: var = type
1331 Maybe Implication) -- Simplified implication (empty or singleton)
1332 -- Precondition: The TcS monad contains an empty worklist and given-only inerts
1333 -- which after trying to solve this implication we must restore to their original value
1334 solveImplication imp@(Implic { ic_tclvl = tclvl
1335 , ic_binds = ev_binds_var
1336 , ic_skols = skols
1337 , ic_given = given_ids
1338 , ic_wanted = wanteds
1339 , ic_info = info
1340 , ic_status = status
1341 , ic_env = env })
1342 | isSolvedStatus status
1343 = return (emptyCts, Just imp) -- Do nothing
1344
1345 | otherwise -- Even for IC_Insoluble it is worth doing more work
1346 -- The insoluble stuff might be in one sub-implication
1347 -- and other unsolved goals in another; and we want to
1348 -- solve the latter as much as possible
1349 = do { inerts <- getTcSInerts
1350 ; traceTcS "solveImplication {" (ppr imp $$ text "Inerts" <+> ppr inerts)
1351
1352 -- Solve the nested constraints
1353 ; (no_given_eqs, given_insols, residual_wanted)
1354 <- nestImplicTcS ev_binds_var tclvl $
1355 do { let loc = mkGivenLoc tclvl info env
1356 givens = mkGivens loc given_ids
1357 ; solveSimpleGivens givens
1358
1359 ; residual_wanted <- solveWanteds wanteds
1360 -- solveWanteds, *not* solveWantedsAndDrop, because
1361 -- we want to retain derived equalities so we can float
1362 -- them out in floatEqualities
1363
1364 ; (no_eqs, given_insols) <- getNoGivenEqs tclvl skols
1365 -- Call getNoGivenEqs /after/ solveWanteds, because
1366 -- solveWanteds can augment the givens, via expandSuperClasses,
1367 -- to reveal given superclass equalities
1368
1369 ; return (no_eqs, given_insols, residual_wanted) }
1370
1371 ; (floated_eqs, residual_wanted)
1372 <- floatEqualities skols no_given_eqs residual_wanted
1373
1374 ; traceTcS "solveImplication 2"
1375 (ppr given_insols $$ ppr residual_wanted)
1376 ; let final_wanted = residual_wanted `addInsols` given_insols
1377
1378 ; res_implic <- setImplicationStatus (imp { ic_no_eqs = no_given_eqs
1379 , ic_wanted = final_wanted })
1380
1381 ; (evbinds, tcvs) <- TcS.getTcEvBindsAndTCVs ev_binds_var
1382 ; traceTcS "solveImplication end }" $ vcat
1383 [ text "no_given_eqs =" <+> ppr no_given_eqs
1384 , text "floated_eqs =" <+> ppr floated_eqs
1385 , text "res_implic =" <+> ppr res_implic
1386 , text "implication evbinds =" <+> ppr (evBindMapBinds evbinds)
1387 , text "implication tvcs =" <+> ppr tcvs ]
1388
1389 ; return (floated_eqs, res_implic) }
1390
1391 ----------------------
1392 setImplicationStatus :: Implication -> TcS (Maybe Implication)
1393 -- Finalise the implication returned from solveImplication:
1394 -- * Set the ic_status field
1395 -- * Trim the ic_wanted field to remove Derived constraints
1396 -- Precondition: the ic_status field is not already IC_Solved
1397 -- Return Nothing if we can discard the implication altogether
1398 setImplicationStatus implic@(Implic { ic_binds = ev_binds_var
1399 , ic_status = status
1400 , ic_info = info
1401 , ic_wanted = wc
1402 , ic_needed = old_discarded_needs
1403 , ic_given = givens })
1404 | ASSERT2( not (isSolvedStatus status ), ppr info )
1405 -- Precondition: we only set the status if it is not already solved
1406 some_insoluble
1407 = return $ Just $
1408 implic { ic_status = IC_Insoluble
1409 , ic_needed = new_discarded_needs
1410 , ic_wanted = pruned_wc }
1411
1412 | some_unsolved
1413 = do { traceTcS "setImplicationStatus" $
1414 vcat [ppr givens $$ ppr simples $$ ppr insols $$ ppr mb_implic_needs]
1415 ; return $ Just $
1416 implic { ic_status = IC_Unsolved
1417 , ic_needed = new_discarded_needs
1418 , ic_wanted = pruned_wc }
1419 }
1420
1421 | otherwise -- Everything is solved; look at the implications
1422 -- See Note [Tracking redundant constraints]
1423 = do { ev_binds <- TcS.getTcEvBindsAndTCVs ev_binds_var
1424 ; let all_needs = neededEvVars ev_binds $
1425 solved_implic_needs `unionVarSet` new_discarded_needs
1426
1427 dead_givens | warnRedundantGivens info
1428 = filterOut (`elemVarSet` all_needs) givens
1429 | otherwise = [] -- None to report
1430
1431 final_needs = all_needs `delVarSetList` givens
1432
1433 discard_entire_implication -- Can we discard the entire implication?
1434 = null dead_givens -- No warning from this implication
1435 && isEmptyBag pruned_implics -- No live children
1436 && isEmptyVarSet final_needs -- No needed vars to pass up to parent
1437
1438 final_status = IC_Solved { ics_need = final_needs
1439 , ics_dead = dead_givens }
1440 final_implic = implic { ic_status = final_status
1441 , ic_needed = emptyVarSet -- Irrelevant for IC_Solved
1442 , ic_wanted = pruned_wc }
1443
1444 -- Check that there are no term-level evidence bindings
1445 -- in the cases where we have no place to put them
1446 ; MASSERT2( termEvidenceAllowed info || isEmptyEvBindMap (fst ev_binds)
1447 , ppr info $$ ppr ev_binds )
1448
1449 ; traceTcS "setImplicationStatus 2" $
1450 vcat [ppr givens $$ ppr ev_binds $$ ppr all_needs]
1451 ; return $ if discard_entire_implication
1452 then Nothing
1453 else Just final_implic }
1454 where
1455 WC { wc_simple = simples, wc_impl = implics, wc_insol = insols } = wc
1456
1457 some_insoluble = insolubleWC wc
1458 some_unsolved = not (isEmptyBag simples && isEmptyBag insols)
1459 || isNothing mb_implic_needs
1460
1461 pruned_simples = dropDerivedSimples simples
1462 pruned_insols = dropDerivedInsols insols
1463 (pruned_implics, discarded_needs) = partitionBagWith discard_me implics
1464 pruned_wc = wc { wc_simple = pruned_simples
1465 , wc_insol = pruned_insols
1466 , wc_impl = pruned_implics }
1467 new_discarded_needs = foldrBag unionVarSet old_discarded_needs discarded_needs
1468
1469 mb_implic_needs :: Maybe VarSet
1470 -- Just vs => all implics are IC_Solved, with 'vs' needed
1471 -- Nothing => at least one implic is not IC_Solved
1472 mb_implic_needs = foldrBag add_implic (Just emptyVarSet) pruned_implics
1473 Just solved_implic_needs = mb_implic_needs
1474
1475 add_implic implic acc
1476 | Just vs_acc <- acc
1477 , IC_Solved { ics_need = vs } <- ic_status implic
1478 = Just (vs `unionVarSet` vs_acc)
1479 | otherwise = Nothing
1480
1481 discard_me :: Implication -> Either Implication VarSet
1482 discard_me ic
1483 | IC_Solved { ics_dead = dead_givens, ics_need = needed } <- ic_status ic
1484 -- Fully solved
1485 , null dead_givens -- No redundant givens to report
1486 , isEmptyBag (wc_impl (ic_wanted ic))
1487 -- And no children that might have things to report
1488 = Right needed
1489 | otherwise
1490 = Left ic
1491
1492 warnRedundantGivens :: SkolemInfo -> Bool
1493 warnRedundantGivens (SigSkol ctxt _ _)
1494 = case ctxt of
1495 FunSigCtxt _ warn_redundant -> warn_redundant
1496 ExprSigCtxt -> True
1497 _ -> False
1498
1499 -- To think about: do we want to report redundant givens for
1500 -- pattern synonyms, PatSynSigSkol? c.f Trac #9953, comment:21.
1501 warnRedundantGivens (InstSkol {}) = True
1502 warnRedundantGivens _ = False
1503
1504 neededEvVars :: (EvBindMap, TcTyVarSet) -> VarSet -> VarSet
1505 -- Find all the evidence variables that are "needed",
1506 -- and then delete all those bound by the evidence bindings
1507 -- See Note [Tracking redundant constraints]
1508 neededEvVars (ev_binds, tcvs) initial_seeds
1509 = (needed `unionVarSet` tcvs) `minusVarSet` bndrs
1510 where
1511 seeds = foldEvBindMap add_wanted initial_seeds ev_binds
1512 needed = transCloVarSet also_needs seeds
1513 bndrs = foldEvBindMap add_bndr emptyVarSet ev_binds
1514
1515 add_wanted :: EvBind -> VarSet -> VarSet
1516 add_wanted (EvBind { eb_is_given = is_given, eb_rhs = rhs }) needs
1517 | is_given = needs -- Add the rhs vars of the Wanted bindings only
1518 | otherwise = evVarsOfTerm rhs `unionVarSet` needs
1519
1520 also_needs :: VarSet -> VarSet
1521 also_needs needs
1522 = nonDetFoldUniqSet add emptyVarSet needs
1523 -- It's OK to use nonDetFoldUFM here because we immediately forget
1524 -- about the ordering by creating a set
1525 where
1526 add v needs
1527 | Just ev_bind <- lookupEvBind ev_binds v
1528 , EvBind { eb_is_given = is_given, eb_rhs = rhs } <- ev_bind
1529 , is_given
1530 = evVarsOfTerm rhs `unionVarSet` needs
1531 | otherwise
1532 = needs
1533
1534 add_bndr :: EvBind -> VarSet -> VarSet
1535 add_bndr (EvBind { eb_lhs = v }) vs = extendVarSet vs v
1536
1537
1538 {-
1539 Note [Tracking redundant constraints]
1540 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1541 With Opt_WarnRedundantConstraints, GHC can report which
1542 constraints of a type signature (or instance declaration) are
1543 redundant, and can be omitted. Here is an overview of how it
1544 works:
1545
1546 ----- What is a redundant constraint?
1547
1548 * The things that can be redundant are precisely the Given
1549 constraints of an implication.
1550
1551 * A constraint can be redundant in two different ways:
1552 a) It is implied by other givens. E.g.
1553 f :: (Eq a, Ord a) => blah -- Eq a unnecessary
1554 g :: (Eq a, a~b, Eq b) => blah -- Either Eq a or Eq b unnecessary
1555 b) It is not needed by the Wanted constraints covered by the
1556 implication E.g.
1557 f :: Eq a => a -> Bool
1558 f x = True -- Equality not used
1559
1560 * To find (a), when we have two Given constraints,
1561 we must be careful to drop the one that is a naked variable (if poss).
1562 So if we have
1563 f :: (Eq a, Ord a) => blah
1564 then we may find [G] sc_sel (d1::Ord a) :: Eq a
1565 [G] d2 :: Eq a
1566 We want to discard d2 in favour of the superclass selection from
1567 the Ord dictionary. This is done by TcInteract.solveOneFromTheOther
1568 See Note [Replacement vs keeping].
1569
1570 * To find (b) we need to know which evidence bindings are 'wanted';
1571 hence the eb_is_given field on an EvBind.
1572
1573 ----- How tracking works
1574
1575 * When the constraint solver finishes solving all the wanteds in
1576 an implication, it sets its status to IC_Solved
1577
1578 - The ics_dead field, of IC_Solved, records the subset of this
1579 implication's ic_given that are redundant (not needed).
1580
1581 - The ics_need field of IC_Solved then records all the
1582 in-scope (given) evidence variables bound by the context, that
1583 were needed to solve this implication, including all its nested
1584 implications. (We remove the ic_given of this implication from
1585 the set, of course.)
1586
1587 * We compute which evidence variables are needed by an implication
1588 in setImplicationStatus. A variable is needed if
1589 a) it is free in the RHS of a Wanted EvBind,
1590 b) it is free in the RHS of an EvBind whose LHS is needed,
1591 c) it is in the ics_need of a nested implication.
1592
1593 * We need to be careful not to discard an implication
1594 prematurely, even one that is fully solved, because we might
1595 thereby forget which variables it needs, and hence wrongly
1596 report a constraint as redundant. But we can discard it once
1597 its free vars have been incorporated into its parent; or if it
1598 simply has no free vars. This careful discarding is also
1599 handled in setImplicationStatus.
1600
1601 ----- Reporting redundant constraints
1602
1603 * TcErrors does the actual warning, in warnRedundantConstraints.
1604
1605 * We don't report redundant givens for *every* implication; only
1606 for those which reply True to TcSimplify.warnRedundantGivens:
1607
1608 - For example, in a class declaration, the default method *can*
1609 use the class constraint, but it certainly doesn't *have* to,
1610 and we don't want to report an error there.
1611
1612 - More subtly, in a function definition
1613 f :: (Ord a, Ord a, Ix a) => a -> a
1614 f x = rhs
1615 we do an ambiguity check on the type (which would find that one
1616 of the Ord a constraints was redundant), and then we check that
1617 the definition has that type (which might find that both are
1618 redundant). We don't want to report the same error twice, so we
1619 disable it for the ambiguity check. Hence using two different
1620 FunSigCtxts, one with the warn-redundant field set True, and the
1621 other set False in
1622 - TcBinds.tcSpecPrag
1623 - TcBinds.tcTySig
1624
1625 This decision is taken in setImplicationStatus, rather than TcErrors
1626 so that we can discard implication constraints that we don't need.
1627 So ics_dead consists only of the *reportable* redundant givens.
1628
1629 ----- Shortcomings
1630
1631 Consider (see Trac #9939)
1632 f2 :: (Eq a, Ord a) => a -> a -> Bool
1633 -- Ord a redundant, but Eq a is reported
1634 f2 x y = (x == y)
1635
1636 We report (Eq a) as redundant, whereas actually (Ord a) is. But it's
1637 really not easy to detect that!
1638
1639
1640 Note [Cutting off simpl_loop]
1641 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1642 It is very important not to iterate in simpl_loop unless there is a chance
1643 of progress. Trac #8474 is a classic example:
1644
1645 * There's a deeply-nested chain of implication constraints.
1646 ?x:alpha => ?y1:beta1 => ... ?yn:betan => [W] ?x:Int
1647
1648 * From the innermost one we get a [D] alpha ~ Int,
1649 but alpha is untouchable until we get out to the outermost one
1650
1651 * We float [D] alpha~Int out (it is in floated_eqs), but since alpha
1652 is untouchable, the solveInteract in simpl_loop makes no progress
1653
1654 * So there is no point in attempting to re-solve
1655 ?yn:betan => [W] ?x:Int
1656 via solveNestedImplications, because we'll just get the
1657 same [D] again
1658
1659 * If we *do* re-solve, we'll get an ininite loop. It is cut off by
1660 the fixed bound of 10, but solving the next takes 10*10*...*10 (ie
1661 exponentially many) iterations!
1662
1663 Conclusion: we should call solveNestedImplications only if we did
1664 some unification in solveSimpleWanteds; because that's the only way
1665 we'll get more Givens (a unification is like adding a Given) to
1666 allow the implication to make progress.
1667 -}
1668
1669 promoteTyVar :: TcLevel -> TcTyVar -> TcM Bool
1670 -- When we float a constraint out of an implication we must restore
1671 -- invariant (MetaTvInv) in Note [TcLevel and untouchable type variables] in TcType
1672 -- Return True <=> we did some promotion
1673 -- See Note [Promoting unification variables]
1674 promoteTyVar tclvl tv
1675 | isFloatedTouchableMetaTyVar tclvl tv
1676 = do { cloned_tv <- TcM.cloneMetaTyVar tv
1677 ; let rhs_tv = setMetaTyVarTcLevel cloned_tv tclvl
1678 ; TcM.writeMetaTyVar tv (mkTyVarTy rhs_tv)
1679 ; return True }
1680 | otherwise
1681 = return False
1682
1683 promoteTyVarTcS :: TcLevel -> TcTyVar -> TcS ()
1684 -- When we float a constraint out of an implication we must restore
1685 -- invariant (MetaTvInv) in Note [TcLevel and untouchable type variables] in TcType
1686 -- See Note [Promoting unification variables]
1687 -- We don't just call promoteTyVar because we want to use unifyTyVar,
1688 -- not writeMetaTyVar
1689 promoteTyVarTcS tclvl tv
1690 | isFloatedTouchableMetaTyVar tclvl tv
1691 = do { cloned_tv <- TcS.cloneMetaTyVar tv
1692 ; let rhs_tv = setMetaTyVarTcLevel cloned_tv tclvl
1693 ; unifyTyVar tv (mkTyVarTy rhs_tv) }
1694 | otherwise
1695 = return ()
1696
1697 -- | Like 'defaultTyVar', but in the TcS monad.
1698 defaultTyVarTcS :: TcTyVar -> TcS Bool
1699 defaultTyVarTcS the_tv
1700 | isRuntimeRepVar the_tv
1701 = do { traceTcS "defaultTyVarTcS RuntimeRep" (ppr the_tv)
1702 ; unifyTyVar the_tv liftedRepTy
1703 ; return True }
1704 | otherwise
1705 = return False -- the common case
1706
1707 approximateWC :: Bool -> WantedConstraints -> Cts
1708 -- Postcondition: Wanted or Derived Cts
1709 -- See Note [ApproximateWC]
1710 approximateWC float_past_equalities wc
1711 = float_wc emptyVarSet wc
1712 where
1713 float_wc :: TcTyCoVarSet -> WantedConstraints -> Cts
1714 float_wc trapping_tvs (WC { wc_simple = simples, wc_impl = implics })
1715 = filterBag is_floatable simples `unionBags`
1716 do_bag (float_implic trapping_tvs) implics
1717 where
1718 is_floatable ct = tyCoVarsOfCt ct `disjointVarSet` trapping_tvs
1719
1720 float_implic :: TcTyCoVarSet -> Implication -> Cts
1721 float_implic trapping_tvs imp
1722 | float_past_equalities || ic_no_eqs imp
1723 = float_wc new_trapping_tvs (ic_wanted imp)
1724 | otherwise -- Take care with equalities
1725 = emptyCts -- See (1) under Note [ApproximateWC]
1726 where
1727 new_trapping_tvs = trapping_tvs `extendVarSetList` ic_skols imp
1728 do_bag :: (a -> Bag c) -> Bag a -> Bag c
1729 do_bag f = foldrBag (unionBags.f) emptyBag
1730
1731 {- Note [ApproximateWC]
1732 ~~~~~~~~~~~~~~~~~~~~~~~
1733 approximateWC takes a constraint, typically arising from the RHS of a
1734 let-binding whose type we are *inferring*, and extracts from it some
1735 *simple* constraints that we might plausibly abstract over. Of course
1736 the top-level simple constraints are plausible, but we also float constraints
1737 out from inside, if they are not captured by skolems.
1738
1739 The same function is used when doing type-class defaulting (see the call
1740 to applyDefaultingRules) to extract constraints that that might be defaulted.
1741
1742 There is one caveat:
1743
1744 1. When infering most-general types (in simplifyInfer), we do *not*
1745 float anything out if the implication binds equality constraints,
1746 because that defeats the OutsideIn story. Consider
1747 data T a where
1748 TInt :: T Int
1749 MkT :: T a
1750
1751 f TInt = 3::Int
1752
1753 We get the implication (a ~ Int => res ~ Int), where so far we've decided
1754 f :: T a -> res
1755 We don't want to float (res~Int) out because then we'll infer
1756 f :: T a -> Int
1757 which is only on of the possible types. (GHC 7.6 accidentally *did*
1758 float out of such implications, which meant it would happily infer
1759 non-principal types.)
1760
1761 HOWEVER (Trac #12797) in findDefaultableGroups we are not worried about
1762 the most-general type; and we /do/ want to float out of equalities.
1763 Hence the boolean flag to approximateWC.
1764
1765 ------ Historical note -----------
1766 There used to be a second caveat, driven by Trac #8155
1767
1768 2. We do not float out an inner constraint that shares a type variable
1769 (transitively) with one that is trapped by a skolem. Eg
1770 forall a. F a ~ beta, Integral beta
1771 We don't want to float out (Integral beta). Doing so would be bad
1772 when defaulting, because then we'll default beta:=Integer, and that
1773 makes the error message much worse; we'd get
1774 Can't solve F a ~ Integer
1775 rather than
1776 Can't solve Integral (F a)
1777
1778 Moreover, floating out these "contaminated" constraints doesn't help
1779 when generalising either. If we generalise over (Integral b), we still
1780 can't solve the retained implication (forall a. F a ~ b). Indeed,
1781 arguably that too would be a harder error to understand.
1782
1783 But this transitive closure stuff gives rise to a complex rule for
1784 when defaulting actually happens, and one that was never documented.
1785 Moreover (Trac #12923), the more complex rule is sometimes NOT what
1786 you want. So I simply removed the extra code to implement the
1787 contamination stuff. There was zero effect on the testsuite (not even
1788 #8155).
1789 ------ End of historical note -----------
1790
1791
1792 Note [DefaultTyVar]
1793 ~~~~~~~~~~~~~~~~~~~
1794 defaultTyVar is used on any un-instantiated meta type variables to
1795 default any RuntimeRep variables to LiftedRep. This is important
1796 to ensure that instance declarations match. For example consider
1797
1798 instance Show (a->b)
1799 foo x = show (\_ -> True)
1800
1801 Then we'll get a constraint (Show (p ->q)) where p has kind (TYPE r),
1802 and that won't match the typeKind (*) in the instance decl. See tests
1803 tc217 and tc175.
1804
1805 We look only at touchable type variables. No further constraints
1806 are going to affect these type variables, so it's time to do it by
1807 hand. However we aren't ready to default them fully to () or
1808 whatever, because the type-class defaulting rules have yet to run.
1809
1810 An alternate implementation would be to emit a derived constraint setting
1811 the RuntimeRep variable to LiftedRep, but this seems unnecessarily indirect.
1812
1813 Note [Promote _and_ default when inferring]
1814 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1815 When we are inferring a type, we simplify the constraint, and then use
1816 approximateWC to produce a list of candidate constraints. Then we MUST
1817
1818 a) Promote any meta-tyvars that have been floated out by
1819 approximateWC, to restore invariant (MetaTvInv) described in
1820 Note [TcLevel and untouchable type variables] in TcType.
1821
1822 b) Default the kind of any meta-tyvars that are not mentioned in
1823 in the environment.
1824
1825 To see (b), suppose the constraint is (C ((a :: OpenKind) -> Int)), and we
1826 have an instance (C ((x:*) -> Int)). The instance doesn't match -- but it
1827 should! If we don't solve the constraint, we'll stupidly quantify over
1828 (C (a->Int)) and, worse, in doing so zonkQuantifiedTyVar will quantify over
1829 (b:*) instead of (a:OpenKind), which can lead to disaster; see Trac #7332.
1830 Trac #7641 is a simpler example.
1831
1832 Note [Promoting unification variables]
1833 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1834 When we float an equality out of an implication we must "promote" free
1835 unification variables of the equality, in order to maintain Invariant
1836 (MetaTvInv) from Note [TcLevel and untouchable type variables] in TcType. for the
1837 leftover implication.
1838
1839 This is absolutely necessary. Consider the following example. We start
1840 with two implications and a class with a functional dependency.
1841
1842 class C x y | x -> y
1843 instance C [a] [a]
1844
1845 (I1) [untch=beta]forall b. 0 => F Int ~ [beta]
1846 (I2) [untch=beta]forall c. 0 => F Int ~ [[alpha]] /\ C beta [c]
1847
1848 We float (F Int ~ [beta]) out of I1, and we float (F Int ~ [[alpha]]) out of I2.
1849 They may react to yield that (beta := [alpha]) which can then be pushed inwards
1850 the leftover of I2 to get (C [alpha] [a]) which, using the FunDep, will mean that
1851 (alpha := a). In the end we will have the skolem 'b' escaping in the untouchable
1852 beta! Concrete example is in indexed_types/should_fail/ExtraTcsUntch.hs:
1853
1854 class C x y | x -> y where
1855 op :: x -> y -> ()
1856
1857 instance C [a] [a]
1858
1859 type family F a :: *
1860
1861 h :: F Int -> ()
1862 h = undefined
1863
1864 data TEx where
1865 TEx :: a -> TEx
1866
1867 f (x::beta) =
1868 let g1 :: forall b. b -> ()
1869 g1 _ = h [x]
1870 g2 z = case z of TEx y -> (h [[undefined]], op x [y])
1871 in (g1 '3', g2 undefined)
1872
1873
1874
1875 *********************************************************************************
1876 * *
1877 * Floating equalities *
1878 * *
1879 *********************************************************************************
1880
1881 Note [Float Equalities out of Implications]
1882 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1883 For ordinary pattern matches (including existentials) we float
1884 equalities out of implications, for instance:
1885 data T where
1886 MkT :: Eq a => a -> T
1887 f x y = case x of MkT _ -> (y::Int)
1888 We get the implication constraint (x::T) (y::alpha):
1889 forall a. [untouchable=alpha] Eq a => alpha ~ Int
1890 We want to float out the equality into a scope where alpha is no
1891 longer untouchable, to solve the implication!
1892
1893 But we cannot float equalities out of implications whose givens may
1894 yield or contain equalities:
1895
1896 data T a where
1897 T1 :: T Int
1898 T2 :: T Bool
1899 T3 :: T a
1900
1901 h :: T a -> a -> Int
1902
1903 f x y = case x of
1904 T1 -> y::Int
1905 T2 -> y::Bool
1906 T3 -> h x y
1907
1908 We generate constraint, for (x::T alpha) and (y :: beta):
1909 [untouchables = beta] (alpha ~ Int => beta ~ Int) -- From 1st branch
1910 [untouchables = beta] (alpha ~ Bool => beta ~ Bool) -- From 2nd branch
1911 (alpha ~ beta) -- From 3rd branch
1912
1913 If we float the equality (beta ~ Int) outside of the first implication and
1914 the equality (beta ~ Bool) out of the second we get an insoluble constraint.
1915 But if we just leave them inside the implications, we unify alpha := beta and
1916 solve everything.
1917
1918 Principle:
1919 We do not want to float equalities out which may
1920 need the given *evidence* to become soluble.
1921
1922 Consequence: classes with functional dependencies don't matter (since there is
1923 no evidence for a fundep equality), but equality superclasses do matter (since
1924 they carry evidence).
1925 -}
1926
1927 floatEqualities :: [TcTyVar] -> Bool
1928 -> WantedConstraints
1929 -> TcS (Cts, WantedConstraints)
1930 -- Main idea: see Note [Float Equalities out of Implications]
1931 --
1932 -- Precondition: the wc_simple of the incoming WantedConstraints are
1933 -- fully zonked, so that we can see their free variables
1934 --
1935 -- Postcondition: The returned floated constraints (Cts) are only
1936 -- Wanted or Derived
1937 --
1938 -- Also performs some unifications (via promoteTyVar), adding to
1939 -- monadically-carried ty_binds. These will be used when processing
1940 -- floated_eqs later
1941 --
1942 -- Subtleties: Note [Float equalities from under a skolem binding]
1943 -- Note [Skolem escape]
1944 floatEqualities skols no_given_eqs
1945 wanteds@(WC { wc_simple = simples })
1946 | not no_given_eqs -- There are some given equalities, so don't float
1947 = return (emptyBag, wanteds) -- Note [Float Equalities out of Implications]
1948 | otherwise
1949 = do { outer_tclvl <- TcS.getTcLevel
1950 ; mapM_ (promoteTyVarTcS outer_tclvl)
1951 (tyCoVarsOfCtsList float_eqs)
1952 -- See Note [Promoting unification variables]
1953
1954 ; traceTcS "floatEqualities" (vcat [ text "Skols =" <+> ppr skols
1955 , text "Simples =" <+> ppr simples
1956 , text "Floated eqs =" <+> ppr float_eqs])
1957 ; return ( float_eqs
1958 , wanteds { wc_simple = remaining_simples } ) }
1959 where
1960 skol_set = mkVarSet skols
1961 (float_eqs, remaining_simples) = partitionBag (usefulToFloat skol_set) simples
1962
1963 usefulToFloat :: VarSet -> Ct -> Bool
1964 usefulToFloat skol_set ct -- The constraint is un-flattened and de-canonicalised
1965 = is_meta_var_eq pred &&
1966 (tyCoVarsOfType pred `disjointVarSet` skol_set)
1967 where
1968 pred = ctPred ct
1969
1970 -- Float out alpha ~ ty, or ty ~ alpha
1971 -- which might be unified outside
1972 -- See Note [Which equalities to float]
1973 is_meta_var_eq pred
1974 | EqPred NomEq ty1 ty2 <- classifyPredType pred
1975 = case (tcGetTyVar_maybe ty1, tcGetTyVar_maybe ty2) of
1976 (Just tv1, _) -> float_tv_eq tv1 ty2
1977 (_, Just tv2) -> float_tv_eq tv2 ty1
1978 _ -> False
1979 | otherwise
1980 = False
1981
1982 float_tv_eq tv1 ty2 -- See Note [Which equalities to float]
1983 = isMetaTyVar tv1
1984 && (not (isSigTyVar tv1) || isTyVarTy ty2)
1985
1986 {- Note [Float equalities from under a skolem binding]
1987 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1988 Which of the simple equalities can we float out? Obviously, only
1989 ones that don't mention the skolem-bound variables. But that is
1990 over-eager. Consider
1991 [2] forall a. F a beta[1] ~ gamma[2], G beta[1] gamma[2] ~ Int
1992 The second constraint doesn't mention 'a'. But if we float it,
1993 we'll promote gamma[2] to gamma'[1]. Now suppose that we learn that
1994 beta := Bool, and F a Bool = a, and G Bool _ = Int. Then we'll
1995 we left with the constraint
1996 [2] forall a. a ~ gamma'[1]
1997 which is insoluble because gamma became untouchable.
1998
1999 Solution: float only constraints that stand a jolly good chance of
2000 being soluble simply by being floated, namely ones of form
2001 a ~ ty
2002 where 'a' is a currently-untouchable unification variable, but may
2003 become touchable by being floated (perhaps by more than one level).
2004
2005 We had a very complicated rule previously, but this is nice and
2006 simple. (To see the notes, look at this Note in a version of
2007 TcSimplify prior to Oct 2014).
2008
2009 Note [Which equalities to float]
2010 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2011 Which equalities should we float? We want to float ones where there
2012 is a decent chance that floating outwards will allow unification to
2013 happen. In particular:
2014
2015 Float out equalities of form (alpha ~ ty) or (ty ~ alpha), where
2016
2017 * alpha is a meta-tyvar.
2018
2019 * And 'alpha' is not a SigTv with 'ty' being a non-tyvar. In that
2020 case, floating out won't help either, and it may affect grouping
2021 of error messages.
2022
2023 Note [Skolem escape]
2024 ~~~~~~~~~~~~~~~~~~~~
2025 You might worry about skolem escape with all this floating.
2026 For example, consider
2027 [2] forall a. (a ~ F beta[2] delta,
2028 Maybe beta[2] ~ gamma[1])
2029
2030 The (Maybe beta ~ gamma) doesn't mention 'a', so we float it, and
2031 solve with gamma := beta. But what if later delta:=Int, and
2032 F b Int = b.
2033 Then we'd get a ~ beta[2], and solve to get beta:=a, and now the
2034 skolem has escaped!
2035
2036 But it's ok: when we float (Maybe beta[2] ~ gamma[1]), we promote beta[2]
2037 to beta[1], and that means the (a ~ beta[1]) will be stuck, as it should be.
2038
2039
2040 *********************************************************************************
2041 * *
2042 * Defaulting and disambiguation *
2043 * *
2044 *********************************************************************************
2045 -}
2046
2047 applyDefaultingRules :: WantedConstraints -> TcS Bool
2048 -- True <=> I did some defaulting, by unifying a meta-tyvar
2049 -- Input WantedConstraints are not necessarily zonked
2050
2051 applyDefaultingRules wanteds
2052 | isEmptyWC wanteds
2053 = return False
2054 | otherwise
2055 = do { info@(default_tys, _) <- getDefaultInfo
2056 ; wanteds <- TcS.zonkWC wanteds
2057
2058 ; let groups = findDefaultableGroups info wanteds
2059
2060 ; traceTcS "applyDefaultingRules {" $
2061 vcat [ text "wanteds =" <+> ppr wanteds
2062 , text "groups =" <+> ppr groups
2063 , text "info =" <+> ppr info ]
2064
2065 ; something_happeneds <- mapM (disambigGroup default_tys) groups
2066
2067 ; traceTcS "applyDefaultingRules }" (ppr something_happeneds)
2068
2069 ; return (or something_happeneds) }
2070
2071 findDefaultableGroups
2072 :: ( [Type]
2073 , (Bool,Bool) ) -- (Overloaded strings, extended default rules)
2074 -> WantedConstraints -- Unsolved (wanted or derived)
2075 -> [(TyVar, [Ct])]
2076 findDefaultableGroups (default_tys, (ovl_strings, extended_defaults)) wanteds
2077 | null default_tys
2078 = []
2079 | otherwise
2080 = [ (tv, map fstOf3 group)
2081 | group@((_,_,tv):_) <- unary_groups
2082 , defaultable_tyvar tv
2083 , defaultable_classes (map sndOf3 group) ]
2084 where
2085 simples = approximateWC True wanteds
2086 (unaries, non_unaries) = partitionWith find_unary (bagToList simples)
2087 unary_groups = equivClasses cmp_tv unaries
2088
2089 unary_groups :: [[(Ct, Class, TcTyVar)]] -- (C tv) constraints
2090 unaries :: [(Ct, Class, TcTyVar)] -- (C tv) constraints
2091 non_unaries :: [Ct] -- and *other* constraints
2092
2093 -- Finds unary type-class constraints
2094 -- But take account of polykinded classes like Typeable,
2095 -- which may look like (Typeable * (a:*)) (Trac #8931)
2096 find_unary :: Ct -> Either (Ct, Class, TyVar) Ct
2097 find_unary cc
2098 | Just (cls,tys) <- getClassPredTys_maybe (ctPred cc)
2099 , [ty] <- filterOutInvisibleTypes (classTyCon cls) tys
2100 -- Ignore invisible arguments for this purpose
2101 , Just tv <- tcGetTyVar_maybe ty
2102 , isMetaTyVar tv -- We might have runtime-skolems in GHCi, and
2103 -- we definitely don't want to try to assign to those!
2104 = Left (cc, cls, tv)
2105 find_unary cc = Right cc -- Non unary or non dictionary
2106
2107 bad_tvs :: TcTyCoVarSet -- TyVars mentioned by non-unaries
2108 bad_tvs = mapUnionVarSet tyCoVarsOfCt non_unaries
2109
2110 cmp_tv (_,_,tv1) (_,_,tv2) = tv1 `compare` tv2
2111
2112 defaultable_tyvar :: TcTyVar -> Bool
2113 defaultable_tyvar tv
2114 = let b1 = isTyConableTyVar tv -- Note [Avoiding spurious errors]
2115 b2 = not (tv `elemVarSet` bad_tvs)
2116 in b1 && (b2 || extended_defaults) -- Note [Multi-parameter defaults]
2117
2118 defaultable_classes :: [Class] -> Bool
2119 defaultable_classes clss
2120 | extended_defaults = any (isInteractiveClass ovl_strings) clss
2121 | otherwise = all is_std_class clss && (any (isNumClass ovl_strings) clss)
2122
2123 -- is_std_class adds IsString to the standard numeric classes,
2124 -- when -foverloaded-strings is enabled
2125 is_std_class cls = isStandardClass cls ||
2126 (ovl_strings && (cls `hasKey` isStringClassKey))
2127
2128 ------------------------------
2129 disambigGroup :: [Type] -- The default types
2130 -> (TcTyVar, [Ct]) -- All classes of the form (C a)
2131 -- sharing same type variable
2132 -> TcS Bool -- True <=> something happened, reflected in ty_binds
2133
2134 disambigGroup [] _
2135 = return False
2136 disambigGroup (default_ty:default_tys) group@(the_tv, wanteds)
2137 = do { traceTcS "disambigGroup {" (vcat [ ppr default_ty, ppr the_tv, ppr wanteds ])
2138 ; fake_ev_binds_var <- TcS.newTcEvBinds
2139 ; tclvl <- TcS.getTcLevel
2140 ; success <- nestImplicTcS fake_ev_binds_var (pushTcLevel tclvl) try_group
2141
2142 ; if success then
2143 -- Success: record the type variable binding, and return
2144 do { unifyTyVar the_tv default_ty
2145 ; wrapWarnTcS $ warnDefaulting wanteds default_ty
2146 ; traceTcS "disambigGroup succeeded }" (ppr default_ty)
2147 ; return True }
2148 else
2149 -- Failure: try with the next type
2150 do { traceTcS "disambigGroup failed, will try other default types }"
2151 (ppr default_ty)
2152 ; disambigGroup default_tys group } }
2153 where
2154 try_group
2155 | Just subst <- mb_subst
2156 = do { lcl_env <- TcS.getLclEnv
2157 ; let loc = CtLoc { ctl_origin = GivenOrigin UnkSkol
2158 , ctl_env = lcl_env
2159 , ctl_t_or_k = Nothing
2160 , ctl_depth = initialSubGoalDepth }
2161 ; wanted_evs <- mapM (newWantedEvVarNC loc . substTy subst . ctPred)
2162 wanteds
2163 ; fmap isEmptyWC $
2164 solveSimpleWanteds $ listToBag $
2165 map mkNonCanonical wanted_evs }
2166
2167 | otherwise
2168 = return False
2169
2170 the_ty = mkTyVarTy the_tv
2171 mb_subst = tcMatchTyKi the_ty default_ty
2172 -- Make sure the kinds match too; hence this call to tcMatchTyKi
2173 -- E.g. suppose the only constraint was (Typeable k (a::k))
2174 -- With the addition of polykinded defaulting we also want to reject
2175 -- ill-kinded defaulting attempts like (Eq []) or (Foldable Int) here.
2176
2177 -- In interactive mode, or with -XExtendedDefaultRules,
2178 -- we default Show a to Show () to avoid graututious errors on "show []"
2179 isInteractiveClass :: Bool -- -XOverloadedStrings?
2180 -> Class -> Bool
2181 isInteractiveClass ovl_strings cls
2182 = isNumClass ovl_strings cls || (classKey cls `elem` interactiveClassKeys)
2183
2184 -- isNumClass adds IsString to the standard numeric classes,
2185 -- when -foverloaded-strings is enabled
2186 isNumClass :: Bool -- -XOverloadedStrings?
2187 -> Class -> Bool
2188 isNumClass ovl_strings cls
2189 = isNumericClass cls || (ovl_strings && (cls `hasKey` isStringClassKey))
2190
2191
2192 {-
2193 Note [Avoiding spurious errors]
2194 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2195 When doing the unification for defaulting, we check for skolem
2196 type variables, and simply don't default them. For example:
2197 f = (*) -- Monomorphic
2198 g :: Num a => a -> a
2199 g x = f x x
2200 Here, we get a complaint when checking the type signature for g,
2201 that g isn't polymorphic enough; but then we get another one when
2202 dealing with the (Num a) context arising from f's definition;
2203 we try to unify a with Int (to default it), but find that it's
2204 already been unified with the rigid variable from g's type sig.
2205
2206 Note [Multi-parameter defaults]
2207 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2208 With -XExtendedDefaultRules, we default only based on single-variable
2209 constraints, but do not exclude from defaulting any type variables which also
2210 appear in multi-variable constraints. This means that the following will
2211 default properly:
2212
2213 default (Integer, Double)
2214
2215 class A b (c :: Symbol) where
2216 a :: b -> Proxy c
2217
2218 instance A Integer c where a _ = Proxy
2219
2220 main = print (a 5 :: Proxy "5")
2221
2222 Note that if we change the above instance ("instance A Integer") to
2223 "instance A Double", we get an error:
2224
2225 No instance for (A Integer "5")
2226
2227 This is because the first defaulted type (Integer) has successfully satisfied
2228 its single-parameter constraints (in this case Num).
2229 -}